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 \n\t\"\"\"\n\tassert isinstance(qta, (int, Decimal))\n\n\tcodart = 'AC' if tipo_lettura == 'R' else 'ACS'\n\ttry:\n\t\tac = [x for x in fproc if x.fpc_bcodart == codart][0]\n\t\timporto = ac.fpc_costo\n\t\treturn output_line(ac.fpc_bgiorni, 'C', codart, qta, importo)\n\texcept:\n\t\traise DataMissingError('', \"Nei costi manca il codice '{0}'\".format(codart))\n\n\ndef altri_costi():\n\t\"\"\"\n\tProduce una lista di costi aggiuntivi\n\n\t:return <[Output()]>\n\t\"\"\"\n\n\tresult = [\n\t\toutput_line(c.fpc_bgiorni, 'C', c.fpc_bcodart, fpro.fp_periodo_p if c.fpc_bcodart == 'AFF' else 1, c.fpc_costo)\n\t\tfor c in fproc if c.fpc_bcodart not in ('AC', 'ACS')\n\t\t]\n\n\tif len(result) == 0:\n\t\tlogger.prefix_warn(\"Non ci sono costi da fatturare\")\n\n\treturn result\n\n\ndef consumo_mc(letture):\n\t\"\"\"\n\tConsumo in metri cubi\n\n\t:param letture: <[Fatprol()]> - Lista letture\n\t:return - Consumo (mc)\n\t\"\"\"\n\tif letture:\n\t\tassert isinstance(letture[0], Fatprol)\n\n\treturn Decimal(sum([x.fpl_consumo for x in letture]))\n\n\ndef calcolo_storno(st):\n\t\"\"\"\n\tCalcolo dello storno\n\n\t:param st: - Storno\n\t:return Risultato\n\t\"\"\"\n\tassert isinstance(st, Fatpros)\n\n\treturn output_line(st.fps_bgiorni, 'S', st.fps_bcodart, -st.fps_qta, st.fps_costo)\n\n\ndef compatta_storni(storni):\n\t\"\"\"\n\tCompattazione e ordinamento degli storni\n\n\t:param storni: <[Fatpros()]> - Lista degli storni\n\t:return <[Fatpros()]> - Lista degli storni compattati\n\t\"\"\"\n\tif storni:\n\t\tassert isinstance(storni[0], Fatpros)\n\n\ts = {}\n\tfor fps in storni:\n\t\tk = (fps.fps_bcodart, fps.fps_costo, fps.fps_bgiorni)\n\t\ts[k] = fps.fps_qta if k not in s else s[k] + fps.fps_qta\n\n\tstorni = []\n\tfor k in s.keys():\n\t\tfps = Fatpros()\n\t\tfps.fps_bcodart = k[0]\n\t\tfps.fps_costo = k[1]\n\t\tfps.fps_bgiorni = k[2]\n\t\tfps.fps_qta = s[k]\n\t\tstorni.append(fps)\n\n\treturn storni\n\n\ndef calcolo_tariffe(start_date, end_date, tar):\n\tx = []\n\tfor t in tar:\n\t\tif t.fpt_vigore <= end_date:\n\t\t\tcodart = t.fpt_bcodart_r if tipo_lettura == 'R' else t.fpt_bcodart_s\n\t\t\tk = ((t.fpt_vigore, t.fpt_codtar, codart), max(t.fpt_vigore, start_date))\n\t\t\tif k not in x:\n\t\t\t\tx.append(k)\n\tx.sort()\n\n\tcons = OrderedDict()\n\tlx = len(x) - 1\n\tfor i in range(lx):\n\t\tcons[x[i][0]] = (x[i + 1][1] - x[i][1]).days\n\tif lx >= 0:\n\t\tcons[x[lx][0]] = (end_date - x[lx][1]).days\n\n\treturn cons\n\n\ndef giorni_tariffe(start_date, end_date):\n\tconsumi = dict()\n\n\ttariffe = set([x.fpt_codtar for x in fprot])\n\n\tfor t in tariffe:\n\t\tfor k, v in calcolo_tariffe(start_date, end_date, [x for x in fprot if x.fpt_codtar == t]).items():\n\t\t\tconsumi[k] = v\n\n\treturn consumi\n\n\n##======================================================================================================================\n\n\ndef main():\n\tglobal results\n\n\t# Isolamento letture casa da letture garage\n\tletture_casa = [x for x in fprol if x.fpl_garage == '']\n\tletture_garage = [x for x in fprol if x.fpl_garage == 'G']\n\n\t# Consumi casa\n\tmc_consumo_fredda_casa = consumo_mc([x for x in letture_casa if x.fpl_fc == 0])\n\tmc_consumo_calda_casa = consumo_mc([x for x in letture_casa if x.fpl_fc == 1])\n\n\t# Consumi garage\n\tmc_consumo_fredda_garage = consumo_mc([x for x in letture_garage if x.fpl_fc == 0])\n\tmc_consumo_calda_garage = consumo_mc([x for x in letture_garage if x.fpl_fc == 1])\n\n\t# ----------------------------------------------------------------------------------------------\n\t##\tConsumi totali\n\t# ----------------------------------------------------------------------------------------------\n\tmc_consumo_totale_garage = mc_consumo_fredda_garage + mc_consumo_calda_garage\n\tmc_consumo_totale_casa = mc_consumo_fredda_casa + mc_consumo_calda_casa\n\n\tmc_consumo_totale_calda = mc_consumo_calda_casa + mc_consumo_calda_garage\n\t# mc_consumo_totale_fredda = mc_consumo_fredda_casa + mc_consumo_fredda_garage\n\n\tmc_consumo_totale = mc_consumo_totale_casa + mc_consumo_totale_garage\n\t# ----------------------------------------------------------------------------------------------\n\n\t# Periodo di riferimento dei consumi\n\tend_date = fpro.fp_data_let\n\tstart_date = end_date - timedelta(days=fpro.fp_periodo)\n\n\t# Consumi\n\tgt = giorni_tariffe(start_date, end_date)\n\tif len([gt.items()]) == 0:\n\t\tmsg = 'Nessuna tariffa applicabile al periodo specificato [{0} - {1}].'.format(start_date, end_date)\n\t\traise InvalidDataError('', msg)\n\n\t# Lista ordinata di date di inizio periodo. Serve per dare un ordinamento ai record in output\n\t# (nella tupla delle chiavi di 'gt' il primo elemento è la data di inizio del periodo)\n\tperiodi = sorted(set([x[0] for x in gt.keys()]))\n\n\tfor k in gt.keys():\n\t\tdata_vigore = k[0]\n\n\t\t# Per ogni periodo di tariffazione numfat viene incrementato di 1000 * (ordinale_periodo - 1)\n\t\t# Es: 1^ periodo: numfat + 1000 * 0 = numfat, 2^ periodo = numfat + 1000 * 1 = numfat + 1000, ecc.\n\t\t# In pratica il moltiplicatore è l'indice della data di inizio periodo nella lista ordinata \"periodi\"\n\t\tdef ordina_tariffe(o):\n\t\t\to.fpo_numfat += 1000 * periodi.index(data_vigore)\n\t\t\treturn o\n\n\t\tres = []\n\t\tts = [x for x in fprot if x.fpt_vigore == data_vigore and x.fpt_codtar == k[1]]\n\t\tconsumo = Decimal(round(mc_consumo_totale / fpro.fp_periodo * gt[k]))\n\n\t\tfor tar in ts:\n\t\t\tqty = 0\n\t\t\tif tar.fpt_codtar[0] == 'A':\n\t\t\t\tif consumo > 0:\n\t\t\t\t\tsc = scaglione(tar, gt[k])\n\t\t\t\t\tqty = sc if consumo > sc else consumo\n\t\t\t\t\tconsumo -= qty\n\t\t\telse:\n\t\t\t\tqty = consumo if tar.fpt_costo_um == 'MC' else gt[k]\n\n\t\t\tif qty != 0:\n\t\t\t\tres += [ordina_tariffe(costo(tar, qty))]\n\n\t\tresults += res\n\n\t# Per non aver problemi con l'ordinamento dell'output in caso di più di due periodi di tariffazione\n\t# impongo l'ordinamento a numfat + 1000 * numero di scadenze\n\t# Es. se ci sono 2 periodi sarà: nufat + 1000 * 2 = numfat + 2000\n\tdef ordina(o):\n\t\to.fpo_numfat += 1000 * len(periodi)\n\t\treturn o\n\n\t# Acqua calda, se presente\n\ttry:\n\t\tif mc_consumo_totale_calda > 0:\n\t\t\tresults += [ordina(costo_acqua_calda(mc_consumo_totale_calda))]\n\texcept:\n\t\tmsg = \"Consumo acqua calda > 0 (mc {0}) ma non sono presenti i relativi costi\".format(mc_consumo_totale_calda)\n\t\traise DataMissingError(\"Fatproc\", msg)\n\n\t# Costi\n\tresults += [ordina(c) for c in altri_costi()]\n\n\t# Storni\n\tif fpros:\n\t\tresults += [ordina(s) for s in [calcolo_storno(fps) for fps in compatta_storni(fpros)]]\n\n\t# Ordino i risultati rispetto fpo_numfat\n\tresults.sort(key=lambda r: r.fpo_numfat)\n\n\twrite_output(results)\n\n\tlogger.debug('main(): Results written to %s', basename(globals()['output_filename']))\n\n\n##======================================================================================================================\n##\tInizializzazione e verifica della presenza e congruità dei dati\n##======================================================================================================================\n\n\ndef initialize():\n\t\"\"\"\n\tInizializzazione delle variabili globali\n\n\t:return None\n\t\"\"\"\n\tglobal aqua_data, fpro, tipo_lettura, fprol, fproc, fprot, fpros, logger\n\n\ttry:\n\t\t# Controllo presenza dei dati dell'azienda\n\t\tif 'Fatpro' not in aqua_data:\n\t\t\traise DataMissingError('', \"Mancano i dati dell'azienda.\")\n\n\t\tfpro = aqua_data['Fatpro'][0]\n\t\ttipo_lettura = fpro.fp_tipo_let\n\n\t\tlogger.prefix_info(\"Utente:\\t[%d/%s]\", fpro.fp_aconto, fpro.fp_azienda)\n\t\tlogger.prefix_info(\"Lettura:\\t[%s/%d/%d %s]\", tipo_lettura, fpro.fp_numlet_pr, fpro.fp_numlet_aa,\n\t\t\t\t\t\t fpro.fp_data_let)\n\n\t\tif fpro.fp_periodo <= 0:\n\t\t\traise InvalidDataError('', 'Il periodo non può essere di 0 giorni.')\n\n\t\t# Controllo della presenza delle letture\n\t\tif 'Fatprol' not in aqua_data:\n\t\t\traise DataMissingError('', \"Mancano le letture.\")\n\n\t\tfprol = aqua_data['Fatprol'] if 'Fatprol' in aqua_data else None\n\n\t\t# Controllo della presenza delle tariffe\n\t\tif 'Fatprot' not in aqua_data:\n\t\t\traise DataMissingError('', \"Mancano le tariffe.\")\n\n\t\tfprot = sorted(aqua_data['Fatprot'], key=lambda t: (t.fpt_vigore, t.fpt_codtar, t.fpt_colonna))\n\n\t\t# Controllo della presenza dei costi\n\t\tif 'Fatproc' not in aqua_data:\n\t\t\traise DataMissingError(\"\", \"Mancano i costi.\")\n\n\t\t# Filtro le righe con quantità 0\n\t\tfproc = [c for c in aqua_data['Fatproc'] if c.fpc_qta != 0]\n\t\t# Il codice 'CS' deve essere presente\n\t\tif len([c for c in fproc if c.fpc_bcodart == 'CS']) == 0:\n\t\t\traise CostCodeMissingError(\"\", \"Mancano le Competenze di Servizio (cod. CS).\")\n\n\t\t# Controllo della presenza degli storni e filtro le righe con quantità 0\n\t\tif 'Fatpros' not in aqua_data:\n\t\t\tlogger.prefix_warn(\"Non sono stati specificati storni.\")\n\t\telse:\n\t\t\tfpros = [s for s in aqua_data['Fatpros'] if s.fps_qta != 0]\n\n\texcept:\n\t\tlogger.error(\"Errore durante l'inizializzazione!\")\n\t\traise\n\n\n##======================================================================================================================\n##\tStampe di debug\n##======================================================================================================================\n\n\ndef csv_print_results():\n\tprint()\n\tprint(results[0].get_csv_hdr())\n\tprint('\\n'.join([i.get_csv_row() for i in results]))\n\n\ndef csv_print_data():\n\tfor k in aqua_data.keys():\n\t\tprint()\n\t\tprint(aqua_data[k][0].get_csv_hdr())\n\t\tprint('\\n'.join([i.get_csv_row() for i in aqua_data[k]]))\n\n\ndef pretty_print_data():\n\tfor k in aqua_data.keys():\n\t\tprint()\n\t\tprint('\\n\\n'.join([i.pretty_print() for i in aqua_data[k]]))\n\n\ndef pretty_print_results():\n\tprint()\n\tprint('\\n\\n'.join([i.pretty_print() for i in results]))\n\n\n##======================================================================================================================\n\nif __name__ == '__main__':\n\ttry:\n\t\tlogger.debug('initialize(): Starting ')\n\t\tinitialize()\n\t\tlogger.debug('initialize(): Done')\n\n\t\tlogger.debug('main(): Starting')\n\t\tmain()\n\n\t\t# Stampe di debug\n\t\t# csv_print_data()\n\t\t# print()\n\t\t# csv_print_results()\n\t\t# print();\n\t\t# print('#\tTAG1, TAG2, TBA, TEC1, TEC2, CFC, DE, CDE, FO, CFO, QF')\n\t\t# pretty_print_data()\n\t\t# pretty_print_results()\n\n\t\tlogger.debug('main(): Done')\n\texcept:\n\t\traise\n\n##======================================================================================================================\n","sub_path":"generico.py","file_name":"generico.py","file_ext":"py","file_size_in_byte":12513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"247032993","text":"import dash\r\nfrom dash.dependencies import Output, Event, Input\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nimport plotly\r\nimport random\r\nimport plotly.graph_objs as go\r\nfrom collections import deque\r\nimport sqlite3\r\nimport pandas as pd\r\n\r\n#from cache \r\nimport cache\r\nimport time\r\n#print...\r\napp = dash.Dash(__name__)\r\napp.layout = html.Div(\r\n [\r\n html.H2('Live Twitter Sentiment'),\r\n dcc.Input(id='sentiment_term', value='twitter', type='text'),\r\n dcc.Graph(id='live-graph', animate=False),\r\n dcc.Interval(\r\n id='graph-update',\r\n interval=1*1000\r\n ),\r\n ]\r\n)\r\n\r\napp_colors = {\r\n 'background': '#0C0F0A',\r\n 'text': '#FFFFFF',\r\n 'sentiment-plot':'#41EAD4',\r\n 'volume-bar':'#FBFC74',\r\n 'someothercolor':'#FF206E',\r\n}\r\n\r\n@app.callback(Output('live-graph', 'figure'),\r\n [Input(component_id='sentiment_term', component_property='value')],\r\n events=[Event('graph-update', 'interval')])\r\ndef update_graph_scatter(sentiment_term):\r\n try:\r\n conn = sqlite3.connect('twitter.db')\r\n c = conn.cursor()\r\n df = pd.read_sql(\"SELECT * FROM sentiment WHERE tweet LIKE ? ORDER BY unix DESC LIMIT 1000\", conn ,params=('%' + sentiment_term + '%',))\r\n df.sort_values('unix', inplace=True)\r\n df['date'] = pd.to_datetime(df['unix'],unit='ms')\r\n df.set_index('date', inplace=True)\r\n df['sentiment_smoothed'] = df['sentiment'].rolling(int(len(df)/5)).mean()\r\n df.dropna(inplace=True)\r\n #df = df.resample('1s').mean() #averaging per second\r\n\r\n \r\n X = df.index[-100:]\r\n Y = df.sentiment_smoothed.values[-100:]\r\n \r\n data = plotly.graph_objs.Scatter(\r\n x=list(X),\r\n y=list(Y),\r\n name='Scatter',\r\n mode= 'lines+markers'\r\n )\r\n \r\n return {'data': [data],'layout' : go.Layout(xaxis=dict(range=[min(X),max(X)]),\r\n yaxis=dict(range=[min(Y),max(Y)]),\r\n title='Term: {}'.format(sentiment_term))}\r\n \r\n except Exception as e:\r\n with open('errors.txt','a') as f:\r\n f.write(str(e))\r\n f.write('\\n')\r\n\r\n\r\n@app.callback(Output('sentiment-pie', 'figure'),\r\n [Input(component_id='sentiment_term', component_property='value')],\r\n events=[Event('sentiment-pie-update', 'interval')])\r\ndef update_pie_chart(sentiment_term):\r\n\r\n # get data from cache\r\n for i in range(100):\r\n sentiment_pie_dict = cache.get('sentiment_shares', sentiment_term)\r\n if sentiment_pie_dict:\r\n break\r\n time.sleep(0.1)\r\n\r\n if not sentiment_pie_dict:\r\n return None\r\n\r\n labels = ['Positive','Negative']\r\n\r\n try: pos = sentiment_pie_dict[1]\r\n except: pos = 0\r\n\r\n try: neg = sentiment_pie_dict[-1]\r\n except: neg = 0\r\n\r\n \r\n \r\n values = [pos,neg]\r\n colors = ['#007F25', '#800000']\r\n\r\n trace = go.Pie(labels=labels, values=values,\r\n hoverinfo='label+percent', textinfo='value', \r\n textfont=dict(size=20, color=app_colors['text']),\r\n marker=dict(colors=colors, \r\n line=dict(color=app_colors['background'], width=2)))\r\n\r\n return {\"data\":[trace],'layout' : go.Layout(\r\n title='Positive vs Negative sentiment for \"{}\" (longer-term)'.format(sentiment_term),\r\n font={'color':app_colors['text']},\r\n plot_bgcolor = app_colors['background'],\r\n paper_bgcolor = app_colors['background'],\r\n showlegend=True)}\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run_server(debug=True)","sub_path":"rh.py","file_name":"rh.py","file_ext":"py","file_size_in_byte":3970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"630115230","text":"\r\n\"\"\"\r\n Customers Menu\r\n Create Customers Details\r\n Display all Customers Details\r\n Search Record\r\n Modify Customers Records\r\n Delete Customers Records\r\n Back to MainMenu\"\"\"\r\n\r\nimport os\r\nimport sqlite3\r\nfrom prettytable import from_db_cursor\r\n\r\nclass Customer(object):\r\n \"\"\"No Name address Phone no\"\"\"\r\n\r\n def __init__(self):\r\n \r\n try:\r\n os.chdir(\"Data\")\r\n except:\r\n os.mkdir(\"Data\")\r\n os.chdir(\"Data\")\r\n \r\n self.db = sqlite3.connect(database=\"dt.db\")\r\n self.cur = self.db.cursor()\r\n\r\n cmd = \"\"\"create table if not exists CustomersDt (CustNo int NOT NULL, Name varchar(100),\r\n address varchar(100), PhoneNo int,\r\n primary key(CustNo))\"\"\"\r\n self.cur.execute(cmd)\r\n self.db.commit()\r\n cmd = \"\"\"select No from CustomersDt\"\"\"\r\n self.cursor.execute(cmd)\r\n self.No_list = self.cursor.fetchall()\r\n self.prev_no = self._productNoinitializer(self.No_list)\r\n\r\n\r\n def createCustomersDetails(self):\r\n name = input(\"\\t\\tEnter the name of the Customer: \")\r\n address = input(\"\\t\\tEnter the address of the Customer: \")\r\n phoneno = int(input(\"\\t\\tEnter Phone no:\"))\r\n if len(phoneno) <= 10:\r\n pass\r\n else:\r\n print(\"Invalid PhoneNo\")\r\n\r\n\r\n ls = (self.prev_no, name, address, phoneno)\r\n cmd = \"\"\"insert into CustomersDt values (?, ?, ?, ?)\"\"\"\r\n self.cur.execute(cmd, ls)\r\n\r\n\r\n def displayCustomerDetails(self):\r\n con = sqlite3.connect(database=\"dt.db\")\r\n with con:\r\n cur = con.cursor()\r\n cur.execute(\"select * from CustomersDt\")\r\n\r\n x = from_db_cursor(cur)\r\n \r\n print(x)\r\n\r\n def searchRecords(self):\r\n self._fetchData()\r\n \r\n item_to_search = input(\"\\t\\tEnter the name of the product: \")\r\n is_item_found = False\r\n for _,e in enumerate(self.data_list):\r\n for i in e:\r\n if i == item_to_search:\r\n print(\"Product is present in the Database\")\r\n is_item_found = True\r\n break\r\n else:\r\n continue\r\n \r\n if not is_item_found:\r\n print(\"Product not present in the Database\")\r\n\r\n \r\n def modifyCustomerDetails(self):\r\n self._fetchData()\r\n self.displayCustomerDetails()\r\n no = int(input(\"\\t\\tEnter the CustNo to be modified: \"))\r\n def _modifyRow():\r\n name = input(\"\\t\\tEnter the Customer's name: \")\r\n address = input(\"\\t\\tEnter the address: \")\r\n phoneno = int(input(\"\\t\\tEnter Phone no: \"))\r\n if len(phoneno) <= 10:\r\n pass\r\n else:\r\n print(\"Invalid PhoneNo\") \r\n\r\n cmd = \"\"\"update CustomersDt\r\n set\r\n Name = ?,\r\n address = ?,\r\n PhoneNo = ?\r\n where\r\n No = ?\"\"\"\r\n \r\n tup = (name, address, phoneno)\r\n self.cur.execute(cmd, tup)\r\n self.dt.commit()\r\n print(\"\\t\\Customer data has been modified\")\r\n\r\n _modifyRow()\r\n\r\n \r\n def deleteCustomerRecords(self):\r\n self.displayCustomerDetails()\r\n no = int(input(\"\\t\\tEnter the CustNo to be deleted::\"))\r\n def _deleteRow():\r\n cmd = \"\"\"delete from CustomersDt where No = ?\"\"\"\r\n self.cur.execute(cmd, str(no))\r\n self.dt.commit()\r\n \r\n if no not in self.No_list:\r\n print(\"\\t\\tCustomer is not in database\")\r\n else:\r\n if input(\"\\t\\tPress Enter to delete: \"):\r\n _deleteRow()\r\n print(\"\\t\\tCustomer deleted from the database\")\r\n\r\n \r\n def _productNoinitializer(self, No_list):\r\n try:\r\n res = int(''.join(map(str, No_list[-1])))\r\n return res + 1\r\n except IndexError:\r\n return 0\r\n\r\n\r\n def _fetchData(self):\r\n cmd = \"select * from CustomersDt\"\r\n self.cursor.execute(cmd)\r\n self.data_list = self.cursor.fetchall()\r\n ","sub_path":"Res/Customers.py","file_name":"Customers.py","file_ext":"py","file_size_in_byte":4679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"45851195","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n# ### 分析数据特征的目的,增加时间的差值的个数\n# 1. 2alter.csv 和 5right.csv的数据较多,希望能高在这两个文件的融合出下下功夫\n# \n# + (TZ,BRANCH,RECRUIT) ---> (CHANGE,RIGHT)\n# + (LAWSUIT,PROJECT,QUALIFICATION,BREAKFAITH) ---> (RIGHT)\n# + 左右两边就行了两两组合\n# + \n\n# In[ ]:\n\ntimeType = ['RGYEAR','FIRST_CHANGE_TIME','END_CHANGE_TIME','BRANCH_FIRST_YEAR','BRANCH_END_YEAR',\n 'BRANCH_FIRST_CLOSE_YEAR','TZ_QY_FIRST_TIME','TZ_QY_END_TIME','TZ_FIRST_CLOSE_TIME',\n 'RIGHT_FIRST_ASK_TIME', 'RIGHT_FIRST_FB_TIME','RIGHT_END_ASK_TIME', 'RIGHT_END_FB_TIME',\n 'PROJECT_FIRST_TIME', 'PROJECT_END_TIME', 'LAWSUIT_FIRST_TIME', 'LAWSUIT_END_TIME', \n 'BREAKFAITH_FIRST_FIRST_TIME', 'BREAKFAITH_FIRST_END_TIME','BREAKFAITH_END_FIRST_TIME',\n 'RECRUIT_FIRST_TIME','RECRUIT_END_TIME','QUALIFICATION_FIRST_FIRST_TIME',\n 'QUALIFICATION_FIRST_END_TIME','QUALIFICATION_END_FIRST_TIME']\n\n\n# In[12]:\n\nTBR = ['TZ_QY_FIRST_TIME','TZ_QY_END_TIME','TZ_FIRST_CLOSE_TIME','BRANCH_FIRST_YEAR','BRANCH_END_YEAR',\n 'BRANCH_FIRST_CLOSE_YEAR','RECRUIT_FIRST_TIME','RECRUIT_END_TIME']\n\nLPQ = ['PROJECT_FIRST_TIME', 'PROJECT_END_TIME','LAWSUIT_FIRST_TIME','LAWSUIT_END_TIME',\n 'QUALIFICATION_FIRST_FIRST_TIME','QUALIFICATION_FIRST_END_TIME','QUALIFICATION_END_FIRST_TIME',\n 'PROJECT_FIRST_TIME', 'PROJECT_END_TIME']\n\nCR = ['FIRST_CHANGE_TIME','END_CHANGE_TIME','RIGHT_FIRST_ASK_TIME','RIGHT_END_ASK_TIME',]\n\nR = ['RIGHT_FIRST_ASK_TIME','RIGHT_END_ASK_TIME']\n\n\n\n# In[13]:\n\ndf_all = pd.read_csv('../data/alldata/df_data1234567890.csv')\n\n\n# In[16]:\n\ndef timeDiff(x):\n a = x[:x.find(':')]\n b = x[x.find(':')+1:]\n y = int(a[:a.find('-')]) - int(b[:b.find('-')])\n m = int(a[a.find('-')+1:]) - int(b[b.find('-')+1:])\n return y * 12 + m\n\nfor f1 in TBR:\n for f2 in LPQ:\n df_all[f1+\"_\"+f2+\"_DIFF\"] = (df_all[f1] + ':' + df_all[f2]).apply(timeDiff)\n\nfor f1 in CR:\n for f2 in R:\n df_all[f1+\"_\"+f2+\"_DIFF\"] = (df_all[f1] + ':' + df_all[f2]).apply(timeDiff)\n\ndf_all.to_csv('../data/alldata/df_data1234567890_plus.csv',index=False,index_label=False)\n\n\n# In[3]:\n\n\n\n","sub_path":"stack/0_add_features.py","file_name":"0_add_features.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"172788084","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nSSO Security Helper\n\"\"\"\n\n__author__ = 'VMware, Inc.'\n__copyright__ = 'Copyright 2015, 2017 VMware, Inc. All rights reserved. -- VMware Confidential' # pylint: disable=line-too-long\n\nfrom base64 import b64encode, b64decode\nimport datetime\nimport decimal\nimport json\nfrom lxml import etree\nfrom OpenSSL import crypto\nimport re\nimport six\n\nfrom vmware.vapi.bindings.datetime_helper import DateTimeConverter\nfrom vmware.vapi.core import SecurityContext\nfrom vmware.vapi.lib.jsonlib import (\n DecimalEncoder, canonicalize_double)\nfrom vmware.vapi.lib.constants import (\n PARAMS, SCHEME_ID, EXECUTION_CONTEXT, SECURITY_CONTEXT)\nfrom vmware.vapi.protocol.common.lib import RequestProcessor\n\nkey_regex = re.compile(r'-----BEGIN [A-Z ]*PRIVATE KEY-----\\n')\nSAML_SCHEME_ID = 'com.vmware.vapi.std.security.saml_hok_token'\nSAML_BEARER_SCHEME_ID = 'com.vmware.vapi.std.security.saml_bearer_token'\nPRIVATE_KEY = 'privateKey'\nSAML_TOKEN = 'samlToken'\nSIGNATURE_ALGORITHM = 'signatureAlgorithm'\nDEFAULT_ALGORITHM_TYPE = 'RS256'\nTIMESTAMP = 'timestamp'\nEXPIRES = 'expires'\nCREATED = 'created'\nREQUEST_VALIDITY = 20\nSIGNATURE = 'signature'\nDIGEST = 'value'\nAUTHENTICATED = 'requestAuthenticated'\nSTS_URL_PROP = 'stsurl'\nCERTIFICATE_PROP = 'certificate'\nPRIVATE_KEY_PROP = 'privatekey'\nSECTION = __name__\n# Algorithm Header Parameter Values for JWS based on the following link\n# https://datatracker.ietf.org/doc/draft-ietf-jose-json-web-algorithms/?include_text=1\nalgorithm_map = {\n 'RS256': 'sha256',\n 'RS384': 'sha384',\n 'RS512': 'sha512',\n}\n\n\ndef create_saml_bearer_security_context(token):\n \"\"\"\n Create a security context for SAML bearer token based\n authentication scheme\n\n :type token: :class:`str`\n :param token: SAML Token\n \"\"\"\n return SecurityContext({SCHEME_ID: SAML_BEARER_SCHEME_ID,\n SAML_TOKEN: token})\n\n\ndef create_saml_security_context(token, private_key):\n \"\"\"\n Create a security context for SAML token based\n authentication scheme\n\n :type token: :class:`str`\n :param token: SAML Token\n :type private_key: :class:`str`\n :param private_key: Absolute file path of the private key of the user\n :rtype: :class:`vmware.vapi.core.SecurityContext`\n :return: Newly created security context\n \"\"\"\n private_key_data = None\n with open(private_key, 'r') as fp:\n private_key_data = fp.read()\n return SecurityContext({SCHEME_ID: SAML_SCHEME_ID,\n PRIVATE_KEY: private_key_data,\n SAML_TOKEN: token,\n SIGNATURE_ALGORITHM: DEFAULT_ALGORITHM_TYPE})\n\n\nclass JSONCanonicalEncoder(json.JSONEncoder):\n \"\"\"\n Custom JSON Encoder class to canonicalize dictionary\n and list objects\n \"\"\"\n def encode(self, o):\n \"\"\"\n Encode a given python object\n\n :type o: :class:`object`\n :param o: Python object\n :rtype: :class:`str`\n :return: JSON string in canonicalized form\n \"\"\"\n if isinstance(o, dict):\n # Remove non-significant whitespace characters\n # Keys are sorted lexicographically using UCS code\n # point values\n sorted_keys = sorted(o.keys())\n sorted_items = ['%s:%s' % (self.encode(key),\n self.encode(o[key]))\n for key in sorted_keys]\n string = ','.join(sorted_items)\n return '{%s}' % string\n elif isinstance(o, list):\n # Arrays must preserve the initial ordering\n # Remove non-significant whitespace characters\n string = ','.join([self.encode(item)\n for item in o])\n return '[%s]' % string\n elif isinstance(o, decimal.Decimal):\n return canonicalize_double(o)\n else:\n return json.JSONEncoder.encode(self, o)\n\n\nclass JSONCanonicalizer(object):\n \"\"\"\n This class is responsible for transforming JSON messages into their\n canonical representation.\n\n The canonical form is defined by the following rules:\n 1. Non-significant(1) whitespace characters MUST NOT be used\n 2. Non-significant(1) line endings MUST NOT be used\n 3. Entries (set of name/value pairs) in JSON objects MUST be sorted\n lexicographically(2) by their names based on UCS codepoint values\n 4. Arrays MUST preserve their initial ordering\n\n Link to the IEFT proposal:\n https://datatracker.ietf.org/doc/draft-staykov-hu-json-canonical-form/\n \"\"\"\n @staticmethod\n def canonicalize(input_message):\n \"\"\"\n Canonicalize the input message\n\n :type input_message: :class:`str`\n :param input_message: Input message\n :rtype: :class:`str`\n :return: Canonicalized message\n \"\"\"\n py_obj = json.loads(input_message, parse_float=decimal.Decimal)\n return JSONCanonicalEncoder().encode(py_obj)\n\n @staticmethod\n def canonicalize_py_obj(py_obj):\n \"\"\"\n Canonicalize the input python object\n\n :type input_message: :class:`object`\n :param input_message: Input python object\n :rtype: :class:`str`\n :return: Canonicalized message\n \"\"\"\n return JSONCanonicalEncoder().encode(py_obj)\n\n\nclass JSONSSOSigner(RequestProcessor):\n \"\"\"\n This class is used for signing JSON request messages\n \"\"\"\n def process(self, input_message):\n \"\"\"\n Sign the input JSON request message.\n\n The message is signed using user's private key. The digest and saml\n token is then added to the security context block of the execution\n context. A timestamp is also added to guard against replay attacks\n\n Sample input security context:\n {\n 'schemeId': 'SAML_TOKEN',\n 'privateKey': ,\n 'samlToken': ,\n 'signatureAlgorithm': ,\n }\n\n Security context block before signing:\n {\n 'schemeId': 'SAML_TOKEN',\n 'signatureAlgorithm': ,\n 'timestamp': {\n 'created': '2012-10-26T12:24:18.941Z',\n 'expires': '2012-10-26T12:44:18.941Z',\n }\n }\n\n Security context block after signing:\n {\n 'schemeId': 'SAML_TOKEN',\n 'signatureAlgorithm': ,\n 'signature': {\n 'samlToken': ,\n 'value': \n }\n 'timestamp': {\n 'created': '2012-10-26T12:24:18.941Z',\n 'expires': '2012-10-26T12:44:18.941Z',\n }\n }\n \"\"\"\n if input_message is None:\n return\n\n # process only if the schemeId in the request matches the schemeId of\n # this signer\n if isinstance(input_message, six.binary_type):\n unicode_input_message = input_message.decode()\n else:\n unicode_input_message = input_message\n if SAML_SCHEME_ID not in unicode_input_message:\n return input_message\n\n py_obj = json.loads(unicode_input_message, parse_float=decimal.Decimal)\n json_params = py_obj.get(PARAMS) # pylint: disable=E1103\n ctx = json_params.get(EXECUTION_CONTEXT)\n\n sec_ctx = ctx.get(SECURITY_CONTEXT)\n private_key = sec_ctx.get(PRIVATE_KEY)\n saml_token = sec_ctx.get(SAML_TOKEN)\n jws_algorithm = sec_ctx.get(SIGNATURE_ALGORITHM)\n algorithm = algorithm_map.get(jws_algorithm)\n\n new_sec_ctx = {}\n new_sec_ctx[SCHEME_ID] = sec_ctx.get(SCHEME_ID)\n new_sec_ctx[TIMESTAMP] = _generate_request_timestamp()\n new_sec_ctx[SIGNATURE_ALGORITHM] = jws_algorithm\n\n # Replace the old security context with the new one\n del ctx[SECURITY_CONTEXT]\n ctx[SECURITY_CONTEXT] = new_sec_ctx\n\n pkey = crypto.load_privatekey(\n crypto.FILETYPE_PEM, _prep_private_key(private_key))\n canonical_message = JSONCanonicalizer.canonicalize_py_obj(py_obj)\n base64_encoded_digest = b64encode(crypto.sign(\n pkey, canonical_message.encode(), algorithm))\n # Convert to unicode since json library does not accept bytes\n unicode_digest = base64_encoded_digest.decode()\n\n new_sec_ctx[SIGNATURE] = {SAML_TOKEN: saml_token,\n DIGEST: unicode_digest}\n return json.dumps(py_obj,\n check_circular=False,\n separators=(',', ':'),\n cls=DecimalEncoder)\n\n\nclass JSONSSOVerifier(RequestProcessor):\n \"\"\"\n This class is used to verify the authenticity of the request\n message by verifying the digest present in the security context\n block.\n \"\"\"\n def process(self, input_message):\n \"\"\"\n Verify the input JSON message.\n\n For verification, we need 4 things:\n\n 1. algorithm: extracted from security context\n 2. certificate: public key of the principal embedded in the\n SAML token is used\n 3. digest: value field from signature block\n 4. canonical msg: signature block is removed from the request\n and the remaining part is canonicalized\n\n Sample input security context:\n {\n 'schemeId': 'SAML_TOKEN',\n 'signatureAlgorithm': ,\n 'signature': {\n 'samlToken': ,\n 'value': \n }\n 'timestamp': {\n 'created': '2012-10-26T12:24:18.941Z',\n 'expires': '2012-10-26T12:44:18.941Z',\n }\n }\n\n :type input_message: :class:`str`\n :param input_message: Input JSON request message\n :rtype: :class:`str`\n :return: JSON request message after signature verification\n \"\"\"\n if not input_message:\n return\n\n if isinstance(input_message, six.binary_type):\n unicode_input_message = input_message.decode()\n else:\n unicode_input_message = input_message\n if SAML_SCHEME_ID not in unicode_input_message:\n return input_message\n\n py_obj = json.loads(unicode_input_message, parse_float=decimal.Decimal)\n json_params = py_obj.get(PARAMS) # pylint: disable=E1103\n execution_ctx = json_params.get(EXECUTION_CONTEXT)\n sec_ctx = execution_ctx.get(SECURITY_CONTEXT)\n\n signature = sec_ctx.get(SIGNATURE)\n del sec_ctx[SIGNATURE]\n\n base64_encoded_digest = signature.get(DIGEST).encode()\n digest = b64decode(base64_encoded_digest)\n jws_algorithm = sec_ctx.get(SIGNATURE_ALGORITHM)\n algorithm = algorithm_map.get(jws_algorithm)\n saml_token = signature.get(SAML_TOKEN)\n certificate = _extract_certificate(saml_token)\n\n pubkey = crypto.load_certificate(\n crypto.FILETYPE_PEM, _prep_certificate(certificate))\n canonical_message = JSONCanonicalizer.canonicalize_py_obj(py_obj)\n crypto.verify(\n pubkey, digest, canonical_message.encode(), algorithm)\n\n sec_ctx[SAML_TOKEN] = saml_token\n sec_ctx[AUTHENTICATED] = True\n sec_ctx[SIGNATURE_ALGORITHM] = jws_algorithm\n\n return json.dumps(py_obj,\n check_circular=False,\n separators=(',', ':'),\n cls=DecimalEncoder)\n\n\ndef _extract_element(xml, element_name, namespace):\n \"\"\"\n An internal method provided to extract an element from the given XML.\n\n :type xml: :class:`str`\n :param xml: The XML string from which the element will be extracted.\n :type element_name: :class:`str`\n :param element_name: The element that needs to be extracted from the XML.\n :type namespace: :class:`dict`\n :param namespace: A dict containing the namespace of the element to be\n extracted.\n :rtype: etree element.\n :return: The extracted element.\n \"\"\"\n assert(len(namespace) == 1)\n result = xml.xpath(\"//%s:%s\" % (list(namespace.keys())[0], element_name),\n namespaces=namespace)\n if result:\n return result[0]\n else:\n raise KeyError(\"%s does not seem to be present in the XML.\" %\n element_name)\n\n\ndef _prep_private_key(private_key):\n \"\"\"\n Append proper prefix and suffix text to a private key. There is no\n standard way for storing certificates. OpenSSL expects the demarcation\n text. This method makes sure that the text the markers are present.\n\n :type text: :class:`str`\n :param text: The private key of the service user.\n\n :rtype: :class:`str`\n :return: Normalized private key.\n \"\"\"\n if not key_regex.search(private_key):\n return \"\"\"-----BEGIN RSA PRIVATE KEY-----\n%s\n-----END RSA PRIVATE KEY-----\"\"\" % private_key\n return private_key\n\n\ndef _prep_certificate(certificate):\n \"\"\"\n Append proper prefix and suffix text to a certificate. There is no\n standard way for storing certificates. OpenSSL expects the demarcation\n text. This method makes sure that the text the markers are present.\n\n :type text: :class:`str`\n :param text: The certificate of the service user.\n\n :rtype: :class:`str`\n :return: Normalized certificate\n \"\"\"\n if not certificate.startswith('-----BEGIN CERTIFICATE-----'):\n return \"\"\"-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\"\"\" % certificate\n return certificate\n\n\ndef _extract_certificate(hok_token):\n \"\"\"\n Extract Certificate of the principal from Holder of Key SAML token\n\n :type hok_token: :class:`str`\n :param hok_token: Holder of key SAML token\n :rtype: :class:`str`\n :return: Certificate of the principal\n \"\"\"\n xml = etree.fromstring(hok_token)\n subject = _extract_element(\n xml,\n 'SubjectConfirmationData',\n {'saml2': 'urn:oasis:names:tc:SAML:2.0:assertion'})\n xml_certificate = subject.getchildren()[0].getchildren()[0].getchildren()[0]\n return xml_certificate.text.replace('\\\\n', '\\n')\n\n\ndef _generate_request_timestamp():\n \"\"\"\n Generate a timestamp for the request. This will be embedded in the security\n context of the request to protect it against replay attacks\n\n :rtype: :class:`dict`\n :return: Timestamp block that can be inserted in security context\n \"\"\"\n created_dt = datetime.datetime.utcnow()\n offset = datetime.timedelta(minutes=REQUEST_VALIDITY)\n created = DateTimeConverter.convert_from_datetime(created_dt)\n expires = DateTimeConverter.convert_from_datetime(created_dt + offset)\n return {EXPIRES: expires, CREATED: created}\n","sub_path":"alexa-program.bak/vmware/vapi/security/sso.py","file_name":"sso.py","file_ext":"py","file_size_in_byte":14708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"75623560","text":"import os\nimport sys\nimport time\nimport shutil\nfrom math import degrees, atan2\nimport numpy as np\n\n\nfrom .manager import ExperimentManager\nfrom .settings import *\n\nfrom .my_imports import _prep_temp_folder\n\n\nif __name__ == '__main__':\n\n EXPERIMENT_SAVE_MODE_ON = 0 # pylint: disable=bad-whitespace\n WRITE_PLOT = 0 # pylint: disable=bad-whitespace\n CONTROL_ON = 1 # pylint: disable=bad-whitespace\n TRACKER_ON = 1 # pylint: disable=bad-whitespace\n TRACKER_DISPLAY_ON = 1 # pylint: disable=bad-whitespace\n USE_TRUE_KINEMATICS = 0 # pylint: disable=bad-whitespace\n USE_REAL_CLOCK = 0 # pylint: disable=bad-whitespace\n DRAW_OCCLUSION_BARS = 1 # pylint: disable=bad-whitespace\n\n RUN_EXPERIMENT = 1 # pylint: disable=bad-whitespace\n RUN_TRACK_PLOT = 0 # pylint: disable=bad-whitespace\n\n RUN_VIDEO_WRITER = 0 # pylint: disable=bad-whitespace\n\n if RUN_EXPERIMENT:\n EXPERIMENT_MANAGER = ExperimentManager(save_on=EXPERIMENT_SAVE_MODE_ON,\n write_plot=WRITE_PLOT,\n control_on=CONTROL_ON,\n tracker_on=TRACKER_ON,\n tracker_display_on=TRACKER_DISPLAY_ON,\n use_true_kin=USE_TRUE_KINEMATICS,\n use_real_clock=USE_REAL_CLOCK,\n draw_occlusion_bars=DRAW_OCCLUSION_BARS)\n print(f'\\nLane Changing experiment started. [{time.strftime(\"%H:%M:%S\")}]\\n')\n EXPERIMENT_MANAGER.run()\n\n print(f'\\n\\nLane Changing experiment finished. [{time.strftime(\"%H:%M:%S\")}]\\n')\n\n if RUN_TRACK_PLOT:\n FILE = open('plot_info.csv', 'r')\n \n # plot switches\n SHOW_ALL = 1 # set to 1 to show all plots \n\n SHOW_CARTESIAN_PLOTS = 1\n SHOW_LOS_KIN_1 = 1\n SHOW_LOS_KIN_2 = 1\n SHOW_ACCELERATIONS = 1\n SHOW_TRAJECTORIES = 1\n SHOW_SPEED_HEADING = 1\n SHOW_ALTITUDE_PROFILE = 0\n SHOW_3D_TRAJECTORIES = 1\n SHOW_DELTA_TIME_PROFILE = 0\n SHOW_Y1_Y2 = 0\n\n _TIME = []\n _R = []\n _THETA = []\n _V_THETA = []\n _V_R = []\n _DRONE_POS_X = []\n _DRONE_POS_Y = []\n _CAR_POS_X = []\n _CAR_POS_Y = []\n _DRONE_ACC_X = []\n _DRONE_ACC_Y = []\n _DRONE_ACC_LAT = []\n _DRONE_ACC_LNG = []\n _CAR_VEL_X = []\n _CAR_VEL_Y = []\n _TRACKED_CAR_POS_X = []\n _TRACKED_CAR_POS_Y = []\n _TRACKED_CAR_VEL_X = []\n _TRACKED_CAR_VEL_Y = []\n _CAM_ORIGIN_X = []\n _CAM_ORIGIN_Y = []\n _DRONE_SPEED = []\n _DRONE_ALPHA = []\n _DRONE_VEL_X = []\n _DRONE_VEL_Y = []\n _MEASURED_CAR_POS_X = []\n _MEASURED_CAR_POS_Y = []\n _MEASURED_CAR_VEL_X = []\n _MEASURED_CAR_VEL_Y = []\n _DRONE_ALTITUDE = []\n _ABS_DEN = []\n _MEASURED_R = []\n _MEASURED_THETA = []\n _MEASURED_V_R = []\n _MEASURED_V_THETA = []\n _TRUE_R = []\n _TRUE_THETA = []\n _TRUE_V_R = []\n _TRUE_V_THETA = []\n _DELTA_TIME = []\n _Y1 = []\n _Y2 = []\n _CAR_SPEED = []\n _CAR_HEADING = []\n _TRUE_Y1 = []\n _TRUE_Y2 = []\n _OCC_CASE = []\n\n # get all the data in memory\n for line in FILE.readlines():\n if line.split(',')[0].strip().lower()=='time':\n continue\n data = tuple(map(float, list(map(str.strip, line.strip().split(',')))))\n _TIME.append(data[0])\n _R.append(data[1])\n _THETA.append(data[2]) # degrees\n _V_THETA.append(data[3])\n _V_R.append(data[4])\n _DRONE_POS_X.append(data[5]) # true\n _DRONE_POS_Y.append(data[6]) # true\n _CAR_POS_X.append(data[7]) # true\n _CAR_POS_Y.append(data[8]) # true\n _DRONE_ACC_X.append(data[9])\n _DRONE_ACC_Y.append(data[10])\n _DRONE_ACC_LAT.append(data[11])\n _DRONE_ACC_LNG.append(data[12])\n _CAR_VEL_X.append(data[13])\n _CAR_VEL_Y.append(data[14])\n _TRACKED_CAR_POS_X.append(data[15])\n _TRACKED_CAR_POS_Y.append(data[16])\n _TRACKED_CAR_VEL_X.append(data[17])\n _TRACKED_CAR_VEL_Y.append(data[18])\n _CAM_ORIGIN_X.append(data[19])\n _CAM_ORIGIN_Y.append(data[20])\n _DRONE_SPEED.append(data[21])\n _DRONE_ALPHA.append(data[22])\n _DRONE_VEL_X.append(data[23])\n _DRONE_VEL_Y.append(data[24])\n _MEASURED_CAR_POS_X.append(data[25])\n _MEASURED_CAR_POS_Y.append(data[26])\n _MEASURED_CAR_VEL_X.append(data[27])\n _MEASURED_CAR_VEL_Y.append(data[28])\n _DRONE_ALTITUDE.append(data[29])\n _ABS_DEN.append(data[30])\n _MEASURED_R.append(data[31])\n _MEASURED_THETA.append(data[32])\n _MEASURED_V_R.append(data[33])\n _MEASURED_V_THETA.append(data[34])\n _TRUE_R.append(data[35])\n _TRUE_THETA.append(data[36])\n _TRUE_V_R.append(data[37])\n _TRUE_V_THETA.append(data[38])\n _DELTA_TIME.append(data[39])\n _Y1.append(data[40])\n _Y2.append(data[41])\n _CAR_SPEED.append(data[42])\n _CAR_HEADING.append(data[43])\n _TRUE_Y1.append(data[44])\n _TRUE_Y2.append(data[45])\n _OCC_CASE.append(data[46])\n\n FILE.close()\n\n # plot\n if len(_TIME) < 5:\n print('Not enough data to plot.')\n sys.exit()\n import matplotlib.pyplot as plt\n import scipy.stats as st\n\n _PATH = f'./sim_outputs/{time.strftime(\"%Y-%m-%d_%H-%M-%S\")}'\n _prep_temp_folder(os.path.realpath(_PATH))\n\n # copy the plot_info file to the where plots figured will be saved\n shutil.copyfile('plot_info.csv', f'{_PATH}/plot_info.csv')\n plt.style.use('seaborn-whitegrid')\n\n # -------------------------------------------------------------------------------- figure 1\n # line of sight kinematics 1\n if SHOW_ALL or SHOW_LOS_KIN_1:\n f0, axs = plt.subplots(2, 1, sharex=True, gridspec_kw={'hspace': 0.25})\n if SUPTITLE_ON:\n f0.suptitle(r'$\\mathbf{Line\\ of\\ Sight\\ Kinematics\\ -\\ I}$', fontsize=TITLE_FONT_SIZE)\n\n # t vs r\n axs[0].plot(\n _TIME,\n _MEASURED_R,\n color='forestgreen',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$measured\\ r$',\n alpha=0.9)\n axs[0].plot(\n _TIME,\n _R,\n color='royalblue',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$estimated\\ r$',\n alpha=0.9)\n axs[0].plot(\n _TIME,\n _TRUE_R,\n color='red',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$true\\ r$',\n alpha=0.9)\n axs[0].plot(\n _TIME,\n [i*10 for i in _OCC_CASE],\n color='orange',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$case\\ r$',\n alpha=0.9)\n\n axs[0].legend(loc='upper right')\n axs[0].set(ylabel=r'$r\\ (m)$')\n axs[0].set_title(r'$\\mathbf{r}$', fontsize=SUB_TITLE_FONT_SIZE)\n\n # t vs θ\n axs[1].plot(\n _TIME,\n _MEASURED_THETA,\n color='forestgreen',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$measured\\ \\theta$',\n alpha=0.9)\n axs[1].plot(\n _TIME,\n _THETA,\n color='royalblue',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$estimated\\ \\theta$',\n alpha=0.9)\n axs[1].plot(\n _TIME,\n _TRUE_THETA,\n color='red',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$true\\ \\theta$',\n alpha=0.9)\n\n axs[1].legend(loc='upper right')\n axs[1].set(xlabel=r'$time\\ (s)$', ylabel=r'$\\theta\\ (^{\\circ})$')\n axs[1].set_title(r'$\\mathbf{\\theta}$', fontsize=SUB_TITLE_FONT_SIZE)\n\n f0.savefig(f'{_PATH}/1_los1.png', dpi=300)\n f0.show()\n\n # -------------------------------------------------------------------------------- figure 2\n # line of sight kinematics 2\n if SHOW_ALL or SHOW_LOS_KIN_2:\n f1, axs = plt.subplots(2, 1, sharex=True, gridspec_kw={'hspace': 0.25})\n if SUPTITLE_ON:\n f1.suptitle(r'$\\mathbf{Line\\ of\\ Sight\\ Kinematics\\ -\\ II}$', fontsize=TITLE_FONT_SIZE)\n\n # t vs vr\n axs[0].plot(\n _TIME,\n _MEASURED_V_R,\n color='palegreen',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$measured\\ V_{r}$',\n alpha=0.9)\n axs[0].plot(\n _TIME,\n _V_R,\n color='royalblue',\n linestyle='-',\n linewidth=LINE_WIDTH_2,\n label=r'$estimated\\ V_{r}$',\n alpha=0.9)\n axs[0].plot(\n _TIME,\n _TRUE_V_R,\n color='red',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$true\\ V_{r}$',\n alpha=0.9)\n\n axs[0].legend(loc='upper right')\n axs[0].set(ylabel=r'$V_{r}\\ (\\frac{m}{s})$')\n axs[0].set_title(r'$\\mathbf{V_{r}}$', fontsize=SUB_TITLE_FONT_SIZE)\n\n # t vs vtheta\n axs[1].plot(\n _TIME,\n _MEASURED_V_THETA,\n color='palegreen',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$measured\\ V_{\\theta}$',\n alpha=0.9)\n axs[1].plot(\n _TIME,\n _V_THETA,\n color='royalblue',\n linestyle='-',\n linewidth=LINE_WIDTH_2,\n label=r'$estimated\\ V_{\\theta}$',\n alpha=0.9)\n axs[1].plot(\n _TIME,\n _TRUE_V_THETA,\n color='red',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$true\\ V_{\\theta}$',\n alpha=0.9)\n\n axs[1].legend(loc='upper right')\n axs[1].set(xlabel=r'$time\\ (s)$', ylabel=r'$V_{\\theta}\\ (\\frac{m}{s})$')\n axs[1].set_title(r'$\\mathbf{V_{\\theta}}$', fontsize=SUB_TITLE_FONT_SIZE)\n\n f1.savefig(f'{_PATH}/1_los2.png', dpi=300)\n f1.show()\n\n # -------------------------------------------------------------------------------- figure 2\n # acceleration commands\n if SHOW_ALL or SHOW_ACCELERATIONS:\n f2, axs = plt.subplots()\n if SUPTITLE_ON:\n f2.suptitle(r'$\\mathbf{Acceleration\\ commands}$', fontsize=TITLE_FONT_SIZE)\n\n axs.plot(\n _TIME,\n _DRONE_ACC_LAT,\n color='forestgreen',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$a_{lat}$',\n alpha=0.9)\n axs.plot(\n _TIME,\n _DRONE_ACC_LNG,\n color='deeppink',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$a_{long}$',\n alpha=0.9)\n axs.legend()\n axs.set(xlabel=r'$time\\ (s)$', ylabel=r'$acceleration\\ (\\frac{m}{s_{2}})$')\n\n f2.savefig(f'{_PATH}/2_accel.png', dpi=300)\n f2.show()\n\n # -------------------------------------------------------------------------------- figure 3\n # trajectories\n if SHOW_ALL or SHOW_TRAJECTORIES:\n f3, axs = plt.subplots(2, 1, gridspec_kw={'hspace': 0.4})\n if SUPTITLE_ON:\n f3.suptitle(\n r'$\\mathbf{Vehicle\\ and\\ UAS\\ True\\ Trajectories}$',\n fontsize=TITLE_FONT_SIZE)\n\n ndx = np.array(_DRONE_POS_X) + np.array(_CAM_ORIGIN_X)\n ncx = np.array(_CAR_POS_X) + np.array(_CAM_ORIGIN_X)\n ndy = np.array(_DRONE_POS_Y) + np.array(_CAM_ORIGIN_Y)\n ncy = np.array(_CAR_POS_Y) + np.array(_CAM_ORIGIN_Y)\n\n axs[0].plot(\n ndx,\n ndy,\n color='darkslategray',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$UAS$',\n alpha=0.9)\n axs[0].plot(\n ncx,\n ncy,\n color='limegreen',\n linestyle='-',\n linewidth=LINE_WIDTH_2,\n label=r'$Vehicle$',\n alpha=0.9)\n axs[0].set(ylabel=r'$y\\ (m)$')\n axs[0].set_title(r'$\\mathbf{World\\ frame}$', fontsize=SUB_TITLE_FONT_SIZE)\n axs[0].legend()\n\n ndx = np.array(_DRONE_POS_X)\n ncx = np.array(_CAR_POS_X)\n ndy = np.array(_DRONE_POS_Y)\n ncy = np.array(_CAR_POS_Y)\n\n x_pad = (max(ncx) - min(ncx)) * 0.05\n y_pad = (max(ncy) - min(ncy)) * 0.05\n xl = max(abs(max(ncx)), abs(min(ncx))) + x_pad\n yl = max(abs(max(ncy)), abs(min(ncy))) + y_pad\n axs[1].plot(\n ndx,\n ndy,\n color='darkslategray',\n marker='+',\n markersize=10,\n label=r'$UAS$',\n alpha=0.7)\n axs[1].plot(\n ncx,\n ncy,\n color='limegreen',\n linestyle='-',\n linewidth=LINE_WIDTH_2,\n label=r'$Vehicle$',\n alpha=0.9)\n axs[1].set(xlabel=r'$x\\ (m)$', ylabel=r'$y\\ (m)$')\n axs[1].set_title(r'$\\mathbf{Camera\\ frame}$', fontsize=SUB_TITLE_FONT_SIZE)\n axs[1].legend(loc='lower right')\n axs[1].set_xlim(-xl, xl)\n axs[1].set_ylim(-yl, yl)\n f3.savefig(f'{_PATH}/3_traj.png', dpi=300)\n f3.show()\n\n # -------------------------------------------------------------------------------- figure 4\n # true and estimated trajectories\n if SHOW_ALL or SHOW_CARTESIAN_PLOTS:\n f4, axs = plt.subplots()\n if SUPTITLE_ON:\n f4.suptitle(\n r'$\\mathbf{Vehicle\\ True\\ and\\ Estimated\\ Trajectories}$',\n fontsize=TITLE_FONT_SIZE)\n\n axs.plot(\n _TRACKED_CAR_POS_X,\n _TRACKED_CAR_POS_Y,\n color='darkturquoise',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$estimated\\ trajectory$',\n alpha=0.9)\n axs.plot(\n _CAR_POS_X,\n _CAR_POS_Y,\n color='crimson',\n linestyle=':',\n linewidth=LINE_WIDTH_1,\n label=r'$true\\ trajectory$',\n alpha=0.9)\n axs.set_title(r'$\\mathbf{camera\\ frame}$', fontsize=SUB_TITLE_FONT_SIZE)\n axs.legend()\n axs.axis('equal')\n axs.set(xlabel=r'$x\\ (m)$', ylabel=r'$y\\ (m)$')\n f4.savefig(f'{_PATH}/4_traj_comp.png', dpi=300)\n f4.show()\n\n # -------------------------------------------------------------------------------- figure 5\n # true and tracked pos\n if SHOW_ALL or SHOW_CARTESIAN_PLOTS:\n f4, axs = plt.subplots(2, 1, sharex=True, gridspec_kw={'hspace': 0.4})\n if SUPTITLE_ON:\n f4.suptitle(\n r'$\\mathbf{Vehicle\\ True\\ and\\ Estimated\\ Positions}$',\n fontsize=TITLE_FONT_SIZE)\n\n axs[0].plot(\n _TIME,\n _TRACKED_CAR_POS_X,\n color='rosybrown',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$estimated\\ x$',\n alpha=0.9)\n axs[0].plot(\n _TIME,\n _CAR_POS_X,\n color='red',\n linestyle=':',\n linewidth=LINE_WIDTH_1,\n label=r'$true\\ x$',\n alpha=0.9)\n axs[0].set(ylabel=r'$x\\ (m)$')\n axs[0].set_title(r'$\\mathbf{x}$', fontsize=SUB_TITLE_FONT_SIZE)\n axs[0].legend()\n axs[1].plot(\n _TIME,\n _TRACKED_CAR_POS_Y,\n color='mediumseagreen',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$estimated\\ y$',\n alpha=0.9)\n axs[1].plot(\n _TIME,\n _CAR_POS_Y,\n color='green',\n linestyle=':',\n linewidth=LINE_WIDTH_1,\n label=r'$true\\ y$',\n alpha=0.9)\n axs[1].set(xlabel=r'$time\\ (s)$', ylabel=r'$y\\ (m)$')\n axs[1].set_title(r'$\\mathbf{y}$', fontsize=SUB_TITLE_FONT_SIZE)\n axs[1].legend()\n f4.savefig(f'{_PATH}/5_pos_comp.png', dpi=300)\n f4.show()\n\n # -------------------------------------------------------------------------------- figure 6\n # true and tracked velocities\n if SHOW_ALL or SHOW_CARTESIAN_PLOTS:\n f5, axs = plt.subplots(2, 1, sharex=True, gridspec_kw={'hspace': 0.4})\n if SUPTITLE_ON:\n f5.suptitle(\n r'$\\mathbf{True,\\ Measured\\ and\\ Estimated\\ Vehicle\\ Velocities}$',\n fontsize=TITLE_FONT_SIZE)\n\n axs[0].plot(\n _TIME,\n _MEASURED_CAR_VEL_X,\n color='paleturquoise',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$measured\\ V_x$',\n alpha=0.9)\n axs[0].plot(\n _TIME,\n _TRACKED_CAR_VEL_X,\n color='darkturquoise',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$estimated\\ V_x$',\n alpha=0.9)\n axs[0].plot(\n _TIME,\n _CAR_VEL_X,\n color='crimson',\n linestyle='-',\n linewidth=LINE_WIDTH_2,\n label=r'$true\\ V_x$',\n alpha=0.7)\n axs[0].set(ylabel=r'$V_x\\ (\\frac{m}{s})$')\n axs[0].set_title(r'$\\mathbf{V_x}$', fontsize=SUB_TITLE_FONT_SIZE)\n axs[0].legend(loc='upper right')\n\n axs[1].plot(\n _TIME,\n _MEASURED_CAR_VEL_Y,\n color='paleturquoise',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$measured\\ V_y$',\n alpha=0.9)\n axs[1].plot(\n _TIME,\n _TRACKED_CAR_VEL_Y,\n color='darkturquoise',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$estimated\\ V_y$',\n alpha=0.9)\n axs[1].plot(\n _TIME,\n _CAR_VEL_Y,\n color='crimson',\n linestyle='-',\n linewidth=LINE_WIDTH_2,\n label=r'$true\\ V_y$',\n alpha=0.7)\n axs[1].set(xlabel=r'$time\\ (s)$', ylabel=r'$V_y\\ (\\frac{m}{s})$')\n axs[1].set_title(r'$\\mathbf{V_y}$', fontsize=SUB_TITLE_FONT_SIZE)\n axs[1].legend(loc='upper right')\n\n f5.savefig(f'{_PATH}/6_vel_comp.png', dpi=300)\n f5.show()\n\n # -------------------------------------------------------------------------------- figure 7\n # speed and heading\n if SHOW_ALL or SHOW_SPEED_HEADING:\n f6, axs = plt.subplots(2, 1, sharex=True, gridspec_kw={'hspace': 0.4})\n if SUPTITLE_ON:\n f6.suptitle(\n r'$\\mathbf{Vehicle\\ and\\ UAS,\\ Speed\\ and\\ Heading}$',\n fontsize=TITLE_FONT_SIZE)\n c_speed = (CAR_INITIAL_VELOCITY[0]**2 + CAR_INITIAL_VELOCITY[1]**2)**0.5\n c_heading = degrees(atan2(CAR_INITIAL_VELOCITY[1], CAR_INITIAL_VELOCITY[0]))\n\n axs[0].plot(_TIME,\n _CAR_SPEED,\n color='lightblue',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$|V_{vehicle}|$',\n alpha=0.9)\n axs[0].plot(\n _TIME,\n _DRONE_SPEED,\n color='blue',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$|V_{UAS}|$',\n alpha=0.9)\n axs[0].set(ylabel=r'$|V|\\ (\\frac{m}{s})$')\n axs[0].set_title(r'$\\mathbf{speed}$', fontsize=SUB_TITLE_FONT_SIZE)\n axs[0].legend()\n\n axs[1].plot(_TIME, _CAR_HEADING, color='lightgreen',\n linestyle='-', linewidth=LINE_WIDTH_2, label=r'$\\angle V_{vehicle}$', alpha=0.9)\n axs[1].plot(\n _TIME,\n _DRONE_ALPHA,\n color='green',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$\\angle V_{UAS}$',\n alpha=0.9)\n axs[1].set(xlabel=r'$time\\ (s)$', ylabel=r'$\\angle V\\ (^{\\circ})$')\n axs[1].set_title(r'$\\mathbf{heading}$', fontsize=SUB_TITLE_FONT_SIZE)\n axs[1].legend()\n\n f6.savefig(f'{_PATH}/7_speed_head.png', dpi=300)\n f6.show()\n\n # -------------------------------------------------------------------------------- figure 7\n # altitude profile\n if SHOW_ALL or SHOW_ALTITUDE_PROFILE:\n f7, axs = plt.subplots()\n if SUPTITLE_ON:\n f7.suptitle(r'$\\mathbf{Altitude\\ profile}$', fontsize=TITLE_FONT_SIZE)\n axs.plot(\n _TIME,\n _DRONE_ALTITUDE,\n color='darkgoldenrod',\n linestyle='-',\n linewidth=2,\n label=r'$altitude$',\n alpha=0.9)\n axs.set(xlabel=r'$time\\ (s)$', ylabel=r'$z\\ (m)$')\n\n f7.savefig(f'{_PATH}/8_alt_profile.png', dpi=300)\n f7.show()\n\n # -------------------------------------------------------------------------------- figure 7\n # 3D Trajectories\n ndx = np.array(_DRONE_POS_X) + np.array(_CAM_ORIGIN_X)\n ncx = np.array(_CAR_POS_X) + np.array(_CAM_ORIGIN_X)\n ndy = np.array(_DRONE_POS_Y) + np.array(_CAM_ORIGIN_Y)\n ncy = np.array(_CAR_POS_Y) + np.array(_CAM_ORIGIN_Y)\n\n if SHOW_ALL or SHOW_3D_TRAJECTORIES:\n f8 = plt.figure()\n if SUPTITLE_ON:\n f8.suptitle(r'$\\mathbf{3D\\ Trajectories}$', fontsize=TITLE_FONT_SIZE)\n axs = f8.add_subplot(111, projection='3d')\n axs.plot3D(\n ncx,\n ncy,\n 0,\n color='limegreen',\n linestyle='-',\n linewidth=2,\n label=r'$Vehicle$',\n alpha=0.9)\n axs.plot3D(\n ndx,\n ndy,\n _DRONE_ALTITUDE,\n color='darkslategray',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$UAS$',\n alpha=0.9)\n\n for point in zip(ndx, ndy, _DRONE_ALTITUDE):\n x = [point[0], point[0]]\n y = [point[1], point[1]]\n z = [point[2], 0]\n axs.plot3D(x, y, z, color='gainsboro', linestyle='-', linewidth=0.5, alpha=0.1)\n axs.plot3D(ndx, ndy, 0, color='silver', linestyle='-', linewidth=1, alpha=0.9)\n axs.scatter3D(ndx, ndy, _DRONE_ALTITUDE, c=_DRONE_ALTITUDE, cmap='plasma', alpha=0.3)\n\n axs.set(xlabel=r'$x\\ (m)$', ylabel=r'$y\\ (m)$', zlabel=r'$z\\ (m)$')\n axs.view_init(elev=41, azim=-105)\n # axs.view_init(elev=47, azim=-47)\n axs.set_title(r'$\\mathbf{World\\ frame}$', fontsize=SUB_TITLE_FONT_SIZE)\n axs.legend()\n\n f8.savefig(f'{_PATH}/9_3D_traj.png', dpi=300)\n f8.show()\n\n # -------------------------------------------------------------------------------- figure 7\n # delta time\n if SHOW_ALL or SHOW_DELTA_TIME_PROFILE:\n f9, axs = plt.subplots(2, 1, gridspec_kw={'hspace': 0.4})\n if SUPTITLE_ON:\n f9.suptitle(r'$\\mathbf{Time\\ Delay\\ profile}$', fontsize=TITLE_FONT_SIZE)\n axs[0].plot(\n _TIME,\n _DELTA_TIME,\n color='darksalmon',\n linestyle='-',\n linewidth=2,\n label=r'$\\Delta\\ t$',\n alpha=0.9)\n axs[0].set(xlabel=r'$time\\ (s)$', ylabel=r'$\\Delta t\\ (s)$')\n\n _NUM_BINS = 300\n _DIFF = max(_DELTA_TIME) - min(_DELTA_TIME)\n _BAR_WIDTH = _DIFF/_NUM_BINS if USE_REAL_CLOCK else DELTA_TIME * 0.1\n _RANGE = (min(_DELTA_TIME), max(_DELTA_TIME)) if USE_REAL_CLOCK else (-2*abs(DELTA_TIME), 4*abs(DELTA_TIME))\n _HIST = np.histogram(_DELTA_TIME, bins=_NUM_BINS, range=_RANGE, density=1) if USE_REAL_CLOCK else np.histogram(_DELTA_TIME, bins=_NUM_BINS, density=1)\n axs[1].bar(_HIST[1][:-1], _HIST[0]/sum(_HIST[0]), width=_BAR_WIDTH*0.9, \n color='lightsteelblue', label=r'$Frequentist\\ PMF\\ distribution$', alpha=0.9)\n if not USE_REAL_CLOCK:\n axs[1].set_xlim(-2*abs(DELTA_TIME), 4*abs(DELTA_TIME))\n \n if USE_REAL_CLOCK:\n _MIN, _MAX = axs[1].get_xlim()\n axs[1].set_xlim(_MIN, _MAX)\n _KDE_X = np.linspace(_MIN, _MAX, 301)\n _GAUSS_KER = st.gaussian_kde(_DELTA_TIME)\n _PDF_DELTA_T = _GAUSS_KER.pdf(_KDE_X)\n axs[1].plot(_KDE_X, _PDF_DELTA_T/sum(_PDF_DELTA_T), color='royalblue', linestyle='-',\n linewidth=2, label=r'$Gaussian\\ Kernel\\ Estimate\\ PDF$', alpha=0.8)\n axs[1].set(ylabel=r'$Probabilities$', xlabel=r'$\\Delta t\\ values$')\n axs[1].legend(loc='upper left')\n\n f9.savefig(f'{_PATH}/9_delta_time.png', dpi=300)\n\n f9.show()\n\n # -------------------------------------------------------------------------------- figure 7\n # y1, y2\n if SHOW_ALL or SHOW_Y1_Y2:\n f10, axs = plt.subplots(2, 1, gridspec_kw={'hspace': 0.4})\n if SUPTITLE_ON:\n f10.suptitle(r'$\\mathbf{Objectives}$', fontsize=TITLE_FONT_SIZE)\n axs[0].plot(\n _TIME,\n _TRUE_Y1,\n color='red',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$true\\ y_1$',\n alpha=0.9)\n axs[0].plot(\n _TIME,\n _Y1,\n color='royalblue',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$estimated\\ y_1$',\n alpha=0.9)\n axs[0].plot(\n _TIME,\n [K_W for _ in _TIME],\n color='orange',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$w_1$',\n alpha=0.9)\n axs[0].legend(loc='upper right')\n axs[0].set(ylabel=r'$y_1$')\n axs[0].set_title(r'$\\mathbf{y_1}$', fontsize=SUB_TITLE_FONT_SIZE)\n\n axs[1].plot(\n _TIME,\n _TRUE_Y2,\n color='red',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$true\\ y_2$',\n alpha=0.9)\n axs[1].plot(\n _TIME,\n _Y2,\n color='royalblue',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$estimated\\ y_2$',\n alpha=0.9)\n axs[1].plot(\n _TIME,\n [0.0 for _ in _TIME],\n color='orange',\n linestyle='-',\n linewidth=LINE_WIDTH_1,\n label=r'$w_2$',\n alpha=0.9)\n\n axs[1].legend(loc='upper right')\n axs[1].set(xlabel=r'$time\\ (s)$', ylabel=r'$y_2$')\n axs[1].set_title(r'$\\mathbf{y_2}$', fontsize=SUB_TITLE_FONT_SIZE)\n\n\n f10.savefig(f'{_PATH}/10_objectives.png', dpi=300)\n\n f10.show()\n plt.show()\n\n if RUN_VIDEO_WRITER:\n EXPERIMENT_MANAGER = ExperimentManager()\n # create folder path inside ./sim_outputs\n _PATH = f'./sim_outputs/{time.strftime(\"%Y-%m-%d_%H-%M-%S\")}'\n _prep_temp_folder(os.path.realpath(_PATH))\n VID_PATH = f'{_PATH}/sim_track_control.avi'\n print('Making video.')\n EXPERIMENT_MANAGER.make_video(VID_PATH, SIMULATOR_TEMP_FOLDER)\n","sub_path":"vbot/experiments/exp_lc/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":29711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"416137242","text":"\"\"\"Dynamic Manifest Generation.\"\"\"\n\nimport logging\nfrom datetime import datetime as dt, timedelta\nfrom f8a_report.helpers.report_helper import ReportHelper\nfrom f8a_report.helpers.manifest_helper import manifest_interface\nimport os\n\nlogger = logging.getLogger(__file__)\n\n\ndef main():\n \"\"\"Generate the dynamic manifest file weekly.\"\"\"\n r = ReportHelper()\n today = dt.today()\n\n start_date_wk = (today - timedelta(days=7)).strftime('%Y-%m-%d')\n end_date_wk = today.strftime('%Y-%m-%d')\n\n logger.info(\"Value of generate_manifest flag is %s\",\n os.environ.get('GENERATE_MANIFESTS', 'False'))\n if os.environ.get('GENERATE_MANIFESTS', 'False') in ('True', 'true', '1'):\n logger.info('Generating Manifests based on last 1 week Stack Analyses calls.')\n stacks = r.retrieve_stack_analyses_content(start_date_wk, end_date_wk)\n manifest_interface(stacks)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"f8a_report/manifest_main.py","file_name":"manifest_main.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"341554088","text":"# Basic List comprehensions\neven_numbers = [ num * 2 for num in range(6) ]\nprint('event_numbers = %s' % even_numbers)\n\nsquares = [ num ** 2 for num in range(6) ]\nprint('squares = %s' % squares)\n\n# Basic Dict Comprehensions\neven_number_mapping = { num : num * 2 for num in range(6) }\nprint('even_number_mapping = %s' % even_number_mapping)\n\nsquare_mapping = { root : root ** 2 for root in range(6) }\nprint('square mapping = %s' % square_mapping)\n\n# multiple loop comprehensions\nsome_coords = [\n (x, y)\n for x in range(2)\n for y in range(2) # x is accessible in this loop\n]\n\nprint('some_coords = %s' % some_coords)","sub_path":"03-exercises/list-comprehensions.py","file_name":"list-comprehensions.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"151125626","text":"import time\nimport torch\nimport argparse\nimport sys\nsys.path.append('./models')\nfrom models_dict import dict\nfrom data_loader_1 import data_loader\nfrom functions_for_time_test import *\nfrom torch.nn import DataParallel\nfrom torch.autograd import Variable\n\n# ***********************************************************************************Training settings\nparser = argparse.ArgumentParser(description='models on rgb data')\nparser.add_argument('--data_list_root', type=str, default='../preprocess/data_list/')\nparser.add_argument('--data_set', type=str, default='N_UCLA')\nparser.add_argument('--model_split', type=str, default='cs')\nparser.add_argument('--split_type', type=str, default='v3')\nparser.add_argument('--sample_shape', type=int, default=[224, 224, 32])\nparser.add_argument('--model_name', type=str, default='ITS_1')\nparser.add_argument('--use_cuda', type=bool, default=True)\nparser.add_argument('--devices', type=str, default='0')\nparser.add_argument('--test_batch_size', type=int, default=4)\nparser.add_argument('--topk', type=int, default=5)\nparser.add_argument('--num_workers', type=int, default=2)\nargs = parser.parse_args()\n\n# os.environ['CUDA_VISIBLE_DEVICES'] = args.devices\n\n# ************************************************************************************data loaders\nrgb_data_dir = args.data_list_root + '{}/{}_{}_rgb_test.txt'.format(args.data_set, args.data_set, args.split_type)\nrgb_eval_data_dir = args.data_list_root + '{}/{}_{}_rgb_test_eval.txt'.format(args.data_set, args.data_set, args.split_type)\n\nrgb_val_loader = torch.utils.data.DataLoader(data_loader(rgb_eval_data_dir, args.sample_shape, 'rgb', 'eval')\n , batch_size=args.test_batch_size, shuffle=False, num_workers=args.num_workers)\n\n# *************************************************************************************initial model and optimizer\nmodel_rgb = DataParallel(dict[args.model_name](num_classes=10, input_channel=3, dropout_keep_prob=0.0))\n# model_rgb = dict[args.model_name](num_classes=10, input_channel=3, dropout_keep_prob=0.0)\nif args.use_cuda: model_rgb.cuda()\n\n\nfor data, target, video_ids in rgb_val_loader:\n if args.use_cuda:\n data = data.cuda()\n data = Variable(data / 127.5 - 1, volatile=True)\n time_start=time.time()\n output = model_rgb(data)\n torch.cuda.synchronize()\n time_cost = time.time()-time_start\n print(time_cost)\n\n\n","sub_path":"training/time_test_main.py","file_name":"time_test_main.py","file_ext":"py","file_size_in_byte":2376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"195517819","text":"# In The Name Of Allah\n#\n# Jalali date converter\n# Ported from PHP (http://jdf.scr.ir/) to Python (2&3) by Mohammad Javad Naderi \n#\n# As mentioned in http://jdf.scr.ir/, the original code is free and open source,\n# and you are not allowed to sell it. You can read more in http://jdf.scr.ir/.\n#\n# Original License Notes:\n#\n# /** Software Hijri_Shamsi , Solar(Jalali) Date and Time\n# Copyright(C)2011, Reza Gholampanahi , http://jdf.scr.ir\n# version 2.55 :: 1391/08/24 = 1433/12/18 = 2012/11/15 */\n#\n# /** Convertor from and to Gregorian and Jalali (Hijri_Shamsi,Solar) Functions\n# Copyright(C)2011, Reza Gholampanahi [ http://jdf.scr.ir/jdf ] version 2.50 */\n#\n# Example Usage:\n# >>> import jalali\n# >>> jalali.convert_to_gregorian('1393-1-11')\n# datetime.date(2014, 3, 31)\n# >>> jalali.convert_to_jalali('2014-3-31')\n# '1393-1-11'\n# >>> import datetime\n# >>> today = datetime.date(2014, 5, 7)\n# >>> jalali.convert_to_jalali(today)\n# '1393-2-17'\n\nimport re\nimport datetime\n\n\ndef convert_to_jalali(date):\n\tif type(date) is str:\n\t\tm1 = re.match(r'^(\\d{4})-(\\d{1,2})-(\\d{1,2})$', date)\n\t\tif m1:\n\t\t\t[year, month, day] = [int(m1.group(1)), int(m1.group(2)), int(m1.group(3))]\n\t\telse:\n\t\t\traise Exception(\"Invalid Input String\")\n\telif type(date) is datetime.date:\n\t\t[year, month, day] = [date.year, date.month, date.day]\n\telse:\n\t\traise Exception(\"Invalid Input Type\")\n\tif month > 12 or day > 31:\n\t\traise Exception(\"Incorrect Date\")\n\td_4 = year % 4\n\tg_a = [0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]\n\tdoy_g = g_a[month] + day\n\tif d_4 == 0 and month > 2:\n\t\tdoy_g += 1\n\td_33 = int(((year-16) % 132)*.0305)\n\ta = 286 if (d_33 == 3 or d_33 < (d_4-1) or d_4 == 0) else 287\n\tif (d_33 == 1 or d_33 == 2) and (d_33 == d_4 or d_4 == 1):\n\t\tb = 78\n\telse:\n\t\tb = 80 if (d_33 == 3 and d_4 == 0) else 79\n\tif int((year-10)/63) == 30:\n\t\ta -= 1\n\t\tb += 1\n\tif doy_g > b:\n\t\tjy = year-621\n\t\tdoy_j = doy_g-b\n\telse:\n\t\tjy = year-622\n\t\tdoy_j = doy_g+a\n\tif doy_j < 187:\n\t\tjm = int((doy_j-1)/31)\n\t\tjd = doy_j-(31*jm)\n\t\tjm += 1\n\telse:\n\t\tjm = int((doy_j-187)/30)\n\t\tjd = doy_j-186-(jm*30)\n\t\tjm += 7\n\treturn \"{}-{}-{}\".format(jy, jm, jd)\n\n\ndef convert_to_gregorian(date):\n\tm1 = re.match(r'^(\\d{4})-(\\d{1,2})-(\\d{1,2})$', date)\n\tif m1:\n\t\t[year, month, day] = [int(m1.group(1)), int(m1.group(2)), int(m1.group(3))]\n\telse:\n\t\traise Exception(\"Incorrect Date Format\")\n\tif month > 12 or day > 31:\n\t\traise Exception(\"Incorrect Date\")\n\td_4 = (year+1) % 4\n\tif month < 7:\n\t\tdoy_j = ((month-1)*31)+day\n\telse:\n\t\tdoy_j = ((month-7)*30)+day+186\n\td_33 = int(((year-55) % 132)*.0305)\n\ta = 287 if (d_33 != 3 and d_4 <= d_33) else 286\n\tif (d_33 == 1 or d_33 == 2) and (d_33 == d_4 or d_4 == 1):\n\t\tb = 78\n\telse:\n\t\tb = 80 if (d_33 == 3 and d_4 == 0) else 79\n\tif int((year-19)/63) == 20:\n\t\ta -= 1\n\t\tb += 1\n\tif doy_j <= a:\n\t\tgy = year+621\n\t\tgd = doy_j+b\n\telse:\n\t\tgy = year+622\n\t\tgd = doy_j-a\n\tfor gm, v in enumerate([0, 31, 29 if (gy % 4 == 0) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]):\n\t\tif gd <= v:\n\t\t\tbreak\n\t\tgd -= v\n\treturn datetime.date(gy, gm, gd)","sub_path":"jalali.py","file_name":"jalali.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"239123852","text":"import numpy as np\ns=[]\ner=0\ntol=0.05\nd=[]\na=np.array([[1.0,2.0,-1.0],[5.0,2.0,2.0],[-3.0,5.0,-1.0]])\nb=np.array([[2.0],[9.0],[1.0]])\nx=np.array([[3.0],[3.0],[3.0]]) #x的值隨便設,反正之後會變\nn=3\nfor i in range(0,n,1):\n s.append(abs(a[i,0])) #將a[i,0]加入s矩陣\n #print(s[i])\n for j in range(1,n):\n if abs(a[i,j])>s[i]: #如果同一列有數大於s[i](同一列第一個被加進去的數),較大的就取代之,直到s矩陣是每一列最大的數\n s[i]=(abs(a[i,j]))\n#eliminate\nfor k in range(0,n-1): #交換+前消\n#pivot\n p=k #p為列號\n big=abs(a[k,k]/s[k]) #pivot=對角線數/最大值\n for o in range(k+1,n): #從下一列開始比較(k+1列),找pivot最大的列\n dummy=abs(a[o,k]/s[o]) #假設dum=某列的值/某列最大值\n if dummy>big: #如果dum>big,即某列值/最大值>原列值/最大值\n big=dummy #pivot值改成dum\n p=o #p由k列改成o\n if p!=k: #如果p不等於k:\n for m in range(k,n):#把第一列和下面的列數比較,若p不等於k則每一列元素和原本的互換,\n d=a[p,m] #a矩陣的互換\n a[p,m]=a[k,m]\n a[k,m]=d\n c=b[p,0] #b矩陣互換\n b[p,0]=b[k,0]\n b[k,0]=c\n \n e=s[p] #s矩陣互換\n s[p]=s[k]\n s[k]=e\n\n if abs(a[k,k]/s[k]) 0, regions.values())\n # start sorting from the region with the most overage to make this algorithm more stable\n #todo Is this claim of greater stability true?\n for source_region in sorted(regions_w_overage, key=lambda x: x.overage, reverse=True):\n if restrict_to_neighbors:\n # Get neighboring regions in the order in which we'll check them\n target_region_set = filter(lambda x: x in source_region.neighboring_regions, available_regions)\n else:\n target_region_set = available_regions\n\n for target_region_id in target_region_set:\n target_region = regions[target_region_id]\n new_overage = target_region.distrib_overage(source_region.overage)\n\n if VERBOSE and new_overage != source_region.overage:\n print(\"Transferring %d lbs from region %d to %d -- neighbors? %s\" %\n (source_region.overage - new_overage, source_region.id, target_region.id,\n str(restrict_to_neighbors)))\n\n source_region.overage = new_overage\n\n if source_region.overage == 0:\n break\n\n# -------------------------------------------------------------\n\n# Step 1 - Read input files\nneighbor_map = dict()\n#todo put error checking from check_puma_mapping.py in here\nwith open(PUMA_MAP_FILE, 'rbU') as csvfile:\n reader = csv.reader(csvfile)\n\n # skip the header rows\n next(reader, None)\n\n for row in reader:\n region_id = int(row[0])\n neighbors = map(lambda x: int(x), row[1].split(\",\"))\n\n if region_id in neighbor_map:\n print(\"Region id %d appears twice in region mapping file\" % region_id)\n else:\n neighbor_map[region_id] = set(neighbors)\n\nregion_to_demand = dict()\nregion_to_target = dict()\nwith open(REGION_INPUT_FILE, 'rbU') as csvfile:\n reader = csv.reader(csvfile)\n\n # skip the header rows\n next(reader, None)\n\n for row in reader:\n if not row[0].isdigit():\n continue\n\n region_id = int(row[0])\n name = row[1]\n ppl_in_need = str_to_int(row[2])\n ef_demand_total = str_to_int(row[3])\n ef_demand_satisfied = str_to_int(row[4])\n ef_demand_residual = str_to_int(row[5])\n region_target = str_to_int(row[6])\n\n region_to_demand[region_id] = ef_demand_residual\n region_to_target[region_id] = region_target\n\nregions = dict() # region_id -> Region\nwith open(AGENCY_INPUT_FILE, 'rbU') as csvfile:\n reader = csv.reader(csvfile)\n\n # skip the header rows\n next(reader, None)\n\n for row in reader:\n # get rid of the unicode nonsense (thanks MSFT!)\n row = map(lambda x: str(x.decode(\"ascii\", \"ignore\")), row)\n\n if row[0] == \"\":\n continue\n\n agency_name = row[0]\n ch_id = row[1]\n efro = int(row[2])\n region_id = int(row[3])\n meals_served = int(row[4])\n agency_region_count = int(row[5])\n pctg = row[6] # todo fix output format from excel\n tgt_pounds = str_to_int(row[7])\n capacity = str_to_int(row[8])\n\n if region_id not in regions:\n if region_id not in neighbor_map:\n print(\"Could not find region->neighbor mapping for region %d\" % region_id)\n continue\n\n if region_id not in region_to_demand:\n print(\"Could not find region->demadn mapping for region %d\" % region_id)\n continue\n\n regions[region_id] = Region(region_id, region_to_demand[region_id], neighbor_map[region_id])\n\n regions[region_id].add_agency(Agency(ch_id, tgt_pounds, capacity, meals_served))\n\n# Some regions don't have agencies. Set the overage for those regions appropriately.\nregions_wo_agencies = set(region_to_target.keys()) - set(regions.keys())\nfor region_id in regions_wo_agencies:\n if region_id not in neighbor_map:\n print(\"Could not find region->neighbor mapping for region %d\" % region_id)\n continue\n\n regions[region_id] = Region(region_id, region_to_demand[region_id], neighbor_map[region_id])\n regions[region_id].overage = region_to_target[region_id]\n\n# Step 2 - Redistribute within a region, from agency with most bandwidth to least bandwidth\nfor region in regions.values():\n #todo Move this to Region method?\n overage = 0\n for agency in region.agencies:\n if agency.get_overage() > 0:\n overage += agency.get_overage()\n agency.cur_tgt = agency.capacity\n\n if overage > 0:\n region.overage = region.distrib_overage(overage)\n\n# Step 3 - Redistribute among neighboring regions, from region with most need to region with least need\ndistrib_btwn_regions(True)\n\n# Step 4 - Deal with remainder: Redistribute among regions, from region with most need to region with least need\ndistrib_btwn_regions(False)\n\n# Step 5 - Output\nfor region in regions.values():\n for agency in region.agencies:\n print(\"%s,%s,%d,%d,%d\" % (region.id, agency.ch_id, agency.init_tgt, agency.cur_tgt, agency.true_capacity))\n\nfor region in regions.values():\n if VERBOSE and region.overage > 0:\n print(\"Region %d has unallocated overage of %d\" % (region.id, region.overage))\n","sub_path":"agency_targeting.py","file_name":"agency_targeting.py","file_ext":"py","file_size_in_byte":7800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"552464713","text":"import os\nfrom os.path import realpath, dirname, join, isfile\nimport subprocess\n\nCURRENT_DIRECTORY = realpath(dirname(__file__))\nMTS1_DIST = realpath(join(CURRENT_DIRECTORY, '../../../../../mitsuba/dist'))\nMTS2_DIST = realpath(join(CURRENT_DIRECTORY, '../../../../build/dist'))\nassert isfile(join(MTS1_DIST, 'mitsuba'))\n\nscene_variants = {\n 'cbox_spectral': 'cbox-spectral.xml',\n 'cbox_rgb': 'cbox-rgb.xml',\n}\nmodes = [\n 'scalar_rgb',\n 'scalar_spectral',\n # 'packet_rgb',\n # 'packet_spectral',\n]\n\n\ndef main():\n i = 0\n for variant, scene_fname in scene_variants.items():\n # Mitsuba 1 reference\n mts1_fname = join(CURRENT_DIRECTORY, 'mts1-' + scene_fname)\n out = join(CURRENT_DIRECTORY, '{:02d}-mts1-{}.exr'.format(i, variant))\n subprocess.check_call(['./mitsuba', mts1_fname, '-o', out], cwd=MTS1_DIST)\n i += 1\n\n # Mitsuba 2, different modes\n for mode in modes:\n mts2_fname = join(CURRENT_DIRECTORY, scene_fname)\n out = join(CURRENT_DIRECTORY, '{:02d}-mts2-{}--{}.exr'.format(i, variant, mode))\n subprocess.check_call(['./mitsuba', mts2_fname,\n '-m', mode,\n '-o', out], cwd=MTS2_DIST)\n i += 1\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scenes/cbox/test_cbox_variants.py","file_name":"test_cbox_variants.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"613664516","text":"#!/usr/bin/env python\n# encoding: utf-8\nimport redis\nimport sys\nimport os\nimport logging\nsys.path.append(os.getcwd())\nfrom settings import LOCAL_REDIS_HOST, LOCAL_REDIS_PORT,PROXY_BASEURL,LOCAL_MONGO_PORT, LOCAL_MONGO_HOST, DB_NAME, PROFILE_GROUP\nfrom pymongo import MongoClient\nfrom sina.spiders.utils import get_random_proxy\n\n\n\n# init redis \nr = redis.Redis(host=LOCAL_REDIS_HOST, port=LOCAL_REDIS_PORT)\nfor key in r.scan_iter(\"weibo_user_timeline_spider*\"):\n r.delete(key)\n\nclient = MongoClient(LOCAL_MONGO_HOST, LOCAL_MONGO_PORT)\nprofiles_collection = client[DB_NAME]['user_profiles']\n\nif PROFILE_GROUP > 0:\n seeds = profiles_collection.find(\n {\"timelineCrawlJob_current_complete\": False, \"group\":PROFILE_GROUP}\n )\nelse:\n seeds = profiles_collection.find(\n {\"timelineCrawlJob_current_complete\": False}\n )\n\nprint(seeds.count(),\"profiles found\")\nfor seed in seeds:\n if PROXY_BASEURL:\n base_url = get_random_proxy()\n else:\n base_url = \"https://weibo.cn\"\n start_url = base_url + '/{}?page={}'.format(seed['_id'],seed['timelineCrawlJob_current_page'])\n print(\"[DEBUG] start url: \"+start_url)\n r.lpush('weibo_user_timeline_spider:start_urls', start_url)\n\n\nprint('Redis initialized')\n\n\n\n# push urls to redis\n# for uid in start_uids:\n# start_url = base_url+(\"%s/info\" % uid)\n# r.lpush('weibo_user_timeline_spider:start_urls', start_url)\n\n# for url in start_urls:\n# url = url.replace(\"https://weibo.cn\",PROXY_BASEURL)\n# r.lpush('weibo_user_timeline_spider:start_urls', url)\n\n# print('Redis initialized')\n","sub_path":"crawl_user_timeline/sina/redis_init.py","file_name":"redis_init.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"254782551","text":"import os\nimport pickle\n\nimport cv2\nimport numpy as np\n\nfrom utils import hand_angle, plothand\n\nhand_connMat = np.array(\n [0, 1, 1, 2, 2, 3, 3, 4, 0, 5, 5, 6, 6, 7, 7, 8, 0, 9, 9, 10, 10, 11, 11, 12, 0, 13, 13, 14, 14, 15, 15, 16, 0, 17,\n 17, 18, 18, 19, 19, 20]).reshape(-1, 2)\n# don't include chinese character in path, or cv2 read image will fail\nfolder_path = '\\mtc_dataset\\hand_data'\n\n\ndef project(joints, calib, apply_distort=True):\n \"\"\"\n project is a function that project 3d world joints to 2d and 3d joints in camera coordination\n\n Args:\n :param joints: joints in 3d world coordination. N * 3 numpy array.\n :param calib: a dict containing 'R', 'K', 't', 'distCoef' (numpy array)\n\n Returns:\n :return pt: N * 2 numpy array\n :return pt_cam: N * 3 numpy array in camera coordination\n \"\"\"\n x = np.dot(calib['R'], joints.T) + calib['t']\n xp = x[:2, :] / x[2, :]\n\n if apply_distort:\n x2 = xp[0, :] * xp[0, :]\n y2 = xp[1, :] * xp[1, :]\n xy = x2 * y2\n r2 = x2 + y2\n r4 = r2 * r2\n r6 = r4 * r2\n\n dc = calib['distCoef']\n radial = 1.0 + dc[0] * r2 + dc[1] * r4 + dc[4] * r6\n tan_x = 2.0 * dc[2] * xy + dc[3] * (r2 + 2.0 * x2)\n tan_y = 2.0 * dc[3] * xy + dc[2] * (r2 + 2.0 * y2)\n\n # xp = [radial;radial].*xp(1:2,:) + [tangential_x; tangential_y]\n xp[0, :] = radial * xp[0, :] + tan_x\n xp[1, :] = radial * xp[1, :] + tan_y\n\n # pt = bsxfun(@plus, cam.K(1:2,1:2)*xp, cam.K(1:2,3))';\n pt = np.dot(calib['K'][:2, :2], xp) + calib['K'][:2, 2].reshape((2, 1))\n\n return pt.T, x.T\n\n\ndef viz(outpath, savefig=False):\n \"\"\"\n viz is a function that crop and visualize keypoint annotation on image\n\n Args:\n :param outpath: the output path of image if savefile is True\n :param savefig : whether to save the visualized image. default to False\n\n Returns:\n :return None\n \"\"\"\n with open(os.path.join(folder_path + 'annotation.pkl'), 'rb') as f:\n data = pickle.load(f)\n\n with open(os.path.join(folder_path + 'camera_data.pkl'), 'rb') as f:\n cam = pickle.load(f)\n\n mode_data = data['training_data']\n # mode_data = data['testing_data']\n\n for i, sample in enumerate(mode_data):\n if i > 15:\n break\n seq_name = sample['seqName']\n frame_str = sample['frame_str']\n frame_path = os.path.join(folder_path, 'hdImgs/{}/{}'.format(seq_name, frame_str))\n outdir_parent = os.path.join(outpath, seq_name, frame_str)\n\n if 'left_hand' in sample:\n # this means left hands exists, then we project 3d to 31 different camera\n outdir = os.path.join(outdir_parent, 'left')\n if savefig:\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n for c in range(31):\n img_name = os.path.join(frame_path, '00_{:02d}_{}.jpg'.format(c, frame_str))\n # since some camera image is missing, we need to judge whether image exists\n if os.path.exists(img_name) and sum(sample['left_hand']['2D'][c]['occluded']) <= 5:\n calib_data = cam[seq_name][c]\n # kp process\n left_hand_landmark = np.array(sample['left_hand']['landmarks']).reshape(-1, 3)\n left_kp_2d, camera_3d = project(left_hand_landmark, calib_data)\n angle = hand_angle(camera_3d)\n\n # image process\n img = cv2.imread(img_name)\n x_min = min(left_kp_2d[:, 0])\n x_max = max(left_kp_2d[:, 0])\n y_min = min(left_kp_2d[:, 1])\n y_max = max(left_kp_2d[:, 1])\n crop_x_min = max(0, int(x_min - ((x_max - x_min) / 2)))\n crop_x_max = min(img.shape[1] - 1, int(x_max + ((x_max - x_min) / 2)))\n crop_y_min = max(0, int(y_min - ((y_max - y_min) / 2)))\n crop_y_max = min(img.shape[0] - 1, int(y_max + ((y_max - y_min) / 2)))\n img = img[crop_y_min:crop_y_max, crop_x_min:crop_x_max]\n left_kp_2d[:, 0] = left_kp_2d[:, 0] - crop_x_min\n left_kp_2d[:, 1] = left_kp_2d[:, 1] - crop_y_min\n\n plothand(img, left_kp_2d)\n if savefig:\n outpath_img = os.path.join(outdir, '00_{:02d}_{}.jpg'.format(c, frame_str))\n cv2.imwrite(outpath_img, img)\n else:\n cv2.imshow('00_{:02d}_{}.jpg'.format(c, frame_str), img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n if 'right_hand' in sample:\n # this means left hands exists, then we project 3d to 31 different camera\n outdir = os.path.join(outdir_parent, 'right')\n if savefig:\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n for c in range(31):\n img_name = os.path.join(frame_path, '00_{:02d}_{}.jpg'.format(c, frame_str))\n # since some camera image is missing, we need to judge whether image exists\n if os.path.exists(img_name) and sum(sample['right_hand']['2D'][c]['occluded']) <= 5:\n calib_data = cam[seq_name][c]\n # kp process\n right_hand_landmark = np.array(sample['right_hand']['landmarks']).reshape(-1, 3)\n right_kp_2d, camera_3d = project(right_hand_landmark, calib_data)\n angle = hand_angle(camera_3d)\n\n # image process\n img = cv2.imread(img_name)\n x_min = min(right_kp_2d[:, 0])\n x_max = max(right_kp_2d[:, 0])\n y_min = min(right_kp_2d[:, 1])\n y_max = max(right_kp_2d[:, 1])\n crop_x_min = max(0, int(x_min - ((x_max - x_min) / 2)))\n crop_x_max = min(img.shape[1] - 1, int(x_max + ((x_max - x_min) / 2)))\n crop_y_min = max(0, int(y_min - ((y_max - y_min) / 2)))\n crop_y_max = min(img.shape[0] - 1, int(y_max + ((y_max - y_min) / 2)))\n img = img[crop_y_min:crop_y_max, crop_x_min:crop_x_max]\n right_kp_2d[:, 0] = right_kp_2d[:, 0] - crop_x_min\n right_kp_2d[:, 1] = right_kp_2d[:, 1] - crop_y_min\n\n plothand(img, right_kp_2d)\n if savefig:\n outpath_img = os.path.join(outdir, '00_{:02d}_{}.jpg'.format(c, frame_str))\n cv2.imwrite(outpath_img, img)\n else:\n cv2.imshow('00_{:02d}_{}.jpg'.format(c, frame_str), img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\ndef main():\n outpath = 'sample'\n viz(outpath, savefig=False)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"CMU/mtc/viz.py","file_name":"viz.py","file_ext":"py","file_size_in_byte":7038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"491021530","text":"# \n# def solution_(people, limit):\n# answer = 0\n \n# people.sort()\n# i = 0 \n# while True:\n# if i == len(people) - 1:\n# answer += 1\n# break\n# elif people[i] + people[i+1] <= limit:\n# answer += 1\n# i += 2\n# elif people[i] <= limit and people[i+1] + people[i] > limit:\n# answer += 1\n# i += 1\n \n# print(answer)\n# return answer\n\n\ndef solution(people, limit):\n answer = 0\n \n people.sort()\n\n # 양끝에서부터 확인\n i = 0 \n j = len(people) - 1\n\n # 중심에 도달할때까지 반복\n while i <= j:\n # max 값을 cnt 한번 해주고 시작\n answer += 1\n if people[i] + people[j] <= limit:\n i += 1\n j -= 1\n\n return answer\n\npeople = [30,40,50,60,70,80]\nlimit = 100\nsolution(people, limit)","sub_path":"Programmers/Level2/구명보트.py","file_name":"구명보트.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"563556505","text":"'''\nCreated on Mar 1, 2019\n\n@author: dan\n'''\n\nimport os\nimport time\nimport argparse\nimport subprocess\nimport shutil\n\nROOT_DIR = os.path.dirname(os.path.abspath(__file__))\n\ndef main():\n \n start = time.time()\n\n args = parse_args()\n \n with open(args.problemlist) as file:\n problemlist = [line.strip() for line in file]\n \n with open(args.testsetup) as file:\n lines = [line.strip() for line in file]\n \n testsetup = []\n \n for line in lines:\n testsetup.append([ int(vals) for vals in line.split()])\n \n dirnames = os.listdir(args.trajectoriessource)\n \n used_counter = 0\n \n dirlist = []\n\n for testline in testsetup:\n \n copy_size = testline[0]\n amount_of_copies = testline[1]\n \n for i in range(0, amount_of_copies): \n dirlist.append(dirnames[used_counter:used_counter + copy_size])\n used_counter += copy_size;\n \n for dirs_to_copy in dirlist:\n \n for dir in dirs_to_copy:\n src = args.trajectoriessource + '/' + dir\n dst = args.trajectories + '/' + dir\n shutil.copytree(src, dst)\n\n for problem in problemlist: \n if problem.endswith(\".pddl\"): \n processList = ['java', '-jar', args.jar, \n args.creator,\n args.grounded,\n args.localview,\n args.trajectories,\n args.domain,\n problem,\n args.agents,\n args.output,\n args.outputtest\n ]\n \n print((', '.join(processList)))\n \n process = subprocess.Popen(processList)\n process.wait() \n \n end = time.time() \n \n print((\"Done! (time - %0.4f\" %(end - start)+\")\"))\n \n\ndef parse_args():\n \n argparser = argparse.ArgumentParser()\n \n argparser.add_argument(\n \"creator\", help=\"creator class\", type=str)\n argparser.add_argument(\n \"grounded\", help=\"path to grounded problem directory\", type=str)\n argparser.add_argument(\n \"localview\", help=\"path to localview directory\", type=str)\n argparser.add_argument(\n \"trajectories\", help=\"path to trajectories directory\", type=str)\n argparser.add_argument(\n \"domain\", help=\"domain file name\", type=str)\n argparser.add_argument(\n \"problem\", help=\"problem file name\", type=str)\n argparser.add_argument(\n \"agents\", help=\"path to agents file\", type=str)\n argparser.add_argument(\n \"output\", help=\"path to output directory\", type=str)\n argparser.add_argument(\n \"outputtest\", help=\"path to test output directory\", type=str)\n argparser.add_argument(\n \"jar\", help=\"path to jar file\", type=str)\n argparser.add_argument(\n \"problemlist\", help=\"path to problem list file\", type=str)\n argparser.add_argument(\n \"trajectoriessource\", help=\"path to test setup file\", type=str)\n argparser.add_argument(\n \"testsetup\", help=\"path to test setup file\", type=str)\n \n return argparser.parse_args()\n\n\nif __name__ == '__main__':\n main()\n \n","sub_path":"OurPlanner/Scripts/run-list.py","file_name":"run-list.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"122484779","text":"from rest_framework import serializers\n\nfrom apps.manager.models import GroupsManager\nfrom apps.account.models import CustomUser\nfrom apps.group.api.serializers import UserNameWithLinkSerializer, UserNameSerializer, HomeGroupSerializer, \\\n HomeGroupNameSerializer, \\\n HomeGroupNamePeoplesCountSerializer, UserNameWithImageSerializer\nfrom apps.account.api.serializers import UserSingleSerializer\n\n\nclass ManagerSerializer(serializers.ModelSerializer):\n manager = UserNameWithImageSerializer(read_only=True, required=False, source='person')\n\n class Meta:\n model = GroupsManager\n fields = ('manager', 'group_count', 'leader_count', 'peoples_count')\n\n\nclass ManagersHomeGroupDetailSerializer(serializers.ModelSerializer):\n managed_groups = serializers.SerializerMethodField('get_managedgroups')\n\n class Meta:\n model = CustomUser\n fields = ('id', 'fullname', 'managed_groups')\n\n def get_managedgroups(self, instance):\n return HomeGroupNamePeoplesCountSerializer([gm.group for gm in instance.managed_groups.all()], read_only=True,\n many=True).data\n\n\nclass ManagersHomeGroupReportLevelOneSerializer(serializers.ModelSerializer):\n manager = serializers.SerializerMethodField()\n total = serializers.SerializerMethodField()\n home_meeting = serializers.SerializerMethodField()\n marathon_meeting = serializers.SerializerMethodField()\n serving_meeting = serializers.SerializerMethodField()\n\n class Meta:\n model = CustomUser\n fields = ('manager', 'total', 'home_meeting', 'marathon_meeting', 'serving_meeting')\n\n def get_manager(self, obj):\n return {'id': obj.id, 'fullname': obj.fullname}\n\n def get_total(self, obj):\n payload = {\n 'leaders': self.context.get('leader_total_count'),\n 'groups': self.context.get('group_total_count'),\n 'people': self.context.get('people_total_count'),\n 'trainee': self.context.get('trainee_total_count')\n }\n return payload\n\n def get_home_meeting(self, obj):\n payload = {\n 'people_sum_on_start_period': self.context.get('home_meeting_people_sum_start_period'),\n 'attends_on_start_period': self.context.get('home_meeting_attends_start_period'),\n 'people_sum_on_end_period': self.context.get('home_meeting_people_sum_end_period'),\n 'attends_on_end_period': self.context.get('home_meeting_attends_end_period'),\n 'new_people_count_for_period': self.context.get('home_meeting_new_people_for_period_count'),\n 'repented_count_for_period': self.context.get('home_meeting_repented_for_period_count'),\n 'guests_count_for_period': self.context.get('home_meeting_guests_for_period_count'),\n 'growing': {'attends': self.context.get('home_meeting_growing_attends'),\n 'visits': self.context.get('home_meeting_growing_visits'),\n 'new_people': self.context.get('home_meeting_growing_new_people'),\n 'repented': self.context.get('home_meeting_growing_repented'),\n 'guests': self.context.get('home_meeting_growing_guest'),\n 'all': self.context.get('home_meeting_growing_all')\n },\n 'percent_attends_on_edges': self.context.get('home_meeting_percent_avg'),\n 'home_meeting_reports_count': self.context.get('home_meeting_number'),\n }\n return payload\n\n def get_marathon_meeting(self, obj):\n payload = {\n 'people_sum_on_start_period': self.context.get('marathon_meeting_people_sum_start_period'),\n 'attends_on_start_period': self.context.get('marathon_meeting_attends_start_period'),\n 'people_sum_on_end_period': self.context.get('marathon_meeting_people_sum_end_period'),\n 'attends_on_end_period': self.context.get('marathon_meeting_attends_end_period'),\n 'new_people_count_for_period': self.context.get('marathon_meeting_new_people_for_period_count'),\n 'repented_count_for_period': self.context.get('marathon_meeting_repented_for_period_count'),\n 'guests_count_for_period': self.context.get('marathon_meeting_guests_for_period_count'),\n 'growing': {'attends': self.context.get('marathon_meeting_growing_attends'),\n 'visits': self.context.get('marathon_meeting_growing_visits'),\n 'new_people': self.context.get('marathon_meeting_growing_new_people'),\n 'repented': self.context.get('marathon_meeting_growing_repented'),\n 'guests': self.context.get('marathon_meeting_growing_guest'),\n 'all': self.context.get('marathon_meeting_growing_all')\n },\n 'percent_attends_on_edges': self.context.get('marathon_meeting_percent_avg'),\n 'marathon_meeting_reports_count': self.context.get('marathon_meeting_number'),\n }\n return payload\n\n def get_serving_meeting(self, obj):\n payload = {\n 'people_sum_on_start_period': self.context.get('serving_meeting_people_sum_start_period'),\n 'attends_on_start_period': self.context.get('serving_meeting_attends_start_period'),\n 'people_sum_on_end_period': self.context.get('serving_meeting_people_sum_end_period'),\n 'attends_on_end_period': self.context.get('serving_meeting_attends_end_period'),\n 'new_people_count_for_period': self.context.get('serving_meeting_new_people_for_period_count'),\n 'repented_count_for_period': self.context.get('serving_meeting_repented_for_period_count'),\n 'guests_count_for_period': self.context.get('serving_meeting_guests_for_period_count'),\n 'growing': {'attends': self.context.get('serving_meeting_growing_attends'),\n 'visits': self.context.get('serving_meeting_growing_visits'),\n 'new_people': self.context.get('serving_meeting_growing_new_people'),\n 'repented': self.context.get('serving_meeting_growing_repented'),\n 'guests': self.context.get('serving_meeting_growing_guest'),\n 'all': self.context.get('serving_meeting_growing_all')\n },\n 'percent_attends_on_edges': self.context.get('serving_meeting_percent_avg'),\n 'serving_meeting_reports_count': self.context.get('serving_meeting_number'),\n }\n return payload\n\n\nclass GroupManagerListSerializer(serializers.ModelSerializer):\n person = UserNameWithLinkSerializer(read_only=True, required=False)\n group = HomeGroupNameSerializer(read_only=True, required=False)\n\n class Meta:\n model = GroupsManager\n fields = ('id', 'person', 'group')\n\n\nclass GroupManagerDetailSerializer(serializers.ModelSerializer):\n person = UserSingleSerializer(read_only=True, required=False)\n group = HomeGroupSerializer(read_only=True, required=False)\n\n class Meta:\n model = GroupsManager\n fields = ('id', 'person', 'group')\n\n\nclass GroupManagerWriteSerializer(serializers.ModelSerializer):\n class Meta:\n model = GroupsManager\n fields = ('id', 'person', 'group')\n","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":7335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"205157375","text":"from ...core import Entity, Structure, Comment\nimport re\n\ndef process_entity(entity, subs):\n for code in entity._value.keys():\n entity._value[code] = re.sub('\\&([^$]+)\\;',\n lambda m:subs[m.group(1)],\n entity._value[code])\n\ndef process(self):\n if not self.params.has_key('exents') or \\\n not self.params['exents']:\n return\n for elem in self:\n if isinstance(elem, Entity):\n process_entity(elem, self.params['exents'])\n\nclass DTDStructure(Structure):\n def __init__(self, id=None):\n self.process_cb = process\n Structure.__init__(self)\n","sub_path":"vendor-local/lib/python/silme/format/dtd/structure.py","file_name":"structure.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"260773987","text":"import attr\nimport copy\nfrom typing import List\n\nfrom game_state import GameState\nfrom player import Player\nfrom resources import Resources\nfrom unit import Unit\nfrom unit_kind import UnitKind\n\n@attr.s\nclass OtherPlayer:\n name: str = attr.ib()\n units: List[Unit] = attr.ib()\n build_order: List[List[UnitKind]] = attr.ib()\n alive: bool = attr.ib()\n\n @staticmethod\n def of_player(player: Player) -> 'OtherPlayer':\n return OtherPlayer(name=player.name, units=player.units[:], build_order=player.build_order[:], alive=player.alive)\n\n@attr.s\nclass GameView:\n view_player: Player = attr.ib()\n other_players: List[OtherPlayer] = attr.ib()\n turn: int = attr.ib()\n # Reading productions is technically cheating, but we allow it because it\n # makes the AI simpler.\n productions: List[Resources] = attr.ib()\n\n # Returns a player's view of the game state (all the information they can\n # see). Modifying this view should not affect the original game state in\n # any way.\n @staticmethod\n def of_gamestate(game: GameState, player_index: int) -> 'GameView':\n return GameView(view_player=game.players[player_index].clone(),\n other_players=[OtherPlayer.of_player(p) for i, p in enumerate(game.players) if i != player_index],\n turn=game.turn,\n productions=[p.production for i, p in enumerate(game.players) if i != player_index])\n\n def to_gamestate(self, resources: List[Resources]) -> GameState:\n return GameState(players=[self.view_player] + [\n Player(\n p.name,\n p.units,\n resources[i],\n self.productions[i],\n alive=p.alive\n )\n for i, p in enumerate(self.other_players)\n ], turn=self.turn)\n","sub_path":"units_py/game_view.py","file_name":"game_view.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"559060941","text":"#coding: utf-8\nfrom libs.github import *\nfrom settings import GITHUB_TOKEN\n\n\ngh = GitHub(GITHUB_TOKEN)\n# /repos/:owner/:repo branch is master default\n# /repos/:owner/:repo/contributors\nrepo = gh.repos('angular')('angular').get()\nrepo_attr = [repo.watchers_count, repo.stargazers_count, repo.forks_count, repo.open_issues_count]\nrepo_ctb = gh.repos('angular')('angular').contributors().get()\nrepo_ctb_count = len(repo_ctb)\n# /repos/:owner/:repo/languages 返回各个语言所占的行数 是个字典\nrepo_lang = gh.repos('angular')('angular').languages().get()\n# GET /repos/:owner/:repo/branches\nrepos_branchs = gh.repos('angular')('angular').branches().get()\n\n# GET /repos/:owner/:repo/stats/commit_activity 去年一年的每周每天的commit提交量\n# {'days': [0, 0, 0, 0, 0, 0, 0], 'total': 0, 'week': 1418515200}] 类似这样的数据\nrepo_ca = gh.repos('angular')('angular').stats().commit_activity().get()\n\n\n# GET /repos/:owner/:repo/events\n# repo的最近活动情况 动态\n\n# repos/:owner/:repo/commits\nrepo_commits = gh.repos('angular')('angular').commits().get(sha='master')\n# ==================================\n# reddit # 这个里面得到的信息得到的 subscribers是订阅人的个数\n# http://www.reddit.com/r/redis/about.json\n# http://www.reddit.com/r/redis/top.json http://www.reddit.com/r/redis/new.json\n\n# stackoverflow\n# 获得几个tag的统计情况 items里面有个数\n# http://api.stackexchange.com/2.2/tags/redis;python/info?order=desc&sort=popular&site=stackoverflow\n# 最好的几个问题 经常被问到的一些问题 这个的参数还是分开写吧。 不能redis;python这样来写\n# http://api.stackexchange.com/2.2/tags/redis/faq?site=stackoverflow","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"288135320","text":"# -*- coding: utf-8 -*-\n\nfrom flask import views, Blueprint, render_template\n\nfrom toogle.extensions import es_get_source, es_mget_source\n\nbp = Blueprint('user', __name__, url_prefix='/user')\n\n\nclass UserView(views.MethodView):\n \"\"\"\n 单个用户的个人信息页面\n \"\"\"\n template = 'individual.html'\n\n def get(self, id):\n user = es_get_source(id)\n followers = []\n friends = []\n if user:\n user_followers_ids = user.get('followers')\n user_friends_ids = user.get('friends')\n if user_followers_ids:\n followers = es_mget_source(user_followers_ids)\n if user_friends_ids:\n friends = es_mget_source(user_friends_ids)\n\n return render_template(self.template, user=user,\n followers=followers, friends=friends,\n id=id)\n\n\nclass UserFollowersView(views.MethodView):\n \"\"\"\n 单个用户与粉丝的关联延伸\n \"\"\"\n\n template = 'individual_followers.html'\n\n def get(self, id):\n return render_template(self.template, id=id)\n\n\nclass UserFriendsView(views.MethodView):\n \"\"\"\n 单个用户与好友的关联延伸\n \"\"\"\n\n template = 'individual_friends.html'\n\n def get(self, id):\n return render_template(self.template, id=id)\n\n\nbp.add_url_rule('//', view_func=UserView.as_view('detail'))\nbp.add_url_rule('//followers/', view_func=UserFollowersView.as_view('followers'))\nbp.add_url_rule('//friends/', view_func=UserFriendsView.as_view('friends'))\n","sub_path":"toogle/toogle/views/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"206695047","text":"# timer module using datetime\r\n\r\nimport datetime\r\n\r\nstartTime = None\r\nendTime = None\r\nelapsed = []\r\ntime = \"time elapsed: None\"\r\n\r\ndef formatTime(timeVar):\r\n timestr = str(timeVar)\r\n timeList = []\r\n timeList.append(int(timestr[:4]))\r\n timeList.append(int(timeVar.strftime(\"%j\")))\r\n timeList.append(int(timestr[11:13]))\r\n timeList.append(int(timestr[14:16]))\r\n timeList.append(float(timestr[17:]))\r\n return timeList\r\n\r\ndef timeDiff(start, end):\r\n times = {\r\n 0:0,\r\n 1:365,\r\n 2:24,\r\n 3:60,\r\n 4:60\r\n }\r\n diff = []\r\n for i in range(len(start)):\r\n diff.append(end[i] - start[i])\r\n for i in range(len(diff)-1,-1,-1):\r\n if diff[i] < 0:\r\n diff[i] += times[i]\r\n diff[i-1] = diff[i-1] - 1\r\n if i == 1 and start[0]%4 == 0:\r\n diff[i] += 1\r\n return diff\r\n\r\ndef startTimer():\r\n global startTime, endTime\r\n startTime = datetime.datetime.now()\r\n endTime = None\r\n\r\ndef endTimer():\r\n global startTime, endTime, elapsed, time\r\n endTime = datetime.datetime.now()\r\n time = \"time elapsed: \"\r\n if type(startTime) == None: startTime = endTime\r\n elapsed = timeDiff(formatTime(startTime),formatTime(endTime))\r\n times = {\r\n 0:\" year\",\r\n 1:\" day\",\r\n 2:\" hour\",\r\n 3:\" minute\",\r\n 4:\" second\"\r\n }\r\n for i in range(len(elapsed)):\r\n if elapsed[i] == 0: continue\r\n time += str(elapsed[i]) + times[i]\r\n if elapsed[i] != 1: time+=\"s \"\r\n else: time+=\" \"\r\n\r\n\r\ndef printTime():\r\n global time\r\n print(time)\r\n\r\n","sub_path":"Python/Problems 51-100/Timer.py","file_name":"Timer.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"254503117","text":"#!/usr/bin/env python\n\nfrom itertools import count\n\ncoins = (200, 100, 50, 20, 10, 5, 2, 1)\ntotal = 200\n\n\ndef pos(l, amount):\n if len(l) == 1:\n return 1\n\n c = l[0]\n ways = 0\n i = 0\n while (i * c) <= amount:\n if (i * c) < amount:\n ways += pos(l[1:], amount - (i * c))\n else:\n ways += 1\n i += 1\n\n return ways\n\n\nprint(pos(coins, total))\n","sub_path":"31.py","file_name":"31.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"331501954","text":"import json, pickle\n\nfrom django.contrib import messages\nfrom django.shortcuts import render, HttpResponse\nfrom django.http import JsonResponse\n\nfrom steam import steam_api, search_sort_utils, utils, bst\n\n\n# Redirects to the index.html page\ndef index(request, reverse=False, key='appid', checked_button='binary'):\n # render index page with the necessary values\n return render(request, 'index.html', {\n 'reverse': reverse,\n 'filter_key': key,\n 'checked_button': checked_button\n })\n\n# This is an async task in which the api's will be called\ndef fetch_steam_data_ajax(request, filter_key, sort_type, reversed):\n print(f'Key: {filter_key}')\n\n # Gather apps from API\n apps = steam_api.fetch_all_apps_steamspy()\n\n # sets the filter_key if none is set (usually on first load)\n if filter_key not in steam_api.getKeys():\n print('Filterkey is none')\n filter_key = 'appid'\n\n # Check which sort type is selected on the main screen\n if sort_type == 'merge':\n sorted_apps = search_sort_utils.merge_recursive(apps, key=filter_key)\n elif sort_type == 'insertion':\n sorted_apps = search_sort_utils.insertionsort(apps, key=filter_key)\n else:\n tree = bst.createbst(apps, filter_key)\n sorted_apps = tree.collapse()\n\n # Gets the owners dictionary (to know in which percentage the game is)\n # This data will be used in the index.html Javascript\n owners_apps = steam_api.get_data(sorted_apps, 'owners', force_int=False)\n owners_scaled, frac_labels = utils.get_scaled_data(owners_apps)\n\n # Get all the keys in which you can filter on\n keys = steam_api.getKeys()\n\n # group all the values\n context = {\n 'apps': sorted_apps,\n 'reverse': reversed,\n 'keys': keys,\n 'fraction_labels': frac_labels\n }\n\n # create json data and send that to the index.html. This will be retrieved in the JS - Ajax portion\n data = json.dumps(context)\n return HttpResponse(data, content_type='application/json')\n\n# Render the details page\ndef app_details(request, appid):\n return render(request, 'details.html', {\n 'appid': appid\n })\n\n# Async call in which the details of a page are retrieved\ndef fetch_details_ajax(request, appid):\n\n # gatehr details from api. Both Steam and SteamSpy API's are used\n details = steam_api.fetch_details(appid)\n details_ss = steam_api.fetch_details_steamspy(appid)\n\n # check if the details returned are actually completen. The key 'success' will be False if this is the case\n success = utils.isValidDetails(details, appid)\n if not success:\n messages.info(request, f'Game id {appid} does not have any details :(')\n\n # group together\n context = {\n 'details': details,\n 'details_ss': details_ss,\n 'success': success\n }\n\n # Create json and then to the details page\n data = json.dumps(context)\n return HttpResponse(data, content_type='application/json')\n\n# Logic that runs when you filter on the index page\ndef filterTags(request):\n # get the key (which you want to filter on) from the page with the GET method\n key = request.GET.get('key')\n # Get reverse value (true of false)\n reverse = request.GET.get('reverse_list')\n # Get the sorting style from the index page\n radio_sort = request.GET.get('radio_sort')\n # render index page with the new values\n return index(request, reverse=reverse, key=key, checked_button=radio_sort)\n\n# Load stats template\ndef stats(request):\n return render(request, 'stats.html', {})\n\n# Async task that runs when generating the bar graph\ndef populate_prices(request):\n # init\n labels = []\n data = []\n\n # Gather all apps from API's and sort them\n sorted_apps = search_sort_utils.merge_recursive(steam_api.fetch_all_apps_steamspy(), key='appid')\n # Get prices from the apps since we are showing the prices in the graphs\n prices = steam_api.get_data(sorted_apps, 'price')\n prices_scaled, frac_labels = utils.get_scaled_data(prices)\n\n # add the prices (in dollars. They are retrieved from the API in cents)\n for k, v in prices_scaled.items():\n labels.append('${:.2f}'.format(float(k) / 100))\n data.append(v)\n\n # return values in JSON to the stats html\n return JsonResponse(data={\n 'labels': labels,\n 'data': data,\n })\n\n# Async task that runs when generating the ownerd pychart\ndef games_sequence(request):\n # init\n labels = []\n data = []\n # Gather all apps from API's and sort them\n sorted_apps = search_sort_utils.merge_recursive(steam_api.fetch_all_apps_steamspy(), key='appid')\n # get all appids and amount of games\n appids = steam_api.get_data(sorted_apps, 'appid')\n appidsScaled, frac_labels = utils.get_scaled_data(appids)\n\n # fill lists with values\n for k, v in appidsScaled.items():\n labels.append(k)\n data.append(k)\n\n # return to charts\n return JsonResponse(data={\n 'labels': labels,\n 'data': data,\n })\n\ndef populate_owners(request):\n labels = []\n data = []\n sorted_apps = search_sort_utils.merge_recursive(steam_api.fetch_all_apps_steamspy(), key='appid')\n owners = steam_api.get_data(sorted_apps, 'owners', force_int=False)\n owners_scaled, frac_labels = utils.get_scaled_data(owners)\n\n\n\n for k, v in owners_scaled.items():\n labels.append(k)\n data.append(v)\n\n return JsonResponse(data={\n 'labels': labels,\n 'data': data,\n })\n\ndef boxplot_stats(request, type):\n # get all apps and sort them\n sorted_apps = search_sort_utils.merge_recursive(steam_api.fetch_all_apps_steamspy(), key='appid')\n\n # gather all the stats from the function\n stats_all = search_sort_utils.stats(sorted_apps, type, force_int=True)\n\n return JsonResponse(data={\n 'stats': stats_all,\n 'chart_type': type\n })\n\n# render the top 100 apps page\ndef top100(request):\n return render(request, 'topApps.html', {})\n\n# get top 100 games and return to view\ndef fetch_top100(request):\n top100 = steam_api.get_top_100()\n owners_apps = steam_api.get_data(top100, 'owners', force_int=False)\n owners_scaled, frac_labels = utils.get_scaled_data(owners_apps)\n\n # set all in a dict\n context = {\n 'apps': top100,\n 'fraction_labels': frac_labels\n }\n\n # convert to json\n data = json.dumps(context)\n # return the json to the view\n return HttpResponse(data, content_type='application/json')\n\n# def fetch_binary_search_tree(request, filter_key, reversed):\n#\n# # gather all apps\n# apps = steam_api.fetch_all_apps_steamspy()\n# # retrieve tree from all apps\n# tree = bst.createbst(apps, filter_key)\n# # collapse the tree into a list with all nodes (apps)\n# result = tree.collapse()\n#\n# # group all values together\n# context = {\n# 'apps': result,\n# 'keys': {\n# 'appid',\n# 'name'\n# },\n# 'filter_key': filter_key,\n# 'reversed': reversed,\n#\n# }\n# # generate JSON and return\n# data = json.dumps(context, default=serialize_sets)\n# return HttpResponse(data, content_type='application/json')\n#\n# # This is used to serialize the json. Otherwise it will cause an exception\n# def serialize_sets(obj):\n# if isinstance(obj, set):\n# return list(obj)\n#\n# return obj\n","sub_path":"steam/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"215383972","text":"import pytest\n\nfrom datetime import datetime\nfrom storagehub import FileVersion\n\n\n@pytest.mark.parametrize(\"creation_date, identifier, checksum, content_type, additional_info\", [\n (datetime(2018, 6, 2), 'TEST_ID', 'TEST_CHECKSUM', 'TEST_TYPE', {'TEST_KEY_1': 'TEST_INFO_1',\n 'TEST_KEY_2': 'TEST_INFO_2'}),\n])\ndef test_getters(creation_date, identifier, checksum, content_type, additional_info):\n file_version = FileVersion(creation_date, identifier, checksum, content_type, additional_info)\n assert file_version.creation_date == creation_date\n assert file_version.identifier == identifier\n assert file_version.checksum == checksum\n assert file_version.content_type == content_type\n assert file_version.additional_info == additional_info\n\n\n@pytest.mark.parametrize(\"creation_date, identifier, checksum, content_type, additional_info\", [\n (datetime(2018, 6, 2), 'TEST_ID', 'TEST_CHECKSUM', 'TEST_TYPE', {'TEST_KEY_1': 'TEST_INFO_1',\n 'TEST_KEY_2': 'TEST_INFO_2'}),\n])\ndef test_setters(creation_date, identifier, checksum, content_type, additional_info):\n file_version = FileVersion(creation_date, identifier, checksum, content_type, additional_info)\n with pytest.raises(AttributeError):\n file_version.creation_date = datetime(2000, 1, 1)\n with pytest.raises(AttributeError):\n file_version.identifier = 'NEW_TEST_ID'\n with pytest.raises(AttributeError):\n file_version.checksum = 'NEW_TEST_CHECKSUM'\n with pytest.raises(AttributeError):\n file_version.content_type = 'NEW_TEST_TYPE'\n with pytest.raises(AttributeError):\n file_version.additional_info = {'NEW_TEST_KEY_1': 'NEW_TEST_INFO_1'}\n\n\n@pytest.mark.parametrize(\"creation_date, identifier, checksum, content_type, additional_info\", [\n (datetime(2018, 6, 2), 'TEST_ID', 'TEST_CHECKSUM', 'TEST_TYPE', {'TEST_KEY_1': 'TEST_INFO_1',\n 'TEST_KEY_2': 'TEST_INFO_2'}),\n])\n@pytest.mark.parametrize(\"parameter_name, wrong_value\", [\n ('creation_date', None),\n ('identifier', None),\n ('checksum', None),\n ('content_type', None),\n ('additional_info', None),\n])\ndef test_failed_initializations(creation_date, identifier, checksum, content_type, additional_info,\n parameter_name, wrong_value):\n parameters = {'creation_date': creation_date, 'identifier': identifier, 'checksum': checksum,\n 'content_type': content_type, 'additional_info': additional_info, parameter_name: wrong_value}\n with pytest.raises(AssertionError):\n FileVersion(**parameters)\n","sub_path":"storagehub/tests/unitary/components/FileVersion.py","file_name":"FileVersion.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"86527729","text":"from abc import ABC, abstractmethod\n\n\nclass Animal(ABC):\n @abstractmethod\n def __init__(self, animal_type, size, character):\n self.animal_type = animal_type\n self.size = size\n self.character = character\n\n @property\n def ferocious(self):\n if self.size == \"中等\" and self.animal_type == \"食肉\" and self.character == \"凶猛\":\n return True\n return False\n\n\nclass Cat(Animal):\n voice = \"喵\"\n\n def __init__(self, name, animal_type, size, character):\n self.name = name\n super().__init__(animal_type, size, character)\n\n @property\n def is_pet(self):\n if not self.ferocious:\n return True\n else:\n return False\n\n\nclass Zoo(object):\n def __init__(self, name):\n self.name = name\n self.animals = []\n # def __set__(self, instance, value):\n # print(f'__set__{instance} {value}')\n # self.animals.append(value)\n\n def add_animal(self, animal):\n animal_name = animal.__class__.__name__\n\n if animal_name in self.animals:\n print(f\"Zoo already have {animal_name}\")\n return\n self.animals.append(animal_name)\n\n if not hasattr(self, animal_name):\n setattr(self, animal_name, animal)\n\n @property\n def animal(self):\n return self.animal\n\n\n# 实例化动物园\nz = Zoo('时间动物园')\n# 实例化一只猫,属性包括名字、类型、体型、性格\ncat1 = Cat('大花猫 1', '食肉', '小', '温顺')\nprint(cat1.is_pet)\n# 增加一只猫到动物园\nz.add_animal(cat1)\n# 动物园是否有猫这种动物\nhave_cat = getattr(z, 'Cat')\nz.add_animal(cat1)\nprint(bool(have_cat), have_cat.name)","sub_path":"week07/base_zoo.py","file_name":"base_zoo.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"20873090","text":"import xml.etree.ElementTree\nimport json\nimport datetime\nimport dateutil\nimport dateutil.tz\nimport httplib2\n\nclass File:\n @staticmethod\n def read(path): \n file = open(path, \"r\")\n text = file.read() \n file.close()\n return text\n\n @staticmethod\n def write(path, text): \n file = open(path, \"w\") \n file.write(text) \n file.close()\n\n @staticmethod\n def read_xml(path): \n return xml.etree.ElementTree.XML(File.read(path))\n\n @staticmethod\n def read_json(path): \n return json.loads(File.read(path))\n\n @staticmethod\n def write_json(path, obj): \n File.write(path, json.dumps(obj, indent=2, separators=(',', ': ')))\n \nclass DateTime:\n @staticmethod\n def parse_local_to_utc(local_str):\n local = datetime.datetime.strptime(local_str, \"%Y-%m-%dT%H:%M:%S\")\n\n # Tell the datetime object that it's in local time zone\n local = local.replace(tzinfo=dateutil.tz.tzlocal())\n\n # Convert time zone\n return local.astimezone(dateutil.tz.tzutc())\n\n @staticmethod\n def format_utc_to_local(utc):\n # Tell the datetime object that it's in UTC time zone since \n # datetime objects are 'naive' by default\n utc = utc.replace(tzinfo=dateutil.tz.tzutc()) \n\n # Convert time zone\n local_time = utc.astimezone(dateutil.tz.tzlocal())\n\n # Format string\n return local_time.strftime(\"%Y-%m-%dT%H:%M:%S\")\n\nclass Http:\n @staticmethod\n def get(url):\n http = httplib2.Http() \n return http.request(url, \"GET\")[1] \n","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"226925548","text":"# the robot can only move right and down, starting from upper left corner\n\nclass Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\nclass Solution:\n def __init__(self, N):\n self.paths = []\n self.N = N\n\n def isFree(self, x, y):\n point = Point(x, y)\n if point in self.paths:\n return False\n return True\n\n def getPaths(self, x, y):\n point = Point(x, y)\n self.paths.append(point)\n if x == N-1 and y == N-1:\n return True\n success = False\n if x < N-1 and y <= N-1 and self.isFree(x+1, y):\n success = self.getPaths(x+1, y)\n \n\n","sub_path":"Recursion/robot_paths.py","file_name":"robot_paths.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"237693558","text":"\"\"\"\nThe Forecaster class is meant to fit regression models to the residuals\ncoming from evaluating predictive validity. We want to predict the residuals\nforward with respect to how much data is currently in the model and how far out into the future.\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport itertools\nfrom curvefit.utils import data_translator\n\n\nclass ResidualModel:\n def __init__(self, data, outcome, covariates):\n \"\"\"\n Base class for a residual model. Can fit and predict out.\n\n Args:\n data: (pd.DataFrame) data to use\n outcome: (str) outcome column name\n covariates: List[str] covariates to predict\n \"\"\"\n self.data = data\n self.outcome = outcome\n self.covariates = covariates\n\n assert type(self.outcome) == str\n assert type(self.covariates) == list\n\n self.coef = None\n\n def fit(self):\n pass\n\n def predict(self, df):\n pass\n\n\nclass LinearResidualModel(ResidualModel):\n def __init__(self, **kwargs):\n \"\"\"\n A basic linear regression for the residuals.\n\n Args:\n **kwargs: keyword arguments to ResidualModel base class\n \"\"\"\n super().__init__(**kwargs)\n\n def fit(self):\n df = self.data.copy()\n df['intercept'] = 1\n pred = np.asarray(df[['intercept'] + self.covariates])\n out = np.asarray(df[[self.outcome]])\n self.coef = np.linalg.inv(pred.T.dot(pred)).dot(pred.T).dot(out)\n\n def predict(self, df):\n df['intercept'] = 1\n pred = np.asarray(df[['intercept'] + self.covariates])\n return pred.dot(self.coef)\n\n\nclass Forecaster:\n def __init__(self):\n \"\"\"\n A Forecaster will generate forecasts of residuals to create\n new, potential future datasets that can then be fit by the ModelPipeline\n \"\"\"\n\n self.mean_residual_model = None\n self.std_residual_model = None\n\n def fit_residuals(self, residual_data, mean_col, std_col,\n residual_covariates, residual_model_type):\n \"\"\"\n Run a regression for the mean and standard deviation\n of the scaled residuals.\n\n Args:\n residual_data: (pd.DataFrame) data frame of residuals\n that has the columns listed in the covariate\n mean_col: (str) the name of the column that has mean\n of the residuals\n std_col: (str) the name of the column that has the std\n of the residuals\n residual_covariates: (str) the covariates to include in the regression\n residual_model_type: (str) what type of residual model to it\n types include 'linear'\n\n \"\"\"\n residual_data[f'log_{std_col}'] = np.log(residual_data[std_col])\n if residual_model_type == 'linear':\n self.mean_residual_model = LinearResidualModel(\n data=residual_data, outcome=mean_col, covariates=residual_covariates\n )\n self.std_residual_model = LinearResidualModel(\n data=residual_data, outcome=f'log_{std_col}', covariates=residual_covariates\n )\n else:\n raise ValueError(f\"Unknown residual model type {residual_model_type}.\")\n\n self.mean_residual_model.fit()\n self.std_residual_model.fit()\n\n def predict(self, far_out, num_data):\n \"\"\"\n Predict out the residuals for all combinations of far_out and num_data\n for both the mean residual and the standard deviation of the residuals.\n\n Args:\n far_out: (np.array) of how far out to predict\n num_data: (np.array) of numbers of data points\n\n Returns:\n\n \"\"\"\n data_dict = {'far_out': far_out, 'num_data': num_data}\n rows = itertools.product(*data_dict.values())\n new_data = pd.DataFrame.from_records(rows, columns=data_dict.keys())\n\n new_data['residual_mean'] = self.mean_residual_model.predict(df=new_data)\n new_data['log_residual_std'] = self.std_residual_model.predict(df=new_data)\n new_data['residual_std'] = np.exp(new_data['log_residual_std'])\n\n return new_data\n\n def simulate(self, mp, far_out, num_simulations, group, epsilon=1e-2, theta=1):\n \"\"\"\n Simulate the residuals based on the mean and standard deviation of predicting\n into the future.\n\n Args:\n mp: (curvefit.model_generator.ModelPipeline) model pipeline\n far_out: (int) how far out into the future to predict\n num_simulations: number of simulations\n group: (str) the group to make the simulations for\n epsilon: (epsilon) the floor for standard deviation moving out into the future\n theta: (theta) scaling of residuals to do relative to prediction magnitude\n\n Returns:\n List[pd.DataFrame] list of data frames for each simulation\n \"\"\"\n data = mp.all_data.loc[mp.all_data[mp.col_group] == group].copy()\n max_t = data[mp.col_t].max()\n num_obs = data.loc[~data[mp.col_obs_compare].isnull()][mp.col_group].count()\n\n num_out = np.array(range(far_out)) + 1\n forecast_times = max_t + num_out\n\n observations = np.asarray(data[mp.col_obs_compare])\n obs_times = np.asarray(data[mp.col_t])\n all_times = np.append(obs_times, forecast_times)\n\n mean_pred = mp.predict(\n times=forecast_times, predict_space=mp.predict_space, predict_group=group\n )\n residuals = self.predict(\n far_out=num_out,\n num_data=np.array([num_obs])\n )\n mean_residual = residuals['residual_mean'].values\n std_residual = residuals['residual_std'].apply(lambda x: max(x, epsilon)).values\n\n error = np.random.normal(\n loc=mean_residual, scale=std_residual, size=(num_simulations, far_out)\n )\n forecast_data = mean_pred - (mean_pred ** theta) * error\n simulated_flag = np.append(\n np.repeat(0, len(observations)),\n np.repeat(1, far_out)\n )\n cov_dict = {}\n for cov in mp.all_cov_names:\n covariate = data[cov].unique()\n assert len(covariate) == 1, f\"There is not a unique covariate value for {cov} group {group}\"\n cov_dict[cov] = covariate[0]\n\n dfs = []\n for i in range(num_simulations):\n new_observations = np.append(observations, forecast_data[i, :])\n # translate into new space with data translator\n fit_space_new_observations = data_translator(\n data=new_observations, input_space=mp.predict_space, output_space=mp.fun\n )\n df = pd.DataFrame({\n mp.col_t: all_times,\n mp.col_obs: fit_space_new_observations,\n mp.col_obs_compare: new_observations,\n mp.col_group: group,\n 'simulated': simulated_flag,\n 'intercept': 1\n })\n for k, v in cov_dict.items():\n df[k] = v\n if mp.obs_se_func is not None:\n df[mp.col_obs_se] = df[mp.col_t].apply(mp.obs_se_func)\n dfs.append(df)\n\n return dfs\n","sub_path":"src/curvefit/forecaster.py","file_name":"forecaster.py","file_ext":"py","file_size_in_byte":7231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"72152831","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/12/11 11:15\n# @Author : Junee\n# @FileName: x的平方根.py\n# @Software : PyCharm\n# Observing PEP 8 coding style\n\n# 递归法写二分查找没法返回值:原问题代码\n# def half_search(s, e,nums, target):\n# if s > e:\n# return -1\n# h = (s + e) // 2\n# print(s,h,e)\n# if nums[h] == target:\n# print(\"find!!!\")\n# return '返回值测试' # 这里的return都没有返回值,原因,这个是返回成下面条件语句里头的递归函数的返回值,\n# # 但是那个递归函数没有采用返回值,导致了这个返回值凭空蒸发了\n# elif nums[h] > target:\n# half_search(s + 1, h, nums,target)\n# print(\"左半边\")\n# return h # 这里头的h 永远是第一次的h,因为在迭代里面修改的h没有反映出来,应该加一个返回值\n# # 迭代里面的h是被修改了,但是我们这个return是在迭代子函数之外的,反应的总是最外层的h\n# elif nums[h] < target:\n# half_search(h + 1, e, nums,target)\n# print('右半边')\n# return h\n\n# 结论,应该要给递归子函数加一个返回值,用来反映到上层,才能对上层的参数进行更新\ndef half_search(s, e,nums, target):\n if s > e:\n return -1\n h = (s + e) // 2\n print(s,h,e)\n if nums[h] == target:\n print(\"find!!!\",h)\n return h\n elif nums[h] > target:\n h = half_search(s + 1, h, nums,target)\n print(\"左半边\")\n return h # 这里头的h 永远是第一次的h,因为在迭代里面修改的h没有反映出来,应该加一个返回值\n\n elif nums[h] < target:\n h = half_search(h + 1, e, nums,target)\n print('右半边')\n return h\n return h\n\nnums = [-1,0,3,5,9,12,13,14,15,16,17,18,19]\ntarget = 18\n# nums = [-1,0,3,5,9,12]\n# target = 2\ns, e = 0,len(nums)-1\nre = half_search(s,e,nums,target) # 写递归时,明明已经找到了解,却无法return,莫名其妙的错误\nprint(re)\n","sub_path":"递归算法中不返回值.py","file_name":"递归算法中不返回值.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"192238525","text":"# -*- coding: utf-8 -*-\n# Para utilizarla debes meter esta araña en un template de scrapy y definir un item sofosItem()\n# o modificar este código (realmente no es necesario usar ningún item).\n\nimport scrapy,re,json\nfrom tutorial_scrapy.items import sofosItems\n\nsuper = {}\n\nclass sofosSpider(scrapy.Spider):\n name = \"sofos\"\n allowed_domains = [\"sofosagora.net\"]\n start_urls = [\n \"http://sofosagora.net/rellano-f58/script-diccionarios-los-usuarios-t6163.html\"\n ] \n \n def parse(self, response):\n dicti = re.compile(r'(?P.*?):(?:
|\\s)*(?P.*?)(?:
|)*$')\n for autor in response.xpath('//b[@class=\"postauthor\"]'):\n item = sofosItems() \n item['autor'] = autor.xpath('text()').extract()\n for spoiler in autor.xpath('following::*[@class=\"postbody\"][1]//*[contains(@style,\"display: none\")]'):\n bloques = re.split('#',spoiler.extract())\n del bloques[0]\n for x in bloques:\n item['coleccion'] = dicti.match(x).groupdict()\n if item['coleccion']['definicion'] != \"\":\n item['coleccion']['definicion'] = item['coleccion']['definicion'].replace(\">\",\">\").replace(\"<\",\"<\").replace(\"&\",\"&\")\n super.setdefault(item['autor'][0], []).append(item['coleccion'])\n \n next_page = response.xpath('//td[@class=\"gensmall\"]//strong[1]/following-sibling::a[1]/@href')\n if next_page:\n url = response.urljoin(next_page[0].extract())\n return scrapy.Request(url, self.parse)\n \n with open(r'sofos_buba.json', 'wb') as outfile:\n json.dump(super, outfile)\n","sub_path":"sofos_spider.py","file_name":"sofos_spider.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"135369809","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don\"t forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport json\nimport codecs\nfrom twisted.enterprise import adbapi\n\nclass SpiderPipeline(object):\n def __init__(self):\n self.file = codecs.open(\"guokr.json\", \"w\", encoding=\"utf-8\")\n\n def process_item(self, item, spider):\n line = json.dumps(dict(item), ensure_ascii=False) + \"\\n\"\n self.file.write(line)\n return item\n\n def spider_closed(self, spider):\n self.file.close()\n\nclass MySQLStorePipeline(object):\n def __init__(self, dbpool):\n self.dbpool = dbpool\n\n @classmethod\n def from_settings(cls, settings):\n dbargs = dict(\n host = settings[\"MYSQL_HOST\"],\n db = settings[\"MYSQL_DBNAME\"],\n user = settings[\"MYSQL_USER\"],\n passwd = settings[\"MYSQL_PASSWD\"],\n charset = \"utf8\",\n use_unicode = True,\n )\n dbpool = adbapi.ConnectionPool(\"MySQLdb\", **dbargs)\n return cls(dbpool)\n\n def process_item(self, item, spider):\n d = self.dbpool.runInteraction(self._do_upsert, item, spider)\n d.addErrback(self._handle_error, item, spider)\n d.addBoth(lambda _: item)\n return d\n\n def _do_upsert(self, conn, item, spider):\n conn.execute(\"SELECT 1 FROM articles WHERE id = %s\", (item[\"id\"], ))\n\n ret = conn.fetchone()\n\n if ret:\n conn.execute(\n \"update articles set subject = %s, subject_url = %s, author = %s, author_url = %s, url = %s, title = %s, small_image = %s, summary = %s, content = %s, date_created = %s, date_published = %s, date_modified = %s, resource_url = %s where id = %s\",\n (item[\"subject\"][\"name\"], item[\"subject\"][\"url\"], item[\"author\"][\"nickname\"], item[\"author\"][\"url\"], item[\"url\"], item[\"title\"], item[\"small_image\"], item[\"summary\"], item[\"content\"], item[\"date_created\"], item[\"date_published\"], item[\"date_modified\"], item[\"resource_url\"], item[\"id\"])\n )\n spider.log(\"Item updated in db: %s\" % item[\"id\"])\n else:\n conn.execute(\n \"insert into articles(id, subject, subject_url, author, author_url, url, title, small_image, summary, content, date_created, date_published, date_modified, resource_url) values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\",\n (item[\"id\"], item[\"subject\"][\"name\"], item[\"subject\"][\"url\"], item[\"author\"][\"nickname\"], item[\"author\"][\"url\"], item[\"url\"], item[\"title\"], item[\"small_image\"], item[\"summary\"], item[\"content\"], item[\"date_created\"], item[\"date_published\"], item[\"date_modified\"], item[\"resource_url\"])\n )\n spider.log(\"Item stored in db: %s\" % item[\"id\"])\n\n def _handle_error(self, failue, item, spider):\n spider.log.err(failure)\n\n","sub_path":"spider/nutker/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"567107873","text":"import random\n\ndef busca_linear_com_sentinela(chave, lista):\n\tlista.append(chave)\n\tindex = 0\n\t\n\twhile lista[index] != chave:\n\t\tindex +=1\n \n\tif index == len(lista) - 1: #ou ao invés de -1 usar lista.pop(index)\n\t\treturn None\n\n\treturn index\t\t\n\t\t\nlista = []\nfor i in range(10):\n\ti = random.randint(0,100)\n\tlista.append(i)\n\nprint(lista)\nchave = input(\"Insira a chave a ser buscada: \")\nchave = int(chave)\n\nresultado = busca_linear(chave, lista)\n\nif resultado != None:\n\tprint(\"A chave {} foi encontrada a posição {}.\".format(chave, resultado))\t\nelse:\n\tprint(\"Valor não encontrado!\")","sub_path":"Python/Python3/busca_linear_com_sentinela.py","file_name":"busca_linear_com_sentinela.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"486460905","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\nimport networkx as nx\n\nfrom logdag import showdag\n\n\ndef search_gid(conf, gid):\n l_result = []\n for r in showdag.iter_results(conf):\n for edge in r.graph.edges():\n #g = nx.Graph(r.graph)\n #for edge in g.edges():\n temp_gids = [evdef.gid for evdef in r.edge_evdef(edge)]\n if gid in temp_gids:\n l_result.append((r, edge))\n return l_result\n\n","sub_path":"logdag/visual/edge_search.py","file_name":"edge_search.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"80555101","text":"import sys\nsys.setrecursionlimit(10**9)\n\nk=int(input())\n\ndef dfs(keta,num):\n global ans\n ans.append(int(''.join(num)))\n\n if keta==10:\n return\n\n min_n=max(0,int(num[-1])-1)\n max_n=min(9,int(num[-1])+1)\n for i in range(min_n,max_n+1):\n dfs(keta+1,num+[str(i)])\n\nans=[]\nfor i in range(1,10):\n dfs(1,[str(i)])\n\nans.sort()\nprint(ans[k-1])","sub_path":"Python_codes/p02720/s114954252.py","file_name":"s114954252.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"338681300","text":"import sys\nfrom setuptools import setup\n\ntry:\n import pypandoc\n readme = pypandoc.convert('README.md', 'rst')\n readme = readme.replace(\"\\r\", \"\")\nexcept ImportError:\n import io\n with io.open('README.md', encoding=\"utf-8\") as f:\n readme = f.read()\n\nsetup(name='modbus_logger',\n version=1.1,\n description='Read GPIO and run command hackrf '+\n 'and store in local database.',\n long_description=readme,\n url='https://github.com/GuillermoElectrico/Digital-Inputs-HackRF-Pi',\n download_url='',\n author='Guillermo Electrico',\n author_email='electrico@outlook.com',\n platforms='Raspberry Pi',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: GNU License v3',\n 'Operating System :: Raspbian',\n 'Programming Language :: Python :: 3.5'\n ],\n keywords='Digital Inputs HackRF Pi',\n install_requires=[]+(['setuptools', 'pyyaml', 'ez_setup', 'RPi.GPIO'] if \"linux\" in sys.platform else []),\n license='MIT',\n packages=[],\n include_package_data=True,\n tests_require=[],\n test_suite='',\n zip_safe=True)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"539778672","text":"N = int(input()) # 测试用例个数\nresult = [0 for i in range(N)]\n\nfor i in range(N):\n M = int(input()) # 当前用例的帧数\n all_zhen = {}\n bigest = 0\n\n for j in range(M):\n tmp = [int(a) for a in input().split()] \n cur_num = tmp[0] # 当前帧的特征运动个数\n \n if cur_num == 0:\n all_zhen = {}\n continue\n\n for k in range(1, cur_num, 2):\n key = (tmp[k], tmp[k+1])\n if key in all_zhen:\n all_zhen[key] += 1\n else:\n all_zhen[key] = 1\n bigest = max(bigest, all_zhen[key])\n result[i] = bigest\n\nfor i in range(N):\n print(result[i])\n \n ","sub_path":"interview/头条/b_0.py","file_name":"b_0.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"629054965","text":"\nimport psycopg2\nimport sys\n\nargs = sys.argv\ntry:\n conn = psycopg2.connect(\n host = \"127.0.0.1\",\n database = \"quicknhealthy\",\n user = \"postgres\",\n password = \"XXXXXXXXXX\",\n port = \"5432\"\n )\n\n print(\"Database successfully connected\")\n\nexcept:\n print(\"Connection to database failed\")\n\ncur = conn.cursor()\n\n#execute the query\n# splitting it up to make it more readable\ncommand = \"INSERT INTO Driver (EmployeeID, FirstName, LastName, StatusID) VALUES (\" \ncommand = command + args[1] + \", \\'\" + args[2] + \"\\', \\'\" \ncommand = command + args[3] + \"\\', \\'\" + args[4] + \"\\')\"\n\ncur.execute(command)\n\ncur.execute(\"SELECT * FROM Driver\")\n\nconn.commit()\n\n#close the connection\ncur.close()\nconn.close()","sub_path":"insertDriver.py","file_name":"insertDriver.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"478115775","text":"\"\"\"\nCONTROLLER File\n\"\"\"\nfrom system.core.controller import *\n\nclass Quotes(Controller):\n\tdef __init__(self, action):\n\t\tsuper(Quotes, self).__init__(action)\n\n\t\tself.load_model('Quote')\n\t\tself.load_model('User')\n\t\tself.db = self._app.db\n\n\n\n\n\tdef quotes(self):\n\t\tuser_id = session['id']\n\t\tquotes = self.models['Quote'].get_all_quotes()\n\t\tfavorites = self.models['Quote'].get_all_favorites(user_id)\n\t\talias = session['alias']\n\t\treturn self.load_view('quotes.html', alias=alias, quotes=quotes, favorites=favorites)\n\n\tdef add_quote(self):\n\t\tinfo = {\n\t\t'author':request.form['author'],\n\t\t'quote':request.form['quote'],\n\t\t'added_by':session['id']\n\t\t}\n\t\tquote_status = self.models['Quote'].add_quote_to_db(info)\n\t\tif quote_status['status'] == True:\n\t\t\treturn redirect('/quotes')\n\t\telse:\n\t\t\tfor message in quote_status['errors']:\n\t\t\t\tflash( message, 'quote_errors')\n\t\t\treturn redirect('/quotes')\n\n\tdef user(self, user_id):\n\t\tinfo = {\n\t\t'user_id': user_id\n\t\t}\n\t\tuser = self.models['Quote'].get_user_by_id(user_id)\n\t\tcount = self.models['Quote'].get_quote_count(user_id)\n\t\treturn self.load_view('user.html', user=user, count=count)\n\n\n\tdef add_to_favorites(self, quote_id):\n\t\tinfo = {\n\t\t'quote_id':quote_id,\n\t\t'user_id':session['id']\n\t\t}\n\n\t\tfavorites = self.models['Quote'].add_to_favorites(info)\n\t\treturn redirect('/quotes')\n\n\tdef remove_from_favorites_by_id(self, quote_id):\n\t\tuser_id = session['id']\n\t\tinfo = {\n\t\t'quote_id': quote_id,\n\t\t'user_id': user_id\n\t\t}\n\t\tself.models['Quote'].remove_from_favorites_by_id(info)\n\t\treturn redirect('/quotes')\n\n","sub_path":"pylot/exam_retake/app/controllers/Quotes.py","file_name":"Quotes.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"257502887","text":"import xml.etree.ElementTree as ET\n\n\ntree = ET.parse(\"mondial.xml\")\nroot = tree.getroot()\n\noutputSQL = open(\"insertStatements.sql\", \"w\")\n\n\n#INSERT INTO Country\n#With iter, all sub-nodes are examined\nfor country in root.iter(\"country\"):\n #pStr is the final statement that is executed for each country\n pStr = \"INSERT INTO Country VALUES(\"\n \n #country name\n #Without iter, it only looks at the immediate children nodes of country\n for name in country:\n #*.tag gives the tag name, *.text gives the content\n if name.tag == \"name\":\n pStr += \"'\" + name.text + \"'\"\n break;\n \n #country code\n #*.attrib is a dictonary (python's hash table) that stores ATTLIST\n pStr += \",\" + \"'\" + country.attrib[\"car_code\"] + \"'\"\n \n #capital and province\n try:\n for city in country.iter(\"city\"):\n if city.attrib[\"id\"] == country.attrib[\"capital\"]:\n pStr += \",\" + \"'\" + city[0].text + \"'\"\n #counting the number of province in a country so we can print\n #NULL if a country does not have any province\n provinceCount = 0\n for province in country.iter(\"province\"):\n provinceCount += 1\n #when it does, the province field is set to the province of the\n #capital\n if province.attrib[\"id\"] == city.attrib[\"province\"]:\n pStr += \",\" + \"'\" + province[0].text + \"'\"\n break;\n if provinceCount == 0:\n #has a capital, but no province\n pStr += \",\" + \"NULL\"\n break;\n except:\n #when there is no capital in a country, both are NULL\n pStr += \",NULL,NULL\"\n break;\n\n #area\n pStr += \",\" + country.attrib[\"area\"]\n\n #population\n #iter won't work here because country has many sub-nodes of \"population\"\n for pop in country:\n if pop.tag == \"population\":\n pStr += \",\" + pop.text + \");\\n\"\n\n outputSQL.write(pStr)\n\n#INSERT INTO City\nfor country in root.iter(\"country\"):\n #name\n for city in country: \n if city.tag == \"city\":\n pStr = \"INSERT INTO City VALUES(\"\n pStr += \"'\" + city[0].text + \"',\"\n \n #country\n pStr += \"'\" + city.attrib[\"country\"] + \"',\"\n\n #province\n pStr += \"NULL,\"\n \n #population\n hasPop = 0\n for pop in city:\n if pop.tag == \"population\":\n hasPop = 1\n pStr += pop.text + \",\" \n if hasPop == 0:\n pStr += \"NULL,\"\n \n #coordinates\n hasCoor = 0\n for co in city:\n if co.tag == \"longitude\":\n hasCoor = 1\n lo = co.text\n if co.tag == \"latitude\":\n pStr += \"(\" + lo + \", \" + co.text + \"));\\n\"\n if hasCoor == 0:\n pStr += \"NULL);\\n\"\n \n outputSQL.write(pStr)\n\n#INSERT INTO Province\nfor province in root.iter(\"province\"):\n for city in province:\n #INSERT INTO City (for countries with provinces)\n if city.tag == \"city\":\n pStr = \"INSERT INTO City VALUES(\"\n pStr += \"'\" + city[0].text + \"',\"\n \n #country\n pStr += \"'\" + city.attrib[\"country\"] + \"',\"\n\n #province\n pStr += \"'\" + province[0].text + \"',\"\n \n #population\n hasPop = 0\n for pop in city:\n if pop.tag == \"population\":\n hasPop = 1\n pStr += pop.text + \",\" \n if hasPop == 0:\n pStr += \"NULL,\"\n \n #coordinates\n hasCoor = 0\n for co in city:\n if co.tag == \"longitude\":\n hasCoor = 1\n lo = co.text\n if co.tag == \"latitude\":\n pStr += \"(\" + lo + \", \" + co.text + \"));\\n\"\n if hasCoor == 0:\n pStr += \"NULL);\\n\"\n \n outputSQL.write(pStr)\n \n pStr = \"INSERT INTO Province VALUES('\" + province[0].text + \"',\"\n pStr += \"'\" + province.attrib[\"country\"] + \"',\"\n hasPop = 0\n for pop in province:\n if pop.tag == \"population\":\n hasPop = 1\n pStr += pop.text + \",\"\n if hasPop == 0:\n pStr += \"NULL,\"\n hasArea = 0\n for area in province:\n if area.tag == \"area\":\n hasArea = 1\n pStr += area.text + \",\"\n if hasArea == 0:\n pStr += \"NULL,\"\n try:\n pStr += \"'\" + province.attrib[\"capital\"] + \"');\\n\"\n except:\n pStr += \"NULL);\\n\"\n outputSQL.write(pStr)\n \n#INSERT INTO Economy\nfor country in root.iter(\"country\"):\n pStr = \"INSERT INTO Economy VALUES('\" + country.attrib[\"car_code\"] + \"',\"\n hasGDP = 0\n for gdp_total in country:\n if gdp_total.tag == \"gdp_total\":\n hasGDP = 1\n pStr += \"'\" + gdp_total.text + \"',\"\n if hasGDP == 0:\n pStr += \"NULL,\"\n hasAgri = 0\n for gdp_agri in country:\n if gdp_agri.tag == \"gdp_agri\":\n hasAgri = 1\n pStr += \"'\" + gdp_agri.text + \"',\"\n if hasAgri == 0:\n pStr += \"NULL,\"\n hasInd = 0\n for gdp_ind in country:\n if gdp_ind.tag == \"gdp_ind\":\n hasInd = 1\n pStr += \"'\" + gdp_ind.text + \"',\"\n if hasInd == 0:\n pStr += \"NULL,\"\n hasServ = 0\n for gdp_serv in country:\n if gdp_serv.tag == \"gdp_serv\":\n hasServ = 1\n pStr += \"'\" + gdp_serv.text + \"',\"\n if hasServ == 0:\n pStr += \"NULL,\"\n hasInf = 0\n for inflation in country:\n if inflation.tag == \"inflation\":\n hasInf = 1\n pStr += \"'\" + inflation.text + \"');\\n\"\n if hasInf == 0:\n pStr += \"NULL);\\n\"\n\n outputSQL.write(pStr)\n\n#INSERT INTO Population\n#INSERT INTO Politics\n#INSERT INTO Language\n#INSERT INTO Religion\n#INSERT INTO EthnicGroup\n#INSERT INTO Continent\n#INSERT INTO borders\n#INSERT INTO encompasses\n#INSERT INTO Organization\n#INSERT INTO isMember\n#INSERT INTO Mountain\n#INSERT INTO Desert\n#INSERT INTO Island\n#INSERT INTO Lake\n#INSERT INTO Sea\n#INSERT INTO River\n#INSERT INTO geo_Mountain\n#INSERT INTO geo_Desert\n#INSERT INTO geo_Island\n#INSERT INTO geo_River\n#INSERT INTO geo_Sea\n#INSERT INTO geo_Lake\n#INSERT INTO geo_Source\n#INSERT INTO geo_Estuary\n#INSERT INTO geo_mergesWith\n#INSERT INTO located\n#INSERT INTO locatedOn\n#INSERT INTO islandIn\n#INSERT INTO MountainOnIsland\n\n\noutputSQL.close()\n","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":5815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"330070246","text":"#!/usr/bin/python3\n\nimport argparse\nimport logging\nimport os\nimport sys\n\nsys.path.append(os.path.dirname(__file__))\n\nfrom src import Deployer, Logger\n\n\ndef main():\n parser = argparse.ArgumentParser(prog='Creep',\n description='Perform incremental deployment from workspace to remote directory.')\n\n parser.add_argument('name', nargs='*', help='Deploy to specified named location (* = everywhere)')\n\n parser.add_argument('-a',\n '--append',\n action='append',\n default=[],\n help='Manually append file or directory to locations',\n metavar='PATH')\n\n parser.add_argument('-b',\n '--base',\n default='.',\n help='Use given path to workspace instead of current directory',\n metavar='DIR')\n\n parser.add_argument('-d',\n '--definition',\n default='.creep.def',\n help='Read definition configuration from specified file or JSON string',\n metavar='FILE/JSON')\n\n parser.add_argument('-e',\n '--environment',\n default='.creep.env',\n help='Read environment configuration from specified file or JSON string',\n metavar='FILE/JSON')\n\n parser.add_argument('-f',\n '--rev-from',\n help='Use given initial version instead of reading it from revision file',\n metavar='REV')\n\n parser.add_argument('-q',\n '--quiet',\n dest='level',\n action='store_const',\n const=logging.WARNING,\n default=logging.INFO,\n help='Quiet mode, don\\'t display anything but errors')\n\n parser.add_argument('-r',\n '--remove',\n action='append',\n default=[],\n help='Manually remove file or directory from locations',\n metavar='PATH')\n\n parser.add_argument('-t',\n '--rev-to',\n help='Use given target version instead of reading it from current workspace',\n metavar='REV')\n\n parser.add_argument('-v',\n '--verbose',\n dest='level',\n action='store_const',\n const=logging.DEBUG,\n default=logging.INFO,\n help='Verbose mode, display extra information')\n\n parser.add_argument('-y',\n '--yes',\n action='store_true',\n help='Skip every prompt and always assume \"yes\" answer instead')\n\n parser.add_argument('--extra-append', action='append', default=[], help=argparse.SUPPRESS)\n parser.add_argument('--extra-remove', action='append', default=[], help=argparse.SUPPRESS)\n\n args = parser.parse_args()\n logger = Logger.build(args.level)\n\n deployer = Deployer(logger, args.definition, args.environment, args.yes)\n\n append = args.append + args.extra_append\n remove = args.remove + args.extra_remove\n\n return not deployer.deploy(args.base, args.name, append, remove, args.rev_from, args.rev_to) and 1 or 0\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"creep/creep.py","file_name":"creep.py","file_ext":"py","file_size_in_byte":3555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"554378039","text":"nome = 'Caio'\nsobrenome_mae = 'Almeida'\nsobrenome_pai = 'Neves'\n\n#CONCATENAÇÃO\nfull_name = nome + ' ' + sobrenome_mae + ' ' + sobrenome_pai\nprint(full_name)\n\n# TAMANHO VARIAVEL\nprint(f'Para saber o tamanho da variável, utiliza-se a função \"len\" e o tamanho é: {len(full_name)}')\n","sub_path":"Python/PYHTON/Strings/UDMY1 - Strings.py","file_name":"UDMY1 - Strings.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"274002519","text":"import os, datetime, cStringIO, base64\n\nimport database\n\nimport logger\n\nfrom PIL import Image\n\nfrom utils import *\nfrom iputils import *\n\nBASE_DIR = os.path.dirname(__file__)\n\nMISS_LOOPY_DB = 'missloopy'\n\nAGE_MIN = 18\nAGE_MAX = 99\nHEIGHT_MIN = 120\nHEIGHT_MAX = 250\n\n# Columns in profiles\nCOL_ID = 0\nCOL_EMAIL = 1\nCOL_PASSWORD = 2\nCOL_CREATED_OLD = 3\nCOL_VERIFIED = 4\nCOL_LAST_LOGIN = 5\nCOL_NAME = 6\nCOL_GENDER = 7\nCOL_DOB = 8\nCOL_HEIGHT = 9\nCOL_WEIGHT = 10\nCOL_ETHNICITY = 11\nCOL_EDUCATION = 12\nCOL_STATUS = 13\nCOL_SMOKING = 14\nCOL_DRINKING = 15\nCOL_COUNTRY = 16\nCOL_REGION_OLD = 17\nCOL_PLACENAME_OLD = 18\nCOL_X = 19\nCOL_Y = 20\nCOL_TZ = 21\nCOL_OCCUPATION = 22\nCOL_SUMMARY = 23\nCOL_DESCRIPTION = 24\nCOL_LOOKING_FOR = 25\nCOL_GENDER_CHOICE = 26\nCOL_AGE_MIN = 27\nCOL_AGE_MAX = 28\nCOL_HEIGHT_MIN = 29\nCOL_HEIGHT_MAX = 30\nCOL_WEIGHT_CHOICE = 31\nCOL_ETHNICITY_CHOICE = 32\nCOL_LOCATION = 33\nCOL_LAST_IP = 34\nCOL_CREATED2 = 35\nCOL_LAST_IP_COUNTRY = 36\nCOL_NOTIFICATIONS = 37\n\n# Columns in photos\nCOL3_PID = 0\nCOL3_ID = 1\nCOL3_OFFSET = 2\nCOL3_MASTER = 3\n\n# Columns in emails\nCOL4_ID_FROM = 0\nCOL4_ID_TO = 1\nCOL4_MESSAGE = 2\nCOL4_SENT = 3\nCOL4_VIEWED = 4\nCOL4_IMAGE = 5\n\n# Columns in blocked\nCOL6_ID = 0\nCOL6_ID_BLOCK = 1\n\n# Columns in favorites\nCOL7_ID = 0\nCOL7_ID_FAVORITE = 1\n\n# Columns in results\nCOL5_ID = 0\nCOL5_ID_SEARCH = 1\nCOL5_ID_PREVIOUS = 2\nCOL5_ID_NEXT = 3\n\n# Gender enum\nGEN_MAN = 1<<0\nGEN_WOMAN = 1<<1\nGEN_SUGAR_PUP = 1<<2\nGEN_SUGAR_BABY = 1<<3\nGEN_SUGAR_DADDY = 1<<4\nGEN_SUGAR_MOMMA = 1<<5\n\n# Ethnicity enum\nETH_WHITE = 1<<0\nETH_BLACK = 1<<1\nETH_LATINO = 1<<2\nETH_ASIAN = 1<<3\nETH_MIXED = 1<<4\nETH_OTHER = 1<<5\nETH_INDIAN = 1<<6\n\n# Weight enum\nWGT_SLIM = 1<<0\nWGT_ATHLETIC = 1<<1\nWGT_AVERAGE = 1<<2\nWGT_EXTRA_POUNDS = 1<<3\nWGT_LARGE = 1<<4\n\n# Education enum\nEDU_SCHOOL = 1<<0\nEDU_HIGHER = 1<<1\nEDU_UNIVERSITY = 1<<2\n\n# Status enum\nSTA_SINGLE = 1<<0\nSTA_MARRIED = 1<<1\nSTA_COHABITATING = 1<<2\nSTA_WITH_FRIENDS = 1<<3\nSTA_WITH_FAMILY = 1<<4\nSTA_COMPLICATED = 1<<5\n\n# Smoking enum\nSMO_NEVER = 1<<0\nSMO_SOCIAL = 1<<1\nSMO_REGULAR = 1<<2\nSMO_HEAVY = 1<<3\n\n# Drinking enum\nDRI_NEVER = 1<<0\nDRI_SOCIAL = 1<<1\nDRI_REGULAR = 1<<2\nDRI_HEAVY = 1<<3\n\n# Notification enum\nNOT_NEW_MEMBERS = 1<<0\nNOT_NEW_MESSAGE = 1<<1\n\nPHOTOS_DIR = 'photos'\nMEMBERS_DIR = 'members'\nSCAMMERS_DIR = 'scammers'\n\ndb = database.Database(MISS_LOOPY_DB)\n\ndef Range(min,max):\n if min and max:\n return 'from %s to %s' % (str(min), str(max))\n if min:\n return 'at least %s' % (str(min))\n if max:\n return 'no more than %s' % (str(max))\n return None\n\ndef Gender(enum):\n if not enum:\n return None\n if enum&GEN_MAN:\n return 'Man'\n if enum&GEN_WOMAN:\n return 'Woman'\n if enum&GEN_SUGAR_PUP:\n return 'Sugar Pup'\n if enum&GEN_SUGAR_BABY:\n return 'Sugar Baby'\n if enum&GEN_SUGAR_DADDY:\n return 'Sugar Daddy'\n if enum&GEN_SUGAR_MOMMA:\n return 'Sugar Momma'\n return None\n\ndef GenderList(enum):\n if not enum:\n return None\n list = []\n if enum&GEN_MAN:\n list.append('Men')\n if enum&GEN_WOMAN:\n list.append('Women')\n if enum&GEN_SUGAR_PUP:\n list.append('Sugar Pups')\n if enum&GEN_SUGAR_BABY:\n list.append('Sugar Babies')\n if enum&GEN_SUGAR_DADDY:\n list.append('Sugar Daddies')\n if enum&GEN_SUGAR_MOMMA:\n list.append('Sugar Mommas')\n return ' or '.join(list)\n\ndef Ethnicity(enum):\n if not enum:\n return None\n if enumÐ_WHITE:\n return 'White'\n if enumÐ_BLACK:\n return 'Black'\n if enumÐ_LATINO:\n return 'Latino'\n if enumÐ_ASIAN:\n return 'Asian'\n if enumÐ_MIXED:\n return 'Mixed'\n if enumÐ_OTHER:\n return 'Other'\n return None\n\ndef EthnicityList(enum):\n if not enum:\n return None\n list = []\n if enumÐ_WHITE:\n list.append('White')\n if enumÐ_BLACK:\n list.append('Black')\n if enumÐ_LATINO:\n list.append('Latino')\n if enumÐ_ASIAN:\n list.append('Asian')\n if enumÐ_MIXED:\n list.append('Mixed')\n if enumÐ_OTHER:\n list.append('Other')\n return ' or '.join(list)\n\ndef Weight(enum):\n if not enum:\n return None\n if enum&WGT_SLIM:\n return 'Slim'\n if enum&WGT_ATHLETIC:\n return 'Athletic'\n if enum&WGT_AVERAGE:\n return 'Average'\n if enum&WGT_EXTRA_POUNDS:\n return 'A few extra pounds'\n if enum&WGT_LARGE:\n return 'Large'\n return None\n\ndef Education(enum):\n if not enum:\n return None\n if enum&EDU_SCHOOL:\n return 'School'\n if enum&EDU_HIGHER:\n return 'College'\n if enum&EDU_UNIVERSITY:\n return 'University'\n return None\n\ndef Status(enum):\n if not enum:\n return None\n if enum&STA_SINGLE:\n return 'Single'\n if enum&STA_MARRIED:\n return 'Married'\n if enum&STA_COHABITATING:\n return 'Cohabitating'\n if enum&STA_WITH_FRIENDS:\n return 'With friends'\n if enum&STA_WITH_FAMILY:\n return 'With family'\n if enum&STA_COMPLICATED:\n return 'It\\'s complicated'\n return None\n\ndef Smoking(enum):\n if not enum:\n return None\n if enum&SMO_NEVER:\n return 'Never'\n if enum&SMO_SOCIAL:\n return 'Social'\n if enum&SMO_REGULAR:\n return 'Regular'\n if enum&SMO_HEAVY:\n return 'Heavy'\n return None\n\ndef Drinking(enum):\n if not enum:\n return None\n if enum&DRI_NEVER:\n return 'Never'\n if enum&DRI_SOCIAL:\n return 'Social'\n if enum&DRI_REGULAR:\n return 'Regular'\n if enum&DRI_HEAVY:\n return 'Heavy'\n return None\n\ndef ImageData(filename):\n im = Image.open(filename)\n data = cStringIO.StringIO()\n im.save(data, 'JPEG')\n return 'data:image/jpg;base64,' + base64.b64encode(data.getvalue())\n\ndef ImageDimensions(filename):\n im = Image.open(filename)\n return im.size\n\ndef PhotoFilename(pid):\n if pid > 0:\n name = 'img%d' % (pid)\n else:\n name = 'dummy'\n return os.path.join(PHOTOS_DIR, name + '.jpg')\n\ndef MasterPhoto(id):\n db.execute('SELECT pid FROM photos WHERE id=%d AND master LIMIT 1' % (id))\n entry = db.fetchone()\n db.commit()\n if not entry:\n db.execute('SELECT pid FROM photos WHERE id=%d LIMIT 1' % (id))\n entry = db.fetchone()\n db.commit()\n if not entry:\n return 0\n return entry[0]\n\ndef Login(email,password):\n # Authenticate\n db.execute('SELECT * FROM profiles WHERE email ILIKE %s LIMIT 1' % (Quote(email)))\n entry = db.fetchone()\n db.commit()\n if not entry:\n return {'error': 'Email Address not found.'}\n if entry[COL_PASSWORD] != password:\n return {'error': 'Password does not match.'}\n if not entry[COL_VERIFIED]:\n return {'code': 1001}\n\n id = entry[COL_ID]\n\n return {'id': id}\n\ndef Authenticate(cookies=None,remote_addr=None):\n if not cookies:\n cookies = FetchCookies()\n if not cookies:\n return None\n\n if 'id' not in cookies:\n return None\n if 'email' not in cookies:\n return None\n if 'password' not in cookies:\n return None\n\n id = int(cookies['id'])\n email = cookies['email']\n password = cookies['password']\n\n # Authenticate\n db.execute('SELECT * FROM profiles WHERE id=%d AND email ILIKE %s AND password=%s LIMIT 1' % (id, Quote(email), Quote(password)))\n entry = db.fetchone()\n db.commit()\n if not entry:\n return None\n\n now = datetime.datetime.utcnow()\n db.execute('UPDATE profiles SET last_login=%s WHERE id=%d' % (Quote(str(now)), id))\n db.commit()\n if not remote_addr:\n remote_addr = FetchRemoteAddr()\n if remote_addr and entry[COL_LAST_IP] != remote_addr:\n db.execute('UPDATE profiles SET last_ip=%s,last_ip_country=%s WHERE id=%d' % (Quote(remote_addr), Quote(IpCountry(remote_addr)), id))\n db.commit()\n\n return entry\n\ndef Blocked(id,id_with):\n db.execute('SELECT COUNT(*) FROM blocked WHERE id=%d AND id_block=%d' % (id, id_with))\n entry = db.fetchone()\n db.commit()\n return (entry[0] > 0)\n\ndef BlockedMutually(id,id_with):\n db.execute('SELECT COUNT(*) FROM blocked WHERE (id=%d AND id_block=%d) OR (id=%d AND id_block=%d)' % (id, id_with, id_with, id))\n entry = db.fetchone()\n db.commit()\n return (entry[0] > 0)\n\ndef DeletePhoto(pid):\n # Remove photo file using pid\n db.execute('DELETE FROM photos WHERE pid=%d' % (pid))\n db.commit()\n filename = os.path.join(BASE_DIR, 'static', PhotoFilename(pid))\n try:\n os.remove(filename)\n except:\n logger.error('ERROR: os.remove(%s) failed!' % filename)\n\ndef DeletePhotos(pids):\n for pid in pids:\n DeletePhoto(pid)\n\ndef DeleteMember(id):\n db.execute('DELETE FROM profiles WHERE id=%d' % (id))\n db.execute('SELECT pid FROM photos WHERE id=%d' % (id))\n pids = [(entry[0]) for entry in db.fetchall()]\n DeletePhotos(pids)\n db.execute('DELETE FROM favorites WHERE id=%d OR id_favorite=%d' % (id, id))\n db.execute('DELETE FROM blocked WHERE id=%d OR id_block=%d' % (id, id))\n db.execute('DELETE FROM emails WHERE id_from=%d OR id_to=%d' % (id, id))\n db.execute('DELETE FROM results WHERE id=%d' % (id))\n #PurgeResults(id)\n db.commit()\n\ndef InboxCount(id):\n db.execute('SELECT COUNT(*) FROM emails WHERE id_to=%d AND not viewed AND id_from NOT IN (SELECT id_block FROM blocked WHERE id=id_to) AND id_to NOT IN (SELECT id_block FROM blocked WHERE id=id_from)' % (id))\n entry = db.fetchone()\n db.commit()\n return entry[0]\n\ndef OutboxCount(id):\n db.execute('SELECT COUNT(*) FROM emails WHERE id_from=%d AND not viewed AND id_from NOT IN (SELECT id_block FROM blocked WHERE id=id_to) AND id_to NOT IN (SELECT id_block FROM blocked WHERE id=id_from)' % (id))\n entry = db.fetchone()\n db.commit()\n return entry[0]\n\ndef SaveResults(id,results):\n db.execute('DELETE FROM results WHERE id=%d' % (id))\n for i in range(len(results)):\n id_previous = results[i-1] if i > 0 else 0\n id_search = results[i]\n id_next = results[i+1] if i < len(results)-1 else 0\n db.execute('INSERT INTO results (id, id_search, id_previous, id_next) VALUES (%d,%d,%d,%d)' % (id, id_search, id_previous, id_next))\n db.commit()\n\ndef PreviousResult(id,id_search):\n db.execute('SELECT id_previous FROM results WHERE id=%d AND id_search=%d LIMIT 1' % (id, id_search))\n entry = db.fetchone()\n db.commit()\n if not entry:\n return 0\n return entry[0]\n\ndef NextResult(id,id_search):\n db.execute('SELECT id_next FROM results WHERE id=%d AND id_search=%d LIMIT 1' % (id, id_search))\n entry = db.fetchone()\n db.commit()\n if not entry:\n return 0\n return entry[0]\n\ndef PurgeResults(id_search):\n db.execute('SELECT * FROM results WHERE id_search=%d' % (id_search))\n for entry in db.fetchall():\n id = entry[COL5_ID]\n id_previous = entry[COL5_ID_PREVIOUS]\n id_next = entry[COL5_ID_NEXT]\n if id_previous:\n db.execute('UPDATE results SET id_next=%d WHERE id=%d AND id_search=%d' % (id_next, id, id_previous))\n if id_next:\n db.execute('UPDATE results SET id_previous=%d WHERE id=%d AND id_search=%d' % (id_previous, id, id_next))\n db.commit()\n","sub_path":"mlutils.py","file_name":"mlutils.py","file_ext":"py","file_size_in_byte":11057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"650862009","text":"import pickle\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n#mpl.use('pdf')\nimport itertools\nimport numpy as np\nfrom datetime import datetime\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport os\nimport sys\nimport pandas as pd\n\nfrom utils.utilities import meter\nfrom utils import make_histos\nfrom utils.utilities import cartesian_converter\nfrom utils.utilities import make_model\nfrom utils import dataXZ\n\nfrom nflows.transforms.autoregressive import MaskedUMNNAutoregressiveTransform\nfrom nflows.flows.base import Flow\nfrom nflows.distributions.normal import StandardNormal\nfrom nflows.distributions.normal import DiagonalNormal\nfrom nflows.transforms.base import CompositeTransform\nfrom nflows.transforms.autoregressive import MaskedAffineAutoregressiveTransform\nfrom nflows.transforms.permutations import ReversePermutation\n\ndev = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n#dev = \"cpu\"\nprint(dev)\ndevice = torch.device(dev)\n\n#reonstruct an nflow model\n#model_path = \"models/\"\nmodel_path = \"models/Cond/3features/\"\n#model_name = \"TM_16_18_4_400_299_-12.37.pt\" #16 feature with Cond\n#model_name = \"TM_16_6_80_400_799_-26.48.pt\" #16 feature with Cond\n#model_name = \"TMUMNN_16_6_80_400_499_-28.70.pt\"\n#model_name = \"TM-UMNN_16_6_80_400_3999_-42.91.pt\"\nfeature_subset = \"all\" #All 16 features\n\n\n\n#model_name = \"TM_16_18_20_100_799_-15.19.pt\" #For initial double precision studies\n#model_name = \"TM_4_6_4_100_3199_-0.88.pt\" #4 features with QD, initial training\n\n#model_name = \"TM_16_16_32_400_4399_-14.42.pt\" #16 feature with QD\n#feature_subset = \"all\" #All 16 features\n\n#model_name = \"TM-Final_4_6_80_400_-1.97.pt\" #4 feature (electron) train, done 5/10 at 4 PM\n#feature_subset = [0,1,2,3] #Just electron features\n\n\n#This mechanism needs to be adjusted. It is hard coded. \n# A mechanism to read the feature subset from the trained model should be implemented\n#feature_subset = [4,5,6,7] #Just proton features\n\nprint(\" reading electron NF model \")\n#model_name = \"TM-Final-UMNN_elec_4_6_80_400_-9.76.pt\"\n#model_name = \"TM-Final-UMNN_elec_3_2_80_128_-6.75.pt\"\n#model_name = \"TM-Final-UMNN_elec_3_2_80_128_-6.62.pt\"\n#model_name = \"TM-Final-UMNN_elec_3_2_80_128_-9.88.pt\"\nmodel_name = \"TM-Final-UMNN_elec_3_6_80_128_-9.54.pt\"\nparams = model_name.split(\"_\")\nnum_features = int(params[2])\nnum_layers = int(params[3])\nnum_hidden_features = int(params[4])\ntraining_sample_size = int(params[5])\n\nif \"Final\" in model_name:\n epoch_num = 9999 #identify as final\n training_loss = float((params[6]).split(\".p\")[0])\nelse:\n epoch_num = int(params[5])\n training_loss = float((params[6]).split(\".p\")[0])\n\n\nprint(num_features,num_layers,num_hidden_features,training_sample_size,training_loss)\n\nflow_e, optimizer_e = make_model(num_layers,num_features,num_hidden_features,device)\nprint(\"number of params: \", sum(p.numel() for p in flow_e.parameters()))\nflow_e.load_state_dict(torch.load(model_path+model_name))\nflow_e.eval()\n\nprint(\" reading proton NF model \")\n\n#model_name = \"TM-Final-UMNN_prot_3_2_80_128_-9.13.pt\"\n#model_name = \"TM-Final-UMNN_prot_3_2_80_128_-9.13.pt\"\n#model_name = \"TM-Final-UMNN_prot_3_2_80_128_-7.38.pt\"\n#model_name = \"TM-Final-UMNN_prot_3_2_80_128_-9.74.pt\"\nmodel_name = \"TM-Final-UMNN_prot_3_6_80_128_-9.97.pt\"\nparams = model_name.split(\"_\")\nnum_features = int(params[2])\nnum_layers = int(params[3])\nnum_hidden_features = int(params[4])\ntraining_sample_size = int(params[5])\n\nif \"Final\" in model_name:\n epoch_num = 9999 #identify as final\n training_loss = float((params[6]).split(\".p\")[0])\nelse:\n epoch_num = int(params[5])\n training_loss = float((params[6]).split(\".p\")[0])\n\n\nprint(num_features,num_layers,num_hidden_features,training_sample_size,training_loss)\n\nflow_p, optimizer_p = make_model(num_layers,num_features,num_hidden_features,device)\nprint(\"number of params: \", sum(p.numel() for p in flow_p.parameters()))\nflow_p.load_state_dict(torch.load(model_path+model_name))\nflow_p.eval()\n\n\nprint(\" reading photon NF model \")\n\n\n#model_name = \"TM-Final-UMNN_phot_4_6_40_400_-10.24.pt\"\n#model_name = \"TM-Final-UMNN_phot_3_6_40_400_-3.96.pt\"\n#model_name = \"TM-Final-UMNN_phot_3_2_80_128_-5.87.pt\"\n#model_name = \"TM-Final-UMNN_phot_3_2_80_128_-5.53.pt\"\nmodel_name = \"TM-Final-UMNN_phot_3_2_80_128_-6.81.pt\"\nparams = model_name.split(\"_\")\nnum_features = int(params[2])\nnum_layers = int(params[3])\nnum_hidden_features = int(params[4])\ntraining_sample_size = int(params[5])\n\nif \"Final\" in model_name:\n epoch_num = 9999 #identify as final\n training_loss = float((params[6]).split(\".p\")[0])\nelse:\n epoch_num = int(params[5])\n training_loss = float((params[6]).split(\".p\")[0])\n\n\nprint(num_features,num_layers,num_hidden_features,training_sample_size,training_loss)\n\nflow_g, optimizer_g = make_model(num_layers,num_features,num_hidden_features,device)\n\nprint(\"number of params: \", sum(p.numel() for p in flow_g.parameters()))\nflow_g.load_state_dict(torch.load(model_path+model_name))\nflow_g.eval()\n\n\nprint (\" reading data\")\n#Initialize dataXZ object for quantile inverse transform\n#xb = dataXZ.dataXZ(feature_subset=feature_subset, file = \"data/pi0toepg.pkl\", mode = \"epg\")\nxb = dataXZ.dataXZ(feature_subset=feature_subset, file = \"data/train.pkl\", mode = \"epg\")\nxentire = xb.x.detach().numpy()\nbentire = xb.b.detach().numpy()\n#QuantTran = xb.qt\n\nprint (\" done with reading data\")\n\nmax_range = 10#Number of sets per loop\nsample_size = 200 #Number of samples per set\nmaxloops = len(xentire)//(max_range*sample_size) #Number of overall loops\n\nfor loop_num in range(maxloops):\n print(\"new loop \"+str(loop_num))\n xs = []\n bs = []\n gens = []\n start = datetime.now()\n start_time = start.strftime(\"%H:%M:%S\")\n print(\"Start Time =\", start_time)\n for i in range(1,max_range+1):\n print(\"On set {}\".format(i))\n \n #For nonconditional flows:\n #val_gen= flow.double().sample(sample_size).cpu().detach().numpy()\n \n #For conditional flows:\n #z = sampleDict[\"z\"]\n #x = sampleDict[\"x\"]\n b = bentire[sample_size*(max_range*loop_num+i-1):sample_size*(max_range*loop_num+i), :]\n x = xentire[sample_size*(max_range*loop_num+i-1):sample_size*(max_range*loop_num+i), :]\n bs.append(b)\n xs.append(x)\n #electron\n context_val_e = torch.tensor(b[:, [1,2,3]], dtype=torch.float32).to(device)\n val_gen_e = flow_e.sample(1,context=context_val_e).cpu().detach().numpy().reshape((sample_size,-1))\n E_gen_e = np.sqrt(val_gen_e[:, 0]**2 + val_gen_e[:, 1]**2 + val_gen_e[:, 2]**2 + (0.5109989461 * 0.001)**2).reshape((-1, 1))\n #proton\n context_val_p = torch.tensor(b[:, [5,6,7]], dtype=torch.float32).to(device)\n val_gen_p = flow_p.sample(1,context=context_val_p).cpu().detach().numpy().reshape((sample_size,-1))\n E_gen_p = np.sqrt(val_gen_p[:, 0]**2 + val_gen_p[:, 1]**2 + val_gen_p[:, 2]**2 + (0.938272081)**2).reshape((-1, 1))\n #photon\n context_val_g = torch.tensor(b[:, [9,10,11]], dtype=torch.float32).to(device)\n val_gen_g = flow_g.sample(1,context=context_val_g).cpu().detach().numpy().reshape((sample_size,-1))\n E_gen_g = np.sqrt(val_gen_g[:, 0]**2 + val_gen_g[:,1]**2 + val_gen_g[:, 2]**2).reshape((-1, 1))\n gens.append( np.hstack( (E_gen_e, val_gen_e, E_gen_p, val_gen_p, E_gen_g, val_gen_g)))\n now = datetime.now()\n elapsedTime = (now - start )\n print(\"Current time is {}\".format(now.strftime(\"%H:%M:%S\")))\n print(\"Elapsed time is {}\".format(elapsedTime))\n print(\"Total estimated run time is {}\".format(elapsedTime+elapsedTime/i*(max_range+1-i)))\n X = np.concatenate(xs)\n B = np.concatenate(bs)\n Gens = np.concatenate(gens)\n #z = QuantTran.inverse_transform(X)\n df_B = pd.DataFrame(B)\n df_B.to_pickle(\"gendata/Cond/3features/UMNN/B_UMNN_{}_{}_{}_{}_{}_dvcs_{}.pkl\".format(num_features,\n num_layers,num_hidden_features,training_sample_size,training_loss,loop_num))\n df_X = pd.DataFrame(X)\n df_X = df_B + df_X\n df_X.to_pickle(\"gendata/Cond/3features/UMNN/X_UMNN_{}_{}_{}_{}_{}_dvcs_{}.pkl\".format(num_features,\n num_layers,num_hidden_features,training_sample_size,training_loss,loop_num))\n df_Gens = pd.DataFrame(Gens)\n df_Gens = df_B + df_Gens\n df_Gens.to_pickle(\"gendata/Cond/3features/UMNN/GenData_UMNN_{}_{}_{}_{}_{}_dvcs_{}.pkl\".format(num_features,\n num_layers,num_hidden_features,training_sample_size,training_loss,loop_num))\n\nprint(\"done\")\nquit()\n","sub_path":"gen_NF_samples.py","file_name":"gen_NF_samples.py","file_ext":"py","file_size_in_byte":8496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"442680044","text":"\"\"\"Create tag table\n\nRevision ID: 738a04ab8395\nRevises: 98b2c43d2dbe\nCreate Date: 2018-05-12 04:51:35.079263\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '738a04ab8395'\ndown_revision = '98b2c43d2dbe'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.create_table(\n 'conduit_api_tag',\n sa.Column(\n 'id',\n sa.Integer,\n autoincrement=True,\n primary_key=True,\n unique=True,\n nullable=False\n ),\n sa.Column(\n 'body',\n sa.String(20),\n nullable=False\n )\n )\n\n\ndef downgrade():\n op.drop_table('conduit_api_tag')\n","sub_path":"src/models/migrations/versions/738a04ab8395_create_tag_table.py","file_name":"738a04ab8395_create_tag_table.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"353937886","text":"from detectron2.config import get_cfg\nfrom detectron2.engine import DefaultTrainer\n# import some common detectron2 utilities\nfrom detectron2 import model_zoo\nfrom detectron2.engine import DefaultPredictor\nfrom detectron2.config import get_cfg\nfrom detectron2.utils.visualizer import Visualizer\nfrom detectron2.data import MetadataCatalog\nfrom detectron2.structures import BitMasks, Boxes, BoxMode, Keypoints, PolygonMasks, RotatedBoxes\n\nimport os\nimport numpy as np\n#%matplotlib inline\n#from matplotlib import pyplot as plt\n#from MyDetector.Postprocess import postfilter\nfrom MyDetector import Postprocess\n\nclass MyDetectron2Detector(object):\n #args.showfig\n #args.modelname\n #args.modelbasefolder\n #args.modelfilename\n\n def __init__(self, args):\n self.args = args\n self.FULL_LABEL_CLASSES=args.FULL_LABEL_CLASSES\n use_cuda = True\n self.threshold = args.threshold if args.threshold is not None else 0.1\n# self.cfg = get_cfg()\n# self.cfg.merge_from_file(\"detectron2/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml\")\n# self.cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this model\n# self.cfg.MODEL.WEIGHTS = \"detectron2://COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/model_final_f10217.pkl\"\n# self.predictor = DefaultPredictor(self.cfg)\n \n self.cfg = get_cfg()\n self.cfg.merge_from_file(model_zoo.get_config_file(\"COCO-Detection/\"+self.args.modelname+\".yaml\" ))#faster_rcnn_X_101_32x8d_FPN_3x\n #self.cfg.merge_from_file(model_zoo.get_config_file(\"COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x.yaml\"))#faster_rcnn_X_101_32x8d_FPN_3x\n #cfg.merge_from_file('faster_rcnn_R_101_C4_3x.yaml')#Tridentnet\n #cfg.merge_from_file(model_zoo.get_config_file(\"COCO-Detection/retinanet_R_101_FPN_3x.yaml\"))\n #cfg.DATASETS.TRAIN = (\"myuav1_train\",)\n #cfg.DATASETS.TEST = (\"myuav1_val\",)\n self.cfg.DATALOADER.NUM_WORKERS = 1 #2\n #cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(\"COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x.yaml\") # Let training initialize from model zoo\n self.cfg.MODEL.WEIGHTS = os.path.join(self.args.modelbasefolder, self.args.modelfilename) #model_0159999.pth\n if os.path.isfile(self.cfg.MODEL.WEIGHTS) == False:\n self.cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(\"COCO-Detection/\"+self.args.modelname+\".yaml\") # Let training initialize from model zoo\n else:\n self.cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = 512#128 # faster, and good enough for this toy dataset (default: 512)\n self.cfg.MODEL.ROI_HEADS.NUM_CLASSES = len(self.FULL_LABEL_CLASSES) # Kitti has 9 classes (including donot care)\n #self.cfg.MODEL.WEIGHTS = os.path.join('/home/010796032/PytorchWork/output_uav', \"model_0119999.pth\") #model_0159999.pth\n #cfg.MODEL.WEIGHTS = os.path.join('/home/010796032/PytorchWork', \"fasterrcnn_x101_fpn_model_final_68b088.pkl\")#using the local downloaded model\n self.cfg.SOLVER.IMS_PER_BATCH = 2\n self.cfg.SOLVER.BASE_LR = 0.00025 # pick a good LRgkyjmh,\n self.cfg.SOLVER.MAX_ITER = 100000 # you may need to train longer for a practical dataset\n\n self.cfg.TEST.DETECTIONS_PER_IMAGE = 500\n \n self.predictor = DefaultPredictor(self.cfg)\n\n def bbox(self, img):\n rows = np.any(img, axis=1)\n cols = np.any(img, axis=0)\n rmin, rmax = np.where(rows)[0][[0, -1]]\n cmin, cmax = np.where(cols)[0][[0, -1]]\n return cmin, rmin, cmax, rmax\n\n def detect(self, im):\n outputs = self.predictor(im)\n #return outputs\n #print(outputs)\n \n #if (self.args.showfig):\n# plt.figure(figsize=(20,30))\n# v = Visualizer(im[:, :, ::-1],\n# metadata=uavval_metadata, \n# scale=0.8, )\n# v = v.draw_instance_predictions(outputs[\"instances\"].to(\"cpu\"))\n# #cv2_imshow(v.get_image()[:, :, ::-1])\n# plt.imshow(v.get_image()[:, :, ::-1])\n# plt.show()\n \n# predictions = outputs[\"instances\"].to(\"cpu\")\n# boxes = predictions.pred_boxes if predictions.has(\"pred_boxes\") else None\n# newboxes=_convert_boxes(boxes)\n #bbox_xcycwh=BoxMode.convert(newboxes, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS) #BoxMode.convert(x, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS)\n \n pred_boxes = outputs[\"instances\"].pred_boxes.tensor.cpu().numpy()\n pred_class = outputs[\"instances\"].pred_classes.cpu().numpy()\n pred_score = outputs[\"instances\"].scores.cpu().numpy()\n \n #bbox_xywh=BoxMode.convert(boxes, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS)\n #pred_class = [INSTANCE_CATEGORY_NAMES[i] for i in list(pred[0]['labels'].cpu().numpy())] # Get the Prediction Score\n pred_boxes = [[(i[0], i[1]), (i[2], i[3])] for i in list(pred_boxes)] # Bounding boxes\n #pred_score = list(pred[0]['scores'].detach().cpu().numpy())\n \n #Post filter based on threshold\n #pred_boxes, pred_class, pred_score = postfilter(pred_boxes, pred_class, pred_score, self.threshold)\n pred_boxes, pred_class, pred_score = Postprocess.postfilter_thresholdandsize(pred_boxes, pred_class, pred_score, self.threshold, minsize=1)\n \n #return pred_boxes, pred_class, pred_score\n return np.array(pred_boxes), np.array(pred_class), np.array(pred_score)\n\n\n# bbox_xcycwh, cls_conf, cls_ids = [], [], []\n\n# #box format is XYXY_ABS\n# for (box, _class, score) in zip(boxes, classes, scores):\n# #if _class == 0: # the orignal code only track people?\n# x0, y0, x1, y1 = box\n# bbox_xcycwh.append([(x1 + x0) / 2, (y1 + y0) / 2, (x1 - x0), (y1 - y0)]) # convert to x-center, y-center, width, height\n# cls_conf.append(score)\n# cls_ids.append(_class)\n\n# return np.array(bbox_xcycwh, dtype=np.float64), np.array(cls_conf), np.array(cls_ids)\n\n# def detectwithvisualization(self, im)\n# pred_boxes, classes, scores=self.detect(im)","sub_path":"MyDetector/Detectron2Detector.py","file_name":"Detectron2Detector.py","file_ext":"py","file_size_in_byte":6152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"344924629","text":"import os, sys\nif sys.version_info >= (3,0):\n from distribute_setup import use_setuptools\n use_setuptools()\nfrom setuptools import setup\nfrom setuptools.command.test import test\n\nlong_description = \"\"\"\nciss: code-centered single-file \"ISSUES.txt\" issue tracking\nPlatforms: Linux, Win32, OSX\nInterpreters: Python versions 2.4 through to 3.1, Jython 2.5.1.\n(c) Holger Krekel 2009\n\"\"\"\n#from ciss import __version__ as version\ndef main():\n setup(\n name='ciss',\n description='ciss: code-centered single \"ISSUES.txt\" issue tracking',\n long_description = long_description,\n version='0.2',\n url='http://codespeak.net/ciss',\n license='MIT license',\n platforms=['unix', 'linux', 'osx', 'cygwin', 'win32'],\n author='holger krekel',\n author_email='holger at merlinux.eu',\n cmdclass = {'test': PyTest},\n tests_require = ['py'],\n entry_points={'console_scripts': [\n 'ciss = ciss:main',\n ]},\n classifiers=['Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: POSIX',\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: MacOS :: MacOS X',\n 'Topic :: Utilities',\n 'Intended Audience :: Developers',\n 'Programming Language :: Python'],\n py_modules = ['ciss'],\n install_requires = ['py'],\n zip_safe=False,\n )\n\nclass PyTest(test):\n user_options = []\n def initialize_options(self):\n test.initialize_options(self)\n self.test_suite = \".\"\n def run_tests(self):\n import py\n py.cmdline.pytest(['.'])\n\nif __name__ == '__main__':\n main()\n","sub_path":"pypi_install_script/ciss-0.2.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"160590819","text":"from pprint import pprint\n\nimport urllib.request, json\ndef update():\n with urllib.request.urlopen(\"https://api.coinmarketcap.com/v2/ticker/?limit=100&sort=rank\") as url:\n data = json.loads(url.read().decode())\n\n \"\"\" Creating id-name pair by using API from coinmarketcap. \n \"\"\"\n\n name_USD_pair = {}\n\n with open('users.json') as json_file:\n users_data = json.load(json_file)\n for p in users_data['users']:\n coinId = p[\"coinId\"]\n coinAmount = p[\"coinAmount\"]\n USD = data[\"data\"][coinId][\"quotes\"][\"USD\"][\"price\"] * coinAmount\n name_USD_pair[p[\"name\"]] = USD;\n # print(USD)\n\n id_name_pair = {}\n for i in data[\"data\"]:\n # pprint(i)\n id_name_pair[data[\"data\"][i][\"name\"].lower()] = i\n\n userData = {}\n userData[\"users\"] = []\n typos = []\n with open('userList.csv') as csvfile:\n for row in csvfile:\n row1 = row.strip(\"\\n\").split(\",\")\n try:\n price = data[\"data\"][id_name_pair[row1[1].lower()]][\"quotes\"][\"USD\"][\"price\"]\n coinAmount = name_USD_pair[row1[0]] / price;\n # print(coinAmount)\n userData[\"users\"].append({\"coinAmount\": coinAmount,\n \"coinId\": id_name_pair[row1[1].lower()],\n \"name\": row1[0],\n \"buyPrice\": price})\n except Exception:\n typos.append(row1[0])\n # print(typos)\n with open('users.json') as json_file:\n users_data = json.load(json_file)\n for p in users_data['users']:\n if (p[\"name\"] in typos):\n userData[\"users\"].append({\"coinAmount\": p[\"coinAmount\"],\n \"coinId\": p[\"coinId\"],\n \"name\": p[\"name\"],\n \"buyPrice\": p[\"buyPrice\"]})\n\n with open('users.json', 'w+') as outfile:\n json.dump(userData, outfile)\n","sub_path":"updateUserJson.py","file_name":"updateUserJson.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"49624279","text":"# coding=utf-8\nimport json\nfrom flask.views import MethodView\nfrom flask import request\nimport os\nimport shutil\nimport time\nimport math\nfrom PIL import Image\nfrom boto3 import client\n\nclass Upload(MethodView):\n def getDictArray(self, post, name):\n dic = {}\n for k in post.keys():\n if k.startswith(name):\n rest = k[len(name):]\n\n # split the string into different components\n parts = [p[:-1] for p in rest.split('[')][1:]\n print (parts)\n id = int(parts[0])\n\n # add a new dictionary if it doesn't exist yet\n if id not in dic:\n dic[id] = {}\n\n # add the information to the dictionary\n dic[id][parts[1]] = post.get(k)\n return dic\n\n def extension(self, extension, type):\n if type == '':\n return extension\n elif type=='image/png':\n return '.png'\n elif type=='image/gif':\n return '.gif'\n elif type=='image/jpg':\n return '.jpg'\n\n return extension\n\n def get(self):\n return 'Hello KaBuM!'\n\n def resize_canvas(self, old_image_path, new_image_path, canvas_width=500, canvas_height=500):\n # curl -X POST \\\n # http://localhost/upload \\\n # -H 'cache-control: no-cache' \\\n # -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \\\n # -H 'postman-token: a8edf0e8-9836-c97f-9f28-1b70fa9f4460' \\\n # -F arquivo=@Rainbow.png \\\n # -F path=/produtos/fotos/1500/ \\\n # -F type=image/jpg \\\n # -F 'imagem[0][width]=500' \\\n # -F 'imagem[0][height]=500' \\\n # -F 'imagem[0][type]=jpg' \\\n # -F 'imagem[0][name]=g' \\\n # -F 'imagem[0][branco]=0'\n\n im = Image.open(old_image_path)\n old_width, old_height = im.size\n\n # Center the image\n x1 = int(math.floor((canvas_width - old_width) / 2))\n y1 = int(math.floor((canvas_height - old_height) / 2))\n\n mode = im.mode\n\n if len(mode) == 1: # L, 1\n new_background = (255)\n if len(mode) == 3: # RGB\n new_background = (255, 255, 255)\n if len(mode) == 4: # RGBA, CMYK\n new_background = (255, 255, 255, 255)\n\n newImage = Image.new(mode, (canvas_width, canvas_height), new_background)\n newImage.paste(im, (x1, y1, x1 + old_width, y1 + old_height))\n newImage.save(new_image_path)\n return 1\n\n def post(self, bucket_name):\n tmp_arquivo = ''\n tamanho = []\n if not 'path' in request.form:\n return \"Necessário enviar a variável 'path'\", 404\n else:\n path = request.form['path']\n if not os.path.exists(\"/tmp/\" + path):\n os.makedirs(\"/tmp/\" + path)\n\n file_extension = ''\n if(request.files):\n if (request.files['arquivo'].filename):\n file = request.files['arquivo'];\n file.save(os.path.join(\"/tmp/\", file.filename))\n tmp_arquivo = \"/tmp/\" + file.filename\n filename, file_extension = os.path.splitext('/tmp/' + file.filename)\n\n if(tmp_arquivo):\n im = Image.open(tmp_arquivo)\n\n tamanho_width_original = im.size[0]\n tamanho_height_original = im.size[1]\n\n tamanho.append({\n \"quality\": 100,\n \"height\": {\"foto\": tamanho_height_original, \"branco\": 0},\n \"width\": {\"foto\": tamanho_width_original, \"branco\": 0},\n \"name\": \"original\" + file_extension,\n \"branco\": 0,\n \"path\": path,\n })\n\n images = self.getDictArray(request.form, 'imagem')\n\n for i in images:\n filename, file_extension = os.path.splitext('/tmp/' + file.filename)\n width_imagem = int(images[i]['height'])\n height_imagem = int(images[i]['width'])\n\n if(tamanho_width_original > tamanho_height_original):\n fator = tamanho_width_original / tamanho_height_original\n largura = width_imagem\n altura = int(largura / fator)\n elif(tamanho_height_original > tamanho_width_original):\n fator = tamanho_height_original / tamanho_width_original\n altura = height_imagem\n largura = int(altura / fator)\n else:\n altura = height_imagem\n largura = width_imagem\n\n if largura > tamanho_width_original:\n largura = tamanho_width_original\n\n if altura > tamanho_height_original:\n altura = tamanho_height_original\n\n branco = 0\n if 'branco' in images[i]:\n if images[i][\"branco\"]==1:\n branco = 1\n\n tamanho.append({\n \"height\": {\"foto\": altura, \"branco\": height_imagem},\n \"width\": {\"foto\": largura, \"branco\": width_imagem},\n \"quality\": 100,\n \"name\": str(i) + '_' + str(int(time.time())) + '_' + str(altura) + \"x\" + str(largura) + \"_\" +images[i]['name'] + file_extension,\n \"path\": path,\n \"branco\": branco\n })\n\n for valor in tamanho:\n size = valor[\"width\"][\"foto\"], valor[\"height\"][\"foto\"]\n\n im.thumbnail(size)\n im.save(\"/tmp\" + valor[\"path\"] + valor[\"name\"], quality=valor[\"quality\"])\n\n if valor[\"height\"][\"branco\"] > 0 and valor[\"width\"][\"branco\"] and valor[\"branco\"] == 1:\n self.resize_canvas(\"/tmp\" + valor[\"path\"] + valor[\"name\"], \"/tmp\" + valor[\"path\"] + valor[\"name\"], valor[\"width\"][\"branco\"], valor[\"height\"][\"branco\"]);\n\n valor['height'] = valor['height']['foto']\n valor['width'] = valor['width']['foto']\n valor['path_phisical'] = \"/tmp\" + valor[\"path\"] + valor[\"name\"]\n del (valor[\"quality\"])\n\n s3_client = client(\n service_name='s3',\n endpoint_url='http://fakes3:4567',\n region_name='',\n aws_access_key_id='',\n aws_secret_access_key=''\n )\n\n os.remove(\"/tmp/\" + file.filename)\n for valor in tamanho:\n s3_client.upload_file(valor[\"path_phisical\"], bucket_name, valor[\"path\"] + valor[\"name\"])\n\n valor[\"url\"] = \"http://fakes3:4567/\"\n valor[\"name\"] = valor[\"name\"]\n valor[\"uri\"] = valor[\"path\"]\n valor[\"name\"] = valor[\"name\"]\n del (valor[\"height\"])\n del (valor[\"width\"])\n del (valor[\"path\"])\n del (valor[\"path_phisical\"])\n del (valor[\"branco\"])\n\n else:\n return \"Necessário enviar o arquivo com a variável 'arquivo'\", 404\n\n return tamanho\n","sub_path":"bkp/python/upload-file/www/controller/Upload.py","file_name":"Upload.py","file_ext":"py","file_size_in_byte":7139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"331109611","text":"def fib(n):\n \"\"\"\n n是非负数,返回第n个斐波那契数\n \"\"\"\n if n == 0 or n == 1:\n return n\n else:\n return fib(n-1) + fib(n-2)\n\ndef fast_fib(n, memo={}):\n if n == 0 or n == 1:\n return 1\n try :\n return memo[n]\n except KeyError:\n result = fast_fib(n - 1, memo) + fast_fib(n - 2, memo)\n memo[n] = result\n return result\n\nprint(fast_fib(120))\n","sub_path":"IntroductionToComputationAndProgrammingUsingPython/chapter13/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"543013079","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 3 14:00:05 2021\n\n@author: user\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\n#from sklearn.preprocessing import LabelBinarizer\nimport cv2\nimport os\nimport threading\nfrom tensorflow.keras.preprocessing.image import load_img, img_to_array\nfrom tensorflow.keras.optimizers import Adam\nimport math\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom numba import cuda\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nbatch_size =32\nD_out = 50\n\n\nclass threadsafe_iter:\n \"\"\"Takes an iterator/generator and makes it thread-safe by\n serializing call to the `next` method of given iterator/generator.\n \"\"\"\n\n def __init__(self, it):\n self.it = it\n self.lock = threading.Lock()\n\n def __iter__(self):\n return self\n\n def __next__(self):\n with self.lock:\n return self.it.__next__()\n\n\ndef threadsafe_generator(f):\n \"\"\"A decorator that takes a generator function and makes it thread-safe.\n \"\"\"\n def g(*a, **kw):\n return threadsafe_iter(f(*a, **kw))\n return g\n\n\ndef MakeOneHot(Y, D_out):\n N = Y.shape[0]\n Z = np.zeros((N, D_out))\n Z[np.arange(N), Y] = 1\n return Z\n\n\nwith open('val.txt', 'r') as f:\n index_val = f.readlines()\n # state=np.random.get_state()\n np.random.shuffle(index_val)\n lable_list_val = [0]*len(index_val)\n k = 0\n Batch_val = []\n for line in index_val:\n img_lable = line.split()\n lable_list_val[k] = int(img_lable[1])\n img_val = load_img(img_lable[0])\n img_val = img_to_array(img_val)\n img_re = cv2.resize(img_val, (64, 64), interpolation=cv2.INTER_AREA)\n Batch_val.append(img_re)\n k += 1\n lable_list_val = np.array(lable_list_val)\n lable_list_val = MakeOneHot(lable_list_val, D_out)\n Batch_val = np.array(Batch_val)\n\n\n\n@threadsafe_generator\ndef batch_iter(path, batch_size=batch_size):\n f = open(path, 'r')\n index = f.readlines()\n while 1:\n # state=np.random.get_state()\n np.random.shuffle(index)\n cnt = 0\n Batch = []\n Y = []\n sample_num = batch_size\n data_num = len(index)\n for line in index:\n img_i = line.split()\n img = load_img(img_i[0])\n img = img_to_array(img)\n #img = cv2.imread(img_i[0])\n img_re = cv2.resize(img, (64, 64), interpolation=cv2.INTER_AREA)\n Batch.append(img_re)\n Y.append(int(img_i[1]))\n cnt += 1\n if cnt == sample_num:\n # print(sample_num)\n data_num = data_num - cnt\n if data_num < batch_size:\n sample_num = data_num\n cnt = 0\n lable = MakeOneHot(np.array(Y), D_out)\n #kk = np.array(Batch)\n yield (np.array(Batch), lable)\n Batch = []\n Y = []\n f.close()\n\n\npath = 'train.txt'\nbatch_iter(path)\nf = open(path, 'r')\nindex = f.readlines()\ndata_num = len(index)\n#sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))\nprint(tf.config.list_physical_devices('GPU'))\n\nclass MyModel(tf.keras.Model):\n\n def __init__(self):\n super(MyModel, self).__init__(name='MyModel', dynamic=Talse)\n self.conv1 = tf.keras.layers.Conv2D(filters=6, kernel_size=(5, 5), padding='valid',\n input_shape=(64, 64, 3), activation='relu')\n self.pool1 = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))\n self.conv2 = tf.keras.layers.Conv2D(filters=16, kernel_size=(5, 5),\n padding='valid', activation='relu')\n self.pool2 = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))\n self.flat = tf.keras.layers.Flatten()\n self.dense1 = tf.keras.layers.Dense(1000, activation=tf.nn.relu)\n self.dense2 = tf.keras.layers.Dense(200, activation=tf.nn.relu)\n self.dense3 = tf.keras.layers.Dense(50, activation=tf.nn.softmax)\n #self.dropout = tf.keras.layers.Dropout(0.5)\n\n def call(self, inputs): \n # 使用在 `__init__` 建構的 layers 物件,在這裡實作正向傳播\n x = self.conv1(inputs)\n x = self.pool1(x)\n x = self.conv2(x)\n x = self.pool1(x)\n x = self.flat(x)\n x = self.dense1(x)\n x = self.dense2(x)\n x = self.dense3(x)\n return x\n \n\n\nmodel = MyModel()\nadam = Adam(lr=0.0001)\nmodel.compile(optimizer=adam, loss='categorical_crossentropy',\n metrics=['accuracy'])\nsave_dir = './checkpoints'\n#model.fit(trainData, trainLabels, batch_size=500, epochs=20, verbose=1, shuffle=True)\ncheckpointer = ModelCheckpoint(os.path.join(save_dir, 'model_{epoch:03d}.hdf5'),\n verbose=1, save_weights_only=False)\nimport time \na1 = time.time()\nhistory = model.fit(batch_iter(path, batch_size=batch_size),\n steps_per_epoch=math.ceil(data_num/batch_size), epochs=20, validation_data=(Batch_val, lable_list_val),\n max_queue_size=4, verbose=1, workers=2, callbacks=[checkpointer])\na2 = time.time()\na = a2 -a1\n\nhist= history.history\nimport matplotlib.pyplot as plt\nplt.plot(history.history['loss'][0:10],color='r',label='Loss train')\nplt.plot(history.history['val_loss'][0:10],color='g',label='Loss validation')\nplt.legend() \nplt.show() \n\nplt.plot(history.history['accuracy'][0:10],color='r',label='Train accuracy')\nplt.plot(history.history['val_accuracy'][0:10],color='g',label='Validation accuracy')\nplt.legend() \nplt.show()\n\nprint(\"time: \"+ str(a/60)+\" mins\")\n\n","sub_path":"Keras_dynamic.py","file_name":"Keras_dynamic.py","file_ext":"py","file_size_in_byte":5415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"392807147","text":"import asyncio\nimport collections\nimport functools\nimport os\nimport re\nimport webbrowser\n\nfrom PIL import Image\n\nPALETTE = list(\"@$&mWJV/!:\") # From darkest to brightest\nLEVEL_STEP = 255 // len(PALETTE)\n\n\ndef start(input_path, output_path=None, thumbnail_resolution=(320, 320), callback=webbrowser.open):\n # Load Image\n img = Image.open(input_path).convert('LA')\n img.thumbnail(thumbnail_resolution)\n\n # Create Dimension (x,y)\n width, height = img.size\n dim = img.load()\n\n # Convert Image\n avglevel, multiply = leveling_brightness(dim, width, height)\n # if avglevel > 100:\n # ascii_converted = convert(dim, width, height, multiply)\n # else:\n # ascii_converted = convert_most10only(dim, width, height)\n ascii_converted = convert(dim, width, height, multiply)\n ascii_converted += '\\nPowered by asciipy'\n\n # Save Image if need\n if output_path:\n with open(output_path, 'w') as f:\n f.write(ascii_converted)\n\n # Call callback if available\n if callback:\n callback(output_path)\n\n return ascii_converted\n\n\ndef leveling_brightness(dim, width, height):\n avglevel = 0\n for h in range(height):\n for w in range(width):\n avglevel += dim[w, h][0]\n avglevel = avglevel / (width * height)\n multiply = 192 / avglevel if avglevel <= 128 else 1\n return avglevel, multiply\n\n\ndef convert(dim, width, height, brightness_multiply=1):\n ascii_converted = list()\n\n for h in range(height):\n ascii_converted.append(list())\n for w in range(width):\n bright = dim[w, h][0] * brightness_multiply\n level = int(bright // LEVEL_STEP)\n if level >= len(PALETTE):\n level = len(PALETTE) - 1\n elif level <= 0:\n level = 0\n c = PALETTE[level]\n ascii_converted[h].append(c)\n\n # merge characters into single string\n for h in range(height):\n ascii_converted[h] = ''.join(ascii_converted[h])\n ascii_converted = '\\n'.join(ascii_converted)\n\n return ascii_converted\n\n\ndef convert_most10only(dim, width, height):\n ascii_converted = list()\n\n # Find most 10\n pixels = list()\n for h in range(height):\n for w in range(width):\n pixels.append(dim[w, h][0])\n counter = collections.Counter(pixels)\n pixels.clear()\n\n # Convert most 10\n most10 = dict(counter.most_common(10))\n most10_levels = sorted(most10.keys(), reverse=True)\n most10_levels = dict([(e[1], e[0]) for e in enumerate(most10_levels)])\n for h in range(height):\n ascii_converted.append(list())\n for w in range(width):\n b = dim[w, h][0]\n if b in most10:\n c = PALETTE[most10_levels[b]]\n else:\n c = ' '\n ascii_converted[h].append(c)\n\n # merge characters into single string\n for h in range(height):\n ascii_converted[h] = ''.join(ascii_converted[h])\n ascii_converted = '\\n'.join(ascii_converted)\n\n return ascii_converted\n\n\ndef autodiscover():\n pathes = list()\n for root, dirs, names in os.walk(os.path.dirname(os.path.abspath(__file__))):\n for name in names:\n if not re.match('.*[.](jpg|jpeg|png|gif)$', name, re.I):\n continue\n input_path = os.path.join(root, name)\n output_path = input_path + '.txt'\n pathes.append((input_path, output_path))\n return pathes\n\n\ndef main():\n io = asyncio.get_event_loop()\n futures = list()\n for input_path, output_path in autodiscover():\n # Convert image in parallel\n futures.append(io.run_in_executor(None, functools.partial(start, input_path, output_path)))\n io.run_until_complete(asyncio.wait(futures))\n io.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"asciipy.py","file_name":"asciipy.py","file_ext":"py","file_size_in_byte":3807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"137661767","text":"# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\n\nimport warnings\nimport ruamel.yaml as yaml\nimport os\n\n\"\"\"\nThis module provides classes to perform topological analyses of structures.\n\"\"\"\n\n__author__ = \"Shyue Ping Ong, Geoffroy Hautier, Sai Jayaraman\"\n__copyright__ = \"Copyright 2011, The Materials Project\"\n__version__ = \"1.0\"\n__maintainer__ = \"Shyue Ping Ong\"\n__email__ = \"shyuep@gmail.com\"\n__status__ = \"Production\"\n__date__ = \"Sep 23, 2011\"\n\n\nfrom math import pi, acos\nimport numpy as np\nimport itertools\nimport collections\n\nfrom monty.dev import deprecated\n\nfrom warnings import warn\nfrom scipy.spatial import Voronoi\nfrom pymatgen import PeriodicSite\nfrom pymatgen import Element, Specie, Composition\nfrom pymatgen.util.num import abs_cap\nfrom pymatgen.symmetry.analyzer import SpacegroupAnalyzer\nfrom pymatgen.core.surface import SlabGenerator\nfrom pymatgen.analysis.local_env import VoronoiNN, JmolNN\n\n\ndef average_coordination_number(structures, freq=10):\n \"\"\"\n Calculates the ensemble averaged Voronoi coordination numbers\n of a list of Structures using VoronoiNN.\n Typically used for analyzing the output of a Molecular Dynamics run.\n Args:\n structures (list): list of Structures.\n freq (int): sampling frequency of coordination number [every freq steps].\n Returns:\n Dictionary of elements as keys and average coordination numbers as values.\n \"\"\"\n coordination_numbers = {}\n for spec in structures[0].composition.as_dict().keys():\n coordination_numbers[spec] = 0.0\n count = 0\n for t in range(len(structures)):\n if t % freq != 0:\n continue\n count += 1\n vnn = VoronoiNN()\n for atom in range(len(structures[0])):\n cn = vnn.get_cn(structures[t], atom, use_weights=True)\n coordination_numbers[structures[t][atom].species_string] += cn\n elements = structures[0].composition.as_dict()\n for el in coordination_numbers:\n coordination_numbers[el] = coordination_numbers[el] / elements[\n el] / count\n return coordination_numbers\n\n\nclass VoronoiAnalyzer:\n \"\"\"\n Performs a statistical analysis of Voronoi polyhedra around each site.\n Each Voronoi polyhedron is described using Schaefli notation.\n That is a set of indices {c_i} where c_i is the number of faces with i\n number of vertices. E.g. for a bcc crystal, there is only one polyhedron\n notation of which is [0,6,0,8,0,0,...].\n In perfect crystals, these also corresponds to the Wigner-Seitz cells.\n For distorted-crystals, liquids or amorphous structures, rather than one-type,\n there is a statistical distribution of polyhedra.\n See ref: Microstructure and its relaxation in Fe-B amorphous system\n simulated by molecular dynamics,\n Stepanyuk et al., J. Non-cryst. Solids (1993), 159, 80-87.\n\n Args:\n cutoff (float): cutoff distance to search for neighbors of a given atom\n (default = 5.0)\n qhull_options (str): options to pass to qhull (optional)\n \"\"\"\n\n def __init__(self, cutoff=5.0, qhull_options=\"Qbb Qc Qz\"):\n self.cutoff = cutoff\n self.qhull_options = qhull_options\n\n def analyze(self, structure, n=0):\n \"\"\"\n Performs Voronoi analysis and returns the polyhedra around atom n\n in Schlaefli notation.\n\n Args:\n structure (Structure): structure to analyze\n n (int): index of the center atom in structure\n\n Returns:\n voronoi index of n: \n where c_i denotes number of facets with i vertices.\n \"\"\"\n center = structure[n]\n neighbors = structure.get_sites_in_sphere(center.coords, self.cutoff)\n neighbors = [i[0] for i in sorted(neighbors, key=lambda s: s[1])]\n qvoronoi_input = np.array([s.coords for s in neighbors])\n voro = Voronoi(qvoronoi_input, qhull_options=self.qhull_options)\n vor_index = np.array([0, 0, 0, 0, 0, 0, 0, 0])\n\n for key in voro.ridge_dict:\n if 0 in key: # This means if the center atom is in key\n if -1 in key: # This means if an infinity point is in key\n raise ValueError(\"Cutoff too short.\")\n else:\n try:\n vor_index[len(voro.ridge_dict[key]) - 3] += 1\n except IndexError:\n # If a facet has more than 10 edges, it's skipped here.\n pass\n return vor_index\n\n def analyze_structures(self, structures, step_freq=10,\n most_frequent_polyhedra=15):\n \"\"\"\n Perform Voronoi analysis on a list of Structures.\n Note that this might take a significant amount of time depending on the\n size and number of structures.\n\n Args:\n structures (list): list of Structures\n cutoff (float: cutoff distance around an atom to search for\n neighbors\n step_freq (int): perform analysis every step_freq steps\n qhull_options (str): options to pass to qhull\n most_frequent_polyhedra (int): this many unique polyhedra with\n highest frequences is stored.\n\n Returns:\n A list of tuples in the form (voronoi_index,frequency)\n \"\"\"\n voro_dict = {}\n step = 0\n for structure in structures:\n step += 1\n if step % step_freq != 0:\n continue\n\n v = []\n for n in range(len(structure)):\n v.append(str(self.analyze(structure, n=n).view()))\n for voro in v:\n if voro in voro_dict:\n voro_dict[voro] += 1\n else:\n voro_dict[voro] = 1\n return sorted(voro_dict.items(),\n key=lambda x: (x[1], x[0]),\n reverse=True)[:most_frequent_polyhedra]\n\n @staticmethod\n def plot_vor_analysis(voronoi_ensemble):\n t = zip(*voronoi_ensemble)\n labels = t[0]\n val = list(t[1])\n tot = np.sum(val)\n val = [float(j) / tot for j in val]\n pos = np.arange(len(val)) + .5 # the bar centers on the y axis\n import matplotlib.pyplot as plt\n plt.figure()\n plt.barh(pos, val, align='center', alpha=0.5)\n plt.yticks(pos, labels)\n plt.xlabel('Count')\n plt.title('Voronoi Spectra')\n plt.grid(True)\n return plt\n\n\nclass RelaxationAnalyzer:\n \"\"\"\n This class analyzes the relaxation in a calculation.\n \"\"\"\n\n def __init__(self, initial_structure, final_structure):\n \"\"\"\n Please note that the input and final structures should have the same\n ordering of sites. This is typically the case for most computational\n codes.\n\n Args:\n initial_structure (Structure): Initial input structure to\n calculation.\n final_structure (Structure): Final output structure from\n calculation.\n \"\"\"\n if final_structure.formula != initial_structure.formula:\n raise ValueError(\"Initial and final structures have different \" +\n \"formulas!\")\n self.initial = initial_structure\n self.final = final_structure\n\n def get_percentage_volume_change(self):\n \"\"\"\n Returns the percentage volume change.\n\n Returns:\n Volume change in percentage, e.g., 0.055 implies a 5.5% increase.\n \"\"\"\n initial_vol = self.initial.lattice.volume\n final_vol = self.final.lattice.volume\n return final_vol / initial_vol - 1\n\n def get_percentage_lattice_parameter_changes(self):\n \"\"\"\n Returns the percentage lattice parameter changes.\n\n Returns:\n A dict of the percentage change in lattice parameter, e.g.,\n {'a': 0.012, 'b': 0.021, 'c': -0.031} implies a change of 1.2%,\n 2.1% and -3.1% in the a, b and c lattice parameters respectively.\n \"\"\"\n initial_latt = self.initial.lattice\n final_latt = self.final.lattice\n d = {l: getattr(final_latt, l) / getattr(initial_latt, l) - 1\n for l in [\"a\", \"b\", \"c\"]}\n return d\n\n def get_percentage_bond_dist_changes(self, max_radius=3.0):\n \"\"\"\n Returns the percentage bond distance changes for each site up to a\n maximum radius for nearest neighbors.\n\n Args:\n max_radius (float): Maximum radius to search for nearest\n neighbors. This radius is applied to the initial structure,\n not the final structure.\n\n Returns:\n Bond distance changes as a dict of dicts. E.g.,\n {index1: {index2: 0.011, ...}}. For economy of representation, the\n index1 is always less than index2, i.e., since bonding between\n site1 and siten is the same as bonding between siten and site1,\n there is no reason to duplicate the information or computation.\n \"\"\"\n data = collections.defaultdict(dict)\n for inds in itertools.combinations(list(range(len(self.initial))), 2):\n (i, j) = sorted(inds)\n initial_dist = self.initial[i].distance(self.initial[j])\n if initial_dist < max_radius:\n final_dist = self.final[i].distance(self.final[j])\n data[i][j] = final_dist / initial_dist - 1\n return data\n\n\nclass VoronoiConnectivity:\n \"\"\"\n Computes the solid angles swept out by the shared face of the voronoi\n polyhedron between two sites.\n\n Args:\n structure (Structure): Input structure\n cutoff (float) Cutoff distance.\n \"\"\"\n\n # Radius in Angstrom cutoff to look for coordinating atoms\n\n def __init__(self, structure, cutoff=10):\n self.cutoff = cutoff\n self.s = structure\n recp_len = np.array(self.s.lattice.reciprocal_lattice.abc)\n i = np.ceil(cutoff * recp_len / (2 * pi))\n offsets = np.mgrid[-i[0]:i[0] + 1, -i[1]:i[1] + 1, -i[2]:i[2] + 1].T\n self.offsets = np.reshape(offsets, (-1, 3))\n # shape = [image, axis]\n self.cart_offsets = self.s.lattice.get_cartesian_coords(self.offsets)\n\n @property\n def connectivity_array(self):\n \"\"\"\n Provides connectivity array.\n\n Returns:\n connectivity: An array of shape [atomi, atomj, imagej]. atomi is\n the index of the atom in the input structure. Since the second\n atom can be outside of the unit cell, it must be described\n by both an atom index and an image index. Array data is the\n solid angle of polygon between atomi and imagej of atomj\n \"\"\"\n # shape = [site, axis]\n cart_coords = np.array(self.s.cart_coords)\n # shape = [site, image, axis]\n all_sites = cart_coords[:, None, :] + self.cart_offsets[None, :, :]\n vt = Voronoi(all_sites.reshape((-1, 3)))\n n_images = all_sites.shape[1]\n cs = (len(self.s), len(self.s), len(self.cart_offsets))\n connectivity = np.zeros(cs)\n vts = np.array(vt.vertices)\n for (ki, kj), v in vt.ridge_dict.items():\n atomi = ki // n_images\n atomj = kj // n_images\n\n imagei = ki % n_images\n imagej = kj % n_images\n\n if imagei != n_images // 2 and imagej != n_images // 2:\n continue\n\n if imagei == n_images // 2:\n # atomi is in original cell\n val = solid_angle(vt.points[ki], vts[v])\n connectivity[atomi, atomj, imagej] = val\n\n if imagej == n_images // 2:\n # atomj is in original cell\n val = solid_angle(vt.points[kj], vts[v])\n connectivity[atomj, atomi, imagei] = val\n\n if -10.101 in vts[v]:\n warn('Found connectivity with infinite vertex. '\n 'Cutoff is too low, and results may be '\n 'incorrect')\n return connectivity\n\n @property\n def max_connectivity(self):\n \"\"\"\n returns the 2d array [sitei, sitej] that represents\n the maximum connectivity of site i to any periodic\n image of site j\n \"\"\"\n return np.max(self.connectivity_array, axis=2)\n\n def get_connections(self):\n \"\"\"\n Returns a list of site pairs that are Voronoi Neighbors, along\n with their real-space distances.\n \"\"\"\n con = []\n maxconn = self.max_connectivity\n for ii in range(0, maxconn.shape[0]):\n for jj in range(0, maxconn.shape[1]):\n if maxconn[ii][jj] != 0:\n dist = self.s.get_distance(ii, jj)\n con.append([ii, jj, dist])\n return con\n\n def get_sitej(self, site_index, image_index):\n \"\"\"\n Assuming there is some value in the connectivity array at indices\n (1, 3, 12). sitei can be obtained directly from the input structure\n (structure[1]). sitej can be obtained by passing 3, 12 to this function\n\n Args:\n site_index (int): index of the site (3 in the example)\n image_index (int): index of the image (12 in the example)\n \"\"\"\n atoms_n_occu = self.s[site_index].species\n lattice = self.s.lattice\n coords = self.s[site_index].frac_coords + self.offsets[image_index]\n return PeriodicSite(atoms_n_occu, coords, lattice)\n\n\ndef solid_angle(center, coords):\n \"\"\"\n Helper method to calculate the solid angle of a set of coords from the\n center.\n\n Args:\n center (3x1 array): Center to measure solid angle from.\n coords (Nx3 array): List of coords to determine solid angle.\n\n Returns:\n The solid angle.\n \"\"\"\n o = np.array(center)\n r = [np.array(c) - o for c in coords]\n r.append(r[0])\n n = [np.cross(r[i + 1], r[i]) for i in range(len(r) - 1)]\n n.append(np.cross(r[1], r[0]))\n vals = []\n for i in range(len(n) - 1):\n v = -np.dot(n[i], n[i + 1]) \\\n / (np.linalg.norm(n[i]) * np.linalg.norm(n[i + 1]))\n vals.append(acos(abs_cap(v)))\n phi = sum(vals)\n return phi + (3 - len(r)) * pi\n\n\ndef get_max_bond_lengths(structure, el_radius_updates=None):\n \"\"\"\n Provides max bond length estimates for a structure based on the JMol\n table and algorithms.\n \n Args:\n structure: (structure)\n el_radius_updates: (dict) symbol->float to update atomic radii\n \n Returns: (dict) - (Element1, Element2) -> float. The two elements are \n ordered by Z.\n \"\"\"\n #jmc = JMolCoordFinder(el_radius_updates)\n jmnn = JmolNN(el_radius_updates=el_radius_updates)\n\n bonds_lens = {}\n els = sorted(structure.composition.elements, key=lambda x: x.Z)\n\n for i1 in range(len(els)):\n for i2 in range(len(els) - i1):\n bonds_lens[els[i1], els[i1 + i2]] = jmnn.get_max_bond_distance(\n els[i1].symbol, els[i1 + i2].symbol)\n\n return bonds_lens\n\n\n@deprecated(message=(\"find_dimension has been moved to\"\n \"pymatgen.analysis.dimensionality.get_dimensionality_gorai\"\n \" this method will be removed in pymatgen v2019.1.1.\"))\ndef get_dimensionality(structure, max_hkl=2, el_radius_updates=None,\n min_slab_size=5, min_vacuum_size=5,\n standardize=True, bonds=None):\n \"\"\"\n This method returns whether a structure is 3D, 2D (layered), or 1D (linear\n chains or molecules) according to the algorithm published in Gorai, P.,\n Toberer, E. & Stevanovic, V. Computational Identification of Promising\n Thermoelectric Materials Among Known Quasi-2D Binary Compounds. J. Mater.\n Chem. A 2, 4136 (2016).\n\n Note that a 1D structure detection might indicate problems in the bonding\n algorithm, particularly for ionic crystals (e.g., NaCl)\n\n Users can change the behavior of bonds detection by passing either\n el_radius_updates to update atomic radii for auto-detection of max bond\n distances, or bonds to explicitly specify max bond distances for atom pairs.\n Note that if you pass both, el_radius_updates are ignored.\n\n Args:\n structure: (Structure) structure to analyze dimensionality for\n max_hkl: (int) max index of planes to look for layers\n el_radius_updates: (dict) symbol->float to update atomic radii\n min_slab_size: (float) internal surface construction parameter\n min_vacuum_size: (float) internal surface construction parameter\n standardize (bool): whether to standardize the structure before\n analysis. Set to False only if you already have the structure in a\n convention where layers / chains will be along low indexes.\n bonds ({(specie1, specie2): max_bond_dist}: bonds are\n specified as a dict of tuples: float of specie1, specie2\n and the max bonding distance. For example, PO4 groups may be\n defined as {(\"P\", \"O\"): 3}.\n\n Returns: (int) the dimensionality of the structure - 1 (molecules/chains),\n 2 (layered), or 3 (3D)\n\n \"\"\"\n if standardize:\n structure = SpacegroupAnalyzer(structure). \\\n get_conventional_standard_structure()\n\n if not bonds:\n bonds = get_max_bond_lengths(structure, el_radius_updates)\n\n num_surfaces = 0\n for h in range(max_hkl):\n for k in range(max_hkl):\n for l in range(max_hkl):\n if max([h, k, l]) > 0 and num_surfaces < 2:\n sg = SlabGenerator(structure, (h, k, l),\n min_slab_size=min_slab_size,\n min_vacuum_size=min_vacuum_size)\n slabs = sg.get_slabs(bonds)\n for _ in slabs:\n num_surfaces += 1\n\n return 3 - min(num_surfaces, 2)\n\n\ndef contains_peroxide(structure, relative_cutoff=1.1):\n \"\"\"\n Determines if a structure contains peroxide anions.\n\n Args:\n structure (Structure): Input structure.\n relative_cutoff: The peroxide bond distance is 1.49 Angstrom.\n Relative_cutoff * 1.49 stipulates the maximum distance two O\n atoms must be to each other to be considered a peroxide.\n\n Returns:\n Boolean indicating if structure contains a peroxide anion.\n \"\"\"\n ox_type = oxide_type(structure, relative_cutoff)\n if ox_type == \"peroxide\":\n return True\n else:\n return False\n\n\nclass OxideType:\n \"\"\"\n Separate class for determining oxide type.\n\n Args:\n structure: Input structure.\n relative_cutoff: Relative_cutoff * act. cutoff stipulates the max.\n distance two O atoms must be from each other. Default value is\n 1.1. At most 1.1 is recommended, nothing larger, otherwise the\n script cannot distinguish between superoxides and peroxides.\n \"\"\"\n\n def __init__(self, structure, relative_cutoff=1.1):\n self.structure = structure\n self.relative_cutoff = relative_cutoff\n self.oxide_type, self.nbonds = self.parse_oxide()\n\n def parse_oxide(self):\n \"\"\"\n Determines if an oxide is a peroxide/superoxide/ozonide/normal oxide.\n\n Returns:\n oxide_type (str): Type of oxide\n ozonide/peroxide/superoxide/hydroxide/None.\n nbonds (int): Number of peroxide/superoxide/hydroxide bonds in\n structure.\n \"\"\"\n structure = self.structure\n relative_cutoff = self.relative_cutoff\n o_sites_frac_coords = []\n h_sites_frac_coords = []\n lattice = structure.lattice\n\n if isinstance(structure.composition.elements[0], Element):\n comp = structure.composition\n elif isinstance(structure.composition.elements[0], Specie):\n elmap = collections.defaultdict(float)\n for site in structure:\n for species, occu in site.species.items():\n elmap[species.element] += occu\n comp = Composition(elmap)\n if Element(\"O\") not in comp or comp.is_element:\n return \"None\", 0\n\n for site in structure:\n syms = [sp.symbol for sp in site.species.keys()]\n if \"O\" in syms:\n o_sites_frac_coords.append(site.frac_coords)\n if \"H\" in syms:\n h_sites_frac_coords.append(site.frac_coords)\n\n if h_sites_frac_coords:\n dist_matrix = lattice.get_all_distances(o_sites_frac_coords,\n h_sites_frac_coords)\n if np.any(dist_matrix < relative_cutoff * 0.93):\n return \"hydroxide\", len(\n np.where(dist_matrix < relative_cutoff * 0.93)[0]) / 2.0\n dist_matrix = lattice.get_all_distances(o_sites_frac_coords,\n o_sites_frac_coords)\n np.fill_diagonal(dist_matrix, 1000)\n is_superoxide = False\n is_peroxide = False\n is_ozonide = False\n if np.any(dist_matrix < relative_cutoff * 1.35):\n bond_atoms = np.where(dist_matrix < relative_cutoff * 1.35)[0]\n is_superoxide = True\n elif np.any(dist_matrix < relative_cutoff * 1.49):\n is_peroxide = True\n bond_atoms = np.where(dist_matrix < relative_cutoff * 1.49)[0]\n if is_superoxide:\n if len(bond_atoms) > len(set(bond_atoms)):\n is_superoxide = False\n is_ozonide = True\n try:\n nbonds = len(set(bond_atoms))\n except UnboundLocalError:\n nbonds = 0.0\n if is_ozonide:\n str_oxide = \"ozonide\"\n elif is_superoxide:\n str_oxide = \"superoxide\"\n elif is_peroxide:\n str_oxide = \"peroxide\"\n else:\n str_oxide = \"oxide\"\n if str_oxide == \"oxide\":\n nbonds = comp[\"O\"]\n return str_oxide, nbonds\n\n\ndef oxide_type(structure, relative_cutoff=1.1, return_nbonds=False):\n \"\"\"\n Determines if an oxide is a peroxide/superoxide/ozonide/normal oxide\n\n Args:\n structure (Structure): Input structure.\n relative_cutoff (float): Relative_cutoff * act. cutoff stipulates the\n max distance two O atoms must be from each other.\n return_nbonds (bool): Should number of bonds be requested?\n \"\"\"\n\n ox_obj = OxideType(structure, relative_cutoff)\n if return_nbonds:\n return ox_obj.oxide_type, ox_obj.nbonds\n else:\n return ox_obj.oxide_type\n\n\ndef sulfide_type(structure):\n \"\"\"\n Determines if a structure is a sulfide/polysulfide\n\n Args:\n structure (Structure): Input structure.\n\n Returns:\n (str) sulfide/polysulfide/sulfate\n \"\"\"\n structure = structure.copy()\n structure.remove_oxidation_states()\n s = Element(\"S\")\n comp = structure.composition\n if comp.is_element or s not in comp:\n return None\n\n finder = SpacegroupAnalyzer(structure, symprec=0.1)\n symm_structure = finder.get_symmetrized_structure()\n s_sites = [sites[0] for sites in symm_structure.equivalent_sites if\n sites[0].specie == s]\n\n def process_site(site):\n\n # in an exceptionally rare number of structures, the search\n # radius needs to be increased to find a neighbor atom\n search_radius = 4\n neighbors = []\n while len(neighbors) == 0:\n neighbors = structure.get_neighbors(site, search_radius)\n search_radius *= 2\n if search_radius > max(structure.lattice.abc)*2:\n break\n\n neighbors = sorted(neighbors, key=lambda n: n[1])\n nn, dist = neighbors[0]\n coord_elements = [site.specie for site, d in neighbors\n if d < dist + 0.4][:4]\n avg_electroneg = np.mean([e.X for e in coord_elements])\n if avg_electroneg > s.X:\n return \"sulfate\"\n elif avg_electroneg == s.X and s in coord_elements:\n return \"polysulfide\"\n else:\n return \"sulfide\"\n\n types = set([process_site(site) for site in s_sites])\n if \"sulfate\" in types:\n return None\n elif \"polysulfide\" in types:\n return \"polysulfide\"\n else:\n return \"sulfide\"\n\n\n","sub_path":"pymatgen/analysis/structure_analyzer.py","file_name":"structure_analyzer.py","file_ext":"py","file_size_in_byte":24388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"27506608","text":"import argparse\nimport csv\nimport random\n\nfrom sudachipy import dictionary\n\nfrom .create_sudachi_dict import POS_CONVERSION\n\n\ndef convert_pos(entry):\n word, pos = tuple(entry.split('/'))\n if pos in POS_CONVERSION:\n pos = POS_CONVERSION[pos]\n return word + '/' + pos\n\n\ndef main(args):\n with open(args.akama_file, encoding='utf8') as f:\n style_lines = f.read().rstrip().split('\\n')\n header = style_lines[0]\n del style_lines[0]\n\n entry_to_sents = {}\n\n for line in style_lines:\n comps = line.split(',')\n entry_to_sents[comps[0]] = []\n entry_to_sents[comps[1]] = []\n\n tokenizer_obj = dictionary.Dictionary(args.sudachipy_config).create()\n\n with open(args.corpus, encoding='utf8') as f:\n for i, line in enumerate(f):\n line = line.rstrip()\n if i % 1000 == 0:\n print(f'Processing line {i}')\n morphemes = tokenizer_obj.tokenize(line)\n for m in morphemes:\n all_pos = m.part_of_speech()\n for pos_i in range(min(2, len(all_pos)) - 1, -1, -1):\n entry = m.surface() + '/' + all_pos[pos_i]\n if entry in entry_to_sents:\n entry_to_sents[entry].append(line)\n break\n\n for l in entry_to_sents.values():\n # keep the shortest sentences\n l.sort(key=lambda s: len(s))\n if len(l) > args.sentences_per_pair * 2:\n del l[args.sentences_per_pair * 2:]\n random.shuffle(l)\n\n found, not_found = 0, 0\n total_list_len = 0\n for key, l in entry_to_sents.items():\n if l:\n found += 1\n total_list_len += len(l)\n else:\n not_found += 1\n\n print(f'Found {found} / {found + not_found} entries, avg list len {total_list_len / found}')\n\n found_pairs = 0\n\n for split in ['dev', 'test']:\n with open(getattr(args, 'out_path_' + split), 'w', encoding='utf8') as f:\n wr = csv.writer(f, quoting=csv.QUOTE_ALL)\n wr.writerow(['sentence 1', 'sentence 2'] + header.split(','))\n\n for line in style_lines:\n comps = line.split(',')\n entry1, entry2 = comps[0], comps[1]\n found = False\n\n right_center = random.randint(0, 1)\n half1, half2 = (len(entry_to_sents[entry1]) + right_center) // 2, \\\n (len(entry_to_sents[entry2]) + right_center) // 2\n if split == 'dev':\n l1, l2 = entry_to_sents[entry1][:half1], entry_to_sents[entry2][:half2]\n else:\n l1, l2 = entry_to_sents[entry1][half1:], entry_to_sents[entry2][half2:]\n\n for entry1_sent in l1:\n for entry2_sent in l2:\n found = True\n wr.writerow([entry1_sent] + [entry2_sent] + [entry1] + [entry2] + comps[2:])\n\n if found:\n found_pairs += 1\n\n print(f'Found {found_pairs} / {len(style_lines)} entry pairs')\n\n\nif __name__ == '__main__':\n random.seed(12345)\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--akama-file', required=True)\n parser.add_argument('--corpus', required=True)\n parser.add_argument('--out-path-dev', required=True)\n parser.add_argument('--out-path-test', required=True)\n parser.add_argument('--sudachipy-config', required=True)\n parser.add_argument('--sentences-per-pair', default=5, type=int, help='Finds up to this many sentences per pair')\n main(parser.parse_args())\n","sub_path":"data/downstream/Japanese/filter_corpus_akama.py","file_name":"filter_corpus_akama.py","file_ext":"py","file_size_in_byte":3604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"460716833","text":"import math\n\nclass SubMain(object):\n\n def num(self):\n for i in range(10000):\n n = math.sqrt(i + 100)\n m = math.sqrt(i + 268)\n if n % 1 == 0 and m % 1 == 0:\n print(i)\n\n def date():\n cal = input('data: ')\n date = cal.split('-')\n\n year = int(date[0])\n month = int(date[1])\n day = int(date[2])\n\n month_arr = [0,31,28,31,30,31,30,31,31,30,31,30,31]\n\n num = 0\n\n for i in range(1, len(month_arr)):\n if month > i:\n num += month_arr[i]\n else:\n num += day\n break\n print(num)","sub_path":"Exercise/sub.py","file_name":"sub.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"68743864","text":"\nfrom ..linalg import solver_counter, LogexpTransformation\n\n# numpy/scipy stuff \nimport numpy as np\nfrom numpy.linalg.linalg import LinAlgError\nfrom numpy.testing import assert_array_almost_equal\nfrom scipy.optimize import fmin_l_bfgs_b\n\n# development stuff\nfrom logging import getLogger\nfrom warnings import warn\nlogger = getLogger(__name__)\n\nclass BaseModel (object):\n # for pos. or neg. constrained problems, as close as it can get to zero\n # by default this is not used\n param_shift = {'+ve':1e-200, '-ve':-1e-200} \n _transformations = {'+ve':LogexpTransformation()}\n\n def __init__(self):\n \"\"\" initialize a few instance variables \"\"\"\n logger.debug('Initializing %s model.' % self.__class__.__name__)\n self.dependent_attributes = ['_alpha',\n '_log_like',\n '_gradient','_K',\n '_log_det']\n self._previous_parameters = None # previous parameters from last call\n self.grad_method = None # could be {'finite_difference','adjoint'}\n self.noise_var_constraint = '+ve' # Gaussian noise variance constraint\n return\n\n\n def log_likelihood(self, return_gradient=False):\n \"\"\"\n computes the log likelihood and the gradient (if not already computed).\n\n If return_gradient then gradient will be returned as second arguement.\n \"\"\"\n p = self.parameters # this has to be called first\n\n # check if I need to recompute anything\n if return_gradient and (self._gradient is None):\n # compute the log likelihood and gradient wrt the parameters\n if 'adjoint' in self.grad_method:\n (self._log_like, self._gradient) = self._adjoint_gradient(p)\n elif 'finite_difference' in self.grad_method:\n (self._log_like, self._gradient) = self._finite_diff_gradient(p)\n else:\n raise RuntimeError('unknown grad_method %s' % repr(self.grad_method))\n elif self._log_like is None: # compute the log-likelihood without gradient\n self._log_like = self._compute_log_likelihood(p)\n else: # everything is already computed\n pass\n\n if return_gradient: # return both\n return self._log_like, self._gradient\n else: # just return likelihood\n return self._log_like\n\n\n def optimize(self, max_iters=1e3, messages=False, use_counter=False,\\\n factr=1e7, pgtol=1e-05):\n \"\"\"\n maximize the log likelihood\n\n Inputs:\n max_iters : int\n maximum number of optimization iterations\n factr, pgtol : lbfgsb convergence criteria, see fmin_l_bfgs_b help\n use factr of 1e12 for low accuracy, 10 for extremely high accuracy \n (default 1e7)\n \"\"\"\n logger.debug('Beginning MLE to optimize hyperparams. grad_method=%s'\\\n % self.grad_method)\n\n # setup the optimization\n try:\n x0 = self._transform_parameters(self.parameters)\n assert np.all(np.isfinite(x0))\n except:\n logger.error('Transformation failed for initial values. '\\\n + 'Ensure constraints are met or the value is not too small.')\n raise\n\n # filter out the fixed parameters\n free = np.logical_not(self._fixed_indicies)\n x0 = x0[free]\n\n # setup the counter\n if use_counter:\n self._counter = solver_counter(disp=True)\n else:\n self._counter = None\n\n # run the optimization\n try:\n x_opt, f_opt, opt = fmin_l_bfgs_b(func=self._objective_grad, x0=x0,\\\n factr=factr, pgtol=pgtol, maxiter=max_iters, disp=messages)\n except (KeyboardInterrupt,IndexError):\n logger.info('Keyboard interrupt raised. Cleaning up...')\n if self._counter is not None and self._counter.backup is not None:\n self.parameters = self._counter.backup[1]\n logger.info('will return best parameter set with'\\\n + 'log-likelihood = %.4g' % self._counter.backup[0])\n else:\n logger.info('Function Evals: %d. Exit status: %s' % (f_opt, opt['warnflag']))\n # extract the optimal value and set the parameters to this\n transformed_parameters = self._previous_parameters \n transformed_parameters[free] = x_opt\n self.parameters = self._untransform_parameters(transformed_parameters)\n return opt\n\n\n def checkgrad(self, decimal=3, raise_if_fails=True):\n \"\"\"\n checks the gradient and raises if does not pass\n \"\"\"\n grad_exact = self._finite_diff_gradient(self.parameters)[1]\n grad_exact[self._fixed_indicies] = 1 # gradients of fixed variables\n grad_analytic = self.log_likelihood(return_gradient=True)[1]\n grad_analytic[self._fixed_indicies] = 1 # gradients of fixed variables\n\n # first protect from nan values incase both analytic and exact are small\n protected_nan = np.logical_and(np.abs(grad_exact) < 1e-8, \\\n np.abs(grad_analytic) < 1e-8)\n\n # protect against division by zero\n protected_div0 = np.abs(grad_exact-grad_analytic) < 1e-5\n # artificially change these protected values\n grad_exact[np.logical_or(protected_nan, protected_div0)] = 1.\n grad_analytic[np.logical_or(protected_nan, protected_div0)] = 1.\n\n try:\n assert_array_almost_equal(grad_exact / grad_analytic,\\\n np.ones(grad_exact.shape),decimal=decimal)\n except:\n logger.info('Gradient check failed.')\n logger.debug('[[Finite-Diff Gradient], [Analytic Gradient]]:\\n%s\\n'\\\n % repr(np.asarray([grad_exact,grad_analytic])))\n if raise_if_fails:\n raise\n else:\n logger.info(format_exc()) # print the output\n return False\n else:\n logger.info('Gradient check passed.')\n return True\n\n @property\n def parameters(self):\n \"\"\"\n this gets the parameters from the object attributes\n \"\"\"\n parameters = np.concatenate( (np.ravel(self.noise_var),\\\n self.kern.parameters), axis=0)\n\n # check if the parameters have changed\n if not np.array_equal(parameters, self._previous_parameters):\n # remove the internal variables that rely on the parameters\n for attr in self.dependent_attributes:\n setattr(self, attr, None)\n # update the previous parameter array\n self._previous_parameters = parameters.copy()\n return parameters.copy()\n\n @parameters.setter\n def parameters(self,parameters):\n \"\"\"\n takes optimization variable parameters and sets the internal state of\n self to make it consistent with the variables\n \"\"\"\n # set the parameters internally\n self.noise_var = parameters[0]\n self.kern.parameters = parameters[1:]\n\n # check if the parameters have changed\n if not np.array_equal(parameters, self._previous_parameters):\n # remove the internal variables that rely on the parameters\n for attr in self.dependent_attributes:\n setattr(self, attr, None)\n # update the previous parameter array\n self._previous_parameters = parameters.copy()\n return parameters\n\n @property\n def constraints(self):\n \"\"\" returns the model parameter constraints as a list \"\"\"\n constraints = np.concatenate( (np.ravel(self.noise_var_constraint), \n self.kern.constraints), axis=0)\n return constraints\n\n\n def predict(self, Xnew, compute_var=None):\n \"\"\"\n make predictions at new points\n MUST begin with call to parameters property\n \"\"\"\n raise NotImplementedError('')\n\n\n def fit(self):\n \"\"\"\n determines the weight vector _alpha\n MUST begin with a call to parameters property\n \"\"\"\n raise NotImplementedError('')\n\n\n def _objective_grad(self, transformed_free_parameters):\n \"\"\" \n determines the objective and gradients in the transformed input space \n \"\"\"\n # get the fixed indices and add to the transformed parameters\n free = np.logical_not(self._fixed_indicies)\n transformed_parameters = self._previous_parameters\n transformed_parameters[free] = transformed_free_parameters\n try:\n # untransform and internalize parameters\n self.parameters = self._untransform_parameters(transformed_parameters)\n # compute objective and gradient in untransformed space\n (objective, gradient) = self.log_likelihood(return_gradient=True)\n objective = -objective # since we want to minimize\n gradient = -gradient\n # ensure the values are finite\n if not np.isfinite(objective):\n logger.debug('objective is not finite')\n if not np.all(np.isfinite(gradient[free])):\n logger.debug('some derivatives are non-finite')\n # transform the gradient \n gradient = self._transform_gradient(self.parameters, gradient)\n except (LinAlgError, ZeroDivisionError, ValueError):\n logger.error('numerical issue computing log-likelihood or gradient')\n raise\n # get rid of the gradients of the fixed parameters\n free_gradient = gradient[free]\n\n # call the counter if ness\n if self._counter is not None:\n msg='log-likelihood=%.4g, gradient_norm=%.2g'\\\n % (-objective, np.linalg.norm(gradient))\n if self._counter.backup is None or self._counter.backup[0]<-objective:\n self._counter(msg=msg,store=(-objective,self.parameters.copy()))\n else: # don't update backup\n self._counter(msg=msg)\n return objective, free_gradient\n\n @property\n def _fixed_indicies(self):\n \"\"\" \n returns a bool array specifiying where the indicies are fixed \n \"\"\"\n fixed_inds = self.constraints == 'fixed'\n return fixed_inds\n\n @property\n def _free_indicies(self):\n \"\"\" \n returns a bool array specifiying where the indicies are free \n \"\"\"\n return np.logical_not(self._fixed_indicies)\n\n\n def _transform_parameters(self, parameters):\n \"\"\"\n applies a transformation to the parameters based on a constraint\n \"\"\"\n constraints = self.constraints\n assert parameters.size == np.size(constraints) # check if sizes correct\n transformed_parameters = np.zeros(parameters.size)\n for i,(param,constraint) in enumerate(zip(parameters,constraints)):\n if constraint is None or constraint == 'fixed' or constraint == '':\n transformed_parameters[i] = param\n else: # I need to transform the parameters\n transformed_parameters[i] =\\\n self._transformations[constraint].transform(\\\n param - self.param_shift[constraint])\n\n # check to ensure transformation led to finite value\n if not np.all(np.isfinite(transformed_parameters)):\n logger.debug('transformation led to non-finite value')\n return transformed_parameters\n\n\n def _transform_gradient(self, parameters, gradients):\n \"\"\"\n see _transform parameters\n \"\"\"\n constraints = self.constraints\n assert parameters.size == gradients.size == np.size(constraints)\n transformed_grads = np.zeros(parameters.size)\n ziplist = zip(parameters,gradients,constraints)\n for i,(param,grad,constraint) in enumerate(ziplist):\n if constraint is None or constraint == '': # no transformation\n transformed_grads[i] = grad\n elif constraint != 'fixed': # apply transformation\n transformed_grads[i] =\\\n self._transformations[constraint].transform_grad(\\\n param - self.param_shift[constraint],grad)\n\n # check to ensure transformation led to finite value\n if not np.all(np.isfinite(transformed_grads)):\n logger.debug('transformation led to non-finite value')\n return transformed_grads\n\n\n def _untransform_parameters(self, transformed_parameters):\n \"\"\" \n applies a reverse transformation to the parameters given constraints\n \"\"\"\n assert transformed_parameters.size == np.size(self.constraints)\n parameters = np.zeros(transformed_parameters.size)\n ziplist = zip(transformed_parameters,self.constraints)\n for i,(t_param,constraint) in enumerate(ziplist):\n if constraint is None or constraint == 'fixed' or constraint == '':\n parameters[i] = t_param\n else:\n parameters[i] = \\\n self._transformations[constraint].inverse_transform(t_param)\\\n + self.param_shift[constraint]\n\n # check to ensure transformation led to finite value\n if not np.all(np.isfinite(parameters)):\n logger.debug('transformation led to non-finite value')\n return parameters\n\n\n def _finite_diff_gradient(self, parameters):\n \"\"\"\n helper function to compute function gradients by finite difference.\n\n Inputs:\n parameters : 1d array\n whose first element is the Gaussian noise and the other \n elements are the kernel parameters\n log_like : float\n log likelihood at the current point\n\n Outputs:\n log_likelihood\n \"\"\"\n assert isinstance(parameters,np.ndarray)\n # get the free indicies\n free_inds = np.nonzero(np.logical_not(self._fixed_indicies))[0]\n\n # first take a forward step in each direction\n step = 1e-6 # finite difference step\n log_like_fs = np.zeros(free_inds.size)\n for i,param_idx in enumerate(free_inds):\n p_fs = parameters.copy()\n p_fs[param_idx] += step # take a step forward\n log_like_fs[i] = self._compute_log_likelihood(p_fs)\n\n # compute the log likelihood at current point\n log_like = self._compute_log_likelihood(parameters)\n\n # compute the gradient\n gradient = np.zeros(parameters.shape) # default gradient is zero\n gradient[free_inds] = (log_like_fs-log_like)\n gradient[free_inds] = gradient[free_inds]/step # divide by step length\n return log_like, gradient\n\n\n def _compute_log_likelihood(self, parameters):\n \"\"\"\n helper function to compute log likelihood.\n Inputs:\n parameters : 1d array\n whose first element is the Gaussian noise and the other \n elements are the kernel parameters\n\n Outputs:\n log_likelihood\n \"\"\"\n raise NotImplementedError('')\n\n\n def _adjoint_gradient(self,parameters):\n raise NotImplementedError('')\n return log_like, gradient","sub_path":"gp_grief/models/basemodel.py","file_name":"basemodel.py","file_ext":"py","file_size_in_byte":15384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"193951950","text":"import json\n\nfrom flask import make_response\nfrom flask_restful import Resource\n\nfrom app.settings import settings\n\n\nclass Healthcheck(Resource):\n @staticmethod\n def get():\n service_info = dict(status={}, service_meta={})\n service_info[\"service_meta\"][\"publisher_slug\"] = settings.PUBLISHER_SLUG\n service_info[\"service_meta\"][\"deployment_id\"] = settings.DEPLOYMENT_ID\n\n status_code = 200\n status_msg = \"ServiceHealthcheckSuccess\"\n\n service_info[\"status\"][\"status_code\"] = status_code\n service_info[\"status\"][\"status_msg\"] = status_msg\n\n return make_response(json.dumps(service_info), status_code)\n","sub_path":"app/resources/healthcheck.py","file_name":"healthcheck.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"435341483","text":"voting_data = list(open(\"voting_record_dump109.txt\"))\n## Task 1\n\ndef create_voting_dict():\n \"\"\"\n Input: None (use voting_data above)\n Output: A dictionary that maps the last name of a senator\n to a list of numbers representing the senator's voting\n record.\n Example:\n >>> create_voting_dict()['Clinton']\n [-1, 1, 1, 1, 0, 0, -1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, 1]\n\n This procedure should return a dictionary that maps the last name\n of a senator to a list of numbers representing that senator's\n voting record, using the list of strings from the dump file (strlist). You\n will need to use the built-in procedure int() to convert a string\n representation of an integer (e.g. '1') to the actual integer\n (e.g. 1).\n\n You can use the split() procedure to split each line of the\n strlist into a list; the first element of the list will be the senator's\n name, the second will be his/her party affiliation (R or D), the\n third will be his/her home state, and the remaining elements of\n the list will be that senator's voting record on a collection of bills.\n A \"1\" represents a 'yea' vote, a \"-1\" a 'nay', and a \"0\" an abstention.\n\n The lists for each senator should preserve the order listed in voting data.\n \"\"\"\n\n voting_record = {}\n for line in voting_data:\n voting_record[line.split()[0]] = [ int(vote) for vote in line.split()[3:] ]\n return voting_record\n\n## Task 2\n\ndef policy_compare(sen_a, sen_b, voting_dict):\n \"\"\"\n Input: last names of sen_a and sen_b, and a voting dictionary mapping senator\n names to lists representing their voting records.\n Output: the dot-product (as a number) representing the degree of similarity\n between two senators' voting policies\n Example:\n >>> voting_dict = {'Fox-Epstein':[-1,-1,-1,1],'Ravella':[1,1,1,1]}\n >>> policy_compare('Fox-Epstein','Ravella', voting_dict)\n -2\n \"\"\"\n return sum([a * b for a, b in zip(voting_dict[sen_a], voting_dict[sen_b])])\n\n## Task 3\n\ndef most_similar(sen, voting_dict):\n \"\"\"\n Input: the last name of a senator, and a dictionary mapping senator names\n to lists representing their voting records.\n Output: the last name of the senator whose political mindset is most\n like the input senator (excluding, of course, the input senator\n him/herself). Resolve ties arbitrarily.\n Example:\n >>> vd = {'Klein': [1,1,1], 'Fox-Epstein': [1,-1,0], 'Ravella': [-1,0,0]}\n >>> most_similar('Klein', vd)\n 'Fox-Epstein'\n\n Note that you can (and are encouraged to) re-use you policy_compare procedure.\n \"\"\"\n\n most_similar_score = -len(voting_dict[sen])\n most_similar_sen = sen\n\n for senators in voting_dict.keys():\n if senators != sen:\n temp_score = policy_compare(sen, senators, voting_dict)\n if temp_score > most_similar_score:\n most_similar_score = temp_score\n most_similar_sen = senators\n return most_similar_sen\n\n## Task 4\n\ndef least_similar(sen, voting_dict):\n \"\"\"\n Input: the last name of a senator, and a dictionary mapping senator names\n to lists representing their voting records.\n Output: the last name of the senator whose political mindset is least like the input\n senator.\n Example:\n >>> vd = {'Klein': [1,1,1], 'Fox-Epstein': [1,-1,0], 'Ravella': [-1,0,0]}\n >>> least_similar('Klein', vd)\n 'Ravella'\n \"\"\"\n\n least_similar_score = len(voting_dict[sen])\n least_similar_sen = \"\"\n\n for senators in voting_dict.keys():\n if senators != sen:\n temp_score = policy_compare(sen, senators, voting_dict)\n if temp_score < least_similar_score:\n least_similar_score = temp_score\n least_similar_sen = senators\n return least_similar_sen\n\n## Task 5\n\nmost_like_chafee = most_similar('Chafee', create_voting_dict())\nleast_like_santorum = least_similar('Santorum', create_voting_dict())\n\n# Task 6\n\ndef find_average_similarity(sen, sen_set, voting_dict):\n \"\"\"\n Input: the name of a senator, a set of senator names, and a voting dictionary.\n Output: the average dot-product between sen and those in sen_set.\n Example:\n >>> vd = {'Klein': [1,1,1], 'Fox-Epstein': [1,-1,0], 'Ravella': [-1,0,0]}\n >>> find_average_similarity('Klein', {'Fox-Epstein','Ravella'}, vd)\n -0.5\n \"\"\"\n\n return sum([policy_compare(sen, s, voting_dict) for s in sen_set]) / len(sen_set)\n\ndef sen_Democrat_list():\n sen_set_D = []\n # Create voting set for Democrats only\n for line in voting_data:\n if line.split()[1] == 'D':\n sen_set_D.append(line.split()[0])\n return sen_set_D\n\ndef most_average_Democrat_fn():\n most_average = 0.0\n most_average_name = \"\"\n\n voting_dict = create_voting_dict()\n sen_set_d = sen_Democrat_list()\n\n # Calculate individual score\n for sen in sen_set_d:\n temp_set = list(sen_set_d)\n temp_set.remove(sen)\n temp_avg = find_average_similarity(sen, temp_set, voting_dict)\n if temp_avg > most_average:\n most_average = temp_avg\n most_average_name = sen\n return most_average_name\n\nmost_average_Democrat = 'Biden' # give the last name (or code that computes the last name)\n\n# Task 7\n\ndef find_average_record(sen_set, voting_dict):\n \"\"\"\n Input: a set of last names, a voting dictionary\n Output: a vector containing the average components of the voting records\n of the senators in the input set\n Example:\n >>> voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Ravella': [0,0,1]}\n >>> find_average_record({'Fox-Epstein','Ravella'}, voting_dict)\n [-0.5, -0.5, 0.0]\n \"\"\"\n\n average_voting = []\n\n for sen in sen_set:\n if not average_voting:\n average_voting = voting_dict[sen]\n else:\n average_voting = list(map(sum, zip(average_voting, voting_dict[sen])))\n\n average_voting = [i / len(sen_set) for i in average_voting]\n\n return average_voting\n\n# print (find_average_record(sen_Democrat_list(), create_voting_dict()))\naverage_Democrat_record = [-0.16279069767441862, -0.23255813953488372, 1.0, 0.8372093023255814, 0.9767441860465116, -0.13953488372093023, -0.9534883720930233, 0.813953488372093, 0.9767441860465116, 0.9767441860465116, 0.9069767441860465, 0.7674418604651163, 0.6744186046511628, 0.9767441860465116, -0.5116279069767442, 0.9302325581395349, 0.9534883720930233, 0.9767441860465116, -0.3953488372093023, 0.9767441860465116, 1.0, 1.0, 1.0, 0.9534883720930233, -0.4883720930232558, 1.0, -0.32558139534883723, -0.06976744186046512, 0.9767441860465116, 0.8604651162790697, 0.9767441860465116, 0.9767441860465116, 1.0, 1.0, 0.9767441860465116, -0.3488372093023256, 0.9767441860465116, -0.4883720930232558, 0.23255813953488372, 0.8837209302325582, 0.4418604651162791, 0.9069767441860465, -0.9069767441860465, 1.0, 0.9069767441860465, -0.3023255813953488] # (give the vector)\n\ndef find_most_similar_to_average_Democrat_record():\n voting_dict = create_voting_dict()\n average_Democrat_record_sum = sum(i for i in average_Democrat_record) / len(average_Democrat_record)\n sen_set = [ line.split()[0] for line in voting_data ]\n\n all_sen_average_similarity = {}\n\n for sen in sen_set:\n temp_avg = find_average_similarity(sen, sen_set, voting_dict)\n # all_sen_average_similarity[sen] = temp_avg / len(sen_set)\n all_sen_average_similarity[sen] = temp_avg\n\n temp = -1\n most_average_sen = \"\"\n for k, v in all_sen_average_similarity.items():\n if temp < v:\n temp = v\n most_average_sen = k\n return most_average_sen\n\n# No, it's not the same. This contains all senators (R & D). Task 6 only contains senators from democratic party.\n\n# Task 8\n\ndef bitter_rivals(voting_dict):\n \"\"\"\n Input: a dictionary mapping senator names to lists representing\n their voting records\n Output: a tuple containing the two senators who most strongly\n disagree with one another.\n Example:\n >>> voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Ravella': [0,0,1]}\n >>> bitter_rivals(voting_dict)\n ('Fox-Epstein', 'Ravella')\n \"\"\"\n\n sen_a = \"\"\n sen_b = \"\"\n strongly_disagree = float('inf')\n\n for sen in voting_dict.keys():\n least_sen = least_similar(sen, voting_dict)\n temp_disagree = policy_compare(sen, least_sen, voting_dict)\n if temp_disagree < strongly_disagree:\n strongly_disagree = temp_disagree\n sen_a = sen\n sen_b = least_sen\n return (sen_a, sen_b)","sub_path":"Coursera/Coding The Matrix/week1/politics_lab/politics_lab.py","file_name":"politics_lab.py","file_ext":"py","file_size_in_byte":8832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"333020634","text":"#===================================================================#\n# Tool Name: Galileo SAS IOM FVS Tool #\n# Version: 0.7 #\n# Edit by: Chris Liu 2018/03/24 #\n#===================================================================#\nimport sys\nimport datetime\nimport subprocess\nimport os\nimport configparser\nimport time\nimport ctypes\nimport serial\nimport serial.tools.list_ports\nimport shutil\n\nglobal VER\nVER = \"0.7\"\n\nglobal DEBUG_MODE\nDEBUG_MODE = True\n\nglobal FAIL_CONTINUE\nFAIL_CONTINUE = True\n\nglobal FMP_UBOOT_VER\nFMP_UBOOT_VER = \"0.0.0.16\"\n\nglobal FMP_OS_VER\nFMP_OS_VER = \"2015.11-svn5153\"\n\nglobal EXP_VER\nEXP_VER = \"0.77\"\n\nglobal IOC_VER\nIOC_VER = \"1.33\"\n\n#EXP 115200 J5 Right1\nglobal COM_PORT_EXP\nCOM_PORT_EXP = \"COM6\"\n\n#IOC 57600 J2 Left1\nglobal COM_PORT_IOC\nCOM_PORT_IOC = \"COM4\"\n\n#FMP 115200 J6 Right2\nglobal COM_PORT_FMP\nCOM_PORT_FMP = \"COM3\"\n\nglobal ROOT_DIR\nROOT_DIR = os.getcwd()\n\nglobal LOG_DIR\nLOG_DIR = os.path.join(ROOT_DIR, \"Log\")\n\nglobal SFC_DIR\nSFC_DIR = os.path.join(ROOT_DIR, \"SFC\")\n\nFONT_NONE = 0\nFONT_WHITE = 1\nFONT_RED = 2\nFONT_GREEN = 3\nFONT_YELLOW = 4\n\nPASS_BANNER = \"\"\"\n######## ### ###### ###### #### ####\n## ## ## ## ## ## ## ## #### ####\n## ## ## ## ## ## #### ####\n######## ## ## ###### ###### ## ##\n## ######### ## ##\n## ## ## ## ## ## ## #### ####\n## ## ## ###### ###### #### ####\n\"\"\"\n\nFAIL_BANNER = \"\"\"\n######## ### #### ## #### ####\n## ## ## ## ## #### ####\n## ## ## ## ## #### ####\n###### ## ## ## ## ## ##\n## ######### ## ##\n## ## ## ## ## #### ####\n## ## ## #### ######## #### ####\n\"\"\"\n\nPOWER_ON_BANNER = \"\"\"\n######## ####### ## ## ######## ######## ####### ## ##\n## ## ## ## ## ## ## ## ## ## ## ## ### ##\n## ## ## ## ## ## ## ## ## ## ## ## #### ##\n######## ## ## ## ## ## ###### ######## ## ## ## ## ##\n## ## ## ## ## ## ## ## ## ## ## ## ####\n## ## ## ## ## ## ## ## ## ## ## ## ###\n## ####### ### ### ######## ## ## ####### ## ##\n\"\"\"\n\nPPID_BANNER = \"\"\"\n######## ######## #### ########\n## ## ## ## ## ## ##\n## ## ## ## ## ## ##\n######## ######## ## ## ##\n## ## ## ## ##\n## ## ## ## ##\n## ## #### ########\n\"\"\"\n\nMAC_BANNER = \"\"\"\n## ## ### ######\n### ### ## ## ## ##\n#### #### ## ## ##\n## ### ## ## ## ##\n## ## ######### ##\n## ## ## ## ## ##\n## ## ## ## ######\n\"\"\"\n#===============================================================================\ndef Banner(msg):\n\tline_0 = \"#\" + \"=\"*78 + \"#\"\n\tline_1 = \"#\" + \" \"*78 + \"#\"\n\ttmp_str = \"#\" + msg.center(78) + \"#\"\n\n\tif(sys.platform == \"win32\"):\n\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x08)\n\t\tprint(\"\")\n\t\tprint(line_0)\n\t\tprint(line_1)\n\t\tprint(tmp_str)\n\t\tprint(line_1)\n\t\tprint(line_0)\n\t\tprint(\"\")\n\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x04)\n\telse:\n\t\tprint(\"\")\n\t\tprint(\"\\033[35;1m%s\\033[0m\"%(line_0))\n\t\tprint(\"\\033[35;1m%s\\033[0m\"%(line_1))\n\t\tprint(\"\\033[35;1m%s\\033[0m\"%(tmp_str))\n\t\tprint(\"\\033[35;1m%s\\033[0m\"%(line_1))\n\t\tprint(\"\\033[35;1m%s\\033[0m\"%(line_0))\n\t\tprint(\"\")\n#===============================================================================\ndef Banner_1(msg):\n\tif(sys.platform == \"win32\"):\n\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x08)\n\t\tprint(\"\")\n\t\tprint(msg)\n\t\tprint(\"\")\n\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x04)\n\telse:\n\t\tprint(\"\")\n\t\tprint(\"\\033[35;1m%s\\033[0m\"%(msg))\n\t\tprint(\"\")\n#===============================================================================\ndef Log(msg, color = FONT_WHITE):\n\ttmp = \"[%s] %s\\n\"%(datetime.datetime.strftime(datetime.datetime.now(), \"%y/%m/%d %H:%M:%S\"), msg)\n\n\ttry:\n\t\tf = open(LOG_FILE, \"a\")\n\t\tf.write(tmp)\n\t\tf.close()\n\texcept:\n\t\tprint(\"Logging Error!!\")\n\t\treturn\n\n\ttmp = tmp[:-1]\n\n\tif(color == FONT_RED):\n\t\tif(sys.platform == \"win32\"):\n\t\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x04 | 0x08)\n\t\t\tprint(tmp)\n\t\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x04)\n\t\telse:\n\t\t\tprint(\"\\033[31;1m%s\\033[0m\"%(tmp))\n\telif(color == FONT_GREEN):\n\t\tif(sys.platform == \"win32\"):\n\t\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x02 | 0x08)\n\t\t\tprint(tmp)\n\t\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x04)\n\t\telse:\n\t\t\tprint(\"\\033[32;1m%s\\033[0m\"%(tmp))\n\telif(color == FONT_YELLOW):\n\t\tif(sys.platform == \"win32\"):\n\t\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x02 | 0x04 | 0x08)\n\t\t\tprint(tmp)\n\t\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x04)\n\t\telse:\n\t\t\tprint(\"\\033[33;1m%s\\033[0m\"%(tmp))\n\telif(color == FONT_NONE):\n\t\tpass\n\telse:\n\t\ttry:\n\t\t\tprint(tmp)\n\t\texcept:\n\t\t\tprint(\"Logging Error!!\")\n#===============================================================================\ndef Show_Pass():\n\tLog(\"PASS\", FONT_GREEN)\n\n\ttest_log = os.path.join(LOG_DIR, \"%s_PASS_%s.txt\"%(PPID, datetime.datetime.strftime(datetime.datetime.now(), \"%y%m%d-%H%M%S\")))\n\tLog(\"Test Log: %s\"%(test_log), FONT_GREEN)\n\tshutil.move(LOG_FILE, test_log)\n\n\tif(sys.platform == \"win32\"):\n\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x02 | 0x08)\n\t\tprint(PASS_BANNER)\n\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x04)\n\telse:\n\t\tprint(\"\\033[32;1m%s\\033[0m\"%(PASS_BANNER))\n\n\tconfig = configparser.ConfigParser()\n\tconfig.read(os.path.join(SFC_DIR, \"SFC.ini\"))\n\tconfig[\"UUT\"][\"result\"] = \"PASS\"\n\tconfig[\"UUT\"][\"errormessage\"] = \"NA\"\n\tconfig[\"UUT\"][\"firmwarever\"] = \"[FMP:%s][Expander:%s][IOC:%s]\"%(FMP_OS_VER, EXP_VER, IOC_VER)\n\tconfig.write(open(os.path.join(SFC_DIR, \"SFC.ini\"), \"w\"))\n\n\tif(UUT_STATIONID != \"DBG-001\"):\n\t\tos.chdir(SFC_DIR)\n\t\tos.system(\"SFCTool.exe\")\n\t\tos.chdir(ROOT_DIR)\n\n\tos.system(\"pause\")\n\tsys.exit(0)\n#===============================================================================\ndef Show_Fail(error_msg):\n\tLog(\"FAIL: %s\"%(error_msg), FONT_RED)\n\n\ttest_log = os.path.join(LOG_DIR, \"%s_FAIL_%s.txt\"%(PPID, datetime.datetime.strftime(datetime.datetime.now(), \"%y%m%d-%H%M%S\")))\n\tLog(\"Test Log: %s\"%(test_log), FONT_RED)\n\tshutil.move(LOG_FILE, test_log)\n\n\tif(sys.platform == \"win32\"):\n\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x04 | 0x08)\n\t\tprint(FAIL_BANNER)\n\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x04)\n\telse:\n\t\tprint(\"\\033[31;1m%s\\033[0m\"%(FAIL_BANNER))\n\n\tconfig = configparser.ConfigParser()\n\tconfig.read(os.path.join(SFC_DIR, \"SFC.ini\"))\n\tconfig[\"UUT\"][\"result\"] = \"FAIL\"\n\tconfig[\"UUT\"][\"errormessage\"] = error_msg\n\tconfig[\"UUT\"][\"firmwarever\"] = \"[FMP:%s][Expander:%s][IOC:%s]\"%(FMP_OS_VER, EXP_VER, IOC_VER)\n\tconfig.write(open(os.path.join(SFC_DIR, \"SFC.ini\"), \"w\"))\n\n\tif(UUT_STATIONID != \"DBG-001\"):\n\t\tos.chdir(SFC_DIR)\n\t\tos.system(\"SFCTool.exe\")\n\t\tos.chdir(ROOT_DIR)\n\n\tos.system(\"pause\")\n\tsys.exit(-1)\n#===============================================================================\ndef Scan_PPID():\n\tBanner_1(PPID_BANNER)\n\n\tglobal PPID\n\tglobal LOG_FILE\n\n\twhile(1):\n\t\tPPID = input(\"Please Scan Board PPID!!\\n\")\n\t\tif(PPID == \"a\"):\n\t\t\tPPID = \"CN0PG5NRFCP0074Q0003X20\"\n\t\tif(len(PPID) == 23 and PPID[2:8] == \"0PG5NR\" and PPID[0:2] == \"CN\" and PPID[8:13] == \"FCP00\"):\n\t\t\tLOG_FILE = os.path.join(ROOT_DIR, \"%s.txt\"%PPID)\n\t\t\tLog(\"Galileo SAS IOM PPID!! (%s)\"%(PPID), FONT_YELLOW)\n\t\t\tScan_MAC()\n\t\t\tbreak\n\t\telse:\n\t\t\tprint(\"PPID is Wrong, Please Scan Again!!\")\n#===============================================================================\ndef Scan_MAC():\n\tBanner_1(MAC_BANNER)\n\n\tglobal MAC_LABEL\n\tglobal MAC_ETH0\n\tglobal MAC_ETH1\n\tglobal SAS_ADDR\n\n\twhile(1):\n\t\tMAC_LABEL = input(\"Please Scan Board MAC Label!!\\n\")\n\t\tif(MAC_LABEL == \"a\"):\n\t\t\tMAC_LABEL = \"D094660F94B4,D094660F94B5,D094660F94B6\"\n\t\tif(len(MAC_LABEL) == 38 and (MAC_LABEL[0:6] == MAC_LABEL[13:19] == MAC_LABEL[26:32] == \"D09466\")):\n\t\t\tMAC_ETH0 = ConvertMAC(MAC_LABEL[0:12])\n\t\t\tMAC_ETH1 = ConvertMAC(MAC_LABEL[13:25])\n\t\t\tSAS_ADDR = \"5\" + MAC_LABEL[26:32] + \"1\" + MAC_LABEL[32:38] + \"00\"\n\t\t\tif(DEBUG_MODE):\n\t\t\t\tLog(\"eth0 MAC Address: %s\"%(MAC_ETH0), FONT_YELLOW)\n\t\t\t\tLog(\"eth1 MAC Address: %s\"%(MAC_ETH1), FONT_YELLOW)\n\t\t\t\tLog(\"SAS Address: %s\"%(SAS_ADDR), FONT_YELLOW)\n\t\t\tbreak\n\t\telse:\n\t\t\tprint(\"MAC is Wrong, Please Scan Again!!\")\n#===============================================================================\ndef ConvertMAC(addr):\n\taddr = addr.upper()\n\treturn addr[0:2] + \":\" + addr[2:4] + \":\" + addr[4:6] + \":\" + addr[6:8] + \":\" + addr[8:10] + \":\" + addr[10:12]\n#===============================================================================\ndef Input_CMD_FMP(cmd, delay = 1):\n\tLog(\"Input FMP Command: %s\"%(cmd), FONT_WHITE)\n\n\ttry:\n\t\ts = serial.Serial(port = COM_PORT_FMP, baudrate = 115200, timeout = delay)\n\texcept:\n\t\tLog(\"Open FMP COM Port Fail!! (%s)\"%(COM_PORT_FMP), FONT_RED)\n\t\treturn False\n\n\tcmd = \"%s\\r\"%(cmd)\n\n\ts.write(cmd.encode(errors = \"ignore\"))\n\tret = s.readlines()\n\tfor i in range(len(ret)):\n\t\tret[i] = ret[i].decode(errors = \"ignore\").strip()\n\t\tif(DEBUG_MODE):\n\t\t\tLog(\"ret[%02d] %s\"%(i, ret[i]), FONT_WHITE)\n\n\ts.close()\n\n\treturn ret\n#===============================================================================\ndef Input_CMD_IOC(cmd, delay = 1):\n\tLog(\"Input IOC Command: %s\"%(cmd), FONT_WHITE)\n\n\ttry:\n\t\ts = serial.Serial(port = COM_PORT_IOC, baudrate = 57600, timeout = delay)\n\texcept:\n\t\tLog(\"Open IOC COM Port Fail!! (%s)\"%(COM_PORT_IOC), FONT_RED)\n\t\treturn False\n\n\tcmd = \"%s\\r\"%(cmd)\n\n\ts.write(cmd.encode(errors = \"ignore\"))\n\tret = s.readlines()\n\tfor i in range(len(ret)):\n\t\tret[i] = ret[i].decode(errors = \"ignore\").strip()\n\t\tif(DEBUG_MODE):\n\t\t\tLog(\"ret[%02d] %s\"%(i, ret[i]), FONT_WHITE)\n\n\ts.close()\n\n\treturn ret\n#===============================================================================\ndef Input_CMD_EXP(cmd, delay = 1):\n\tLog(\"Input EXP Command: %s\"%(cmd), FONT_WHITE)\n\n\ttry:\n\t\ts = serial.Serial(port = COM_PORT_EXP, baudrate = 115200, timeout = delay)\n\texcept:\n\t\tLog(\"Open EXP COM Port Fail!! (%s)\"%(COM_PORT_EXP), FONT_RED)\n\t\treturn False\n\n\tcmd = \"%s\\r\"%(cmd)\n\n\ts.write(cmd.encode(errors = \"ignore\"))\n\tret = s.readlines()\n\tfor i in range(len(ret)):\n\t\tret[i] = ret[i].decode(errors = \"ignore\").strip()\n\t\tif(DEBUG_MODE):\n\t\t\tLog(\"ret[%02d] %s\"%(i, ret[i]), FONT_WHITE)\n\n\ts.close()\n\n\treturn ret\n#===============================================================================\ndef Enter_EXP_CLI():\n\t'''Enter SAS Expander CLI'''\n\n\tflag = False\n\n\ttimeout_5s = 20\n\tfor i in range(timeout_5s):\n\t\tret = Input_CMD_EXP(\"help\")\n\t\tif(ret == False):\n\t\t\treturn False\n\n\t\tif(len(ret) > 1 and \"=>\" in ret[-1]):\n\t\t\tLog(\"Enter SAS Expander CLI\", FONT_YELLOW)\n\t\t\tflag = True\n\t\t\tbreak\n\n\t\tif(i < timeout_5s - 1):\n\t\t\ttime.sleep(5)\n\t\t\tprint((\"%s secs...\")%(5*(timeout_5s - i)))\n\t\telse:\n\t\t\tLog(\"Enter SAS Expander CLI Fail (Timeout)\", FONT_RED)\n\t\t\treturn False\n\n\tif(flag):\n\t\tLog(\"Enter_EXP_CLI Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Enter_EXP_CLI Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_EXP_FW_Ver():\n\t'''Check SAS Expander FW Version'''\n\n\tflag = False\n\n\tret = Input_CMD_EXP(\"version\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"Expander Firmware Version\" in i and EXP_VER in i):\n\t\t\tflag = True\n\n\tif(flag):\n\t\tLog(\"Check_EXP_FW_Ver Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Check_EXP_FW_Ver Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_EXP_Phy_Info():\n\t'''Check SAS Expander PHY Information'''\n\n\t#Phy00~07: SAS IOC\n\t#Phy08~11: SLED1\n\t#Phy12~15: SLED2\n\t#Phy16~19: SLED3\n\t#Phy20~23: SLED4\n\t#Phy24~27: SLED5\n\t#Phy28~31: SLED6\n\t#Phy32~35: SLED7\n\t#Phy36~39: SLED8\n\t#Phy40~43: JBOD Connector Port1\n\t#Phy44~47: JBOD Connector Port2\n\t#Phy48~51: JBOD Connector Port3\n\t#Phy52~55: JBOD Connector Port4\n\t#Phy56~59: Switch Stacking Connector Port1\n\t#Phy60~63: Switch Stacking Connector Port2\n\t#Phy64~67: Unused\n\n\tsas_ioc = list(range(0, 8))\n\tsled1 = list(range(8, 12))\n\tsled2 = list(range(12, 16))\n\tsled3 = list(range(16, 20))\n\tsled4 = list(range(20, 24))\n\tsled5 = list(range(24, 28))\n\tsled6 = list(range(28, 32))\n\tsled7 = list(range(32, 36))\n\tsled8 = list(range(36, 40))\n\tjbod_port1 = list(range(40, 44))\n\tjbod_port2 = list(range(44, 48))\n\tjbod_port3 = list(range(48, 52))\n\tjbod_port4 = list(range(52, 56))\n\tss_port1 = list(range(56, 60))\n\tss_port2 = list(range(60, 64))\n\n\tphy_list = sas_ioc + sled1 + sled2 + sled3 + sled4 + sled5 + sled6 + sled7 + sled8 + ss_port1 + ss_port2 + jbod_port2 + jbod_port3 + jbod_port4\n\n\tLog(\"Show All Phy Status\", FONT_YELLOW)\n\tret = Input_CMD_EXP(\"phy id=all enable\")\n\ttime.sleep(3)\n\n\tret = Input_CMD_EXP(\"phy id=all showstats\")\n\tif(ret == False):\n\t\treturn False\n\n\tflag_status = True\n\tflag_speed = True\n\n\tfor index in phy_list:\n\t\tfor i in ret:\n\t\t\tif(\"| %02d|\"%(index) in i):\n\t\t\t\tif(\"Linked\" not in i):\n\t\t\t\t\tflag_status = False\n\t\t\t\tif(\"12.0\" not in i):\n\t\t\t\t\tflag_speed = False\n\n\t\tif(flag_status and flag_speed):\n\t\t\tLog(\"Check Phy%02d PASS\"%(index), FONT_GREEN)\n\t\t\tcontinue\n\t\telse:\n\t\t\tLog(\"Check Phy%02d FAIL\"%(index), FONT_RED)\n\t\t\tbreak\n\n\tif(flag_status and flag_speed):\n\t\tLog(\"Check_EXP_Phy_Info Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_status == False):\n\t\t\tLog(\"Check_EXP_Phy_Info Fail (Phy%d Status)\"%(index), FONT_RED)\n\t\tif(flag_speed == False):\n\t\t\tLog(\"Check_EXP_Phy_Info Fail (Phy%d Speed)\"%(index), FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Clear_EXP_Phy_Error():\n\t'''Clear SAS Expander Phy Error Count'''\n\n\tss_port2 = list(range(0, 4))\n\tss_port1 = list(range(4, 8))\n\n\tInput_CMD_EXP(\"sdkcli on\")\n\n\tflag = True\n\n\tphy_list = list(range(68))\n\t#phy_list = ss_port1 + ss_port2 + list(range(40,64))\n\n\tfor i in phy_list:\n\t\tLog(\"Clear Phy%d Error Count\"%(i), FONT_YELLOW)\n\t\tret = Input_CMD_EXP(\"err_cnts %d clear\"%(i))\n\t\tif(ret == False):\n\t\t\treturn False\n\n\t\tif(\"done\" not in ret[1]):\n\t\t\tflag = False\n\t\t\tbreak\n\n\tInput_CMD_EXP(\"sdkcli off\")\n\n\tif(flag):\n\t\tLog(\"Clear SAS_Expander Phy Error Count Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Clear SAS_Expander Phy Error Count Fail (Phy%d)\"%(i), FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_EXP_Phy_Error():\n\t'''Check SAS Expander Phy Error Count'''\n\n\tss_port2 = list(range(0, 4))\n\tss_port1 = list(range(4, 8))\n\n\tInput_CMD_EXP(\"sdkcli on\")\n\n\tflag = False\n\n\tphy_list = list(range(68))\n\t#phy_list = ss_port1 + ss_port2 + list(range(40,64))\n\n\tfor i in phy_list:\n\t\tflag = True\n\n\t\tLog(\"Check Phy%d Error Count\"%(i), FONT_YELLOW)\n\t\tret = Input_CMD_EXP(\"err_cnts %d read\"%(i))\n\t\tif(ret == False):\n\t\t\treturn False\n\t\t#CRC Error\n\t\terror_list = ret[3].split()[10:]\n\t\tfor j in error_list:\n\t\t\tif(j != \"0x00000000\"):\n\t\t\t\tflag = False\n\t\t\t\tbreak\n\n\t\tif(flag == False):\n\t\t\tbreak\n\n\tInput_CMD_EXP(\"sdkcli off\")\n\n\tif(flag):\n\t\tLog(\"Check SAS_Expander Phy Error Count Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Check SAS_Expander Phy Error Count Fail (Phy%d)\"%(i), FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_EXP_I2C():\n\t'''Check SAS Expander I2C Function'''\n\n\tflag = False\n\n\tInput_CMD_EXP(\"sdkcli on\")\n\n\t#EEPROM: I2C Bus 0 Address 0xAE (0x57)\n\tret = Input_CMD_EXP(\"rd_seeprom 0x0A 0x57 0x00 1 16\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"01 01 00 10 00 00 00 ee 01 44 45 4c 4c 00 00 00\" in i):\n\t\t\tflag = True\n\n\tInput_CMD_EXP(\"sdkcli off\")\n\n\tif(flag):\n\t\tLog(\"Check_EXP_I2C Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Check_EXP_I2C Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_EXP_SAS_Addr():\n\t'''Check SAS Expander SAS Address'''\n\n\tglobal PPID\n\n\tflag_address = False\n\tflag_offset = False\n\tflag_sn = False\n\n\tsn = PPID[0:2] + PPID[8:20]\n\n\tret = Input_CMD_EXP(\"version\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"Product Serial Number\" in i and sn in i):\n\t\t\tflag_sn = True\n\n\tret = Input_CMD_EXP(\"expander show\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"SasAddress:\" in i and \"0x500056B8\" in i):\n\t\t\tflag_address = True\n\t\tif(\"SasAddressOffset\" in i and \"0x0000007F\" in i):\n\t\t\tflag_offset = True\n\n\tif(flag_address and flag_offset and flag_sn):\n\t\tLog(\"Check_EXP_SAS_Addr Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_address == False):\n\t\t\tLog(\"Check_EXP_SAS_Addr Fail (Address)\", FONT_RED)\n\t\tif(flag_offset == False):\n\t\t\tLog(\"Check_EXP_SAS_Addr Fail (Offset)\", FONT_RED)\n\t\tif(flag_sn == False):\n\t\t\tLog(\"Check_EXP_SAS_Addr Fail (Serial Number)\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Enter_IOC_CLI():\n\t'''Enter SAS IOC CLI'''\n\n\tflag = False\n\n\ttimeout_5s = 20\n\tfor i in range(timeout_5s):\n\t\tret = Input_CMD_IOC(\"help\")\n\t\tif(ret == False):\n\t\t\treturn False\n\n\t\tif(len(ret) > 1 and \"Available commands are:\" in ret[1]):\n\t\t\tLog(\"Enter SAS IOC CLI\", FONT_YELLOW)\n\t\t\tflag = True\n\t\t\tbreak\n\n\t\tif(i < timeout_5s - 1):\n\t\t\ttime.sleep(5)\n\t\t\tprint((\"%s secs...\")%(5*(timeout_5s - i)))\n\t\telse:\n\t\t\tLog(\"Enter SAS IOC CLI Fail (Timeout)\", FONT_RED)\n\t\t\treturn False\n\n\tif(flag):\n\t\tLog(\"Enter_IOC_CLI Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Enter_IOC_CLI Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_IOC_Mode():\n\t'''Check SAS IOC Mode'''\n\n\tflag = False\n\n\tret = Input_CMD_IOC(\"ctrlr show_mode\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"HBA, SSP Initiator\" in i):\n\t\t\tflag = True\n\n\tif(flag):\n\t\tLog(\"Check_IOC_Mode Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Check_IOC_Mode Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_IOC_FW_Ver():\n\t'''Check SAS IOC FW Version'''\n\n\tflag_firmware = False\n\tflag_bootblock = False\n\n\tret = Input_CMD_IOC(\"show version\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"Firmware version\" in i and IOC_VER in i):\n\t\t\tflag_firmware = True\n\t\tif(\"Bootblock version\" in i and \"6.02\" in i):\n\t\t\tflag_bootblock = True\n\n\tif(flag_firmware and flag_bootblock):\n\t\tLog(\"Check_IOC_FW_Ver Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_firmware == False):\n\t\t\tLog(\"Check_IOC_FW_Ver Fail (Firmware Version)\", FONT_RED)\n\t\tif(flag_bootblock == False):\n\t\t\tLog(\"Check_IOC_FW_Ver Fail (Bootblock Version)\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_IOC_Phy_Info():\n\t'''Check SAS IOC PHY Information'''\n\n\tflag = False\n\n\tret = Input_CMD_IOC(\"phy show_info\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"Link Rates\" in i and \"BBBBBBBB000000000000000000\" in i):\n\t\t\tflag = True\n\n\tif(flag):\n\t\tLog(\"Check_IOC_Phy_Info Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Check_IOC_Phy_Info Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_IOC_PCIe():\n\t'''Check SAS IOC PCIe Information'''\n\n\tflag_rev = False\n\tflag_lane = False\n\tflag_rate = False\n\n\tret = Input_CMD_IOC(\"pci show\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"rev=1\" in i):\n\t\t\tflag_rev = True\n\t\tif(\"ln=1\" in i):\n\t\t\tflag_lane = True\n\t\tif(\"rate=5.0\" in i):\n\t\t\tflag_rate = True\n\n\tif(flag_rev and flag_lane and flag_rate):\n\t\tLog(\"Check_IOC_PCIe Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_rev == False):\n\t\t\tLog(\"Check_IOC_PCIe Fail (PCIe Revision)\", FONT_RED)\n\t\tif(flag_lane == False):\n\t\t\tLog(\"Check_IOC_PCIe Fail (PCIe Lanes)\", FONT_RED)\n\t\tif(flag_rate == False):\n\t\t\tLog(\"Check_IOC_PCIe Fail (PCIe Rate)\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_IOC_I2C():\n\t'''Check SAS IOC I2C Function (SEEPROM)'''\n\n\tflag_bus1 = False\n\tflag_bus2 = False\n\tflag_bus7 = False\n\n\t#Bus1: bootstrap\n\tret = Input_CMD_IOC(\"hal i2c read 1 0 256\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"0x00F0:A0 8D 4C 7A 00 00 00 64 A0 8D 44 2C 00 00 00 00\" in i):\n\t\t\tflag_bus1 = True\n\n\t#Bus2: host_nvram\n\tret = Input_CMD_IOC(\"hal i2c read 2 0 256\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"0x00F0:00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\" in i):\n\t\t\tflag_bus2 = True\n\n\t#Bus7: local_nvram\n\tret = Input_CMD_IOC(\"hal i2c read 7 0 256\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"0x00F0:00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\" in i):\n\t\t\tflag_bus7 = True\n\n\tif(flag_bus1 and flag_bus2 and flag_bus7):\n\t\tLog(\"Check_IOC_I2C Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_bus1 == False):\n\t\t\tLog(\"Check_IOC_I2C Fail (Bus1: bootstrap)\", FONT_RED)\n\t\tif(flag_bus2 == False):\n\t\t\tLog(\"Check_IOC_I2C Fail (Bus2: host_nvram)\", FONT_RED)\n\t\tif(flag_bus7 == False):\n\t\t\tLog(\"Check_IOC_I2C Fail (Bus7: local_nvram)\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Wait_FMP_Serial():\n\t'''Waiting for FMP Serial Port Ready'''\n\n\tglobal COM_PORT_FMP\n\tglobal COM_PORT_IOC\n\tglobal COM_PORT_EXP\n\n\tflag_fmp = False\n\tflag_ioc = False\n\tflag_exp = False\n\n\tBanner_1(POWER_ON_BANNER)\n\tLog(\"System Power On...\", FONT_YELLOW)\n\n\tretry_cnt = 30\n\tfor i in range(retry_cnt):\n\t\ttime.sleep(1)\n\t\tports = list(serial.tools.list_ports.comports())\n\n\t\tfor (com, name, usb) in ports:\n\t\t\t#XR21B1424 USB UART Ch A\n\t\t\tif(\"Ch A\" in name):\n\t\t\t\tCOM_PORT_EXP = com\n\t\t\t\tflag_exp = True\n\t\t\t\tLog(\"Expander COM Port: %s\"%(com), FONT_YELLOW)\n\t\t\t#XR21B1424 USB UART Ch B\n\t\t\tif(\"Ch B\" in name):\n\t\t\t\tCOM_PORT_IOC = com\n\t\t\t\tflag_ioc = True\n\t\t\t\tLog(\"IOC COM Port: %s\"%(com), FONT_YELLOW)\n\t\t\t#XR21B1424 USB UART Ch D\n\t\t\tif(\"Ch D\" in name):\n\t\t\t\tCOM_PORT_FMP = com\n\t\t\t\tflag_fmp = True\n\t\t\t\tLog(\"FMP COM Port: %s\"%(com), FONT_YELLOW)\n\n\t\tif(flag_fmp and flag_ioc and flag_exp):\n\t\t\tbreak\n\t\telse:\n\t\t\tLog(\"COM Port Not Ready!! Retry...\", FONT_RED)\n\n\t\tif(i == retry_cnt - 1):\n\t\t\tLog(\"Wait_FMP_Serial Fail (Timeout)\", FONT_RED)\n\t\t\tbreak\n\n\tif(flag_fmp and flag_ioc and flag_exp):\n\t\tLog(\"Wait_FMP_Serial Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_fmp == False):\n\t\t\tLog(\"Wait_FMP_Serial Fail (FMP)\", FONT_RED)\n\t\tif(flag_ioc == False):\n\t\t\tLog(\"Wait_FMP_Serial Fail (IOC)\", FONT_RED)\n\t\tif(flag_exp == False):\n\t\t\tLog(\"Wait_FMP_Serial Fail (EXP)\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Enter_FMP_UBoot():\n\t'''Enter FMP UBoot'''\n\n\tflag_login = False\n\tflag_pcie = False\n\tflag_copt = True\n\n\tBanner_1(POWER_ON_BANNER)\n\tLog(\"System Power On...\", FONT_YELLOW)\n\n\ttry:\n\t\ts = serial.Serial(port = COM_PORT_FMP, baudrate = 115200, timeout = 1)\n\texcept:\n\t\tLog(\"Open FMP COM Port Fail!! (%s)\"%(COM_PORT_FMP), FONT_RED)\n\t\treturn False\n\n\ts.write(\"\\r\".encode(errors = \"ignore\"))\n\n\tstart = time.time()\n\twhile 1:\n\t\tret = s.readline().decode(errors = \"ignore\").strip()\n\n\t\tif(DEBUG_MODE):\n\t\t\tLog(ret, FONT_WHITE)\n\n\t\tif(\"PCI-e 0 (IF 0 - bus 0) Root Complex Interface, Detected Link X1, GEN 2.0\" in ret):\n\t\t\tflag_pcie = True\n\n\t\tif(\"Copt calculation failed, no valid window for bus 0\" in ret):\n\t\t\tflag_copt = False\n\n\t\tif(\"Success sending control code.\" in ret):\n\t\t\ttime.sleep(1)\n\t\t\ts.write(\"\\r\".encode(errors = \"ignore\"))\n\n\t\tif(\"Hit any key to stop autoboot\" in ret):\n\t\t\ts.write(\"\\r\".encode(errors = \"ignore\"))\n\n\t\tif(\"Marvell>>\" in ret):\n\t\t\tif(flag_pcie == True):\n\t\t\t\tLog(\"Into Marvell\", FONT_YELLOW)\n\t\t\t\tflag_login = True\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tLog(\"Booting speed is too fast , need to reboot!!\", FONT_YELLOW)\n\t\t\t\ts.write(\"reset\\r\".encode(errors = \"ignore\"))\n\n\t\tif((time.time() - start) > 120):\n\t\t\tLog(\"Enter_FMP_UBoot Fail (Timeout)\", FONT_RED)\n\t\t\treturn False\n\n\ts.close()\n\n\tif(flag_login and flag_pcie and flag_copt):\n\t\tLog(\"Enter_FMP_UBoot Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_login == False):\n\t\t\tLog(\"Enter_FMP_UBoot Fail (Login)\", FONT_RED)\n\t\tif(flag_pcie == False):\n\t\t\tLog(\"Enter_FMP_UBoot Fail (PCIe)\", FONT_RED)\n\t\tif(flag_copt == False):\n\t\t\tLog(\"Enter_FMP_UBoot Fail (Copt)\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_FMP_UBoot_Ver():\n\t'''Check FMP UBoot Version'''\n\n\tflag = False\n\n\tret = Input_CMD_FMP(\"version\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(FMP_UBOOT_VER in i):\n\t\t\tflag = True\n\n\tif(flag):\n\t\tLog(\"Check_FMP_UBoot_Ver Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Check_FMP_UBoot_Ver Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_FMP_eMMC():\n\t'''Check FMP eMMC Function under UBoot'''\n\n\tflag_device = False\n\tflag_version = False\n\tflag_size = False\n\n\tInput_CMD_FMP(\"mmc rescan\")\n\n\tret = Input_CMD_FMP(\"mmcinfo\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"Device\" in i and \"mv_sdh\" in i):\n\t\t\tflag_device = True\n\t\tif(\"MMC version\" in i and \"4.0\" in i):\n\t\t\tflag_version = True\n\t\tif(\"Capacity\" in i and \"7.3 GiB\" in i):\n\t\t\tflag_size = True\n\n\tif(flag_device and flag_version and flag_size):\n\t\tLog(\"Check_FMP_eMMC Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_device == False):\n\t\t\tLog(\"Check_FMP_eMMC Fail (Device)\", FONT_RED)\n\t\tif(flag_version == False):\n\t\t\tLog(\"Check_FMP_eMMC Fail (MMC version)\", FONT_RED)\n\t\tif(flag_size == False):\n\t\t\tLog(\"Check_FMP_eMMC Fail (Capacity)\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_FMP_SPI():\n\t'''Check FMP SPI Function under UBoot'''\n\n\tflag_info = False\n\tflag_size = False\n\n\tInput_CMD_FMP(\"sf probe\")\n\n\tret = Input_CMD_FMP(\"flash_part_print\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"Detected W25Q32 with page size 4 KiB, total 4 MiB\" in i):\n\t\t\tflag_info = True\n\t\tif(\"Spi flash size\" in i and \"8MB\" in i):\n\t\t\tflag_size = True\n\n\tif(flag_info and flag_size):\n\t\tLog(\"Check_FMP_SPI Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_info == False):\n\t\t\tLog(\"Check_FMP_SPI Fail (Information)\", FONT_RED)\n\t\tif(flag_size == False):\n\t\t\tLog(\"Check_FMP_SPI Fail (Size)\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_FMP_PCIe():\n\t'''Check FMP PCIe Function under UBoot'''\n\n\tflag_device1 = False\n\tflag_device2 = False\n\n\tret = Input_CMD_FMP(\"sp\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\t#Mass storage controller\n\t\tif(\"Bus: 0 Device: 0 Func: 0 Vendor ID: 9005 Device ID: 28f\" in i):\n\t\t\tflag_device1 = True\n\t\t#Memory controller\n\t\tif(\"Bus: 0 Device: 1 Func: 0 Vendor ID: 11ab Device ID: 6810\" in i):\n\t\t\tflag_device2 = True\n\n\tif(flag_device1 and flag_device2):\n\t\tLog(\"Check_FMP_PCIe Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_device1 == False):\n\t\t\tLog(\"Check_FMP_PCIe Fail (Mass storage controller)\", FONT_RED)\n\t\tif(flag_device2 == False):\n\t\t\tLog(\"Check_FMP_PCIe Fail (Memory controller)\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_FMP_I2C():\n\t'''Check FMP I2C Function under UBoot'''\n\n\tflag_bus0 = False\n\tflag_bus1 = False\n\n\t#I2C Bus0\n\tInput_CMD_FMP(\"i2c dev 0\")\n\n\tret = Input_CMD_FMP(\"i2c probe\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"32 64\" in i):\n\t\t\tflag_bus0 = True\n\n\t#I2C Bus1\n\tInput_CMD_FMP(\"i2c dev 1\")\n\n\tret = Input_CMD_FMP(\"i2c probe\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"34 35 37 41 64 78\" in i):\n\t\t\tflag_bus1 = True\n\n\tif(flag_bus0 and flag_bus1):\n\t\tLog(\"Check_FMP_I2C Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_bus0 == False):\n\t\t\tLog(\"Check_FMP_I2C Fail (Bus0)\", FONT_RED)\n\t\tif(flag_bus1 == False):\n\t\t\tLog(\"Check_FMP_I2C Fail (Bus1)\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Enter_FMP_Kernel():\n\t'''Enter FMP Kernel'''\n\n\tflag = False\n\n\tInput_CMD_FMP(\"boot\")\n\n\ttry:\n\t\ts = serial.Serial(port = COM_PORT_FMP, baudrate = 115200, timeout = 1)\n\texcept:\n\t\tLog(\"Open FMP COM Port Fail!! (%s)\"%(COM_PORT_FMP), FONT_RED)\n\t\treturn False\n\n\tstart = time.time()\n\twhile 1:\n\t\tret = s.readline().decode(errors = \"ignore\").strip()\n\t\tif(DEBUG_MODE):\n\t\t\tLog(ret, FONT_WHITE)\n\n\t\tif(\"Sending ICM Ready\" in ret):\n\t\t\ts.write(\"\\r\".encode(errors = \"ignore\"))\n\n\t\tif(\"VSM>\" in ret):\n\t\t\tLog(\"Enter Linux\", FONT_YELLOW)\n\t\t\tbreak\n\n\t\tif((time.time() - start) > 240):\n\t\t\tbreak\n\n\ts.close()\n\n\tret = Input_CMD_FMP(\"++rootdebug\")\n\tfor i in ret:\n\t\tif(\"Starting rootdebug shell\" in i):\n\t\t\tflag = True\n\n\tif(flag):\n\t\tLog(\"Enter_FMP_Kernel Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Enter_FMP_Kernel Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_FMP_HW():\n\t'''Check FMP HW Information'''\n\n\tflag_cpu_model = False\n\tflag_cpu_family = False\n\tflag_mem_size = False\n\tflag_fw_ver = False\n\tflag_mmc_info = False\n\tflag_i2c_fred = False\n\tflag_i2c_expander = False\n\tflag_mac0 = False\n\tflag_mac1 = False\n\tflag_eth0_speed = False\n\tflag_eth0_status = False\n\tflag_eth1_speed = False\n\tflag_eth1_status = False\n\tflag_pcie_id = False\n\tflag_pcie_status = False\n\tflag_ioc_info = False\n\n\tret = Input_CMD_FMP(\"cat /proc/cpuinfo | grep model\")\n\tfor i in ret:\n\t\tif(\"ARMv7 Processor rev 1 (v7l)\" in i):\n\t\t\tflag_cpu_model = True\n\n\tret = Input_CMD_FMP(\"cat /proc/cpuinfo | grep Hardware\")\n\tfor i in ret:\n\t\tif(\"Marvell Armada 380/381/382/383/384/385/388 (Device Tree)\" in i):\n\t\t\tflag_cpu_family = True\n\n\tret = Input_CMD_FMP(\"cat /proc/meminfo | grep MemTotal\")\n\tfor i in ret:\n\t\tif(\"2069808 kB\" in i):\n\t\t\tflag_mem_size = True\n\n\tret = Input_CMD_FMP(\"cat /etc/os-release\")\n\tfor i in ret:\n\t\tif(FMP_OS_VER in i):\n\t\t\tflag_fw_ver = True\n\n\tret = Input_CMD_FMP(\"fdisk -l /dev/mmcblk0 | grep /dev/mmcblk0:\")\n\tfor i in ret:\n\t\tif(\"7.3 GiB\" in i):\n\t\t\tflag_mmc_info = True\n\n\tret = Input_CMD_FMP(\"/opt/vsm/bin/i2ctool 1 emic r 0x7402 8\")\n\tfor i in ret:\n\t\tif(\"00 00 00 00 00 00 00 00\" in i):\n\t\t\tflag_i2c_fred = True\n\n\tret = Input_CMD_FMP(\"/opt/vsm/bin/i2ctool 1 exp1 r 0 16\")\n\tfor i in ret:\n\t\tif(\"00 00 00 00 00 00 02 01 00 fd 03 ff ff ff ff ff\" in i):\n\t\t\tflag_i2c_expander = True\n\n\tret = Input_CMD_FMP(\"ifconfig -a eth0 | grep 'HWaddr' | awk '{ print $5}'\")\n\tfor i in ret:\n\t\tif(MAC_ETH0 in i):\n\t\t\tflag_mac0 = True\n\n\tret = Input_CMD_FMP(\"ifconfig -a eth1 | grep 'HWaddr' | awk '{ print $5}'\")\n\tfor i in ret:\n\t\tif(MAC_ETH1 in i):\n\t\t\tflag_mac1 = True\n\n\tret = Input_CMD_FMP(\"ethtool eth0\")\n\tfor i in ret:\n\t\tif(\"Speed: 1000Mb/s\" in i):\n\t\t\tflag_eth0_speed = True\n\t\tif(\"Link detected: yes\" in i):\n\t\t\tflag_eth0_status = True\n\n\tret = Input_CMD_FMP(\"ethtool eth1\")\n\tfor i in ret:\n\t\tif(\"Speed: 1000Mb/s\" in i):\n\t\t\tflag_eth1_speed = True\n\t\tif(\"Link detected: yes\" in i):\n\t\t\tflag_eth1_status = True\n\n\tret = Input_CMD_FMP(\"lspci -vv -x -s 01:00.0\")\n\tfor i in ret:\n\t\tif(\"00: 05 90 8f 02\" in i):\n\t\t\tflag_pcie_id = True\n\t\tif(\"LnkSta:\" in i and \"Speed 5GT/s, Width x1\" in i):\n\t\t\tflag_pcie_status = True\n\n\tret = Input_CMD_FMP(\"/opt/vsm/bin/iocutil controllerinfo\")\n\tfor i in ret:\n\t\tif(\"Product ID\" in i and \"IOC Gilgamesh\" in i):\n\t\t\tflag_ioc_info = True\n\n\tif(flag_cpu_model and flag_cpu_family and flag_mem_size and flag_fw_ver and flag_mmc_info and flag_i2c_fred and flag_i2c_expander and flag_mac0 and flag_mac1 and flag_eth0_speed and flag_eth0_status and flag_eth1_speed and flag_eth1_status and flag_pcie_id and flag_pcie_status and flag_ioc_info):\n\t\tLog(\"Check_FMP_HW Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_cpu_model == False):\n\t\t\tLog(\"Check_FMP_HW Fail (CPU Model)\", FONT_RED)\n\t\tif(flag_cpu_family == False):\n\t\t\tLog(\"Check_FMP_HW Fail (CPU Family)\", FONT_RED)\n\t\tif(flag_mem_size == False):\n\t\t\tLog(\"Check_FMP_HW Fail (Memory Size)\", FONT_RED)\n\t\tif(flag_fw_ver == False):\n\t\t\tLog(\"Check_FMP_HW Fail (Version)\", FONT_RED)\n\t\tif(flag_mmc_info == False):\n\t\t\tLog(\"Check_FMP_HW Fail (eMMC Info)\", FONT_RED)\n\t\tif(flag_i2c_fred == False):\n\t\t\tLog(\"Check_FMP_HW Fail (FreD I2C)\", FONT_RED)\n\t\tif(flag_i2c_expander == False):\n\t\t\tLog(\"Check_FMP_HW Fail (SAS Expander I2C)\", FONT_RED)\n\t\tif(flag_mac0 == False):\n\t\t\tLog(\"Check_FMP_HW Fail (eth0 MAC Address)\", FONT_RED)\n\t\tif(flag_mac1 == False):\n\t\t\tLog(\"Check_FMP_HW Fail (eth1 MAC Address)\", FONT_RED)\n\t\tif(flag_eth0_speed == False):\n\t\t\tLog(\"Check_FMP_HW Fail (eth0 Speed)\", FONT_RED)\n\t\tif(flag_eth0_status == False):\n\t\t\tLog(\"Check_FMP_HW Fail (eth0 Status)\", FONT_RED)\n\t\tif(flag_eth1_speed == False):\n\t\t\tLog(\"Check_FMP_HW Fail (eth1 Speed)\", FONT_RED)\n\t\tif(flag_eth1_status == False):\n\t\t\tLog(\"Check_FMP_HW Fail (eth1 Status)\", FONT_RED)\n\t\tif(flag_pcie_id == False):\n\t\t\tLog(\"Check_FMP_HW Fail (SAS IOC PCIe VID/DID)\", FONT_RED)\n\t\tif(flag_pcie_status == False):\n\t\t\tLog(\"Check_FMP_HW Fail (SAS IOC PCIe Link Speed/Width)\", FONT_RED)\n\t\tif(flag_ioc_info == False):\n\t\t\tLog(\"Check_FMP_HW Fail (IOC Information)\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_FMP_FW():\n\t'''Check FMP Firmware Version'''\n\n\tflag_vsm = False\n\tflag_cpld = False\n\tflag_expander = False\n\tflag_ioc = False\n\tflag_uboot = False\n\n\tret = Input_CMD_FMP(\"/opt/vsm/bin/dbgdiag rominfo\", 3)\n\tfor i in ret:\n\t\tif(\"12G VSM FW\" in i and \"0.2.7.17\" in i):\n\t\t\tflag_vsm = True\n\t\tif(\"Cpld FW\" in i and \"0.3.1\" in i):\n\t\t\tflag_cpld = True\n\t\tif(\"Expander FW\" in i and \"002.0.77.000\" in i):\n\t\t\tflag_expander = True\n\t\tif(\"IOC FW\" in i and \"1.32.0.0014\" in i):\n\t\t\tflag_ioc = True\n\t\tif(\"UBoot FW\" in i and \"0.0.0.16\" in i):\n\t\t\tflag_uboot = True\n\n\tif(flag_vsm and flag_cpld and flag_expander and flag_ioc and flag_uboot):\n\t\tLog(\"Check_FMP_FW Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_vsm == False):\n\t\t\tLog(\"Check_FMP_FW Fail (VSM)\", FONT_RED)\n\t\tif(flag_cpld == False):\n\t\t\tLog(\"Check_FMP_FW Fail (CPLD)\", FONT_RED)\n\t\tif(flag_expander == False):\n\t\t\tLog(\"Check_FMP_FW Fail (Expander)\", FONT_RED)\n\t\tif(flag_ioc == False):\n\t\t\tLog(\"Check_FMP_FW Fail (IOC)\", FONT_RED)\n\t\tif(flag_uboot == False):\n\t\t\tLog(\"Check_FMP_FW Fail (UBoot)\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_FMP_GPIO():\n\t'''Check FMP GPIO Strapping'''\n\n\tflag_GPIO10 = False\n\tflag_GPIO13 = False\n\tflag_GPIO14 = False\n\tflag_GPIO15 = False\n\tflag_GPIO16 = False\n\tflag_GPIO17 = False\n\tflag_GPIO18 = False\n\tflag_GPIO19 = False\n\tflag_GPIO20 = False\n\tflag_GPIO21 = False\n\tflag_GPIO28 = False\n\tflag_GPIO29 = False\n\tflag_GPIO31 = False\n\tflag_GPIO32 = False\n\tflag_GPIO33 = False\n\tflag_GPIO37 = False\n\tflag_GPIO38 = False\n\tflag_GPIO39 = False\n\tflag_GPIO40 = False\n\tflag_GPIO41 = False\n\tflag_GPIO43 = False\n\tflag_GPIO44 = False\n\tflag_GPIO45 = False\n\tflag_GPIO46 = False\n\tflag_GPIO47 = False\n\n\tret = Input_CMD_FMP(\"/opt/vsm/bin/dbgdiag emic gpiodump\")\n\tfor i in ret:\n\t\tif(\"IOM Partner Booted output(GPIO10) = 0\" in i):\n\t\t\tflag_GPIO10 = True\n\t\tif(\"Exar USB Port Sel output(GPIO13) = 0\" in i):\n\t\t\tflag_GPIO13 = True\n\t\tif(\"IOM PG input(GPIO14) = 1\" in i):\n\t\t\tflag_GPIO14 = True\n\t\tif(\"Partner PG input(GPIO15) = 0\" in i):\n\t\t\tflag_GPIO15 = True\n\t\tif(\"Partner Booted input(GPIO16) = 0\" in i):\n\t\t\tflag_GPIO16 = True\n\t\tif(\"IOM Shutdown output(GPIO17) = 0\" in i):\n\t\t\tflag_GPIO17 = True\n\t\tif(\"Expander interrupt(GPIO18) = 0\" in i):\n\t\t\tflag_GPIO18 = True\n\t\tif(\"IOM Power Cycle output(GPIO19) = 0\" in i):\n\t\t\tflag_GPIO19 = True\n\t\tif(\"Partner Reset Partial output(GPIO20) = 0\" in i):\n\t\t\tflag_GPIO20 = True\n\t\tif(\"IOM Booted output(GPIO21) = 1\" in i):\n\t\t\tflag_GPIO21 = True\n\t\tif(\"IOM Reset Partial output(GPIO28) = 0\" in i):\n\t\t\tflag_GPIO28 = True\n\t\tif(\"IOM Reset Full output(GPIO29) = 0\" in i):\n\t\t\tflag_GPIO29 = True\n\t\tif(\"IOM Therm Trip output(GPIO31) = 1\" in i):\n\t\t\tflag_GPIO31 = True\n\t\tif(\"IOM Fault output(GPIO32) = 0\" in i):\n\t\t\tflag_GPIO32 = True\n\t\tif(\"IOC Reset output(GPIO33) = 0\" in i):\n\t\t\tflag_GPIO33 = True\n\t\tif(\"IOM slot input(GPIO37) = 0\" in i):\n\t\t\tflag_GPIO37 = True\n\t\tif(\"FReD event interrupt(GPIO38) = 0\" in i):\n\t\t\tflag_GPIO38 = True\n\t\tif(\"Partner Present input(GPIO39) = 1\" in i):\n\t\t\tflag_GPIO39 = True\n\t\tif(\"IOC PCIe Reset output(GPIO40) = 1\" in i):\n\t\t\tflag_GPIO40 = True\n\t\tif(\"FReD message interrupt(GPIO41) = 0\" in i):\n\t\t\tflag_GPIO41 = True\n\t\tif(\"IOM FReD Reset output(GPIO43) = 0\" in i):\n\t\t\tflag_GPIO43 = True\n\t\tif(\"Boot progress output(GPIO44) = 0\" in i):\n\t\t\tflag_GPIO44 = True\n\t\tif(\"Expander Reset output(GPIO45) = 0\" in i):\n\t\t\tflag_GPIO45 = True\n\t\tif(\"Mfg Mode input(GPIO46) = 0\" in i):\n\t\t\tflag_GPIO46 = True\n\t\tif(\"FReD FMP Serial DCD output(GPIO47) = 0\" in i):\n\t\t\tflag_GPIO47 = True\n\n\tif(flag_GPIO10 and flag_GPIO13 and flag_GPIO14 and flag_GPIO15 and flag_GPIO16 and flag_GPIO17 and flag_GPIO18 and flag_GPIO19 \\\n\t\tand flag_GPIO20 and flag_GPIO21 and flag_GPIO28 and flag_GPIO29 and flag_GPIO31 and flag_GPIO32 and flag_GPIO33 and flag_GPIO37 \\\n\t\tand flag_GPIO38 and flag_GPIO39 and flag_GPIO40 and flag_GPIO41 and flag_GPIO43 and flag_GPIO44 and flag_GPIO45 and flag_GPIO46 and flag_GPIO47):\n\t\tLog(\"Check_FMP_GPIO Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_GPIO10 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO10)\", FONT_RED)\n\t\tif(flag_GPIO13 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO13)\", FONT_RED)\n\t\tif(flag_GPIO14 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO14)\", FONT_RED)\n\t\tif(flag_GPIO15 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO15)\", FONT_RED)\n\t\tif(flag_GPIO16 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO16)\", FONT_RED)\n\t\tif(flag_GPIO17 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO17)\", FONT_RED)\n\t\tif(flag_GPIO18 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO18)\", FONT_RED)\n\t\tif(flag_GPIO19 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO19)\", FONT_RED)\n\t\tif(flag_GPIO20 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO20)\", FONT_RED)\n\t\tif(flag_GPIO21 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO21)\", FONT_RED)\n\t\tif(flag_GPIO28 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO28)\", FONT_RED)\n\t\tif(flag_GPIO29 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO29)\", FONT_RED)\n\t\tif(flag_GPIO31 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO31)\", FONT_RED)\n\t\tif(flag_GPIO32 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO32)\", FONT_RED)\n\t\tif(flag_GPIO33 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO33)\", FONT_RED)\n\t\tif(flag_GPIO37 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO37)\", FONT_RED)\n\t\tif(flag_GPIO38 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO38)\", FONT_RED)\n\t\tif(flag_GPIO39 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO39)\", FONT_RED)\n\t\tif(flag_GPIO40 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO40)\", FONT_RED)\n\t\tif(flag_GPIO41 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO41)\", FONT_RED)\n\t\tif(flag_GPIO43 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO43)\", FONT_RED)\n\t\tif(flag_GPIO44 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO44)\", FONT_RED)\n\t\tif(flag_GPIO45 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO45)\", FONT_RED)\n\t\tif(flag_GPIO46 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO46)\", FONT_RED)\n\t\tif(flag_GPIO47 == False):\n\t\t\tLog(\"Check_FMP_GPIO Fail (GPIO47)\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef main():\n\tglobal VER\n\tglobal UUT_STATIONID\n\tglobal DEBUG_MODE\n\tglobal PPID\n\tglobal MAC_LABEL\n\tglobal FMP_OS_VER\n\tglobal FMP_UBOOT_VER\n\tglobal EXP_VER\n\tglobal IOC_VER\n\tglobal COM_PORT_FMP\n\tglobal COM_PORT_IOC\n\tglobal COM_PORT_EXP\n\n\tBanner(\"Galileo SAS IOM FVS Tool, By Foxconn CESBG-EPDI-TE, Version: %s\"%(VER))\n\n\tif(os.path.isdir(LOG_DIR) == False):\n\t\tos.mkdir(LOG_DIR)\n\n\tScan_PPID()\n\n\tconfig = configparser.ConfigParser()\n\tconfig.read(os.path.join(SFC_DIR, \"SFC.ini\"))\n\tDEBUG_MODE = config.getboolean(\"Test\", \"DEBUG_MODE\")\n\tFAIL_CONTINUE = config.getboolean(\"Test\", \"FAIL_CONTINUE\")\n\tFMP_OS_VER = config.get(\"Test\", \"FMP_OS_VER\")\n\tFMP_UBOOT_VER = config.get(\"Test\", \"FMP_UBOOT_VER\")\n\tEXP_VER = config.get(\"Test\", \"EXP_VER\")\n\tIOC_VER = config.get(\"Test\", \"IOC_VER\")\n\tCOM_PORT_FMP = config.get(\"Test\", \"COM_PORT_FMP\")\n\tCOM_PORT_IOC = config.get(\"Test\", \"COM_PORT_IOC\")\n\tCOM_PORT_EXP = config.get(\"Test\", \"COM_PORT_EXP\")\n\tUUT_STATIONID = config.get(\"UUT\", \"STATIONID\")\n\tconfig[\"UUT\"][\"diagsver\"] = VER\n\tconfig[\"UUT\"][\"PPID\"] = PPID\n\tconfig[\"UUT\"][\"result\"] = \"PASS\"\n\tconfig[\"UUT\"][\"errormessage\"] = \"NA\"\n\tconfig[\"UUT\"][\"firmwarever\"] = \"NA\"\n\tconfig[\"UUT\"][\"begintime\"] = \"%d\"%time.time()\n\tconfig[\"UUT\"][\"mac\"] = MAC_LABEL.replace(\",\", \";\")\n\tconfig.write(open(os.path.join(SFC_DIR, \"SFC.ini\"), \"w\"))\n\n\tif(UUT_STATIONID == \"DBG-001\"):\n\t\tLog(\"DEBUG STATION\", FONT_YELLOW)\n\tif(DEBUG_MODE):\n\t\tLog(\"DEBUG_MODE\", FONT_YELLOW)\n\tif(FAIL_CONTINUE):\n\t\tLog(\"FAIL_CONTINUE\", FONT_YELLOW)\n\n\ttest_sequence = [\n\t\t# Wait_FMP_Serial,\n\t\tEnter_FMP_UBoot,\n\t\tCheck_FMP_UBoot_Ver,\n\t\tCheck_FMP_eMMC,\n\t\tCheck_FMP_SPI,\n\t\tCheck_FMP_PCIe,\n\t\tCheck_FMP_I2C,\n\t\tEnter_FMP_Kernel,\n\t\tCheck_FMP_HW,\n\t\tCheck_FMP_FW,\n\t\tCheck_FMP_GPIO,\n\n\t\tEnter_EXP_CLI,\n\t\tCheck_EXP_FW_Ver,\n\t\tCheck_EXP_Phy_Info,\n\t\tCheck_EXP_I2C,\n\t\tCheck_EXP_SAS_Addr,\n\t\tCheck_EXP_Phy_Error,\n\t\tClear_EXP_Phy_Error,\n\n\t\tEnter_IOC_CLI,\n\t\tCheck_IOC_Mode,\n\t\tCheck_IOC_FW_Ver,\n\t\tCheck_IOC_Phy_Info,\n\t\tCheck_IOC_PCIe,\n\t\tCheck_IOC_I2C,\n\t]\n\n\ttest_result = True\n\tresult_msg = []\n\n\ttest_start = datetime.datetime.now()\n\tLog(\"Test Start...\", FONT_YELLOW)\n\tfor test_item in test_sequence:\n\t\tLog(\"=\"*58, FONT_NONE)\n\t\tBanner(test_item.__doc__)\n\t\tLog(\"Test Item: %s (%s)\"%(test_item.__doc__, test_item.__name__), FONT_YELLOW)\n\t\t# time.sleep(1)\n\t\tif(test_item() == False):\n\t\t\ttest_result = False\n\t\t\tresult_msg.append((test_item.__name__, False))\n\t\t\tif(FAIL_CONTINUE):\n\t\t\t\tinput(\"%s Fail!! Press ENTER to Continue...\"%(test_item.__doc__))\n\t\t\telse:\n\t\t\t\tbreak\n\t\telse:\n\t\t\tresult_msg.append((test_item.__name__, True))\n\t\t# time.sleep(1)\n\t\tLog(\"=\"*58, FONT_NONE)\n\tLog(\"Test End...\", FONT_YELLOW)\n\ttest_end = datetime.datetime.now()\n\n\tprint(\"\")\n\tLog(\"Test Start: %s\"%(str(test_start)), FONT_YELLOW)\n\tLog(\"Test End: %s\"%(str(test_end)), FONT_YELLOW)\n\tLog(\"Test Time: %s\"%(str(test_end - test_start)), FONT_YELLOW)\n\tprint(\"\")\n\tfor (item_name, result) in result_msg:\n\t\tif(result):\n\t\t\tmsg = item_name.ljust(52, \"-\") + \"[PASS]\"\n\t\t\tLog(msg, FONT_GREEN)\n\t\telse:\n\t\t\tmsg = item_name.ljust(52, \"-\") + \"[FAIL]\"\n\t\t\tLog(msg, FONT_RED)\n\tprint(\"\")\n\n\tif(test_result):\n\t\tShow_Pass()\n\telse:\n\t\tShow_Fail(\"%s Fail\"%(test_item.__doc__))\n#===============================================================================\nif(__name__ == \"__main__\"):\n\ttry:\n\t\tmain()\n\texcept Exception as e:\n\t\tprint(\"ERROR: %s\"%(str(e)))\n\t\tsys.exit(-1)\n\tsys.exit(0)\n","sub_path":"14G/Galileo SAS IOM/Galileo_SAS_IOM_FVS_Tool.py","file_name":"Galileo_SAS_IOM_FVS_Tool.py","file_ext":"py","file_size_in_byte":42965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"531397238","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 31 13:01:49 2019\n\n@author: genome\n\n\"\"\"\n\ndef juncmut_assadj(input_file, output_file):\n\n sample = input_file.split('.')[0]\n \n with open(input_file, 'r') as in1:\n with open(output_file, 'w') as out1:\n \n for line in in1:\n F = line.rstrip('\\n').split('\\t')\n r=F[6]\n \n if \"Alternative\" in F[9] or \"alternative\" in F[9]:\n if \"e\" in F[13]: #strand=+ 3'SS\n a =str(F[14])\n b = a.split(';',2)\n if b[0] == '*':\n b[0] = '0'\n c=F[0]\n si=int(F[1])-1*int(b[0])\n ei=int(F[2])-1*int(b[0])\n out1.write(str(c)+'\\t'+str(si)+'\\t'+str(ei)+'\\t'+str(F[1])+'\\t'+str(F[2])+'\\t'+str(sample)+'\\t'+str(F[9])+'\\t+\\t'+str(r)+'\\n')\n else:\n c=F[0]\n si=int(F[1])-1*int(b[0])\n ei=int(F[2])-1*int(b[0])\n out1.write(str(c)+'\\t'+str(si)+'\\t'+str(ei)+'\\t'+str(F[1])+'\\t'+str(F[2])+'\\t'+str(sample)+'\\t'+str(F[9])+'\\t+\\t'+str(r)+'\\n')\n elif \"s\" in F[13]: #strand=- 5'SS\n a =str(F[14])\n b = a.split(';',2)\n if b[0] == '*':\n b[0] = '0'\n c=F[0]\n si=int(F[1])-1*int(b[0])\n ei=int(F[2])-1*int(b[0])\n out1.write(str(c)+'\\t'+str(si)+'\\t'+str(ei)+'\\t'+str(F[1])+'\\t'+str(F[2])+'\\t'+str(sample)+'\\t'+str(F[9])+'\\t-\\t'+str(r)+'\\n')\n else:\n c=F[0]\n si=int(F[1])-1*int(b[0])\n ei=int(F[2])-1*int(b[0])\n out1.write(str(c)+'\\t'+str(si)+'\\t'+str(ei)+'\\t'+str(F[1])+'\\t'+str(F[2])+'\\t'+str(sample)+'\\t'+str(F[9])+'\\t-\\t'+str(r)+'\\n')\n elif \"s\" in F[17]: #strand=+ 5'SS\n a =str(F[18])\n b = a.split(';',2)\n if b[0] == '*':\n b[0] = '0'\n c=F[0]\n si=int(F[1])-1*int(b[0])\n ei=int(F[2])-1*int(b[0])\n out1.write(str(c)+'\\t'+str(si)+'\\t'+str(ei)+'\\t'+str(F[1])+'\\t'+str(F[2])+'\\t'+str(sample)+'\\t'+str(F[9])+'\\t-\\t'+str(r)+'\\n')\n else:\n c=F[0]\n si=int(F[1])-1*int(b[0])\n ei=int(F[2])-1*int(b[0])\n out1.write(str(c)+'\\t'+str(si)+'\\t'+str(ei)+'\\t'+str(F[1])+'\\t'+str(F[2])+'\\t'+str(sample)+'\\t'+str(F[9])+'\\t+\\t'+str(r)+'\\n')\n elif \"e\" in F[17]: #strand=- 3'SS\n a =str(F[18])\n b = a.split(';',2)\n if b[0] == '*':\n b[0] = '0'\n c=F[0]\n si=int(F[1])-1*int(b[0])\n ei=int(F[2])-1*int(b[0])\n out1.write(str(c)+'\\t'+str(si)+'\\t'+str(ei)+'\\t'+str(F[1])+'\\t'+str(F[2])+'\\t'+str(sample)+'\\t'+str(F[9])+'\\t-\\t'+str(r)+'\\n')\n else:\n c=F[0]\n si=int(F[1])-1*int(b[0])\n ei=int(F[2])-1*int(b[0])\n out1.write(str(c)+'\\t'+str(si)+'\\t'+str(ei)+'\\t'+str(F[1])+'\\t'+str(F[2])+'\\t'+str(sample)+'\\t'+str(F[9])+'\\t-\\t'+str(r)+'\\n')\n\nif __name__== \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser() #make a parser\n\n parser.add_argument(\"input_file\", metavar = \"input_file\", default = None, type = str,\n help = \"input file\") \n \n parser.add_argument(\"output_file\", metavar = \"output_file\", default = \"my_sample\", type = str,\n help = \"output_file\") \n \n args = parser.parse_args()\n\n input_file = args.input_file\n output_file = args.output_file\n\n print(input_file) \n juncmut_assadj(input_file, output_file)\n","sub_path":"juncmut/juncmut_assadj.py","file_name":"juncmut_assadj.py","file_ext":"py","file_size_in_byte":4631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"103409885","text":"#!/usr/bin/env python3\n# -*- encoding: utf-8 -*-\nfrom os.path import dirname, join\n\nfrom setuptools import find_packages, setup\n\n\ntests_require = [\n 'coverage>=4.5.1, < 5.0',\n 'flake8>=3.5.0, < 4.0',\n 'pycodestyle==2.3.1',\n 'tblib>=1.3.2, < 2.0',\n 'pyflakes>=1.6.0, < 2.0'\n]\n\nsetup(\n name='fortunato',\n version='0.0.1',\n description='Happy, Lucky, Rich, Blessed',\n long_description=open(join(dirname(__file__), 'README.rst')).read(),\n author='Andrew Crouse',\n author_email='amcrouse@data-get.org',\n url='https://github.com/edmontonpy/fortunato',\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n classifiers=[\n # See: http://pypi.python.org/pypi?%3Aaction=list_classifiers\n ],\n keywords=[\n 'fortunato'\n ],\n scripts=[\n 'bin/fortunato'\n ],\n install_requires=[\n ],\n test_suite=\"fortunato\",\n tests_require=tests_require,\n extras_require={\n 'dev': tests_require,\n },\n)\n","sub_path":"Tutorial 2/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"275336239","text":"import math\n\nfrom django import template\nfrom django.utils.safestring import mark_safe\nfrom django.contrib.humanize.templatetags.humanize import intcomma\n\nregister = template.Library()\n\n\n@register.simple_tag(takes_context=True)\ndef conditional_js(context, filename):\n tag_format = ''\n if context.get('DEBUG', True):\n tag = tag_format % (filename, '')\n else:\n tag = tag_format % (filename, 'min.')\n return mark_safe(tag)\n\n\n@register.filter\ndef wholenum(num):\n return int(round(num))\n\n\n@register.filter\ndef deltawords(num, arg):\n \"\"\"An adverb to come after the word 'improved' or 'slipped'\n \"\"\"\n delta = abs(num - arg)\n # We only pick out changes over 10%; over 30% in 9 months is unheard of.\n if delta == 0:\n word = \"not at all\"\n elif delta < 10:\n word = \"slightly\"\n elif delta < 20:\n word = \"moderately\"\n elif delta < 30:\n word = \"considerably\"\n else:\n word = \"massively\"\n return word\n\n\n@register.filter\ndef roundpound(num):\n order = 10 ** math.floor(math.log10(num))\n if order > 0:\n return intcomma(int(round(num/order) * order))\n else:\n return str(int(round(num)))\n\n\n@register.simple_tag\ndef url_toggle(request, field):\n dict_ = request.GET.copy()\n if field in dict_:\n del(dict_[field])\n else:\n dict_[field] = 1\n return dict_.urlencode()\n","sub_path":"openprescribing/frontend/templatetags/template_extras.py","file_name":"template_extras.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"24167402","text":"\"\"\"Unitary tests for eToken contract\"\"\"\n\nfrom functools import wraps\nfrom collections import namedtuple\nimport pytest\nfrom prototype.contracts import RevertError\nfrom prototype import ensuro\nfrom prototype.wadray import _W, _R, Wad\nfrom prototype.utils import WEEK, DAY\nfrom brownie.network.contract import Contract\nfrom . import wrappers\n\nAAVE = namedtuple(\"AAVE\", \"address_provider lending_pool price_oracle\")\n\n\nAAVE_AP_ADDRESS = \"0xd05e3E715d945B59290df0ae8eF85c1BdB684744\"\nWMATIC_ADDRESS = \"0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270\"\nUSDC_ADDRESS = \"0x2791bca1f2de4661ed88a30c99a7a9449aa84174\"\nSUSHISWAP_ROUTER_ADDRESS = \"0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506\"\n\n\n@pytest.fixture\ndef USDC():\n return wrappers.IERC20.connect(USDC_ADDRESS)\n\n\n@pytest.fixture\ndef aave():\n ILendingPoolAddressesProvider = wrappers.get_contract_factory(\"ILendingPoolAddressesProvider\")\n ap = Contract.from_abi(\n \"LendingPoolAddressesProvider\", AAVE_AP_ADDRESS,\n ILendingPoolAddressesProvider.abi\n )\n\n addr = ap.getLendingPool()\n ILendingPool = wrappers.get_contract_factory(\"ILendingPool\")\n lending_pool = Contract.from_abi(\"LendingPool\", addr, ILendingPool.abi)\n\n addr = ap.getPriceOracle()\n IPriceOracle = wrappers.get_contract_factory(\"IPriceOracle\")\n price_oracle = Contract.from_abi(\"PriceOracle\", addr, IPriceOracle.abi)\n\n return AAVE(ap, lending_pool, price_oracle)\n\n\ndef get_account(name):\n return wrappers.AddressBook.instance.get_account(name)\n\n\n@pytest.fixture\ndef WMATIC():\n return wrappers.IERC20.connect(WMATIC_ADDRESS)\n\n\ndef get_usdc_from_ether(account, USDC, aave, WMATIC, collat_ratio):\n account = get_account(account)\n wmatic_balance = WMATIC.balance_of(account)\n\n WMATIC.approve(account, aave.lending_pool, wmatic_balance)\n\n aave.lending_pool.deposit(\n WMATIC.contract.address,\n # \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\",\n wmatic_balance, account, 0,\n {\"from\": account}\n )\n wmatic_in_eth = Wad(aave.price_oracle.getAssetPrice(WMATIC.contract))\n USDC_in_eth = Wad(aave.price_oracle.getAssetPrice(USDC.contract))\n wmatic_in_usdc = wmatic_in_eth // USDC_in_eth\n usd_amount = (wmatic_balance * wmatic_in_usdc * collat_ratio) // _W(10**12)\n\n aave.lending_pool.borrow(USDC.contract.address, usd_amount, 2, 0, account, {\"from\": account})\n\n usd_per_matic = (usd_amount * _W(10**12)) // (wmatic_balance * collat_ratio)\n\n return wmatic_balance, usd_amount, usd_per_matic\n\n\n@pytest.fixture\ndef PolicyPoolAndConfig(USDC):\n from brownie import PolicyPoolMockForward\n\n config = wrappers.PolicyPoolConfig(\"owner\")\n pool = PolicyPoolMockForward.deploy(get_account(None), USDC.contract, config.contract,\n {\"from\": config.owner})\n return config, pool\n\n\ndef donate_wmatic(WMATIC, ac_from, ac_to, amount=None):\n # First convert MATIC to WMATIC\n ac_from, ac_to = get_account(ac_from), get_account(ac_to)\n amount = amount or ac_from.balance()\n ac_from.transfer(WMATIC.contract.address, amount)\n # Then transfer to destination\n WMATIC.transfer(ac_from, ac_to, amount)\n\n\ndef skip_if_not_fork(f):\n from brownie._config import CONFIG\n if CONFIG.argv.get(\"network\", None) == \"polygon-main-fork\":\n return f\n else:\n def test_foo():\n pass\n test_foo.__name__ = f.__name__\n\n return test_foo\n\n\n# @pytest.mark.require_network(\"polygon-main-fork\") - DOES NOT WORK\n@skip_if_not_fork\ndef test_get_balance(USDC, aave, PolicyPoolAndConfig, WMATIC):\n AAVE_address = \"0x1a13f4ca1d028320a707d99520abfefca3998b7f\"\n assert int(USDC.balance_of(AAVE_address)) > (1000000 * 10**6) # At least 1 millon if in the right fork\n\n # Donates matic so we have more balance\n for i in range(5):\n donate_wmatic(WMATIC, f\"CHARITY{i}\", \"LP1\")\n\n wmatic_balance, usd_amount, usd_per_matic = get_usdc_from_ether(\"LP1\", USDC, aave, WMATIC, _W(\"0.3\"))\n USDC.balance_of(\"LP1\").assert_equal(usd_amount)\n\n config, pool = PolicyPoolAndConfig\n\n liquidity_min = usd_amount * _W(\"0.1\")\n liquidity_middle = usd_amount * _W(\"0.5\")\n liquidity_max = usd_amount * _W(\"0.8\")\n\n aave_mgr = wrappers.AaveAssetManager(\n config.owner, pool,\n liquidity_min=liquidity_min,\n liquidity_middle=liquidity_middle,\n liquidity_max=liquidity_max,\n aave_address_provider=AAVE_AP_ADDRESS,\n swap_router=SUSHISWAP_ROUTER_ADDRESS\n )\n\n # Donate 2 matic to aave_mgr\n donate_wmatic(WMATIC, \"VITALIK\", aave_mgr.contract, _W(2))\n\n pool.setForwardTo(aave_mgr.contract, {\"from\": config.owner})\n\n aave_mgr.get_investment_value().assert_equal(_W(2) * usd_per_matic // _W(10**12))\n\n config.grant_role(\"LEVEL1_ROLE\", config.owner)\n config.set_asset_manager(aave_mgr)\n\n # Transfer LP1 USD to PolicyPoolMockForward\n USDC.transfer(\"LP1\", pool, usd_amount)\n USDC.balance_of(pool).assert_equal(usd_amount)\n\n aave_mgr.rebalance()\n aave_mgr.aToken.balance_of(aave_mgr).assert_equal(liquidity_middle)\n USDC.balance_of(pool).assert_equal(usd_amount - liquidity_middle)\n # Rewards are reinvested on each rebalance\n aave_mgr.rewardToken.balance_of(aave_mgr).assert_equal(_W(0))\n aave_mgr.rewardAToken.balance_of(aave_mgr).assert_equal(_W(2))\n\n # swapRewards\n with pytest.raises(RevertError, match=\"AccessControl\"):\n swapIn, swapOut = aave_mgr.swap_rewards(_W(3))\n\n config.grant_role(\"SWAP_REWARDS_ROLE\", \"WHOKNOWSWHENTOSELL\")\n\n with aave_mgr.as_(\"WHOKNOWSWHENTOSELL\"):\n wmatic_in, usdc_out = aave_mgr.swap_rewards(_W(3))\n\n wmatic_in.assert_equal(_W(2))\n usdc_out.assert_equal(_W(2) * usd_per_matic // _W(10**12))\n aave_mgr.aToken.balance_of(aave_mgr).assert_equal(liquidity_middle + usdc_out)\n\n # Donate another 3 matic to aave_mgr\n donate_wmatic(WMATIC, \"VITALIK\", aave_mgr.contract, _W(1))\n\n aave_mgr.get_investment_value().assert_equal(\n liquidity_middle + usdc_out + _W(1) * usd_per_matic // _W(10**12)\n )\n\n one_dollar = _W(1) // _W(10**12)\n with aave_mgr.thru_policy_pool():\n aave_mgr.refill_wallet(usd_amount - liquidity_middle + one_dollar)\n # Money taken from aToken\n aave_mgr.aToken.balance_of(aave_mgr).assert_equal(liquidity_middle + usdc_out - one_dollar)\n\n USDC.balance_of(pool).assert_equal(usd_amount - liquidity_middle + one_dollar)\n aave_mgr.rebalance()\n USDC.balance_of(pool).assert_equal(usd_amount - liquidity_middle) # Shouldn't change\n\n config.set_asset_manager(None) # Should deinvestAll\n USDC.balance_of(pool).assert_equal(usd_amount + _W(3) * usd_per_matic // _W(10**12))\n\n # No funds in aave_mgr\n aave_mgr.aToken.balance_of(aave_mgr).assert_equal(_W(0))\n WMATIC.balance_of(aave_mgr).assert_equal(_W(0))\n aave_mgr.rewardAToken.balance_of(aave_mgr).assert_equal(_W(0))\n","sub_path":"tests/test_aave_assetmanager.py","file_name":"test_aave_assetmanager.py","file_ext":"py","file_size_in_byte":6850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"76986442","text":"import shodan\nfrom glimmer.libs.core.exceptions import ParserExceptions\n\n\nclass ShodanClient:\n def __init__(self, key):\n self.key = key\n self.api = shodan.Shodan(key)\n\n def query(self, query_str, max_page=1, limit=None, fields=\"\", minify=True):\n \"\"\"\n support fields:\n\n asn data ip(ip_str) ipv6 port timestamp hostnames domains location(Object) country(location.country_name) opts org isp os transport link title html product version devicetype info cpe\n\n https://developer.shodan.io/api/banner-specification\n \"\"\"\n try:\n for page in range(1, max_page+1):\n data = self.api.search(query_str, page, limit, minify=minify)\n if fields == \"\":\n yield data\n else:\n for result in data['matches']:\n yield [_getinfo(result, field) for field in fields.split(\",\")]\n except shodan.APIError as e:\n raise ParserExceptions.CyberSpace.APIError(e) from e\n\n\ndef _getinfo(data: dict, attr=''):\n if attr == \"ip\":\n return data[\"ip_str\"]\n elif attr == \"country\":\n return data[\"location\"][\"country_name\"]\n return data[attr]\n","sub_path":"glimmer/utils/cyberspace/shodan.py","file_name":"shodan.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"246585926","text":"'''This program will extract the atoms of a pdb file, calculate all inter-chain\r\nand intra-chain distances between amino acids LYS, ARG, ASP, GLU and\r\nwrite the energies of interactions within 8 ang to inter-chain and intra-chain output files'''\r\n\r\nfilename=\"3AYW.pdb\"\r\n\r\n## get each line of data\r\nfh_in=open(filename)\r\ncontents=fh_in.readlines()\r\narr=[]\r\nfor line in contents:\r\n frag=line.split()\r\n arr.append(frag)\r\n\r\n## extract amino acids and their data\r\naminoacids=[]\r\ndna=[]\r\nsaltbridgers=[]\r\nfor atom in arr:\r\n if atom[0]==\"ATOM\":\r\n zero=atom[0]\r\n one=atom[1]\r\n element=atom[2]\r\n residue=atom[3]\r\n chain=atom[4]\r\n pos=atom[5]\r\n xcoord=float(atom[6])\r\n ycoord=float(atom[7])\r\n zcoord=float(atom[8])\r\n if len(str(atom[9]))!=4:\r\n nine=atom[9][0:4]\r\n ten=atom[9][4:]\r\n eleven=atom[10]\r\n else:\r\n nine=atom[9]\r\n ten=atom[10]\r\n eleven=atom[11]\r\n\r\n if (residue==\"LYS\" and element==\"NZ\") or (residue==\"ARG\" and element==\"CZ\"):\r\n charge=1\r\n aminoacids.append([residue, pos, chain, xcoord, ycoord, zcoord,charge])\r\n saltbridgers.append([zero, one, element, residue, chain, pos, xcoord, ycoord, zcoord, nine, ten, eleven, charge])\r\n elif (element==\"P\"):\r\n charge=-1\r\n dna.append([residue, pos, chain, xcoord, ycoord, zcoord,charge])\r\n saltbridgers.append([zero, one, element, residue, chain, pos, xcoord, ycoord, zcoord, nine, ten, eleven, charge])\r\n\r\n##calculate distances and energies\r\nimport math\r\nsaltbridge=[]\r\nfor n in range(0, len(saltbridgers)-1):\r\n aa=saltbridgers[n]\r\n for s in range(n+1,len(saltbridgers)):\r\n bb=saltbridgers[s]\r\n xsquared=(bb[6]-aa[6])**2\r\n ysquared=(bb[7]-aa[7])**2\r\n zsquared=(bb[8]-aa[8])**2\r\n distance=math.sqrt(xsquared+ysquared+zsquared)\r\n if distance<=10:\r\n energy=(aa[12]*bb[12])\r\n if energy<0:\r\n saltbridge.append(aa[0:12])\r\n saltbridge.append(bb[0:12])\r\n\r\n## create outfile\r\n\r\ncluster_out=open(\"3AYW_cluster.pdb\", \"w\")\r\nfor q in saltbridge:\r\n## pos,neg,dis,e=q\r\n## dis=int(dis*1000)/float(1000)\r\n## e=int(e*1000)/float(1000)\r\n for p in q:\r\n cluster_out.write(str(p)+\"\\t\")\r\n cluster_out.write(\"\\n\")\r\ncluster_out.close()\r\n\r\n##create textfile\r\n##Submit a text file that has as its contents the following items (histone chain ID, \r\n##histone residue number, residue name, DNA chain ID, DNA residue number, DNA \r\n##nucleotide type, salt bridge distance). Please use the following name for your file: \r\n##\r\n\r\n##text_out=open(\"Chau_A_3AYWSaltBr.txt\")\r\n##for q in saltbridge:\r\n## text_out.write(\r\n","sub_path":"AllisonChau_saltbridge.py","file_name":"AllisonChau_saltbridge.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"399245767","text":"import os\nimport re\nimport json\nimport glob\nimport webbrowser\nfrom flask import Flask, request, Response\n\nmetric_files = ['upstream/1_Diversity-Inclusion.md', 'upstream/2_Growth-Maturity-Decline.md', 'upstream/3_Risk.md', 'upstream/4_Value.md']\n\nmetric_type_by_file = {\n 'upstream/1_Diversity-Inclusion.md': 'Diversity and Inclusion',\n 'upstream/2_Growth-Maturity-Decline.md': 'Growth, Maturity, and Decline',\n 'upstream/3_Risk.md': 'Risk',\n 'upstream/4_Value.md': 'Value',\n}\n\ncolor_by_status = {\n 'unimplemented': 'unimplemented',\n 'in_progress': 'in progress',\n 'implemented': 'implemented'\n}\n\nstatusMap = json.loads(open('status.json', 'r').read())\nstatusHTML = \"\"\"\n\n\n Augur Metrics Status\n \n\n\n

Augur Metrics Status

\n \n\"\"\"\n\ndef getFileID(path):\n return os.path.splitext(os.path.basename(path))[0]\n\ndef printMetric(title, path):\n global statusHTML\n status = 'unimplemented'\n fileID = getFileID(path)\n if fileID in statusMap:\n status = statusMap[fileID]\n if status != 'printed':\n statusHTML += '{}
{} ({})'.format(color_by_status[status], path, title, fileID)\n statusMap[fileID] = 'printed'\n return fileID\n\n# Iterate through the category Markdown files to categorize links\nfor filename in metric_files:\n file = open(filename, 'r')\n matches = re.findall(r'\\[(.*?)\\]\\((.*?\\.md)\\)', file.read())\n if len(matches) > 0:\n statusHTML += '

' + metric_type_by_file[filename] + '

'\n for match in matches:\n printMetric(match[0], match[1])\n statusHTML += '
statusmetric
'\n \n\n# Iterate through the files in activity-metrics to find uncategorized metrics\nstatusHTML += '

Uncategorized

'\nfor filename in glob.iglob('upstream/activity-metrics/*.md'):\n printMetric(getFileID(filename).replace('-', ' ').title(), 'activity-metrics/' + getFileID(filename) + '.md')\n\n\nstatusHTML += \"\"\"\n
statusmetric
\n\n\n\"\"\"\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef root():\n return statusHTML\n\ndef run():\n webbrowser.open_new_tab('http://localhost:5001/')\n app.run(port=5001)\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"docs/metrics/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"635585885","text":"import nibabel\nimport popeye.utilities as utils\nfrom scipy.ndimage import imread\nimport popeye.plotting as pp\nstyle.use('fivethirtyeight')\n\nsubjects = [2,8]\nbase = '.'\nthr = 0.10\n\n#### SIGMA SCATTER ####\nxs = np.array([])\nys = np.array([])\nss = np.array([])\nws = np.array([])\nhs = np.array([])\nps = np.array([])\nrs = np.array([])\n\nfor subject in subjects:\n \n # overlay \n fname = '%s/%d/figures/prf_tau.nii.gz' %(base,subject)\n prf = nibabel.load(fname).get_data()\n pol = utils.cartes_to_polar(prf)\n \n fname = '%s/%d/figures/LGN_rs.nii.gz' %(base,subject)\n mask = nibabel.load(fname).get_data().astype(bool)\n \n # censoring\n mask[prf[...,-1]0.99] = 0\n \n # pull\n x = prf[mask,0]\n y = prf[mask,1]\n s = prf[mask,2]\n w = prf[mask,3]\n # h = prf[mask,6]\n p = pol[mask,0]\n r = pol[mask,1]\n \n # stack\n xs = np.concatenate((xs,x))\n ys = np.concatenate((ys,y))\n ss = np.concatenate((ss,s))\n ws = np.concatenate((ws,w))\n hs = np.concatenate((hs,h))\n ps = np.concatenate((ps,p))\n rs = np.concatenate((rs,r))\n\nplt.hist(hs,bins=np.arange(-3,3.5,0.5),color='k')\nax = plt.gca()\nax.set_yticks(np.arange(20,160,20))\nax.set_yticklabels(['{:3.0f}%'.format(x*100) for x in np.arange(0.05,0.40,0.05)])\nax.set_ylabel('Fractional Volume',fontsize=24)\nax.set_xlabel('HRF delay',fontsize=24)\ntight_layout()\nsavefig('hrf.pdf')\n\n","sub_path":"analysis/scripts/hrf.py","file_name":"hrf.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"210255099","text":"import decimal\nimport json\nimport os\nimport boto3\nfrom botocore.config import Config\n\nconf = Config(\n retries = {\n 'max_attempts': 1,\n 'mode': 'standard'\n }\n)\n\nTABLE_NAME = os.environ['TABLE_NAME']\n\n# Helper class to convert a DynamoDB item to JSON.\nclass DecimalEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, decimal.Decimal):\n if abs(o) % 1 > 0:\n return float(o)\n else:\n return int(o)\n return super(DecimalEncoder, self).default(o)\n\ndef handler(event, _):\n ddb = boto3.resource('dynamodb', config = conf)\n table = ddb.Table(TABLE_NAME)\n\n # Retrieve the latest state data\n response = table.get_item(\n Key={\n 'PK': event['ID'],\n 'SK': 'v0'\n }\n )\n item = response['Item']\n print(json.dumps(item, indent=4, cls=DecimalEncoder))\n","sub_path":"examples/version-control/number-based-version/transactional-write/src/get_latest_version/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"558818259","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Author: hjweddie@163.com\n# Time: Sat 03 Jan 2015 05:00:02 PM CST\n# File: api/handlers/handler.py\n# Desc:\n#\n\n\nfrom tornado.options import options\n\nimport os\nimport yaml\nimport time\nimport redis\nimport torndb\nimport common\nimport logging\nimport tornado.web\nimport logging.handlers\n\n\nclass BaseHandler(tornado.web.RequestHandler):\n # load config of the server\n def __configure(self, appkey):\n self.appkey = appkey\n\n self.__configure_setting()\n self.__configure_log()\n self.__configure_args()\n self.__configure_db()\n\n def __configure_setting(self):\n with open(options.config, \"r\") as fd:\n self.config = yaml.load(fd)\n\n sql_yaml_file = self.config[\"query_tpl\"]\n with file(sql_yaml_file, \"r\") as tplfile:\n self.query_tpl = yaml.load(tplfile)\n\n def __configure_args(self):\n self.args = {}\n\n if \"GET\" == self.request.method:\n for k, v in self.request.arguments.iteritems():\n self.args[k] = common.to_unicode(v[0])\n else:\n # if request method is POST\n if self.request.headers[\"Content-Type\"].startswith(\"application/json\"):\n self.args = common.jsonstr2dict(self.request.body)\n\n def __configure_db(self):\n # redis 连接\n pool = redis.ConnectionPool(**self.config['redis'])\n self.redis = redis.Redis(connection_pool=pool)\n\n # gw 连接\n self.gw = torndb.Connection(**self.config['gw_db'])\n\n self.select_report_db()\n\n def select_report_db(self):\n sql = self.config[\"route_query\"] % self.appkey\n rows = self.gw.query(sql)\n if 1 != len(rows):\n self.app_name = \"\"\n self.db_name = \"\"\n self.db = \"\"\n else:\n self.app_name = rows[0][\"app_name\"]\n self.db_name = rows[0][\"db_name\"]\n\n # mysql 连接\n self.config[\"mysql\"][\"database\"] = self.db_name\n self.db = torndb.Connection(**self.config['mysql'])\n\n def __configure_log(self):\n today = time.strftime(\"%Y%m%d\")\n common.ensure_dir(options.log_path)\n log_file = os.path.join(options.log_path, \"%s.log\" % today)\n self.log_handler = logging.FileHandler(log_file, mode='a', encoding='utf-8')\n\n # log format\n log_formatter = logging.Formatter(self.config[\"log\"][\"format\"])\n self.log_handler.setFormatter(log_formatter)\n\n logger = logging.getLogger('datamaster_api_log')\n logger.addHandler(self.log_handler)\n logger.propagate = False\n\n # logger threshold\n logger.setLevel(logging.DEBUG)\n\n self.logger = logger\n\n configure = __configure\n","sub_path":"src/api/handlers/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"311725623","text":"#!/usr/bin/env python\n\n\"\"\"\n\n{\n \n method:\"seek\",\n id:\"optional, post cmd text /seek/{id}\n args:{more json}\n\n}\n\n\n\n\"\"\"\ndef main(wsBindAddr,wsBindPort,hostPath):\n import asyncio\n import websockets\n import json\n import requests\n\n @asyncio.coroutine\n def proxy(websocket, path):\n cmd_text = yield from websocket.recv()\n print(cmd_text)\n cmd = json.loads(cmd_text)\n output = \"\"\n if cmd[\"method\"] == \"seek\":\n seekarg = cmd[\"id\"]\n newpath = ''.join((hostPath,\"seek/\",seekarg))\n r = requests.get(newpath)\n output = r.text\n if cmd[\"method\"] == \"get\":\n seekarg = cmd[\"id\"]\n newpath = ''.join((hostPath,\"get/\",seekarg))\n r = requests.get(newpath)\n output = r.text\n if cmd[\"method\"] == \"poll\":\n seekarg = cmd[\"id\"]\n t = cmd[\"time\"]\n newpath = ''.join((hostPath,\"poll/\",seekarg,\"/\",str(t)))\n r = requests.get(newpath)\n output = r.text\n if cmd[\"method\"] == \"store\":\n seekarg = cmd[\"id\"]\n newpath = ''.join((hostPath,\"store/\",seekarg))\n data = json.dumps(cmd[\"data\"])\n r = requests.post(newpath, data=data)\n output = r.text\n if cmd[\"method\"] == \"post\":\n seekarg = cmd[\"id\"]\n newpath = ''.join((hostPath,\"post/\",seekarg))\n data = json.dumps(cmd[\"data\"])\n r = requests.post(newpath, data=data)\n output = r.text\n\n yield from websocket.send(output)\n\n start_server = websockets.serve(proxy, wsBindAddr, wsBindPort)\n\n asyncio.get_event_loop().run_until_complete(start_server)\n asyncio.get_event_loop().run_forever()\n\n","sub_path":"websocketProxy.py","file_name":"websocketProxy.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"571104638","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound\nfrom cache.models import Page\nfrom django.views.decorators.csrf import csrf_exempt\nimport urllib.request\n\nform = \"\"\"

\"\"\"\n\n@csrf_exempt\n\ndef barra(request):\n\n if request.method == \"POST\":\n url = request.POST['url']\n if url == \"\":\n response = '

No url introduced


'+'
Return to Main Menu'\n return HttpResponse(response)\n\n elif url.find(\"http://\")==-1 and url.find(\"https://\")==-1:\n url = \"https://\" + url\n\n try:\n page = Page.objects.get(name = url)\n response = '

page already saved in cache


' + 'Return to Main Menu'\n return HttpResponse(response)\n except Page.DoesNotExist:\n content = (urllib.request.urlopen(url)).read()\n page = Page(name= url, page=content)\n page.save()\n\n response = '' + '

Add page

'\n response = \"

Hi!, these are our contents managed:

\" + response + form\n return HttpResponse(response)\n\ndef get(request, name):\n try:\n page = Page.objects.get(name=name)\n except Page.DoesNotExist:\n return HttpResponse('

La pagina no se encuentra en la cache


' +'Return to Main Menu')\n response = page.page\n return HttpResponse(response)\n","sub_path":"cache/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"447532168","text":"# -*- coding: utf-8 -*-\nfrom django.conf import settings\nfrom django.conf.urls import patterns, include, url\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.views.generic import RedirectView, TemplateView\n\n\nurlpatterns = patterns(\n '',\n url(r'^$', RedirectView.as_view(url='/admin/'), name='home'),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^markdown/help/$', TemplateView.as_view(\n template_name='markdown_help.html')),\n url(r'^markdown/', include('django_markdown.urls')),\n url(r'^location_field/', include('common.libs.location_field.urls')),\n url(r'^metro/$', 'admin_app.core.views.metro', name='metro'),\n url(r'^chaining/', include('common.libs.smart_selects.urls')),\n\n url(r'^feeds/', include('admin_app.feeds.urls')),\n\n url(\n r'^autocomplete/(?P[\\w.]+)/(?P[\\w]+)/(?P[\\w]+)/$',\n 'admin_app.core.views.autocomplete',\n name='autocomplete'\n ),\n url(\n r'^ajaxchosen/(?P[\\w.]+)/(?P[\\w]+)/(?P[\\w]+)/$',\n 'admin_app.core.views.ajaxchosen',\n name='ajaxchosen'\n ),\n)+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n\n# uploading and getting files from/to pgc\nurlpatterns += patterns(\n 'admin_app.core.views',\n url(r'^pgc/image/upload/$', 'pgc_image_upload', name='pgc_image_upload'),\n url(\n r'^pgc/image/external/$',\n 'pgc_image_external',\n name='pgc_image_external'\n ),\n url(r'^pgc/image/detail/$', 'pgc_image_detail', name='pgc_image_detail'),\n)\n\nif settings.ENABLE_DEBUG_TOOLBAR:\n import debug_toolbar\n urlpatterns += patterns('',\n url(r'^__debug__/', include(debug_toolbar.urls)),\n )\n","sub_path":"src/admin_app/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"118655444","text":"\"\"\"ResNet model implemented using slim components\n\nRelated ResNet papers:\nhttps://arxiv.org/pdf/1603.05027v2.pdf\nhttps://arxiv.org/pdf/1512.03385v1.pdf\nhttps://arxiv.org/pdf/1605.07146v1.pdf\n\"\"\"\nfrom collections import namedtuple\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\n\nfrom tensorflow.python.training import moving_averages\n\nHParams = namedtuple('HParams',\n 'batch_size, num_classes, min_lrn_rate, lrn_rate, '\n 'num_residual_units, use_bottleneck, weight_decay_rate, '\n 'relu_leakiness, optimizer')\n\n\nclass ResNet(object):\n \"\"\"ResNet model.\"\"\"\n\n def __init__(self, hps, images, labels, mode):\n \"\"\"ResNet constructor.\n\n Args:\n hps: Hyperparameters.\n images: Batches of images. [batch_size, image_size, image_size, 3]\n labels: Batches of labels. [batch_size, num_classes]\n mode: One of 'train' and 'eval'.\n \"\"\"\n self.hps = hps\n self._images = images\n self.labels = labels\n self.mode = mode\n\n self._extra_train_ops = []\n\n def build_graph(self):\n \"\"\"Build a whole graph for the model.\"\"\"\n self.global_step = tf.Variable(0, name='global_step', trainable=False)\n self._build_model()\n if self.mode == 'train':\n self._build_train_op()\n self.summaries = tf.merge_all_summaries()\n\n def _build_model(self):\n \"\"\"Build the core model within the graph.\"\"\"\n with tf.variable_scope('init'):\n x = self._images\n x = self._conv('init_conv', x, 16, stride=1)\n\n res_func = self._residual\n filters = [16, 16, 32, 64]\n # Uncomment the following codes to use w28-10 wide residual network.\n # It is more memory efficient than very deep residual network and has\n # comparably good performance.\n # https://arxiv.org/pdf/1605.07146v1.pdf\n # filters = [16, 160, 320, 640]\n # Update hps.num_residual_units to 9\n\n with tf.variable_scope('unit_1_0'):\n x = res_func(x, filters[0], filters[1], stride=1)\n for i in range(1, self.hps.num_residual_units):\n with tf.variable_scope('unit_1_%d' % i):\n x = res_func(x, filters[1], filters[1], stride=1)\n\n with tf.variable_scope('unit_2_0'):\n x = res_func(x, filters[1], filters[2], stride=2)\n for i in range(1, self.hps.num_residual_units):\n with tf.variable_scope('unit_2_%d' % i):\n x = res_func(x, filters[2], filters[2], stride=1)\n\n with tf.variable_scope('unit_3_0'):\n x = res_func(x, filters[2], filters[3], stride=2)\n for i in range(1, self.hps.num_residual_units):\n with tf.variable_scope('unit_3_%d' % i):\n x = res_func(x, filters[3], filters[3], stride=1)\n\n with tf.variable_scope('unit_last'):\n x = self._batch_norm(x)\n x = self._relu(x, self.hps.relu_leakiness)\n x = self._global_avg_pool(x)\n\n with tf.variable_scope('logit'):\n x = slim.layers.flatten(x)\n self.logits = self._fully_connected(x, self.hps.num_classes)\n self.predictions = tf.nn.softmax(self.logits)\n\n with tf.variable_scope('costs'):\n xent = tf.nn.softmax_cross_entropy_with_logits(\n self.logits, self.labels)\n self.cost = tf.reduce_mean(xent, name='xent')\n self.cost += self._decay()\n\n tf.scalar_summary('cost', self.cost)\n\n def _residual(self, x, in_filter, out_filter, stride):\n \"\"\"Residual unit with 2 sub layers.\"\"\"\n with tf.variable_scope('residual_only_activation'):\n orig_x = x\n x = self._batch_norm(x)\n x = self._relu(x, self.hps.relu_leakiness)\n\n with tf.variable_scope('sub1'):\n x = self._conv('conv1', x, out_filter, stride=stride)\n\n with tf.variable_scope('sub2'):\n x = self._batch_norm(x)\n x = self._relu(x, self.hps.relu_leakiness)\n x = self._conv('conv2', x, out_filter, stride=1)\n\n with tf.variable_scope('sub_add'):\n if in_filter != out_filter:\n orig_x = tf.nn.avg_pool(orig_x, [1, stride, stride, 1], [1, stride, stride, 1], 'VALID')\n orig_x = tf.pad(\n orig_x, [[0, 0], [0, 0], [0, 0],\n [(out_filter-in_filter)//2, (out_filter-in_filter)//2]])\n x += orig_x\n\n tf.logging.info('image after unit %s', x.get_shape())\n return x\n\n def _build_train_op(self):\n \"\"\"Build training specific ops for the graph.\"\"\"\n self.lrn_rate = tf.constant(self.hps.lrn_rate, tf.float32)\n tf.scalar_summary('learning rate', self.lrn_rate)\n\n trainable_variables = tf.trainable_variables()\n grads = tf.gradients(self.cost, trainable_variables)\n\n if self.hps.optimizer == 'sgd':\n optimizer = tf.train.GradientDescentOptimizer(self.lrn_rate)\n elif self.hps.optimizer == 'mom':\n optimizer = tf.train.MomentumOptimizer(self.lrn_rate, 0.9)\n\n apply_op = optimizer.apply_gradients(\n zip(grads, trainable_variables),\n global_step=self.global_step, name='train_step')\n\n train_ops = [apply_op] + self._extra_train_ops + tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n self.train_op = tf.group(*train_ops)\n\n def _decay(self):\n \"\"\"L2 weight decay loss.\"\"\"\n costs = []\n for var in tf.trainable_variables():\n if var.op.name.find(r'weights') > 0:\n costs.append(tf.nn.l2_loss(var))\n # tf.histogram_summary(var.op.name, var)\n\n return tf.mul(self.hps.weight_decay_rate, tf.add_n(costs))\n\n def _conv(self, name, x, out_filters, stride):\n filter_size = 3\n n = filter_size * filter_size * out_filters\n return slim.layers.conv2d(x, out_filters, [filter_size, filter_size], stride=stride,\n padding='SAME', activation_fn=None,\n weights_initializer=tf.random_normal_initializer(stddev=np.sqrt(2.0/n)),\n scope=name)\n\n def _batch_norm(self, x):\n if self.mode == 'train':\n return slim.layers.batch_norm(x, scale=False, decay=0.9, scope='bn', is_training=True)\n else:\n return slim.layers.batch_norm(x, scale=False, decay=0.9, scope='bn', is_training=False)\n\n\n def _relu(self, x, leakiness=0.0):\n \"\"\"Relu, with optional leaky support.\"\"\"\n return tf.select(tf.less(x, 0.0), leakiness * x, x, name='leaky_relu')\n\n def _fully_connected(self, x, out_dim):\n return slim.layers.fully_connected(x, out_dim,\n weights_initializer=tf.uniform_unit_scaling_initializer(factor=1.0))\n\n def _global_avg_pool(self, x):\n assert x.get_shape().ndims == 4\n return tf.reduce_mean(x, [1, 2])","sub_path":"nets/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":6423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"438763944","text":"\"\"\"Interacting with external COVIZ data.\"\"\"\nimport logging\nimport pkg_resources\n\nimport pandas as pd\n\n_logger = logging.getLogger(__name__) # pylint: disable=invalid-name\n\n\ndef read_confirmed_time_series():\n \"\"\"Read latest new confirmed by day csv.\"\"\"\n _logger.info(\"Reading time series data...\")\n return pd.read_csv(\n pkg_resources.resource_stream(\n \"api\",\n \"COVID-19/csse_covid_19_data/csse_covid_19_time_series/\"\n \"time_series_covid19_confirmed_global.csv\",\n ),\n index_col=[\"Country/Region\", \"Province/State\"],\n )\n","sub_path":"backend/api/coviz.py","file_name":"coviz.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"59008293","text":"from flask import Blueprint, render_template, flash, redirect, url_for, request\nfrom flask_login import login_required, current_user\nfrom jobplus.models import User\nfrom jobplus.forms import CompanyProfileForm\n\ncompany = Blueprint('company', __name__, url_prefix='/company')\n\n@company.route('/profile/', methods=['GET', 'POST'])\n@login_required\ndef profile():\n if not current_user.is_company:\n flash('you don\\'t company user', 'warning')\n return redirect(url_for('front.index'))\n form = CompanyProfileForm(obj=current_user.company_detail)\n form.name.data = current_user.username\n form.email.data = current_user.email\n if form.validate_on_submit():\n form.updated_profile(current_user)\n flash('update company info success', 'success')\n return redirect(url_for('front.index'))\n return render_template('company/profile.html', form=form)\n","sub_path":"jobplus/jobplus/handlers/company.py","file_name":"company.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"586752502","text":"from Theta import Theta\nfrom Model import Model\nimport re\n\n# read Theta from file.\n# return valus: model, list of Thetas (corresponding to iterations), list of reported stats (corresponding to iterations)\ndef readHist(filename):\n \n # read file\n with open(filename, 'r') as f:\n inp = f.read()\n return Theta.fromString(inp, calcHmm = False)\n\n# read and parse loop file\ndef readLoop(filename):\n \n # read file\n with open(filename, 'r') as f:\n inp = f.read()\n \n # read model specs first\n pattern = re.compile(r\"\"\"\n ^\n Model\\ specifications:\\n (?P(.*\\n)+)\\n # model specs\n (?PAfter\\ 0\\ iterations:\\n(.*\\n)+) # rest of file\n $\n \"\"\", re.VERBOSE)\n \n # match input to pattern\n match = pattern.search(inp)\n assert match is not None\n \n # parse model specs\n model = Model.fromString(match.group(\"model\"))\n \n # read iteration by iteration\n params, stats = [], []\n inp = match.group(\"rest\")\n while (len(inp) > 0):\n \n # read Theta & stats from next iteration\n # define pattern\n pattern = re.compile(r\"\"\"\n ^\n After\\ (?P\\d+)\\ iterations: \\n\\n # iteration header\n (?P rec.+\\n\\n .+\\n (\\t.+\\n)+ ) \\n # Theta\n Statistics:\\n \\t.+\\n \\t(?P.+)\\n\\n # stats\n (?P (.*\\n)*) # rest of file\n $\n \"\"\", re.VERBOSE)\n # match input to pattern\n match = pattern.search(inp)\n assert match is not None\n\n assert int(match.group(\"nIter\")) == len(params)\n params.append(Theta.fromString(match.group(\"theta\")))\n \n # treat missing values ('.') as nan\n def _castFloat(x):\n if x == '.':\n return float('nan')\n return float(x)\n stats.append(map(_castFloat, re.findall(r\"([-|\\w|\\+|\\.]+)\", match.group(\"stats\"))))\n inp = match.group(\"rest\")\n \n return model, params, stats\n\n ","sub_path":"code/readUtils.py","file_name":"readUtils.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"566900745","text":"# This is supposed to be the most comprehensive code that allows for all doors and all feeders to be\n# activated via frequency thresholds. Definitely a work in progress still.\n\nimport trodesnetwork as tnp\nimport numpy as np\nimport matplotlib as plt\nimport serial\nimport matplotlib.pyplot as pyplot\n\n\n# create a queue for frequency calculations\nclass ElectrodeChannels(object):\n def __init__(self):\n self.array = []\n self.firing_rate = []\n self.frequency_plot = pyplot.figure()\n self.frequency_ax = self.frequency_plot.add_subplot(1, 1, 1)\n self.spikes_plot = pyplot.figure()\n self.spikes_ax = self.spikes_plot.add_subplot(1, 1, 1)\n self.first_time = -1\n\n def de_queue(self):\n return self.array.pop(0)\n\n def enqueue(self, val):\n if len(self.array) < 19:\n self.array.append(val)\n elif len(self.array) == 19:\n self.array.append(val)\n self.firing_rate.append([val, self.frequency()])\n else:\n self.de_queue()\n self.array.append(val)\n self.firing_rate.append([val, self.frequency()])\n #if self.check():\n # ser.write(\"FT08\\n\".encode(\"ascii\"))\n if len(self.firing_rate) > 1000:\n self.firing_rate.pop(0)\n\n def frequency(self):\n first = self.array[0]\n last = self.array[-1]\n return len(self.array) / (last - first) * 30000\n\n def one_channel_freq(self):\n freq_cutoff = 3\n time = 5\n frequency = 30000\n tf = time * frequency\n first = self.firing_rate[0][0]\n last = self.firing_rate[-1][0]\n if last - first < tf:\n return False\n else:\n current = last\n index = len(self.firing_rate)\n while last - current < tf:\n index -= 1\n current = self.firing_rate[index][0]\n if self.firing_rate[index][1] < freq_cutoff:\n return False\n return True\n\n def spikes(self, array):\n temporaryx = []\n temporaryy = []\n for j in range(len(array)):\n temporaryx.append(array[j][0])\n temporaryy.append(array[j][1])\n self.spikes_ax.plot(temporaryx, temporaryy)\n self.spikes_plot.canvas.draw()\n\n def plot_frequency(self):\n dataArray = self.firing_rate\n xar = []\n yar = []\n for pair in dataArray:\n xar.append((pair[0] - self.first_time) / 30000)\n yar.append(pair[1])\n self.frequency_ax.clear()\n self.frequency_ax.plot(xar, yar)\n self.frequency_plot.canvas.draw()\n\n\ndef read_sensors():\n string = ''\n new = ''\n while new != '\\n':\n new = str(ser.read())\n if new != '':\n string += new\n ser.reset_input_buffer()\n return string\n\n\ndef interpret_string(string):\n if string[0:2] == 'MS':\n close_door_behind(string[2])\n elif string[0:2] == 'MF':\n ser.write(('FT0' + string[3] + '\\n').encode('ascii'))\n\n\ndef open_door(door):\n ser.write((\"D0\" + door + \"0\\n\").encode(\"ascii\"))\n read_sensors()\n code = read_sensors()\n while code[0:2] != 'MS':\n code = read_sensors()\n interpret_string(code)\n\n\ndef close_door_behind(door):\n while 1:\n if read_sensors() != 'MS' + door + '1':\n break\n ser.write(('D0' + door + '1\\n').encode('ascii'))\n\n\n''' Rewrite this function for PCA\ndef is_good(spike):\n peaks = []\n for e in range(len(spike)-2):\n if (spike[e]>spike[e+1] and spike[e+1]spike[e+2]):\n peaks.append(spike[e+1])\n if len(peaks) != 2:\n return False\n else:\n if peaks[0] in range(60, 150) and peaks[1] in range(-60,150):\n return True\n elif peaks[1] in range(60,150) and peaks[0] in range(-60,150):\n return True\n else:\n return False\n'''\n\n\ndef check_threshold(data, stamp):\n# function that checks if weighted values remain above a certain frequency for a time\n num_doors = 8\n num_channels = 32\n weights = np.zeros((num_doors, num_channels))\n for l in range(num_doors):\n current = []\n for m in range(num_channels):\n if str(m + 1) in data and sum(weights[l]) != 0:\n temp = []\n for o in range(len(data[str(m+1)].firing_rate)):\n temp.append([data[str(m+1)].firing_rate[o][0], data[str(m+1)].firing_rate[o][1]*weights[l][m]/sum(weights[l])])\n current.append(temp)\n if above_threshold(current, stamp):\n return l+1\n return 0\n\n\ndef above_threshold(array, stamp):\n # helper function that does number crunching for check_threshold()\n time = 5 # in seconds\n frequency = 30000\n tf = time*frequency\n threshold = 3 # in Hz\n lasts = []\n for chan in array:\n w = chan[-1][0]\n while chan[-1][0] - chan[w][0] < tf:\n w -= 1\n lasts.append(chan[w+1:-1])\n for vals in lasts:\n lasts[vals] = sum(vals)/len(vals)\n if sum(lasts) >= threshold:\n return True\n return False\n\n\n# Define this for breaking loop, comes in later\nstillrunning = True\ndef stoploop():\n global stillrunning\n stillrunning = False\n\n\n# Definition of network client class\nclass PythonClient(tnp.AbstractModuleClient):\n def recv_quit(self):\n stoploop()\n# Initialize network\nnetwork = PythonClient(\"TestPython\", \"tcp://127.0.0.1\", 49152)\nif network.initialize() != 0:\n print(\"Network could not successfully initialize\")\n del network\n quit()\n# Initialize Maze Control\nser = serial.Serial(\"/dev/ttyUSB0\", 9600)\nser._timeout = .1\nif not ser.isOpen():\n print(\"Serial not open\")\n quit()\nchannels = ['1,0', '2,0', '3,0']\ndatastream = network.subscribeSpikesData(100, channels)\ndatastream.initialize() # Initialize the streaming object\nbuf = datastream.create_numpy_array()\ntimestamp = 0\npyplot.ion()\ndata = {}\nfor channel in channels:\n data[channel[0]] = ElectrodeChannels()\n\n# Continuously get data until Trodes tells us to quit, which triggers the function that flips the \"stillrunning\" variable\nwhile stillrunning:\n # Get the number of data points that came in\n n = datastream.available(1000) # timeout in ms\n # Go through and grab all the data packets, processing one at a time\n for p in range(n):\n timestamp = datastream.getData()\n k = []\n for i in range(len(buf[0][3])):\n k.append(buf[0][3][i][1])\n print(buf)\n if max(k) < 1000 and min(k) > -600:\n if data[str(buf[0][0])].first_time == -1:\n data[str(buf[0][0])].first_time = buf[0][2]\n data[str(buf[0][0])].enqueue(buf[0][2])\n data[str(buf[0][0])].spikes(buf[0][3])\n data[str(buf[0][0])].plot_frequency()\n\n num = check_threshold(data, buf[0][2]) # I don't know if this works with blank arrays, may need conditional.\n if num != 0:\n open_door(num)\n\n# Cleanup\ndel network\n","sub_path":"SpikesMaze.py","file_name":"SpikesMaze.py","file_ext":"py","file_size_in_byte":7043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"438578850","text":"# Distributed under the MIT License.\n# See LICENSE.txt for details.\n\nimport logging\nimport os\nimport re\n\n\nclass MissingExpectedOutputError(Exception):\n def __init__(self, missing_files):\n self.missing_files = missing_files\n\n def __str__(self):\n return \"Expected output files are missing: {}\".format(\n self.missing_files)\n\n\ndef clean_output(input_file, output_dir, force):\n \"\"\"\n Deletes output files specified in the `input_file` from the `output_dir`,\n raising an error if the expected output files were not found.\n\n The `input_file` must list its expected output files in a comment, with the\n list of files indented by two spaces:\n ```yaml\n # ExpectedOutput:\n # Reduction.h5\n # Volume0.h5\n ```\n \"\"\"\n found_indentation = None\n missing_files = []\n for line in open(input_file, 'r'):\n # Iterate through the file until we find the `ExpectedOutput` comment\n if found_indentation is None:\n matched_indentation = re.match('#([ ]*)ExpectedOutput:', line)\n if matched_indentation is not None:\n found_indentation = matched_indentation.groups()[0] + ' '\n else:\n # Now collect the output files listed in the comment.\n # We look for lines that are indented by two spaces relative to the\n # preceding `ExpectedOutput` comment\n matched_output_file = re.match('#' + found_indentation + '(.+)',\n line)\n if matched_output_file is None:\n logging.debug(\"Reached end of expected output file list.\")\n break\n else:\n expected_output_file = os.path.join(\n output_dir,\n matched_output_file.groups()[0])\n logging.debug(\"Attempting to remove file {}...\".format(\n expected_output_file))\n if os.path.exists(expected_output_file):\n os.remove(expected_output_file)\n logging.info(\n \"Removed file {}.\".format(expected_output_file))\n elif not force:\n missing_files.append(expected_output_file)\n logging.error(\"Expected file {} was not found.\".format(\n expected_output_file))\n if found_indentation is None:\n logging.warning(\n \"Input file {} does not list `ExpectedOutput` files.\".format(\n input_file))\n # Raise an error if expected files were not found\n if len(missing_files) > 0:\n raise MissingExpectedOutputError(missing_files)\n\n\ndef parse_args():\n import argparse as ap\n parser = ap.ArgumentParser(description=\"\")\n parser.add_argument('--input-file',\n required=True,\n help=\"Path to the input file of the run to clean up\")\n parser.add_argument('--output-dir',\n required=True,\n help=\"Output directory of the run to clean up\")\n parser.add_argument('-v',\n '--verbose',\n action='count',\n default=0,\n help=\"Verbosity (-v, -vv, ...)\")\n parser.add_argument('--force',\n action='store_true',\n help=\"Suppress all errors\")\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n\n # Set the log level\n logging.basicConfig(level=logging.WARNING - args.verbose * 10)\n\n clean_output(args.input_file, args.output_dir, args.force)\n","sub_path":"tools/CleanOutput.py","file_name":"CleanOutput.py","file_ext":"py","file_size_in_byte":3629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"118791277","text":"import numpy as np\nimport pandas as pd \n\nimport cufflinks as cf\nimport plotly\nimport plotly.offline as py\nimport plotly.graph_objs as go\nimport plotly.express as px\n\ncf.go_offline() # required to use plotly offline (no account required).\npy.init_notebook_mode() # graphs charts inline (IPython).\n\n\ndef test_shotDis_Freq():\n '''\n This function plot the frequency of FGM, FGA or FG% based on the season and 5 players and the selected attribute\n \n Inputs - \n season: Selected Season\n player1-5: The 5 selected players\n feat: the selected attribute (FGM, FGA or FG%)\n \n Output - \n Frequency of attributed from different distances \n '''\n \n# season, player1, player2, player3, player4, player5, feat\n\n\n stats = pd.read_csv('shotDis_2019-2020.csv')\n stats.fillna(0)\n assert isinstance(stats, pd.DataFrame)\n assert not stats is None\n assert ('FGM' and 'FGM.1' and 'FGM.2' and 'FGM.3' and 'FGM.4'and'FGM.5'and'FGM.6'and'FGM.7'and'FGM.8'and'FGA'and'FGA.1'and'FGA.2'and'FGA.3'and 'FGA.4'and'FGA.5'and'FGA.6'and'FGA.7'and 'FGA.8'and'FG_PCT'and'FG_PCT.1'and'FG_PCT.2'and'FG_PCT.3'and 'FG_PCT.4'and'FG_PCT.5'and'FG_PCT.6'and'FG_PCT.7'and 'FG_PCT.8') in stats\n \n # Add row for league averages \n avg = {'PLAYER_NAME': 'League Average',\n 'TEAM_ABBREVIATION': 'AVG'}\n assert isinstance(avg, dict)\n \n for i in list(stats.columns)[2:]:\n avg[i] = stats[i].mean()\n stats = stats.append(avg, ignore_index=True)\n \n # Find the total FGM, FGA, FG% for all distance \n stats['FGM_Tot'] = stats['FGM']+stats['FGM.1']+stats['FGM.2']+stats['FGM.3']+stats['FGM.4']+stats['FGM.5']+stats['FGM.6']+stats['FGM.7']+stats['FGM.8']\n stats['FGA_Tot'] = stats['FGA']+stats['FGA.1']+stats['FGA.2']+stats['FGA.3']+stats['FGA.4']+stats['FGA.5']+stats['FGA.6']+stats['FGA.7']+stats['FGA.8']\n stats['FG%_Tot'] = stats['FG_PCT']+stats['FG_PCT.1']+stats['FG_PCT.2']+stats['FG_PCT.3']+stats['FG_PCT.4']+stats['FG_PCT.5']+stats['FG_PCT.6']+stats['FG_PCT.7']+stats['FG_PCT.8']\n \n \n if 'FGM' == 'FGM':\n ff = 3\n ffstr = 'FGM_Tot'\n elif 'FGM' == 'FGA':\n ff = 4\n ffstr = 'FGA_Tot'\n elif 'FGM' == 'FG%':\n ff = 5\n ffstr = 'FG%_Tot'\n\n # Find the row for the input player \n player_name1 = stats.loc[stats['PLAYER_NAME'] == 'James Harden']\n player_name2 = stats.loc[stats['PLAYER_NAME'] == 'Chris Paul']\n player_name3 = stats.loc[stats['PLAYER_NAME'] == 'Kemba Walker']\n player_name4 = stats.loc[stats['PLAYER_NAME'] == 'Anthony Davis']\n player_name5 = stats.loc[stats['PLAYER_NAME'] == 'Ben Simmons']\n \n assert isinstance(player_name1, pd.DataFrame)\n assert not player_name1 is None\n assert isinstance(player_name2, pd.DataFrame)\n assert not player_name2 is None\n assert isinstance(player_name3, pd.DataFrame)\n assert not player_name3 is None\n assert isinstance(player_name4, pd.DataFrame)\n assert not player_name4 is None\n assert isinstance(player_name5, pd.DataFrame)\n assert not player_name5 is None\n \n # Find the Frequency of shots at each distance for the whole seasons average\n league_avg = stats.loc[stats['PLAYER_NAME'] == 'League Average']\n assert isinstance(league_avg, pd.DataFrame)\n assert not league_avg is None\n \n freq_league_avg = []\n for i in range(ff,len(list(league_avg.columns)),3):\n freq_league_avg.append(int(league_avg[list(stats.columns)[i]]/league_avg[ffstr]*100))\n del(freq_league_avg[-1])\n assert isinstance(freq_league_avg, list)\n assert len(freq_league_avg) == 9\n \n \n # Find the Frequency of shots at each distance for the input player\n freq_player1 = []\n for i in range(ff,len(list(player_name1.columns)),3):\n freq_player1.append(int(player_name1[list(stats.columns)[i]]/player_name1[ffstr]*100))\n del(freq_player1[-1])\n assert isinstance(freq_player1, list)\n assert len(freq_player1) == 9\n \n freq_player2 = []\n for i in range(ff,len(list(player_name2.columns)),3):\n freq_player2.append(int(player_name2[list(stats.columns)[i]]/player_name2[ffstr]*100))\n del(freq_player2[-1])\n assert isinstance(freq_player2, list)\n assert len(freq_player2) == 9\n \n freq_player3 = []\n for i in range(ff,len(list(player_name3.columns)),3):\n freq_player3.append(int(player_name3[list(stats.columns)[i]]/player_name3[ffstr]*100))\n del(freq_player3[-1])\n assert isinstance(freq_player3, list)\n assert len(freq_player3) == 9\n \n freq_player4 = []\n for i in range(ff,len(list(player_name4.columns)),3):\n freq_player4.append(int(player_name4[list(stats.columns)[i]]/player_name4[ffstr]*100))\n del(freq_player4[-1])\n assert isinstance(freq_player4, list)\n assert len(freq_player4) == 9\n \n freq_player5 = []\n for i in range(ff,len(list(player_name5.columns)),3):\n freq_player5.append(int(player_name5[list(stats.columns)[i]]/player_name5[ffstr]*100))\n del(freq_player5[-1])\n assert isinstance(freq_player5, list)\n assert len(freq_player5) == 9\n \n # Format Data to plot\n distances = ['Less Than 5 ft.', '5-9 ft.', '10-14 ft.', '15-19 ft.', '20-24 ft.', '25-29 ft.', '30-34 ft.', '35-39 ft.', '40+ ft.']\n assert isinstance(distances, list)\n assert len(distances) == 9\n \n plot = pd.DataFrame(np.array([freq_league_avg,freq_player1,freq_player2,freq_player3,freq_player4,freq_player5]),\n columns=distances,\n index = ['League Average', 'James Harden','Chris Paul','Kemba Walker','Anthony Davis','Ben Simmons'])\n assert isinstance(plot, pd.DataFrame)\n assert not plot is None\n assert len(plot) == 6\n assert len(plot.columns) == len(distances)\n \n to_plot = plot.T\n \n # Plot Data\n fig = go.Figure()\n \n fig.add_trace(go.Scatter(x=to_plot.index, y=to_plot['League Average'], name = 'League Average',\n line = dict(color='royalblue', width=4, dash='dashdot')))\n \n fig.add_trace(go.Scatter(x=to_plot.index, y=to_plot['James Harden'], name = 'James Harden',\n line = dict(color='firebrick', width=4, dash='dashdot')))\n fig.add_trace(go.Scatter(x=to_plot.index, y=to_plot['Chris Paul'], name = 'Chris Paul',\n line = dict(color='seagreen', width=4, dash='dashdot')))\n fig.add_trace(go.Scatter(x=to_plot.index, y=to_plot['Kemba Walker'], name = 'Kemba Walker',\n line = dict(color='orange', width=4, dash='dashdot')))\n fig.add_trace(go.Scatter(x=to_plot.index, y=to_plot['Anthony Davis'], name = 'Anthony Davis',\n line = dict(color='black', width=4, dash='dashdot')))\n fig.add_trace(go.Scatter(x=to_plot.index, y=to_plot['Ben Simmons'], name = 'Ben Simmons',\n line = dict(color='plum', width=4, dash='dashdot')))\n \n max_val = max(max(to_plot['James Harden']),max(to_plot['Chris Paul']),max(to_plot['Kemba Walker']),max(to_plot['Anthony Davis']),max(to_plot['Ben Simmons']),max(to_plot['League Average']))+1\n \n fig.add_shape(\n # Line Vertical\n dict(\n type=\"line\",\n x0=4,\n y0=-1,\n x1=4,\n y1=max_val,\n \n line=dict(\n color=\"rgb(150,150,150)\",\n width=3,\n dash='dash'\n )\n ))\n \n fig.add_trace(go.Scatter(\n x=[list(to_plot.index)[4]],\n y=[max_val],\n text=[' 3 Point Distance'],\n mode=\"text\",\n name = '3 Point Distance',\n showlegend=False\n ))\n \n fig.update_layout(title = 'Frequency of FGM',\n xaxis_title = 'Distances',\n yaxis_title = 'Frequency %')\n \n fig.show()\n \n return","sub_path":"pyTest/test_ShotDisFreq.py","file_name":"test_ShotDisFreq.py","file_ext":"py","file_size_in_byte":7848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"557857456","text":"import os\nimport sys\n\nsys.path.append(\"../src\")\nimport localmodule\n\n\n# Define constants.\nunits = localmodule.get_units()\nbg_durations = [1, 2, 5, 10, 30, 60, 120, 300, 600, 1800, 3600, 7200]\nscript_name = \"027_compute-full-background-summaries.py\"\n\n\n# Create folder.\nsbatch_dir = os.path.join(script_name[:-3], \"sbatch\")\nos.makedirs(sbatch_dir, exist_ok=True)\nslurm_dir = os.path.join(script_name[:-3], \"slurm\")\nos.makedirs(slurm_dir, exist_ok=True)\n\n\n# Loop over background durations.\nfor bg_duration in bg_durations:\n # Define string for background duration (prepend zeros).\n T_str = str(bg_duration).zfill(4)\n\n # Define file path.\n file_path = os.path.join(\n sbatch_dir, script_name[:3] + \"_T-\" + T_str + \".sh\")\n\n # Open shell file.\n with open(file_path, \"w\") as f:\n # Print header.\n f.write(\n \"# This shell script executes the Slurm jobs for computing \" +\n \"backgrounds on clips.\\n\")\n f.write(\"\\n\")\n\n # Loop over recording units.\n for unit_str in units:\n\n # Define job name.\n job_name = \"_\".join([script_name[:3], \"T-\" + T_str, unit_str])\n sbatch_str = \"sbatch \" + job_name + \".sbatch\"\n\n # Write SBATCH command to shell file.\n f.write(sbatch_str + \"\\n\")\n\n\n # Grant permission to execute the shell file.\n # https://stackoverflow.com/a/30463972\n mode = os.stat(file_path).st_mode\n mode |= (mode & 0o444) >> 2\n os.chmod(file_path, mode)\n","sub_path":"sbatch/generate_027-shell.py","file_name":"generate_027-shell.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"417807943","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.macosx-10.7-x86_64/egg/calibration_client/__init__.py\n# Compiled at: 2019-08-21 18:40:35\n# Size of source mod 2**32: 1762 bytes\n__doc__ = 'Client library for encapsulating and managing the interaction with the\\nCalibration Constants Catalogue Web Application'\nimport importlib.util\n__author__ = 'Luís Maia '\n__version__ = '6.1.3'\noauthlib_spec = importlib.util.find_spec('oauthlib')\nrequests_spec = importlib.util.find_spec('requests')\nrequests_oauthlib_spec = importlib.util.find_spec('requests_oauthlib')\noauth2_xfel_client_spec = importlib.util.find_spec('oauth2_xfel_client')\nif oauthlib_spec is not None or requests_spec is not None or requests_oauthlib_spec is not None or oauth2_xfel_client_spec is not None:\n import oauthlib, requests, requests_oauthlib, oauth2_xfel_client\n if oauthlib.__version__ < '3.0.2':\n msg = 'You are using oauthlib version %s. Please upgrade it to version 3.0.2.'\n raise Warning(msg % oauthlib.__version__)\n if requests.__version__ < '2.22.0':\n msg = 'You are using requests version %s. Please upgrade it to version 2.22.0.'\n raise Warning(msg % requests.__version__)\n if requests_oauthlib.__version__ < '1.2.0':\n msg = 'You are using requests_oauthlib version %s. Please upgrade it to version 1.2.0.'\n raise Warning(msg % requests_oauthlib.__version__)\n if oauth2_xfel_client.__version__ < '5.1.0':\n msg = 'You are using oauth2_xfel_client version %s. Please upgrade it to version 5.1.0.'\n raise Warning(msg % oauth2_xfel_client.__version__)","sub_path":"pycfiles/calibraxis-0.2.0-py2.py3-none-any/__init__.cpython-36.py","file_name":"__init__.cpython-36.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"389140037","text":"\"\"\"Project URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/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\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, re_path\nfrom django.views.generic import TemplateView\nfrom profiles import views as profiles_views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('profile/view', profiles_views.viewOnline_Owner, name='viewowner'),\n path('', TemplateView.as_view(template_name=\"home.html\"), name='index'),\n path('login/', profiles_views.login_request, name='login'),\n path('check//', profiles_views.login_check, name='logincheck'),\n path('register/', profiles_views.register, name='register'),\n path('profile/usr/', profiles_views.userProfile, name='usrprofile'),\n path('createfolder/', profiles_views.createFolder, name='create'),\n path('logout', profiles_views.SiteLogoutView.as_view(), name='logout'),\n path('profile/', profiles_views.EditProfileView.as_view(), name='profile'),\n path('profile/viewfile/', profiles_views.viewfilebyusername, name='view'),\n path('profile/viewDetail/', profiles_views.viewDetail, name='viewDetail'),\n path('profile/document/', TemplateView.as_view(template_name=\"document.html\"), name='document'),\n path('profile/upinf/', profiles_views.upinf, name='upload'),\n path('profile/usr/changepassword/', profiles_views.change_password, name='change_password'),\n path('profile/downloadfile/', profiles_views.downloadfileInProfile, name='downloadInProfile'),\n path('profile/downloadFile/', profiles_views.downloadfileInSharing, name='download1'),\n path('profile/deletefile/', profiles_views.deleteFile, name='delete'),\n path('profile/viewlicensed/revoke', profiles_views.revokeFile_Offline, name='revoke'),\n path('profile/viewlicensed/revoKe', profiles_views.revokeFile_Online, name='revoKe'),\n path('profile/viewlicensed/', profiles_views.view_revoke, name='view_revoke'),\n path('viewlink/', profiles_views.createLink, name='createLink'),\n path('sendmail/', profiles_views.sendMail, name='sendmail'),\n path('create/', profiles_views.create, name='cr'),\n path('linkshare//', profiles_views.linkshare),\n path('sharefile/return/', profiles_views.re, name='returnshare'),\n path('back/', profiles_views.back, name='back'),\n path('otponline/', profiles_views.sendMailOTP, name='sendotp'),\n path('otpOnline/', profiles_views.sendmailOTP, name='sendOtp'),\n path('otponline/viewonline/', profiles_views.viewOnline, name='viewonline'),\n path('sharefile/', profiles_views.viewsharefile, name='viewsharefile'),\n]\n","sub_path":"Project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"586954433","text":"import requests, os, re, pickle, sys\nfrom bs4 import BeautifulSoup\n\ndef hot_souPot(url):\n source_code = requests.get(url)\n plain_text = source_code.text\n soup = BeautifulSoup(plain_text, \"html.parser\")\n return soup\n\n# variable for os\ncwd = os.getcwd()\n\n# variable for tourist\nbaseurl = \"http://old-engineering.tumblr.com/\"\nif baseurl[-1] == \"/\":\n baseurl = baseurl[:-1]\nmonthLinksFile = cwd + \"/monthLinksList.txt\"\npostLinksFile = cwd + \"/postLinksList.txt\"\nmonthLinks = []\npostLinks = []\nyymmUrl_regx = re.compile(\"\\/+(archive)+\\/(\\d{4})+\\/+(\\d+)\")\npostUrl_regx = re.compile(baseurl + \"/\" + \"(post\\/)(.*)\")\n\n# monthley links grabber\ndef linksChecker(linksFile):\n linksBucket = []\n if os.access(linksFile, os.F_OK) == True and os.path.getsize(linksFile) > 10:\n with open(linksFile, \"rb\") as f:\n linksBucket = pickle.load(f)\n return linksBucket\n else:\n return False\n\nif linksChecker(monthLinksFile) == False:\n url = baseurl + \"/archive\"\n print(url)\n source_code = requests.get(url)\n plain_text = source_code.text\n soup = BeautifulSoup(plain_text, \"html.parser\")\n month_links_grabber = soup.find_all(href = yymmUrl_regx)\n print(\"start grabbing monthley page links from archive page\")\n for i in range(0, len(month_links_grabber)):\n getUrl = baseurl + month_links_grabber[i]['href']\n monthLinks.append(getUrl)\n print(getUrl)\n with open(monthLinksFile, \"wb\") as f:\n pickle.dump(monthLinks,f)\n print(\"done\")\n","sub_path":"archive-tourist_monthfinder.py","file_name":"archive-tourist_monthfinder.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"250715844","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python\nimport re\nfrom math import pi, cos, sin, radians, acos\nR = 6371\n\n\ndef ExtractPosition(PositionStr):\n items = re.search('(\\d+)\\D(\\d+)\\D(\\d+)\\D(\\w)', PositionStr).groups()\n if 'W' in PositionStr or 'S' in PositionStr:\n return radians(-(int(items[0]) * 3600\n + int(items[1]) * 60 + int(items[2])) / 3600.0)\n return radians((int(items[0]) * 3600 + int(items[1]) * 60\n + int(items[2])) / 3600.0)\n\n\ndef distance(first, second):\n if len(first.split()) == 2:\n first = first.split()\n else:\n first = first.split(',')\n if len(second.split()) == 2:\n second = second.split()\n else:\n second = second.split(',')\n FirstLatitude, FirstLongitude, SecondLatitude, SecondLongitude = map(\n ExtractPosition, first + second)\n DirectDistance = sin(FirstLatitude) * sin(SecondLatitude) + cos(FirstLatitude) * \\\n cos(SecondLatitude) * cos(FirstLongitude - SecondLongitude)\n if acos(DirectDistance) == 0:\n return pi * R\n return round(R * acos(DirectDistance), 1)\n\n\nif __name__ == '__main__':\n # These \"asserts\" using only for self-checking and not necessary for\n # auto-testing\n def almost_equal(checked, correct, significant_digits=1):\n precision = 0.1 ** significant_digits\n return correct - precision < checked < correct + precision\n\n assert almost_equal(\n distance(u\"51°28′48″N 0°0′0″E\", u\"46°12′0″N, 6°9′0″E\"), 739.2), \"From Greenwich to Geneva\"\n assert almost_equal(\n distance(u\"90°0′0″N 0°0′0″E\", u\"90°0′0″S, 0°0′0″W\"), 20015.1), \"From South to North\"\n assert almost_equal(\n distance(u\"33°51′31″S, 151°12′51″E\", u\"40°46′22″N 73°59′3″W\"), 15990.2), \"Opera Night\"\n distance(u\"48°27′0″N,34°59′0″E\", u\"15°47′56″S 47°52′0″W\")\n","sub_path":"Earth Distances.py","file_name":"Earth Distances.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"375204605","text":"import cv2\r\nimport numpy as np\r\ndef nothing(x):\r\n pass\r\ncap=cv2.VideoCapture(0)\r\ncv2.namedWindow('trackbar')\r\ncv2.createTrackbar('L-H','trackbar',0,179,nothing)\r\ncv2.createTrackbar('L-S','trackbar',0,255,nothing)\r\ncv2.createTrackbar('L-V','trackbar',0,255,nothing)\r\ncv2.createTrackbar('U-H','trackbar',179,179,nothing)\r\ncv2.createTrackbar('U-S','trackbar',255,255,nothing)\r\ncv2.createTrackbar('U-V','trackbar',255,255,nothing)\r\nwhile True:\r\n x,frame=cap.read()\r\n hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)\r\n lh=cv2.getTrackbarPos('L-H','trackbar')\r\n ls=cv2.getTrackbarPos('L-S','trackbar')\r\n lv=cv2.getTrackbarPos('L-V','trackbar')\r\n uh=cv2.getTrackbarPos('U-H','trackbar')\r\n us=cv2.getTrackbarPos('U-S','trackbar')\r\n uv=cv2.getTrackbarPos('U-V','trackbar')\r\n\r\n lrange=np.array([lh,ls,lv])\r\n urange=np.array([uh,us,uv])\r\n mask=cv2.inRange(hsv,lrange,urange)\r\n hotspot=cv2.bitwise_and(frame,frame,mask=mask)\r\n \r\n contours, heirarchy=cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)\r\n areas=[cv2.contourArea(c) for c in contours]\r\n max_index=np.argmax(areas)\r\n max_contour=contours[max_index]\r\n cv2.drawContours(frame,[max_contour],-1,(0,255,0),5)\r\n\r\n cv2.imshow('frame',frame)\r\n cv2.imshow('a',mask)\r\n cv2.imshow('b',hotspot)\r\n key=cv2.waitKey(1)\r\n if key==27:\r\n break\r\n\r\n","sub_path":"day7/q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"223632444","text":"from math import gcd\nN=int(input())\nfor _ in range(N):\n s = input()\n if '(' not in s:\n a=int(s[2:])\n b=10**len(s[2:])\n temp=gcd(a,b)\n a=a//temp\n b=b//temp\n print('{0}/{1}'.format(a,b))\n elif s[2] == '(':\n a=int(s[3:-1])\n b=int('9'*len(s[3:-1]))\n temp=gcd(a,b)\n a=a//temp\n b=b//temp\n print('{0}/{1}'.format(a,b))\n else:\n x,y=s[2:].split('(')\n y=y[:-1]\n a=int(x+y)-int(x)\n b=int('9'*len(y)+'0'*len(x))\n temp=gcd(a,b)\n a=a//temp\n b=b//temp\n print('{0}/{1}'.format(a,b))\n","sub_path":"백준/Python/알고파/수학/5376(소수를 분수로).py","file_name":"5376(소수를 분수로).py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"571109167","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom mist_api_v2.models.base_model_ import Model\nfrom mist_api_v2 import util\n\n\nclass CronSchedule(Model):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).\n\n Do not edit the class manually.\n \"\"\"\n\n def __init__(self, schedule_type=None, minute=None, hour=None, day_of_month=None, month_of_year=None, day_of_week=None, start_after=None, expires=None, max_run_count=None): # noqa: E501\n \"\"\"CronSchedule - a model defined in OpenAPI\n\n :param schedule_type: The schedule_type of this CronSchedule. # noqa: E501\n :type schedule_type: str\n :param minute: The minute of this CronSchedule. # noqa: E501\n :type minute: str\n :param hour: The hour of this CronSchedule. # noqa: E501\n :type hour: str\n :param day_of_month: The day_of_month of this CronSchedule. # noqa: E501\n :type day_of_month: str\n :param month_of_year: The month_of_year of this CronSchedule. # noqa: E501\n :type month_of_year: str\n :param day_of_week: The day_of_week of this CronSchedule. # noqa: E501\n :type day_of_week: str\n :param start_after: The start_after of this CronSchedule. # noqa: E501\n :type start_after: datetime\n :param expires: The expires of this CronSchedule. # noqa: E501\n :type expires: datetime\n :param max_run_count: The max_run_count of this CronSchedule. # noqa: E501\n :type max_run_count: int\n \"\"\"\n self.openapi_types = {\n 'schedule_type': str,\n 'minute': str,\n 'hour': str,\n 'day_of_month': str,\n 'month_of_year': str,\n 'day_of_week': str,\n 'start_after': datetime,\n 'expires': datetime,\n 'max_run_count': int\n }\n\n self.attribute_map = {\n 'schedule_type': 'schedule_type',\n 'minute': 'minute',\n 'hour': 'hour',\n 'day_of_month': 'day_of_month',\n 'month_of_year': 'month_of_year',\n 'day_of_week': 'day_of_week',\n 'start_after': 'start_after',\n 'expires': 'expires',\n 'max_run_count': 'max_run_count'\n }\n\n self._schedule_type = schedule_type\n self._minute = minute\n self._hour = hour\n self._day_of_month = day_of_month\n self._month_of_year = month_of_year\n self._day_of_week = day_of_week\n self._start_after = start_after\n self._expires = expires\n self._max_run_count = max_run_count\n\n @classmethod\n def from_dict(cls, dikt) -> 'CronSchedule':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The CronSchedule of this CronSchedule. # noqa: E501\n :rtype: CronSchedule\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def schedule_type(self):\n \"\"\"Gets the schedule_type of this CronSchedule.\n\n\n :return: The schedule_type of this CronSchedule.\n :rtype: str\n \"\"\"\n return self._schedule_type\n\n @schedule_type.setter\n def schedule_type(self, schedule_type):\n \"\"\"Sets the schedule_type of this CronSchedule.\n\n\n :param schedule_type: The schedule_type of this CronSchedule.\n :type schedule_type: str\n \"\"\"\n allowed_values = [\"crontab\"] # noqa: E501\n if schedule_type not in allowed_values:\n raise ValueError(\n \"Invalid value for `schedule_type` ({0}), must be one of {1}\"\n .format(schedule_type, allowed_values)\n )\n\n self._schedule_type = schedule_type\n\n @property\n def minute(self):\n \"\"\"Gets the minute of this CronSchedule.\n\n\n :return: The minute of this CronSchedule.\n :rtype: str\n \"\"\"\n return self._minute\n\n @minute.setter\n def minute(self, minute):\n \"\"\"Sets the minute of this CronSchedule.\n\n\n :param minute: The minute of this CronSchedule.\n :type minute: str\n \"\"\"\n if minute is None:\n raise ValueError(\"Invalid value for `minute`, must not be `None`\") # noqa: E501\n\n self._minute = minute\n\n @property\n def hour(self):\n \"\"\"Gets the hour of this CronSchedule.\n\n\n :return: The hour of this CronSchedule.\n :rtype: str\n \"\"\"\n return self._hour\n\n @hour.setter\n def hour(self, hour):\n \"\"\"Sets the hour of this CronSchedule.\n\n\n :param hour: The hour of this CronSchedule.\n :type hour: str\n \"\"\"\n if hour is None:\n raise ValueError(\"Invalid value for `hour`, must not be `None`\") # noqa: E501\n\n self._hour = hour\n\n @property\n def day_of_month(self):\n \"\"\"Gets the day_of_month of this CronSchedule.\n\n\n :return: The day_of_month of this CronSchedule.\n :rtype: str\n \"\"\"\n return self._day_of_month\n\n @day_of_month.setter\n def day_of_month(self, day_of_month):\n \"\"\"Sets the day_of_month of this CronSchedule.\n\n\n :param day_of_month: The day_of_month of this CronSchedule.\n :type day_of_month: str\n \"\"\"\n if day_of_month is None:\n raise ValueError(\"Invalid value for `day_of_month`, must not be `None`\") # noqa: E501\n\n self._day_of_month = day_of_month\n\n @property\n def month_of_year(self):\n \"\"\"Gets the month_of_year of this CronSchedule.\n\n\n :return: The month_of_year of this CronSchedule.\n :rtype: str\n \"\"\"\n return self._month_of_year\n\n @month_of_year.setter\n def month_of_year(self, month_of_year):\n \"\"\"Sets the month_of_year of this CronSchedule.\n\n\n :param month_of_year: The month_of_year of this CronSchedule.\n :type month_of_year: str\n \"\"\"\n if month_of_year is None:\n raise ValueError(\"Invalid value for `month_of_year`, must not be `None`\") # noqa: E501\n\n self._month_of_year = month_of_year\n\n @property\n def day_of_week(self):\n \"\"\"Gets the day_of_week of this CronSchedule.\n\n\n :return: The day_of_week of this CronSchedule.\n :rtype: str\n \"\"\"\n return self._day_of_week\n\n @day_of_week.setter\n def day_of_week(self, day_of_week):\n \"\"\"Sets the day_of_week of this CronSchedule.\n\n\n :param day_of_week: The day_of_week of this CronSchedule.\n :type day_of_week: str\n \"\"\"\n if day_of_week is None:\n raise ValueError(\"Invalid value for `day_of_week`, must not be `None`\") # noqa: E501\n\n self._day_of_week = day_of_week\n\n @property\n def start_after(self):\n \"\"\"Gets the start_after of this CronSchedule.\n\n The datetime when schedule should start running, e.g 2021-09-22T18:19:28Z # noqa: E501\n\n :return: The start_after of this CronSchedule.\n :rtype: datetime\n \"\"\"\n return self._start_after\n\n @start_after.setter\n def start_after(self, start_after):\n \"\"\"Sets the start_after of this CronSchedule.\n\n The datetime when schedule should start running, e.g 2021-09-22T18:19:28Z # noqa: E501\n\n :param start_after: The start_after of this CronSchedule.\n :type start_after: datetime\n \"\"\"\n\n self._start_after = start_after\n\n @property\n def expires(self):\n \"\"\"Gets the expires of this CronSchedule.\n\n The datetime when schedule should expire, e.g 2021-09-22T18:19:28Z # noqa: E501\n\n :return: The expires of this CronSchedule.\n :rtype: datetime\n \"\"\"\n return self._expires\n\n @expires.setter\n def expires(self, expires):\n \"\"\"Sets the expires of this CronSchedule.\n\n The datetime when schedule should expire, e.g 2021-09-22T18:19:28Z # noqa: E501\n\n :param expires: The expires of this CronSchedule.\n :type expires: datetime\n \"\"\"\n\n self._expires = expires\n\n @property\n def max_run_count(self):\n \"\"\"Gets the max_run_count of this CronSchedule.\n\n\n :return: The max_run_count of this CronSchedule.\n :rtype: int\n \"\"\"\n return self._max_run_count\n\n @max_run_count.setter\n def max_run_count(self, max_run_count):\n \"\"\"Sets the max_run_count of this CronSchedule.\n\n\n :param max_run_count: The max_run_count of this CronSchedule.\n :type max_run_count: int\n \"\"\"\n if max_run_count is not None and max_run_count < 1: # noqa: E501\n raise ValueError(\"Invalid value for `max_run_count`, must be a value greater than or equal to `1`\") # noqa: E501\n\n self._max_run_count = max_run_count\n","sub_path":"mist_api_v2/models/cron_schedule.py","file_name":"cron_schedule.py","file_ext":"py","file_size_in_byte":8811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"204540437","text":"# -*- coding: utf-8 -*-\n\n\nfrom openerp import api, exceptions, fields, models, _\n\n\nclass LeaveApproval(models.Model):\n _name = 'leave.approval'\n _description = 'Leave Approval'\n\n name = fields.Char(string='Name', size=64, help='Name', required=True, )\n # department_id = fields.Many2one(\n # comodel_name='hr.department', string='Department', help='Department')\n department_ids = fields.Many2many(\n comodel_name='hr.department', string='Departments', help='')\n # leave_type_id = fields.Many2one(\n # comodel_name='hr.holidays.status',\n # string='Leave Type', help='Leave type')\n leave_type_ids = fields.Many2many(\n comodel_name='hr.holidays.status', string='Leave Type',\n help='Add multiple leave type.')\n approval_line_ids = fields.One2many(\n comodel_name='leave.approval.line',\n inverse_name='leave_approval_id', string='Leave Approval', help='')\n\n\nLeaveApproval()\n\n\nclass LeaveApprovalLine(models.Model):\n _name = 'leave.approval.line'\n _description = 'Leeve Approval Line'\n _order = 'sequence asc'\n\n sequence = fields.Integer(string='Sequence', help='Sequence', default=1, )\n employee_ids = fields.Many2many(\n comodel_name='hr.employee',\n string='Employee', help='Add multiple employee as approver.')\n leave_approval_id = fields.Many2one(\n comodel_name='leave.approval', string='Leave Approval', help='')\n\n\nLeaveApprovalLine()\n","sub_path":"beta-dev1/opt/odoo/odoo/addons/core/leave_multi_approval_levels/models/leave_approval.py","file_name":"leave_approval.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"17761372","text":"from __future__ import print_function\n\nfrom datetime import datetime, timedelta\n\nfrom airflow import models\nfrom airflow.operators import bash_operator\nfrom airflow.operators import python_operator\nfrom airflow.contrib.kubernetes import pod\nfrom airflow.contrib.kubernetes import secret\nfrom airflow.models import Variable\nfrom airflow.contrib.operators import kubernetes_pod_operator\n\naffinity_values={\n 'nodeAffinity': {\n # requiredDuringSchedulingIgnoredDuringExecution means in order\n # for a pod to be scheduled on a node, the node must have the\n # specified labels. However, if labels on a node change at\n # runtime such that the affinity rules on a pod are no longer\n # met, the pod will still continue to run on the node.\n 'requiredDuringSchedulingIgnoredDuringExecution': {\n 'nodeSelectorTerms': [{\n 'matchExpressions': [{\n # When nodepools are created in Google Kubernetes\n # Engine, the nodes inside of that nodepool are\n # automatically assigned the label\n # 'cloud.google.com/gke-nodepool' with the value of\n # the nodepool's name.\n 'key': 'cloud.google.com/gke-nodepool',\n 'operator': 'In',\n # The label key's value that pods can be scheduled\n # on.\n 'values': [\n 'pool-1',\n ]\n }]\n }]\n }\n }\n }\n\n\nsecret_env = secret.Secret(\n # Expose the secret as environment variable.\n deploy_type='env',\n # The name of the environment variable, since deploy_type is `env` rather\n # than `volume`.\n deploy_target='SQL_CONN',\n # Name of the Kubernetes Secret\n secret='air-sec',\n # Key of a secret stored in this Secret object\n key='sql_alchemy_conn')\n\n\ndefault_dag_args = {\n 'start_date': datetime(2018, 1, 1),\n 'depends_on_past': False,\n 'owner': 'airflow',\n 'retries': 1,\n 'retry_delay': timedelta(minutes=1),\n 'project_id': Variable.get('gcp_project')\n # The start_date describes when a DAG is valid / can be run. Set this to a\n # fixed point in time rather than dynamically, since it is evaluated every\n # time a DAG is parsed. See:\n # https://airflow.apache.org/faq.html#what-s-the-deal-with-start-date\n\n}\n\n# Define a DAG (directed acyclic graph) of tasks.\n# Any task you create within the context manager is automatically added to the\n# DAG object.\nwith models.DAG(\n 'node_scale_down_3',\n catchup=False,\n schedule_interval='*/1 * * * *',\n default_args=default_dag_args) as dag:\n\n pod_res = pod.Resources(request_memory='10Mi',request_cpu='10m',limit_memory='15Mi',limit_cpu='15m')\n # setattr(pod_res, 'request_memory', '1Mi')\n # setattr(pod_res, 'request_cpu', None)\n # setattr(pod_res, 'limit_cpu', None)\n # An instance of an operator is called a task. In this case, the\n # hello_python task calls the \"greeting\" Python function.\n scale_down = kubernetes_pod_operator.KubernetesPodOperator(\n # The ID specified for the task.\n task_id='node-scale_down',\n # Name of task you want to run, used to generate Pod ID.\n name='scale-down',\n # resources=pod_res,\n # Entrypoint of the container, if not specified the Docker container's\n # entrypoint is used. The cmds parameter is templated.\n cmds=[\"echo\", \"I am here to scale down\"],\n resources=pod_res,\n # The namespace to run within Kubernetes, default namespace is\n # `default`. There is the potential for the resource starvation of\n # Airflow workers and scheduler within the Cloud Composer environment,\n # the recommended solution is to increase the amount of nodes in order\n # to satisfy the computing requirements. Alternatively, launching pods\n # into a custom namespace will stop fighting over resources.\n namespace='bs4-app',\n is_delete_operator_pod=True,\n affinity=affinity_values,\n config_file='/home/airflow/composer_kube_config',\n # Docker image specified. Defaults to hub.docker.com, but any fully\n # qualified URLs will point to a custom repository. Supports private\n # gcr.io images if the Composer Environment is under the same\n # project-id as the gcr.io images.\n image='alpine:latest')\n\n\n\n scale_down\n","sub_path":"nodes_scaledown.py","file_name":"nodes_scaledown.py","file_ext":"py","file_size_in_byte":4585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"271191880","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# imports the csv file our data is on\r\ndef permittivity_from_frequency(material, frequency):\r\n df = pd.read_csv('Acetone_Fits.csv')\r\n # print(df.head)\r\n grouped = df.groupby('Material')\r\n fit = grouped.get_group(material)\r\n A = fit['A'].iloc[0]\r\n B = fit['B'].iloc[0]\r\n return A, B #*frequency+B\r\nprint(permittivity_from_frequency('20acetone',1e9))\r\n","sub_path":"leastSquares/Inverse_Function.py","file_name":"Inverse_Function.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"552238809","text":"from glob import iglob\nimport random\nimport pickle\nimport music21 as mu\n\nfrom .piece import Piece\nfrom .fmt.piece_data import PieceData\nfrom . import piece_filter\n\nclass AbstractCorpus(object):\n def __init__(self):\n raise NotImplementedError\n\n def save(self, fname): \n with open(fname, 'wb+') as f:\n pickle.dump(self.__dict__,\n f,\n pickle.HIGHEST_PROTOCOL)\n\n def load(self, fname):\n with open(fname, 'rb') as f:\n self.__dict__ = pickle.load(f)\n\nclass Corpus(AbstractCorpus):\n def __init__(self, patterns=tuple(), filters=tuple(), from_file=None, discard_rests=False, max_len=None, ignore_load_errors=False, verbose=False, transpose_to=None):\n '''\n Load a corpus of pieces.\n patterns: an iterable of patterns (ie '*.musicxml') to load into the corpus.\n '''\n self._pieces = []\n self._num_rejected = 0\n\n if from_file is not None:\n if len(patterns) > 1:\n raise ValueError('Should not provide patterns if loading from file')\n self.load(from_file)\n else:\n def load(self_):\n for pattern in patterns:\n for fname in iglob(pattern):\n try:\n res, why = self_.load_piece(fname, filters, transpose_to)\n except (mu.exceptions21.StreamException, mu.musicxml.xmlToM21.MusicXMLImportException):\n if verbose: print(f' Failed to load file {fname}: ', end='')\n if ignore_load_errors:\n if verbose: print('continuing')\n continue\n if verbose: print('failing (use `ignore_load_errors=True` in corpus to prevent)')\n raise\n if verbose:\n if res:\n print(f' loaded: {fname}')\n else:\n print(f' rejected: {fname}, {why}')\n if max_len is not None and self_.size() >= max_len:\n return\n load(self)\n \n if discard_rests:\n self.discard_rests()\n\n def size(self):\n return len(self._pieces)\n\n @property\n def pieces(self):\n return self._pieces\n\n @property\n def num_rejected(self):\n return self._num_rejected\n\n def passes_filters(self, piece, filters):\n for f in filters:\n if not f(piece):\n self._num_rejected += 1\n return False, piece_filter.failure_reason(f)\n return True, \"Passes\"\n\n def load_piece(self, piece, filters=tuple(), transpose_to=None):\n p = Piece(piece, transpose_to)\n passes, reason = self.passes_filters(p, filters)\n if passes:\n p = self._pieces.append(p)\n return True, \"Success\"\n return False, reason\n\n def format_data(self, formatter, slice_resolution, discard_rests=False):\n return DataCorpus(self, formatter, slice_resolution, discard_rests)\n\n def filter(self, *filters):\n '''\n Filter out pieces that do not adhere to a set of filters.\n see: piece_filter.py\n '''\n len_old = len(self._pieces)\n for f in filters:\n self._pieces = [p for p in self._pieces if f(p)]\n self._num_rejected += len_old - len(self._pieces)\n\n def discard_rests(self):\n for piece in self._pieces:\n piece.discard_rests()\n\nclass DataCorpus(AbstractCorpus):\n def __init__(self, corpus, formatter, slice_resolution, discard_rests=False):\n self._data = [PieceData(p, formatter, slice_resolution, discard_rests)\n for p in corpus.pieces]\n\n def size(self):\n return len(self._data)\n\n @property\n def data(self):\n return self._data\n\n def __iter__(self):\n return self._data.__iter__()\n \n def __len__(self):\n return len(self._data)\n\n\n","sub_path":"mud/corpus.py","file_name":"corpus.py","file_ext":"py","file_size_in_byte":4109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"316028698","text":"# Copyright 2013 Rackspace Hosting Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom neutron.extensions import securitygroup as sg_ext\nfrom neutron import quota\nfrom neutron_lib import exceptions as n_exc\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nfrom oslo_utils import uuidutils\n\nfrom quark.db import api as db_api\nfrom quark.environment import Capabilities\nfrom quark import exceptions as q_exc\nfrom quark import plugin_views as v\nfrom quark import protocols\n\nCONF = cfg.CONF\nLOG = logging.getLogger(__name__)\nDEFAULT_SG_UUID = \"00000000-0000-0000-0000-000000000000\"\nGROUP_NAME_MAX_LENGTH = 255\nGROUP_DESCRIPTION_MAX_LENGTH = 255\n\n\ndef _validate_security_group_rule(context, rule):\n # TODO(mdietz): As per RM8615, Remote groups are not currently supported\n if rule.get(\"remote_group_id\"):\n raise n_exc.InvalidInput(\n error_message=\"Remote groups are not currently supported\")\n\n direction = rule.get(\"direction\")\n if direction == Capabilities.EGRESS:\n if Capabilities.EGRESS not in CONF.QUARK.environment_capabilities:\n raise q_exc.EgressSecurityGroupRulesNotEnabled()\n\n protocol = rule.pop('protocol')\n port_range_min = rule['port_range_min']\n port_range_max = rule['port_range_max']\n ethertype = protocols.translate_ethertype(rule[\"ethertype\"])\n\n if protocol:\n protocol = protocols.translate_protocol(protocol, rule[\"ethertype\"])\n protocols.validate_protocol_with_port_ranges(ethertype,\n protocol,\n port_range_min,\n port_range_max)\n rule['protocol'] = protocol\n else:\n if port_range_min is not None or port_range_max is not None:\n raise sg_ext.SecurityGroupProtocolRequiredWithPorts()\n\n rule[\"ethertype\"] = ethertype\n\n protocols.validate_remote_ip_prefix(ethertype,\n rule.get(\"remote_ip_prefix\"))\n\n return rule\n\n\ndef _validate_security_group(security_group):\n if \"name\" in security_group:\n if len(security_group[\"name\"]) > GROUP_NAME_MAX_LENGTH:\n raise n_exc.InvalidInput(\n error_message=\"Group name must be 255 characters or less\")\n\n if security_group[\"name\"] == \"default\":\n raise sg_ext.SecurityGroupDefaultAlreadyExists()\n\n if (\"description\" in security_group and\n len(security_group[\"description\"]) > GROUP_DESCRIPTION_MAX_LENGTH):\n raise n_exc.InvalidInput(\n error_message=\"Group description must be 255 characters or less\")\n\n\ndef create_security_group(context, security_group):\n LOG.info(\"create_security_group for tenant %s\" %\n (context.tenant_id))\n group = security_group[\"security_group\"]\n _validate_security_group(group)\n\n group_name = group.get('name', '')\n group_id = uuidutils.generate_uuid()\n\n with context.session.begin():\n group[\"id\"] = group_id\n group[\"name\"] = group_name\n group[\"tenant_id\"] = context.tenant_id\n dbgroup = db_api.security_group_create(context, **group)\n return v._make_security_group_dict(dbgroup)\n\n\ndef create_security_group_rule(context, security_group_rule):\n LOG.info(\"create_security_group for tenant %s\" %\n (context.tenant_id))\n with context.session.begin():\n rule = _validate_security_group_rule(\n context, security_group_rule[\"security_group_rule\"])\n rule[\"id\"] = uuidutils.generate_uuid()\n\n group_id = rule[\"security_group_id\"]\n group = db_api.security_group_find(context, id=group_id,\n scope=db_api.ONE)\n if not group:\n raise sg_ext.SecurityGroupNotFound(id=group_id)\n\n quota.QUOTAS.limit_check(\n context, context.tenant_id,\n security_rules_per_group=len(group.get(\"rules\", [])) + 1)\n\n new_rule = db_api.security_group_rule_create(context, **rule)\n return v._make_security_group_rule_dict(new_rule)\n\n\ndef delete_security_group(context, id):\n LOG.info(\"delete_security_group %s for tenant %s\" %\n (id, context.tenant_id))\n\n with context.session.begin():\n group = db_api.security_group_find(context, id=id, scope=db_api.ONE)\n\n # TODO(anyone): name and ports are lazy-loaded. Could be good op later\n if not group:\n raise sg_ext.SecurityGroupNotFound(id=id)\n if id == DEFAULT_SG_UUID or group.name == \"default\":\n raise sg_ext.SecurityGroupCannotRemoveDefault()\n if group.ports:\n raise sg_ext.SecurityGroupInUse(id=id)\n db_api.security_group_delete(context, group)\n\n\ndef delete_security_group_rule(context, id):\n LOG.info(\"delete_security_group %s for tenant %s\" %\n (id, context.tenant_id))\n with context.session.begin():\n rule = db_api.security_group_rule_find(context, id=id,\n scope=db_api.ONE)\n if not rule:\n raise sg_ext.SecurityGroupRuleNotFound(id=id)\n\n group = db_api.security_group_find(context, id=rule[\"group_id\"],\n scope=db_api.ONE)\n if not group:\n raise sg_ext.SecurityGroupNotFound(id=id)\n\n rule[\"id\"] = id\n db_api.security_group_rule_delete(context, rule)\n\n\ndef get_security_group(context, id, fields=None):\n LOG.info(\"get_security_group %s for tenant %s\" %\n (id, context.tenant_id))\n group = db_api.security_group_find(context, id=id, scope=db_api.ONE)\n if not group:\n raise sg_ext.SecurityGroupNotFound(id=id)\n return v._make_security_group_dict(group, fields)\n\n\ndef get_security_group_rule(context, id, fields=None):\n LOG.info(\"get_security_group_rule %s for tenant %s\" %\n (id, context.tenant_id))\n rule = db_api.security_group_rule_find(context, id=id,\n scope=db_api.ONE)\n if not rule:\n raise sg_ext.SecurityGroupRuleNotFound(id=id)\n return v._make_security_group_rule_dict(rule, fields)\n\n\ndef get_security_groups(context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n LOG.info(\"get_security_groups for tenant %s\" %\n (context.tenant_id))\n groups = db_api.security_group_find(context, **filters)\n return [v._make_security_group_dict(group) for group in groups]\n\n\ndef get_security_group_rules(context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n LOG.info(\"get_security_group_rules for tenant %s\" %\n (context.tenant_id))\n rules = db_api.security_group_rule_find(context, **filters)\n return [v._make_security_group_rule_dict(rule) for rule in rules]\n\n\ndef update_security_group(context, id, security_group):\n if id == DEFAULT_SG_UUID:\n raise sg_ext.SecurityGroupCannotUpdateDefault()\n new_group = security_group[\"security_group\"]\n _validate_security_group(new_group)\n\n with context.session.begin():\n group = db_api.security_group_find(context, id=id, scope=db_api.ONE)\n db_group = db_api.security_group_update(context, group, **new_group)\n return v._make_security_group_dict(db_group)\n","sub_path":"quark/plugin_modules/security_groups.py","file_name":"security_groups.py","file_ext":"py","file_size_in_byte":7966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"528702280","text":"from django import forms\nfrom .widgets import CustomClearableFileInput\nfrom .models import ProductReview, Product, Category\n\n\nclass ReviewForm(forms.ModelForm):\n\n class Meta:\n model = ProductReview\n exclude = ('product', 'user', 'date_added')\n\n\nclass ProductForm(forms.ModelForm):\n\n class Meta:\n model = Product\n fields = '__all__'\n\n image = forms.ImageField(\n label='Image', required=False, widget=CustomClearableFileInput)\n\n def __init__(self, *args, **kwargs):\n super(). __init__(*args, **kwargs)\n categories = Category.objects.all()\n friendly_names = [(c.id, c.get_friendly_name()) for c in categories]\n\n self.fields['category'].choices = friendly_names\n","sub_path":"products/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"173872731","text":"\"\"\" Implementation of Gauci et al's controller which uses our calibrated image\ninputs. Doesn't seem to work very well. \"\"\"\n\nfrom .controller import Controller\nfrom math import fabs, pi\nfrom common import *\nfrom configsingleton import ConfigSingleton\n\n# Our mechanism for selectively importing pyglet/GUI-related stuff.\nimport gui_setting\nif gui_setting.use:\n from common.drawing import draw_ray, draw_segment_wrt_robot\n\nclass GauciImageController(Controller):\n\n def __init__(self, puck_mask):\n self.puck_mask = puck_mask\n\n config = ConfigSingleton.get_instance()\n\n self.front_angle_threshold = config.getfloat(\"GauciController\",\n \"front_angle_threshold\")\n self.linear_speed = config.getfloat(\"GauciController\", \"linear_speed\")\n self.angular_speed = config.getfloat(\"GauciController\", \"angular_speed\")\n self.slow_factor = config.getfloat(\"GauciController\", \"slow_factor\")\n\n def react(self, this_robot, sensor_dump, visualize=False):\n twist = Twist()\n\n image = sensor_dump.lower_image\n\n # Relying on only a single forward-pointing ray causes distant pucks\n # to be easily missed (they may be detected, but too sporadically to\n # attract the robot). We accept as forward-pointing any sensor ray\n # within 'front_angle_threshold' of zero. Correspondingly set the\n # two predicates 'react_to_puck' and 'react_to_robot'.\n react_to_puck = False\n react_to_robot = False\n for i in range(image.n_rows):\n angle = image.calib_array[i,4]\n dist = image.calib_array[i,5]\n if fabs(angle) < self.front_angle_threshold:\n if image.masks[i] & self.puck_mask != 0:\n react_to_puck = True\n if image.masks[i] == ROBOT_MASK:\n react_to_robot = True\n\n if react_to_robot:\n react_to_puck = False\n\n # Now react...\n if react_to_puck:\n # Turn left\n twist.linear = self.linear_speed\n twist.angular = self.angular_speed\n if visualize:\n draw_ray(this_robot, 0, (255, 0, 255))\n\n elif react_to_robot:\n # Turn left and slow\n twist.linear = self.linear_speed * self.slow_factor\n twist.angular = self.angular_speed\n\n if visualize: # Reacting to robot\n draw_ray(this_robot, 0, (255, 0, 0))\n else:\n # Turn right\n twist.linear = self.linear_speed\n twist.angular = -self.angular_speed\n\n if visualize:\n draw_ray(this_robot, 0, (0, 255, 0))\n \n return twist\n","sub_path":"controllers/gauciimagecontroller.py","file_name":"gauciimagecontroller.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"175382073","text":"# -*- coding: utf-8 -*-\nimport pygame,random\nclass MyBallClass(pygame.sprite.Sprite):\n def __init__(self,imageName,loc,speed):\n pygame.sprite.Sprite.__init__(self)\n self.image=pygame.image.load(imageName)\n self.rect=self.image.get_rect()\n self.rect.left,self.rect.top=loc\n self.speed=speed\n def move(self):\n self.rect=self.rect.move(self.speed)\n if self.rect.left<0 or self.rect.right>screen.get_width():\n self.speed[0]=-self.speed[0]\n if self.rect.top<0:\n self.speed[1]=-self.speed[1]\n if self.rect.bottom>screen.get_height():\n #pygame.quit()\n print(\"��输了!\")\n return -1\n return 0\nclass WackyPadClass(pygame.sprite.Sprite):\n def __init__(self,loc2):\n pygame.sprite.Sprite.__init__(self)\n i_s=pygame.surface.Surface([400,60])\n i_s.fill([random.randint(100,200),random.randint(100,200),random.randint(100,200)])\n self.image=i_s.convert()\n self.rect=self.image.get_rect()\n self.rect.left,self.rect.top=loc2\npygame.init()\nscreen=pygame.display.set_mode([700,700])\nclock=pygame.time.Clock()\nball_s=[8,8]\nmyball=MyBallClass('wackyball.bmp',[100,100],ball_s)\nbalgro=pygame.sprite.Group(myball)\npad=WackyPadClass([100,400])\nrunning=True\nwhile running:\n clock.tick(35)\n screen.fill([255,255,255])\n for event in pygame.event.get():\n if event.type==pygame.QUIT:\n running=False\n elif event.type==pygame.KEYDOWN:\n if event.key==pygame.K_a:\n pad.rect.left=pad.rect.left-50\n elif event.key==pygame.K_b:\n pad.rect.right=pad.rect.right+50\n if pygame.sprite.spritecollide(pad,balgro,False):\n myball.speed[1]=-myball.speed[1]\n a=myball.move()\n if a==-1:\n running=False\n #pygame.quit()\n else:\n screen.blit(myball.image,myball.rect)\n screen.blit(pad.image,pad.rect)\n pygame.display.flip()\npygame.quit()","sub_path":"pong1.py","file_name":"pong1.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"434064260","text":"# Heavily referenced data\nlines_url = \"https://www.bovada.lv/services/sports/event/v2/events/A/description/\"\n\naz_teams = ['Atlanta Hawks', 'Boston Celtics',\n 'Brooklyn Nets', 'Charlotte Hornets',\n 'Chicago Bulls', 'Cleveland Cavaliers',\n 'Dallas Mavericks', 'Denver Nuggets',\n 'Detroit Pistons', 'Golden State Warriors',\n 'Houston Rockets', 'Indiana Pacers',\n 'Los Angeles Clippers', 'Los Angeles Lakers',\n 'Memphis Grizzlies', 'Miami Heat',\n 'Milwaukee Bucks', 'Minnesota Timberwolves',\n 'New Orleans Pelicans', 'New York Knicks',\n 'Oklahoma City Thunder', 'Orlando Magic',\n 'Philadelphia 76ers', 'Phoenix Suns',\n 'Portland Trail Blazers', 'Sacramento Kings',\n 'San Antonio Spurs', 'Toronto Raptors',\n 'Utah Jazz', 'Washington Wizards']\n\nbov_game_info = ['sport', 'league', 'game_id', 'a_team', 'h_team', 'cur_time']\n\nbov_score_headers = ['lms_date','lms_time','quarter','secs','a_pts','h_pts','status',\n 'a_win','h_win']\n\nbov_lines_headers = ['last_mod_to_start', 'last_mod_lines','num_markets','a_ml','h_ml','a_deci_ml','h_deci_ml',\n 'a_odds_ps','h_odds_ps','a_deci_ps','h_deci_ps','a_hcap_ps','h_hcap_ps','a_odds_tot',\n 'h_odds_tot','a_deci_tot','h_deci_tot','a_hcap_tot', 'h_hcap_tot', 'a_ou', 'h_ou', 'game_start_time']\n\n\nbovada_headers = bov_game_info + bov_score_headers + bov_lines_headers\n\nsuffixes = ['?marketFilterId=def&liveOnly=true&lang=en',\n '?marketFilterId=def&preMatchOnly=true&eventsLimit=10&lang=en']\n\n\nsports = ['basketball/nba', 'basketball/college-basketball', 'baseball/mlb',\n 'esports', 'football/nfl', 'tennis', 'volleyball', 'hockey']\n\n\ndef build_urls():\n urls = []\n for sport in sports:\n for suffix in suffixes:\n urls.append(lines_url + sport + suffix)\n return urls\n","sub_path":"sips/gym_sip/h/macros.py","file_name":"macros.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"633627597","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nimport time\nimport signal\nimport socket\nimport subprocess\nimport numpy as np\nimport scipy as sp\nfrom datetime import datetime\n\n############ PRE-DEFINITIONS\n\n## PC Settings\nip_canada = \"10.152.8.206\"\nserialport = \"/dev/rs485tty0\"\n\n## INSTRUMENT IPs\nsubnet = \"10.136.117.\"\n# POCAM\ns_p1 = [subnet + \"141\", \"4001\"]\ns_p2 = [subnet + \"131\", \"4001\"]\ns_p3 = [subnet + \"131\", \"4003\"]\n\n# sDOMs\nip_s1 = subnet + \"145\"\nip_s2 = subnet + \"146\"\nip_s3 = subnet + \"147\"\nip_s4 = subnet + \"135\" #!\nip_s5 = subnet + \"136\" #!\ns_s1 = [ip_s1, \"4002\"]\ns_s2 = [ip_s2, \"4003\"]\ns_s3 = [ip_s3, \"4004\"]\ns_s4 = [ip_s4, \"4002\"] #!\ns_s5 = [ip_s5, \"4004\"] #!\n\n# MEDUSAs\nm_port = \"54321\"\nip_m1 = subnet + \"143\" # master\nip_m2 = subnet + \"133\" # slave\n\n# DICTS\npocams = {'p1':s_p1, 'p2':s_p2, 'p3':s_p3}\nsdoms = {'s1':s_s1, 's2':s_s2, 's3':s_s3, 's4':s_s4, 's5':s_s5}\nmedusas = {'mm':ip_m1, 'ms':ip_m2}\n\n## SYNC / TRIGGER CONTTROL\nwrite_CTRL = \"18 00 00 00 00 00 00 00 00 \"\ntrigger_off = write_CTRL + \"40 00 00\"\ntrigger_rdy = write_CTRL + \"42 00 00\"\ntrigger_on = write_CTRL + \"02 00 00\"\ntrigger_n = write_CTRL + \"00 00 00\"\n\n############ FUNCTIONS\n\n# Send UDP hex packages to MEDUSA\ndef SendUDP(ip, port, message, sleep):\n ip = str(ip)\n port = int(port)\n m = bytes.fromhex(message)\n print(ip,port,m)\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # initializes udp\n sock.sendto(m, (ip, port))\n time.sleep(sleep)\n\n# POCAM flashing \n#NEV=$1\n#FILE=$2\n#LED=$3\n#FREQUENCY=$4\n#KAP=$5\n#SIPM=$6\n\ndef POCAM(p_id, num=1000000, calf=0, LED=8, freq=10000, KapV=20000, SiPM=10000):\n \n subprocess.call('sudo killall socat', shell=True, preexec_fn=os.setsid)\n \n # get connection details\n pocam = pocams[\"p%s\" %(p_id)]\n p_ip = pocam[0]\n p_port = pocam[1]\n \n # open serial connection\n createserial = subprocess.Popen('sudo ./createserial.sh %s %s' %(p_ip, p_port), \n shell=True, preexec_fn=os.setsid)\n time.sleep(2)\n # enable serial connectio echo to see POCAM response\n socat = subprocess.Popen('sudo socat - %s,raw,echo=0,crnl' %(serialport), \n shell=True, preexec_fn=os.setsid)\n time.sleep(1)\n # and flash\n flash_cmd = 'sudo ./flash.sh %i %i %02i %i %i %i' %(num, calf, LED, freq, KapV, SiPM)\n print(flash_cmd)\n flash = subprocess.call(flash_cmd, shell=True, preexec_fn=os.setsid)\n \n time.sleep(10)\n os.killpg(os.getpgid(socat.pid), signal.SIGTERM)\n os.killpg(os.getpgid(createserial.pid), signal.SIGTERM)\n\n# sDOM readying\ndef sDOM(s_id):\n # Get connection information\n s_det = sdoms['s%s' %s_id]\n s_ip = s_det[0]\n s_ser = s_det[1]\n # Run sDOM-ready script to switch on TRBnet if necessary\n serial = subprocess.call('./sdom-ready.sh ' + s_ip, shell=True, preexec_fn=os.setsid)\n \n\n############ USER INPUT\n\n# Define POCAM_ID\nPOCAM_IDs = [\"1\", \"2\", \"3\"]\nSDOM_IDs = [\"1\", \"2\", \"3\", \"4\", \"5\"]\n\n# Define Flash-parameters\nLEDS = [1, 2, 4, 8] #input(\"Enter LED to flash: (1) 365 nm (2) 400 nm (3) 465 nm (4) 605 nmS: \")\nVOLTS = [20000,16000,12000,10000,8000]#[6000 + i * 1000 for i in np.arange(0, 16, 2)] #input(\"Enter Kapustinsky Voltage in Volts: \")\nFREQ = 5000 #input(\"Enter flash frequency in Hertz: \")\nNEV = 2000000 #input(\"Enter number of flashes: \")\nN_FILE = 0 #if int(FREQ) > 100 else 1\nSENSHV = 10000 #if int(FREQ) > 100 else 28500\n#TRIGG = \"02\"\n#SAMP = \"05\"\n#HEM = \"3\"\n#FPGA = \"3\"\n\n# Define desired time to take live data in seconds\nT_DATA = 60 # seconds\n\n############ STRAW EXECUTION\nsubprocess.call('sudo killall socat', shell=True, preexec_fn=os.setsid)\n\n# Switch off SYNC\nprint('SYNC: off')\nSendUDP(medusas['mm'], m_port, trigger_off, 2)\nSendUDP(medusas['ms'], m_port, trigger_off, 2)\n\n# Ready sDOMs for data-taking\nfor s_id in SDOM_IDs:\n sDOM(s_id)\n \n# Ready SYNC for TRB clock-reset\nprint('SYNC: ready')\nSendUDP(medusas['mm'], m_port, trigger_rdy, 2)\nSendUDP(medusas['ms'], m_port, trigger_rdy, 2)\n\n# Start Flashing\ntimestamp = datetime.utcnow().strftime(\"%Y%m%dT%H%M%SUTC\")\nfor pocam in POCAM_IDs:\n for led in LEDS:\n for volt in VOLTS:\n # Print current stage\n print('\\nPOCAM', pocam, 'LED', led, 'Voltage', volt)\n \n # Create TdcEventBuilder.xml\n print('Creating TdcEventBuilder.xml for each SDOM')\n data_files = {}\n for s in SDOM_IDs:\n\t\t# tag data\n unique_id = \"S\" + s + \"_\" + timestamp + \"_P\" + pocam + \"_L%02i\" %led + \"_V%05i\" %volt + \"_F%i_\" %FREQ\n data_files[s] = unique_id\n print(unique_id)\n\t\t# initialize eventbuilder file tags\n subprocess.call('./make-eventbuilder.sh ' + unique_id + \" \" + sdoms['s'+s][0], shell=True, preexec_fn=os.setsid)\n \n # Flash POCAM\n print('POCAM: initializing flasher process')\n POCAM(pocam, num=NEV, calf=N_FILE, LED=led, freq=FREQ, KapV=volt, SiPM=SENSHV)\n \n # Start DABC\n print('DABC: starting')\n for s in SDOM_IDs:\n subprocess.Popen('ssh odroid@' + sdoms['s'+s][0] + \" \\\"cd ~/trbsoft/daqtools/users/deepsea; . ~/trbsoft/trb3/trb3login; dabc_exe TdcEventBuilder.xml\\\"\", shell=True, preexec_fn=os.setsid)# | grep Events: | sed s/^/\"+s+\"/\\\"\", shell=True, preexec_fn=os.setsid)\n time.sleep(30)\n\n # Start SYNC\n print('SYNC: on')\n SendUDP(medusas['mm'], m_port, trigger_on, 0)#T_DATA)\n SendUDP(medusas['ms'], m_port, trigger_on, 0)#T_DATA)\n \n # Run for requested amount of time\n print('DABC: Recording ... for %i seconds'%T_DATA)\n time.sleep(T_DATA)\n \n # Stop SYNC\n print('SYNC: off')\n SendUDP(medusas['mm'], m_port, trigger_off, 2)\n SendUDP(medusas['ms'], m_port, trigger_off, 2)\n \n # Stop DABC\n print('DABC: end')\n for s in SDOM_IDs:\n subprocess.call('ssh odroid@' + sdoms['s'+s][0] + \" \\\"killall dabc_exe\\\"\", shell=True, preexec_fn=os.setsid)\n\n # Download data\n print('Downloading data')\n for s in SDOM_IDs:\n print(data_files[s])\n subprocess.call('scp odroid@' + sdoms['s'+s][0] + \":/d/\" + data_files[s] + \"* /home/canada/diskstation/STRAW_data/\", shell=True, preexec_fn=os.setsid)\n time.sleep(1)\n","sub_path":"run-STRAW-run.py","file_name":"run-STRAW-run.py","file_ext":"py","file_size_in_byte":6505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"309589157","text":"import random\nimport requests\nimport json\nfrom pprint import pprint\nfrom copy import deepcopy\nfrom lxml import etree\n\ndef process_competency_doc(url):\n namespaces = {\n \"c\": \"http://ns.medbiq.org/competencyframework/v1/\",\n \"lom\": \"http://ltsc.ieee.org/xsd/LOM\",\n \"hx\": \"http://ns.medbiq.org/lom/extend/v1/\",\n }\n #data = requests.get(url, stream=True)\n #root = etree.parse(data.raw)\n #data = root.xpath(\"//c:CompetencyFramework/c:Includes/c:Entry/text()\", namespaces=namespaces)\n data = [\"http://example.com/competency/\" + str(i) for i in range(20)]\n while True:\n yield random.choice(data)\n\nlr_url = \"http://localhost:5000/publish\"\nBASE_ENVELOPE = {\n \"TOS\": {\n \"submission_TOS\": \"http://www.learningregistry.org/tos/cc0/v0-5/\"\n },\n \"payload_placement\": \"inline\",\n \"active\": True,\n \"identity\": {\n \"owner\": \"ADL\",\n \"submitter\": \"walt.grata.ctr@adlnet.gov\",\n \"submitter_type\": \"user\",\n },\n \"doc_type\": \"resource_data\",\n \"payload_schema\": [ ],\n \"doc_version\": \"0.23.0\",\n}\ndef resources(resource_id=random.randint(0, 200)):\n return \"http://example.org/content{0}\".format(resource_id)\n \ndef identity(mbox_id=random.randint(0, 50)):\n template = \"mailto:user{0}@example.com\"\n return template.format(mbox_id)\n\ndef get_lrmi_envelopes(url):\n return {'careerCluster': [],\n 'dateCreated': '3/1/2012',\n 'description': \"Description for {0}\".format(url),\n 'educationalUse': ['Professional Development'],\n 'groupType': ['Reference Material'],\n 'inLanguage': 'English',\n 'mediaType': ['PDF'],\n 'name': 'Nane for {0}'.format(url),\n 'publisher': 'Illinois Shared Learning Environment',\n 'requires': '',\n 'timeRequired': 'P0D0H30M',\n 'typicalAgeRange': [],\n 'url': url,\n 'useRightsUrl': 'http://creativecommons.org/licenses/by/3.0/'}\n\ndef get_lr_paradata(url, compentency_id):\n return {\"activity\": {\n \"content\": \"A resource found at http://www.freesound.org/people/hello_flowers/sounds/39087/ was matched to the competency with ID http://adlnet.gov/competency/computer-science/case-statements by an admin on http://localhost:5000 system on 2014-05-08T14:24:44.086113+00:00\",\n \"verb\": {\"action\": \"matched\",\n \"date\": \"2014-05-08T14:24:44.086113+00:00\",\n \"context\": {\"objectType\": \"Application\",\n \"description\": \"ADL's XCI project\",\n \"id\": \"http://localhost:5000\" }},\n \"related\": [{\n \"content\": \"Exhibits an understanding of case statements\",\n \"id\": compentency_id,\n \"objectType\": \"competency\"\n }],\n \"actor\": {\"description\": [\"ADL XCI admin\",\n \"TIG New Wave 125 MGuitar A\"],\n \"objectType\": \"admin\"},\n \"object\": {\"id\": url}}}\n\ndef publish_lr_metadata():\n print(\"publish metadata\")\n header = {\"Content-Type\": \"application/json\"}\n base_publish_package = {\"documents\": []}\n for i in range(0, 2000):\n url = resources(i)\n envelope = deepcopy(BASE_ENVELOPE)\n envelope['resource_locator'] = url\n envelope['resource_data_type'] = \"metadata\"\n envelope['resource_data'] = get_lrmi_envelopes(url)\n envelope['payload_schema'].append(\"lrmi\")\n base_publish_package['documents'].append(envelope)\n if (len(base_publish_package['documents']) % 500) == 0:\n pprint(requests.post(lr_url, data=json.dumps(base_publish_package), headers=header, auth=(\"admin\", \"password\")).json())\n base_publish_package['documents'] = []\n pprint(requests.post(lr_url, data=json.dumps(base_publish_package), headers=header, auth=(\"admin\", \"password\")).json())\n\ndef publish_paradata():\n print(\"publish paradata\")\n headers = {\"Content-Type\": \"application/json\"}\n base_publish_package = {\"documents\": []}\n for url, competency_url in [(resources(i[0]), i[1]) for i in zip(range(0, 2000), process_competency_doc(\"http://adlnet.gov/competency-framework/computer-science/basic-programming.xml\"))]:\n envelope = deepcopy(BASE_ENVELOPE)\n envelope['resource_locator'] = url\n envelope['resource_data_type'] = \"paradata\"\n envelope['resource_data'] = get_lr_paradata(url, competency_url)\n envelope['payload_schema'].append(\"LR Paradata 1.0\")\n base_publish_package['documents'].append(envelope)\n if len(base_publish_package.get(\"documents\", [])) % 500 == 0:\n pprint(requests.post(lr_url, data=json.dumps(base_publish_package), headers=headers, auth=('admin', 'password')).json())\n base_publish_package['documents'] = []\n pprint(requests.post(lr_url, data=json.dumps(base_publish_package), headers=headers, auth=('admin', 'password')).json())\n\n\ndef create_statement(email, activity):\n return {u'actor': {u'mbox': email,\n u'name': email,\n u'objectType': u'Agent'},\n u'context': {u'contextActivities': {u'parent': [{u'definition': {u'description': {u'en-US': u'A sample HTML5 mobile app with xAPI tracking.'},\n u'name': {u'en-US': u'xAPI for jQuery Demo'}},\n u'id': u'http://adlnet.gov/xapi/samples/xapi-jqm',\n u'objectType': u'Activity'}]}},\n u'object': {u'definition': {u'name': {u'en-US': u'xAPI jQuery Mobile toc toc'},\n u'type': u'http://adlnet.gov/xapi/activities/link'},\n u'id': activity,\n u'objectType': u'Activity'},\n u'verb': {u'display': {u'en-US': u'experienced'},\n u'id': u'http://adlnet.gov/expapi/verbs/experienced'},\n u'version': u'1.0.0'}\n\ndef publish_statements():\n print(\"publish statements\")\n endpoint = \"http://localhost:8000/xapi/statements\"\n auth = (\"walt\", \"password\")\n headers = {\"Content-Type\": \"application/json\", \"X-Experience-API-Version\": \"1.0\"}\n for i in range(0, 2000):\n for j in range(0, 50):\n statement = create_statement(identity(random.randint(0, 50)), resources(random.randint(0, 200)))\n print(requests.post(endpoint, data=json.dumps(statement), headers=headers, auth=auth).text)\n\ndef main():\n publish_lr_metadata()\n publish_paradata()\n publish_statements()\n\nif __name__ == \"__main__\":\n main()\n \n","sub_path":"data_generator/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"291369907","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author:XuMing(xuming624@qq.com)\n@description: \n\"\"\"\nimport os\nfrom codecs import open\nimport pickle\nfrom sklearn.cluster import MiniBatchKMeans\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport sys\n\nsys.path.append('..')\nfrom pytextclassifier.log import logger\nfrom pytextclassifier.tokenizer import Tokenizer\n\npwd_path = os.path.abspath(os.path.dirname(__file__))\ndefault_stopwords_path = os.path.join(pwd_path, 'data/stopwords.txt')\n\n\ndef load_list(path):\n \"\"\"\n 加载停用词\n :param path:\n :return: list\n \"\"\"\n return [word for word in open(path, 'r', encoding='utf-8').read().split()]\n\n\ndef load_pkl(pkl_path):\n \"\"\"\n 加载词典文件\n :param pkl_path:\n :return:\n \"\"\"\n with open(pkl_path, 'rb') as f:\n result = pickle.load(f)\n return result\n\n\ndef save_pkl(vocab, pkl_path, overwrite=True):\n \"\"\"\n 存储文件\n :param pkl_path:\n :param overwrite:\n :return:\n \"\"\"\n if pkl_path and os.path.exists(pkl_path) and not overwrite:\n return\n if pkl_path:\n with open(pkl_path, 'wb') as f:\n pickle.dump(vocab, f, protocol=pickle.HIGHEST_PROTOCOL)\n # pickle.dump(vocab, f, protocol=2) # 兼容python2和python3\n print(\"save %s ok.\" % pkl_path)\n\n\ndef show_plt(feature_matrix, labels, image_file='cluster.png'):\n \"\"\"\n Show cluster plt\n :param feature_matrix:\n :param labels:\n :param image_file:\n :return:\n \"\"\"\n from sklearn.decomposition import TruncatedSVD\n import matplotlib.pyplot as plt\n svd = TruncatedSVD()\n plot_columns = svd.fit_transform(feature_matrix)\n plt.scatter(x=plot_columns[:, 0], y=plot_columns[:, 1], c=labels)\n if image_file:\n plt.savefig(image_file)\n plt.show()\n\n\nclass TextCluster(object):\n def __init__(self, model=None, tokenizer=None, vectorizer=None, stopwords_path=None,\n n_clusters=3, n_init=10, ngram_range=(1, 2), **kwargs):\n self.model = model if model else MiniBatchKMeans(n_clusters=n_clusters, n_init=n_init)\n self.tokenizer = tokenizer if tokenizer else Tokenizer()\n self.vectorizer = vectorizer if vectorizer else TfidfVectorizer(ngram_range=ngram_range, **kwargs)\n self.stopwords = set(load_list(stopwords_path)) if stopwords_path else set(load_list(default_stopwords_path))\n self.is_trained = False\n\n def __repr__(self):\n return 'TextCluster instance ({}, {}, {})'.format(self.model, self.tokenizer, self.vectorizer)\n\n @staticmethod\n def load_file_data(file_path, sep='\\t', use_col=1):\n \"\"\"\n Load text file, format(txt): text\n :param file_path: str\n :param sep: \\t\n :param use_col: int or None\n :return: list, text list\n \"\"\"\n contents = []\n if not os.path.exists(file_path):\n raise ValueError('file not found. path: {}'.format(file_path))\n with open(file_path, \"r\", encoding='utf-8') as f:\n for line in f:\n line = line.strip()\n if use_col:\n contents.append(line.split(sep)[use_col])\n else:\n contents.append(line)\n logger.info('load file done. path: {}, size: {}'.format(file_path, len(contents)))\n return contents\n\n def encode_data(self, X):\n \"\"\"\n Encoding input text\n :param X: list of text, eg: [text1, text2, ...]\n :return: X, X_tokens\n \"\"\"\n # tokenize text\n X_tokens = [' '.join([w for w in self.tokenizer.tokenize(line) if w not in self.stopwords]) for line in X]\n logger.debug('data tokens top 1: {}'.format(X_tokens[:1]))\n return X_tokens\n\n def train(self, X, model_dir=''):\n \"\"\"\n Train model and save model\n :param X: list of text, eg: [text1, text2, ...]\n :param n_clusters: int\n :return: model\n \"\"\"\n logger.debug('train model')\n X_tokens = self.encode_data(X)\n X_vec = self.vectorizer.fit_transform(X_tokens)\n # fit cluster\n self.model.fit(X_vec)\n labels = self.model.labels_\n logger.debug('cluster labels:{}'.format(labels))\n if model_dir:\n os.makedirs(model_dir, exist_ok=True)\n vectorizer_path = os.path.join(model_dir, 'cluster_vectorizer.pkl')\n save_pkl(self.vectorizer, vectorizer_path)\n model_path = os.path.join(model_dir, 'cluster_model.pkl')\n save_pkl(self.model, model_path)\n logger.info('save done. vec path: {}, model path: {}'.format(vectorizer_path, model_path))\n\n self.is_trained = True\n return X_vec, labels\n\n def predict(self, X):\n \"\"\"\n Predict label\n :param X: list, input text list, eg: [text1, text2, ...]\n :return: list, label name\n \"\"\"\n if not self.is_trained:\n raise ValueError('model is None, run train first.')\n # tokenize text\n X_tokens = self.encode_data(X)\n # transform\n X_vec = self.vectorizer.transform(X_tokens)\n return self.model.predict(X_vec)\n\n def show_clusters(self, feature_matrix, labels, image_file='cluster.png'):\n \"\"\"\n Show cluster plt image\n :param feature_matrix:\n :param labels:\n :param image_file:\n :return:\n \"\"\"\n if not self.is_trained:\n raise ValueError('model is None, run train first.')\n show_plt(feature_matrix, labels, image_file)\n\n def load_model(self, model_dir=''):\n \"\"\"\n Load model from model_dir\n :param model_dir: path\n :return: None\n \"\"\"\n model_path = os.path.join(model_dir, 'cluster_model.pkl')\n if not os.path.exists(model_path):\n raise ValueError(\"model is not found. please train and save model first.\")\n self.model = load_pkl(model_path)\n vectorizer_path = os.path.join(model_dir, 'cluster_vectorizer.pkl')\n self.vectorizer = load_pkl(vectorizer_path)\n self.is_trained = True\n logger.info('model loaded {}'.format(model_dir))\n","sub_path":"pytextclassifier/textcluster.py","file_name":"textcluster.py","file_ext":"py","file_size_in_byte":6089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"606075393","text":"from django.db import models\n\n\nclass TodoList(models.Model):\n # Attributes Class\n created = models.DateTimeField(auto_now_add=True)\n title = models.CharField(max_length=100, blank=True)\n text = models.TextField(default='')\n owner = models.ForeignKey('auth.User', related_name='todos')\n\n class Meta:\n ordering = ('created',)\n\n def save(self, *args, **kwargs):\n # Create and save the validated object\n super(TodoList, self).save(*args, **kwargs)\n","sub_path":"django-rest-swagger/myapp/todolist/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"594804448","text":"#-*- coding: utf-8 -*-\n\nimport base64\n\nfrom flask import render_template, request\nfrom flask.ext.classy import FlaskView, route\nfrom mosca import app\n\nCHARSETS = (\n \"UTF-8\",\n \"ASCII\",\n \"CP1256\",\n \"ISO-8859-1\",\n \"ISO-8859-2\",\n \"ISO-8859-6\",\n \"ISO-8859-15\",\n \"Windows-1252\",\n)\n\n\nclass ToolsViews(FlaskView):\n route_base = '/tools/'\n\n @route('/')\n def tools_list(self):\n tools = []\n return render_template('tools/list.html', tools=tools)\n\n @route('/base64/encode', methods=['GET'])\n def tools_base64encode(self):\n return render_template(\n 'tools/base64/encode.html',\n view='encode',\n CHARSETS=CHARSETS)\n\n @route('/base64/encode', methods=['POST'])\n def tools_base64encode_post(self):\n data = request.form.get('data')\n charset = request.form.get('charset')\n encoded = base64.b64encode(bytes(data, charset)).decode(charset)\n return render_template(\n 'tools/base64/encode.html',\n encoded=encoded, view='encode',\n data=data, charset=charset,\n CHARSETS=CHARSETS)\n\n @route('/base64/decode', methods=['GET'])\n def tools_base64decode_get(self):\n return render_template(\n 'tools/base64/decode.html', view='decode',\n CHARSETS=CHARSETS)\n\n @route('/base64/decode', methods=['POST'])\n def tools_base64decode_post(self):\n data = request.form.get('data')\n charset = request.form.get('charset')\n try:\n decoded = str(base64.b64decode(data.encode(charset)), charset)\n except UnicodeDecodeError as e:\n decoded = str(e)\n return render_template(\n 'tools/base64/decode.html',\n decoded=decoded, view='decode',\n data=data, charset=charset,\n CHARSETS=CHARSETS)\n\n @route('/docs/cpf', methods=['GET'])\n def tools_docs_cpf_get(self):\n return render_template(\n 'tools/docs/cpf.html')\n\n @route('/url/encode', methods=['GET'])\n def tools_urlencode(self):\n tools = []\n return render_template('tools/url/encode.html', tools=tools)\n\n @route('/url/decode')\n def tools_urldecode(self):\n tools = []\n return render_template('tools/url/decode.html', tools=tools)\n","sub_path":"etc/mosca/mosca/mosca/views/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"417803039","text":"from app.config import Config\nfrom database import Connection\nfrom app.video_dao import VideoDAO\n\nfrom models.video import Video\n\nimport unittest\n\nclass VideoDAOTest(unittest.TestCase):\n\n def setUp(self):\n Config()\n\n self.v = VideoDAO()\n self.test_id = 'TEST-123'\n\n self.v.session.add(Video(self.test_id))\n self.v.commit()\n\n def test_get_video(self):\n video = self.v.get_video(self.test_id)\n self.assertEqual(video.id, self.test_id)\n\n def test_add_if_not_exist(self):\n # case 1. 데이터가 이미 존재함\n video = self.v.add_if_not_exist(self.test_id)\n self.v.commit()\n\n self.assertEqual(video.id, self.test_id)\n\n # case 2. 데이터가 없어서 새로 생성해야 할 경우\n self.v.session.delete(video)\n self.v.commit()\n video = self.v.add_if_not_exist(self.test_id)\n self.v.commit()\n\n self.assertEqual(video.id, self.test_id)\n\n def tearDown(self):\n test_video = Video.query.filter_by(id=self.test_id).first()\n if test_video:\n self.v.session.delete(test_video)\n self.v.commit()","sub_path":"beefarm/test/video_dao_test.py","file_name":"video_dao_test.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"501944380","text":"import os\nimport re\nimport sys\n\ntry:\n import git\nexcept ModuleNotFoundError:\n print('{{ cookiecutter._template }} requires gitpython.')\n raise\n\nPROJECT_DIRECTORY = os.path.realpath(os.path.curdir)\nMODULE_REGEX = r'^[_a-zA-Z][_a-zA-Z0-9]+$'\n\nnamespace_name = '{{ cookiecutter.project_namespace }}'\nmodule_name = '{{ cookiecutter.project_slug }}'\n\n\ndef assert_project_slug_is_valid_module_name():\n if not re.match(MODULE_REGEX, module_name):\n print(\n 'ERROR: The project slug (%s) is not a valid Python module name. Please do not use a - and use _ instead' % module_name)\n # Exit to cancel project\n sys.exit(1)\n\n\ndef assert_project_namespace_is_valid():\n if not re.match(MODULE_REGEX, namespace_name):\n print(\n 'ERROR: The project namespace (%s) is not a valid Python module name. Please do not use a - and use _ instead' % namespace_name)\n # Exit to cancel project\n sys.exit(1)\n\n\ndef initialize_git():\n r = git.Repo.init(PROJECT_DIRECTORY)\n\n\nif __name__ == '__main__':\n assert_project_namespace_is_valid()\n assert_project_slug_is_valid_module_name()\n\n initialize_git()\n\n\n","sub_path":"hooks/pre_gen_project.py","file_name":"pre_gen_project.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"71734055","text":"import pandas as pd\nimport numpy as np\n\nfrom bokeh.plotting import figure\nfrom bokeh.models import DatetimeTickFormatter\nfrom bokeh.layouts import column\n\ndef bar(dataframe: pd.DataFrame, data_inicial, data_final):\n cluster_label = [\"cluster_\" + str(cluster_label_i) for cluster_label_i in dataframe.cluster_label]\n conversao = list(dataframe.convertido)\n\n cluster = [label for label in dataframe[\"cluster_label\"]]\n colors = [set_color(_) for _ in cluster]\n\n title = \"Total Conversão by cluster in the period: \" + str(data_inicial) + \"-\" + str(data_final)\n p = figure(x_range=cluster_label, title=title,\n toolbar_location=None, tools=\"\")\n\n p.vbar(x=cluster_label, top=conversao, width=0.9, fill_color=colors)\n\n p.xgrid.grid_line_color = None\n p.y_range.start = 0\n\n return p\n\n\ndef line_time(dataframe: pd.DataFrame, data_inicial, data_final):\n\n if ('hora' in dataframe.columns)==True:\n dataframe[\"data\"] = pd.to_datetime(dataframe.data) + pd.to_timedelta(list(map(int, dataframe.hora)), unit='h')\n\n colors = set_color_unproportional(dataframe.cluster_label.unique())\n\n title = \"Conversão time series plot in the period: \" + str(data_inicial) + \"-\" + str(data_final)\n plots = []\n for cluster_label, color in zip(range(0, dataframe.cluster_label.nunique()), colors):\n p = figure(title=\"\",\n toolbar_location=None, tools=\"\", x_axis_label=\"datatime\", y_axis_label=\"Conversão\", plot_width=1300)\n date = pd.to_datetime(dataframe.loc[dataframe[\"cluster_label\"] == str(cluster_label)]['data'])\n convertido = dataframe.loc[dataframe[\"cluster_label\"] == str(cluster_label)]['convertido']\n lengenda = \"cluster \" + str(cluster_label)\n sample_size = len(date[::1])\n limite_central, limite_superior, limite_inferior = get_bootstrap_confidencial_interval(convertido)\n\n p.line(date, convertido, line_color=color, line_width=2, legend=lengenda)\n p.circle(date[::1], np.repeat(limite_central, sample_size), size=3, fill_color=\"black\", line_color=\"black\")\n p.circle(date[::1], np.repeat(limite_inferior, sample_size), size=3, fill_color=\"black\", line_color=\"black\")\n p.circle(date[::1], np.repeat(limite_superior, sample_size), size=3, fill_color=\"black\", line_color=\"black\",\n legend= \"bootstrap confidential intervals\")\n p.xaxis.formatter = DatetimeTickFormatter(\n hours=[\"%d %B %Y\"],\n days=[\"%d %B %Y\"],\n months=[\"%d %B %Y\"],\n years=[\"%d %B %Y\"],\n )\n p.xaxis.major_label_orientation = 3.1614 / 4\n plots.append(p)\n\n return column(plots)\n\n\ndef set_color_unproportional(label):\n COLORS = [\"green\", \"blue\", \"red\", \"orange\", \"purple\", \"yellow\", \"grey\", \"lawngreen\"]\n\n index = len(label)\n\n return COLORS[0:index]\n\ndef set_color(color):\n COLORS = [\"green\", \"blue\", \"red\", \"orange\", \"purple\", \"yellow\", \"grey\", \"lawngreen\"]\n\n index = color % len(COLORS)\n\n return COLORS[index]\n\ndef get_bootstrap_confidencial_interval(sample):\n sample = np.array(sample)\n sample = sample[~np.isnan(sample)]\n sample_size = len(sample)\n mean_bootstrap, limite_superior_bootstrap, limite_inferior_bootstrap = [], [], []\n for bootstrap_i in range(0, 1000):\n position = np.random.choice(sample_size, sample_size, replace =True)\n sample_bootstrap = sample[position]\n sample_mean = np.mean(sample_bootstrap)\n limite_superior = np.quantile(sample_bootstrap, 0.975)\n limite_inferior = np.quantile(sample_bootstrap, 0.025)\n mean_bootstrap.append(sample_mean)\n limite_superior_bootstrap.append(limite_superior)\n limite_inferior_bootstrap.append(limite_inferior)\n mean_bootstrap = np.mean(mean_bootstrap)\n limite_superior_bootstrap = np.mean(limite_superior_bootstrap)\n limite_inferior_bootstrap = np.mean(limite_inferior_bootstrap)\n return mean_bootstrap, limite_superior_bootstrap, limite_inferior_bootstrap","sub_path":"desafio_iafront/jobs/graphics/conversao_graphics/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"606390567","text":"from collections import deque, OrderedDict\n\nfrom bitarray import bitarray\n\nimport mint\nfrom mint import simulation\nfrom mint.exceptions import Full, Empty\nfrom mint.snippets import block_on\nfrom mint.algorithms import bitstuff\n\nclass Buffer(object):\n\n def __init__(self, size):\n self.size = size\n self.used = 0\n self.items = deque()\n\n @property\n def unused(self):\n return self.size - self.used\n\n def append(self, data):\n if len(data) > self.unused:\n raise Full\n self.items.append(data)\n self.used += len(data)\n\n def popleft(self):\n if not self.items:\n raise Empty\n item = self.items.popleft()\n self.used -= len(item)\n return item\n\n def __str__(self):\n return '{}/{}'.format(self.used, self.size)\n\ndef block_on(exc):\n def deco(f):\n def f_(*args, **kwargs):\n while True:\n block = kwargs.pop('block', True)\n try:\n return f(*args, **kwargs)\n except exc:\n if block:\n mint.elapse(1)\n else:\n raise\n return f_\n return deco\n\nclass Delimiter(object):\n\n def __init__(self, tip, buffer_size=512):\n self.host = tip.host\n tip.master = self\n self.tip = tip\n self.obuffer = Buffer(buffer_size)\n self.ibuffer = Buffer(buffer_size)\n self.odata = ''\n self.idata = ''\n\n @block_on(Full)\n def send(self, data):\n self.odata = data\n self.obuffer.append(data)\n\n @block_on(Empty)\n def recv(self):\n return self.ibuffer.popleft()\n\n @property\n def status(self):\n return OrderedDict([\n ('obuffer', str(self.obuffer)),\n ('ibuffer', str(self.ibuffer)),\n ])\n\nclass NIC(Delimiter):\n\n def __init__(self, *args, **kwargs):\n super(NIC, self).__init__(*args, **kwargs)\n self.oframe = Outputter(self.host)\n self.iframe = Inputter(self.host)\n mint.worker(self.run, priority=simulation.NIC_PRIORITY)\n\n def run(self):\n while True:\n self.output()\n self.input()\n mint.elapse(1)\n\n def output(self):\n if not self.oframe:\n try:\n payload = self.obuffer.popleft()\n self.oframe = Outputter(self.host, payload)\n except Empty:\n pass\n self.tip.osymbol = self.oframe.next_bit()\n\n def input(self):\n self.iframe.feed(self.tip.isymbol)\n if self.iframe.complete:\n payload = self.iframe.tobytes()\n self.idata = payload\n try:\n self.ibuffer.append(payload)\n except Full:\n pass\n self.host.report('frame dropped')\n self.iframe = Inputter(self.host)\n\n @property\n def status(self):\n r = super(NIC, self).status\n s_oframe = str(self.oframe.bits[self.oframe.i:])[10:-2]\n s_iframe = str(self.iframe.bits)[10:-2]\n r.update(OrderedDict([\n ('oframe', s_oframe),\n ('iframe', s_iframe),\n ('i_count', self.iframe.count),\n ('osymbol', self.tip.osymbol),\n ('isymbol', self.tip.isymbol),\n ]))\n return r\n\n @property\n def sending(self):\n return self.oframe.frame_length\n\n @property\n def sent(self):\n return self.oframe.frame_length - len(self.oframe)\n\nclass Outputter(object):\n\n def __init__(self, host, bytes=None):\n self.host = host\n if bytes is None:\n self.bits = bitarray(endian='big')\n else:\n self.bits = bitstuff.stuffed(bytes)\n self.frame_length = len(self.bits)\n self.i = 0\n\n def next_bit(self):\n try:\n r = self.bits[self.i]\n self.i += 1\n return int(r)\n except IndexError:\n del self.bits[:]\n self.frame_length = 0\n self.i = 0\n return 0\n\n def __len__(self):\n return self.frame_length - self.i\n\nclass Inputter(object):\n\n def __init__(self, host):\n self.host = host\n self.bits = bitarray(endian='big')\n self.idle = True\n self.complete = False\n self.count = 0\n self.recving_finished = False\n\n def feed(self, bit):\n if self.idle:\n if bit:\n self.count += 1\n else:\n if self.count == 6:\n self.idle = False\n self.count = 0\n else:\n self.bits.append(bit)\n if bit:\n self.count += 1\n else:\n if self.count == 5:\n del self.bits[-1]\n elif self.count == 6:\n del self.bits[-8:]\n self.complete = True\n self.count = 0\n\n def tobytes(self):\n return self.bits.tobytes()\n","sub_path":"mint/_versions/20151210190047 DHCP/mint/nic.py","file_name":"nic.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"208875868","text":"from bs4 import BeautifulSoup\r\nimport requests\r\n\r\nimport re\r\n\r\n\r\ndef find_movie_name(bs):\r\n titleName = bs.find(\"h1\", {'class': re.compile('TitleHeader*')})\r\n if titleName is None: # in case of null\r\n name = \"\"\r\n else:\r\n name = titleName.contents[0].replace(u'\\xa0', u'')\r\n return name\r\n\r\n\r\ndef find_genre(bs):\r\n info = \"\"\r\n genre = bs.find_all('li', class_=\"ipc-metadata-list__item\")\r\n for li in genre:\r\n lable = li.find('span', class_=\"ipc-metadata-list-item__label\")\r\n if lable != None:\r\n content = li.find('div')\r\n\r\n if lable.get_text() == \"Genres\":\r\n info = info + content.get_text(',')\r\n # print(f\"{lable.get_text()} : {content.get_text(',')}\")\r\n return info\r\n\r\n\r\ndef find_directors(bs):\r\n names = \"\"\r\n directors = bs.find(\"div\", {'class': re.compile('ipc-metadata-list*')})\r\n for director in directors.contents[0]:\r\n names = director.getText(\",\") + names\r\n # print(director.getText() + \" \")\r\n return names\r\n\r\n\r\ndef find_actors(bs):\r\n names = \"\"\r\n all_cast = bs.find_all('section', {\"data-testid\": \"title-cast\"})\r\n if len(all_cast) == 0:\r\n return names\r\n cast = all_cast[0]\r\n\r\n all_items = cast.find_all('div', {\"data-testid\": \"title-cast-item\"})\r\n for item in all_items:\r\n data = item.get_text(\"#$#\")\r\n names = names + \",\" + data.split(\"#$#\")[0]\r\n\r\n names = names[1:]\r\n\r\n return names\r\n\r\n\r\ndef find_info(bs):\r\n rating = bs.find(\"div\", {'class': re.compile('TitleBlock*')}).find_all('li')\r\n str = \"\"\r\n for r in rating:\r\n if r != None:\r\n str = str + \"|\" + r.getText()\r\n\r\n index = str[1:].find('|')\r\n str = str[index + 2:]\r\n if str.isdigit():\r\n str = \"\"\r\n return str\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n f = open(\"output.txt\", \"a+\", encoding=\"utf8\")\r\n index = 0\r\n user_input = input(\"Enter something:\\n> \") # The user enters a title\r\n search_terms = user_input.split()\r\n url = \"http://www.imdb.com/find?q=\" + '+'.join(search_terms) + '&s=tt' + '&ttype=ft' # tt for titles\r\n response = requests.get(url)\r\n soup = BeautifulSoup(response.text, 'html.parser')\r\n links = [a.attrs.get('href') for a in soup.select('td.result_text a')] # links is array of all the movies(tv..)\r\n\r\n for link in links: # Loop for each movie\r\n search_terms = link.split()\r\n url2 = \"http://www.imdb.com/\" + '+'.join(search_terms) # The url of specific movie\r\n response2 = requests.get(url2)\r\n soup2 = BeautifulSoup(response2.text, 'html.parser')\r\n\r\n movie_name = find_movie_name(soup2)\r\n directors_names = find_directors(soup2)\r\n genre_info = find_genre(soup2)\r\n info = find_info(soup2)\r\n actors = find_actors(soup2)\r\n\r\n if movie_name.lower().find(user_input.lower()) != -1:\r\n s = movie_name + \"|\" + genre_info + \"|\" + info + \"|\" + directors_names + \"|\" + actors + \"\\n\"\r\n f.write(s)\r\n print(s)\r\n\r\n f.close()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"479422929","text":"import requests\n\nendpoint = \"https://newsapi.org/docs/endpoints/top-headlines\"\napi_key = \"35f754e21cb449b79e2be6dac7e5fb82\"\n\n\ndef get_news(country=None, category=None, sources=None, pageSize=None, q=None, page=None):\n params = {\n 'country': country,\n 'category': category,\n 'sources': sources,\n 'pageSize': pageSize,\n 'q': q,\n 'page': page,\n 'apiKey': api_key\n }\n params = {k: v for k, v in params.items() if v is not None}\n r = requests.get(endpoint, params=params)\n return r.json\n","sub_path":"Week_10/Day_3/Class/class.py","file_name":"class.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"108659247","text":"from django.db import models\nfrom db.baseModels import BaseModel\n\n# Create your models here.\nclass OrderInfo(BaseModel):\n \"\"\"订单模型类\"\"\"\n PAY_METHOD_CHOICES = (\n (1,\"货到付款\"),\n (2,\"微信支付\"),\n (3,\"支付宝\"),\n (4,\"银联支付\")\n )\n ORDER_STATUS_CHOICES = (\n (1,\"待支付\"),\n (2,\"待发货\"),\n (3,\"待收货\"),\n (4,\"待评价\"),\n (5,\"已完成\")\n )\n order_id = models.CharField(max_length=128,primary_key=True,verbose_name=\"订单号\")\n user = models.ForeignKey(\"user.User\",on_delete=False,verbose_name=\"用户\")\n addr = models.ForeignKey(\"user.Address\",on_delete=False,verbose_name=\"地址\")\n pay_method = models.SmallIntegerField(choices=PAY_METHOD_CHOICES,default=1,verbose_name=\"支付方式\")\n totle_count = models.IntegerField(default=1,verbose_name=\"商品数量\")\n totle_price = models.DecimalField(max_length=10,decimal_places=2,max_digits=10,verbose_name=\"总金额\")\n transit_price = models.DecimalField(max_length=10,decimal_places=2,max_digits=10,verbose_name=\"运费\")\n order_status = models.SmallIntegerField(choices=ORDER_STATUS_CHOICES,default=1,verbose_name=\"订单状态\")\n trade_no = models.CharField(max_length=128,verbose_name=\"支付编号\")\n\n class Meta:\n db_table = \"df_order_info\"\n verbose_name = \"订单\"\n verbose_name_plural = verbose_name\n\n\nclass OrderGoods(BaseModel):\n \"\"\"订单商品模型类\"\"\"\n order = models.ForeignKey(\"OrderInfo\",on_delete=False,verbose_name=\"订单\")\n sku = models.ForeignKey(\"goods.GoodsSKU\",on_delete=False,verbose_name=\"商品SKU\")\n count = models.IntegerField(default=1,verbose_name=\"商品数目\")\n price = models.DecimalField(max_length=10,decimal_places=2,max_digits=10,verbose_name=\"商品价格\")\n comment = models.CharField(max_length=256,verbose_name=\"评论\")\n\n class Meta:\n db_table = \"df_order_goods\"\n verbose_name = \"订单商品\"\n verbose_name_plural = verbose_name\n","sub_path":"dailyfresh/apps/order/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"64389097","text":"'''\n238. Product of Array Except Self\n\nGiven an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].\nThe product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.\nYou must write an algorithm that runs in O(n) time and without using the division operation. \n\nExample 1:\nInput: nums = [1,2,3,4]\nOutput: [24,12,8,6]\n\nExample 2:\nInput: nums = [-1,1,0,-3,3]\nOutput: [0,0,9,0,0]\n'''\n\nclass Solution:\n def productExceptSelf(self, nums: List[int]) -> List[int]:\n n = len(nums)\n product = [1]*n\n # Calculate product of all elements to the left of index i\n for i in range(1, n):\n product[i] = product[i-1] * nums[i-1]\n prodFromRight = 1 # the product of all element from i+1 to the right\n for i in range(n-1, -1, -1):\n product[i] *= prodFromRight\n prodFromRight *= nums[i]\n return product","sub_path":"Array/238_ProductOfArrayExceptSelf.py","file_name":"238_ProductOfArrayExceptSelf.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"593168372","text":"import itertools\r\n\r\ns = input()\r\nword = list(s[:s.index(\" \")])\r\nword.sort()\r\nk = int(s[s.index(\" \"):])\r\nfor i in range(1,k+1):\r\n perms = list(itertools.combinations(word,i))\r\n for w in perms:\r\n print(\"\".join(w))","sub_path":"Itertools/itertools combinations.py","file_name":"itertools combinations.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"609921062","text":"import subprocess as sp\nimport sys\n\n\ndef decode(\n path, from_position=0, sample_rate=None, channels=None\n):\n # print('from_position', from_position)\n format_options = []\n if sample_rate is not None:\n format_options.extend(('-ar', f'{sample_rate}'))\n if channels is not None:\n format_options.extend(('-ac', f'{channels}'))\n return sp.Popen(\n [\n 'ffmpeg',\n '-ss', f'{from_position}',\n '-i', path,\n '-f', 'f32le',\n *format_options,\n # '-af', 'areverse',\n '-'\n ],\n stdout=sp.PIPE,\n stderr=sp.DEVNULL\n )\n","sub_path":"audio_player/lib/audio_file/adapters/ffmpeg/ffmpeg_process.py","file_name":"ffmpeg_process.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"351687962","text":"import json\nimport sys\nimport mysql.connector\nimport os\n\n# Connect to database\nmydb = mysql.connector.connect(\n host=\"35.237.166.166\",\n user=\"root\",\n passwd=\"sg5ycEoL6mrhMyaK\",\n database=\"data_druid\"\n)\ncursor = mydb.cursor()\n\nif len(sys.argv) < 2:\n print(\"Usage: python3 pull-submissions.py (optional)\")\n exit(1)\n\n# Ensure directory structure exists\nif not os.path.isdir(\"corpus\"):\n os.makedirs(\"corpus\")\nif not os.path.isdir(\"corpus/impls\"):\n os.makedirs(\"corpus/impls\")\nif not os.path.isdir(\"corpus/predicates\"):\n os.makedirs(\"corpus/predicates\")\n\nassignment = sys.argv[1]\ntool = sys.argv[2] if len(sys.argv) == 3 else None\n\n# Pull rows\nquery = 'SELECT id, submission FROM unprompted_log WHERE assignment_id=\"{}\"'.format(assignment)\nif tool: query += ' AND tool=\"{}\"'.format(tool)\ncursor.execute(query)\nrows = cursor.fetchall()\n\nfor row in rows:\n f = open(\"corpus/impls/row-{}\".format(row[0]), \"w\")\n split = row[1].split(\"# DO NOT CHANGE ANYTHING ABOVE THIS LINE\")\n content = 'include file(\"tests.arr\")\\n# DO NOT CHANGE ANYTHING ABOVE THIS LINE\\n' + split[-1]\n f.write(content)\n f.close()","sub_path":"pull-submissions.py","file_name":"pull-submissions.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"205603171","text":"import numpy as np\r\nimport pandas as pd\r\nfrom sklearn import datasets\r\n\r\ndef nonline(x, deriv=False):\r\n if deriv:\r\n return x * (1-x)\r\n return 1 / (1 + np.exp(-x))\r\n\r\ndef main():\r\n np.random.seed(1)\r\n ds = datasets.load_digits()\r\n\r\n # print(len(ds.images), len(ds.target))\r\n X_train, y_train = ds.images[:1500], ds.target[:1500]\r\n X_test, y_test = ds.images[1500:], ds.target[1500:]\r\n # print(len(X_train), len(y_train))\r\n # print(len(X_test), len(y_test))\r\n # print(X_train.shape)\r\n # print(y_train[10:])\r\n\r\n wih = np.random.rand(32, 64)\r\n who = np.random.rand(10, 32)\r\n\r\n conv = [i.flatten() for i in X_train]\r\n X_train_vect = np.array(conv)\r\n # print(X_train_vect[:5])\r\n # print(np.squeeze(np.asarray(X_test[0])))\r\n\r\n # print(wih)\r\n # print(who)\r\n\r\n epochs = 5000\r\n for epoch in range(epochs):\r\n for x_t, y_t in zip(X_train_vect, y_train):\r\n print(x_t)\r\n hidden_output = nonline(np.dot(wih, x_t), False)\r\n final_output = nonline(np.dot(who, hidden_output))\r\n\r\n print(len(final_output))\r\n break\r\n break\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"neural_network/nn_mnist.py","file_name":"nn_mnist.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"410036095","text":"from Functions import *\nfrom Tkinter import *\nimport os\nwindow2=Tk()\nwindow2.config(bg=\"lightblue\") #will set the background of window to light blue.\nwindow2.title(\"BATTLESHIPS\")#will give the title to window as BATTLESHIPS.\n\ntopFrame=Frame(window2)# creates a top frame.\ntopFrame.config(bg=\"lightblue\")\ntopFrame.pack(side=TOP,fill=X)\n\ntitle=Label(topFrame,text=\"BATTLESHIPS\",bg=\"black\",fg = \"white\")#will set the title to BATTLESHIPS.\ntitle.config(font=200)#sets the size of the text to 200.\ntitle.pack(side=TOP)\n\nlabel1=Label(topFrame)\nlabel1.config(width=25,bg=\"lightblue\")\nlabel1.pack(side=TOP)\n\nlabel2=Label(topFrame,text=\"PLAYER 1 TERRITORY\",fg=\"green\")#adds text as PLAYER 1 TERRITORY\nlabel2.config(font=50,width=20)\t\t\t\t\t#fg sets the text colour to green\nlabel2.pack(side=LEFT)\n\nblank=Label(topFrame)#adds a blank label to create gap.\nblank.config(width=10,font=50,bg=\"lightblue\")#width sets the width of the label as 30.\nblank.pack(side=RIGHT,fill=X)\n\nlabel3=Label(topFrame,text=\"PLAYER 2 TERRITORY\",fg=\"green\")#adds text as PLAYER 2 TERRITORY\nlabel3.config(font=50,width=20)\nlabel3.pack(side=RIGHT)\n\nrightFrame=Frame(window2)\nrightFrame.config(bg=\"lightblue\")\nleftFrame=Frame(window2)\nleftFrame.config(bg=\"lightblue\")\n\nuser1frame=Frame(leftFrame)\nuser1frame.config()\nuser1Grid=[]\n#to create a 10X10 grid with buttons\nfor j in range(10):\n Brow=[]\n for i in range(10):\n b=Button(user1frame,bg=\"blue\")\n b.config(height=1,width=2)\n b.grid(row=j,column=i)\n Brow.append(b)\n user1Grid.append(Brow)\nuser1frame.pack(side=LEFT)\n\nuser2frame=Frame(rightFrame)\nuser2frame.config()\nuser2Grid=[]\n#to create a 10X10 grid with buttons\nfor j in range(10):\n Brow=[]\n for i in range(10):\n b=Button(user2frame,bg=\"blue\")\n b.config(height=1,width=2)\n b.grid(row=j,column=i)\n Brow.append(b)\n user2Grid.append(Brow)\nuser2frame.pack(side=LEFT)\ndef quit():#quits the game\n window2.destroy()\ndef newgame():#pressing the button starts a new game\n cmd=\"python NewGame_2.py\"#links the newgame button to NewGame_2.py file\n f=os.popen(cmd)\n quit()\nnewgamebutton=Button(text=\"New Game\",bg=\"red\",command = newgame)#creates a new game button\nquitbutton=Button(text=\"Quit\",bg=\"red\",command=quit)#creates an about button\n\nquitbutton.config(height=2,width=10,font=25)\nquitbutton.pack(side=BOTTOM)\n\n\n\nnewgamebutton.config(height=2,width=10,font=25)\nnewgamebutton.pack(side=BOTTOM)\n\nbottomFrame=Frame(window2,height=50,width=60)\nbottomFrame.config(bg=\"lightblue\")\nlabel4=Label(topFrame,text=\"\")\nlabel4.config(bg=\"lightblue\",font=45,width=50)\nlabel4.pack(side=TOP)\nlabel10=Label(topFrame,text=\"\")\nlabel10.config(bg=\"lightblue\",font=45,width=50)\nlabel10.pack(side=TOP)\nleftFrame.config(height=30)\nrightFrame.config(height=30)\n\ngap1=Label(window2,bg=\"lightblue\")\ngap1.config(width=30,height=40)\n\nuser1=User1(user1Grid, label4, label10)\nuser2=User2(user2Grid,label4, label10)\n\n\n\n\nleftFrame.pack(side=LEFT)#creates a leftframe in window\ngap1.pack(side=LEFT)\nrightFrame.pack(side=RIGHT)#creates a rightframe in window\n\nbottomFrame.pack(side=BOTTOM,fill=X)#creates a bottom frame in window\n\n\nwindow2.mainloop()\n","sub_path":"NewGame_1.py","file_name":"NewGame_1.py","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"112058699","text":"'''\r\nBy listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.\r\n\r\nWhat is the 10 001st prime number?\r\n'''\r\n\r\ndef is_prime(n):\r\n\tif n <= 1:\r\n\t\treturn False\r\n\telif n <= 3:\r\n\t\treturn True\r\n\telif n % 2 == 0 or n % 3 == 0:\r\n\t\treturn False\r\n\r\n\ti = 5\r\n\twhile i * i <= n:\r\n\t\tif n % i == 0 or n % (i + 2) == 0:\r\n\t\t\treturn False\r\n\t\ti += 6\r\n\r\n\treturn True\r\n\r\nwhich_prime = 0\r\ncur_num = 1\r\nwhile which_prime < 10001:\r\n\tcur_num += 1\r\n\tif is_prime(cur_num):\r\n\t\twhich_prime += 1\r\n\r\nprint(str(cur_num))","sub_path":"ProjectEuler/007.py","file_name":"007.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"213908955","text":"# Lesson 3.4: Make Classes\n# Mini-Project: Movies Website\n\n# In this file, you will define instances of the class Movie defined\n# in media.py. After you follow along with Kunal, make some instances\n# of your own!\n\n# After you run this code, open the file fresh_tomatoes.html to\n# see your webpage!\n\nimport media\nimport fresh_tomatoes\n\ntoy_story = media.Movie(\"Toy Story\",\n \"http://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg\",\n \"http://www.youtube.com/watch?v=vwyZH85NQC4\",\n \"1995\")\n\navatar = media.Movie(\"Avatar\",\n \"http://upload.wikimedia.org/wikipedia/id/b/b0/Avatar-Teaser-Poster.jpg\",\n \"http://www.youtube.com/watch?v=-9ceBgWV8io\",\n \"2009\")\ngone_with_the_wind = media.Movie(\"Gone with the Wind\",\n \"http://a1.att.hudong.com/02/59/01300000167882121489590059133.jpg\",\n \"https://www.youtube.com/watch?v=8mM8iNarcRc\",\n \"1939\")\n\nmovies = [toy_story, avatar, gone_with_the_wind]\nfresh_tomatoes.open_movies_page(movies)\n","sub_path":"project3/entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"168592400","text":"import os.path\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nfrom skimage.color import lab2rgb\nfrom Helpers.utilities import validation_methods\nfrom Helpers.KAIST_DataLoader import *\nimport math\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n\n\ndef test(args, device):\n G = torch.load('epochs/' + args.Folder + '/final.pt', map_location=\"cuda:%i\" % args.GPUid)\n G.eval()\n\n test_loader = DataLoader(dataset=DatasetFromFolder(args.Dataset, set='test'),\n num_workers=5, batch_size=1, shuffle=False)\n test_bar = tqdm(test_loader, desc='Colorizing thermal')\n\n running_results = {'batch_sizes': 0, 'psnr': 0, 'rmse': 0, 'ssim': 0}\n for data, _, RGB, fname in test_bar:\n fname = fname\n batch_size = data.size(0)\n running_results['batch_sizes'] += batch_size\n\n data = data.to(device)\n with torch.no_grad():\n colorized_img = G(data)\n colorized_img = denormalize_tensorLAB(colorized_img.data.cpu())\n colorized_img = lab2rgb(colorized_img[0].permute(1, 2, 0).numpy())\n\n colorized_img = np.clip(colorized_img, 0, 1)\n colorized_img = torch.FloatTensor(colorized_img).permute(2, 0, 1).unsqueeze(0)\n\n\n mse, batch_ssim, psnr = validation_methods(colorized_img, RGB)\n running_results['ssim'] += batch_ssim\n running_results['psnr'] += psnr\n running_results['rmse'] += math.sqrt(mse.item())\n\n test_bar.set_description(desc='PSNR: %.6f SSIM: %.6f RMSE: %.6f'\n % (running_results['psnr'] / running_results['batch_sizes'],\n running_results['ssim'] / running_results['batch_sizes'],\n running_results['rmse'] / running_results['batch_sizes']))\n\n dic = args.Folder + '/test/' + fname[0][0].replace('\\\\','/')\n if not os.path.exists(dic):\n os.makedirs(dic)\n\n ndarr = colorized_img[0].mul_(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy()\n im = Image.fromarray(ndarr)\n im.save(join(dic, 'C_' + fname[1][0] + '.png'))\n\n","sub_path":"TIR2LAB/Test_Berge_KAIST.py","file_name":"Test_Berge_KAIST.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"429646254","text":"# -*- coding: utf-8 -*-\n\nimport sys,random\n\nfrom PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget,\n QSplitter, QColorDialog,QInputDialog)\n\nfrom PyQt5.QtCore import pyqtSlot,Qt\n\n\nfrom PyQt5.QtGui import QVector3D\n\n##from PyQt5.QtSql import \n\n##from PyQt5.QtMultimedia import\n\n##from PyQt5.QtMultimediaWidgets import\n\nfrom PyQt5.QtDataVisualization import *\n\n\nfrom ui_MainWindow import Ui_MainWindow\n\nclass QmyMainWindow(QMainWindow): \n\n def __init__(self, parent=None):\n super().__init__(parent) #调用父类构造函数,创建窗体\n self.ui=Ui_MainWindow() #创建UI对象\n self.ui.setupUi(self) #构造UI界面\n\n self.setWindowTitle(\"Demo13_1, Q3DBars和QBar3DSeries绘制三维柱状图\")\n self.ui.sliderZoom.setRange(10,500) #缺省缩放范围,100=原始大小\n self.ui.sliderH.setRange(-180,180) #水平旋转角度范围\n self.ui.sliderV.setRange(-180,180) #垂直旋转角度范围\n\n self.__iniGraph3D() ##创建图表\n splitter=QSplitter(Qt.Horizontal)\n splitter.addWidget(self.ui.frameSetup) #左侧控制面板\n splitter.addWidget(self.__container) #右侧图表\n\n self.setCentralWidget(splitter) #设置主窗口中心组件\n \n\n## ==============自定义功能函数========================\n\n def __iniGraph3D(self): ##创建3D图表\n self.graph3D = Q3DBars()\n self.__container = QWidget.createWindowContainer(self.graph3D) #Q3DBars继承自QWindow\n camView=Q3DCamera.CameraPresetFrontHigh \n self.graph3D.scene().activeCamera().setCameraPreset(camView) #设置视角\n self.graph3D.activeTheme().setLabelBackgroundEnabled(False) #不显示标签背景\n\n ## 创建坐标轴\n axisV=QValue3DAxis() #数值坐标轴\n axisV.setTitle(\"销量(万元)\")\n axisV.setTitleVisible(True) #轴标题可见\n axisV.setLabelFormat(\"%.1f\") #轴标签格式 \n self.graph3D.setValueAxis(axisV) #设置数值坐标轴\n\n axisRow=QCategory3DAxis() #文字类别型坐标轴\n axisRow.setTitle(\"row axis\")\n ## rowLabs=[\"Week1\" , \"Week2\", \"Week3\"]\n ## axisRow.setLabels(rowLabs) #可以在此设置行标签,也可以在dataProxy里设置\n axisRow.setTitleVisible(True)\n ## axisRow.setLabelAutoRotation(90) #随camera自动旋转的角度,最大90,缺省0\n self.graph3D.setRowAxis(axisRow) #设置行坐标轴\n\n axisCol=QCategory3DAxis() #文字类别型坐标轴\n axisCol.setTitle(\"column axis\")\n colLabs=[\"Mon\", \"Tue\" , \"Wed\", \"Thur\", \"Fri\", \"Sat\",\"Sun\"]\n ## axisCol.setLabels(colLabs) #可以在此设置列标签,也可以在dataProxy里设置\n axisCol.setTitleVisible(True)\n ## axisCol.setLabelAutoRotation(90) #随camera自动旋转的角度,最大90,缺省0\n self.graph3D.setColumnAxis(axisCol) #设置列坐标轴\n\n ## 创建序列\n self.series = QBar3DSeries() #三维柱状图序列\n self.series.setMesh(QAbstract3DSeries.MeshCylinder) #棒柱样式 MeshBar,MeshPyramid,MeshCylinder\n self.series.setItemLabelFormat(\"(@rowLabel,@colLabel): %.1f\") #棒柱的标签显示格式\n self.series.setName(\"3D柱状图序列\") #在setItemLabelFormat里可引用@seriesName\n self.graph3D.addSeries(self.series) #添加序列到图表\n\n self.dataProxy=QBarDataProxy() #创建数据代理\n for j in range(3): #3行\n rowItems = [] # 一行的 QBarDataItem 列表\n for i in range(7): #7列\n value=random.uniform(8,16) #均匀分布\n item=QBarDataItem(value) #每个棒柱对应一个QBarDataItem对象\n rowItems.append(item) \n rowStr=\"Week%d\"%(j+1) #行标签\n self.dataProxy.addRow(rowItems,rowStr) #添加行,以及行标签\n\n self.dataProxy.setColumnLabels(colLabs) #设置列标签\n \n self.series.setDataProxy(self.dataProxy) #设置数据代理\n self.series.selectedBarChanged.connect(self.do_barSelected)\n\n## ==============event处理函数==========================\n \n \n## ==========由connectSlotsByName()自动连接的槽函数============ \n\n##===工具栏actions==\n @pyqtSlot() ## \"序列基本颜色\"\n def on_actSeries_BaseColor_triggered(self):\n color=self.series.baseColor()\n color=QColorDialog.getColor(color)\n if color.isValid():\n self.series.setBaseColor(color)\n\n @pyqtSlot() ## \"修改数值\"\n def on_actBar_ChangeValue_triggered(self):\n position=self.series.selectedBar()\n if position.x()<0 or position.y()<0:\n return #必须加此判断\n bar=self.dataProxy.itemAt(position) #QBarDataItem\n value=bar.value()\n newValue,OK = QInputDialog.getDouble(self,\n \"输入数值\",\"更改棒柱数值\",value, 0, 50, 1)\n if OK:\n bar.setValue(newValue)\n self.dataProxy.setItem(position,bar)\n \n @pyqtSlot() ## \"添加行\"\n def on_actData_Add_triggered(self):\n rowLabel,OK = QInputDialog.getText(self,\"输入字符串\",\"请输入行标签\")\n rowLabel=rowLabel.strip()\n if (not OK) or (rowLabel==\"\"):\n return\n\n rowItems=[]\n for i in range(7): #一周7天\n value=random.uniform(10,20) #均匀分布\n item=QBarDataItem(value) #创建棒柱数据对象\n rowItems.append(item) \n self.dataProxy.addRow(rowItems,rowLabel) #添加行数据,以及行标签\n\n @pyqtSlot() ## \"插入行\"\n def on_actData_Insert_triggered(self):\n rowLabel,OK = QInputDialog.getText(self,\"输入字符串\",\"请输入行标签\")\n rowLabel=rowLabel.strip()\n if (not OK) or (rowLabel==\"\"):\n return\n\n position=self.series.selectedBar() #当前的棒柱\n if position.x()<0:\n rowIndex=0\n else:\n rowIndex=position.x()\n \n rowItems=[]\n for i in range(7): #一周7天\n value=random.uniform(5,10) #均匀分布\n item=QBarDataItem(value) #创建棒柱数据对象\n rowItems.append(item)\n self.dataProxy.insertRow(rowIndex,rowItems,rowLabel) #插入行\n\n\n @pyqtSlot() ## \"删除行\"\n def on_actData_Delete_triggered(self):\n position=self.series.selectedBar()\n if position.x()<0 or position.y()<0:\n return #必须加此判断\n rowIndex=position.x()\n removeCount=1 #删除的行数\n removeLabels=True #是否删除行标签\n self.dataProxy.removeRows(rowIndex,removeCount,removeLabels)\n \n \n##===三维旋转=== \n @pyqtSlot(int) ## \"预设视角\"\n def on_comboCamera_currentIndexChanged(self,index):\n cameraPos=Q3DCamera.CameraPreset(index)\n self.graph3D.scene().activeCamera().setCameraPreset(cameraPos)\n \n @pyqtSlot(int) ## \"水平旋转\"\n def on_sliderH_valueChanged(self,value):\n xRot=self.ui.sliderH.value() #水平\n self.graph3D.scene().activeCamera().setXRotation(xRot)\n\n @pyqtSlot(int) ## \"垂直旋转\"\n def on_sliderV_valueChanged(self,value):\n yRot=self.ui.sliderV.value() #垂直\n self.graph3D.scene().activeCamera().setYRotation(yRot)\n\n @pyqtSlot(int) ## \"缩放\"\n def on_sliderZoom_valueChanged(self,value):\n zoom=self.ui.sliderZoom.value() #缩放\n self.graph3D.scene().activeCamera().setZoomLevel(zoom)\n\n\n @pyqtSlot() ## 复位到FrontHigh视角\n def on_btnResetCamera_clicked(self):\n cameraPos=Q3DCamera.CameraPresetFrontHigh \n self.graph3D.scene().activeCamera().setCameraPreset(cameraPos)\n \n @pyqtSlot() ## \"左移\"\n def on_btnMoveLeft_clicked(self):\n target3D=self.graph3D.scene().activeCamera().target() #QVector3D\n x=target3D.x()\n target3D.setX(x+0.1)\n self.graph3D.scene().activeCamera().setTarget(target3D)\n\n @pyqtSlot() ## \"右移\"\n def on_btnMoveRight_clicked(self):\n target3D=self.graph3D.scene().activeCamera().target() #QVector3D\n x=target3D.x()\n target3D.setX(x-0.1)\n self.graph3D.scene().activeCamera().setTarget(target3D)\n\n @pyqtSlot() ## \"上移\"\n def on_btnMoveUp_clicked(self):\n target3D=self.graph3D.scene().activeCamera().target() #QVector3D\n z=target3D.z()\n target3D.setZ(z-0.1)\n self.graph3D.scene().activeCamera().setTarget(target3D)\n\n @pyqtSlot() ## \"下移\"\n def on_btnMoveDown_clicked(self):\n target3D=self.graph3D.scene().activeCamera().target() #QVector3D\n z=target3D.z()\n target3D.setZ(z+0.1)\n self.graph3D.scene().activeCamera().setTarget(target3D)\n \n\n##====图表总体 \n @pyqtSlot(int) ## \"主题\"\n def on_cBoxTheme_currentIndexChanged(self,index):\n theme=Q3DTheme.Theme(index)\n self.graph3D.activeTheme().setType(theme)\n \n @pyqtSlot(int) ## \"字体大小\"\n def on_spinFontSize_valueChanged(self,arg1):\n font = self.graph3D.activeTheme().font()\n font.setPointSize(arg1)\n self.graph3D.activeTheme().setFont(font)\n\n @pyqtSlot(int) ## \"选择模式\"\n def on_cBoxSelectionMode_currentIndexChanged(self,index):\n if index<=7: #前面8个直接用枚举类型转换\n mode=QAbstract3DGraph.SelectionFlags(index)\n elif index==8: # row slice\n mode=QAbstract3DGraph.SelectionItemAndRow | QAbstract3DGraph.SelectionSlice\n elif index==9: # column slice\n mode=QAbstract3DGraph.SelectionItemAndColumn | QAbstract3DGraph.SelectionSlice\n self.graph3D.setSelectionMode(mode)\n \n \n @pyqtSlot(bool) ## \"显示背景\"\n def on_chkBoxBackground_clicked(self,checked):\n self.graph3D.activeTheme().setBackgroundEnabled(checked)\n \n @pyqtSlot(bool) ## \"显示背景的网格\"\n def on_chkBoxGrid_clicked(self,checked):\n self.graph3D.activeTheme().setGridEnabled(checked)\n\n @pyqtSlot(bool) ## \"数值坐标轴反向\"\n def on_chkBoxReverse_clicked(self,checked):\n self.graph3D.valueAxis().setReversed(checked)\n\n @pyqtSlot(bool) ## \"显示倒影\"\n def on_chkBoxReflection_clicked(self,checked):\n self.graph3D.setReflection(checked)\n \n @pyqtSlot(bool) ## \"轴标题可见\"\n def on_chkBoxAxisTitle_clicked(self,checked):\n self.graph3D.valueAxis().setTitleVisible(checked)\n self.graph3D.rowAxis().setTitleVisible(checked)\n self.graph3D.columnAxis().setTitleVisible(checked)\n\n @pyqtSlot(bool) ## \"轴标签背景可见\"\n def on_chkBoxAxisBackground_clicked(self,checked):\n self.graph3D.activeTheme().setLabelBackgroundEnabled(checked)\n\n##===序列设置\n @pyqtSlot(int) ## \"棒柱样式\"\n def on_cBoxBarStyle_currentIndexChanged(self,index):\n mesh=QAbstract3DSeries.Mesh(index+1) # 0=MeshUserDefined\n self.series.setMesh(mesh)\n \n @pyqtSlot(bool) ## \"光滑效果\"\n def on_chkBoxSmooth_clicked(self,checked):\n self.series.setMeshSmooth(checked)\n\n @pyqtSlot(bool) ## \"选中棒柱的标签可见\"\n def on_chkBoxItemLabel_clicked(self,checked):\n self.series.setItemLabelVisible(checked)\n\n \n## =============自定义槽函数=============================== \n def do_barSelected(self,position): ##选择一个棒柱时触发\n if position.x()<0 or position.y()<0: #无选中的棒柱\n self.ui.actBar_ChangeValue.setEnabled(False)\n return #必须加此判断\n \n self.ui.actBar_ChangeValue.setEnabled(True)\n bar=self.series.dataProxy().itemAt(position) #QBarDataItem\n info=\"选中的棒柱,Row=%d, Column=%d, Value=%.1f\"%(\n position.x(),position.y(),bar.value())\n self.ui.statusBar.showMessage(info)\n \n\n## ============窗体测试程序 ================================\nif __name__ == \"__main__\": #用于当前窗体测试\n app = QApplication(sys.argv) #创建GUI应用程序\n form=QmyMainWindow() #创建窗体\n form.show()\n sys.exit(app.exec_())\n","sub_path":"pyqt/DemoFullCode-PythonQt/chap13DataVisualization/Demo13_1Bar3D/myMainWindow.py","file_name":"myMainWindow.py","file_ext":"py","file_size_in_byte":11934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"436390199","text":"import sys\nimport os\nfrom PyQt4 import QtGui\n\n\nabspath = os.path.abspath(__file__)\ndirname = os.path.dirname\n\nsys.path.append(dirname(dirname(dirname(abspath))))\n\n\nimport productname.classes as pn\n\n\nclass ProductNameWidget(QtGui.QWidget):\n def __init__(self, parent=None):\n super(ProductNameWidget, self).__init__(parent)\n layout = QtGui.QVBoxLayout()\n self.setLayout(layout)\n self.valid_name = pn.ProductName()\n self.element_rows = {}\n self.parent = parent\n\n if isinstance(self.parent, ProductNameDialog):\n self.parent.button_ok.setEnabled(False)\n\n for element in self.valid_name.all_elements:\n labeltext = element\n\n if element in self.valid_name.required_elements:\n labeltext = element + ' (*)'\n\n row = {}\n row['layout'] = QtGui.QHBoxLayout()\n row['label'] = QtGui.QLabel(labeltext)\n row['label'].setMinimumWidth(50)\n row['lineedit'] = QtGui.QLineEdit()\n row['lineedit'].setObjectName(element)\n row['lineedit'].setMinimumWidth(200)\n row['lineedit'].textEdited.connect(self.element_changed)\n row['layout'].addWidget(row['label'])\n row['layout'].addWidget(row['lineedit'])\n self.element_rows[element] = row\n\n layout.addLayout(self.element_rows[element]['layout'])\n\n name_layout = QtGui.QHBoxLayout()\n name_label = QtGui.QLabel('valid product name:')\n name_label.setMinimumWidth(50)\n self.valid_name_label = QtGui.QLabel()\n self.valid_name_label.setMinimumWidth(200)\n name_layout.addWidget(name_label)\n name_layout.addWidget(self.valid_name_label)\n layout.addLayout(name_layout)\n\n def element_changed(self, text):\n current_element = str(self.sender().objectName())\n value = str(text)\n\n if current_element == 'year':\n try:\n value = int(value)\n except ValueError:\n self.element_rows['year']['lineedit'].setText('numbers only')\n\n setattr(self.valid_name, current_element, value)\n\n for element in self.valid_name.all_elements:\n row_lineedit = self.element_rows[element]['lineedit']\n row_lineedit.setStyleSheet(\"color: rgb(0, 150, 0);\")\n\n if element in self.valid_name.invalid_elements:\n row_lineedit.setStyleSheet(\"color: rgb(255, 0, 0);\")\n\n if self.valid_name:\n self.valid_name_label.setText(self.valid_name.name)\n\n if isinstance(self.parent, ProductNameDialog):\n self.parent.button_ok.setEnabled(True)\n\n else:\n self.valid_name_label.setText('---')\n\n if isinstance(self.parent, ProductNameDialog):\n self.parent.button_ok.setEnabled(False)\n\nclass ProductNameDialog(QtGui.QDialog):\n def __init__(self, parent=None):\n QtGui.QDialog.__init__(self, parent)\n self.button_ok = QtGui.QPushButton('Ok', self)\n self.button_ok.clicked.connect(self.accept)\n self.button_cancel = QtGui.QPushButton('Cancel', self)\n self.button_cancel.clicked.connect(self.reject)\n self.productname_widget = ProductNameWidget(self)\n self.valid_name = self.productname_widget.valid_name\n layout = QtGui.QGridLayout(self)\n layout.addWidget(self.productname_widget, 0, 0)\n layout.addWidget(self.button_ok, 1, 0)\n layout.addWidget(self.button_cancel, 2, 0)\n\n\n\n# def show_widget():\n# \"\"\"\n# Example using the dialog\n# \"\"\"\n\n# example_dialog = ProductNameDialog()\n# example_dialog.exec_()\n\n# print '\\n\\nclass:\\n', example_dialog.valid_name\n\n\n# def print_valid_name(validname):\n# print '\\n===>', validname\n\n# def main():\n# \"\"\"\n# example showing the widget.\n# \"\"\"\n# app = QtGui.QApplication([])\n# mainwindow = QtGui.QWidget()\n# mainwindow.show()\n# layout = QtGui.QVBoxLayout()\n# vnw = ProductNameWidget()\n# btn_d = QtGui.QPushButton('show dialog')\n# btn_print = QtGui.QPushButton('print valid name')\n# btn_d.clicked.connect(show_widget)\n# btn_print.clicked.connect(lambda: print_valid_name(validname=vnw.valid_name))\n# mainwindow.setLayout(layout)\n# layout.addWidget(vnw)\n# layout.addWidget(btn_d)\n# layout.addWidget(btn_print)\n# sys.exit(app.exec_())\n\n\n# if __name__ == '__main__':\n# main()\n","sub_path":"gui/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":4448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"621263142","text":"\"\"\"\nWritten by Dr. Elishai Ezra Tsur \n@ The Neuro-Biomorphic Engineering Lab (NBEL-lab.com)\n@ The Open University of Israel\n@ 25.8.2020\n\nThis work is based on ABR's adaptive controller availible at: \nhttps://github.com/abr/abr_control/tree/master/abr_control \nUsing this code is subjected to ABR's licensing\n\nAdaptive control theory is based on:\nDeWolf, Travis, Terrence C. Stewart, Jean-Jacques Slotine, and Chris Eliasmith. \n\"A spiking neural model of adaptive arm control.\" \nProceedings of the Royal Society B: Biological Sciences 283, no. 1843 (2016): 20162134.\n\nPhysical simulation is based the MuJoCo simulator (http://www.mujoco.org)\nUsing the simulator is subject to acquiring a license for MuJoCo (https://www.roboti.us/license.html)\n\nAdaptive control is implemented with the nengo framework (nengo.ai)\n\nOperational space controller is based on:\nKhatib, Oussama. \n\"A unified approach for motion and force control of robot manipulators: The operational space formulation.\" \nIEEE Journal on Robotics and Automation 3.1 (1987): 43-53. \n\"\"\"\n\nimport mujoco_py as mjc\nimport numpy as np\nimport glfw\nimport time\nfrom datetime import datetime\nimport logging\n\nfrom OSC import OSC\nfrom utilities import euler_from_quaternion\nfrom adaptive_control import DynamicsAdaptation \n\nclass Controller:\n \n def __init__(self, model):\n \n # Intializing Operational Space Controller (OSC) \n self.controller = OSC(model)\n \n def generate(self, position, velocity, target):\n return self.controller.generate(position, velocity, target)\n \n \nclass Simulation:\n \n def __init__(self, base_dir, # Directory. Used to initiate a logger\n model, # Instance of the mechanical model of the arm \n controller,\n init_angles = None, # Initial configuration of the arm null position.\n target = None, # Array of target coordinates in reference to the EE position\n return_to_null = False, # Return to home position before a approaching a new target\n th = 2e-2, # Treshold for successful approach to target\n sim_dt = 0.01, # Simulation time step\n external_force = None, # External force field (implemented with scaled gravity)\n adapt = False, # Using adaptive controller\n n_gripper_joints = 0, # Number of actuated gripping points \n ): \n\n self.model = model\n self.target = target\n self.return_to_null = return_to_null\n self.th = th\n self.dt = sim_dt\n self.external_force_field = external_force\n self.n_gripper_joints = n_gripper_joints\n self.controller = controller\n \n if init_angles is None:\n self.init_angles = model.ref_angles\n \n #Initialize a logger (debug, info, warning, error, critical)\n self.logger = logging.getLogger(__name__) \n self.logger.setLevel(logging.DEBUG)\n log_name = datetime.now().strftime(\"%b-%d-%Y-%H-%M-%S\")\n file_handler = logging.FileHandler(base_dir +'log/{}.log'.format(log_name))\n formatter = logging.Formatter('%(asctime)s : %(levelname)s : %(message)s')\n file_handler.setFormatter(formatter)\n self.logger.addHandler(file_handler)\n self.logger.info('Logger initialized')\n \n # Initiating the monitor dictionary\n if target is not None:\n self.monitor_dict = {}\n for i, t in enumerate(target):\n self.monitor_dict[i] = {'error': [], # Delta between current to target location\n 'ee': [], # Position of the end-effector\n 'q': [], # Joint angles\n 'dq': [], # Joint velocity\n 'steps' : 0, # number of steps to mitigate the target\n 'target': t, # Target coordinates (referenced to the arm null position)\n 'target_real': 0} # Target coordinates (referenced to the world)\n self.logger.info('Target {}: {}'.format(i, t))\n \n # Get number of joints\n self.n_joints = int(len(\n self.model.simulation.data.get_body_jacp('EE')) / 3) # Jacobian translational component (jacp)\n self.logger.info('Number of joints: {}'.format(self.n_joints))\n \n # Initiating pose\n self.model.goto_null_position()\n self.null_position = self.model.get_ee_position()\n self.logger.info('Null position: {}'.format(self.null_position))\n \n # Initialize adaptive controller\n self.adaptation = adapt\n if adapt: \n self.adapt_controller = DynamicsAdaptation(\n n_input = 10, # Applying adaptation to the first 5 joints, having 5 angles and 5 velocities\n n_output = 5, # Retrieving 5 adaptive signals for the first 5 joints\n n_neurons = 5000, # Number of neurons for neurons per ensemble\n n_ensembles = 5, # Defining an ensemble for each retrived adaptive signals \n pes_learning_rate = 1e-4, # Learning rate for the PES online learning rule\n means = [ # Scaling the input signals with means / variances of expected values. \n 0.12, 2.14, 1.87, 4.32, 0.59, \n 0.12, -0.38, -0.42, -0.29, 0.36],\n variances = [\n 0.08, 0.6, 0.7, 0.3, 0.6, \n 0.08, 1.4, 1.6, 0.7, 1.2]\n )\n self.logger.info('Adaptive controller initialized')\n \n def visualize(self):\n \"\"\" visualizing the model with the initial configuration of the arm \"\"\"\n \n self.model.visualize()\n \n def simulate(self, \n steps = None): # Number of maximum allowable steps for mitigating the target\n \"\"\" Simulating the model \"\"\"\n \n if self.target is None:\n print('A target eas not defined. Try to visualize instead.')\n return\n \n # Signifying termination of the simulation \n breaked = False\n \n # Iterate over the predefined targets ---------------------------------------------------\n for exp in self.monitor_dict:\n \n self.logger.info('Moving to target {} at: {}'.format(exp, self.monitor_dict[exp]['target']))\n \n # Terminate the simulation if it was signaled to using the ESC key\n if breaked:\n break\n \n # Retrieving the position of the target in world's coordinates\n target = self.null_position + self.monitor_dict[exp]['target']\n self.monitor_dict[exp]['target_real'] = np.copy(target[:3])\n self.logger.info('Target position in world coordinates: {}'.format(exp, self.monitor_dict[exp]['target_real']))\n \n # Setting the location of target (sphere; defined in the XML model) in the simulation\n self.model.simulation.data.set_mocap_pos(\"target\", target)\n\n # Keeping track of the simulation's number of steps\n step = 0 \n \n # Initializing error\n error = float(\"inf\")\n\n while True: # Execute simulation -----------------------------------------------------\n\n # Breaking conditions ------------------------------------------------------------\n \n # Keeping track of the steps and moving to the next target if exceeding limit\n step += 1 \n if steps is not None:\n if step > steps:\n self.monitor_dict[exp]['steps'] = step\n self.logger.critical(\n 'Simulation terminated by maxed number of steps (@ {}); Moving to next target'.format(step))\n break\n\n # Terminate simulation with ESC key\n if self.model.viewer.exit:\n breaked = True\n self.logger.warning('Simulation manually terminated @ step {}'.format(step))\n break\n \n # Terminate, or move to the next target when the EE is within \n # the threshold value of the target\n if error < 1e-2:\n self.monitor_dict[exp]['steps'] = step\n if self.return_to_null:\n self.goto_null_position()\n self.logger.info(\n 'Destination reached @ step {} with error {}; Moving to next target'.format(step, error))\n break \n\n # Calculating control signals ----------------------------------------------------\n \n # Force array which will be sent to the arm\n u = np.zeros(self.model.n_joints)\n \n # Retrieve the joint angle values and velocities\n position, velocity = (self.model.get_angles(), self.model.get_velocity())\n\n # Request the OSC to generate control signals to actuate the arm\n u = self.controller.generate(position, velocity, target)\n\n # Converting the retrieved dictionary to force arrays to be send to the arm\n # Only the first 5 actuators are activated. \n # The six'th actuator controls EE orientation.\n position_array = [np.copy(position[i]) for i in range(5)]\n velocity_array = [np.copy(velocity[i]) for i in range(5)]\n \n # If adaptation mode is on, that retireve the adapt signals\n if self.adaptation:\n u_adapt = np.zeros(self.model.n_joints)\n # Retrieveing the adapt signals from the adaptive controller\n u_adapt[:5] = self.adapt_controller.generate(\n # 10 inputs constituting the arm's joints' angles and velocities\n input_signal = np.hstack((position_array, velocity_array)),\n # Training signal for the controller. \n # Training signal is the actuation values retrieved before, \n # without the gravitational force field. \n training_signal = np.array(self.controller.controller.training_signal[:5]),\n )\n # Update the control signal with adaptation\n u += u_adapt\n \n # Adding an external force field to the arm, if such was defined\n if self.external_force_field is not None:\n extra_gravity = self.model.get_gravity_bias() * self.external_force_field\n u += extra_gravity\n\n # Accounting for the not-moving grippers (to adapt dimensions)\n u = np.hstack((u, np.zeros(self.n_gripper_joints)))\n\n # Actuating the arm, calculate error and update viewer ---------------------------\n self.model.send_forces(u) \n self.model.viewer.render()\n \n # retrieve the position of the arm follow actuation\n ee_position = self.model.get_ee_position()\n \n # Calculate error as the distance between the target and the position of the EE\n error = np.sqrt(np.sum((np.array(target[:3]) - np.array(ee_position))** 2))\n \n # Monitoring --------------------------------------------------------------------\n\n self.monitor_dict[exp]['error']. append(np.copy(error)) # Error step\n self.monitor_dict[exp]['ee']. append(np.copy(ee_position)) # Position of the EE\n self.monitor_dict[exp]['q']. append(np.copy(position)) # Joints' angles\n self.monitor_dict[exp]['dq']. append(np.copy(velocity)) # Joints' velocities\n \n \n # End of simulation ----------------------------------------------------------------------\n time.sleep(1.5)\n glfw.destroy_window(self.model.viewer.window)\n \n \n # Monitoring methods -------------------------------------------------------------------------\n \n def show_monitor(self):\n \"\"\" Display monitored motion and performance of the arm\"\"\"\n \n import matplotlib.pyplot as plt\n from mpl_toolkits.mplot3d import axes3d\n\n # For each specified target \n for exp in self.monitor_dict:\n\n # Plot EE convergence to target -------------------------------------------------------\n print('Covering a distance of {}, with an error of: {}, in {} steps '.format(\n np.sqrt(np.sum((self.monitor_dict[exp]['target_real'] - \n self.monitor_dict[exp]['ee'][0])**2)), \n self.monitor_dict[exp]['error'][-1], \n self.monitor_dict[exp]['steps']))\n plt.figure()\n plt.ylabel(\"Distance (m)\")\n plt.xlabel(\"Time (ms)\")\n plt.title(\"Distance to target\")\n plt.plot(self.monitor_dict[exp]['error'])\n plt.show()\n \n # Plot EE trajectory ------------------------------------------------------------------\n\n ax = plt.figure().add_subplot(111, projection='3d')\n ee_x = [ee[0] for ee in self.monitor_dict[exp]['ee']]\n ee_y = [ee[1] for ee in self.monitor_dict[exp]['ee']]\n ee_z = [ee[2] for ee in self.monitor_dict[exp]['ee']]\n\n ax.set_title(\"End-Effector Trajectory\")\n ax.plot(ee_x, ee_y, ee_z)\n\n ax.scatter(self.monitor_dict[exp]['target_real'][0], self.monitor_dict[exp]['target_real'][1], \n self.monitor_dict[exp]['target_real'][2], label=\"target\", c=\"r\")\n ax.legend() \n","sub_path":"ALYN/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":14513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"636865656","text":"import json\nfrom slackclient import SlackClient\n\nwith open(\"settings.json\") as settings_file:\n settings = json.loads(settings_file.read())\n\nBOT_ID = settings[\"bot_id\"]\nAPI_KEY = settings[\"api\"]\nGENERAL_CHANNEL = settings[\"general_channel\"]\nUSER_CHANNELS = settings[\"user_channels\"]\nADMIN_CHANNELS = settings[\"admin_channels\"]\n\n\nslack_client = SlackClient(API_KEY)\n\nif __name__ == \"__main__\":\n if input(\"Clear all bot messages from channels? \") == \"y\":\n print(\"Deleting user channel messages.\")\n for USER_CHANNEL in USER_CHANNELS:\n history = slack_client.api_call(\"channels.history\", channel=USER_CHANNEL)\n for item in history[\"messages\"]:\n if item[\"type\"] == \"message\":\n if (\"username\" in item and item[\"username\"] == \"bot\")\\\n or (\"user\" in item and item[\"user\"] == BOT_ID):\n slack_client.api_call(\"chat.delete\", channel=USER_CHANNEL, ts=item[\"ts\"])\n print(\"Deleting admin channel messages.\")\n for ADMIN_CHANNEL in ADMIN_CHANNELS:\n history = slack_client.api_call(\"channels.history\", channel=ADMIN_CHANNEL)\n for item in history[\"messages\"]:\n if item[\"type\"] == \"message\":\n if (\"username\" in item and item[\"username\"] == \"bot\")\\\n or (\"user\" in item and item[\"user\"] == BOT_ID):\n slack_client.api_call(\"chat.delete\", channel=ADMIN_CHANNEL, ts=item[\"ts\"])\n print(\"Deleting general channel messages.\")\n history = slack_client.api_call(\"channels.history\", channel=GENERAL_CHANNEL)\n for item in history[\"messages\"]:\n if item[\"type\"] == \"message\":\n if (\"username\" in item and item[\"username\"] == \"bot\") or (\"user\" in item and item[\"user\"] == BOT_ID):\n slack_client.api_call(\"chat.delete\", channel=GENERAL_CHANNEL, ts=item[\"ts\"])\n else:\n print(\"Aborting.\")\n","sub_path":"clear_channel.py","file_name":"clear_channel.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"316372113","text":"import sys\nimport torch\nfrom args import get_argparser, parse_args, get_aligner, get_bbox \n\nif __name__ == '__main__':\n parser = get_argparser()\n parser.add_argument('--render_match', \n help='render source with all single pairwise transforms before weighting',\n action='store_true')\n parser.add_argument('--forward_match', \n help='generate matches for all pairs for z to z-i',\n action='store_true')\n parser.add_argument('--reverse_match', \n help='generate matches for all pairs for z to z+i',\n action='store_true')\n parser.add_argument('--batch_size', type=int, default=10,\n help='if distributed, no. of sections to run simultaneously before proceeding')\n args = parse_args(parser) \n a = get_aligner(args)\n bbox = get_bbox(args)\n\n z_range = range(args.bbox_start[2], args.bbox_stop[2])\n # multi_match(a, bbox, z_range) \n a.generate_pairwise(z_range, bbox, forward_match=args.forward_match, \n reverse_match=args.reverse_match, \n render_match=args.render_match, batch_size=args.batch_size)\n\n","sub_path":"inference/_archive/multi_match.py","file_name":"multi_match.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"324842689","text":"# -*- coding:utf-8 -*-\n\nimport turtle #invoca al modulo para generar graficos (instalar)\n\ndef main(): #en principal\n window = turtle.Screen() #genera una ventana\n shelly = turtle.Turtle() #crea una instancia de tortuga\n\n make_square(shelly) #dibuja cuadrado con parametro shelly\n turtle.mainloop()\n\ndef make_square(shelly): #ingresar caracteristicas del cuadrado\n length = int(input('Tamaño de cuadrado: ')) #acepta un largo variable\n\n for i in range(4): # 4 veces la sgte instruccion \n make_line_and_turn(shelly, length)\n\ndef make_line_and_turn(shelly, length): #crea la linea con angulo de giro\n shelly.forward(length)\n shelly.left(90)\n\nif __name__ == '__main__': #define donde comienzan los programas, si a este archivo le llamamos main\n main()","sub_path":"w0/ex_turtle.py","file_name":"ex_turtle.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"9075293","text":"from flask import Flask\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom sqlalchemy import Column, Integer, Text, MetaData, Table, DateTime, Boolean\r\nfrom webapp import config\r\n\r\ndb = SQLAlchemy()\r\n\r\n\r\nclass Group(db.Model):\r\n #__tablename__ = 'groups'\r\n\r\n url = db.Column(db.String, unique=True, nullable=False)\r\n group_id = db.Column(db.Integer, primary_key=True)\r\n domain = db.Column(db.String, unique=True, nullable=False)\r\n group_name = db.Column(db.String, nullable=False)\r\n posts = db.relationship('Post', backref='group')\r\n\r\n def __repr__(self):\r\n return '<Группа {} {}>'.format(self.group_name, self.domain)\r\n\r\n\r\nclass Post(db.Model):\r\n #__tablename__ = 'posts'\r\n\r\n group_id = db.Column(db.Integer, db.ForeignKey('group.group_id'))\r\n post_id = db.Column(db.Integer, primary_key=True)\r\n date = db.Column(db.DateTime, nullable=False)\r\n text = db.Column(db.String, nullable=True)\r\n likes = db.Column(db.Integer, nullable=False)\r\n comments = db.relationship('Comment', backref='post')\r\n\r\n def __repr__(self):\r\n return '<Пост {} {}>'.format(self.post_id, self.text)\r\n\r\n\r\nclass Comment(db.Model):\r\n #__tablename__ = 'comments'\r\n group_id = db.Column(db.Integer, primary_key=True)\r\n post_id = db.Column(db.Integer, db.ForeignKey('post.post_id'))\r\n owner_id = db.Column(db.Integer, primary_key=True)\r\n date = db.Column(db.DateTime, nullable=False)\r\n comment_text = db.Column(db.String, nullable=False)\r\n likes = db.Column(db.Integer, nullable=False)\r\n sentiment = db.Column(db.Boolean, nullable=True)\r\n\r\n def __repr__(self):\r\n return '<Комментарий {} {}>'.format(self.owner_id, self.comment_text)","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"647859997","text":"class Solution:\n def trapRainWater(self, heightMap: List[List[int]]) -> int:\n \"\"\"\n Time Complexity: O(n*log(n))\n Space Complexity: O(n)\n \"\"\"\n def neighbours(i, j):\n for di, dj in [(-1, 0), (0, -1), (0, 1), (1, 0)]:\n if (i + di, j + dj) in visited:\n continue\n if not (0 <= i + di < m):\n continue\n if not (0 <= j + dj < n):\n continue\n yield (i + di, j + dj)\n\n res = 0\n curr_max = 0\n heap = set()\n visited = set()\n m, n = len(heightMap), len(heightMap[0])\n for i in range(m):\n heap.add((heightMap[i][0], i, 0))\n visited.add((i, 0))\n heap.add((heightMap[i][n - 1], i, n - 1))\n visited.add((i, n - 1))\n\n for j in range(n):\n heap.add((heightMap[0][j], 0, j))\n visited.add((0, j))\n heap.add((heightMap[m - 1][j], m - 1, j))\n visited.add((m - 1, j))\n\n heap = list(heap)\n heapq.heapify(heap)\n while heap:\n val, i, j = heapq.heappop(heap)\n curr_max = max(curr_max, val)\n for i_n, j_n in neighbours(i, j):\n val_n = heightMap[i_n][j_n]\n if val_n < curr_max:\n res += curr_max - val_n\n heapq.heappush(heap, (val_n, i_n, j_n))\n visited.add((i_n, j_n))\n\n return res\n\n\n","sub_path":"LeetCodeLearn/matrix/407.py","file_name":"407.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"290261457","text":"import tensorflow as tf\nimport time\nimport numpy as np\nimport os\nimport copy\nimport pickle\nimport argparse\nimport utility\nimport pandas as pd\nfrom tqdm import tqdm\nfrom sklearn.metrics import *\n\ndef get_correlation_loss(y_true, y_pred):\n x = y_true\n y = y_pred\n mx = tf.keras.backend.mean(x)\n my = tf.keras.backend.mean(y)\n xm, ym = x-mx, y-my\n r_num = tf.keras.backend.sum(tf.multiply(xm,ym))\n r_den = tf.keras.backend.sqrt(tf.multiply(tf.keras.backend.sum(tf.keras.backend.square(xm)), tf.keras.backend.sum(tf.keras.backend.square(ym))))\n r = r_num / tf.where(tf.equal(r_den, 0), 1e-3, r_den)\n r = tf.keras.backend.abs(tf.keras.backend.maximum(tf.keras.backend.minimum(r, 1.0), -1.0))\n return tf.keras.backend.square(r)\n\nclass BPR_DRP_RSP_DEBIAS:\n \n def __init__(self, sess, args, train_df, vali_df, item_genre, genre_error_weight,\n key_genre, item_genre_list, user_genre_count, outputs_dir):\n self.dataname = args.dataname\n \n self.ckpt_save_path = os.path.join(outputs_dir, 'check_points')\n os.makedirs(self.ckpt_save_path, exist_ok=True)\n \n self.layers = eval(args.layers)\n \n self.reg_lambda = args.reg_lambda\n\n self.key_genre = key_genre\n self.item_genre_list = item_genre_list\n self.user_genre_count = user_genre_count\n\n self.sess = sess\n self.args = args\n\n self.num_cols = len(train_df['item_id'].unique())\n self.num_rows = len(train_df['user_id'].unique())\n \n self.hidden_neuron = args.hidden_neuron\n self.neg = args.neg\n self.batch_size = args.batch_size\n\n self.train_df = train_df\n self.vali_df = vali_df\n self.num_train = len(self.train_df)\n self.num_vali = len(self.vali_df)\n\n self.train_epoch = args.train_epoch\n self.train_epoch_a = args.train_epoch_a\n self.display_step = args.display_step\n\n self.lr_r = args.lr_r # learning rate\n self.lr_a = args.lr_a # learning rate\n\n self.reg = args.reg # regularization term trade-off\n self.reg_s = args.reg_s\n\n self.num_genre = args.num_genre\n self.alpha = args.alpha\n self.item_genre = item_genre\n self.genre_error_weight = genre_error_weight\n \n all_items_unique = list(np.unique(train_df['item_id'].values))\n self.item_popularity = np.array([len(train_df[train_df['item_id']==item_id].index) for item_id in all_items_unique])\n\n self.genre_count_list = []\n for k in range(self.num_genre):\n self.genre_count_list.append(np.sum(item_genre[:, k]))\n\n print('**********BPR - DPR_RSP_DEBIAS Popularity**********')\n print(self.args)\n self._prepare_model()\n \n def loadmodel(self, saver):\n print(\"loading model...\")\n ckpt = tf.train.get_checkpoint_state(self.ckpt_save_path)\n if ckpt and ckpt.model_checkpoint_path:\n ckpt_name = os.path.basename(ckpt.model_checkpoint_path)\n saver.restore(self.sess, os.path.join(checkpoint_dir, ckpt_name))\n print(\"successfully restored model from checkpoint...\")\n return True\n else:\n return False\n\n def run(self):\n init = tf.compat.v1.global_variables_initializer()\n self.sess.run(init)\n \n saver = tf.compat.v1.train.Saver([self.P, self.Q])\n self.loadmodel(saver)\n \n for epoch_itr in range(1, self.train_epoch + 1 + self.train_epoch_a):\n self.train_model(epoch_itr)\n if epoch_itr % self.display_step == 0:\n self.test_model(epoch_itr)\n return self.make_records()\n\n def _prepare_model(self):\n with tf.compat.v1.name_scope(\"input_data\"):\n self.user_input = tf.compat.v1.placeholder(tf.int32, shape=[None, 1], name=\"user_input\")\n self.item_input_pos = tf.compat.v1.placeholder(tf.int32, shape=[None, 1], name=\"item_input_pos\")\n self.item_input_neg = tf.compat.v1.placeholder(tf.int32, shape=[None, 1], name=\"item_input_neg\")\n \n self.input_item_genre = tf.compat.v1.placeholder(dtype=tf.float32, shape=[None, self.num_genre]\n , name=\"input_item_genre\")\n self.input_item_error_weight = tf.compat.v1.placeholder(dtype=tf.float32, shape=[None, 1]\n , name=\"input_item_error_weight\")\n \n self.input_popularity_corr = tf.compat.v1.placeholder(dtype=tf.float32, shape=[None, 1], \n name=\"input_item_popularity_corr\")\n\n with tf.compat.v1.variable_scope(\"BPR\", reuse=tf.compat.v1.AUTO_REUSE):\n self.P = tf.compat.v1.get_variable(name=\"P\", initializer=tf.random.truncated_normal(shape=[self.num_rows, self.hidden_neuron],\n mean=0, stddev=0.03), dtype=tf.float32, use_resource=False)\n self.Q = tf.compat.v1.get_variable(name=\"Q\", initializer=tf.random.truncated_normal(shape=[self.num_cols, self.hidden_neuron],\n mean=0, stddev=0.03), dtype=tf.float32, use_resource=False)\n \n para_r = tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, scope=\"BPR\")\n \n with tf.compat.v1.variable_scope(\"Adversarial\", reuse=tf.compat.v1.AUTO_REUSE):\n num_layer = len(self.layers)\n adv_W = []\n adv_b = []\n for l in range(num_layer):\n if l == 0:\n in_shape = 1\n else:\n in_shape = self.layers[l - 1]\n adv_W.append(tf.compat.v1.get_variable(name=\"adv_W\" + str(l),\n initializer=tf.random.truncated_normal(shape=[in_shape, self.layers[l]],\n mean=0, stddev=0.03), dtype=tf.float32))#, use_resource=False))\n adv_b.append(tf.compat.v1.get_variable(name=\"adv_b\" + str(l),\n initializer=tf.random.truncated_normal(shape=[1, self.layers[l]],\n mean=0, stddev=0.03), dtype=tf.float32))#, use_resource=False))\n adv_W_out = tf.compat.v1.get_variable(name=\"adv_W_out\",\n initializer=tf.random.truncated_normal(shape=[self.layers[-1], self.num_genre],\n mean=0, stddev=0.03), dtype=tf.float32)#, use_resource=False)\n\n adv_b_out = tf.compat.v1.get_variable(name=\"adv_b_out\",\n initializer=tf.random.truncated_normal(shape=[1, self.num_genre],\n mean=0, stddev=0.03), dtype=tf.float32)#, use_resource=False)\n para_a = tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, scope=\"Adversarial\")\n\n self.saver = tf.compat.v1.train.Saver([self.P, self.Q])\n\n p = tf.reduce_sum(input_tensor=tf.nn.embedding_lookup(params=self.P, ids=self.user_input), axis=1)\n q_neg = tf.reduce_sum(input_tensor=tf.nn.embedding_lookup(params=self.Q, ids=self.item_input_neg), axis=1)\n q_pos = tf.reduce_sum(input_tensor=tf.nn.embedding_lookup(params=self.Q, ids=self.item_input_pos), axis=1)\n\n predict_pos = (tf.reduce_sum(input_tensor=p * q_pos, axis=1))\n predict_neg = (tf.reduce_sum(input_tensor=p * q_neg, axis=1))\n\n r_cost1 = tf.reduce_sum(input_tensor=tf.nn.softplus(-(predict_pos - predict_neg)))\n r_cost2 = self.reg * 0.5 * (self.l2_norm(self.P) + self.l2_norm(self.Q)) # regularization term\n \n pred = tf.matmul(self.P, tf.transpose(a=self.Q))\n self.s_mean = tf.reduce_mean(input_tensor=pred, axis=1)\n self.s_std = tf.keras.backend.std(pred, axis=1)\n self.s_cost = tf.reduce_sum(input_tensor=tf.square(self.s_mean) + tf.square(self.s_std) - 2 * tf.math.log(self.s_std) - 1)\n self.r_cost = r_cost1 + r_cost2 + self.reg_s * 0.5 * self.s_cost\n\n adv_last = tf.reshape(tf.concat([predict_pos, predict_neg], axis=0), [tf.shape(input=self.input_item_genre)[0], 1])\n for l in range(num_layer):\n adv = tf.nn.relu(tf.matmul(adv_last, adv_W[l]) + adv_b[l])\n adv_last = adv\n self.adv_output = tf.nn.sigmoid(tf.matmul(adv_last, adv_W_out) + adv_b_out)\n self.a_cost = tf.reduce_sum(input_tensor=tf.square(self.adv_output - self.input_item_genre) * self.input_item_error_weight)\n \n r_pop_corr_cost = get_correlation_loss((predict_pos - predict_neg), self.input_popularity_corr)\n\n all_cost = self.r_cost - self.alpha * self.a_cost # the *un-regulerized* loss function\n \n self.all_cost_reg = (1 - self.reg_lambda) * all_cost + self.reg_lambda * r_pop_corr_cost #the regularized loss function\n\n with tf.compat.v1.variable_scope(\"Optimizer\", reuse=tf.compat.v1.AUTO_REUSE):\n self.r_optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=self.lr_r).minimize(self.r_cost, var_list=para_r)\n self.a_optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=self.lr_a).minimize(self.a_cost, var_list=para_a)\n self.all_optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=self.lr_r).minimize(self.all_cost_reg, var_list=para_r)\n\n def train_model(self, itr):\n NS_start_time = time.time() * 1000.0\n epoch_r_cost = 0.0\n epoch_s_cost = 0.0\n epoch_s_mean = 0.0\n epoch_s_std = 0.0\n epoch_a_cost = 0.0\n \n num_sample, user_list, item_pos_list, item_neg_list, item_poplarity_corr_lst = \\\n utility.negative_sample(self.train_df, self.num_rows,\n self.num_cols, self.neg,\n item_popularity=self.item_popularity)\n NS_end_time = time.time() * 1000.0\n\n start_time = time.time() * 1000.0\n num_batch = int(num_sample / float(self.batch_size)) + 1\n random_idx = np.random.permutation(num_sample)\n for i in tqdm(range(num_batch)):\n\n # get the indices of the current batch\n if i == num_batch - 1:\n batch_idx = random_idx[i * self.batch_size:]\n elif i < num_batch - 1:\n batch_idx = random_idx[(i * self.batch_size):((i + 1) * self.batch_size)]\n \n if itr > self.train_epoch:\n random_idx_a = np.random.permutation(num_sample)\n for j in range(num_batch):\n if j == num_batch - 1:\n batch_idx_a = random_idx_a[j * self.batch_size:]\n elif j < num_batch - 1:\n batch_idx_a = random_idx_a[(j * self.batch_size):((j + 1) * self.batch_size)]\n item_idx_list = ((item_pos_list[batch_idx_a, :]).reshape((len(batch_idx_a)))).tolist() \\\n + ((item_neg_list[batch_idx_a, :]).reshape((len(batch_idx_a)))).tolist()\n _, tmp_a_cost = self.sess.run( # do the optimization by the minibatch\n [self.a_optimizer, self.a_cost],\n feed_dict={self.user_input: user_list[batch_idx_a, :],\n self.item_input_pos: item_pos_list[batch_idx_a, :],\n self.item_input_neg: item_neg_list[batch_idx_a, :],\n self.input_item_genre: self.item_genre[item_idx_list, :],\n self.input_item_error_weight: self.genre_error_weight[item_idx_list, :],\n self.input_popularity_corr: item_poplarity_corr_lst[item_idx_list, :]})\n epoch_a_cost += tmp_a_cost\n \n item_idx_list = ((item_pos_list[batch_idx, :]).reshape((len(batch_idx)))).tolist() \\\n + ((item_neg_list[batch_idx, :]).reshape((len(batch_idx)))).tolist()\n _, tmp_r_cost, tmp_s_cost, tmp_s_mean, tmp_s_std = self.sess.run( # do the optimization by the minibatch\n [self.all_optimizer, self.all_cost_reg, self.s_cost, self.s_mean, self.s_std],\n feed_dict={self.user_input: user_list[batch_idx, :],\n self.item_input_pos: item_pos_list[batch_idx, :],\n self.item_input_neg: item_neg_list[batch_idx, :],\n self.input_item_genre: self.item_genre[item_idx_list, :],\n self.input_item_error_weight: self.genre_error_weight[item_idx_list, :],\n self.input_popularity_corr: item_poplarity_corr_lst[item_idx_list, :]})\n epoch_r_cost += tmp_r_cost\n epoch_s_mean += np.mean(tmp_s_mean)\n epoch_s_std += np.mean(tmp_s_std)\n epoch_s_cost += tmp_s_cost\n else:\n item_idx_list = ((item_pos_list[batch_idx, :]).reshape((len(batch_idx)))).tolist() \\\n + ((item_neg_list[batch_idx, :]).reshape((len(batch_idx)))).tolist()\n _, tmp_r_cost, tmp_s_cost, tmp_s_mean, tmp_s_std= self.sess.run( # do the optimization by the minibatch\n [self.r_optimizer, self.r_cost, self.s_cost, self.s_mean, self.s_std],\n feed_dict={self.user_input: user_list[batch_idx, :],\n self.item_input_pos: item_pos_list[batch_idx, :],\n self.item_input_neg: item_neg_list[batch_idx, :],\n self.input_item_genre: self.item_genre[item_idx_list, :],\n self.input_item_error_weight: self.genre_error_weight[item_idx_list, :],\n self.input_popularity_corr: item_poplarity_corr_lst[item_idx_list, :]})\n epoch_r_cost += tmp_r_cost\n epoch_s_mean += np.mean(tmp_s_mean)\n epoch_s_std += np.mean(tmp_s_std)\n epoch_s_cost += tmp_s_cost\n epoch_a_cost /= num_batch\n if itr % self.display_step == 0:\n print (\"Training //\", \"Epoch %d //\" % itr, \" Total r_cost = %.5f\" % epoch_r_cost,\n \" Total s_cost = %.5f\" % epoch_s_cost,\n \" Total s_mean = %.5f\" % epoch_s_mean,\n \" Total s_std = %.5f\" % epoch_s_std,\n \" Total a_cost = %.5f\" % epoch_a_cost,\n \"Training time : %d ms\" % (time.time() * 1000.0 - start_time),\n \"negative Sampling time : %d ms\" % (NS_end_time - NS_start_time),\n \"negative samples : %d\" % (num_sample))\n\n self.saver.save(sess, self.ckpt_save_path + \"/check_point.ckpt\", global_step=itr)\n\n def test_model(self, itr): # calculate the cost and rmse of testing set in each epoch\n if itr % self.display_step == 0:\n start_time = time.time() * 1000.0\n P, Q = self.sess.run([self.P, self.Q])\n Rec = np.matmul(P, Q.T)\n\n utility.test_model_all(Rec, self.vali_df, self.train_df)\n utility.ranking_analysis(Rec, self.vali_df, self.train_df, self.key_genre, self.item_genre_list,\n self.user_genre_count)\n\n print (\n \"Testing //\", \"Epoch %d //\" % itr,\n \"Testing time : %d ms\" % (time.time() * 1000.0 - start_time))\n print(\"=\" * 200)\n\n def make_records(self): # record all the results' details into files\n P, Q = self.sess.run([self.P, self.Q])\n Rec = np.matmul(P, Q.T)\n\n [precision, recall, f_score, NDCG] = utility.test_model_all(Rec, self.vali_df, self.train_df)\n return precision, recall, f_score, NDCG, Rec\n\n @staticmethod\n def l2_norm(tensor):\n return tf.reduce_sum(input_tensor=tf.square(tensor))\n\n\nparser = argparse.ArgumentParser(description='BPR-DPR-RSP-DEBIAS')\nparser.add_argument('--train_epoch', type=int, default=20)\nparser.add_argument('--train_epoch_a', type=int, default=20)\nparser.add_argument('--display_step', type=int, default=1)\nparser.add_argument('--lr_r', type=float, default=0.01)\nparser.add_argument('--lr_a', type=float, default=0.005)\nparser.add_argument('--reg', type=float, default=0.1)\nparser.add_argument('--reg_s', type=float, default=30)\nparser.add_argument('--hidden_neuron', type=int, default=20)\nparser.add_argument('--n', type=int, default=1)\nparser.add_argument('--neg', type=int, default=5)\nparser.add_argument('--alpha', type=float, default=5000.0)\nparser.add_argument('--reg_lambda', type=float, default=0.01)\nparser.add_argument('--batch_size', type=int, default=1024)\nparser.add_argument('--layers', nargs='?', default='[50, 50, 50, 50]')\nparser.add_argument('--dataname', nargs='?', default='ml1m-6')\nargs = parser.parse_args()\n\ndataname = args.dataname\n\ndatasets_base_dir = './datasets'\n\ntrain_df = pd.read_pickle(os.path.join(datasets_base_dir, dataname, 'training_df.pkl'))\nvali_df = pd.read_pickle(os.path.join(datasets_base_dir, dataname, 'valiing_df.pkl'))\nwith open(os.path.join(datasets_base_dir, dataname, 'key_genre.pkl'), 'rb') as key_genre_f:\n key_genre = pickle.load(key_genre_f)\nwith open(os.path.join(datasets_base_dir, dataname, 'item_idd_genre_list.pkl'), 'rb') as item_idd_genre_list_f:\n item_idd_genre_list = pickle.load(item_idd_genre_list_f)\nwith open(os.path.join(datasets_base_dir, dataname, 'genre_item_vector.pkl'), 'rb') as genre_item_vector_f:\n genre_item_vector = pickle.load(genre_item_vector_f, encoding=\"latin1\")\nwith open(os.path.join(datasets_base_dir, dataname, 'genre_count.pkl'), 'rb') as genre_count_f:\n genre_count = pickle.load(genre_count_f)\nwith open(os.path.join(datasets_base_dir, dataname, 'user_genre_count.pkl'), 'rb') as user_genre_count_f:\n user_genre_count = pickle.load(user_genre_count_f)\n\nnum_item = len(train_df['item_id'].unique())\nnum_user = len(train_df['user_id'].unique())\nnum_genre = len(key_genre)\n\nargs.num_genre = num_genre\n\nitem_genre_list = []\nfor u in range(num_item):\n gl = item_idd_genre_list[u]\n tmp = []\n for g in gl:\n if g in key_genre:\n tmp.append(g)\n item_genre_list.append(tmp)\n\nprint('!' * 100)\nprint('number of positive feedback: ' + str(len(train_df)))\nprint('estimated number of training samples: ' + str(args.neg * len(train_df)))\nprint('!' * 100)\n\noutputs_dir = os.path.join('.', 'outputs', 'BPR_DRP_RSP_DEBIAS', dataname)\nos.makedirs(outputs_dir, exist_ok=True)\n\noutputs_performance_dir = os.path.join(outputs_dir, 'performance')\nos.makedirs(outputs_performance_dir, exist_ok=True)\n\n# genreate item_genre matrix\nitem_genre = np.zeros((num_item, num_genre))\nfor i in range(num_item):\n gl = item_genre_list[i]\n for k in range(num_genre):\n if key_genre[k] in gl:\n item_genre[i, k] = 1.0\n\ngenre_count_mean_reciprocal = []\nfor k in key_genre:\n genre_count_mean_reciprocal.append(1.0 / genre_count[k])\ngenre_count_mean_reciprocal = (np.array(genre_count_mean_reciprocal)).reshape((num_genre, 1))\ngenre_error_weight = np.dot(item_genre, genre_count_mean_reciprocal)\n\nargs.num_genre = num_genre\n\nprecision = np.zeros(4)\nrecall = np.zeros(4)\nf1 = np.zeros(4)\nndcg = np.zeros(4)\nRSP = np.zeros(4)\nREO = np.zeros(4)\n\nn = args.n\nfor i in range(n):\n with tf.compat.v1.Session() as sess:\n bpr_drp_rsp_debias = BPR_DRP_RSP_DEBIAS(sess, args, train_df, vali_df, item_genre, genre_error_weight, \n key_genre, item_genre_list, user_genre_count, outputs_dir)\n [prec_one, rec_one, f_one, ndcg_one, Rec] = bpr_drp_rsp_debias.run()\n [RSP_one, REO_one] = utility.ranking_analysis(Rec, vali_df, train_df, key_genre, item_genre_list,\n user_genre_count)\n precision += prec_one\n recall += rec_one\n f1 += f_one\n ndcg += ndcg_one\n RSP += RSP_one\n REO += REO_one\n\nwith open(os.path.join(outputs_performance_dir, 'Recs.mat'), \"wb\") as f:\n np.save(f, Rec)\n\n\nprecision /= n\nrecall /= n\nf1 /= n\nndcg /= n\nRSP /= n\nREO /= n\n\nutility.plot_performance(precision, \"Precision\", outputs_performance_dir, dataset_name=dataname, algo_name=\"BPR_DRP_RSP_DEBIAS\")\nutility.plot_performance(recall, \"Recall\", outputs_performance_dir, dataset_name=dataname, algo_name=\"BPR_DRP_RSP_DEBIAS\")\nutility.plot_performance(f1, \"F1\", outputs_performance_dir, dataset_name=dataname, algo_name=\"BPR_DRP_RSP_DEBIAS\")\nutility.plot_performance(ndcg, \"NDCG\", outputs_performance_dir, dataset_name=dataname, algo_name=\"BPR_DRP_RSP_DEBIAS\")\nutility.plot_performance(RSP, \"RSP\", outputs_performance_dir, dataset_name=dataname, algo_name=\"BPR_DRP_RSP_DEBIAS\")\nutility.plot_performance(REO, \"REO\", outputs_performance_dir, dataset_name=dataname, algo_name=\"BPR_DRP_RSP_DEBIAS\")\n\nprint('')\nprint('*' * 100)\nprint('Averaged precision@1\\t%.7f,\\t||\\tprecision@5\\t%.7f,\\t||\\tprecision@10\\t%.7f,\\t||\\tprecision@15\\t%.7f' \\\n % (precision[0], precision[1], precision[2], precision[3]))\nprint('Averaged recall@1\\t%.7f,\\t||\\trecall@5\\t%.7f,\\t||\\trecall@10\\t%.7f,\\t||\\trecall@15\\t%.7f' \\\n % (recall[0], recall[1], recall[2], recall[3]))\nprint('Averaged f1@1\\t\\t%.7f,\\t||\\tf1@5\\t\\t%.7f,\\t||\\tf1@10\\t\\t%.7f,\\t||\\tf1@15\\t\\t%.7f' \\\n % (f1[0], f1[1], f1[2], f1[3]))\nprint('Averaged NDCG@1\\t\\t%.7f,\\t||\\tNDCG@5\\t\\t%.7f,\\t||\\tNDCG@10\\t\\t%.7f,\\t||\\tNDCG@15\\t\\t%.7f' \\\n % (ndcg[0], ndcg[1], ndcg[2], ndcg[3]))\nprint('*' * 100)\nprint('Averaged RSP @1\\t%.7f\\t||\\t@5\\t%.7f\\t||\\t@10\\t%.7f\\t||\\t@15\\t%.7f' \\\n % (RSP[0], RSP[1], RSP[2], RSP[3]))\nprint('Averaged REO @1\\t%.7f\\t||\\t@5\\t%.7f\\t||\\t@10\\t%.7f\\t||\\t@15\\t%.7f' \\\n % (REO[0], REO[1], REO[2], REO[3]))\nprint('*' * 100)\n","sub_path":"BPR-DPR_RSP-DEBIAS.py","file_name":"BPR-DPR_RSP-DEBIAS.py","file_ext":"py","file_size_in_byte":22053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"287230584","text":"import tkinter as tk\r\nfrom tkinter import messagebox\r\n\r\n\r\nclass Barcode(object):\r\n\r\n\r\n def __init__(self, master):\r\n self.master = master\r\n \r\n self.frametext = tk.Frame(master)\r\n self.frametext.pack(side=tk.TOP)\r\n \r\n '''Things in frame text'''\r\n self.namefile = tk.StringVar()\r\n self.angkainput = tk.StringVar()\r\n \r\n self.labelsave = tk.Label(self.frametext, text='Save barcode to PS file [eg: EAN13.eps]:', font=(\"Helvetica\", 14, \"bold\"))\r\n self.entryname = tk.Entry(self.frametext, textvariable=self.namefile)\r\n self.labelcode = tk.Label(self.frametext, text='Enter code (first 12 decimal digits):', font=(\"Helvetica\", 14, \"bold\"))\r\n self.entrycode = tk.Entry(self.frametext, textvariable=self.angkainput)\r\n\r\n self.labelsave.pack()\r\n self.entryname.pack()\r\n self.labelcode.pack()\r\n self.entrycode.pack()\r\n\r\n\r\nclass BarcodeImage(Barcode):\r\n\r\n\r\n def __init__(self, master):\r\n \r\n super().__init__(master)\r\n self.framebarcode = tk.Frame(master)\r\n self.framebarcode.pack(side=tk.BOTTOM, pady=5, padx=5)\r\n \r\n '''Things in frame barcode'''\r\n self.width = 450\r\n self.height = 450\r\n self.barcode = tk.Canvas(self.framebarcode, width=self.width, height=self.height, bg='white')\r\n self.barcode.pack(pady=5, padx=5)\r\n\r\n '''Binds entries'''\r\n self.entrycode.bind('', self.draw)\r\n self.entryname.bind('', self.savefile)\r\n\r\n\r\n def check_digit(self, number):\r\n digitsplit = [x for x in number]\r\n\r\n '''Counts the last digit'''\r\n ganjil = []\r\n genap = []\r\n\r\n for x in range (0, len(digitsplit), 2):\r\n genap.append(digitsplit[x])\r\n\r\n for y in range (1, len(digitsplit)+1, 2):\r\n ganjil.append(digitsplit[y])\r\n \r\n hasil = 0\r\n for n in range(6):\r\n hasil += int(genap[n])+(3*(int(ganjil[n])))\r\n \r\n if hasil%10 == 0:\r\n angkaterakhir = 0\r\n else:\r\n angkaterakhir = 10-(hasil%10)\r\n \r\n self.angka = number + str(angkaterakhir) #Returns the original 12 number with the checksum\r\n return self.angka\r\n \r\n \r\n def savefile(self, event):\r\n namafile = self.namefile.get()\r\n namafile += '.eps'\r\n\r\n '''Forbidden name and characters for a filename in windows''' \r\n if namafile in ['CON', 'PRN', 'AUX', 'NUL', 'COM1', 'COM2', 'COM3', \r\n 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9', 'COM0', \r\n 'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', \r\n 'LPT8', 'LPT9', 'LPT0']:\r\n messagebox.showerror(\"Error : Filename\", 'Forbidden file name')\r\n\r\n for n in namafile:\r\n if n in ['/', '\\\\', '?', '%', '*', ':', '|', '\\\"', \"\\'\", '<', '>', ' ', ]:\r\n messagebox.showerror(\"Error : Filename\", r'Filename characters should not include \\ / ? % * : | \" < >')\r\n\r\n '''Prompt the user whether to replace the file or change the filename'''\r\n try:\r\n f = open(namafile)\r\n f.close()\r\n MsgBox = tk.messagebox.askquestion ('File Already Exist','{} already exists.\\nDo you want to replace it?'.format(namafile), icon = 'warning')\r\n if MsgBox == 'yes':\r\n self.barcode.update()\r\n self.barcode.postscript(file=namafile, height=450, width=450, colormode=\"color\")\r\n except IOError:\r\n self.barcode.update()\r\n self.barcode.postscript(file=namafile, height=450, width=450, colormode=\"color\")\r\n\r\n del namafile\r\n\r\n \r\n def draw(self, event):\r\n self.barcode.delete('all')\r\n digit12 = self.angkainput.get()\r\n \r\n '''Error handling'''\r\n try:\r\n temp = int(digit12)\r\n except ValueError:\r\n messagebox.showerror(\"Error : Number Input\", \"Wrong Input.\\nYou need to input 12 numbers\")\r\n del digit12\r\n return None\r\n\r\n if len(digit12) != 12:\r\n messagebox.showerror(\"Error : Number Input\", \"Wrong Input.\\nYou need to input 12 numbers\")\r\n del digit12\r\n return None\r\n\r\n self.angka = self.check_digit(digit12)\r\n \r\n '''Starts Drawing'''\r\n #Formula for barcode\r\n structure = {0:'LLLLLL', 1:'LLGLGG', 2:'LLGGLG', 3:'LLGGGL', 4:'LGLLGG', 5:'LGGLLG', \r\n 6:'LGGGLL', 7:'LGLGLG', 8:'LGLGGL', 9:'LGGLGL'}\r\n code = {0:['0001101', '0100111', '1110010'], 5:['0110001','0111001','1001110'],\r\n 1:['0011001', '0110011', '1100110'], 6:['0101111','0000101','1010000'], \r\n 2:['0010011','0011011','1101100'], 7:['0111011','0010001','1000100'],\r\n 3:['0111101','0100001','1000010'], 8:['0110111','0001001','1001000'],\r\n 4:['0100011','0011101','1011100'], 9:['0001011','0010111','1110100']}\r\n \r\n normalizerx = int((self.width/2)-((47.5)*2.75)) #Make the barcode centered\r\n normalizery = int((self.width/2)-(150/2)) #Make the barcode centered\r\n \r\n self.barcode.create_text(normalizerx+150, normalizery-50, text=\"EAN-13 Barcode:\", font=(\"Helvetica\", 16, \"bold\"))\r\n self.barcode.create_text(normalizerx-12, normalizery+140, text=self.angka[0], font=(\"Helvetica\", 16, \"bold\"))\r\n self.barcode.create_text(normalizerx+150, normalizery+175, text=\"Check Digit: {}\".format(self.angka[-1]),\r\n font=(\"Helvetica\", 16, \"bold\"), fill=\"orange\")\r\n #start marker\r\n for n in '101':\r\n if n == '1':\r\n self.barcode.create_rectangle(normalizerx, normalizery, normalizerx+2,\r\n normalizery+150, fill=\"black\", outline='black')\r\n normalizerx += 3\r\n normalizerx += 3\r\n\r\n #digit 1-7\r\n for x in range(6):\r\n self.barcode.create_text(normalizerx+10, normalizery+140, \r\n text=self.angka[x+1], font=(\"Helvetica\", 16, \"bold\"))\r\n \r\n rumus = structure[int(self.angka[0])][x]\r\n if rumus == 'L':\r\n for n in code[int(self.angka[x+1])][0]:\r\n if n == '1':\r\n self.barcode.create_rectangle(normalizerx, normalizery,\r\n normalizerx+2, normalizery+125, fill=\"black\", outline='black') \r\n normalizerx += 3\r\n\r\n elif rumus == 'G':\r\n for n in code[int(self.angka[x+1])][1]:\r\n if n == '1':\r\n self.barcode.create_rectangle(normalizerx, normalizery, \r\n normalizerx+2, normalizery+125, fill=\"black\", outline='black') \r\n normalizerx += 3\r\n \r\n \r\n \r\n #center marker\r\n for n in '01010':\r\n if n == '1':\r\n self.barcode.create_rectangle(normalizerx, normalizery, normalizerx+2,\r\n normalizery+150, fill=\"black\", outline='black') \r\n normalizerx += 3\r\n\r\n #digit 7-13\r\n for x in range(7,13):\r\n self.barcode.create_text(normalizerx+10, normalizery+140, text=self.angka[x],\r\n font=(\"Helvetica\", 16, \"bold\"))\r\n for n in code[int(self.angka[x])][2]:\r\n if n == '1':\r\n self.barcode.create_rectangle(normalizerx, normalizery, normalizerx+2,\r\n normalizery+125, fill=\"black\", outline='black') \r\n normalizerx += 3\r\n\r\n #end marker\r\n for n in '101':\r\n if n == '1':\r\n self.barcode.create_rectangle(normalizerx, normalizery, normalizerx+2,\r\n normalizery+150, fill=\"black\", outline='black') \r\n normalizerx += 3\r\n\r\n del digit12\r\n\r\n\r\ndef main():\r\n root = tk.Tk()\r\n userinterface = BarcodeImage(root)\r\n root.mainloop()\r\n\r\nif __name__=='__main__':\r\n main()","sub_path":"DDP 1/Tugas Pemrograman 3/Try.py","file_name":"Try.py","file_ext":"py","file_size_in_byte":8245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"165879240","text":"import datetime\nimport json\nfrom elasticsearch_dsl import Search\nfrom elasticsearch_dsl.query import MultiMatch, Match, Term, Terms, GeoDistance, Range\nfrom mlsproperty import Property\nfrom cma.cma_property import MPSubjectProperty\nfrom cma.cma_offproperty import OffMarketSubjectProperty\n\n\nimport boto3\nfrom botocore.exceptions import ClientError\nfrom boto3.dynamodb.conditions import Key, Attr\ndynamodb = boto3.resource('dynamodb', region_name='us-west-2')\nproperty_tax_table = dynamodb.Table('PropertyTaxRates')\nproperty_taxbycity_table = dynamodb.Table('PropertyTaxByCityRates')\n\n# parameters that the investor is allowed to override\nuser_param_list = [\n\t\t'improvements','downpayment_percent','closing_costs_percent','mortgage_interest_rate','insurance_rate',\n\t\t'property_tax_rate','property_tax_rate_auto','vacancy_rate','maintenance_percent','property_mgmt_percent','hoa_yr',\n\t\t'amortization_yrs','payments_yr','monthly_rent', 'monthly_rent_unit1', 'monthly_rent_unit2','monthly_rent_unit3','monthly_rent_unit4',\n 'purchase_price_type', 'purchase_price','cash_flow_criteria', 'cap_rate_criteria', 'rent_to_value_criteria', 'success_criteria',\n 'comp_max_dist', 'comp_max_days', 'comp_max_num_props', 'rental_max_dist', 'rental_max_days', 'rental_max_num_props'\n]\n\n# List of CMA parameters for calculations\nreq_param_list = [\n\t\t'improvements','downpayment_percent','closing_costs_percent','mortgage_interest_rate','insurance_rate',\n\t\t'property_tax_rate','property_tax_rate_auto','vacancy_rate','maintenance_percent','property_mgmt_percent','hoa_yr',\n\t\t'amortization_yrs','payments_yr','monthly_rent', 'monthly_rent_unit1', 'monthly_rent_unit2','monthly_rent_unit3','monthly_rent_unit4',\n 'purchase_price_type', 'purchase_price','cash_flow_criteria', 'cap_rate_criteria', 'rent_to_value_criteria', 'success_criteria',\n\t\t'comp_max_dist', 'comp_max_age_diff', 'comp_max_days', 'comp_max_sqft_diff', 'comp_max_bed_diff',\n\t\t'comp_max_bath_diff','comp_min_num_props','comp_max_num_props','rental_max_dist', 'rental_max_age_diff',\n\t\t'rental_max_days','rental_max_sqft_diff', 'rental_max_bed_diff', 'rental_max_bath_diff',\n\t\t'rental_min_num_props','rental_max_num_props','comp_dist_score_weight','comp_age_score_weight',\n\t\t'comp_days_score_weight','comp_sqft_score_weight','comp_bed_score_weight','comp_bath_score_weight',\n\t\t'comp_style_score_weight','rental_dist_score_weight','rental_age_score_weight','rental_days_score_weight',\n\t\t'rental_sqft_score_weight','rental_bed_score_weight','rental_bath_score_weight','rental_style_score_weight', 'rental_adjustment_mult',\n\t\t'comp_style_match_type','rental_style_match_type'\n]\n\n\n\nclass CmaCalculator:\n # Init dict to hold param:value pairs consisting of all params and their values\n req_param_values = {}\n request_options = {}\n user_request_params = {} #parameters that the user can change\n cma_pretty_option = False # Init and check for presence of pretty_money option flag (monetary value formatting)\n cma_properties_option = False\n area_properties_option = False\n market_value_option = False\n\n def __init__(self, session, database, site_id, request_params, request_options):\n self.database = database\n tenant_connection = session.resource('dynamodb', region_name='us-west-2')\n self.criteria_table = tenant_connection.Table('CmaCriteria')\n self.site_id = site_id\n\n for param in user_param_list:\n self.user_request_params[param] = request_params.get(param)\n\n self.request_params = request_params\n\t # Add param value to dict for passing into MP_Subject_Property constructor.\n for param in req_param_list:\n self.req_param_values[param] = request_params.get(param)\n\n \n # Check/init the other request options\n request_options = request_options or {}\n self.cma_pretty_option = bool(request_options.get('pretty_money'))\n self.cma_properties_option = bool(request_options.get('cma_properties'))\n self.area_properties_option = bool(request_options.get('area_properties'))\n self.market_value_option = bool(request_options.get('market_value'))\n self.request_options = request_options\n self.__extractParams__()\n\n def __lookupPropertyTax__(self, county):\n print('looking up property tax for ' + county)\n try:\n prop_tax_response = property_tax_table.get_item(Key={'county': county })\n except ClientError as e:\n print(e.response['Error']['Message'])\n return None\n\n prop_tax = prop_tax_response['Item']['rate']\n print('found property tax for ' + county + \": \" + str(prop_tax))\n return prop_tax\n\n def __lookupPropertyTaxByCity__(self, city):\n print('looking up property tax for ' + city)\n try:\n prop_tax_response = property_taxbycity_table.get_item(Key={'city': city })\n except ClientError as e:\n print(e.response['Error']['Message'])\n return None\n\n prop_tax = prop_tax_response['Item']['rate']\n print('found property tax for ' + city + \": \" + str(prop_tax))\n return prop_tax\n\n\n # lookup the missing params from the default values\n def __lookupParams__(self):\n criteria_table = self.criteria_table\n req_param_values = self.req_param_values\n try:\n response = criteria_table.get_item(Key={'siteId': '__DEFAULT__' })\n platform_assumptions = response['Item']\n response = criteria_table.get_item(Key={'siteId': self.site_id })\n # if the site assumptions haven't been overridden, then response will not have Item and just return an empty dictionary\n site_assumptions = response.get('Item', {})\n except ClientError as e:\n print(e.response['Error']['Message'])\n return None\n\n # return a merged dictionary with values from site_assumptions replacing those from platform_assumptions\n\n criteria = {**platform_assumptions, **site_assumptions}\n # Get property search, matching, and scoring options into arrays.\n # Note that the keys are the same between comp and rental options.\n # It's that way so that the cma code can use a common set of values,\n # regardless of whether the cma is being done for property value comp\n # or rental comp analysis.\n comp_prop_match_options = {\n 'MaxDist': int(criteria['comp_max_dist']),\n 'MaxAgeDiff': int(criteria['comp_max_age_diff']),\n 'MaxDays': int(criteria['comp_max_days']),\n 'MaxSqftDiff': int(criteria['comp_max_sqft_diff']),\n 'MaxBedDiff': int(criteria['comp_max_bed_diff']),\n 'MaxBathDiff': int(criteria['comp_max_bath_diff']),\n 'MinNumProps': int(criteria['comp_min_num_props']),\n 'MaxNumProps': int(criteria['comp_max_num_props']),\n 'StyleMatchType':criteria['comp_style_match_type']\n }\n\n rental_prop_match_options = {\n 'MaxDist': int(criteria['rental_max_dist']),\n 'MaxAgeDiff': int(criteria['rental_max_age_diff']),\n 'MaxDays': int(criteria['rental_max_days']),\n 'MaxSqftDiff': int(criteria['rental_max_sqft_diff']),\n 'MaxBedDiff': int(criteria['rental_max_bed_diff']),\n 'MaxBathDiff': int(criteria['rental_max_bath_diff']),\n 'MinNumProps': int(criteria['rental_min_num_props']),\n 'MaxNumProps': int(criteria['rental_max_num_props']),\n 'StyleMatchType':criteria['rental_style_match_type']\n }\n\n comp_scoring_weights = {\n 'DistWeight': int(criteria['comp_dist_score_weight']),\n 'AgeWeight': int(criteria['comp_age_score_weight']),\n 'DaysWeight': int(criteria['comp_days_score_weight']),\n 'SqftWeight': int(criteria['comp_sqft_score_weight']),\n 'BedWeight': int(criteria['comp_bed_score_weight']),\n 'BathWeight': int(criteria['comp_bath_score_weight']),\n 'StyleWeight': int(criteria['comp_style_score_weight'])\n }\n\n rental_scoring_weights = {\n 'DistWeight': int(criteria['rental_dist_score_weight']),\n 'AgeWeight': int(criteria['rental_age_score_weight']),\n 'DaysWeight': int(criteria['rental_days_score_weight']),\n 'SqftWeight': int(criteria['rental_sqft_score_weight']),\n 'BedWeight': int(criteria['rental_bed_score_weight']),\n 'BathWeight': int(criteria['rental_bath_score_weight']),\n 'StyleWeight': int(criteria['rental_style_score_weight']),\n 'RentAdjustmentMult': float(criteria['rental_adjustment_mult'])\n }\n\n\n # Add prop match options and scoring weights to param value array\n req_param_values['comp_prop_match_options'] = comp_prop_match_options\n req_param_values['rental_prop_match_options'] = rental_prop_match_options\n req_param_values['comp_scoring_weights'] = comp_scoring_weights\n req_param_values['rental_scoring_weights'] = rental_scoring_weights\n\n def __extractParams__(self):\n req_param_values = self.req_param_values\n\n # Convert percent values to actual percent for calculations and add to parameter values\n req_param_values['cap_rate_criteria_pcnt'] = float(req_param_values['cap_rate_criteria']) / 100.0\n req_param_values['rent_to_value_criteria_pcnt'] = float(req_param_values['rent_to_value_criteria']) / 100.0\n req_param_values['downpayment_percent_pcnt'] = float(req_param_values['downpayment_percent']) / 100.0\n req_param_values['insurance_rate_pcnt'] = float(req_param_values['insurance_rate']) / 100.0\n req_param_values['mortgage_interest_rate_pcnt'] = float(req_param_values['mortgage_interest_rate']) / 100.0\n req_param_values['property_tax_rate_pcnt'] = float(req_param_values.get('property_tax_rate', 0) or 0) / 100.0\n req_param_values['maintenance_percent_pcnt'] = float(req_param_values['maintenance_percent']) / 100.0\n req_param_values['vacancy_rate_pcnt'] = float(req_param_values['vacancy_rate']) / 100.0\n req_param_values['closing_costs_percent_pcnt'] = float(req_param_values['closing_costs_percent']) / 100.0\n req_param_values['property_mgmt_percent_pcnt'] = float(req_param_values['property_mgmt_percent']) / 100.0\n req_param_values['comp_max_dist'] = int(req_param_values['comp_max_dist'])\n req_param_values['comp_max_days'] = int(req_param_values['comp_max_days'])\n req_param_values['comp_max_num_props'] = int(req_param_values['comp_max_num_props'])\n req_param_values['rental_max_dist'] = int(req_param_values['rental_max_dist'])\n req_param_values['rental_max_days'] = int(req_param_values['rental_max_days'])\n req_param_values['rental_max_num_props'] = int(req_param_values['rental_max_num_props'])\n \n # try to get from the request, but if they aren't there, then look them up\n try:\n # Get property search, matching, and scoring options into arrays.\n # Note that the keys are the same between comp and rental options.\n # It's that way so that the cma code can use a common set of values,\n # regardless of whether the cma is being done for property value comp\n # or rental comp analysis.\n comp_prop_match_options = {\n 'MaxDist': int(req_param_values['comp_max_dist']),\n 'MaxAgeDiff': int(req_param_values['comp_max_age_diff']),\n 'MaxDays': int(req_param_values['comp_max_days']),\n 'MaxSqftDiff': int(req_param_values['comp_max_sqft_diff']),\n 'MaxBedDiff': int(req_param_values['comp_max_bed_diff']),\n 'MaxBathDiff': int(req_param_values['comp_max_bath_diff']),\n 'MinNumProps': int(req_param_values['comp_min_num_props']),\n 'MaxNumProps': int(req_param_values['comp_max_num_props']),\n 'StyleMatchType':req_param_values['comp_style_match_type']\n }\n\n rental_prop_match_options = {\n 'MaxDist': int(req_param_values['rental_max_dist']),\n 'MaxAgeDiff': int(req_param_values['rental_max_age_diff']),\n 'MaxDays': int(req_param_values['rental_max_days']),\n 'MaxSqftDiff': int(req_param_values['rental_max_sqft_diff']),\n 'MaxBedDiff': int(req_param_values['rental_max_bed_diff']),\n 'MaxBathDiff': int(req_param_values['rental_max_bath_diff']),\n 'MinNumProps': int(req_param_values['rental_min_num_props']),\n 'MaxNumProps': int(req_param_values['rental_max_num_props']),\n 'StyleMatchType':req_param_values['rental_style_match_type']\n }\n\n comp_scoring_weights = {\n 'DistWeight': int(req_param_values['comp_dist_score_weight']),\n 'AgeWeight': int(req_param_values['comp_age_score_weight']),\n 'DaysWeight': int(req_param_values['comp_days_score_weight']),\n 'SqftWeight': int(req_param_values['comp_sqft_score_weight']),\n 'BedWeight': int(req_param_values['comp_bed_score_weight']),\n 'BathWeight': int(req_param_values['comp_bath_score_weight']),\n 'StyleWeight': int(req_param_values['comp_style_score_weight'])\n }\n\n rental_scoring_weights = {\n 'DistWeight': int(req_param_values['rental_dist_score_weight']),\n 'AgeWeight': int(req_param_values['rental_age_score_weight']),\n 'DaysWeight': int(req_param_values['rental_days_score_weight']),\n 'SqftWeight': int(req_param_values['rental_sqft_score_weight']),\n 'BedWeight': int(req_param_values['rental_bed_score_weight']),\n 'BathWeight': int(req_param_values['rental_bath_score_weight']),\n 'StyleWeight': int(req_param_values['rental_style_score_weight']),\n 'RentAdjustmentMult': float(req_param_values['rental_adjustment_mult'])\n }\n\n # Add prop match options and scoring weights to param value array\n req_param_values['comp_prop_match_options'] = comp_prop_match_options\n req_param_values['rental_prop_match_options'] = rental_prop_match_options\n req_param_values['comp_scoring_weights'] = comp_scoring_weights\n req_param_values['rental_scoring_weights'] = rental_scoring_weights\n except (KeyError, TypeError):\n print('parameter not found. looking up default values')\n self.__lookupParams__()\n\n\n def calculate(self, listing_number, prop_type, mls_vendor, debug=False):\n # Get the subject listing\n print(self.req_param_values)\n\n listing = Property.get(id=listing_number)\n listing_details = self.database.get_property(listing_number, listing.property_type)\n\n if (not listing):\n print('no listing found: ' + str(listing_number))\n\n elif (listing and listing.property_type != 'VACL'):\n if 'property_tax_rate_auto' in self.req_param_values and self.req_param_values['property_tax_rate_auto']:\n tax_rate = self.__lookupPropertyTax__(listing.county)\n if tax_rate:\n self.req_param_values['property_tax_rate_pcnt'] = tax_rate\n\n # Create Subject Property for listing and perform analysis\n subject_property = MPSubjectProperty(listing, self.req_param_values, listing_details)\n subject_property.calculate_cma(self.market_value_option, debug)\n result = {\n 'request_property': {\n 'listing_number': listing_number,\n 'prop_type': prop_type,\n 'mls_vendor': mls_vendor\n },\n 'options': self.request_options,\n 'parameters': self.user_request_params,\n 'cma': subject_property.get_results(self.cma_properties_option, self.area_properties_option, self.cma_pretty_option)\n }\n\n # Check if pretty option is set\n # if (self.cma_pretty_option):\t\t\t\n # Get pretty sections and their respective values\n # subject_property_values = subject_property.get_subject_property_values(null, $pretty_money);\n # $investment_analysis_results = $subject_property->get_subject_property_investment_analysis_results(null, $pretty_money);\n # $investment_analysis_data = $subject_property->get_subject_property_investment_analysis_data(null, $pretty_money);\n # $investment_criteria_results = $subject_property->get_subject_property_investment_criteria_results(null, $pretty_money);\n\t\t\t\n # result['subject_property_values'] = subject_property_values\n # $result['investment_analysis_results'] = $investment_analysis_results;\n # $result['investment_analysis_data'] = $investment_analysis_data;\n # $result['investment_criteria_results'] = $investment_criteria_results;\n\t\t\n print(\"calculate: result = \", result)\n return result\n else:\n print('skipping CMA calculation')\n print('listing is for VACL ' + str(listing_number) + ' ' + listing.property_type)\n\n\n def calculate_analyze(self, property, debug=False):\n # Get the subject listing\n print(\"cma:calculate analyze: property = \", json.dumps(property))\n\n if (property):\n if 'property_tax_rate_auto' in self.req_param_values and self.req_param_values['property_tax_rate_auto']:\n tax_rate = self.__lookupPropertyTax__(property[\"county\"])\n print(\"tax_rate \", tax_rate, \"for county \", property[\"county\"])\n if tax_rate:\n self.req_param_values['property_tax_rate_pcnt'] = tax_rate\n\n # Create Subject Property for listing and perform analysis\n subject_property = OffMarketSubjectProperty(property, self.req_param_values)\n subject_property.calculate_cma(debug)\n result = {\n 'request_property': {\n 'listing_number': \"\",\n 'prop_type': \"\",\n 'mls_vendor': \"\"\n },\n 'options': self.request_options,\n 'parameters': self.user_request_params,\n 'cma': subject_property.get_results(self.cma_properties_option, self.area_properties_option, self.cma_pretty_option)\n }\n\n # Check if pretty option is set\n # if (self.cma_pretty_option):\t\t\t\n # Get pretty sections and their respective values\n # subject_property_values = subject_property.get_subject_property_values(null, $pretty_money);\n # $investment_analysis_results = $subject_property->get_subject_property_investment_analysis_results(null, $pretty_money);\n # $investment_analysis_data = $subject_property->get_subject_property_investment_analysis_data(null, $pretty_money);\n # $investment_criteria_results = $subject_property->get_subject_property_investment_criteria_results(null, $pretty_money);\n\t\t\t\n # result['subject_property_values'] = subject_property_values\n # $result['investment_analysis_results'] = $investment_analysis_results;\n # $result['investment_analysis_data'] = $investment_analysis_data;\n # $result['investment_criteria_results'] = $investment_criteria_results;\n\t\t\n print(\"calculate analyze: result = \", result)\n return result\n else:\n print('skipping CMA calculation')\n\n","sub_path":"functions/search/src/cma/cma.py","file_name":"cma.py","file_ext":"py","file_size_in_byte":19918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"70227513","text":"import pysam, sys, os, random\nfrom jobTree.src.bioio import fastaRead, fastqRead, \\\ncigarReadFromString,PairwiseAlignment, fastaWrite, fastqWrite, logger, absSymPath, reverseComplementChar\n\ndef pathToBaseNanoporeDir():\n \"\"\"Returns path to base directory \"marginAlign\"\n \"\"\"\n import marginAlign\n i = absSymPath(__file__)\n return os.path.split(os.path.split(os.path.split(i)[0])[0])[0]\n\ndef getFirstNonClippedPositionInRead(alignedSegment, readSeq):\n \"\"\"Gets the coordinate of the first non-clipped position in the read relative to the \n complete read sequence (including any hard clipped bases).\n If the alignment is on the reverse strand the coordinate is negative, e.g. the reverse strand coordinate of\n the 2nd position of the read sequence is -1 (0 based).\n \"\"\"\n if alignedSegment.cigar[0][0] == 5: #Translate the read position to the original \n #coordinates by removing hard clipping\n readOffset = alignedSegment.cigar[0][1]\n else:\n readOffset = 0\n if alignedSegment.is_reverse: #SEQ is reverse complemented\n readOffset = -(len(readSeq) - 1 - readOffset)\n readOffset += alignedSegment.query_alignment_start #This removes any soft-clipping\n return readOffset\n\ndef getLastNonClippedPositionInRead(alignedSegment, readSeq):\n \"\"\"As getFirstNonClippedPositionInRead, but returns the last\n non-clipped position in the read, relative to the complete read sequence.\n \"\"\"\n return getFirstNonClippedPositionInRead(alignedSegment, readSeq) + \\\n alignedSegment.query_alignment_end - alignedSegment.query_alignment_start -1\n\ndef getExonerateCigarFormatString(alignedSegment, sam):\n \"\"\"Gets a complete exonerate like cigar-string describing the sam line,\n with the cigar described with respect to the alignedSegment.query_sequence string,\n which includes softclip bases, but not hard-clipped bases.\n \"\"\"\n for op, length in alignedSegment.cigar:\n assert op in (0, 1, 2, 4, 5)\n translation = { 0:\"M\", 1:\"I\", 2:\"D\" }\n cigarString = \" \".join([ \"%s %i\" % (translation[op], length) for op, length in \n alignedSegment.cigar if op in translation ]) #Ignore soft clips\n completeCigarString = \"cigar: %s %i %i + %s %i %i + 1 %s\" % (\n alignedSegment.query_name, alignedSegment.qstart, alignedSegment.query_alignment_end, \n sam.getrname(alignedSegment.reference_id), alignedSegment.reference_start, alignedSegment.reference_end, cigarString)\n ##Assertions\n pA = cigarReadFromString(completeCigarString) #This checks it's an okay cigar\n assert sum([ op.length for op in pA.operationList if op.type == \\\n PairwiseAlignment.PAIRWISE_MATCH ]) == \\\n len([ readPos for readPos, refPos in alignedSegment.aligned_pairs if \\\n readPos != None and refPos != None ])\n ##End assertions\n return completeCigarString\n\ndef samToBamFile(samInputFile, bamOutputFile):\n \"\"\"Converts a sam file to a bam file (sorted)\n \"\"\"\n samfile = pysam.Samfile(samInputFile, \"r\" )\n bamfile = pysam.Samfile(bamOutputFile, \"wb\", template=samfile)\n for line in samfile:\n bamfile.write(line)\n\n samfile.close()\n bamfile.close()\n \ndef getFastaDictionary(fastaFile):\n \"\"\"Returns a dictionary of the first words of fasta headers to their corresponding \n fasta sequence\n \"\"\"\n namesAndSequences = map(lambda x : (x[0].split()[0], x[1]), fastaRead(open(fastaFile, 'r')))\n names = map(lambda x : x[0], namesAndSequences)\n assert len(names) == len(set(names)) #Check all the names are unique\n return dict(namesAndSequences) #Hash of names to sequences\n\ndef makeFastaSequenceNamesUnique(inputFastaFile, outputFastaFile):\n \"\"\"Makes a fasta file with unique names\n \"\"\"\n names = set()\n fileHandle = open(outputFastaFile, 'w')\n for name, seq in fastaRead(open(inputFastaFile, 'r')):\n while name in names:\n logger.critical(\"Got a duplicate fasta sequence name: %s\" % name)\n name += \"i\"\n names.add(name)\n fastaWrite(fileHandle, name, seq)\n fileHandle.close()\n return outputFastaFile\n\ndef makeFastqSequenceNamesUnique(inputFastqFile, outputFastqFile):\n \"\"\"Makes a fastq file with unique names\n \"\"\"\n names = set()\n fileHandle = open(outputFastqFile, 'w')\n for name, seq, quals in fastqRead(open(inputFastqFile, 'r')):\n name = name.split()[0] #Get rid of any white space\n while name in names:\n logger.critical(\"Got a duplicate fastq sequence name: %s\" % name)\n name += \"i\"\n names.add(name)\n fastqWrite(fileHandle, name, seq, quals)\n fileHandle.close()\n return outputFastqFile\n\ndef samIterator(sam):\n \"\"\"Creates an iterator over the aligned reads in a sam file, filtering out\n any reads that have no reference alignment.\n \"\"\"\n for aR in sam:\n if aR.reference_id != -1:\n yield aR\n\ndef combineSamFiles(baseSamFile, extraSamFiles, outputSamFile):\n \"\"\"Combines the lines from multiple sam files into one sam file\n \"\"\"\n sam = pysam.Samfile(baseSamFile, \"r\" )\n outputSam = pysam.Samfile(outputSamFile, \"wh\", template=sam)\n sam.close()\n for samFile in [ baseSamFile ] + extraSamFiles:\n sam = pysam.Samfile(samFile, \"r\" )\n for line in sam:\n outputSam.write(line)\n sam.close()\n outputSam.close()\n \ndef paralleliseSamProcessingTargetFn(target, samFile, \n referenceFastaFile, outputFile, \n childTargetFn, followOnTargetFn, options):\n \"\"\"Parallelise a computation over the alignments in a SAM file.\n \"\"\"\n #Load reference sequences\n refSequences = getFastaDictionary(referenceFastaFile) #Hash of names to sequences\n \n tempOutputFiles = []\n childCount, totalSeqLength = 0, sys.maxint\n tempExonerateFile, tempQueryFile = None, None \n tempExonerateFileHandle, tempQueryFileHandle = None, None\n refName = None\n \n #Read through the SAM file\n sam = pysam.Samfile(samFile, \"r\" ) \n \n def makeChild():\n #Add a child target to do the processing of a subset of the lines.\n if tempExonerateFile != None:\n tempExonerateFileHandle.close()\n tempQueryFileHandle.close()\n #Temporary cigar file to store the realignment\n tempOutputFiles.append(os.path.join(target.getGlobalTempDir(), \n \"tempOutput_%i.txt\" % childCount))\n target.addChildTargetFn(childTargetFn,\n args=(tempExonerateFile, refName, \n refSequences[refName], \n tempQueryFile, tempOutputFiles[-1], options))\n \n for aR, index in zip(samIterator(sam), xrange(sys.maxint)): \n #Iterate on the sam lines realigning them in parallel\n if totalSeqLength > options.maxAlignmentLengthPerJob or \\\n refName != sam.getrname(aR.reference_id):\n makeChild()\n tempExonerateFile = os.path.join(target.getGlobalTempDir(), \n \"tempExonerateCigar_%s.cig\" % childCount)\n tempExonerateFileHandle = open(tempExonerateFile, 'w')\n tempQueryFile = os.path.join(target.getGlobalTempDir(), \n \"tempQueryCigar_%s.fa\" % childCount)\n tempQueryFileHandle = open(tempQueryFile, 'w')\n childCount += 1\n totalSeqLength = 0\n \n tempExonerateFileHandle.write(getExonerateCigarFormatString(aR, sam) + \"\\n\")\n fastaWrite(tempQueryFileHandle, aR.query_name, aR.query_sequence) #This is the query sequence, including soft clipped bases, but excluding hard clip bases\n totalSeqLength += len(aR.query_sequence)\n refName = sam.getrname(aR.reference_id)\n \n makeChild()\n target.setFollowOnTargetFn(followOnTargetFn, args=(samFile, referenceFastaFile, \\\n outputFile, tempOutputFiles, options))\n #Finish up\n sam.close()\n \n###The following code is used by the tests/plots\n\ndef getFastqDictionary(fastqFile):\n \"\"\"Returns a dictionary of the first words of fastq headers to their corresponding \n fastq sequence\n \"\"\"\n namesAndSequences = map(lambda x : (x[0].split()[0], x[1]), fastqRead(open(fastqFile, 'r')))\n names = map(lambda x : x[0], namesAndSequences)\n assert len(names) == len(set(names)) #Check all the names are unique\n return dict(namesAndSequences) #Hash of names to sequences\n\nclass AlignedPair:\n \"\"\"Represents an aligned pair of positions using absolute reference/read coordinates.\n \n Originally coded when I was figuring out pySam, hence is full of assertions and uses\n global coordinates.\n \"\"\"\n def __init__(self, refPos, refSeq, readPos, isReversed, readSeq, pPair):\n assert refPos >= 0 and refPos < len(refSeq)\n self.refPos = refPos\n self.refSeq = refSeq\n assert readPos >= 0 and readPos < len(readSeq)\n self.readPos = readPos\n self.isReversed = isReversed\n self.readSeq = readSeq\n self.pPair = pPair #Pointer to the previous aligned pair\n self.bases = set([ 'A', 'C', 'G', 'T' ])\n \n def isMatch(self):\n return self.getRefBase().upper() == self.getReadBase().upper() and \\\n self.getRefBase().upper() in self.bases\n \n def isMismatch(self):\n return self.getRefBase().upper() != self.getReadBase().upper() and \\\n self.getRefBase().upper() in self.bases and self.getReadBase().upper() in self.bases\n \n def getRefBase(self):\n return self.refSeq[self.refPos]\n \n def getReadBase(self):\n if self.isReversed:\n return reverseComplementChar(self.readSeq[self.readPos]) \n return self.readSeq[self.readPos]\n \n def getSignedReadPos(self):\n if self.isReversed:\n return -self.readPos\n return self.readPos\n \n def getPrecedingReadInsertionLength(self, globalAlignment=False):\n #If global alignment flag is true any unaligned prefix/suffix insertion at the beginning\n #and end of the read sequence is interpreted as an insertion, rather than being ignored.\n if self.pPair == None:\n if globalAlignment:\n if self.isReversed:\n assert len(self.readSeq) - self.readPos - 1 >= 0\n return len(self.readSeq) - self.readPos - 1\n return self.readPos\n return 0\n return self._indelLength(self.readPos, self.pPair.readPos)\n \n def getPrecedingReadDeletionLength(self, globalAlignment=False):\n if self.pPair == None:\n if globalAlignment:\n return self.refPos\n return 0\n return self._indelLength(self.refPos, self.pPair.refPos)\n \n @staticmethod\n def _indelLength(pos, pPos):\n length = abs(pPos - pos) - 1\n assert length >= 0\n return length\n\n @staticmethod\n def iterator(alignedSegment, refSeq, readSeq):\n \"\"\"Generates aligned pairs from a pysam.AlignedSegment object.\n \"\"\"\n readOffset = getFirstNonClippedPositionInRead(alignedSegment, readSeq)\n pPair = None\n assert len(alignedSegment.query_sequence) <= len(readSeq)\n for readPos, refPos in alignedSegment.aligned_pairs: #Iterate over the block\n if readPos != None and refPos != None:\n assert refPos >= alignedSegment.reference_start and refPos < alignedSegment.reference_end\n if refPos >= len(refSeq): #This is masking an (apparently minor?) one \n #off error in the BWA sam files?\n logger.critical(\"Detected an aligned reference position out of \\\n bounds! Reference length: %s, reference coordinate: %s\" % \\\n (len(refSeq), refPos))\n continue\n aP = AlignedPair(refPos, refSeq, abs(readOffset + readPos), \n alignedSegment.is_reverse, readSeq, pPair)\n if aP.getReadBase().upper() != alignedSegment.query_alignment_sequence[readPos].upper():\n logger.critical(\"Detected a discrepancy between the absolute read \\\n sequence and the aligned read sequence. Bases: %s %s, \\\n read-position: %s, is reversed: %s, absolute read offset: %s, \\\n length absolute read sequence %s, length aligned read sequence %s, \\\n length aligned read sequence plus soft clipping %s, read name: %s, \\\n cigar string %s\" % (aP.getReadBase().upper(), \n alignedSegment.query_alignment_sequence[readPos].upper(), readPos, \n alignedSegment.is_reverse, readOffset, len(readSeq), \n len(alignedSegment.query_alignment_sequence), len(alignedSegment.query_sequence), \n alignedSegment.query_name, alignedSegment.cigarstring))\n\n pPair = aP\n yield aP \n \nclass ReadAlignmentStats:\n \"\"\"Calculates stats of a given read alignment.\n Global alignment means the entire reference and read sequences (trailing indels).\n \"\"\"\n def __init__(self, readSeq, refSeq, alignedRead, globalAlignment=False):\n self.matches = 0\n self.mismatches = 0\n self.ns = 0\n self.totalReadInsertionLength = 0\n self.totalReadInsertions = 0\n self.totalReadDeletionLength = 0\n self.totalReadDeletions = 0\n self.readSeq = readSeq\n self.refSeq = refSeq\n self.globalAlignment = globalAlignment\n \n #Now process the read alignment\n totalReadInsertionLength, totalReadDeletionLength = 0, 0\n aP = None\n for aP in AlignedPair.iterator(alignedRead, self.refSeq, self.readSeq): \n if aP.isMatch():\n self.matches += 1\n elif aP.isMismatch():\n self.mismatches += 1\n else:\n self.ns += 1\n if aP.getPrecedingReadInsertionLength(self.globalAlignment) > 0:\n self.totalReadInsertions += 1\n totalReadInsertionLength += aP.getPrecedingReadInsertionLength(self.globalAlignment)\n if aP.getPrecedingReadDeletionLength(self.globalAlignment) > 0:\n self.totalReadDeletions += 1\n totalReadDeletionLength += aP.getPrecedingReadDeletionLength(self.globalAlignment)\n if self.globalAlignment and aP != None: #If global alignment account for any trailing indels\n assert len(self.refSeq) - aP.refPos - 1 >= 0\n if len(self.refSeq) - aP.refPos - 1 > 0:\n self.totalReadDeletions += 1\n self.totalReadDeletionLength += len(self.refSeq) - aP.refPos - 1\n\n if alignedRead.is_reverse:\n aP.readPos >= 0\n if aP.readPos > 0:\n self.totalReadInsertions += 1\n totalReadInsertionLength += aP.readPos\n else:\n assert len(self.readSeq) - aP.readPos - 1 >= 0\n if len(self.readSeq) - aP.readPos - 1 > 0:\n self.totalReadInsertions += 1\n totalReadInsertionLength += len(self.readSeq) - aP.readPos - 1\n\n assert totalReadInsertionLength <= len(self.readSeq)\n assert totalReadDeletionLength <= len(self.refSeq)\n self.totalReadInsertionLength += totalReadInsertionLength\n self.totalReadDeletionLength += totalReadDeletionLength\n \n @staticmethod\n def formatRatio(numerator, denominator):\n if denominator == 0:\n return float(\"nan\")\n return float(numerator)/denominator\n \n def readCoverage(self):\n return self.formatRatio(self.matches + self.mismatches, self.matches + self.mismatches + self.totalReadInsertionLength)\n \n def referenceCoverage(self):\n return self.formatRatio(self.matches + self.mismatches, self.matches + self.mismatches + self.totalReadDeletionLength)\n \n def readIdentity(self):\n return self.formatRatio(self.matches, self.matches + self.mismatches + self.totalReadInsertionLength)\n \n def alignmentIdentity(self):\n return self.formatRatio(self.matches, self.matches + self.mismatches + self.totalReadInsertionLength + self.totalReadDeletionLength)\n\n def mismatchesPerAlignedBase(self):\n return self.formatRatio(self.mismatches, self.matches + self.mismatches)\n \n def deletionsPerReadBase(self):\n return self.formatRatio(self.totalReadDeletions, self.matches + self.mismatches)\n \n def insertionsPerReadBase(self):\n return self.formatRatio(self.totalReadInsertions, self.matches + self.mismatches)\n \n def readLength(self):\n return len(self.readSeq)\n \n @staticmethod\n def getReadAlignmentStats(samFile, readFastqFile, referenceFastaFile, globalAlignment=True):\n \"\"\"Gets a list of ReadAlignmentStats objects, one for each alignment in the same file\n \"\"\"\n refSequences = getFastaDictionary(referenceFastaFile) #Hash of names to sequences\n readSequences = getFastqDictionary(readFastqFile) #Hash of names to sequences\n sam = pysam.Samfile(samFile, \"r\")\n readsToReadCoverages = {}\n readAlignmentStats = map(lambda aR : ReadAlignmentStats(readSequences[aR.qname], \\\n refSequences[sam.getrname(aR.rname)], aR, globalAlignment), samIterator(sam))\n sam.close()\n return readAlignmentStats\n \n##Functions used in the creation of mutations - used in the testing of margin-caller\n\ndef mutateSequence(sequence, snpRate): #Does not preserve softmasking\n \"\"\"Returns sequence with snpRate proportion of sites mutated and a list of those mutations\n \"\"\"\n mutations = []\n mutatedSequence = list(sequence)\n for i in xrange(len(sequence)):\n if random.random() < snpRate:\n base = sequence[i]\n altBase = random.choice(list(set((\"A\", 'C', 'G', 'T')) - set(base.upper())))\n altBase = altBase if base.upper() == base else altBase.lower()\n mutations.append((i, base, altBase))\n mutatedSequence[i] = altBase\n return \"\".join(mutatedSequence), mutations\n\ndef mutateSequences(sequences, snpRate):\n \"\"\"As mutateSequence, but for collection of sequences. Sequences is a dictionary \n of sequences of names to sequences. Return value is a dictionary of names to mutated\n sequences and a list of those mutations, represented as triples of (sequenceName, position, alt).\n \"\"\"\n mutatedSequences = {}; allMutations = [] #List of refSequenceName, position, altBase\n for name in sequences.keys():\n mutatedSequence, mutations = mutateSequence(sequences[name], snpRate)\n mutatedSequences[name] = mutatedSequence\n allMutations += map(lambda x : (name, x[0], x[1], x[2]), mutations) \n return mutatedSequences, allMutations\n","sub_path":"src/margin/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":19174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"79412095","text":"# -*- coding: utf-8 -*-\n\nimport os\n\nfrom setuptools import setup, find_packages\n\n\ndef get_version():\n current_file = os.path.dirname(__file__)\n\n with open(os.path.join(current_file, 'lostfilmlib/version.py')) as file:\n version = {}\n exec(file.read(), version)\n return version['VERSION']\n\n\nsetup(\n name='lostfilmlib',\n version=get_version(),\n author='Konstantin Kruglov',\n author_email='kruglovk@gmail.com',\n description='scan lostfilm.tv',\n long_description='Scan lostfilm.tv and receiving informations about '\n 'serials',\n entry_points={\n 'console_scripts': [\n 'lostfilmlib-cli = lostfilmlib:tv_shows_cli',\n ],\n },\n url='https://github.com/k0st1an/lostfilmlib',\n packages=find_packages(),\n install_requires=[\n 'beautifulsoup4==4.4.1',\n 'click==6.6'\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"535220683","text":"# import urllib2\n# import json\n#f = urllib2.urlopen('http://api.wunderground.com/api/Your_Key/geolookup/conditions/q/IA/Cedar_Rapids.json')\n#json_string = f.read()\n#parsed_json = json.loads(json_string)\n#location = parsed_json['location']['city']\n#temp_f = parsed_json['current_observation']['temp_f']\n#print(\"Current temperature in %s is: %s\" % (location, temp_f))\n#f.close()\n\n\n#import urllib2, urllib, json\n\n#yahoo_key = \"dj0yJmk9elpFNkJlbTFXYm1uJmQ9WVdrOWJtUlhWMFpNTm5FbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD02Mw--\"\n\nimport urllib\nimport json\n\ndef download_file(url=None, params=None):\n import urllib.request\n import urllib.parse\n\n querystring = urllib.parse.urlencode(params)\n\n response = urllib.request.urlopen(url + \"?\" + querystring)\n data = response.read() # a `bytes` object\n encoding = response.info().get_param(\"charset\", \"utf-8\")\n text = data.decode(encoding) # a `str`; this step can't be used if data is binary\n return text\n\ndef doyqlquery(query):\n import json\n baseurl = \"https://query.yahooapis.com/v1/public/yql\"\n\n result = download_file(baseurl, { \"q\": query, \"format\": \"json\"})\n return json.loads(result)\n\n\n#data = doyqlquery(\"select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\"\"nome, ak\"\")\")\n\n\n\n#data = doyqlquery(\"select wind from weather.forecast where woeid in (select woeid from geo.places(1) where text=\\\"chicago, il\\\")\")\n\nbeijing_woeid = \"2151330\"\n\ndata = doyqlquery(\"select * from weather.forecast where woeid=\" + beijing_woeid)\n\n# Hourly forecast, including wind, for Beijing\n#http://www.weather.com/weather/hourbyhour/l/CHXX0008:1:CH\n\nprint(data['query']['results'])\nprint(data)\n","sub_path":"WindForecast.py","file_name":"WindForecast.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"284355237","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport socket\nimport json\nimport threading\nimport logging\nimport configparser\nimport time\nimport mysql.connector\nimport datetime\nimport csv\nimport sys\nimport re\nimport subprocess\nimport xml.etree.ElementTree as ET\n# Сообщение отладочное\n#logging.debug( u'This is a debug message' )\n# Сообщение информационное\n#logging.info( u'This is an info message' )\n# Сообщение предупреждение\n#logging.warning( u'This is a warning' )\n# Сообщение ошибки\n#logging.error( u'This is an error message' )\n# Сообщение критическое\n#logging.critical( u'FATAL!!!' )\n\nonlines={}\nastercon=\"\"\nastconnected = 0\nevent = True\ngo = {}\nconnect =True\nreloads = {}\nlogfile = '/etc/callchat/ctrlog.log'\nlogging.basicConfig(format = u'%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s', level = logging.DEBUG, filename = logfile)\nping = time.time()\nsocks = {}\npings = {}\nmancount = {}\nanswered = {}\nclanswered = {}\nstarted = {}\nrec_threads = {}\nparse_thread = \"\"\noperators = [\"BMI\",]\nprices = {}\nvalidation = True\ncallid = True\norder = True\nstatsended = False\nasterping = True\nasterpings = {}\navailable = {}\nuids = []\n\n#производит первоначальную конфигурацию\ndef configure():\n global operators\n global validation\n global callid\n global order\n config = configparser.ConfigParser()\n config.readfp(open('/etc/callchat/ctrlconf.cnfg'))\n logfile=config.get('logging', 'logfile')\n logging.basicConfig(format = u'%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s',\n level = logging.DEBUG, filename = logfile)\n lvl=config.get('logging', 'level')\n if lvl==\"debug\":\n logging.getLogger().setLevel(logging.DEBUG)\n elif lvl==\"info\":\n logging.getLogger().setLevel(logging.INFO)\n elif lvl==\"warning\":\n logging.getLogger().setLevel(logging.WARNING)\n elif lvl==\"error\":\n logging.getLogger().setLevel(logging.ERROR)\n elif lvl==\"critical\":\n logging.getLogger().setLevel(logging.CRITICAL)\n\n\n#отправляет запросы в сокет астериска\ndef sending(str_to_send, s):\n for l in str_to_send.split('\\n'):\n logging.debug(u'Sending>' + l)\n s.send(bytes(l+'\\r\\n', \"UTF-8\"))\n\ndef connectToAsterisk(username, password):\n HOST = '127.0.0.1'\n PORT = 6868\n login = \"\"\"Action: login\nUsername: %(username)s\nSecret: %(password)s\n\"\"\"\n login_to_send = login % {\n 'username': username,\n 'password': password\n }\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((HOST, PORT))\n sending(login_to_send, s)\n return s\n\n#отключается от астериска, закрывает сокет\ndef disconnectFromAsterisk(s):\n logoff = \"\"\"Action: Logoff\n\"\"\"\n sending(logoff, s)\n s.close()\n\ndef connectToMysql():\n cnx = mysql.connector.connect(user='asterisk', password='asterisk',\n host='127.0.0.1',\n database='controllerdb')\n return cnx\n\ndef disconnectFromMysql(cnx):\n cnx.close()\n\n#отправляет запрос на звонок к астериску\ndef callsend(action_id, manager, client, message, conn):\n global astconnected\n global astercon\n global answered\n global clanswered\n global started\n global mancount\n try:\n dial = \"\"\"Action: originate\nChannel: %(manager)s\nExten: %(client)s\nContext: %(provider)s-message\nPriority: 1\nTimeout: %(mtimeout)s\nAsync: true\nVariable: MFILE=%(mfile)s\nCallerID: %(client)s\nActionID: %(id)s\nChannelId: %(id)s\n\"\"\"\n if(astconnected==0):\n astercon=connectToAsterisk(\"asterisk\", \"asterisk\")\n astconnected+=1\n\n subprocess.call(\"wget -U 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5' 'https://tts.voicetech.yandex.net/generate?text=\\\"\"+message+\"\\\"&format=wav&lang=ru-RU&emotion=good&speaker=jane&key=b3a7cba8-c45d-465b-8e9a-adaccff0a70c' -O /var/lib/asterisk/wavs/\"+action_id+\".wav\", shell=True)\n subprocess.call(\"sox -t wav '/var/lib/asterisk/wavs/\"+ action_id +\".wav' -r 8000 -c1 -t gsm '/var/lib/asterisk/messages/\"+action_id+\".gsm'\", shell=True)\n\n tofile = \"/var/lib/asterisk/messages/\" + action_id\n dial_to_send = dial % {\n 'manager': 'SIP/BMI/'+manager,\n 'client': client,\n 'provider': \"BMI\",\n 'id': action_id,\n 'mtimeout': 40*1000,\n 'mfile': tofile\n }\n logging.debug(\"sending to asterisk: \"+dial_to_send)\n sending(dial_to_send, astercon)\n astconnected-=1\n except Exception as ex:\n print(\"callsend error \"+ str(err))\n logging.error(\"callsend error \" + str(err))\n\ndef sockclose(s):\n try:\n s.shutdown(socket.SHUT_RDWR)\n except:\n pass\n\n try:\n s.close()\n except:\n pass\n\ndef parse(sock, block):\n global event\n global go\n global reload\n global socks\n global statsended\n global asterpings\n global uids\n bl=\"Main\"\n try:\n strs = block.split(\"\\r\\n\")\n if(len(strs[0].split(\":\"))>1 and \\\n (strs[0].split(\":\")[1].strip()==\"DialBegin\" or \\\n strs[0].split(\":\")[1].strip()==\"DialEnd\" or \\\n strs[0].split(\":\")[1].strip()==\"Hangup\" or \\\n strs[0].split(\":\")[1].strip()==\"VarSet\" or \\\n strs[0].split(\":\")[1].strip()==\"StatusComplete\" )):\n logging.debug(block)\n tuple1=[]\n for item in block.split('\\r\\n'):\n if(len(item.split(\": \"))==2):\n tuple1.append(item.split(\": \"))\n blk = dict((k.strip(), v.strip()) for k, v in tuple1)\n if(blk[\"Event\"] == \"Hangup\"):\n bl=\"Hangup\"\n uniqueid = blk[\"Uniqueid\"]\n logging.debug(\"Hanged up \" + uniqueid)\n if(blk[\"Cause\"]==\"16\" and uniqueid in uids):\n subprocess.call(\"sox /var/lib/asterisk/records/\"+ uniqueid +\".gsm -r 44100 -a /var/lib/asterisk/records/\"+uniqueid+\".wav\", shell=True)\n script_response = subprocess.check_output([\"php\", \"/etc/callchat/recognize.php\", \"/var/lib/asterisk/records/\"+uniqueid+\".wav\"])\n tree = ET.ElementTree(ET.fromstring(script_response))\n root = tree.getroot()\n res = root[0].text\n send(socks[uniqueid], {\"action\": \"message\", \"text\":res, \"id\":uniqueid})\n except socket.error as err:\n print(\"parser socket error in block \"+ bl +\":\" + str(err))\n logging.error(\"parser socket error in block \"+ bl +\":\" + str(err))\n reload = True\n event = False\n disconnectFromAsterisk(sock)\n except Exception as ex:\n print(\"parser error in block \"+ bl +\":\" + str(ex))\n logging.error(\"parser error in block \"+ bl +\":\" + str(ex))\n\n# парсит event'ы\ndef eventparser():\n global event\n global go\n global reload\n sock=connectToAsterisk(\"parser\", \"asterisk\")\n while event:\n try:\n start = True\n data = rec = ''\n while(start or data[-4:] != \"\\r\\n\\r\\n\" and len(rec) > 0):\n start = False\n rec = sock.recv(1024)\n data += rec.decode(\"UTF-8\")\n blocks = data.split(\"\\r\\n\\r\\n\")\n except socket.error as err:\n print(\"event socket error:\" + str(err))\n logging.error(\"event socket error:\" + str(err))\n reload = True\n event = False\n disconnectFromAsterisk(sock)\n except Exception as ex:\n print(\"event error:\" + str(ex))\n logging.error(\"event error:\" + str(ex))\n for block in blocks:\n p_thread = threading.Thread(target=parse, args=(sock, block), name='parse')\n p_thread.daemon = True\n p_thread.start()\n\n\ndef send(s, data):\n msg = bytes(json.dumps(data) + \"\\r\\n\", 'UTF-8')\n msgLen = len(msg)\n sent = 0\n logging.debug(\"send to chat: \"+str(msg))\n while (sent < msgLen):\n try:\n sl = s.send(msg[sent:])\n if sl == 0:\n print(\"Channel broken\")\n sent += sl\n except Exception as ex:\n print(\"%s\" % ex)\n break\n return sent\n\n#обработка данных, поступающих с сервера\ndef receiver(conn, addr):\n global operator\n global onlines\n global reloads\n global pings\n while onlines[addr[0]]:\n try:\n datas = rec = ''\n start=True\n while(start or datas[-2:] != \"\\r\\n\" and len(rec) > 0):\n start = False\n rec = conn.recv(1024)\n datas += rec.decode(\"utf-8\")\n for data in datas.split(\"\\r\\n\"):\n if(data.strip() != \"\" and onlines[addr[0]]):\n logging.debug(u'received message: '+ data)\n request=json.loads(data)\n #обработка пинга\n if request[\"action\"] == \"ping\":\n send(conn, {\"action\":\"pong\"})\n logging.debug(\"ping from \"+addr[0])\n elif request[\"action\"] == \"pong\":\n pings[addr[0]]=time.time()\n logging.debug(\"pong from \"+addr[0])\n elif request[\"action\"] == \"message\":\n uids.append(request[\"id\"])\n logging.debug(\"call to \" + request[\"number\"] + \" from \" + request[\"from\"])\n socks.update({str(request[\"id\"]): conn})\n send_thread=threading.Thread(target=callsend, args=(request[\"id\"], request[\"number\"], request[\"from\"], request[\"text\"], conn), name='callsend')\n send_thread.daemon = True\n send_thread.start()\n except socket.error as err:\n print(\"reciever socket error: %s\" % err)\n logging.error(\"reciever socket error: \"+err)\n reloads[addr[0]] = True\n onlines[addr[0]] = False\n except Exception as ex:\n print(\"ошибка ресивера: %s\" % ex)\n logging.error(\"reciever error: \"+ex)\n\ndef connector(sock, c):\n global connect\n global go\n global pings\n global rec_threads\n global onlines\n global reloads\n while connect:\n try:\n conn, addr = sock.accept()\n print(str(addr))\n reloads.update({addr[0]: False})\n while(addr in onlines.keys()):\n pass\n print(\"Connected from \" + addr[0])\n onlines.update({addr[0]: True})\n go.update({addr[0]: True})\n logging.debug(u'socket connected from '+addr[0])\n rec_thread = threading.Thread(target=receiver, args=(conn, addr), name='receiver')\n rec_thread.daemon = True\n rec_thread.start()\n rec_threads.update({addr[0]:rec_thread})\n pings.update({addr[0]:time.time()})\n ping_thread = threading.Thread(target=pinger, args=(conn, addr), name='pinger')\n ping_thread.daemon = True\n ping_thread.start()\n except socket.error as err:\n print(\"socket error: %s\" % str(err))\n logging.error(\"connector socket error: \"+str(err))\n except Exception as ex:\n print(\"ошибка коннектера: %s\" % str(ex))\n logging.error(\"connector error: \"+str(ex))\n\n#пингующий поток\ndef pinger(conn, addr):\n global go\n global onlines\n global rec_threads\n global reloads\n global pings\n while go[addr[0]]:\n try:\n send(conn, {\"action\" : \"ping\"})\n time.sleep(10)\n print(time.time()-pings[addr[0]])\n if(time.time()-pings[addr[0]]>40 or reloads[addr[0]]):\n logging.error(u'server is not avaliable, disconnect')\n onlines[addr[0]]=False\n go[addr[0]]=False\n sockclose(conn)\n while rec_threads[addr[0]].isAlive():\n pass\n reloads.pop(addr[0])\n rec_threads.pop(addr[0])\n onlines.pop(addr[0])\n except socket.error as err:\n print(\"pinger socket error: %s\" % str(err))\n logging.error(\"pinger socket error: \"+str(err))\n except Exception as ex:\n print(\"ошибка пингера: %s\" % str(ex))\n logging.error(\"pinger error: \"+str(ex))\n go.pop(addr[0])\n\ndef parseconnector():\n global event\n global parse_thread\n while connect:\n try:\n while parse_thread.isAlive():\n pass\n logging.debug(u'restart parseconnector')\n event = True\n parse_thread=threading.Thread(target=eventparser, name=\"eventparser\")\n parse_thread.daemon = True\n parse_thread.start()\n except socket.error as err:\n print(\"parseconnector socket error: %s\" % str(err))\n logging.error(\"parseconnector socket error: \"+str(err))\n except Exception as ex:\n print(\"ошибка парс коннектера: %s\" % str(ex))\n logging.error(\"parseconnector error: \"+str(ex))\n\n#главная функция\nif __name__ == '__main__':\n try:\n configure()\n sock = socket.socket()\n sock.bind((\"\", 7676))\n sock.listen(10)\n astercon=connectToAsterisk(\"asterisk\", \"asterisk\")\n connect=True\n main_thread = threading.Thread(target=connector, args=(sock, connect), name=\"connector\")\n main_thread.daemon = True\n main_thread.start()\n event = True\n parse_thread=threading.Thread(target=eventparser, name=\"eventparser\")\n parse_thread.daemon = True\n parse_thread.start()\n pconn_thread = threading.Thread(target=parseconnector, name=\"parseconnector\")\n pconn_thread.daemon = True\n pconn_thread.start()\n logging.debug(u'Start keyboard listening')\n cmd=input(\"AsteriskController:>>\")\n while cmd != \"stop\":\n cmd = input(\"AsteriskController:>>\")\n finally:\n connect = False\n event = False\n asterping = False\n print(\"Asterisk controller is going to shutdown now. You can check logs in \" + logfile)\n while main_thread.isAlive():\n pass\n sock.close()\n logging.debug(u'socket closed')\n","sub_path":"phoneserver/callchat.py","file_name":"callchat.py","file_ext":"py","file_size_in_byte":14413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"362815006","text":"from odoo import models, fields, api, _\n\n\nclass EmployeeScheduler(models.TransientModel):\n _name = 'hr.employee.schedule.wizard'\n\n #employee_category_ids = fields.Many2many('hr.employee.category')\n project_id = fields.Many2one(\n comodel_name=\"project.project\",\n string=_(\"Project\"),\n )\n\n employee_ids = fields.Many2many(\n comodel_name='hr.employee'\n )\n\n visit_ids = fields.Many2many(\n comodel_name='visit.visit'\n )\n\n use_all_visits = fields.Boolean(\n string=_(\"Apply to all visits\"),\n default=False\n )\n\n @api.multi\n def bulk_assign_employees_to_visits(self):\n # self is the wizard\n self.ensure_one()\n\n if self.use_all_visits:\n self.visit_ids = [(6, 0, self.project_id.visit_ids.ids)]\n\n # DEPRECATE\n #for employee in self.employee_ids:\n # for visit in self.visit_ids:\n # visit.write({\n # 'employee_ids': [(4, employee.id)],\n # 'selection_flag': False,\n # })\n\n for visit in self.visit_ids:\n required = visit.employees_required\n scheduled = visit.employees_scheduled\n for employee in self.employee_ids:\n if scheduled < required:\n visit.write({\n 'employee_ids': [(4, employee.id)],\n })\n scheduled = visit.employees_scheduled\n return True\n\n @api.multi\n def bulk_remove_employees_from_visits(self):\n self.ensure_one()\n\n if self.use_all_visits:\n self.visit_ids = [(6, 0, self.project_id.visit_ids.ids)]\n\n for employee in self.employee_ids:\n for visit in self.visit_ids:\n visit.write({\n 'employee_ids': [(3, employee.id)],\n 'selection_flag': False,\n })\n return True\n","sub_path":"xrma_visits_scheduling/models/hr_scheduling.py","file_name":"hr_scheduling.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"333368270","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport os\nimport sys\nimport time\nimport math\nimport csv\n\nimport multiprocessing\nimport logging\nfrom itertools import product, repeat\nimport optparse\n\nimport rasterio\nfrom rasterio import windows\nfrom rasterio.enums import Resampling\nfrom rasterio.mask import mask\n\nimport pandas as pd\nimport geopandas as gpd\nimport numpy as np\nimport fiona\nfrom shapely import geometry\n\n#######################\n#### FUNCTIONS ########\n#######################\n\ndef grid_calc(width, height, stride):\n #get all the upper left (ul) pixel values of our chips. Combine those into a list of all the chip's ul pixels. \n #NOTE: THESE ARE THE OPPOSITE OF WHAT I THINK THEY SHOULD BE (HEIGHT/WIDTH SWAPPED)\n #I DON\"T KNOW WHY IT WORKS DONT TOUCH THIS FUNCTION UNLESS YOURE GOING TO OWN IT.\n x_chips = height // stride\n x_ul = [stride * s for s in range(x_chips)]\n\n y_chips = width // stride\n y_ul = [stride * s1 for s1 in range(y_chips)]\n\n #xy_ul = product(x_ul, y_ul) #this is the final list of ul pixel values\n print(f\"x chips: {len(x_ul)}\")\n print(f\"y chips: {len(y_ul)}\")\n\n xy_ul = []\n for x in x_ul:\n for y in y_ul:\n xy_ul.append((x, y))\n\n #print(f\"x/y ul len: {len(x_ul)} / {len(y_ul)}\")\n #print(f\"y * x = {len(x_ul) * len(y_ul)}\")\n #print(f\"xy_ul len: {len(xy_ul)}\")\n\n return xy_ul\n\ndef build_window(in_src, in_xy_ul, in_chip_size, in_chip_stride):\n\n out_window = windows.Window(col_off = in_xy_ul[0],\n row_off = in_xy_ul[1],\n width=in_chip_size,\n height=in_chip_size)\n \n out_win_transform = windows.transform(out_window, in_src.transform)\n #print(out_win_transform)\n \n col_id = in_xy_ul[1] // in_chip_stride\n row_id = in_xy_ul[0] // in_chip_stride\n out_win_id = f'{col_id}_{row_id}'\n \n out_win_bounds = windows.bounds(out_window, out_win_transform)\n #print(out_win_bounds)\n \n return out_window, out_win_transform, out_win_bounds, out_win_id\n\ndef make_gdf(polygons, attr_dict, out_crs, out_gdf_path='none'):\n #print(f\"out_gdf_path: {out_gdf_path}\")\n gs = gpd.GeoSeries(polygons)\n \n df = pd.DataFrame(data=attr_dict)\n \n gdf = gpd.GeoDataFrame(df, geometry=gs)\n gdf.crs=out_crs\n \n #optionally write a file if the path was provided. NOTE: COULD EXPAND THIS TO HANDLE FORMATS OTHER THAN GPKG.\n if out_gdf_path != 'none':\n if os.path.exists(os.path.dirname(os.path.abspath(out_gdf_path))):\n print(f\"Writing: {out_gdf_path}\")\n \n gdf.to_file(out_gdf_path, driver='GPKG')\n \n #regardless of writing output, return GDF\n return gdf\n\ndef write_jpeg(in_data, in_count, in_size, in_win_transform, in_src_crs, in_out_path):\n #building a custom jpeg profile for our chip due to some gdal/rasterio bugs in walking from input geotiff to output jpeg\n profile={'driver': 'JPEG',\n 'count': in_count,\n 'dtype': rasterio.ubyte,\n 'height': in_size,\n 'width': in_size,\n 'transform': in_win_transform,\n 'crs': in_src_crs}\n \n #write the chip\n with rasterio.open(in_out_path, 'w', **profile) as dst:\n dst.write(in_data)\n\ndef coords_2_pix(in_bounds, in_affine):\n xmin = in_bounds[0]\n ymin = in_bounds[1]\n xmax = in_bounds[2]\n ymax = in_bounds[3]\n \n xs = (xmin, xmax)\n ys = (ymin, ymax)\n \n pix_coords = rasterio.transform.rowcol(in_affine, xs, ys)\n \n pix_bounds = (pix_coords[0][1], pix_coords[1][1], pix_coords[0][0], pix_coords[1][0])\n \n return pix_bounds\n\ndef coords_2_pix_gdf(gdf):\n gdf['x_min'] = gdf.bounds.minx\n gdf['y_min'] = gdf.bounds.miny\n gdf['x_max'] = gdf.bounds.maxx\n gdf['y_max'] = gdf.bounds.maxy\n \n gdf['px_x_min'] = (gdf['x_min'] - gdf['a2']) // gdf['a0']\n gdf['px_x_max'] = (gdf['x_max'] - gdf['a2']) // gdf['a0']\n \n #NOTE: in coordinates we the origin as the bottom left corner. In pixel coordinates, we set the origin at the top left corner.\n #Anyways, we're flipping our pix min/max here so that our origin starts at the top right corner.\n gdf['px_y_max'] = (gdf['y_min'] - gdf['a5']) // gdf['a4']\n gdf['px_y_min'] = (gdf['y_max'] - gdf['a5']) // gdf['a4']\n \n return gdf\n\ndef pix_2_xy(in_bounds, in_affine):\n xmin = in_bounds[0]\n ymin = in_bounds[1]\n xmax = in_bounds[2]\n ymax = in_bounds[3]\n \n xs = (xmin, xmax)\n ys = (ymin, ymax)\n \n pix_coords = rasterio.transform.xy(in_affine, xs, ys)\n \n pix_bounds = (pix_coords[0][0], pix_coords[1][1], pix_coords[0][1], pix_coords[1][0] )\n #print(f\"pix bounds: {pix_bounds}\")\n return pix_bounds\n\ndef return_intersection(in_tindex, in_annotations, unique_annotation_id):\n inter = gpd.overlay(in_tindex, in_annotations)\n inter['intersect_area'] = inter['geometry'].area\n filter_partial_annotations = inter[inter['intersect_area'] == 1.0]\n remove_duplicates = filter_partial_annotations.drop_duplicates(subset=unique_annotation_id)\n \n return remove_duplicates\n\ndef create_cindex(in_file, in_size, in_stride, in_out_dir):\n basename = os.path.splitext(os.path.basename(in_file))[0]\n #print(basename)\n #print(f\"{in_file}, {in_size}, {in_stride}, {in_out_dir}\")\n gdfs = []\n\n with rasterio.open(in_file, 'r') as src:\n print(f\"Initial Width/Height: {src.width}, {src.height}\")\n #print(f\"src height/width: {src.height}/{src.width}\")\n #print(f\"src bounds: {src.bounds}\")\n #print(f\"src transform: {src.transform}\")\n \n upper_left_grid = grid_calc(src.width, src.height, in_stride)\n \n for ul in upper_left_grid:\n #note, we're currently working with slices because I can't make col_off, row_off work. Code needs to be reworked to naturally work with slices\n col_start = ul[0]\n col_stop = ul[0] + in_size\n row_start = ul[1]\n row_stop = ul[1] + in_size\n #slices = (col_start, row_start, col_stop, row_stop)\n colrow_bounds = (col_start, row_start, col_stop, row_stop)\n \n win, win_transform, win_bounds, win_id = build_window(src, ul, in_size, in_stride)\n\n #NOTE: I had to write my own affine lookup to get bounding boxs from windows (pix_2_coords). Rasterio's windows.bounds(win, win_transform) \n #caused every overlpping tile to shift 256 pix in the x and y direction (removed overlap, doubled area covered by chip tindex)\n #therefore, the win_bounds variable above should not currently be used. I need to investigate further.\n \n #ret = pix_2_coords(slices, src.transform)\n\n ret = pix_2_xy(colrow_bounds, src.transform)\n #print(f\"ret: {ret}\")\n #create and store the chip's geometry (the bounding box of the image chip)\n envelope = geometry.box(*ret)\n geometries=[]\n geometries.append(envelope)\n \n #store the image basename. No real reason, just comes in handy alot.\n attr_basename=[]\n attr_basename.append(in_file)\n \n #store chip name as an attribute in the cindex attribute table\n chip_name = f\"{basename}_{win_id}\"\n attr_filename = []\n attr_filename.append(chip_name)\n \n # store affine values as attributes in the cindex attribute table\n px_width = []\n row_rot = []\n col_off = []\n col_rot = []\n px_height = []\n row_off = []\n \n px_width.append(win_transform[0])\n row_rot.append(win_transform[1])\n col_off.append(win_transform[2])\n col_rot.append(win_transform[3])\n px_height.append(win_transform[4])\n row_off.append(win_transform[5])\n \n #create a single chip feature with attributes and all\n attr_dict = {}\n attr_dict['basename'] = attr_basename\n attr_dict['filename'] = attr_filename\n attr_dict['a0'] = px_width\n attr_dict['a1'] = row_rot\n attr_dict['a2'] = col_off\n attr_dict['a3'] = col_rot\n attr_dict['a4'] = px_height\n attr_dict['a5'] = row_off\n \n chip_gdf = make_gdf(geometries, attr_dict, src.crs)\n\n #append our single chip feature to a list of all chips. Later we will merge all the single chips into a big chip index (cindex).\n gdfs.append(chip_gdf)\n \n #merge all those little chip features together into our master cindex for the input image \n cindex_gdf_path = os.path.join(in_out_dir, f\"{basename}_chip_tindex.gpkg\")\n cindex_gdf = gpd.GeoDataFrame(pd.concat(gdfs, ignore_index=True))\n cindex_gdf.crs = src.crs\n cindex_gdf.to_file(cindex_gdf_path, driver='GPKG')\n\n return cindex_gdf\n\ndef write_annotations(in_gdf, out_path='none'):\n coord_gdf = coords_2_pix_gdf(in_gdf)\n \n #set our columns/column order\n out_gdf = coord_gdf[['filename', 'x_min', 'y_min', 'x_max', 'y_max', \n 'px_x_min', 'px_y_min', 'px_x_max', 'px_y_max', \n 'label_name', 'label', 'label_int']]\n \n if out_path != 'none':\n out_gdf.to_csv(out_path, index=False)\n \n return out_gdf\n\ndef mask_raster(in_poly, src_raster, in_out_path):\n try:\n with rasterio.open(src_raster, 'r') as src:\n out_data, out_transform = mask(src, [in_poly], crop=True)\n except:\n print(\"ERROR 1 in mask_raster:\")\n print(\"Could not read cropped data/transform.\")\n sys.exit(0)\n\n write_jpeg(out_data, src.count, out_data.shape[1], out_transform, src.crs, in_out_path)\n\ndef backbone(args, in_f):\n try:\n #print(f\"backbone: {in_f}\")\n logging.info(f\"backbone: {in_f}\")\n #unpack our args list.\n anno_path = args[0] \n in_anno = gpd.read_file(anno_path)\n \n size = args[1]\n stride = args[2]\n out_dir = args[3]\n #print(f\"{in_anno}, {size}, {stride}, {out_dir}\")\n except:\n print(\"Error loading arguments into backbone. Check your args.\")\n\n try:\n logging.info(f\"cindex: {in_f}\")\n #Chip out our image, return a cindex\n cindex = create_cindex(in_f, size, stride, out_dir)\n except:\n print(\"Error in cindex operation!\")\n\n try:\n logging.info(f\"intersect: {in_f}\")\n #find all the annotations that intersect each chip. Filter chips with no annotations, filter annotations that are not fully contained within a chip.\n intersect = return_intersection(cindex, in_anno, 'unique_pt_id')\n except:\n print(\"Error in intersect operation!\")\n\n try:\n logging.info(f\"writing positive files: {in_f}\")\n #generate a list of positive chips in the annotation database.\n pos_chips = intersect['filename'].unique().tolist()\n \n pos_chips_gdf = cindex[cindex['filename'].isin(pos_chips)]\n #print(pos_chips_gdf.head())\n\n for i, row in pos_chips_gdf[['geometry', 'basename','filename']].iterrows():\n polygon = row[\"geometry\"]\n src_raster = row['basename']\n out_raster_path = os.path.join(out_dir, f\"{row['filename']}.jpg\")\n #print(f\"{polygon}, {src_raster}, {out_raster_path}\")\n #this also write our positive image chip to a jpeg located at out_raster_path\n mask_raster(polygon, src_raster, out_raster_path)\n except:\n print(\"Error when writing images!\")\n print(f\"polygon: {polygon}\")\n print(f\"src_raster: {src_raster}\")\n print(f\"out_raster_path: {out_raster_path}\")\n\n logging.info(f\"backbone COMPLETE: {in_f}\")\n #return our annotations to be bound into a island-wide annotation data set.\n \n return intersect\n\n#######################\n#### END FUNCTIONS ####\n#######################\nif __name__ == \"__main__\":\n #handle our input arguments\n parser = optparse.OptionParser()\n\n parser.add_option('-f', '--filelist',\n action=\"store\", dest=\"file_list\",\n type='string', help=\"A txt list of absolute file paths, one file per line. Must be tifs.\")\n\n parser.add_option('-o', '--outdir',\n action='store', dest='usr_out_dir',\n type='string', help='An out directory to stash files. Images, tile indexes, logfiles, etc.')\n\n parser.add_option('-t', '--chipsize',\n action='store', dest='usr_size',\n type='int', default=512,\n help='Size of image chips in pixel (ie. 512 is 512x512px chips.)')\n\n parser.add_option('-s', '--stride',\n action='store', dest='usr_stride',\n type='int', default=256,\n help='Amount of image chip overlap in pixels (ie 256 is 50 percent overlap with a chipsize of 512)')\n\n parser.add_option('-a', '--annotations',\n action='store', dest='in_annotation',\n type='string',\n help='path to a geopackage containing marine debris annotation envelopes. Note: this probably wont work with all annotations. Use preapproved annos for now.')\n\n options, args = parser.parse_args()\n\n #setup logging\n log_name = r'log.txt'\n log_name = os.path.join(options.usr_out_dir, log_name)\n logging.basicConfig(level=logging.INFO,\n format=\"%(asctime)s %(levelname)s %(message)s\", \n datefmt=\"%H:%M:%S\",\n handlers=[logging.FileHandler(log_name)])\n\n #do some checks to make sure we can find inputs and outputs.\n if os.path.exists(options.usr_out_dir):\n pass\n else:\n print('ERROR: Cannot find out directory. Abort.')\n logging.error('ERROR: Cannot find out directory. Abort.')\n sys.exit(0)\n\n if os.path.exists(options.file_list):\n pass\n else:\n print('ERROR: Cannot find input filelist. Abort.')\n logging.error('ERROR: Cannot find input filelist. Abort.')\n sys.exit(0)\n\n if os.path.exists(options.in_annotation):\n pass\n else:\n print('ERROR: Cannot find input annotations. Abort.')\n logging.error('ERROR: Cannot find input annotations. Abort.')\n sys.exit(0)\n\n #print(\"exists\")\n '''\n with open(options.file_list, 'r') as f:\n in_paths = [line.strip() for line in f]\n \n for fi in in_paths:\n inter = backbone((options.in_annotation, \n options.usr_size, \n options.usr_stride, \n options.usr_out_dir),\n fi)\n '''\n #open our file list and arguments. Zip them up into a list of arguments and a input file that feeds into multiprocessing's starmap.\n with open(options.file_list, 'r') as f:\n in_paths = [line.strip() for line in f]\n\n args = [[options.in_annotation, options.usr_size, options.usr_stride, options.usr_out_dir]] * len(in_paths)\n zipped = zip(args, in_paths)\n\n #print(f\"args {args}\")\n\n #start the pool. Each entry in results will contain a gdf of all the resulting chips.\n pool=multiprocessing.Pool(processes=8)\n map_results = pool.starmap_async(backbone, zipped)\n\n \n\n while not map_results.ready():\n print(f\"retile_for_deeplearning_V2.py | {map_results._number_left} of {len(in_paths)} files remain.\")\n time.sleep(5)\n\n pool.close()\n pool.join()\n\n results = map_results.get()\n\n print(f\"Writing final annotations.\")\n logging.info(f\"Writing final annotations.\")\n #merge all the pd.Dataframes, convert to gpd.GeoDataFrame\n results_df = pd.concat(results, ignore_index=True)\n results_gdf = gpd.GeoDataFrame(results_df, geometry='geometry')\n #print(results_df.head())\n \n #write annotations to csv\n out_path = os.path.join(options.usr_out_dir, 'final_annotations.csv')\n write_annotations(results_gdf, out_path)\n\n print(\"SUCCESS!\")\n logging.info(f\"SUCCESS!\")\n\n#out_df = results_df[['basename', 'filename', \n#'x_min', 'y_min', 'x_max', 'y_max', \n#'px_x_min', 'px_y_min', 'px_x_max', 'px_y_max', \n#'label_name', 'label', 'label_int']]\n","sub_path":"preprocessing/retile_for_deeplearning_V2.py","file_name":"retile_for_deeplearning_V2.py","file_ext":"py","file_size_in_byte":16098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"327382699","text":"# from . import basic_img as bimg\n#\n# img = bimg.basic_img(\"../static/csgo.jpg\")\n# img.color2gray()\n#\n\nimport cv2\n\ntry:\n # im = cv2.imread(self.img_path)\n im = cv2.imread(\"wrong_path.jpg\")\nexcept OSError as e:\n print(\"Error:\" + e)\n\nprint(im)","sub_path":"img_proc/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"392454148","text":"online = {}\r\ns =0\r\nwhile True:\r\n s = list([int(x) for x in input().split()])\r\n if s[0] == 1:\r\n online[s[1]] = 1\r\n elif s[0] == 2:\r\n if s[1] not in online:\r\n print(0)\r\n else:\r\n print(1)\r\n elif s[0] == 0 :\r\n break","sub_path":"Wecode/19521216/Week 2/Problem_5.py","file_name":"Problem_5.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"582218746","text":"import pygame\nfrom pygame.locals import *\nimport sys\nimport random\n\n# SIZE OF THE SCREEN\nWIDTH = 600\nHEIGHT = 500\n\n# FPS\nFPS = 60\n\nUP, DOWN, UPRIGHT, DOWNRIGHT, DOWNLEFT, UPLEFT = 0,1,2,3,4,5\nSTART, STOP = 0, 1\n\n# Speed of Paddle\nPADDLEMOVEMENT = 10\n# Speed of Ball\nBALLMOVEMENT = 3\n\n# SCREEN\nSCREEN = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)\n\n# Position X of the Paddle\nPADDLESTARTPOS = 30\nPADDLEWIDTH = 10\nPADDLEHEIGHT = 60\n\nBALLSIZE = 7\n\nclass Ball():\n def __init__(self):\n # Sets random start orientation\n self.orientation = random.randint(2,5)\n\n self.draw(WIDTH/2, HEIGHT/2)\n \n def update(self):\n xPosition = self.rect.center[0]\n yPosition = self.rect.center[1]\n\n halfHeight = self.rect.width/2\n halfWidth = self.rect.width/2\n\n # Ball hit top border\n if((yPosition - halfHeight - BALLMOVEMENT) < 0):\n self.doWhenHitBorder(self.orientation)\n\n # Ball hit bottom border\n if((yPosition + halfHeight + BALLMOVEMENT) > HEIGHT):\n self.doWhenHitBorder(self.orientation) \n\n if(self.orientation == UPRIGHT):\n self.dy = -BALLMOVEMENT\n self.dx = BALLMOVEMENT\n if(self.orientation == DOWNRIGHT):\n self.dy = BALLMOVEMENT\n self.dx = BALLMOVEMENT\n if(self.orientation == UPLEFT):\n self.dy = -BALLMOVEMENT\n self.dx = -BALLMOVEMENT\n if(self.orientation == DOWNLEFT):\n self.dy = BALLMOVEMENT\n self.dx = -BALLMOVEMENT\n\n self.draw(xPosition + self.dx, yPosition + self.dy)\n\n def doWhenHitBorder(self, direction):\n if(direction == UPRIGHT):\n self.orientation = DOWNRIGHT\n elif(direction == UPLEFT):\n self.orientation = DOWNLEFT\n elif(direction == DOWNRIGHT):\n self.orientation = UPRIGHT\n elif(direction == DOWNLEFT):\n self.orientation = UPLEFT\n\n def doWhenHitPaddle(self):\n if(self.orientation == DOWNRIGHT): self.orientation = DOWNLEFT\n elif(self.orientation == UPRIGHT): self.orientation = UPLEFT\n elif(self.orientation == UPLEFT): self.orientation = UPRIGHT\n elif(self.orientation == DOWNLEFT): self.orientation = DOWNRIGHT\n\n def draw(self, x, y):\n self.rect = pygame.draw.circle(SCREEN, (255,255,255), (x, y), BALLSIZE)\n\nclass Paddle():\n def __init__(self, left):\n self.left = left\n self.top = HEIGHT/2 - PADDLEHEIGHT/2\n \n self.dy = 0\n self.draw(self.left, self.top)\n \n def update(self):\n # New top is actual Y Position + new Y Position\n newTop = self.top + self.dy\n\n # Limit movement out of bounds\n if((newTop + PADDLEHEIGHT) > HEIGHT):\n newTop = HEIGHT - PADDLEHEIGHT\n if(newTop<0):\n newTop = 0\n\n self.top = newTop\n self.draw(self.left, newTop)\n \n def draw(self, left, top):\n self.rect = pygame.draw.rect(SCREEN, (255,255,255), (left, top, PADDLEWIDTH, PADDLEHEIGHT))\n\n def steer(self, direction, operation):\n if operation == STOP:\n self.dy = 0\n elif operation == START:\n self.dy = {UP: -PADDLEMOVEMENT, DOWN: PADDLEMOVEMENT}[direction]\n\nclass Game():\n \n def __init__(self):\n # Initialize Pygame\n pygame.init()\n \n # Fill background\n self.background = pygame.Surface(SCREEN.get_size()).convert()\n\n # Initialize clock\n self.clock = pygame.time.Clock()\n\n # Font configuration\n self.font = pygame.font.SysFont(\"monospace\", 40)\n \n def quit(self):\n pygame.quit()\n sys.exit(0)\n\ndef main():\n # Creates the game\n game = Game()\n\n # Define all Sprites\n ball = Ball()\n barLeft = Paddle(PADDLESTARTPOS)\n barRight = Paddle(WIDTH - PADDLESTARTPOS - 20)\n\n # Define all Texts\n textPlayer1Wins = game.font.render(\"Player 1 Wins\", True, (255,255,255))\n textPlayer2Wins = game.font.render(\"Player 2 Wins\", True, (255,255,255))\n\n while True:\n # Define FPS\n game.clock.tick(FPS)\n\n # Handle Keyboard events\n for event in pygame.event.get():\n if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):\n game.quit()\n if event.type == KEYDOWN:\n if event.key == K_DOWN: barRight.steer(DOWN, START)\n if event.key == K_UP: barRight.steer(UP, START)\n if event.key == K_s: barLeft.steer(DOWN, START)\n if event.key == K_w: barLeft.steer(UP, START)\n\n if event.type == KEYUP:\n if event.key == K_DOWN: barRight.steer(DOWN, STOP)\n if event.key == K_UP: barRight.steer(UP, STOP)\n if event.key == K_s: barLeft.steer(DOWN, STOP)\n if event.key == K_w: barLeft.steer(UP, STOP)\n\n # If ball hit the Left Paddle or Right Paddle\n if((ball.rect.colliderect(barLeft.rect)) or (ball.rect.colliderect(barRight.rect))):\n ball.doWhenHitPaddle()\n\n # Draw background\n SCREEN.blit(game.background, (0, 0))\n\n # If Ball hits left border\n if(ball.rect[0] <= BALLMOVEMENT):\n SCREEN.blit(textPlayer2Wins,(WIDTH / 2 - (textPlayer2Wins.get_width() / 2), HEIGHT / 2 - (textPlayer2Wins.get_height() / 2)))\n pygame.display.update()\n pygame.time.wait(3000)\n ball = Ball()\n\n # If Ball hits right border\n if(ball.rect[0] >= (WIDTH - BALLMOVEMENT - ball.rect.width)):\n SCREEN.blit(textPlayer1Wins,(WIDTH / 2 - (textPlayer1Wins.get_width() / 2), HEIGHT / 2 - (textPlayer1Wins.get_height() / 2)))\n pygame.display.update()\n pygame.time.wait(3000)\n ball = Ball()\n\n barLeft.update()\n barRight.update()\n ball.update()\n\n pygame.display.update()\n\n game.quit()\n\nif __name__ == '__main__':\n main()","sub_path":"pong.py","file_name":"pong.py","file_ext":"py","file_size_in_byte":5974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"506306568","text":"# this is 13th python programme.\n# Created by me.\n# python3\n\nfileName = '13file2.csv'\nWRITE = 'w' # w+/r+ for readwrite\nAPPEND = 'a' # b for binary files(images)\nnumberStudent = int(input(\"Enter no of student added :\"))\n\nfor data in range(numberStudent):\n data = input(\"Enter Roll,Name,Div :\")\n file = open(fileName, mode=APPEND)\n file.write(data+'\\n')\n file.close()\n\nprint(\"file successfully written.\")","sub_path":"LICENSE.md/13file2.py","file_name":"13file2.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"447900406","text":"# -*- coding:utf-8 -*-\n\nclass Solution:\n \"\"\"\n Problem:\n 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,\n 例如,如果输入如下矩阵:\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n 13 14 15 16\n 则依次打印出数字:\n 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.\n -----------------------------------------\n Think:\n 1、观察数据从第一行的第一个元素开始,到第一行的最后一个元素,然后再以列开始,直到16.\n 2、然后再从16输出到13,输出到5,输出到7.是成绩达到11,10\n\n\n -----------------------------------------\n Idea:\n 1、有4个方向,方向的index枚举[(0,1), (1,0), (0,-1),(-1,0)]\n 2、一个方向状态:dircindex,保存当前方向,初始化为0\n 3、判断是否转向条件:下一个元素越界,或者元素不存在,则转向\n 4、访问元素的操作:\n 插入result表,并对元表进行赋值为None,用来记录已经访问过。\n 5、跳出条件:\n 下一个元素越界或者不存在,则结束计算\n 6、有点类似DFS,尝试用DFS的思想去解决\n\n -----------------------------------------\n Code:\n\n\n -----------------------\n 运行时间:\n 占用内存:\n \"\"\"\n # matrix类型为二维列表,需要返回列表\n def printMatrix(self, matrix):\n if matrix is None:\n return None\n\n direc = [(0,1), (1,0), (0,-1),(-1,0)]\n direcindex = 0 #默认第一个方向\n i,j = 0,0 #默认第一个元素\n result = []\n rowlen = len(matrix) #行长度\n columnlen = len(matrix[0]) #列长度\n\n\n bhasnext = True\n while bhasnext and i < rowlen and j < columnlen:\n print(\"i的值:%d,j的值:%d.\" %(i, j))\n print(\"direc的值:%d\" %(direcindex))\n if matrix[i][j]: #当前元素存在\n result.append(matrix[i][j]) #插入元素\n matrix[i][j] = None #置空,状态为已访问\n\n tempi = i + direc[direcindex][0]\n tempj = j + direc[direcindex][1]\n\n #处理拐弯\n if (tempi >= rowlen) or (tempj >= columnlen) or \\\n (not matrix[tempi][tempj]): #越界和不存在下一个值\n direcindex = (direcindex + 1) % 4 #方向旋转\n\n i = i + direc[direcindex][0] #更新i\n j = j + direc[direcindex][1] #更新j\n if (i >= rowlen) or (j >= columnlen) or \\\n not matrix[i][j]: #下个元素不存在则break\n bhasnext = False\n\n return result\n\nif __name__ == '__main__':\n sol = Solution()\n # matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]\n matrix = [[1]]\n print(sol.printMatrix(matrix))\n","sub_path":"code/train/箭指Offer/src/顺时针打印矩阵.py","file_name":"顺时针打印矩阵.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"625175065","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# __author__ = \"Lex\"\n# Date: 2017/12/20\n\n# from multiprocessing import Process\n# import time\n#\n# class Piao(Process):\n#\n# def __init__(self, name):\n# super().__init__()\n# self.name = name\n#\n# def run(self):\n# print('%s is piaoing'% self.name)\n# time.sleep(2)\n# print('%s piao end'% self.name)\n# if __name__ == '__main__':\n# p=Piao('egon')\n# p.start()\n#\n# p.terminate() #关闭进程,不会立即关闭,所以is_alive立刻查看的结果可能还是存活\n# print(p.is_alive()) #结果为Ture\n#\n# time.sleep(1)\n#\n# print(p.is_alive()) #结果为Flase\n\n\nfrom multiprocessing import Process\nimport time\n\nclass Piao(Process):\n\n def __init__(self,name):\n self.name = name\n super().__init__()\n\n def run(self):\n print('%s is piaoing'% self.name)\n time.sleep(2)\n print('%s piao end'%self.name)\n\nif __name__ == '__main__':\n\n p=Piao('egon')\n p.start()\n print('PID',p.pid)\n\n# PID 57104\n# Piao-1 is piaoing\n# Piao-1 piao end","sub_path":"Day37/Process对象的其他方法或属性.py","file_name":"Process对象的其他方法或属性.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"381101497","text":"# coding=utf-8\r\nimport sys, os, shutil\r\n\r\n\r\n# 安装包文件名\r\nctsVer = '1.086'\r\n\r\neggFile = 'CTSlib-' + ctsVer + '_py' + str(sys.version_info[0]) + str(sys.version_info[1]) + '.egg'\r\n\r\n# 获取安装包的绝对路径,与setyp.py在同一目录中\r\nif os.name == \"nt\":\r\n eggPath = os.path.abspath(os.path.split(os.path.realpath(__file__))[0] + '\\\\' + eggFile)\r\nelse:\r\n eggPath = os.path.abspath(os.path.split(os.path.realpath(__file__))[0] + '/' + eggFile)\r\n\r\ndef uninstall():\r\n '''\r\n 卸载CTSlib安装包\r\n '''\r\n \r\n #在系统环境变量中,查找ctslib安装路径\r\n ctsPath = []\r\n for x in sys.path:\r\n x = os.path.abspath(x)\r\n if x.lower().find('ctslib') > 0:\r\n ctsPath.append(x)\r\n print(x)\r\n \r\n if (len(ctsPath) == 0):\r\n print (u'CTSlib未安装')\r\n return\r\n \r\n #切换当前工作目录\r\n if os.name == \"nt\":\r\n os.chdir(sys.prefix + '\\Scripts')\r\n \r\n #执行卸载命令\r\n result = os.popen('easy_install --m CTSlib')\r\n \r\n #打印卸载信息\r\n print(result.read())\r\n \r\n #删除ctslib安装目录\r\n for x in ctsPath:\r\n print(('remove dir:' + x))\r\n shutil.rmtree(x, True)\r\n \r\n noRemove = []\r\n #验证卸载是否成功\r\n for x in ctsPath:\r\n if (os.path.exists(x)):\r\n noRemove.append(x)\r\n \r\n if (len(noRemove) != 0):\r\n print (u'卸载失败,以下目录未删除成功:')\r\n for x in noRemove:\r\n print (x)\r\n else:\r\n print (u'卸载成功')\r\n \r\ndef install():\r\n '''\r\n 安装CTSlib安装包\r\n '''\r\n\r\n #切换当前工作目录\r\n if os.name == \"nt\":\r\n os.chdir(sys.prefix + '\\Scripts')\r\n\r\n #执行安装命令\r\n result = os.popen('easy_install ' + eggPath)\r\n \r\n #打印安装信息\r\n print(result.read())\r\n\r\n #安装完成\r\n print(u'安装成功')\r\n\r\n\r\nif len(sys.argv) >= 2:\r\n if (sys.argv[1] == 'install'):\r\n if (not os.path.exists(eggPath)):\r\n print((u'文件不存在:' + eggPath))\r\n exit()\r\n\r\n print (u'开始卸载旧版本CTSlib安装包')\r\n uninstall()\r\n \r\n print (u'开始安装')\r\n install()\r\n \r\n elif(sys.argv[1] == 'uninstall'):\r\n print (u'开始卸载')\r\n uninstall()\r\n \r\n else:\r\n print (u'参数错误,请输入参数 install/uninstall')\r\n \r\nelse:\r\n uninstall()\r\n print (u'请输入参数 install/uninstall')\r\n","sub_path":"PythonAPI_src/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"60680270","text":"import gdb\nfrom utils.typeinfo import TypeInfo\n\nclass Value (TypeInfo):\n def __init__ (self, val):\n super(Value, self).__init__(val)\n self.types = {\n 0: 'InvalidType',\n 1: 'IntegerType',\n 2: 'RealType',\n 3: 'BooleanType',\n 4: 'StringType',\n 5: 'RealArrayType',\n 6: 'RefType',\n 7: 'ContainerType'\n }\n\n\n def to_string(self):\n t = self.val['mType']\n h = self.val['mHolder']\n s = ''\n if t == 0:\n s = 'Invalid Type'\n elif t == 1:\n s = str(h['i'])\n elif t == 2:\n s = str(h['d'])\n elif t == 3:\n s = str(h['b'])\n elif t == 4:\n string = h['s']\n if string:\n s = string.dereference()\n elif t == 5:\n s = 'real array'\n elif t == 6:\n r = h['refp']\n target_type = gdb.lookup_type('object::Ref').pointer()\n s = str(r.address.cast(target_type))\n elif t == 7:\n s == 'container'\n return s\n","sub_path":"gdb/printers/torch/light/lib/object/_printers/Value.py","file_name":"Value.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"643370416","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 ('cochera', '0021_auto_20141007_1614'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='contacto',\n old_name='persona',\n new_name='titular',\n ),\n migrations.RenameField(\n model_name='vehiculo',\n old_name='persona',\n new_name='titular',\n ),\n migrations.AlterField(\n model_name='lugar',\n name='titular',\n field=models.ForeignKey(verbose_name=b'Titular', blank=True, to='cochera.Persona', null=True),\n ),\n ]\n","sub_path":"cochera/migrations/0022_auto_20141007_2048.py","file_name":"0022_auto_20141007_2048.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"524854650","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 12 16:45:17 2019\n\n@author: ttc\n\"\"\"\n\n# Define Student Class\nclass Student():\n majorSubject = ''\n minorSubject = ''\n CourseList = []\n \n def joinCourse(self, Course):\n self.CourseList.append(Course)\n \n def dropCourse(self, Course):\n self.CourseList.remove(Course)\n \n# Initiate a student object s1\ns1 = Student()\ns2 = Student()\n# Declare s1's major as MIS\ns1.majorSubject = 'MIS'\n\ns2.majorSubject = 'Law'\ns2.minorSubject = 'Commerce'\n\n# s1 join three courses\ns1.joinCourse('Software_Engineering') \ns1.joinCourse('Data_Mining')\ns1.joinCourse('AI')\n\nprint(s1.majorSubject)\nprint(s1.CourseList)\n\n#s1 drop one course\ns1.dropCourse('AI')\nprint(s1.CourseList)\n\n\nprint(s2.majorSubject)\ns2.joinCourse('Introduction to Law') \nprint(s2.CourseList)\n","sub_path":"Student_Class.py","file_name":"Student_Class.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"450363105","text":"from src.abstract_factory.maze_game_af import MazeGame\nfrom src.classes.game_constructor import GameConstructor\n\n\nclass Factory:\n @classmethod\n def run_factory(cls, factory, explode_bomb=False):\n maze_obj = MazeGame().create_maze(factory)\n GameConstructor.construct(maze_obj)\n\n if explode_bomb:\n print('\\n****** Bomb Exploded! - Walls have been damaged... ******\\n')\n maze_obj.rooms[1].bomb_exploded = True\n for side in range(4):\n cur_side = maze_obj.rooms[1].sides[side]\n if 'BombedWall' in str(cur_side):\n cur_side.wall_is_damaged = True\n print('Wall is damaged:', cur_side, cur_side.wall_is_damaged)\n","sub_path":"src/abstract_factory/gameplay_af.py","file_name":"gameplay_af.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"315887946","text":"\"\"\"\nЗадача 2.2:\nСоздать словарь из 10 элементов. Ключи - логины, значения - список из пароля и случайного числа.\nПосле - просить у пользователя ввод.\nЕсли такого логина в словаре нет - создавать, если есть - выводить число из значения.\n\"\"\"\n# Импортируем модуль генерации случайных чисел\nimport random\n\n# Импортируем модуль String для генерации буквенных паролей\nimport string\n\n# создаем список из 10 логинов\nlist21 = ['David', 'Andrey', 'Mark', 'Tatyana', 'Pasha', 'Lena', 'Tim', 'Mira', 'Nadejda', 'Misha']\n\n# создаем строку с набором случайных букв, символов и чисел для генерации пароля\nstr_pw_source = f'{string.ascii_letters}{string.digits}{string.punctuation}'\n\n# Создаем пустой словарь для записи логина, и списка из пароля и числа\ndict21 = {}\n\n# Создаем цикл для записи 10 значений\nfor i in list21:\n # с каждым витком цикла обнуляем список\n list22 = []\n\n # Генерируем пароль\n rand1 = ''.join(random.sample(str_pw_source, 4))\n\n # Генерируем число под паролем\n rand2 = float(random.randint(0, 9999))/100\n\n # записываем пароль и число в список\n list22.append(rand1)\n list22.append(rand2)\n\n # добавляем логин и пару [пароль,число] в словарь\n dict21[i] = list22\n\nprint(\"2.2.1 Выводим словарь с логином и вложенным списком пароль, число \\n\", dict21)\n\n# Просим у пользователя логин\nlgn = input(\"Login:\")\n\n# Проверяем, есть ли ввод среди ключей словаря\nif lgn in dict21:\n # Достаем список пароль значение из словаря по ключу - логину\n l = dict21.get(lgn)\n # Печатаем пароль, чтоб знать что вводить\n print(\"Пароль :\", l[0])\n\n # Запрашиваем пароль\n p = input(\"Введите пароль\")\n\n # Проверяем пароль, если подошел то выводим число\n if p == l[0]:\n print(\"Ваше число:\", l[1])\n else:\n print(\"Неугадали\")\n\n# Если логина нет, то добавляем его\nelse:\n # Добавляем запись в словарь\n dict21.setdefault(lgn, None)\n\n # Печатаем получившийся словарь\n print(\"Теперь словарь выглядит так:\\n\", dict21)\n","sub_path":"P-Ushakov/HW2/HW_2.2.py","file_name":"HW_2.2.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"514580535","text":"# /usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport os\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"UConnector.settings\")\nimport django\ndjango.setup()\nimport time\nimport signal\nimport logging\n\nfrom django.conf import settings\n\nfrom connector.send_message_thread import DataReceiveThread\n\nrunning = True\n\n\ndef action(signum, frame):\n global running\n running = False\n\nif __name__ == '__main__':\n\n signal.signal(signal.SIGINT, action)\n signal.signal(signal.SIGTERM, action)\n\n threads = []\n threads.append(DataReceiveThread('线程B', settings.REDIS_CONFIG['redis_b']))\n threads.append(DataReceiveThread('线程A', settings.REDIS_CONFIG['redis_a']))\n\n for thread in threads:\n thread.start()\n\n while running:\n time.sleep(1)\n\n for thread in threads:\n thread.stop()\n\n logging.info(\"shutdown.\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"333941819","text":"import unittest\n\nfrom parser import *\n\n\nclass TestParser(unittest.TestCase):\n\n def test_parse_cust_name(self):\n cp = ConfigurationParser()\n expected_names = ['CUSTOMER_A', 'CUSTOMER_B', 'CUSTOMER_C']\n parsed_names = cp.parseCustomerNames()\n self.assertEqual(list, type(parsed_names))\n self.assertEqual(expected_names, parsed_names)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"290696868","text":"############\n# Standard #\n############\n\n############\n# External #\n############\nimport pytest\n\n###########\n# Package #\n###########\nfrom .conftest import show_widget\nfrom typhon.func import FunctionPanel, FunctionDisplay\n\nkwargs = dict()\n\n\n@pytest.fixture(scope='module')\ndef func_display():\n # Create mock function\n def foo(first, second: float=3.14, hide: bool=True, third=False):\n kwargs.update({\"first\": first, \"second\": second,\n \"hide\": hide, \"third\": third})\n # Create display\n func_dis = FunctionDisplay(foo, annotations={'first': int},\n hide_params=['hide'])\n return func_dis\n\n\n@show_widget\ndef test_func_display_creation(func_display):\n # Check we made the proper number of control widgets\n assert len(func_display.param_controls) == 3\n # Check our hidden parameter is not available\n assert 'hide' not in [widget.parameter\n for widget in func_display.param_controls]\n # Check that we sorted our parameters correctly\n assert 'first' in func_display.required_params\n assert all([key in func_display.optional_params\n for key in ['second', 'third']])\n return func_display\n\n\ndef test_func_execution(func_display):\n # Configure parameters\n func_display.param_controls[0].param_edit.setText('1')\n func_display.param_controls[1].param_edit.setText('3.14159')\n func_display.param_controls[2].param_control.setChecked(True)\n # Check function execution\n func_display.execute()\n assert kwargs['first'] == 1\n assert kwargs['second'] == 3.14159\n assert kwargs['hide']\n assert kwargs['third']\n\n\ndef test_func_exceptions(func_display):\n # Clear our cache\n kwargs.clear()\n # Configure parameters\n # Improper typing\n func_display.param_controls[0].param_edit.setText('Invalid')\n func_display.param_controls[1].param_edit.setText('3.14159')\n func_display.param_controls[2].param_control.setChecked(True)\n # Check function execution\n func_display.execute()\n # Check our function was not run\n assert kwargs == {}\n\n\n@show_widget\ndef test_func_panel():\n # Mock functions\n def foo(a: int, b: bool=False, c: bool=True):\n pass\n\n def foobar(a: float, b: str, c: float=3.14, d: bool=False):\n pass\n # Create Panel\n fp = FunctionPanel([foo, foobar])\n # Check that all our methods made it in\n assert 'foo' in fp.methods\n assert 'foobar' in fp.methods\n return fp\n","sub_path":"tests/test_func.py","file_name":"test_func.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"129794993","text":"\nimport acm\nimport re\nfrom TraitBasedDealPackage import TraitBasedDealPackage, SetSolverParametersWithSafeExit, Date, DatePeriod, Str, Object, Float, Bool, Box, Int, CalcVal, List, Set, Delegate, Action, Text, Label, Link\nfrom DealPackagePayoffGraphCalculations import PayoffGraphCalculations\nfrom DealPackageUtil import NoChange, UnpackPaneInfo, WrapAsTabControlList\nfrom collections import OrderedDict\n\n# Needed for DevKit\nfrom AttributeMetaData import AcquirerChoices, CounterpartyChoices, PortfolioChoices, TradeStatusChoices, ValGroupChoices, AttributeDialog, NoButtonAttributeDialog, ContextMenu, ContextMenuCommand, NoOverride\nfrom DealPackageUtil import DealPackageException, DealPackageUserException, Settings, InstrumentSetNew_Filter, InstrumentPart, DealPart, ParseFloat, ParseSuffixedFloat, ReturnDomainDecorator, SalesTradingInteraction\nfrom DealPackageDialog import DealPackageDialog, UXDialogsWrapper\nfrom DealPackageCommandActionUtils import CommandActionBase, TradeActions, NoTradeActions, CustomActions\nfrom CompositeAttributeDevKit import CompositeAttributeDefinition \nfrom DealPackageTradeActionCommands import CorrectCommand, NovateCommand, CloseCommand, MirrorCommand\n\n\nclass DealPackageBase(TraitBasedDealPackage):\n \n # Global traits needed fo ALL trait based Deal Packages\n autoRefreshCalc = Bool( noDealPackageRefreshOnChange=True )\n refreshCalcCounter = Int( onChanged='@_OnRefreshCalcCounterChanged' ) # Apply refresh when changed\n sheetNeedsRefresh = Bool( noDealPackageRefreshOnChange=True,\n silent=True)\n sheetDefaultColumns = List( noDealPackageRefreshOnChange=True )\n multiTradingEnabled = Bool( noDealPackageRefreshOnChange=True )\n graphCoordinatesNeedsRefresh = Bool( noDealPackageRefreshOnChange=True,\n silent=True )\n graphCoordinates = Action( action='@_GraphCoordinates',\n noDealPackageRefreshOnChange=True )\n customPanes = List( noDealPackageRefreshOnChange=True )\n transformLayout = Action( noDealPackageRefreshOnChange=True,\n action='@TransformLayout')\n showGraphInitially = Bool( noDealPackageRefreshOnChange=True )\n graphApplicable = Bool( noDealPackageRefreshOnChange=True )\n showSheetInitially = Bool( noDealPackageRefreshOnChange=True )\n sheetApplicable = Bool( noDealPackageRefreshOnChange=True )\n \n updateParentDelegateTraits = Action( action='@_UpdateParentDelegateTraits',\n noDealPackageRefreshOnChange=True )\n \n solverParameter = Str( label=\"Solve For\",\n choiceListSource=\"@_SolverParameterChoices\",\n noDealPackageRefreshOnChange=True )\n solverTopValue = Str( label=\"Goal Value\",\n choiceListSource=\"@_SolverTopValueChoices\",\n noDealPackageRefreshOnChange=True,\n onChanged='@_OnSolverTopValueChanged' )\n solverValue = Float( label=\"Value\",\n noDealPackageRefreshOnChange=True,\n onChanged='@_OnSolverValueChanged' )\n solverAction = Action( label='Solve',\n action='@_Solve',\n noDealPackageRefreshOnChange=True )\n uxCallbacks = Object( objMapping='_UxCallbacks',\n domain='FDictionary',\n noDealPackageRefreshOnChange=True)\n salesTradingInteraction = Object( objMapping='_SalesTradingInteraction',\n noDealPackageRefreshOnChange=True)\n uiViewModeIsSlim = Object( objMapping='UiViewModeIsSlim',\n domain='FDictionary',\n noDealPackageRefreshOnChange=True)\n toggleAllShowModes = Action( label=\"@_SlimDetailLabel\",\n action='@_ToggleShowMode')\n \n def __init__(self, dealPackage):\n TraitBasedDealPackage.__init__(self, dealPackage)\n self._payoffGraphCalculations = PayoffGraphCalculations(self, self._GetCalcSpace)\n self._blockSolve = False\n self._graphCoordinates = []\n self._tradeActionInstances = {}\n self._customActionInstances = {}\n self._uxCallbacks = acm.FDictionary()\n self._uiViewModeIsSlim = acm.FDictionary()\n self._uiViewModeIsSlim.AtPut(\"DetailedMode1\", True)\n self._uiViewModeIsSlim.AtPut(\"DetailedMode2\", True)\n \n def _SalesTradingInteraction(self, input='NoInputVal', *args):\n if input == 'NoInputVal':\n if not hasattr(self, '_salesTradingInteraction'):\n self._salesTradingInteraction = SalesTradingInteraction()\n return self._salesTradingInteraction\n\n def _UxCallbacks(self, input='NoInputVal'):\n if input == 'NoInputVal':\n return self._uxCallbacks\n else:\n for key in input.Keys():\n self._uxCallbacks.AtPut(key, input.At(key))\n\n def UiViewModeIsSlim(self, input='NoInputVal'):\n if input == 'NoInputVal':\n return self._uiViewModeIsSlim\n else:\n for key in input.Keys():\n self._uiViewModeIsSlim.AtPut(key, input.At(key))\n\n def CloseDialog(self):\n closeDialogCallback = self._uxCallbacks.At('closeDialogCb')\n if closeDialogCallback:\n closeDialogCallback()\n else:\n raise DealPackageException('CloseDialog only applicable from Dialog')\n\n def _autoRefreshCalc_default(self):\n return True\n \n def _OnRefreshCalcCounterChanged(self, attrRefreshCalc, oldValue, newValue,*args):\n self._RegisterAllCalculations()\n self._RefreshAllCalculations()\n if not getattr(self, 'autoRefreshCalc'):\n self.SetAttribute('graphCoordinatesNeedsRefresh', True)\n setattr(self, attrRefreshCalc, newValue)\n \n def _uxCallbacks_default(self):\n return self._UxCallbacks()\n \n def _sheetDefaultColumns_default(self):\n return self._SheetDefaultColumns()\n \n def _showGraphInitially_default(self):\n return self._ShowGraphInitially() and self._GraphApplicable()\n\n def _graphApplicable_default(self):\n return self._GraphApplicable()\n \n def _showSheetInitially_default(self):\n return self._ShowSheetInitially() and self._SheetApplicable()\n\n def _multiTradingEnabled_default(self):\n return self._MultiTradingEnabled()\n\n def _sheetApplicable_default(self):\n return self._SheetApplicable()\n \n def _customPanes_default(self):\n return self.TransformLayout(None, self.CustomPanes())\n \n def _SlimDetailLabel(self, attrName):\n isSlim = self.uiViewModeIsSlim.At('DetailedMode1')\n return \"Detail Mode\" if isSlim else \"Slim Mode\"\n \n def _RecursiveUpdateChildShowModes(self, childDp):\n childDp.GetAttribute('toggleAllShowModes')()\n \n def _ToggleShowMode(self, attrName):\n # Need to make copy of dict, else messing with defaultValue \n # (class variable for attributes of type Object)\n newMode = self.uiViewModeIsSlim.At('DetailedMode1') != True\n self.uiViewModeIsSlim.AtPut('DetailedMode1', newMode)\n self.uiViewModeIsSlim.AtPut('DetailedMode2', newMode)\n for child in self.ChildDealPackages():\n self._RecursiveUpdateChildShowModes(child)\n \n '''******************************** \n Layout Util\n ********************************''' \n def TransformLayout(self, attrName, layout):\n if not isinstance(layout, basestring): # if string, do nothing\n layout = WrapAsTabControlList(layout)\n layout = self.__SearchReplaceCompositeAttributes(layout)\n return layout\n \n def __SearchReplaceCompositeAttributes(self, layout):\n if isinstance(layout, basestring):\n layout = self.__ReplaceWithCompositeAttributeNames(layout)\n else:\n for tabCtrlPaneInfo in layout:\n tabCtrlName, tabCtrlLayout = UnpackPaneInfo(tabCtrlPaneInfo)\n for paneInfo in tabCtrlLayout:\n paneName, paneLayout = UnpackPaneInfo(paneInfo)\n paneInfo[paneName] = self.__ReplaceWithCompositeAttributeNames(paneInfo[paneName])\n return layout\n \n def __ReplaceWithCompositeAttributeNames(self, layout):\n compositeAttributes = self._CompositeAttributes()\n for attrName in compositeAttributes:\n attrLayout = compositeAttributes[attrName].GetLayout()\n if isinstance(attrLayout, basestring):\n layout = re.sub((r'\\b%s\\b')%(attrName), attrLayout.strip().rstrip(';'), layout)\n return layout\n \n '''******************************** \n Trait Changed\n ********************************''' \n def RegisterCallbackOnAttributeChanged(self, callback, attributes = None, last = False):\n if last:\n self.on_post_trait_change(callback, attributes)\n else:\n self.on_trait_change(callback, attributes)\n \n '''******************************** \n UI View Mode Helper Functions\n ********************************''' \n \n def IsShowModeDetail(self, *args):\n return self.uiViewModeIsSlim.At(\"DetailedMode1\") == False\n \n def IsShowModeDetail2(self, *args):\n return self.uiViewModeIsSlim.At(\"DetailedMode2\") == False\n \n '''******************************** \n CUSTOM PANDS/LAYOUT\n ********************************'''\n def GetCustomPanesFromExtValue(self, *layouts):\n if len(layouts) == 1 and isinstance(layouts[0], basestring):\n # Backwards compatibility, before tab sections\n return self._GetLayoutFromExtValue(layouts[0])\n else:\n retValue = []\n for nameAndExtValue in layouts:\n assert len(nameAndExtValue) == 2, \"GetCustomPanesFromExtValue, failed to parse layout. Expected arguments as (['Pane Name 1', 'extValueName1'], ['Pane Name 2', 'extValueName2'], ...), got \" + str(layouts)\n paneName = nameAndExtValue[0]\n customPane = self._GetLayoutFromExtValue(nameAndExtValue[1])\n retValue.append({paneName: customPane})\n return retValue\n\n def _GetLayoutFromExtValue(self, extValueName):\n retValue = []\n extCustomPanes = acm.GetDefaultContext().GetExtension(acm.FExtensionValue, acm.FObject, extValueName)\n if extCustomPanes is None:\n raise DealPackageException(\"DealPackageBase, \" + extValueName + \", no such extension value\") \n customPanes = extCustomPanes.Value()\n customPanes = customPanes.rstrip(';') # drop terminating ';'\n \n layoutsAndPanes = customPanes.split(';')\n for pane in layoutsAndPanes:\n layoutNamePane = pane.split(',')\n if len(layoutNamePane) == 2:\n ext = acm.GetDefaultContext().GetExtension(acm.FExtensionValue, acm.FObject, layoutNamePane[0])\n if ext is None:\n error = \"DealPackageBase::GetCustomPanesFromExtValue FObject:\"\n raise DealPackageException(error + layoutNamePane[0] + \", no such layout\") \n layout = ext.Value()\n if not layoutNamePane[1]:\n raise DealPackageException(\"DealPackageBase::GetCustomPanesFromExtValue pane name missing\") \n retValue.append( {layoutNamePane[1]: layout} )\n else:\n raise DealPackageException(\"DealPackageBase::GetCustomPanesFromExtValue corrupt \" + layoutsAndPanes)\n return retValue\n \n \n '''******************************** \n Deal Package on Deal Package only:\n When a deal package child is updated directly, and not via the parent deal package, \n the parent Delegate traits need to be re-read\n ********************************''' \n def _UpdateParentDelegateTraits(self, *args):\n if (not self._muteParentNotifications):\n self._DelegateAttributeMappingDefaultValuesToParent()\n self._RegisterAllObjectMappings()\n \n '''******************************** \n Solver\n ********************************''' \n \n def SolverColor(self, attrName): # API-method in DealPackageDevKit\n solverParam = self.GetAttributeMetaData(attrName, 'solverParameter')()\n if solverParam and self.__HasSolverTopValue():\n return 'BkgDealSolver'\n else:\n return None\n \n def __HasSolverTopValue(self):\n for attrName in self.GetAttributes():\n if self.GetAttributeMetaData(attrName, 'solverTopValue')():\n return True\n return False\n \n def _solverTopValue_default(self):\n return self.__GetFirstChoiceItem(self._SolverTopValueChoices())\n \n def _solverParameter_default(self):\n return self.__GetFirstChoiceItem(self._SolverParameterChoices())\n \n def _solverValue_default(self):\n value = None\n topValue = self.__GetFirstChoiceItem(self._SolverTopValueChoices())\n if topValue:\n value = self.__GetDefaultSolverValue(topValue)\n return value\n \n def _OnSolverValueChanged(self, traitName, *args):\n self._Solve()\n \n def _OnSolverTopValueChanged(self, traitName, *args):\n self._blockSolve = True\n try:\n self.solverValue = self.__GetDefaultSolverValue(self.solverTopValue)\n except:\n pass\n self._blockSolve = False\n \n def __GetDefaultSolverValue(self, attr):\n attr = self.solverParameter if self.__IsSolverAttribute(attr) else None\n value = self.__GetActualValue(attr)\n return value\n \n def __GetActualValue(self, attr):\n value = self.get_trait_value(attr)\n if value and self._GetCalcMapping(attr):\n value = value.Value()\n return value\n \n def __IsSolverAttribute(self, attr):\n return self._GetSolverTopValue(attr) or self._GetSolverParameter(attr)\n \n def _SolverTopValueChoices(self, *args):\n topValues = self.__GetAllWithMatchingProperty(\"solverTopValue\")\n return topValues\n \n def _SolverParameterChoices(self, *args):\n parameters = self.__GetAllWithMatchingProperty(\"solverParameter\")\n return parameters\n \n def __GetAllWithMatchingProperty(self, filterProperty):\n values = acm.FArray()\n for attr in self.get_trait_names():\n filterPropertyValue = self._GetAttributeMetaDataCallback(attr, filterProperty)()\n if filterPropertyValue:\n values.Add(attr)\n return values\n\n def __GetFirstChoiceItem(self, choices):\n value = None\n if not choices.IsEmpty():\n value = choices.First()\n return value\n\n def __IsSolved(self, currentValue, solverValue, precision):\n asArray = acm.GetFunction('doubleArray', 1)\n currentValue = asArray(currentValue)\n solverValueList = list(asArray(solverValue))\n if len(solverValueList) == 1:\n for currentTopValue in currentValue:\n if abs(currentTopValue - solverValue) <= precision:\n return True\n return False\n else:\n if len(currentValue) != len(solverValueList):\n return False\n for currentTopValue, value in zip(currentValue, solverValueList):\n if abs(currentTopValue - value) > precision:\n return False\n return True\n\n def Solve(self, topValue = None, parameter = None, solverValue = None):\n with SetSolverParametersWithSafeExit(self, topValue, parameter, solverValue):\n result = self._DoSolve()\n return result\n \n def _DoSolve(self):\n topValue = self.solverTopValue if self.__IsSolverAttribute(self.solverTopValue) else None\n parameter = self.solverParameter if self.__IsSolverAttribute(self.solverParameter) else None\n if parameter and topValue:\n parameterValue = self.__GetActualValue(parameter)\n minValue = None\n maxValue = None\n precision = 0.001\n maxIterations = 100\n solverParameters = self._GetSolverParameter(parameter)\n if not isinstance(solverParameters, list):\n solverParameters = [solverParameters]\n for solverBoundaries in solverParameters:\n if isinstance(solverBoundaries, dict):\n if \"minValue\" in solverBoundaries:\n minValue = solverBoundaries[\"minValue\"]\n if \"maxValue\" in solverBoundaries:\n maxValue = solverBoundaries[\"maxValue\"]\n if \"precision\" in solverBoundaries:\n precision = solverBoundaries[\"precision\"]\n if \"maxIterations\" in solverBoundaries:\n maxIterations = solverBoundaries[\"maxIterations\"]\n if minValue is None:\n minValue = 0.1 * parameterValue\n if maxValue is None:\n maxValue = 10.0* parameterValue\n \n if self.__IsSolved(self.__GetActualValue(topValue), self.solverValue, precision):\n return self.__GetActualValue(parameter)\n \n result = self.DealPackage().Solve(parameter, topValue, self.solverValue, minValue, maxValue, precision, maxIterations)\n isFinite = acm.Math.IsFinite(result)\n if hasattr(isFinite, 'IsKindOf') and isFinite.IsKindOf(acm.FArray):\n isFinite = reduce(lambda x, y: x and y, isFinite)\n if isFinite:\n return result\n raise DealPackageException(\"No solution found for '%s' that gives expected '%s' of %s. \"\n \"(Using boundary conditions min = %.2f, max = %.2f, precision = %f, max iterations = %d).\"\n %(self.solverParameter, self.solverTopValue, self.solverValue, minValue, maxValue, precision, maxIterations))\n\n def _Solve(self, *args):\n result = None\n if not self._blockSolve:\n result = self._DoSolve()\n if result is not None:\n parameter = self.solverParameter if self.__IsSolverAttribute(self.solverParameter) else None\n self.DealPackage().SetAttribute(parameter, result)\n self.Refresh()\n return result\n \n def _SolveForTrait(self, traitName, value):\n value = self._GetTransform(traitName)(value)\n self.solverTopValue = traitName\n previousSolverValue = self.solverValue\n f = self.__ColumnFormatter(traitName)\n self.solverValue = ParseFloat(value, formatter=f)\n if self.solverValue == previousSolverValue:\n self._Solve()\n \n def __ColumnFormatter(self, traitName):\n formatter = acm.FReal.DefaultFormatter()\n calcInfo = self._GetCalcMapping(traitName)\n if calcInfo:\n _, sheetType, columnId = calcInfo.split(\":\")\n context = acm.GetDefaultContext()\n for colDef in acm.GetColumns(columnId, sheetType, context):\n if colDef.Formatter():\n formatter = colDef.Formatter()\n break\n return formatter\n \n def GetFormatter(self, attrName):\n return self.GetAttributeMetaData(attrName, 'formatter')()\n \n '''******************************** \n GENERAL GRAPH COORDINATES\n ********************************''' \n def _GraphCoordinates(self, *args):\n if self.get_trait_value('graphCoordinatesNeedsRefresh'):\n self._graphCoordinates = self.__CalculateGraphCoordinates()\n self.SetAttribute('graphCoordinatesNeedsRefresh', False)\n return self._graphCoordinates\n \n def __CalculateGraphCoordinates(self):\n xValues = self.GraphXValues()\n yValues = self.GraphYValues(xValues)\n if len(xValues) != len(yValues):\n raise DealPackageException(\"Mismatching x- and y-values. Number of x-values: %s, Number of y-values: %s\", len(xValues), len(yValues))\n return [[x, y] for x, y in map(None, xValues, yValues)]\n \n def GraphYValues(self, xValues):\n return self._payoffGraphCalculations.GraphYValues(xValues)\n \n def GraphXValues(self):\n return self._payoffGraphCalculations.GenerateXValues()\n \n def _TradeActionAt(self, key):\n stringKey = str(key) \n tradeAction = self._tradeActionInstances.get(stringKey)\n if not tradeAction:\n cls = self.__class__._TradeActionHandlers().get(stringKey)\n if cls:\n tradeAction = cls(dealPackage = self.DealPackage())\n self._tradeActionInstances[stringKey] = tradeAction\n return tradeAction\n \n def _CustomActionAt(self, key):\n stringKey = str(key) \n customAction = self._customActionInstances.get(stringKey)\n if not customAction:\n cls = self.__class__._CustomActionHandlers().get(stringKey)\n if cls:\n customAction = cls(dealPackage = self.DealPackage())\n self._customActionInstances[stringKey] = customAction\n return customAction\n \n @classmethod\n def _SheetDefaultColumns(cls):\n return []\n \n @classmethod\n def _MultiTradingEnabled(cls):\n return False\n\n @classmethod\n def _ShowGraphInitially(cls):\n return True\n \n @classmethod\n def _GraphApplicable(cls):\n return True\n \n @classmethod\n def _ShowSheetInitially(cls):\n return True\n \n @classmethod\n def _SheetApplicable(cls):\n return True\n \n @classmethod\n def _IncludeTradeActionTrades(cls):\n return False\n \n @classmethod\n def _TradeActionHandlers(cls):\n return {}\n \n @classmethod\n def _CustomActionHandlers(cls):\n return {}\n \n @classmethod\n def _SalesTradingInteractionSetting(cls, settingName, *args):\n if hasattr(cls, '_salesTradingInteraction') and cls._salesTradingInteraction:\n return cls._salesTradingInteraction.At(settingName)\n \n @classmethod\n def _Create(cls, dealPackage):\n return cls(dealPackage)\n \n \nclass DealPackageChoiceListSource(object):\n def __init__(self):\n self._source = acm.FArray()\n \n def __getattr__(self, attr):\n try:\n return getattr(self._source, attr)\n except AttributeError:\n return object.__getattr__(self, attr)\n \n def AddAll(self, coll):\n with NoChange(self._source):\n self._source.AddAll(coll)\n self._source.Changed()\n \n def Populate(self, coll):\n with NoChange(self._source):\n self._source.Clear()\n self._source.AddAll(coll)\n self._source.Changed()\n \n def Source(self):\n return self._source\n","sub_path":"Extensions/Deal Package/FPythonCode/DealPackageBase.py","file_name":"DealPackageBase.py","file_ext":"py","file_size_in_byte":23735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"79726381","text":"import pandas as pd\nimport time\nfrom selenium import webdriver\nfrom fake_useragent import UserAgent\n\nclass Whoscored: \n def __init__(self, url=\"https://stats.nba.com/teams/traditional/?sort=GP&dir=-1\", headless=False): \n self.url = url\n self.urls = []\n self.team_table_df = None \n \n self.options = webdriver.ChromeOptions() \n self.options.add_argument(\"user-agent={}\".format(UserAgent().chrome))\n if headless:\n self.options.add_argument('headless')\n self.driver = webdriver.Chrome(options=self.options)\n \n def get_team_table(self): \n \n self.driver.get(self.url)\n columns_league = self.driver.find_elements_by_css_selector(\"#standings-16547-grid > thead > tr:first-child > th\")\n columns_league = [column.text for column in columns_league][:-1]\n \n self.league_table_df = pd.DataFrame(columns = columns_league)\n\n\n teams = self.driver.find_elements_by_css_selector(\"#standings-16547-content tr\") # Check\n \n for (index,team) in enumerate(teams):\n league_info = {\n \"R\" : team.find_element_by_css_selector(\".o\").text,\n \"Team\" : team.find_element_by_css_selector(\".team\").text,\n \"P\" : team.find_element_by_css_selector(\".p\").text,\n \"W\" : team.find_element_by_css_selector(\".w\").text,\n \"D\" : team.find_element_by_css_selector(\".d\").text,\n \"L\" : team.find_element_by_css_selector(\".l\").text,\n \"GF\" : team.find_element_by_css_selector(\".gf\").text,\n \"GA\" : team.find_element_by_css_selector(\".ga\").text,\n \"GD\" : team.find_element_by_css_selector(\".gd\").text,\n \"Pts\" : team.find_element_by_css_selector(\".pts\").text,\n }\n self.league_table_df.loc[index] = league_info\n self.url = team.find_element_by_css_selector(\"a\").get_attribute(\"href\")\n self.urls.append(self.url)\n \n return self.league_table_df\n\n \n def get_team_information(self):\n \n self.driver.get(self.urls[0])\n team_infos = self.driver.find_elements_by_css_selector(\"div.stats-container > dl > dt\")\n team_infos = team_infos[2:8]\n columns_team_infos = [team_info.text for team_info in team_infos]\n columns_team_infos.insert(0, \"Team\")\n columns_team_infos.append(\"yellow_card\")\n columns_team_infos.append(\"red_card\")\n \n self.team_infos_df = pd.DataFrame(columns = columns_team_infos)\n \n\n for (index, url) in enumerate(self.urls):\n self.driver.get(url)\n \n try:\n self.driver.find_element_by_css_selector(\".team-profile-side-box div.team-name > a\").text\n \n except:\n print(\"{} data not available\".format(self.driver.find_element_by_css_selector(\"h2.team-header > span.team-header-name\").text))\n \n else: # 여기서 위에 league table 가져온 것 처럼 dictionary형태로 해서 붙여넣으면 yellow card 와 red card column이 에러가 나서 \n # list로 바꿔서 넣어봤더니 되더라구요! 왜 그런걸까요..? dictionary는 여기에서 왜 문제가 되는지 아직 알아내지 못했는데\n # 도와주세요 강사님 ㅠㅠ\n team_info = [\n self.driver.find_element_by_css_selector(\".team-profile-side-box div.team-name > a\").text,\n self.driver.find_element_by_css_selector(\"dl.stats > dd:nth-child(6)\").text,\n self.driver.find_element_by_css_selector(\"dl.stats > dd:nth-child(8)\").text,\n self.driver.find_element_by_css_selector(\"dl.stats > dd:nth-child(10)\").text,\n self.driver.find_element_by_css_selector(\"dl.stats > dd:nth-child(12)\").text,\n self.driver.find_element_by_css_selector(\"dl.stats > dd:nth-child(14)\").text,\n self.driver.find_element_by_css_selector(\"dl.stats > dd:nth-child(16)\").text,\n self.driver.find_element_by_css_selector(\"dl.stats > dd:nth-child(18) > .yellow-card-box\").text,\n self.driver.find_element_by_css_selector(\"dl.stats > dd:nth-child(18) > .red-card-box\").text,\n ]\n self.team_infos_df.loc[index] = team_info \n \n \n time.sleep(8) \n \n \n self.driver.quit()\n print(\"Crawling Completed\")\n return self.team_infos_df \n \n def making_df(self):\n self.final_df = self.league_table_df.merge(self.team_infos_df, how='outer', left_on='Team', right_on='Team')\n return self.final_df\n \n def df_columns_to_num(self, df):\n temp_cols = list(df.columns)\n del temp_cols[1]\n for column in temp_cols:\n try:\n df[column] = df[column].apply(pd.to_numeric)\n except ValueError:\n df[column] = df[column].apply(lambda x: float((str(x).strip('%')))) \n else:\n df[column] = df[column].apply(pd.to_numeric)\n return df.copy().drop(columns = ['Team'])\n\n def crawling(self):\n self.league_table_df = self.get_league_table()\n self.team_infos_df = self.get_team_information()\n self.final_df = self.making_df()\n \nif __name__ == '__main__':\n whoscored = Whoscored()\n df = whoscored.crawling()\n df.tail()","sub_path":"nba_crawling.py","file_name":"nba_crawling.py","file_ext":"py","file_size_in_byte":5545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"248694306","text":"import argparse\nimport wandb\nfrom pathlib import Path\nfrom language_model.NER.dataset import TokenClassificationDataset\nfrom language_model.NER.malfong import Malfong\nfrom language_model.NER.XLM_RoBERTa import XLMRoBERTa\nfrom language_model.lib.log import get_logger\nfrom transformers import AutoTokenizer\n\nparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument(\"--data_dir\", type=str, help=\"Data directory for storing the expirement\", default=\"./data\")\nparser.add_argument(\n \"--run_name\", type=str, help=\"Name the model run . Defaults to icelandic-model\", default=\"icelandic-model\"\n)\nparser.add_argument(\n \"--local_rank\", type=int, help=\"Local rank. Necessary for using the torch.distributed.launch utility.\", default=-1\n)\n\nargv = parser.parse_args()\n\ndata_dir = argv.data_dir\nrun_name = argv.run_name\nlocal_rank = argv.local_rank\n\nlogger = get_logger(__file__)\n\nlogger.info(f\"Starting run: {run_name}\")\n\n\nwandb.login()\n\ndata_dir = Path(f\"{data_dir}\") / run_name\ndata_dir.mkdir(parents=True, exist_ok=True)\ndataset_filename = \"malfong_ner.txt\"\n\nmalfong = Malfong(data_dir)\nmalfong.download()\n\nmax_seq_length = 128\ntokenizer = AutoTokenizer.from_pretrained(\"xlm-roberta-base\")\ndataset = TokenClassificationDataset(data_dir / dataset_filename, tokenizer, max_seq_length)\nmodel = XLMRoBERTa(data_dir, dataset=dataset)\n\n\nmodel.train()\n","sub_path":"src/train_ner_xml_roberta.py","file_name":"train_ner_xml_roberta.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"119939274","text":"#coding:utf-8\nimport random,pygame,time,numpy,math,os\nfrom pygame.locals import *\nfrom os.path import expanduser\n\npygame.init()\nbtex,btey=1280/1.5,1024/1.5\nio = pygame.display.Info()\nmtex,mtey=io.current_w,io.current_h\ntex,tey=int(mtex/1.5),int(mtey/1.5)\nfullscreen=False\nacchardware=False\ndoublebuf=False\n\ncac=\"|\"\ncacc=\"#\"\n\nhome = expanduser(\"~\")\ndre=\"Cube2_remastered/\"\nif not dre[:-1] in os.listdir(home): os.mkdir(home+\"/\"+dre)\ndire=home+\"/\"+dre\n\ndfs=\"save.nath\"\nif not dfs in os.listdir(dire):\n f=open(dire+dfs,\"w\")\n f.write(\"0|0\")\n f.close()\n\nskins_possedes=[]\nskin_equipe=0\n\nf=open(dire+dfs,\"r\").read().split(cac)\nskin_equipe=int(f[0])\nfor ff in f[1].split(cacc):\n try: skins_possedes.append( int(ff) )\n except: pass\nif skin_equipe>=len(skins_possedes): skin_equipe=0\nif len(f)>3:\n tex=int(f[2])\n tey=int(f[3])\nif len(f)>4: fullscreen=bool(int(f[4]))\nif len(f)>5: acchardware=bool(int(f[5]))\nif len(f)>6: doublebuf=bool(int(f[6]))\n\ndef rx(x): return int(x/btex*tex)\ndef ry(y): return int(y/btey*tey)\n\ndef rxx(x): return float(float(x)/float(btex)*float(tex))\ndef ryy(y): return float(float(y)/float(btey)*float(tey))\n\noptions=0\nif fullscreen: options|=pygame.FULLSCREEN\nif acchardware: options|=pygame.HWSURFACE\nif doublebuf: options|=pygame.DOUBLEBUF\n\nfenetre=pygame.display.set_mode([tex,tey],options)\npygame.display.set_caption(\"Cube2\")\nfont=pygame.font.SysFont(\"Arial\",ry(20))\nfont1=pygame.font.SysFont(\"Arial\",ry(17))\nfont2=pygame.font.SysFont(\"Arial\",ry(20))\nfont3=pygame.font.SysFont(\"Arial\",ry(30))\nfont4=pygame.font.SysFont(\"Arial\",ry(40))\nfont5=pygame.font.SysFont(\"Serif\",ry(60))\n\ncursor1,mask1=pygame.cursors.compile((\"XXXXXXXXXXXXXXXX\",\"X..............X\",\"X..............X\",\"X..............X\",\"X..............X\",\"X..............X\",\"X..............X\",\"X..............X\",\"X..............X\",\"X..............X\",\"X..............X\",\"X..............X\",\"X..............X\",\"X..............X\",\"X..............X\",\"XXXXXXXXXXXXXXXX\"), black='X', white='.', xor='o')\ncursor_sizer1=((16,16),(9,8),cursor1,mask1)\npygame.mouse.set_cursor(*cursor_sizer1)\n\nmon_joystick=\"joystick\"\nnb_joysticks = pygame.joystick.get_count()\nif nb_joysticks > 0:\n\tmon_joystick = pygame.joystick.Joystick(0)\n\tmon_joystick.init()\n\ndef rcl(): return (random.randint(50,200),random.randint(50,100),random.randint(50,200))\n\ntpage=int((rx(750)/ry(150))*3)\n\ndimg=\"images/\"\n\n\nskins=[ [ \"skin1/\",0 ,True,0 ] ]\n#0=imgs [0=img base , 1=idle , 2=roulade, 3=dire skin images] 1 = rarete 2=rotate 3=agl base\n#raretes : 0=commun 1=rare 2=epique 3=légendaire 4=divin\n\nskins_com=[]\nskins_rar=[]\nskins_epi=[]\nskins_leg=[]\nskins_div=[]\n\nfor x in range(len(skins)):\n r=skins[x][1]\n if r==0: skins_com.append( x )\n elif r==1: skins_rar.append( x )\n elif r==2: skins_epi.append( x )\n elif r==3: skins_leg.append( x )\n else: skins_div.append( x )\n\nraretes=[\"commun\",\"rare\",\"épique\",\"légendaire\",\"divin\"]\ncl_raretes=[(38,110,224),(199,91,20),(202,14,227),(14,227,49),(255,255,0)]\n\ndef save(skin_equipe,skins_possedes,tex,tey,fullscreen,acchardware,doublebuf):\n txt=str(skin_equipe)+cac\n for s in skins_possedes:\n txt+=str(s)+cacc\n txt=txt[:-1]\n txt+=cac+str(tex)+cac+str(tey)\n fs=\"0\"\n if fullscreen: fs=\"1\"\n txt+=cac+fs\n ah=\"0\"\n if acchardware: ah=\"1\"\n txt+=cac+ah\n db=\"0\"\n if doublebuf: db=\"1\"\n txt+=cac+db\n f=open(dire+dfs,\"w\")\n f.write(txt)\n f.close()\n\nclass Mape:\n def __init__(self,niv):\n dif=int(float(niv)/100.*20.)+1\n self.tx=50+5*dif\n self.ty=50+5*dif\n self.clm=rcl()\n self.cls=(255-self.clm[0],255-self.clm[1],255-self.clm[2])\n self.mape=numpy.zeros([self.tx,self.ty],dtype=int)\n self.chem=[[random.randint(int(self.tx/3),int(self.tx/3*2)),random.randint(int(self.tx/3),int(self.tx/3*2))]]\n self.deb=self.chem[0]\n dbs=[self.deb]\n nbbranches=dif\n dc=0\n fins=[]\n for y in range(nbbranches):\n self.chem.append( random.choice(dbs) ) \n for x in range(random.randint(400,600)):\n c=self.chem[len(self.chem)-1]\n ax,ay=0,0\n if random.choice([0,1,dc])==1:\n ax=random.randint(-1,1)\n dc=1\n else:\n dc=0\n ay=random.randint(-1,1)\n cx,cy=c[0]+ax,c[1]+ay\n if cx < 0: cx=0\n elif cx > self.tx-1: cx=self.tx-1\n if cy < 0: cy=0\n elif cy > self.ty-1: cy=self.ty-1\n self.chem.append([cx,cy])\n for x in range(3): dbs.append( self.chem[len(self.chem)-1] )\n fins.append( self.chem[len(self.chem)-1] )\n fpl=fins[0]\n for f in fins:\n if math.sqrt((self.deb[0]-f[0])**2+(self.deb[1]-f[1])**2) > math.sqrt((self.deb[0]-fpl[0])**2+(self.deb[1]-fpl[1])**2): fpl=f\n self.fin=fpl\n for x in range(self.tx):\n for y in range(self.ty):\n if [x,y] in self.chem: self.mape[x,y]=0 #sol\n else: self.mape[x,y]=1 #mur\n self.p1=False\n self.dp1=time.time()\n self.tp1=1.5\n self.dif=dif\n def update(self):\n if time.time()-self.dp1>=self.tp1:\n self.p1=not self.p1\n self.dp1=time.time()\n\nclass Cube2:\n def __init__(self,cube):\n self.px=cube.px\n self.py=cube.py\n self.tx=cube.tx\n self.ty=cube.ty\n self.cl=(150,150,150)\n self.img=pygame.transform.scale(pygame.image.load(dimg+\"pics.png\"),[self.tx,self.ty])\n self.rect=pygame.Rect(self.px,self.py,self.tx,self.ty)\n self.dbg=time.time()\n self.tbg=0.01\n self.pbg=False\n self.dpbg=time.time()\n self.tpbg=1.5\n self.keys=[]\n def reload(self,cube):\n self.px=cube.px\n self.py=cube.py\n self.rect=pygame.Rect(self.px,self.py,self.tx,self.ty)\n self.vitx=0.\n self.vity=0.\n self.isgrap=False\n self.keys=[]\n self.pbg=False\n self.dpbg=time.time()\n def update(self,cube):\n if not self.pbg and time.time()-self.dpbg >= self.tpbg: self.pbg=True\n if self.pbg and time.time()-self.dbg >= self.tbg:\n if len(self.keys)>=1:\n self.dbg=time.time()\n self.px,self.py=self.keys[0]\n self.rect=pygame.Rect(self.px,self.py,self.tx,self.ty)\n del(self.keys[0])\n\nclass Cube:\n def __init__(self,tcb,tc,mape,niv,skin_equipe,skins_possedes):\n sk=skins[skins_possedes[skin_equipe]]\n self.px=mape.chem[0][0]*tc+rx(1)\n self.py=mape.chem[0][1]*tc+ry(1)\n self.tx=int(tcb/3)\n self.ty=int(tcb/3)\n self.cl=(255,255,255)\n self.rect=pygame.Rect(self.px,self.py,self.tx,self.ty)\n self.dbg=time.time()\n self.tbg=0.01\n self.vitx=0.\n self.vity=0.\n self.acc=rxx(0.10)\n self.decc=rxx(0.05)\n self.vitmax=rxx(5)\n self.dk=time.time()\n self.tk=0.01\n self.checkpoint=[self.px,self.py]\n self.vie_tot=100000000000\n self.vie=self.vie_tot\n self.cangrap=False\n if niv>=10: self.cangrap=True\n self.isgrap=False\n self.grapx=0\n self.grapy=0\n self.vitgrap=7\n self.dgrap=time.time()\n self.tgrap=3\n self.anim_base=[]\n self.anim_idle=[]\n self.anim_bouger=[]\n self.anim_victory=[]\n self.ag=200\n for o in os.listdir(dimg+sk[0]+\"base/\"):\n self.anim_base.append( pygame.transform.scale(pygame.image.load(dimg+sk[0]+\"base/\"+o),[int(self.tx*self.ag/100),int(self.ty*self.ag/100)]) )\n for o in os.listdir(dimg+sk[0]+\"idle/\"):\n self.anim_idle.append( pygame.transform.scale(pygame.image.load(dimg+sk[0]+\"idle/\"+o),[int(self.tx*self.ag/100),int(self.ty*self.ag/100)]) )\n for o in os.listdir(dimg+sk[0]+\"bouger/\"):\n self.anim_bouger.append( pygame.transform.scale(pygame.image.load(dimg+sk[0]+\"bouger/\"+o),[int(self.tx*self.ag/100),int(self.ty*self.ag/100)]) )\n for o in os.listdir(dimg+sk[0]+\"victory/\"):\n self.anim_victory.append( pygame.transform.scale(pygame.image.load(dimg+sk[0]+\"victory/\"+o),[int(self.tx*self.ag/100),int(self.ty*self.ag/100)]) )\n self.imgs=self.anim_base\n self.an=0\n self.dan=time.time()\n self.tan=0.1\n self.tanbg=0.095\n self.agl=0\n self.img=pygame.transform.rotate(self.imgs[self.an],self.agl)\n self.dbg=time.time()\n self.didle=time.time()\n self.tpsidlemin=4\n self.rot=skins[skins_possedes[skin_equipe]][2]\n self.ab=skins[skins_possedes[skin_equipe]][3]\n self.fl1=pygame.transform.scale(pygame.image.load(dimg+\"fl1.png\"),[int(self.tx*140/100),int(self.ty*140/100)])\n self.fl2=pygame.transform.scale(pygame.image.load(dimg+\"fl2.png\"),[int(self.tx*140/100),int(self.ty*140/100)])\n self.fl3=pygame.transform.scale(pygame.image.load(dimg+\"fl3.png\"),[int(self.tx*140/100),int(self.ty*140/100)])\n self.fl4=pygame.transform.scale(pygame.image.load(dimg+\"fl4.png\"),[int(self.tx*140/100),int(self.ty*140/100)])\n self.fl5=pygame.transform.scale(pygame.image.load(dimg+\"fl5.png\"),[int(self.tx*140/100),int(self.ty*140/100)])\n self.fl6=pygame.transform.scale(pygame.image.load(dimg+\"fl6.png\"),[int(self.tx*140/100),int(self.ty*140/100)])\n self.fl7=pygame.transform.scale(pygame.image.load(dimg+\"fl7.png\"),[int(self.tx*140/100),int(self.ty*140/100)])\n self.fl8=pygame.transform.scale(pygame.image.load(dimg+\"fl8.png\"),[int(self.tx*140/100),int(self.ty*140/100)])\n self.sens=\"down\"\n def bouger(self,aa,cube2):\n if time.time()-self.dk >= self.tk:\n self.dk=time.time()\n sens=aa\n if aa==\"up\":\n self.vity-=self.acc\n if self.rot: self.agl=180+self.ab\n elif aa==\"down\":\n self.vity+=self.acc\n if self.rot: self.agl=0+self.ab\n elif aa==\"left\":\n self.vitx-=self.acc\n if self.rot: self.agl=270+self.ab\n elif aa==\"right\":\n self.vitx+=self.acc\n if self.rot: self.agl=90+self.ab\n self.dk=time.time()\n if self.imgs!=self.anim_bouger:\n self.imgs=self.anim_bouger\n self.an=0\n self.img=pygame.transform.rotate(self.imgs[self.an],self.agl)\n self.sens=sens\n def update(self,mape,tc,cube2):\n #animation\n tan=self.tan\n if self.imgs==self.anim_bouger:\n vv=float(abs(self.vitx)+abs(self.vity))\n tan=self.tan-float(float(vv/float(self.vitmax))*float(self.tanbg))\n if self.imgs==self.anim_bouger and self.vitx+self.vity==0:\n self.imgs=self.anim_base\n self.an=0\n if self.imgs==self.anim_base and time.time()-self.dk>=self.tpsidlemin and time.time()-self.didle>=self.tpsidlemin:\n if random.randint(1,1000)==1:\n self.didle=time.time()\n self.imgs=self.anim_idle\n self.an=0\n if time.time()-self.dan>=tan:\n self.dan=time.time()\n self.an+=1\n if self.an>=len(self.imgs):\n self.an=0\n if self.imgs==self.anim_idle: self.imgs=self.anim_base\n self.img=pygame.transform.rotate(self.imgs[self.an],self.agl)\n #reste\n if time.time()-self.dbg>=self.tbg:\n self.dbg=time.time()\n #deplacements\n if self.vitx>self.vitmax: self.vitx=self.vitmax\n if self.vitx<-self.vitmax: self.vitx=-self.vitmax\n if self.vity>self.vitmax: self.vity=self.vitmax\n if self.vity<-self.vitmax: self.vity=-self.vitmax\n self.px+=self.vitx\n self.py+=self.vity\n if self.isgrap:\n if self.grapx>self.px+self.vitgrap: self.px+=self.vitgrap\n elif self.grapx>self.px: self.px=self.grapx\n if self.grapxself.py+self.ty/2+self.vitgrap: self.py+=self.vitgrap\n elif self.grapy>self.py+self.ty/2: self.py=self.grapy\n if self.grapy= 0 and x < mape.tx and y >= 0 and y < mape.ty and self.rect.colliderect( pygame.Rect(x*tc,y*tc,tc,tc) ):\n if mape.mape[x,y]==1: self.vie=0\n if mape.mape[x,y]==2 and mape.p1: self.vie-=50\n if mape.fin==[x,y]: return True\n if self.px<0:\n self.vie=0\n self.px-=self.vitx\n self.py-=self.vity\n if self.px+self.tx>mape.tx*tc:\n self.vie=0\n self.px-=self.vitx\n self.py-=self.vity\n if self.py<0:\n self.vie=0\n self.px-=self.vitx\n self.py-=self.vity\n if self.py+self.ty>mape.ty*tc:\n self.vie=0\n self.px-=self.vitx\n self.py-=self.vity\n if cube2.pbg and self.rect.colliderect(cube2.rect):\n self.vie-=2\n #physique\n if self.vitx>=self.decc: self.vitx-=self.decc\n if self.vitx>0 and self.vitx-self.decc: self.vitx=0\n if self.vity>=self.decc: self.vity-=self.decc\n if self.vity>0 and self.vity-self.decc: self.vity=0\n return None\n \ndef verif_keys(cube,cube2):\n keys=pygame.key.get_pressed()\n if keys[K_UP]: cube.bouger(\"up\",cube2)\n if keys[K_DOWN]: cube.bouger(\"down\",cube2)\n if keys[K_LEFT]: cube.bouger(\"left\",cube2)\n if keys[K_RIGHT]: cube.bouger(\"right\",cube2)\n if nb_joysticks > 0:\n #haut-bas\n aa=float(mon_joystick.get_axis(1))\n if aa > 0.5: aa=1\n elif aa < -0.5 : aa=-1\n else: aa=0 \n if aa==-1: cube.bouger(\"up\",cube2)\n if aa==1: cube.bouger(\"down\",cube2)\n #haut-bas\n aa=float(mon_joystick.get_axis(0))\n if aa > 0.5: aa=1\n elif aa < -0.5 : aa=-1\n else: aa=0 \n if aa==-1: cube.bouger(\"left\",cube2)\n if aa==1: cube.bouger(\"right\",cube2)\n return cube\n\ndef ecran_chargement():\n fenetre.fill((0,0,0))\n fenetre.blit( font4.render(\"chargement...\",True,(255,255,255)) , [tex/3,tey/3])\n pygame.display.update()\n\ndef ecran_fin():\n fenetre.fill((0,0,0))\n fenetre.blit( font3.render(\"Vous avez fini le jeu\",True,(255,255,255)) , [rx(100),ry(250)])\n fenetre.blit( font3.render(\"Revenez jouer le plus vite possible\",True,(255,255,255)) , [rx(100),ry(300)])\n fenetre.blit( font3.render(\"Appuyez sur espace pour quitter\",True,(255,255,255)) , [rx(100),ry(400)])\n pygame.display.update()\n encour_f=True\n while encour_f:\n for event in pygame.event.get():\n if event.type==QUIT: exit()\n elif event.type==KEYDOWN:\n if event.key==K_SPACE: encour_f=False\n\ndef ecran_mort():\n fenetre.fill((0,0,0))\n fenetre.blit( font3.render(\"Vous avez perdu.\",True,(255,255,255)) , [rx(100),ry(250)])\n fenetre.blit( font3.render(\"Revenez jouer le plus vite possible\",True,(255,255,255)) , [rx(100),ry(300)])\n fenetre.blit( font3.render(\"Appuyez sur espace pour quitter\",True,(255,255,255)) , [rx(100),ry(400)])\n pygame.display.update()\n encour_f=True\n while encour_f:\n for event in pygame.event.get():\n if event.type==QUIT: exit()\n elif event.type==KEYDOWN:\n if event.key==K_SPACE: encour_f=False\n\ndef ecran_fin_niveau(cube,niv):\n fenetre.fill((0,0,0))\n fenetre.blit( font3.render(\"Félicitation, Vous avez fini le niveau !\",True,(255,200,200)) , [rx(50),ry(50)])\n fenetre.blit( font3.render(\"Allez courage, il vous en reste encore \"+str(100-niv),True,(255,250,250)) , [rx(50),ry(100)])\n b1=pygame.draw.rect(fenetre,(200,200,200),(rx(300),ry(500),rx(150),ry(50)),0)\n fenetre.blit( font.render(\"continuer\",True,(0,0,0)) , [rx(310),ry(510)])\n pygame.display.update()\n an=0\n dan=time.time()\n tan=0.1\n tean=1\n dean=time.time()\n encour=True\n while encour:\n #an\n if time.time()-dan>=tan:\n dan=time.time()\n if an>=len(cube.anim_victory):\n if time.time()-dean>=tean:\n an=0\n else:\n an+=1\n if an>=len(cube.anim_victory):\n dean=time.time()\n #aff\n pygame.draw.rect(fenetre,(0,0,0),(rx(150),ry(150),rx(200),ry(200)),0)\n aan=an\n if aan>=len(cube.anim_victory): aan-=1\n fenetre.blit( pygame.transform.scale(cube.anim_victory[aan],[rx(300),ry(300)]) , [rx(150),ry(150)] )\n pygame.display.update()\n #events\n for event in pygame.event.get():\n if event.type==QUIT: exit()\n elif event.type==KEYDOWN:\n if event.type==K_ESCAPE: encour=False\n elif event.type==MOUSEBUTTONUP:\n pos=pygame.mouse.get_pos()\n if b1.collidepoint(pos): encour=False\n\ndef ecran_quit():\n fenetre.fill((0,0,0))\n fenetre.blit( font2.render(\"Vous avez quitté la partie\",True,(255,255,255)) , [rx(50),ry(250)])\n fenetre.blit( font2.render(\"Si vous avez ragé, ou que vous en avez assez de jouer à ce jeu\",True,(255,255,255)) , [rx(50),ry(300)])\n fenetre.blit( font2.render(\"Ce n'est pas grave, mais revenez jouer quand même ;)\",True,(255,255,255)) , [rx(50),ry(350)])\n fenetre.blit( font2.render(\"Appuyez sur espace pour quitter\",True,(255,255,255)) , [rx(50),ry(400)])\n pygame.display.update()\n encour_f=True\n while encour_f:\n for event in pygame.event.get():\n if event.type==QUIT: exit()\n elif event.type==KEYDOWN:\n if event.key==K_SPACE: encour_f=False\n\ndef ecran_dep_lvl(mape):\n fenetre.fill(mape.clm)\n ctx=int(tex/mape.mape.shape[0])\n cty=int(tey/mape.mape.shape[1])\n for x in range(mape.mape.shape[0]):\n for y in range(mape.mape.shape[1]):\n cl=mape.clm\n if mape.mape[x,y]==0: cl=mape.cls\n if mape.fin==[x,y]: cl=(0,0,0)\n if mape.deb==[x,y]: cl=(255,255,255)\n pygame.draw.rect(fenetre,cl,(x*ctx,y*cty,ctx,cty),0)\n pygame.display.update()\n pygame.display.flip()\n time.sleep(3)\n\ndef aff(cube,mape,cam,tc,fps,niv,morts,cube2,tps1,tpstot):\n fenetre.fill(mape.clm)\n for x in range(int((-cam[0])/tc),int((-cam[0]+tex)/tc+1)):\n for y in range(int((-cam[1])/tc),int((-cam[1]+tey)/tc+1)):\n if x>=0 and x < mape.tx and y >= 0 and y < mape.ty and mape.mape[x,y]!=1:\n if mape.mape[x,y]==0:\n cl=mape.cls\n if mape.fin==[x,y]: cl=(0,0,0)\n if mape.mape[x,y]==2: #piege clignotant\n if mape.p1: cl=(255,0,0)\n else: cl=(0,255,0)\n pygame.draw.rect(fenetre,cl,(cam[0]+x*tc,cam[1]+y*tc,tc,tc),0)\n if niv <= 10 and x >= 1 and mape.mape[x-1,y]==1: pygame.draw.rect(fenetre,(255,0,0),(cam[0]+x*tc-rx(2),cam[1]+y*tc,rx(2),tc),0)\n try:\n if niv <= 10 and x <= mape.tx-2 and mape.mape[x+1,y]==1: pygame.draw.rect(fenetre,(255,0,0),(cam[0]+x*tc+tc,cam[1]+y*tc,rx(2),tc),0)\n except: pass\n if niv <= 10 and y >= 1 and mape.mape[x,y-1]==1: pygame.draw.rect(fenetre,(255,0,0),(cam[0]+x*tc,cam[1]+y*tc-ry(2),tc,ry(2)),0)\n try:\n if niv <= 10 and y <= mape.ty-2 and mape.mape[x,y+1]==1: pygame.draw.rect(fenetre,(255,0,0),(cam[0]+x*tc,cam[1]+y*tc+tc,tc,ry(2)),0)\n except: pass\n #cube2\n if cube2.pbg: fenetre.blit(cube2.img,[cam[0]+cube2.px,cam[1]+cube2.py])\n else: pygame.draw.rect(fenetre,(50,50,50),(cam[0]+cube2.px,cam[1]+cube2.py,cube2.tx,cube2.ty),0)\n #cube\n if cube.isgrap: pygame.draw.line(fenetre,(79, 47, 19),(cam[0]+cube.px+cube.tx/2,cam[1]+cube.py+cube.ty/2),(cam[0]+cube.grapx,cam[1]+cube.grapy),rx(4))\n #pygame.draw.rect(fenetre,cube.cl,(cam[0]+cube.px,cam[1]+cube.py,cube.tx,cube.ty),0)\n fenetre.blit( cube.img , [cam[0]+cube.px-int(cube.tx*(cube.ag/4)/100),cam[1]+cube.py-int(cube.ty*(cube.ag/4)/100)] )\n if niv==1 and mape.fin[0]*tc > cube.px and abs(mape.fin[1]*tc-cube.py) cube.py and abs(mape.fin[0]*tc-cube.px) cube.px and mape.fin[1]*tc > cube.py: fenetre.blit( cube.fl5 , [cam[0]+cube.px-int(cube.tx*20/100),cam[1]+cube.py-int(cube.ty*20/100)])\n elif niv==1 and mape.fin[0]*tc > cube.px and mape.fin[1]*tc < cube.py: fenetre.blit( cube.fl6 , [cam[0]+cube.px-int(cube.tx*20/100),cam[1]+cube.py-int(cube.ty*20/100)])\n elif niv==1 and mape.fin[0]*tc < cube.px and mape.fin[1]*tc > cube.py: fenetre.blit( cube.fl7 , [cam[0]+cube.px-int(cube.tx*20/100),cam[1]+cube.py-int(cube.ty*20/100)])\n elif niv==1 and mape.fin[0]*tc < cube.px and mape.fin[1]*tc < cube.py: fenetre.blit( cube.fl8 , [cam[0]+cube.px-int(cube.tx*20/100),cam[1]+cube.py-int(cube.ty*20/100)])\n #ui\n pygame.draw.rect(fenetre,(255-int((tpstot-(time.time()-tps1))/tpstot*255),int((tpstot-(time.time()-tps1))/tpstot*255),0),(rx(0),ry(0),int((tpstot-(time.time()-tps1))/tpstot*tex),ry(10)),0)\n pygame.draw.rect(fenetre,(250,0,0),(rx(100),ry(15),int(cube.vie/cube.vie_tot*rx(200)),ry(15)),0)\n pygame.draw.rect(fenetre,(0,0,0),(rx(100),ry(15),rx(200),ry(15)),1)\n fenetre.blit( font1.render(\"fps : \"+str(fps),20,(255,255,255)), [rx(15),ry(15)] )\n fenetre.blit( font1.render(\"lvl : \"+str(niv),20,(255,255,255)), [tex-rx(100),ry(25)] )\n fenetre.blit( font1.render(\"vous êtes mort : \"+str(morts)+\" fois\",20,(255,255,255)), [tex-rx(200),ry(10)] )\n pygame.display.update()\n\ndef cniv(tcb,niv,skin_equipe,skins_possedes):\n tc=int(tcb/3+float((150-niv)/150.*(tcb/2*1.3)))\n mape=Mape(niv)\n cube=Cube(tcb,tc,mape,niv,skin_equipe,skins_possedes)\n cube2=Cube2(cube)\n cube2.tpbg=1+((30-mape.dif)/30*1)\n cam=[-cube.px+tex/2,-cube.py+tey/2]\n tps1=time.time()\n tpstot=60+40*mape.dif\n return mape,cube,cam,cube2,tps1,tpstot,tc\n\ndef main_jeu(skin_equipe,skins_possedes):\n tcb=rx(100)\n niv=1\n ecran_chargement()\n mape,cube,cam,cube2,tps1,tpstot,tc=cniv(tcb,niv,skin_equipe,skins_possedes)\n ecran_dep_lvl(mape)\n cube2.reload(cube)\n encour_g=True\n morts=0\n fps=0\n perdu=False\n while encour_g:\n t1=time.time()\n #cube\n cube2.update(cube)\n cube=verif_keys(cube,cube2)\n etat=cube.update(mape,tc,cube2)\n if cube.vie<=0:\n cube.vie=cube.vie_tot\n morts+=1\n cube.px=cube.checkpoint[0]\n cube.py=cube.checkpoint[1]\n cube.vitx,cube.vity=0,0\n cube.isgrap=False\n time.sleep(0.1)\n cube2.reload(cube)\n elif etat==True:\n if niv<100:\n ecran_fin_niveau(cube,niv)\n niv+=1\n ecran_chargement()\n mape,cube,cam,cube2,tps1,tpstot,tc=cniv(tcb,niv,skin_equipe,skins_possedes)\n ecran_dep_lvl(mape)\n cube2.reload(cube)\n else:\n encour_g=False\n ecran_fin()\n if time.time()-tps1>=tpstot:\n encour=False\n perdu=True\n ecran_mort()\n break\n cam=[-cube.px+tex/2,-cube.py+tey/2]\n #mape\n mape.update()\n #aff\n aff(cube,mape,cam,tc,fps,niv,morts,cube2,tps1,tpstot)\n #event\n for event in pygame.event.get():\n if event.type==QUIT: exit()\n elif event.type==KEYDOWN:\n if event.key==K_ESCAPE:\n encour_g=False\n ecran_quit()\n elif event.key==K_n:\n tpstot/=2\n ecran_dep_lvl(mape)\n elif event.type==MOUSEBUTTONUP:\n pos=pygame.mouse.get_pos()\n if cube.cangrap and time.time()-cube.dgrap>=cube.tgrap:\n cube.dgrap=time.time()\n cube.isgrap=True\n cube.grapx=-cam[0]+pos[0]\n cube.grapy=-cam[1]+pos[1]\n t2=time.time()\n tt=t2-t1\n if tt!=0: fps=int(1./tt)\n sg,txt,cltxt=None,None,None\n if niv < 15: \n if perdu:\n sg=random.choice(skins_com)\n txt=\"Vous avez gagné un skin commun !\"\n cltxt=cl_raretes[0]\n elif niv < 30:\n sg=random.choice(skins_rar)\n txt=\"Vous avez gagné un skin rare !\"\n cltxt=cl_raretes[1]\n elif niv < 60:\n sg=random.choice(skins_epi)\n txt=\"Vous avez gagné un skin épique !\"\n cltxt=cl_raretes[2]\n elif niv < 100:\n sg=random.choice(skins_leg)\n txt=\"Vous avez gagné un skin légendaire !\"\n cltxt=cl_raretes[3]\n else:\n sg=random.choice(skins_div)\n txt=\"Vous avez gagné un skin divin !\"\n cltxt=cl_raretes[4]\n if sg!=None:\n skins_possedes.append(sg)\n skins_possedes=list(set(skins_possedes))\n fenetre.fill((0,0,0))\n fenetre.blit( font4.render(txt,True,cltxt) , [rx(50),ry(100)])\n fenetre.blit( pygame.transform.scale(pygame.image.load(dimg+skins[sg][0]+\"base/\"+os.listdir(dimg+skins[sg][0]+\"base/\")[0]),[rx(200),ry(200)]) , [rx(200),ry(150)] )\n fenetre.blit( font3.render(\"Appuyez sur espace pour continuer\",True,(255,255,255)) , [rx(100),ry(600)])\n pygame.display.update()\n encour=True\n while encour:\n for event in pygame.event.get():\n if event.type==QUIT: exit()\n elif event.type==KEYDOWN:\n if event.key==K_SPACE: encour=False\n elif event.type==MOUSEBUTTONUP:\n encour=False\n return skin_equipe,skins_possedes\n \ndef aff_menu(men,skin_equipe,skins_possedes,ps,an,tex,tey,fullscreen,acchardware,doublebuf):\n btn,btn2,btn3,btn4,btn5,btn6=None,None,None,None,None,None\n bts=[]\n for x in range(3*(tpage+1)): bts.append( None )\n bst=[]\n for x in range(10): bst.append( None )\n fenetre.fill((0,0,0))\n if men==0:\n fenetre.blit( font5.render(\"Cube2\",20,(255,255,255)) , [rx(300),ry(10)] )\n fenetre.blit( font2.render(\"Le but de ce jeu est de trouver la sortie de chaque niveau\",20,(255,255,255)) , [rx(100),ry(100)] )\n fenetre.blit( font2.render(\"La sortie d'un niveau est représentée par un carré noir\",20,(255,255,255)) , [rx(100),ry(130)] )\n fenetre.blit( font2.render(\"Vous dirigez un carré blanc avec les flèches du clavier\",20,(255,255,255)) , [rx(100),ry(160)] )\n fenetre.blit( font2.render(\"Si vous touchez un mur, vous revenez au point de départ\",20,(255,255,255)) , [rx(100),ry(190)] )\n fenetre.blit( font2.render(\"Il y aura du temps pour finir le niveau\",20,(255,255,255)) , [rx(100),ry(220)] )\n fenetre.blit( font2.render(\"Le temps est représenté par une barre tout en haut de l'ecran\",20,(255,255,255)) , [rx(120),ry(250)] )\n fenetre.blit( font2.render(\"A partir du niveau 10, vous débloquez le grapin\",20,(255,255,255)) , [rx(120),ry(280)] )\n fenetre.blit( font2.render(\"Si vous terminez le niveau 100, vous avez fini le jeu\",20,(255,255,255)) , [rx(100),ry(310)] )\n fenetre.blit( font2.render(\"Il y aura un ature cube qui vous suivra, s'il vous touche, vous perdrez de la vie.\",20,(255,255,255)) , [rx(100),ry(340)] )\n fenetre.blit( font2.render(\"Vous pouvez quitter le jeu à tout moment en appuyant sur Echap\",20,(255,255,255)) , [rx(100),ry(370)] )\n fenetre.blit( font2.render(\"Bonne chance !\",20,(255,255,255)) , [rx(100),ry(400)] )\n btn=pygame.draw.rect(fenetre,(150,150,150),(rx(300),ry(500),rx(200),ry(75)),0)\n fenetre.blit( font4.render(\"Jouer\",20,(255,255,255)) , [rx(350),ry(520)] )\n btn2=pygame.draw.rect(fenetre,(150,150,150),(rx(300),ry(600),rx(200),ry(75)),0)\n fenetre.blit( font4.render(\"quitter\",20,(255,255,255)) , [rx(350),ry(620)] )\n btn3=pygame.draw.rect(fenetre,(200,200,200),(rx(50),ry(500),rx(100),ry(50)),0)\n fenetre.blit( font3.render(\"skins\",20,(25,25,25)) , [rx(60),ry(510)] )\n btn6=pygame.draw.rect(fenetre,(200,200,200),(rx(50),ry(565),rx(200),ry(50)),0)\n fenetre.blit( font3.render(\"parametres\",20,(25,25,25)) , [rx(60),ry(575)] )\n elif men==1:\n btn3=pygame.draw.rect(fenetre,(200,200,200),(rx(20),ry(20),rx(100),ry(50)),0)\n fenetre.blit( font3.render(\"retour\",20,(25,25,25)) , [rx(30),ry(30)] )\n fenetre.blit( font3.render(\"skins possedes :\",20,(250,250,250)) , [rx(20),ry(110)] )\n fenetre.blit( font3.render(\"skin équipé :\",20,(250,250,250)) , [rx(200),ry(30)] )\n if skin_equipe>=0 and skin_equipe=0 and skins_possedes[skin_equipe]= 0 and x < len(skins_possedes):\n s=skins_possedes[x]\n #img\n bts[skins_possedes.index(s)]=fenetre.blit( pygame.transform.scale(pygame.image.load(dimg+skins[s][0]+\"base/\"+os.listdir(dimg+skins[s][0]+\"base/\")[0]),[tcx,tcy]) , [xx,yy] )\n pygame.draw.rect(fenetre,cl_raretes[skins[s][1]],(xx,yy,tcx,tcy),2)\n #coordonée image\n xx+=tcx\n if xx>=rx(750):\n xx=rx(50)\n yy+=tcy\n btn4=fenetre.blit( pygame.transform.scale(pygame.image.load(dimg+\"f1.png\"),[rx(50),ry(100)]) , [tex-rx(50),ry(300)])\n btn5=fenetre.blit( pygame.transform.scale(pygame.image.load(dimg+\"f2.png\"),[rx(50),ry(100)]) , [0,ry(300)])\n ms_com,ms_rar,ms_epi,ms_leg,ms_div=0,0,0,0,0\n for s in skins_possedes:\n if skins[s][1]==0: ms_com+=1\n elif skins[s][1]==1: ms_rar+=1\n elif skins[s][1]==2: ms_epi+=1\n elif skins[s][1]==3: ms_leg+=1\n else: ms_div+=1\n fenetre.blit( font2.render(\"skins communs : \"+str(ms_com)+\" / \"+str(len(skins_com)),20,cl_raretes[0]) , [rx(620),ry(30)] )\n fenetre.blit( font2.render(\"skins rares : \"+str(ms_rar)+\" / \"+str(len(skins_rar)),20,cl_raretes[1]) , [rx(620),ry(50)] )\n fenetre.blit( font2.render(\"skins épiques : \"+str(ms_epi)+\" / \"+str(len(skins_epi)),20,cl_raretes[2]) , [rx(620),ry(70)] )\n fenetre.blit( font2.render(\"skins légendaires : \"+str(ms_leg)+\" / \"+str(len(skins_leg)),20,cl_raretes[3]) , [rx(620),ry(90)] )\n fenetre.blit( font2.render(\"skins divins : \"+str(ms_div)+\" / \"+str(len(skins_div)),20,cl_raretes[4]) , [rx(620),ry(110)] )\n fenetre.blit( font2.render(\"skins : \"+str(len(skins_possedes))+\" / \"+str(len(skins)),20,(250,250,250)) , [rx(620),ry(130)] )\n elif men==2:\n btn6=pygame.draw.rect(fenetre,(200,200,200),(rx(15),ry(15),rx(100),ry(50)),0)\n fenetre.blit( font3.render(\"retour\",20,(25,25,25)) , [rx(25),ry(25)] )\n cl=(150,0,0)\n if fullscreen: cl=(0,150,0)\n bst[0]=pygame.draw.rect( fenetre, cl , (rx(50),ry(250),rx(50),rx(50)) , 0)\n fenetre.blit( font3.render(\"fullscreen\",True,(255,255,255)), [rx(120),ry(260)])\n cl=(150,0,0)\n if acchardware: cl=(0,150,0)\n bst[1]=pygame.draw.rect( fenetre, cl , (rx(50),ry(330),rx(50),rx(50)) , 0)\n fenetre.blit( font3.render(\"accelerated hardware\",True,(255,255,255)), [rx(120),ry(340)]) \n cl=(150,0,0)\n if doublebuf: cl=(0,150,0)\n bst[2]=pygame.draw.rect( fenetre, cl , (rx(50),ry(410),rx(50),rx(50)) , 0)\n fenetre.blit( font3.render(\"double buff\",True,(255,255,255)), [rx(120),ry(420)])\n fenetre.blit( font3.render(\"résolution de la fenetre :\",True,(255,255,255)), [rx(170),ry(40)])\n bst[3]=pygame.draw.rect( fenetre, (50,50,50), (rx(100),ry(100),rx(50),ry(50)) , 0)\n fenetre.blit( font3.render(\"<\",True,(255,255,255)), [rx(110),ry(110)])\n pygame.draw.rect(fenetre,(210,210,210),(rx(180),ry(100),rx(300),ry(50)),0)\n fenetre.blit( font3.render(str(tex)+\" x \"+str(tey),True,(25,25,25)), [rx(190),ry(110)])\n bst[4]=pygame.draw.rect( fenetre, (50,50,50), (rx(510),ry(100),rx(50),ry(50)) , 0)\n fenetre.blit( font3.render(\">\",True,(255,255,255)), [rx(520),ry(110)])\n fenetre.blit( font2.render(\"Pour que les parametres s'appliquent, veuillez relancer le jeu\",True,(150,0,0)), [rx(10),ry(500)])\n pygame.display.update()\n return btn,btn2,btn3,btn4,btn5,btn6,bts,bst\n\ndef menu(skin_equipe,skins_possedes,tex,tey,fullscreen,acchardware,doublebuf):\n men=0\n needtoaff=True\n ps=0\n an=0\n tan=0.1\n dan=time.time()\n encour=True\n while encour:\n \"\"\"if time.time()-dan>=tan and len(skins[skins_possedes[skin_equipe]][0])>1:\n dan=time.time()\n an+=1\n if an >= len(skins[skins_possedes[skin_equipe]][0]): an=0\n needtoaff=True\"\"\"\n if needtoaff:\n btn,btn2,btn3,btn4,btn5,btn6,bts,bst=aff_menu(men,skin_equipe,skins_possedes,ps,an,tex,tey,fullscreen,acchardware,doublebuf)\n needtoaff=False\n for event in pygame.event.get():\n if event.type==QUIT: exit()\n elif event.type==KEYDOWN:\n if event.key==K_ESCAPE: encour=False\n elif event.type==MOUSEBUTTONUP:\n pos=pygame.mouse.get_pos()\n if btn!=None and btn.collidepoint(pos):\n save(skin_equipe,skins_possedes,tex,tey,fullscreen,acchardware,doublebuf)\n skin_equipe,skins_possedes=main_jeu(skin_equipe,skins_possedes)\n an=0\n if skin_equipe>=len(skins_possedes): skin_equipe=0\n save(skin_equipe,skins_possedes,tex,tey,fullscreen,acchardware,doublebuf)\n elif btn2!=None and btn2.collidepoint(pos): exit()\n elif btn3!=None and btn3.collidepoint(pos):\n if men==0: men=1\n else: men=0\n an=0\n elif btn4!=None and btn4.collidepoint(pos):\n if len(skins_possedes)>ps+tpage:\n ps+=tpage\n an=0\n elif btn5!=None and btn5.collidepoint(pos):\n if ps>=tpage:\n ps-=tpage\n an=0\n elif btn6!=None and btn6.collidepoint(pos):\n if men==0: men=2\n else: men=0\n an=0\n for b in bts:\n if b!=None and b.collidepoint(pos):\n skin_equipe=skins_possedes.index(skins_possedes[bts.index(b)])\n an=0\n for b in bst:\n if b!=None and b.collidepoint(pos):\n di=bst.index(b)\n if di==0:\n fullscreen=not fullscreen\n if not fullscreen: tex,tey=int(mtex/1.5),int(mtey/1.5)\n else: tex,tey=mtex,mtey\n elif di==1: acchardware=not acchardware\n elif di==2: doublebuf=not doublebuf\n elif di==3:\n d=float(mtex/tex)+0.5\n if d > 3: d=3\n tex,tey=int(mtex/d),int(mtey/d)\n elif di==4:\n d=float(mtex/tex)-0.5\n if d < 1: d=1\n tex,tey=int(mtex/d),int(mtey/d)\n save(skin_equipe,skins_possedes,tex,tey,fullscreen,acchardware,doublebuf)\n needtoaff=True\n\n#try:\nif True:\n menu(skin_equipe,skins_possedes,tex,tey,fullscreen,acchardware,doublebuf)\n#except Exception as e:\nelse:\n pygame.quit()\n if e!=\"name 'exit' is not defined\":\n print(e)\n input(\"please send this at : nathpython@gmail.com\")\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":38153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"35796067","text":"# -*- coding: utf-8 -*-\nimport scrapy, json, os, re\nimport scrapy\nimport json\nimport time\nfrom Scrapy_D44_robodata_V1_02.mysqlAPI import select_count, select, insert, check_table, get_cookie, change_state, restore\nfrom Scrapy_D44_robodata_V1_02.items import DataItem\nfrom Scrapy_D44_robodata_V1_02.settings import root_id\n\ncookie = get_cookie()\n\n\nclass ScrapyRobodata01Spider(scrapy.Spider):\n name = 'D44_Robo_01'\n base_urls = 'https://gw.datayes.com/rrp_adventure/web/supervisor/macro/'\n\n # 登陆\n def start_requests(self):\n url = 'https://gw.datayes.com/usermaster/authenticate/web.json'\n data = {\n # ly\n 'username': cookie['usr'],\n 'password': cookie['pwd'],\n 'rememberMe': 'false'\n }\n yield scrapy.FormRequest(url=url, formdata=data, callback=self.parse_data, dont_filter=True)\n change_state(cookie)\n\n # 登录失败返回:{'code': 0, 'message': 'Success', 'content': {'result': 'INVALID', 'tenantId': 0, 'accountId': 0}}\n # 登录成功返回:{'code': 0, 'message': 'Success', 'content': {'result': 'SUCCESS', 'userId': 7570893, 'principalName': '7570893@wmcloud.com', 'tenantId': 0, 'token': {'tokenString': 'C6782E64E9E0B5F1E23C4A584AA889DC', 'type': 'WEB', 'expiry': 1596453573495, 'expired': False}, 'redirectUrl': 'https://app.datayes.com/cloud-portal/#/portal', 'accountId': 7676915}}\n\n # 根据关键字查找数据目录\n def parse_data(self, response):\n code = json.loads(response.text)['content']['result']\n if code == 'SUCCESS':\n self.logger.info('登录成功!')\n else:\n self.logger.info('登录失败!')\n return\n check_table()\n for k, v in root_id.items():\n menu_id = v\n menu_name = k\n parent_menu_id = '4001'\n isRep = k\n if not select(menu_name, parent_menu_id, isRep):\n insert(menu_id, menu_name, parent_menu_id, isRep)\n else:\n menu_id = select(menu_name, parent_menu_id, isRep)['menu_id']\n\n url = f'https://gw.datayes.com/rrp_adventure/web/supervisor/macro/query?input={k}'\n req = scrapy.Request(url=url, callback=self.parse1, dont_filter=True,\n meta={'parent_id': menu_id, 'sourcekey': k})\n req.headers['referer'] = \"https://robo.datayes.com\"\n yield req\n\n # 返回目录 json\n def parse1(self, response):\n sourcekey = response.meta['sourcekey']\n parent_id = response.meta['parent_id']\n config_info = json.loads(response.text)['data']['catelog']\n if config_info:\n for info in config_info:\n nameCn = info['nameCn']\n hasChildren = info['hasChildren']\n n = select_count(parent_id) + 1\n menu_id = parent_id + \"{:03d}\".format(n)\n menu_name = nameCn\n isRep = info['indicId']\n\n if not select(menu_name, parent_id, isRep):\n insert(menu_id, menu_name, parent_id, isRep)\n else:\n menu_id = select(menu_name, parent_id, isRep)['menu_id']\n yield from self.rec(info['childData'], nameCn, sourcekey, menu_id)\n\n # 解析目录\n def rec(self, data, catelog, sourcekey, parent_id):\n for i in data:\n n = select_count(parent_id) + 1\n menu_name = i['nameCn']\n menu_id = parent_id + \"{:03d}\".format(n)\n if not select(menu_name, parent_id, i['indicId']):\n insert(menu_id, menu_name, parent_id, i['indicId'])\n else:\n menu_id = select(menu_name, parent_id, i['indicId'])['menu_id']\n\n if i['hasChildren']:\n yield from self.rec(i['childData'], catelog, sourcekey, menu_id)\n else:\n for j in data:\n menu_name = j['nameCn']\n routeNames = j['routeNames']\n indicId = j['indicId']\n n = select_count(parent_id) + 1\n menu_id = parent_id + \"{:03d}\".format(n)\n if not select(menu_name, parent_id, indicId):\n insert(menu_id, menu_name, parent_id, indicId)\n else:\n menu_id = select(menu_name, parent_id, indicId)['menu_id']\n\n url = f'https://gw.datayes.com/rrp_adventure/web/supervisor/macro/query?input={sourcekey}¯o={catelog}&catelog={routeNames}&pageIndex=1&pageSize=1000&highlight=true'\n req = scrapy.Request(url=url, callback=self.parse2, dont_filter=True, meta={'parent_id': menu_id})\n req.headers['referer'] = \"https://robo.datayes.com\"\n yield req\n\n # 返回最后一级的数据Json, 并根据 indicId 发送请求\n def parse2(self, response):\n config_info = json.loads(response.text)['data']\n if config_info:\n for info in config_info['hits']:\n indicId = info['indicId']\n url = f'https://gw.datayes.com/rrp_adventure/web/dataCenter/indic/{indicId}?compare=false'\n req = scrapy.Request(url=url, callback=self.parse_detail, dont_filter=True,\n meta={'parent_id': response.meta['parent_id']})\n req.headers['referer'] = \"https://robo.datayes.com\"\n yield req\n\n # 返回详细数据, 并储存\n def parse_detail(self, response):\n parent_id = response.meta['parent_id']\n config_info = json.loads(response.text)['data']\n if config_info:\n indic = config_info['indic']\n data = config_info['data']\n n = select_count(parent_id) + 1\n menu_id = parent_id + \"{:03d}\".format(n)\n menu_name = indic['indicName']\n isRep = indic['indicID']\n if not select(menu_name, parent_id, isRep):\n insert(menu_id, menu_name, parent_id, isRep)\n else:\n menu_id = select(menu_name, parent_id, isRep)['menu_id']\n for info in data:\n item = DataItem()\n value = info['dataValue']\n create_time = info['periodDate']\n year = int(create_time[:4])\n month = int(create_time[5:7])\n day = int(create_time[-2:])\n try:\n frequency = indic['frequency']\n except:\n frequency = None\n if frequency == '年':\n item['frequency'] = 5\n elif frequency == '季':\n if month in [1, 2, 3]:\n item['frequency'] = 1\n elif month in [4, 5, 6]:\n item['frequency'] = 2\n elif month in [7, 8, 9]:\n item['frequency'] = 3\n elif month in [10, 11, 12]:\n item['frequency'] = 4\n elif frequency == '月':\n item['frequency'] = 6\n elif frequency == '周':\n item['frequency'] = 7\n\n elif frequency == '日':\n item['frequency'] = 8\n else:\n item['frequency'] = 0\n item['indic_name'] = menu_name\n item['parent_id'] = menu_id\n item['root_id'] = menu_id[0]\n item['data_year'] = year\n item['data_month'] = month\n item['data_day'] = day\n item['unit'] = indic['unit']\n item['data_source'] = '萝卜投研'\n item['region'] = indic['region']\n item['country'] = indic['country']\n item['create_time'] = create_time\n item['update_time'] = str(int(time.time() * 1000))\n item['data_value'] = float(value)\n item['sign'] = '19'\n item['status'] = 1\n item['cleaning_status'] = 0\n yield item\n self.logger.info({'title': menu_name, 'create_time': create_time, 'data_value': value})\n\n\nif __name__ == '__main__':\n from scrapy import cmdline\n\n args = \"scrapy crawl D44_Robo_01\".split()\n cmdline.execute(args)\n","sub_path":"data_spider/Scrapy_D44_robodata_V1_02_pass/build/lib/Scrapy_D44_robodata_V1_02/spiders/D44_Robo_01.py","file_name":"D44_Robo_01.py","file_ext":"py","file_size_in_byte":8357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"409651988","text":"import hgfp\nimport torch\nimport dgl\nimport numpy as np\nimport copy\nimport random\nimport math\nimport sys\n\ndef run(config):\n ds_tr = hgfp.data.ani.df.topology_batched(100, mm=True)\n\n mean_and_std_dict = torch.load('/data/chodera/wangyq/hgfp_scripts/gcn_param/2020-03-30_11_41_19/norm_dict')\n\n mean_and_std_dict['angle']['eq']['mean'] = mean_and_std_dict['angle']['eq']['mean'] / 180 * math.pi\n\n mean_and_std_dict['angle']['eq']['std'] = mean_and_std_dict['angle']['eq']['std'] / 180 * math.pi\n\n # net = hgfp.models.gcn_with_combine_readout.Net(config)\n\n net = hgfp.models.walk_recurrent.Net(config)\n\n print(net)\n\n norm, unnorm = hgfp.data.utils.get_norm_fn_log_normal(mean_and_std_dict)\n\n opt = torch.optim.Adam(net.parameters(), 1e-4)\n\n loss_fn = torch.nn.functional.mse_loss\n\n def train(g_, x, u, g_h):\n\n g = copy.deepcopy(g_)\n\n g_ = dgl.batch_hetero([g_ for _ in range(u.shape[0])])\n\n g_h = net(g_h, return_graph=True)\n\n for term in ['bond', 'angle']:\n for param in ['k', 'eq']:\n g.nodes[term].data[param] = g_h.nodes[term].data[param]\n\n g = unnorm(g)\n\n g = dgl.batch_hetero([g for _ in range(u.shape[0])])\n\n g.nodes['atom'].data['xyz'] = torch.reshape(x, [-1, 3])\n\n g_.nodes['atom'].data['xyz'] = torch.reshape(x, [-1, 3])\n\n g = hgfp.mm.geometry_in_heterograph.from_heterograph_with_xyz(\n g)\n\n g = hgfp.mm.energy_in_heterograph.u(g)\n\n g_ = hgfp.mm.geometry_in_heterograph.from_heterograph_with_xyz(\n g_)\n \n g_ = hgfp.mm.energy_in_heterograph.u(g_)\n\n u = torch.sum(\n torch.cat(\n [\n g_.nodes['mol'].data['u' + term][:, None] for term in [\n 'bond', 'angle', # 'torsion', 'one_four', 'nonbonded'# , '0'\n ]],\n dim=1),\n dim=1)\n\n u_hat = torch.sum(\n torch.cat(\n [\n g.nodes['mol'].data['u' + term][:, None] for term in [\n 'bond', 'angle'# , 'torsion', 'one_four', 'nonbonded'# , '0'\n ]],\n dim=1),\n dim=1)\n\n return u, u_hat\n\n\n for _ in range(100):\n for g_, x, u, g_h in ds_tr:\n u, u_hat = train(g_, x, u, g_h)\n loss = loss_fn(torch.log(u), torch.log(u_hat))\n opt.zero_grad()\n loss.backward()\n opt.step()\n\n net.eval()\n\n ds_te = list(hgfp.data.ani.df.topology_batched(120, mm=True))[100:]\n\n u_tr = []\n u_hat_tr = []\n u_te = []\n u_hat_te = []\n\n for g_, x, u, g_h in ds_tr:\n u, u_hat = train(g_, x, u, g_h)\n u_tr.append(u)\n u_hat_tr.append(u_hat)\n\n for g_, x, u, g_h in ds_te:\n u, u_hat = train(g_, x, u, g_h)\n u_te.append(u)\n u_hat_te.append(u_hat)\n\n rmses_tr = np.array([torch.sqrt(torch.mean((u - u_hat) ** 2)).detach().numpy() for u, u_hat in zip(u_tr, u_hat_tr)])\n rmses_te = np.array([torch.sqrt(torch.mean((u - u_hat) ** 2)).detach().numpy() for u, u_hat in zip(u_te, u_hat_te)])\n\n np.save('rmses_tr', rmses_tr)\n np.save('rmses_te', rmses_te)\n\n print(rmses_tr)\n print(rmses_te)\n\n from sklearn.metrics import r2_score\n\n r2_tr = np.array([r2_score(u.detach().numpy(), u_hat.detach().numpy()) for u, u_hat in zip(u_tr, u_hat_tr)])\n r2_te = np.array([r2_score(u.detach().numpy(), u_hat.detach().numpy()) for u, u_hat in zip(u_te, u_hat_te)])\n\n print(r2_tr)\n print(r2_te)\n\nif __name__ == '__main__':\n config = sys.argv[1:] \n run(config)\n\n","sub_path":"ani/gn_fit_h.py","file_name":"gn_fit_h.py","file_ext":"py","file_size_in_byte":3617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"451899794","text":"#video/urls.py\nfrom django.conf.urls import url, include\nfrom . import views\n\napp_name='video' # app_name 설정\nurlpatterns =[\n\turl(r'^$',views.video_list,name='list'),\n\t#아래 코드 추가하기\n\turl(r'^new$', views.video_new, name='new'),\n\turl(r'^(?P\\d+)/$', views.video_detail, name='detail'),\n]\n","sub_path":"python/django_Ex/video/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"647421085","text":"#!/usr/bin/env python3\n\"\"\"\nL2 Regularization\n\"\"\"\n\nimport numpy as np\n\n\ndef l2_reg_cost(cost, lambtha, weights, L, m):\n \"\"\"Calculates the cost of a neural network with L2 regularization.\n Args:\n cost (float): cost of the network without L2 regularization.\n lambtha (float): regularization parameter.\n weights (dict): the weights and biases (numpy.ndarrays) of the\n neural network.\n L (int): number of layers in the neural network.\n m (int): number of data points used.\n Returns:\n np.ndarray: the cost of the network accounting for L2 regularization.\n \"\"\"\n summation = 0\n for ly in range(1, L + 1):\n key = \"W{}\".format(ly)\n summation += np.linalg.norm(weights[key])\n\n L2_cost = lambtha * summation / (2 * m)\n\n return cost + L2_cost\n","sub_path":"0x05-regularization/0-l2_reg_cost.py","file_name":"0-l2_reg_cost.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"455587590","text":"ciphertext = \"uapv{ndj'kt_qtvjc_ndjg_rgneid_psktcijgth}\"\n\n\ndef shift(text, shift):\n\ts = ''\n\tfor i in text:\n\t\to = chr(((ord(i)-96+shift)%26+96))\n\t\ts+=o\n\tprint(s)\n\n\nfor x in range(26):\n\tshift(ciphertext, x)\n","sub_path":"Cryptography/Ceaser.py","file_name":"Ceaser.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"606620224","text":"from dedup.index import MinHashIndex, SimHashIndex\nfrom dedup.fingerprint import MinHash, SimHash\n\nfrom nose.tools import assert_raises\n\ndata = []\nobjects = []\nindex = []\n\n\ndef setup():\n global objects, index, data\n\n data = [\n 'How are you? I Am fine. blar blar blar blar blar Thanks.',\n 'How are you i am fine. blar blar blar blar blar than',\n 'This is simhash test.',\n 'How are you i am fine. blar blar blar blar blar thank1']\n\n objects = []\n for k, v in enumerate(data):\n s = SimHash()\n s.update(v)\n objects.append((str(k), s))\n\n index = SimHashIndex(objects, k=10)\n\n\ndef test_init():\n lsh = MinHashIndex(threshold=0.8)\n assert lsh.is_empty() is True\n b1, r1 = lsh.b, lsh.r\n lsh = MinHashIndex(threshold=0.8, weights=(0.2, 0.8))\n b2, r2 = lsh.b, lsh.r\n assert b1 < b2\n assert r1 > r2\n\n\ndef test_minhash_add():\n lsh = MinHashIndex(threshold=0.5, num_perm=16)\n m1 = MinHash(f=16)\n m1.update(\"a\".encode(\"utf8\"))\n m2 = MinHash(f=16)\n m2.update(\"b\".encode(\"utf8\"))\n lsh.add(\"a\", m1)\n lsh.add(\"b\", m2)\n for t in lsh.hash_tables:\n assert len(t) >= 1\n items = []\n for H in t:\n items.extend(t[H])\n assert \"a\" in items\n assert \"b\" in items\n\n assert \"a\" in lsh\n assert \"b\" in lsh\n\n for i, H in enumerate(lsh.keys[\"a\"]):\n assert \"a\" in lsh.hash_tables[i][H]\n\n m3 = MinHash(18)\n assert_raises(ValueError, lsh.add, \"c\", m3)\n\n\ndef test_simhash_query():\n s1 = SimHash()\n s1.update('How are you? I Am fine. blar blar blar blar blar Thanks.')\n\n duplicates = index.query(s1)\n assert len(duplicates) == 1\n\n\n","sub_path":"tests/index_tests.py","file_name":"index_tests.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"548142460","text":"'''\nThis code is expected to convert any number into a string.\nIf it is a floating point value,\nit should round the number up to 2 decimal values then convert to a string\n'''\n\n# Prompt a user for a value\nnumber = input('Please insert a number \\n')\n\n\ndef formatMoney(number):\n '''\n :param number:\n :return: money_value (return the input as a string)\n '''\n try:\n if number.isdigit():\n number = int(number)\n money_value = '{:2,.2f}'.format(number)\n return money_value\n\n else:\n number = float(number)\n money_value = '{:2,.2f}'.format(number)\n return money_value\n\n except:\n return TypeError(\n f'Invalid type of {type(number)} for {number}. Provide Integer or Float')\n\n\ntest = formatMoney(number)\nprint(test)\n","sub_path":"FormatMoney/formatter.py","file_name":"formatter.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"275894529","text":"import msvcrt\nimport RadarBasic\n\nt_delay = 10e-6; # delay of echo in secs\nr_target = RadarBasic.RangeIs(t_delay) # calculate range\nprint(\"Time delay %f sec the Range is %f m\" %(t_delay, r_target) )\n\nr_target = 1e3; # target is 1 km away from radar\nt_delay = RadarBasic.PulseDelayIs(r_target)\t# calculate pulse delay\nprint(\"For Range %f m the delay is %f s\" % (r_target, t_delay))\n\n\nmsvcrt.getch()","sub_path":"Python/2017/Radar/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"102073741","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/7/24 14:22\n# @Author : Philly\n# @File : 09.py\n# @Description: 9 lines: Opening files\n# indent your Python code to put into an email\nimport glob\n# glob supports Unix style pathname extensions\npython_files = glob.glob('*.py')\nfor file_name in sorted(python_files):\n print(' --------' + file_name)\n with open(file_name, encoding='utf-8') as f:\n for line in f:\n print(' ' + line.rstrip())\n print()\n\n","sub_path":"thirty_three_cases/09.py","file_name":"09.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"521473276","text":"from video_stream_ffmpeg import VideoStreamFFmpeg\nfrom video_stream_cv import VideoStreamCV\nimport cv2\nimport time\n\ndef main():\n fsp = 30\n resolution = (640, 480)\n mirror = True\n cam_stream = VideoStreamFFmpeg(src=0, fps=fsp, resolution=resolution)\n # cam_stream = VideoStreamCV(src=0, fps=fsp, resolution=resolution)\n window_name = \"{0}\".format(cam_stream.__class__.__name__)\n \n while True:\n img = cam_stream.read()\n if img is not None:\n if mirror: \n img = cv2.flip(img, 1)\n cv2.imshow(window_name, img)\n if cv2.waitKey(1) == 27: \n break # esc to quit\n\n cam_stream.release()\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python3_playground/ffmpeg_stream/play_2.py","file_name":"play_2.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"373315917","text":"import numpy as np\nfrom sklearn.datasets import load_digits\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import accuracy_score\nimport warnings\n\nwarnings.filterwarnings('ignore')\n\nfrom sklearn.datasets import load_digits\ndigits = load_digits()\n'''\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.80, random_state=0)\n\nX = digits.data\ny = digits.target\n\nprint(len(X))\n\nX = np.loadtxt(\"adult_clean.csv\", usecols=(0, 2, 4, 10, 11, 12), skiprows=1, delimiter=',')\n# Outcome variable\n\nY = np.loadtxt(\"adult_clean.csv\", usecols=14, dtype=str, skiprows=1, delimiter=',')\n\n\n'''\n\n# 3 clients, 500 each\nX = digits.data\nY = digits.target\nX_train1, y_train1 = X[:500], Y[:500]\nX_train2, y_train2 = X[500:1000], Y[500:1000]\nX_train3, y_train3 = X[1000:1500], Y[1000:1500]\n\nX_test, y_test = X[1500:], Y[1500:]\n\nlogisticRegr1 = LogisticRegression()\nlogisticRegr1.fit(X_train1, y_train1)\nscore = logisticRegr1.score(X_test, y_test)\nprint(score)\n\nlogisticRegr2 = LogisticRegression()\nlogisticRegr2.fit(X_train2, y_train2)\nscore = logisticRegr2.score(X_test, y_test)\nprint(score)\n\nlogisticRegr3 = LogisticRegression()\nlogisticRegr3.fit(X_train3, y_train3)\nscore = logisticRegr3.score(X_test, y_test)\nprint(score)\n\ncoef = np.average([logisticRegr1.coef_, logisticRegr2.coef_, logisticRegr3.coef_], axis = 0)\n\nlogisticRegr3.coef_ = coef\nscore = logisticRegr3.score(X_test, y_test)\nprint(score)\n","sub_path":"other/Research/logRegExperiment.py","file_name":"logRegExperiment.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"212409997","text":"import subprocess\nimport basetest\n\n\nclass TestCaseBuildStatusCallback(basetest.BaseTest):\n def test_model_has_inconsistency_errors(self):\n self._test_helper(\"model-with-consistency-errors-7.0.2.mpk\")\n try:\n self.startApp()\n except subprocess.CalledProcessError:\n logs_out = self.cmd((\"cf\", \"logs\", self.app_name, \"--recent\"))\n print(logs_out)\n assert \"Submitting build status\" in logs_out\n\n def test_model_has_no_inconsistency_errors(self):\n self._test_helper(\"empty-model-7.0.2.mpk\")\n self.startApp()\n self.assert_app_running()\n\n def _test_helper(self, package_name):\n self.setUpCF(\n package_name,\n env_vars={\n \"FORCE_WRITE_BUILD_ERRORS\": \"true\",\n \"BUILD_STATUS_CALLBACK_URL\": \"http://localhost/buildstatus\",\n },\n )\n","sub_path":"tests/usecase/test_buildstatus_callback.py","file_name":"test_buildstatus_callback.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"347460611","text":"from skimage import io, color\nfrom matplotlib import pyplot as plt\nimport string\nimport random\n\nimport Cluster\nimport Node\n\n__author__ = 'Camilo'\n\n\ndef main(img_path, threshold):\n image_array = io.imread(img_path)\n lab = color.rgb2lab(image_array)\n\n pixels = graph_cut(image_array, lab, threshold)\n\n plt.subplot(121), plt.imshow(plt.imread(img_path)), plt.title('Original')\n plt.subplot(122), plt.imshow(pixels), plt.title('Using GraphCut')\n plt.show()\n\n\ndef graph_cut(pixels, lab, threshold):\n rows = range(len(pixels))\n cols = range(len(pixels[0]))\n\n graph = create_graph(rows, cols)\n\n init_graph(graph, rows, cols, pixels, lab)\n\n clusters = create_clusters(graph, threshold)\n\n color_clusters(clusters)\n\n build_image(pixels, graph, rows, cols)\n\n return pixels\n\n\ndef create_graph(rows, cols):\n print(\"Creating Graph...\")\n return [[Node.Node(i, j, random.choice(string.ascii_letters)) for j in cols] for i in rows]\n\n\ndef init_graph(graph, rows, cols, pixels, lab):\n print(\"Calculating colors and linking neighbors for each node...\")\n for i in rows:\n for j in cols:\n current_node = graph[i][j]\n\n current_node.set_values(pixels[i][j], lab[i][j])\n\n if i > 0:\n neighbor = graph[i - 1][j]\n current_node.neighbors.append(neighbor)\n\n if j > 0:\n neighbor = graph[i][j - 1]\n current_node.neighbors.append(neighbor)\n\n if j < (len(cols) - 1):\n neighbor = graph[i][j + 1]\n current_node.neighbors.append(neighbor)\n\n if i < (len(rows) - 1):\n neighbor = graph[i + 1][j]\n current_node.neighbors.append(neighbor)\n\n\ndef create_clusters(graph, threshold):\n print(\"Making cuts and creating clusters...\")\n\n clusters = []\n for row in graph:\n for node in row:\n\n for neighbor in node.neighbors:\n delta_e = get_color_difference(neighbor.lab_values, node.lab_values)\n\n if delta_e > threshold:\n node.cut(neighbor)\n neighbor.cut(node)\n\n for cluster in clusters:\n if cluster.belongs_to_cluster(node, threshold):\n cluster.nodes.append(node)\n node.cluster()\n break\n\n if not node.clustered:\n new_cluster = Cluster.Cluster()\n new_cluster.add_node(node)\n clusters.append(new_cluster)\n return clusters\n\n\ndef color_clusters(clusters):\n print(\"Recoloring clusters...\")\n colors_used = []\n for cluster in clusters:\n cluster.colourify(colors_used)\n\n\ndef build_image(pixels, graph, rows, cols):\n print(\"Constructing Image...\")\n for i in rows:\n for j in cols:\n current_node = graph[i][j]\n pixels[i][j] = current_node.rgb_values\n\n\n# Color difference using the Cie76 Formula\ndef get_color_difference(lab1, lab2):\n return ((lab2[0] - lab1[0]) ** 2 + (lab2[1] - lab1[1]) ** 2 + (lab2[2] - lab1[2]) ** 2) ** 0.5\n\n\nmain(\"../Img/Sample_TIFF.tiff\", 15)\n","sub_path":"Scripts/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"112026638","text":"\nimport csv\nimport numpy\nimport idSim\nimport time\nimport FBC_KNN_genres as FKG\nimport FBC_KNN_users as FKU\nimport FBC_KNN_movie_reviews as FKMR\n\nCONST_TOTAL_MOVIES = 3564\nCONST_TOTAL_USERS = 3974\nCONST_K = 35\nCONST_DECIMAL_PLACES = 100\nCONST_SIM = 1\nCONST_TRAIN_FILE = \"train_data.csv\"\nCONST_TEST_FILE = \"test_data.csv\"\nCONST_SIM_FILE_NAME = \"results/similarities_by_review_30_words.csv\"\nCONST_OUTPUT_FILE = \"results/output.csv\"\nW_1 = 1\nW_2 = 7\nW_3 = 3\n\n\ndef globalMean(ratingsMatrix, movieID, userID):\n\n totalRating = 0.0\n numReviews = 0\n\n # avalia a media global do item\n for i in range(0, len(ratingsMatrix)-1):\n if ratingsMatrix[i][movieID-1] != 0:\n totalRating += ratingsMatrix[i][movieID-1]\n numReviews += 1\n # se o item possui uma media global, retorne-a\n if numReviews != 0:\n return totalRating / numReviews\n # se nao possui\n else:\n # calcula a media do usuario\n for i in range(0, len(ratingsMatrix[0])-1):\n if ratingsMatrix[userID-1][i] != 0:\n totalRating += ratingsMatrix[userID-1][i]\n numReviews += 1\n # se o usuario possui uma media global, retorne-a\n if numReviews != 0:\n return totalRating / numReviews\n # se o usuario nao possui uma media global, retorna um valor mediano fixo 3\n else:\n return 3\n\n return totalRating / numReviews\n\n\ndef calculateFinalSim(A, B):\n\n id_and_sim = list([])\n # verifica os filmes que estão em ambas as listas\n # e retorna a similaridade média deles\n for eachA in A:\n for eachB in B:\n if eachA.id == eachB.id:\n finalSim = (eachA.sim + eachB.sim) / 2\n auxIdSim = idSim.idSim(eachA.id, finalSim)\n id_and_sim.append(auxIdSim)\n break\n\n # print(\"tamanho:\", len(id_and_sim))\n return id_and_sim\n\n\ndef predictRating(userID, movieID, ratingsMatrix, moviesSimMatrix, byUser, option):\n\n userID = int(userID)\n movieID = int(movieID)\n\n # -- CRIAÇÃO DA LISTA DE SIMILARIDADES --\n id_and_sim = list([])\n aux_id_and_sim = list([])\n\n # -------- OPCOES DE ALGORITMOS --------\n if option == '1' or option == '5':\n id_and_sim = FKG.fbc_knn_genres(movieID, ratingsMatrix, userID, CONST_K)\n elif option == '2':\n id_and_sim = FKU.fbc_knn_users(userID, ratingsMatrix, movieID, CONST_K)\n elif option == '3':\n id_and_sim = FKMR.fbc_knn_movie_reviews(userID, ratingsMatrix, movieID, moviesSimMatrix, CONST_K)\n elif option == '4':\n id_and_sim = FKG.fbc_knn_genres(movieID, ratingsMatrix, userID, CONST_K)\n aux_id_and_sim = FKMR.fbc_knn_movie_reviews(userID, ratingsMatrix, movieID, moviesSimMatrix, CONST_K)\n id_and_sim = calculateFinalSim(id_and_sim, aux_id_and_sim)\n else:\n exit(\"Erro. Opção inexistente\")\n\n simSum = 0\n ratingSum = 0\n\n # PARA CADA UM DOS FILMES MAIS SIMILARES:\n for eachSimilar in id_and_sim:\n simSum += eachSimilar.sim\n # flag para quando o knn_users for usado\n if byUser == 1:\n ratingSum += eachSimilar.sim * ratingsMatrix[eachSimilar.id-1][movieID-1]\n elif byUser == 0:\n ratingSum += eachSimilar.sim * ratingsMatrix[userID-1][eachSimilar.id-1]\n\n # se o usuario nao deu nenhuma avaliação,\n # ou se o item não tem nenhuma avaliação,\n # pega a media global do item\n if len(id_and_sim) == 0:\n return round(globalMean(ratingsMatrix, movieID, userID), CONST_DECIMAL_PLACES)\n\n return round(ratingSum / simSum, CONST_DECIMAL_PLACES)\n\n\ndef create_moviesSimMatrix():\n\n csv_file = open(CONST_SIM_FILE_NAME, encoding=\"utf8\")\n csv_reader = csv.reader(csv_file, delimiter=',')\n next(csv_reader)\n\n moviesSimMatrix = numpy.zeros(shape=(CONST_TOTAL_MOVIES, CONST_TOTAL_MOVIES))\n\n for row in csv_reader:\n id1, id2, sim = row\n print(\"Lendo similaridades do filme de ID\", id1)\n moviesSimMatrix[int(id1)-1][int(id2)-1] = round(float(sim), 4) * CONST_SIM\n moviesSimMatrix[int(id2) - 1][int(id1) - 1] = round(float(sim), 4) * CONST_SIM\n\n return moviesSimMatrix\n\n\ndef menu():\n print(\"1) FBC-KNN por gênero\")\n print(\"2) FBC-KNN por usuário\")\n print(\"3) FBC-KNN por análise\")\n print(\"4) Hibridização monolítica\")\n print(\"5) Hibridização paralela\")\n\n\ndef optionChosen(option):\n if option == '2':\n return 1\n else:\n return 0\n\n\ndef main():\n\n # -- ABRE ARQUIVO DE TREINO --\n csv_file = open(CONST_TRAIN_FILE)\n csv_train = csv.reader(csv_file, delimiter=',')\n next(csv_train)\n\n # matriz de ratings USERS x MOVIES\n ratingsMatrix = numpy.zeros(shape=(CONST_TOTAL_USERS, CONST_TOTAL_MOVIES))\n\n # -- LENDO DADOS DE TREINO --\n # guardando todos os ratings em objetos do tipo Umr\n print(\"Lendo as avaliações...\")\n for row in csv_train:\n userID, movieID, rating, timeStamp = row\n # se for um novo usuario\n ratingsMatrix[int(userID)-1][int(movieID)-1] = int(rating)\n csv_file.close()\n\n # -- ABRE ARQUIVO DE TESTE --\n csv_file = open(CONST_TEST_FILE)\n csv_test = csv.reader(csv_file, delimiter=',')\n next(csv_test)\n\n # -- CRIA ARQUIVO DE OUTPUT --\n file = open(CONST_OUTPUT_FILE, 'w')\n fields = ('id', 'rating')\n wr = csv.DictWriter(file, fieldnames=fields, lineterminator='\\n')\n wr.writeheader()\n\n # -- MOSTRA O MENU E AVALIA A OPÇÃO ESCOLHIDA\n moviesSimMatrix = None\n menu()\n option = input()\n byUser = optionChosen(option)\n\n start_time = time.time()\n\n # opções que usam o FBC_KNN_REVIEW\n if option == '3' or option == '4' or option == '5':\n # matriz de similaridade MOVIES x MOVIES\n moviesSimMatrix = create_moviesSimMatrix()\n\n\n # -- CALCULA A PREDIÇÃO E COLOCA NO ARQUIVO E NO OUTPUT --\n print(\"Calculando as predições...\")\n\n # -- PREDIÇÕES --\n for row in csv_test:\n\n ratingID, userID, movieID, timeStamp = row\n prediction = predictRating(userID, movieID, ratingsMatrix, moviesSimMatrix, byUser, option)\n\n # se for a opção de hibridização paralela, faço a predição com os outros 2 modelos\n if option == '5':\n prediction2 = predictRating(userID, movieID, ratingsMatrix, moviesSimMatrix, 1, '2')\n prediction3 = predictRating(userID, movieID, ratingsMatrix, moviesSimMatrix, 0, '3')\n\n prediction = ((W_1 * prediction) + (W_2 * prediction2) + (W_3 * prediction3)) / (W_1 + W_2 + W_3)\n\n # AQUI É INSERIDA A PREDIÇÃO NO ARQUIVO DE SAÍDA\n wr.writerow({'id': ratingID, 'rating': prediction})\n\n auxStr = str(ratingID) + ',' + str(prediction)\n print(auxStr)\n\n print(\"--- %s segundos ---\" % (time.time() - start_time))\n\n csv_file.close()\n file.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"sysrec/sysrect2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"41314630","text":"from lensesio.core.ws_auth import WebsocketAuth\nfrom lensesio.core.endpoints import getEndpoints\nimport websocket\nimport json\n\n\nclass DataSubscribe(WebsocketAuth):\n\n def __init__(self):\n getEndpoints.__init__(self, \"websocketEndpoints\")\n\n self.lenses_websocket_endpoint = self.url + self.lensesWebsocketEndpoint\n\n if 'https' in self.lenses_websocket_endpoint:\n self.lenses_websocket_endpoint = self.lenses_websocket_endpoint.replace(\n \"https\", \"wss\"\n )\n else:\n self.lenses_websocket_endpoint = self.lenses_websocket_endpoint.replace(\n \"http\", \"ws\"\n )\n\n def Publish(self, topic, key, value, clientId='LensesPy'):\n self._Login(clientId)\n\n requestdict = {\n \"type\": \"PUBLISH\",\n \"content\": '{\"topic\" :\"' + topic + '\",\"key\" :\"' + key + '\",\"value\" : \"' + value + '\"}',\n \"correlationId\": 1,\n \"authToken\": self.wc_conn_token\n }\n\n ws_con = websocket.create_connection(self.url_req)\n ws_con.send(json.dumps(requestdict))\n\n self.publish = json.loads(ws_con.recv())\n ws_con.close()\n return self.publish\n\n def Commit(self, topic, partition, offset, clientId='LensesPy'):\n self._Login(clientId)\n\n requestdict = {\n \"type\": \"COMMIT\",\n \"content\": '{\"commits\": [{\"topic\":\"' + str(topic) + '\",\"partition\":\"' + str(partition) + '\",\"offset\" : \"' + str(offset) + '\"}]}',\n \"correlationId\": 1,\n \"authToken\": self.wc_conn_token\n }\n\n ws_con = websocket.create_connection(self.url_req)\n ws_con.send(json.dumps(requestdict))\n\n self.commit = json.loads(ws_con.recv())\n ws_con.close()\n return self.commit\n\n def Subscribe(self, dataFunc, query, clientId='LensesPy'):\n self._Login(clientId)\n\n request = {\n \"type\": \"SUBSCRIBE\",\n \"content\": '{\"sqls\" : [\"' + query + '\"]}',\n \"correlationId\": 1,\n \"authToken\": self.wc_conn_token\n }\n\n ws_con = websocket.create_connection(self.url_req)\n ws_con.send(json.dumps(request))\n\n while True:\n bucket = json.loads(ws_con.recv())\n if bucket['type'] == 'KAFKAMSG':\n for message in bucket['content']:\n dataFunc(message)\n elif bucket['type'] in ['HEARTBEAT', 'SUCCESS']:\n dataFunc(bucket)\n\n ws_con.close()\n\n def Unsubscribe(self, topic, clientId='LensesPy'):\n self._Login(clientId)\n\n requestjson = {\n \"type\": \"UNSUBSCRIBE\",\n \"content\": '{\"topics\": [\"' + topic + '\"]}',\n \"correlationId\": 1,\n \"authToken\": self.wc_conn_token,\n }\n\n ws_con = websocket.create_connection(self.url_req)\n ws_con.send(json.dumps(requestjson))\n\n self.unscribe = json.loads(ws_con.recv())\n ws_con.close()\n return self.unscribe\n","sub_path":"lensesio/data/data_subscribe.py","file_name":"data_subscribe.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"291912289","text":"__author__ = 'Boone Adkins'\n\n# Github path : https://github.com/b-adkins/cvutils\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef inria_hog_reshape(hog, win_size, block_size, block_stride, cell_size, nbins):\n '''\n Reshapes a 1D Histogram of Oriented Gradients to a 4D array.\n :param hog: A HOG descriptor following the INRIA standard. (E.g. from\n OpenCV.) Shape must be (x, y, cell, bin)\n :param win_size: Window size two-tuple, (x, y).\n :param block_size: Block size two-tuple, (x, y)\n :param block_stride: How far each successive block is shifted. Two-tuple,\n (x, y).\n :param cell_size: Cell size two-tuple, (x, y).\n :param nbins: Number of angle bins.\n :return: Hog with shape (x, y, cell, bin)\n '''\n new_shape = [win_size[1]/block_stride[1] - 1, win_size[0]/block_stride[0] - 1,\n block_size[0]/cell_size[0]*block_size[1]/cell_size[1], nbins]\n hog.shape = new_shape\n return hog\n\ndef plot_hog_grid(win_size, cellSize, color='g'):\n plt.vlines(np.arange(0, win_size[0], cellSize[0]), 0, win_size[1], color=color)\n plt.hlines(np.arange(0, win_size[1], cellSize[1]), 0, win_size[0], color=color)\n\ndef plot_hog(hog, win_size, cell_size, n_bins, combine_bins=True, color='r', **kwargs):\n '''\n Visualizes a Histogram of Oriented Gradients using glyphs.\n :param hog: A HOG descriptor. Shape must be (x, y, cell, bin)\n :param win_size: Window size two-tuple, (x, y).\n :param cell_size: Cell size two-tuple, (x, y).\n :param n_bins: Number of angle bins.\n :param combine_bins: True to display the vector sum of the angle bins\n False to display a line for each one.\n :param color: Any acceptable Matplotlib color.\n :param kwargs: Will be passed directly to pyplot.quiver().\n :return:\n '''\n\n # Default plot settings\n kwargs_ = {'scale': cell_size[0], 'width': 0.01, 'headwidth': 1e-9, 'angles': 'xy', 'minshaft': 1, 'pivot': 'mid',\n 'headlength': 1e-9, 'headaxislength': 1e-9}\n kwargs_.update(kwargs) # Overwrites existing settings\n\n hog = np.swapaxes(hog, 0, 1) # Swaps x, y to y, x\n\n x = np.arange(cell_size[0]/2, win_size[0] - cell_size[0], cell_size[0])\n y = np.arange(cell_size[1]/2, win_size[1] - cell_size[1], cell_size[1])\n X, Y = np.meshgrid(x, y)\n\n angles = np.arange(0, np.pi, np.pi/n_bins)\n u = hog[:, :, 0, :] * np.cos(angles)\n v = hog[:, :, 0, :] * np.sin(angles)\n\n n_bins = 9 # Number of bins\n if combine_bins:\n U = np.sum(u, axis=2)\n V = np.sum(v, axis=2)\n lengths = np.sqrt(U**2 + V**2)\n U /= np.max(lengths)\n V /= np.max(lengths)\n\n plt.quiver(X, Y, U, V, color=color, **kwargs_)\n else:\n # Plot each HOG angle\n for b in range(0, n_bins): # The HOG angles bins\n U = u[:, :, b]\n V = v[:, :, b]\n lengths = np.sqrt(U**2 + V**2)\n U /= np.max(lengths)\n V /= np.max(lengths)\n\n plt.quiver(X, Y, U, V, color=color, **kwargs_)\n\n\t\t\t\n# Showing Kanak how git works\t\t\t","sub_path":"Misc/hog_vis.py","file_name":"hog_vis.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"639832100","text":"'''\nLinear search algorithm to return the index of an element in an array\n\nPseudocode\nfor(start to end of array)\n{\n if (current_element equals to m) \n {\n print (current_index);\n }\n}\n'''\n\ndef linear_search(arr, m):\n for index, element in enumerate(arr):\n if element == m:\n return index\n return -1\n\nlist_1 = list(range(15))\nlist_2 = list (range(0,30,2))\n\nprint(linear_search(['b','d','e','v','a','y'], 'a'))\nprint(linear_search(list_1,9))\nprint(linear_search(list_2,9))\n\n","sub_path":"D2_assessment/algorithms/linear search/linear_search.py","file_name":"linear_search.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"496341254","text":"\n# code: utf-8\n\nimport matplotlib.pyplot as plt\nimport mne\nimport numpy as np\nimport os\nimport time\nimport sys\n\nfrom copy import deepcopy\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import ShuffleSplit\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn import svm\nfrom sklearn import metrics\n\n'''\nThis script is to score MEG RSVP data.\nScoring is using MVPA and cross-validation.\nTraining data is cropped from 1.0~2.0 seconds, so names as middleTrain.\nThere are several filter parameters in preprocessing.\nUsing csp for feature extraction.\nUsing OneClassSVM as classifier.\nSaving scores into npz files.\n'''\n\n##############\n# Parameters #\n##############\ntime_stamp = time.strftime(\n 'RSVP_MEG_middleTrain_OneClassSVM_%Y-%m-%d-%H-%M-%S')\nprint('Initing parameters.')\n# Results pdf path\n# root_path = os.path.join('D:\\\\', 'RSVP_MEG_experiment', 'scripts', 'RSVP')\nroot_path = os.path.join('/', 'nfs', 'cell_a', 'userhome', 'zcc', 'Documents', 'RSVP_MEG_experiment', 'scripts', 'RSVP')\nresult_dir = os.path.join(root_path, 'results', time_stamp)\nif not os.path.exists(result_dir):\n os.mkdir(result_dir)\n\nnpz_path = os.path.join(result_dir, 'npz_%s.npz')\n\n# Parameter for read raw\nfile_dir = os.path.join(root_path, '..', '..', 'rawdata',\n '20190326_RSVP_MEG_%s',\n 'S%02d_lixiangTHU_20190326_%02d.ds')\nsubject_name = 'maxuelin'\nsubject_idx = 2\n# if len(sys.argv) > 1:\n# subject_name = sys.argv[1]\n# subject_idx = int(sys.argv[2])\nrun_idx = [e for e in range(4, 11)]\n# run_idx = [5, 7]\n\n# Parameter for preprocess raw\nfreq_l, freq_h = 0.1, 7\nfir_design = 'firwin'\nmeg = True\nref_meg = False\nexclude = 'bads'\n\n# Parameter for epochs\nevent_id = dict(Odd=1, Norm=2)\ntmin, t0, tmax = -0.2, 0, 1\nfreq_resample = 200\ndecim = 1\nreject = dict(mag=5e-12)\nstim_channel = 'UPPT001'\n\n# frequency\nn_cycles = 2\nnum = 20\n\n# MVPA\ntmin_middle, tmax_middle = 0.2, 0.5\nn_components = 6\nrepeat_times = 10\nn_folder = 10\n\n# multi cores\nn_jobs = 32\n\n# prepare rawobject\nraw_files = [mne.io.read_raw_ctf(\n file_dir % (subject_name, subject_idx, j), preload=True)\n for j in run_idx]\n[e.filter(freq_l, freq_h, fir_design=fir_design) for e in raw_files]\nraw = mne.concatenate_raws(raw_files)\n# raw.filter(freq_l, freq_h, fir_design=fir_design)\n# choose channel type\npicks = mne.pick_types(raw.info, meg=meg, ref_meg=ref_meg, exclude=exclude)\n\n#############\n# Let it go #\n#############\n# Get epochs\nprint('Getting epochs.')\nevents = mne.find_events(raw, stim_channel=stim_channel)\nbaseline = (tmin, t0)\nepochs = mne.Epochs(raw, event_id=event_id, events=events,\n decim=decim, tmin=tmin, tmax=tmax,\n picks=picks, baseline=baseline,\n detrend=1,\n reject=reject, preload=True)\nepochs.resample(freq_resample, npad=\"auto\")\n\n# Exclude abscent channels in layout\nch_names = [e[0:5] for e in epochs.ch_names]\nlayout_all = mne.find_layout(epochs.info)\nex = [e for e in layout_all.names if e not in ch_names]\nprint('Exclude channels are', ex)\n# layout_all.plot(picks=[layout_all.names.index(e) for e in ex])\nlayout = mne.find_layout(epochs.info, exclude=ex)\n\n# MVPA\nepochs_train = epochs.copy().crop(tmin=tmin_middle, tmax=tmax_middle)\nlabels = epochs.events[:, -1]\nepochs_data = epochs.get_data()\nepochs_data_train = epochs_train.get_data()\n\n# CSP LR demo\ncv = ShuffleSplit(n_folder, test_size=0.2)\ncsp = mne.decoding.CSP(n_components=n_components, reg=None,\n log=True, norm_trace=False)\nocsvm = svm.OneClassSVM(nu=0.1, gamma='auto')\n\n# MVPA time_resolution\n# make windows\nsfreq = epochs.info['sfreq']\nw_length = int(sfreq * 0.1) # running classifier: window length\nw_step = int(sfreq * 0.05) # running classifier: window step size\nw_start = np.arange(0, epochs_data.shape[2] - w_length, w_step)\n\nprint('repeat_times:', repeat_times)\nprint('n_folder:', cv.get_n_splits())\nprint('windows_number:', len(w_start))\n\n# prepare csp_pipelines and scores\ncsp_pipeline = make_pipeline(\n mne.decoding.Scaler(epochs_train.info),\n csp, mne.decoding.Vectorizer())\nscores = np.zeros(\n [repeat_times, cv.get_n_splits(), len(w_start)])\n# sccuracy\nscores_Acc = deepcopy(scores)\n# recall\nscores_Rec = deepcopy(scores)\n\nfor rep in range(repeat_times):\n # for each repeat\n print(rep)\n # n_folder cross validation\n for split, idxs in enumerate(cv.split(epochs_data)):\n print(rep, ':', split)\n train_idx, test_idx = idxs\n # labels\n y_train, y_test = labels[train_idx], labels[test_idx]\n # training data\n X_train = epochs_data_train[train_idx]\n\n # fit\n X_train_csp = csp_pipeline.fit_transform(X_train, y_train)\n ocsvm.fit(X_train_csp[y_train == 2])\n\n for w, n in enumerate(w_start):\n # testing data\n X_test = epochs_data[test_idx][:, :, n:(n+w_length)]\n\n X_test_csp = csp_pipeline.transform(X_test)\n\n y_predict = ocsvm.predict(X_test_csp)\n y_predict = y_predict * 0.5 + 1.5\n\n # scoring acc\n score_acc = metrics.accuracy_score(y_test, y_predict)\n # scoring rec\n score_rec = metrics.recall_score(y_test, y_predict)\n\n # storing scores\n scores_Acc[rep, split, w] = score_acc\n scores_Rec[rep, split, w] = score_rec\n\n\n# time line\nw_times = (w_start + w_length / 2.) / sfreq + epochs.tmin\n\n# save into npz file\nnp.savez(npz_path % str(freq_resample),\n scores_Acc=scores_Acc,\n scores_Rec=scores_Rec,\n w_times=w_times)\n","sub_path":"RSVP/MVPA_RSVP_MEG_middleTrain_OneClassSVM.py","file_name":"MVPA_RSVP_MEG_middleTrain_OneClassSVM.py","file_ext":"py","file_size_in_byte":5669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"214953375","text":"import numpy as np\r\nfrom grabscreen import grab_screen\r\nimport cv2\r\nimport time\r\nfrom getkeys import key_check\r\nimport os\r\n\r\ndef keys_to_output(keys):\r\n '''\r\n [D, S, A, W]\r\n '''\r\n output = [0, 0, 0, 0]\r\n \r\n if 'D' in keys:\r\n output [0] = 1\r\n\r\n elif 'S' in keys:\r\n output [1] = 1\r\n\r\n elif 'A' in keys:\r\n output [2] = 1\r\n\r\n else:\r\n output [3] = 1\r\n\r\n return output\r\n\r\n\r\nfile_name = 'training_data.npy'\r\n\r\nif os.path.isfile(file_name):\r\n print(\"File exists, loading previous data.\")\r\n training_data = list(np.load(file_name))\r\nelse:\r\n print(\"File does not exist, starting fresh.\")\r\n training_data = []\r\n\r\n\r\ndef main():\r\n \r\n for i in list(range(4))[::-1]:\r\n print(i+1)\r\n time.sleep(1)\r\n last_time = time.time()\r\n\r\n paused = False\r\n while(True):\r\n screen = grab_screen(region=(0, 50, 600, 700))\r\n last_time = time.time()\r\n screen = cv2.cvtColor(screen, cv2.COLOR_BGR2HSV)\r\n screen = cv2.resize(screen,(80, 60))\r\n keys = key_check()\r\n output = keys_to_output(keys)\r\n training_data.append([screen, output])\r\n print('Loop took {} seconds'.format(time.time() - last_time))\r\n last_time = time.time()\r\n\r\n if len(training_data) % 1000 == 0:\r\n print(len(training_data))\r\n np.save(file_name, training_data)\r\n\r\nmain()\r\n","sub_path":"Project/Snake/Script/script_HSV.py","file_name":"script_HSV.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"547956067","text":"import unittest\nfrom com.project.src.PythonCrashCourse.IOPuts.IOFile import IOFile\n\n\nclass IOFileTest(unittest.TestCase):\n path = '/com/project/src/PythonCrashCourse/IOPuts/Resource\\\\'\n\n def test_readFileByLine_returns_ListOfLines(self,path = path):\n \"\"\"io.readFile() expected 'ListOfLine'\"\"\"\n iof = IOFile\n path += 'textfile.txt'\n actual = iof.readFileByLine(path)\n actual= len(actual)\n expected = 3\n self.assertEqual(actual, expected)\n\n \"\"\"\n def test_readDelimterByLine_returns_LengthOf6(self, path=path):\n iof = IOFile\n path += 'delimitRead.txt'\n actual = iof.readDelimterByLine(iof, path, ',')\n actual = len(actual)\n expected = 5\n self.assertEqual(actual, expected)\n\n def test_writeToFileDelimter_returns_LengthOf1(self, path=path):\n iof = IOFile\n path += 'delimitWrite.txt'\n iof.writeToFileDelimiter(iof, path, 'Goldman Sacs', 'GS', ',')\n actual = iof.readDelimterByLine(iof, path, ',')\n actual = len(actual)\n expected = 1\n self.assertEqual(actual, expected)\n\n def test_appendToFileDelimter_returnsAddToExistingFile(self,path = path):\n iof = IOFile\n path += 'delimitAppend.txt'\n iof.writeToFileDelimiter(iof,path,'','','')\n iof.appendToFileDelimiter(iof,path,'Goldman Sacs','GS',',')\n iof.appendToFileDelimiter(iof, path, 'Blackstone', 'BX', ',')\n actual = iof.readDelimterByLine(iof, path , ',')\n actual = len(actual)\n expected = 2\n self.assertEqual(actual,expected)\n\n def test_deleteContentFile_returns0lines(self,path = path):\n iof = IOFile\n path += 'delimitDelete.txt'\n iof.appendToFileDelimiter(iof, path, 'Goldman Sacs', 'GS', ',')\n iof.appendToFileDelimiter(iof, path, 'Blackstone', 'BX', ',')\n actual = iof.readDelimterByLine(iof,path,',')\n actual = len(actual)\n iof.deleteContentFile(iof,path)\n expected = iof.readDelimterByLine(iof, path, ',')\n expected = len(expected)\n self.assertEqual(actual-2,expected)\n \"\"\"\n\n\n","sub_path":"com/project/src/PythonCrashCourse/UnitTesting/IOTest/TestIOFile.py","file_name":"TestIOFile.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"589771871","text":"from django.contrib.auth.models import User\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom .serializer import BookSerializer\nfrom rest_framework.generics import RetrieveAPIView, UpdateAPIView, DestroyAPIView\nfrom rest_framework import viewsets, filters, generics\nfrom .models import Book, Order\nfrom rest_framework.permissions import (\nAllowAny,IsAuthenticated,IsAdminUser,IsAuthenticatedOrReadOnly\n)\n\n\nclass BookViewSet(viewsets.ModelViewSet):\n queryset = Book.objects.all()\n serializer_class = BookSerializer\n\nclass BookDetail(RetrieveAPIView):\n queryset = Book.objects.all()\n serializer_class = BookSerializer\n lookup_field = 'id'\n\nclass BookUpdate(UpdateAPIView):\n queryset = Book.objects.all()\n serializer_class = BookSerializer\n lookup_field = 'id'\n\n\nclass BookDelete(DestroyAPIView):\n queryset = Book.objects.all()\n serializer_class = BookSerializer\n lookup_field = 'id'\n\nclass BookSearch(generics.ListCreateAPIView):\n queryset = Book.objects.all()\n serializer_class = BookSerializer\n filter_backends = [filters.SearchFilter,]\n search_fields = ['name','author']\n ordering_fields = ['name', 'author']\n\n\n\n\n","sub_path":"books/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"460671797","text":"import face_recognition\nimport cv2\nimport os\nimport pickle\n\nknown_face_encodings = []\nknown_face_names = []\nBASE_DIR=os.path.dirname(os.path.abspath(__file__))\nimage_dir=os.path.join(BASE_DIR,'images')\n\n\nfor (root,dirs,files) in os.walk(image_dir):\n for file in files:\n if file.endswith('png') or file.endswith('jpg'):\n path = os.path.join(root,file)\n label=os.path.basename(root).replace(' ',\"-\").lower()\n person_image = face_recognition.load_image_file(path)\n person_face_encoding = face_recognition.face_encodings(person_image)\n if person_face_encoding:\n known_face_encodings.append(person_face_encoding[0])\n known_face_names.append(label)\n else:\n os.remove(path)\n#print(known_face_names)\nwith open('./train_data/know_face.pickle','wb') as f:\n pickle.dump(known_face_names,f)\nwith open(\"./train_data/know_face_encode.pickle\",'wb') as f:\n pickle.dump(known_face_encodings,f)\n","sub_path":"train_face.py","file_name":"train_face.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"651149729","text":"import jsonpickle as jsonpickle\nimport logging\nimport socket\nfrom tkinter import *\nfrom tkinter import messagebox\nfrom tkinter.ttk import Combobox\n\nfrom oef3.data.calcData import *\n\n\ndef show_result(num):\n messagebox.showinfo(\"Result\", f\"res = {num}\")\n\n\nclass Window(Frame):\n\n def __init__(self, master=None):\n Frame.__init__(self, master)\n self.master = master\n self.init_window()\n self.host = socket.gethostname()\n self.port = 9999\n self.makeConnnectionWithServer()\n\n def init_window(self):\n self.master.title(\"Stopafstand\")\n self.pack(fill=BOTH, expand=1)\n\n Label(self, text=\"Snelheid (km/u):\").grid(row=0)\n Label(self, text=\"Reactietijd (sec):\", pady=10).grid(row=1)\n Label(self, text=\"Type wegdek:\", pady=10).grid(row=2)\n\n self.entry_snelheid = Entry(self, width=40)\n self.entry_reactietijd = Entry(self, width=40)\n self.entry_wegdek = Entry(self, width=40)\n self.entry_snelheid.grid(row=0, column=1, sticky=E + W, pady=(5, 5))\n self.entry_reactietijd.grid(row=1, column=1, sticky=E + W)\n\n choices = ('Droog',\n 'Nat')\n self.cbo_wegdek = Combobox(self, state=\"readonly\", width=40)\n self.cbo_wegdek['values'] = choices\n self.cbo_wegdek.grid(row=2, column=1, sticky=E + W)\n Label(self, text=\"km/u\").grid(row=0, column=2)\n Label(self, text=\"sec\", pady=10).grid(row=1, column=2)\n self.buttonCalculate = Button(self, text=\"Bereken stopafstand\", command=self.calculateStopafstand)\n self.buttonCalculate.grid(row=3, column=0, columnspan=3, pady=(0, 5), padx=(5, 5), sticky=N + S + E + W)\n Grid.rowconfigure(self, 2, weight=1)\n Grid.columnconfigure(self, 1,\n weight=1)\n\n def __del__(self):\n self.close_connection()\n\n def makeConnnectionWithServer(self):\n socket_to_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.conn = socket_to_server.connect((self.host, self.port))\n self.writer = socket_to_server.makefile(mode='rw')\n\n def calculateStopafstand(self):\n data = CalcData(\n snelheid=float(self.entry_snelheid.get()),\n reactie=float(self.entry_reactietijd.get()),\n wegdek=self.cbo_wegdek.get()\n )\n\n print(jsonpickle.encode(data))\n logging.info(f\"Data: {data}\")\n self.writer.write(f\"{jsonpickle.encode(data)}\\n\")\n self.writer.flush()\n\n msg = self.writer.readline().rstrip(\"\\n\")\n res = jsonpickle.decode(msg)\n show_result(res)\n\n def close_connection(self):\n self.conn.close()\n\n\nlogging.basicConfig(level=logging.INFO)\nroot = Tk()\napp = Window(root)\nroot.mainloop()\n","sub_path":"week 5/oef3/client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"469299668","text":"'''AresBNet in PyTorch.\n\nThis AresBNet block is motivated from XNOR-Net and applied to ResNet below.\nReference:\n[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun\n Deep Residual Learning for Image Recognition. arXiv:1512.03385\n\n\n'''\nimport torch\nimport torch.nn as nn\nimport functools\nimport torch.nn.functional as F\n\n######################################################################################\nclass BinActive(torch.autograd.Function):\n '''\n Binarize the input activations. \n '''\n def forward(self, input):\n self.save_for_backward(input)\n size = input.size()\n input = input.add(1e-30).sign()\n return input\n\n def backward(self, grad_output):\n input, = self.saved_tensors\n grad_input = grad_output.clone()\n grad_input[input.ge(1)] = 0\n grad_input[input.le(-1)] = 0\n return grad_input\n\nclass ShuffleBlock(nn.Module):\n def __init__(self, groups):\n super(ShuffleBlock, self).__init__()\n self.groups = groups\n\n def forward(self, x):\n '''Channel shuffle: [N,C,H,W] -> [N,g,C/g,H,W] -> [N,C/g,g,H,w] -> [N,C,H,W]'''\n N,C,H,W = x.size()\n g = self.groups\n return x.view(N,g,C//g,H,W).permute(0,2,1,3,4).reshape(N,C,H,W)\n\nclass BasicBlock_AresB(nn.Module): \n expansion = 2 \n def __init__(self, in_planes, planes, stride=1, suffle=False):\n super(BasicBlock_AresB, self).__init__()\n self.in_planes = in_planes\n self.planes = planes\n self.stride = stride\n self.suffle = suffle\n self.shuffle1 = ShuffleBlock(groups=2)\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False, groups=2)\n self.relu1 = nn.LeakyReLU(inplace=True)\n self.bn1 = nn.BatchNorm2d(planes)\n self.shuffle2 = ShuffleBlock(groups=2)\n self.conv2 = nn.Conv2d(2*planes, planes, kernel_size=3, stride=1, padding=1, bias=False, groups=2)\n self.maxpool2d= nn.MaxPool2d(3, stride=2, padding=1)\n self.bn2 = nn.BatchNorm2d(2*planes)\n self.relu2 = nn.LeakyReLU(inplace=True)\n self.bn3 = nn.BatchNorm2d(planes)\n \n def forward(self, x):\n if self.suffle:\n x = self.shuffle1(x)\n xa, xb = torch.chunk(x, 2, dim=1)\n x1 = BinActive()(x)\n x1 = self.conv1(x1)\n x1 = self.relu1(x1)\n x2 = self.bn1(x1)\n if self.stride != 1 :\n x3a = self.maxpool2d(x)\n x3b = x3a\n else:\n x3a = xa\n x3b = xb\n x3 = torch.cat((x2+x3a, x3b),1) \n x3 = self.bn2(x3)\n x3 = self.shuffle2(x3)\n x4 = BinActive()(x3)\n x4 = self.conv2(x4)\n x4 = self.relu2(x4)\n x4 = self.bn3(x4)\n x5a, x5b = torch.chunk(x3, 2, dim=1)\n x5 = torch.cat((x4+x5a, x5b),1) \n out = x5\n return out \n\nclass AresBNet(nn.Module):\n def __init__(self, block, num_blocks, num_classes=10):\n super(AresBNet, self).__init__()\n self.in_planes = 64 * 2\n\n self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(64*2)\n self.maxpool2d= nn.MaxPool2d(3, stride=1, padding=1)\n self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1, suffle=False)\n self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2, suffle=True)\n self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2, suffle=True)\n self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2, suffle=True)\n self.bn2 = nn.BatchNorm2d(512)\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) \n self.dropout = nn.Dropout()\n self.linear = nn.Linear(512, num_classes)\n\n def _make_layer(self, block, planes, num_blocks, stride, suffle):\n strides = [stride] + [1]*(num_blocks-1)\n layers = []\n if suffle:\n dosuffle=True\n else: \n dosuffle=False\n for stride in strides:\n layers.append(block(self.in_planes, planes, stride, dosuffle))\n self.in_planes = planes * block.expansion\n dosuffle = True\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = F.leaky_relu(self.conv1(x))\n out = torch.cat(2*[out], 1)\n out = self.bn1(out)\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.layer4(out)\n out = torch.chunk(out, 2, dim=1)[0]\n out = self.avgpool(out)\n out = torch.flatten(out, 1)\n out = self.linear(out) \n return out\n\ndef AresBNet10():\n return AresBNet(BasicBlock_AresB, [1,1,1,1])\n\ndef AresBNet18():\n return AresBNet(BasicBlock_AresB, [2,2,2,2])\n\ndef AresBNet34(): \n return AresBNet(BasicBlock_AresB, [3,4,6,3])\n\n","sub_path":"cifar10/models/aresbnet.py","file_name":"aresbnet.py","file_ext":"py","file_size_in_byte":4833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"577182593","text":"import numpy as np\nimport tensorflow as tf\nimport paint_auth as pa\nfrom sklearn.model_selection import train_test_split, StratifiedKFold\n\ndef weight_variable(shape):\n init = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(init)\n\ndef bias_variable(shape):\n init = tf.constant(0.1, shape=shape)\n return tf.Variable(init)\n\ndef conv2d(x, W, padding='SAME'):\n \"\"\"\n strides = [b,i,j,d]\n b: starting batch\n d: depth of batch\n here we have from 1 to 1 depth so every image is used\n \"\"\"\n \n return tf.nn.conv2d(x, W, strides=[1,2,2,1], padding=padding)\n\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')\n\ndef avg_pool(x, ksize, padding):\n return tf.nn.avg_pool(x, ksize=ksize, strides=[1,1,1,1], padding=padding)\n\ndef evaluate(output, y):\n correct_prediction = tf.equal(tf.argmax(output, 1), tf.argmax(y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n return accuracy\n\ndef loss(output, y):\n cross_entropy = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=output))\n return cross_entropy\n\ndef train(cost, l_rate):\n train_op = tf.train.GradientDescentOptimizer(l_rate).minimize(cost)\n return train_op\n \ndef model(x, num_class):\n #Conv. layer 1\n W_conv1 = weight_variable([3, 3, 1, 64])\n b_conv1 = bias_variable([64])\n \n h_conv1 = tf.nn.relu(conv2d(x, W_conv1) + b_conv1)\n \n #Conv. layer 2\n W_conv2 = weight_variable([3,3,64,128])\n b_conv2 = bias_variable([128])\n \n h_conv2 = tf.nn.relu(conv2d(h_conv1, W_conv2) + b_conv2)\n #print h_conv2.shape\n #Conv. layer 3\n W_conv3 = weight_variable([3,3,128,256])\n b_conv3 = bias_variable([256])\n \n h_conv3 = tf.nn.relu(conv2d(h_conv2, W_conv3) + b_conv3)\n \n #Conv. layer 4\n W_conv4 = weight_variable([3,3,256,256])\n b_conv4 = bias_variable([256])\n \n h_conv4 = tf.nn.relu(conv2d(h_conv3, W_conv4) + b_conv4)\n \n #Conv. layer 5\n W_conv5 = weight_variable([3,3,256,128])\n b_conv5 = bias_variable([128])\n \n h_conv5 = tf.nn.relu(conv2d(h_conv4, W_conv5) + b_conv5)\n \n b, w, l, d = h_conv5.shape\n \n #Avg. pooling\n #3x3 stride 1\n h_pool = avg_pool(h_conv5, [1,int(w),int(l),1], 'VALID')\n \n b, w, l, d = h_pool.shape #getting shape of conv5\n flat_dim = int(w*l*d)\n \n #fully connected\n W_fc1 = weight_variable([flat_dim, 2048])\n b_fc1 = bias_variable([2048])\n \n #reshape h_pool2\n h_pool2_flat = tf.reshape(h_pool, [-1, flat_dim])\n #fc 1\n #apply relu\n h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n \n #fc 2\n W_fc2 = weight_variable([2048, 2048])\n b_fc2 = bias_variable([2048]) \n h_fc2 = tf.nn.relu(tf.matmul(h_fc1, W_fc2) + b_fc2)\n \n #output layer\n W_out = weight_variable([2048, num_class])\n b_out = bias_variable([num_class])\n output = tf.nn.relu(tf.matmul(h_fc2, W_out) + b_out)\n \n return output\n \n ##applying dropout\n #h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n \n #W_fc2 = weight_variable([1024, 10])\n #b_fc2 = bias_variable([10])\n \n #y_hat = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\n \ndef run_model(X, num_classes):\n \"\"\"\n Run given nerual network given input X and output y\n \"\"\"\n \n with tf.Session() as sess:\n x = tf.placeholder(tf.float32, shape=[None, 256, 256, 1])\n output = model(x, num_classes)\n \n sess.run(tf.global_variables_initializer())\n sess.run(output, feed_dict={x: X})\n\ndef next_batch(num, data, labels):\n \"\"\"\n Return a total of num random samples and labels. \n \"\"\"\n idx = np.arange(0, len(data))\n np.random.shuffle(idx)\n idx = idx[:num]\n data_shuffle = [data[i] for i in idx]\n labels_shuffle = [labels[i] for i in idx]\n\n return np.asarray(data_shuffle), np.asarray(labels_shuffle)\n \ndef train(X, y):\n \"\"\"\n Trains model given data X and y labels\n \"\"\"\n # Parameters\n learning_rate = 0.005\n training_epochs = 3\n batch_size = 10\n display_step = 1\n \n n = 256\n m = 256\n num_classes = 1179\n \n with tf.Session() as sess:\n \n #place holders for data\n x = tf.placeholder(tf.float32, shape=[None, n, m, 1])\n y_ = tf.placeholder(tf.float32, shape=[None, num_classes]) \n\n #initialization\n output = model(x, num_classes)\n cost = loss(output, y_)\n train_step = train(cost, learning_rate)\n eval_op = evaluate(output, y_)\n \n sess.run(tf.global_variables_initializer())\n \n for i in range(training_epochs):\n batch = next_batch(batch_size, X, y)\n train_step.run(feed_dict={x: batch[0], y_: batch[1], num_classes: num_classes})\n \n if i % display_step == 0:\n train_accuracy = sess.run(eval_op, feed_dict={\n x:batch[0], y_: batch[1], num_classes: num_classes})\n print(\"step %d, training accuracy %g\"%(i, train_accuracy))\n \n \n \n \nif __name__ == \"__main__\":\n pass","sub_path":"cnn_paint.py","file_name":"cnn_paint.py","file_ext":"py","file_size_in_byte":5123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"220741899","text":"class Solution:\n def findDisappearedNumbers(self, nums: List[int]) -> List[int]:\n ans=[]\n for n in nums:\n n=abs(n)\n if nums[n-1] > 0 :\n nums[n-1]= -nums[n-1]\n for n in range(len(nums)):\n if nums[n]>0:\n ans.append(n+1)\n return ans\n","sub_path":"Find All Numbers Disappeared in an Array.py","file_name":"Find All Numbers Disappeared in an Array.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"15822080","text":"class Product:\n\n def __init__(self):\n self.name = 'Iphone'\n self.description = 'best'\n self.price = 100000\n\n def display(self):\n print(self.name)\n print(self.price)\n print(self.description)\n\n\np1 = Product()\np1.display()\n","sub_path":"product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"305115987","text":"from __future__ import absolute_import, division, print_function\n\nimport stripe\nfrom tests.helper import StripeResourceTest\n\n\nclass ApplicationFeeTest(StripeResourceTest):\n\n def test_list_application_fees(self):\n stripe.ApplicationFee.list()\n self.requestor_mock.request.assert_called_with(\n 'get',\n '/v1/application_fees',\n {}\n )\n\n\nclass ApplicationFeeRefundsTests(StripeResourceTest):\n def test_create_refund(self):\n stripe.ApplicationFee.create_refund(\n 'fee_123'\n )\n self.requestor_mock.request.assert_called_with(\n 'post',\n '/v1/application_fees/fee_123/refunds',\n {},\n None\n )\n\n def test_retrieve_refund(self):\n stripe.ApplicationFee.retrieve_refund(\n 'fee_123',\n 'fr_123'\n )\n self.requestor_mock.request.assert_called_with(\n 'get',\n '/v1/application_fees/fee_123/refunds/fr_123',\n {},\n None\n )\n\n def test_modify_refund(self):\n stripe.ApplicationFee.modify_refund(\n 'fee_123',\n 'fr_123',\n metadata={'foo': 'bar'}\n )\n self.requestor_mock.request.assert_called_with(\n 'post',\n '/v1/application_fees/fee_123/refunds/fr_123',\n {'metadata': {'foo': 'bar'}},\n None\n )\n\n def test_list_refunds(self):\n stripe.ApplicationFee.list_refunds(\n 'fee_123'\n )\n self.requestor_mock.request.assert_called_with(\n 'get',\n '/v1/application_fees/fee_123/refunds',\n {},\n None\n )\n","sub_path":"tests/api_resources/test_application_fee.py","file_name":"test_application_fee.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"121306869","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'此模块功能:UDP网络示例服务器程序'\n\n__author__ = 'HouBin'\n\nimport socket\nimport time\n\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n# 绑定端口:\ns.bind(('localhost', 9999))\nprint('服务器绑定UDP端口:9999...')\nwhile True:\n #接收数据\n data, addr = s.recvfrom(1024)\n print(\"-----------------------------------------------------------\")\n print('收到来自%s:%s的消息:' % addr)\n print(data.decode('utf-8'))\n if data.decode('utf-8')==\"你好,服务器!\":\n #发送数据\n s.sendto((\"你好,客户端%s:%s!\" % addr).encode('utf-8'), addr)\n elif data.decode('utf-8')==\"服务器,你吃饭了吗?\":\n #向客户端2发送数据\n s.sendto(\"我吃过了,客户端2,你吃了吗?\".encode('utf-8') , addr)\n print(\"向客户端2发送数据:我吃过了,客户端2,你吃了吗?\")\n elif data.decode('utf-8')==\"我吃过了。\":\n time.sleep(5)\n #向客户端1发送数据\n s.sendto(\"散会!\".encode('utf-8') , ('127.0.0.1', 6666))\n print(\"向客户端1发送数据:散会!\")\n #向客户端2发送数据\n s.sendto(\"散会!\".encode('utf-8') , ('127.0.0.1', 8888))\n print(\"向客户端2发送数据:散会!\")\n","sub_path":"06-Socket/02-UDP/Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"81522537","text":"import dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.graph_objects as go\nimport pandas as pd\nimport dash_table\nimport dash\nfrom .app import app\nfrom dash.dependencies import Input, Output\nfrom .dados import ipca\nfrom datetime import date\nfrom .uteis import funcoes\n\n\n# Estilo da tabela, definido aqui porque não há como aplicar classe no dashTable.\n\nstyle_header={\n 'backgroundColor': '#0D6ABF',\n 'color': 'white',\n 'fontWeight': 'bold',\n 'fontSize': '14px'\n}\nstyle_cell={\n 'backgroundColor': 'white',\n 'color': 'black',\n 'border': '1px solid #1F94FF',\n 'textAlign': 'center',\n 'padding': '7px'\n}\n\nstyle_table={\n 'width': '350px',\n 'height':'592px',\n 'overflowY': 'auto'\n}\n\nstyle_data_conditional=[\n {\n 'if': {'row_index': 'odd'},\n 'backgroundColor': '#C5E5EA'\n }\n]\n\n\n# Função que retorna uma tabela a partir das informações do IPCA\n\ndef controiTabelaIpca(ipca,inicioData,fimData,mes_ano):\n \n ipcas = []\n for i in ipca:\n ipcas.append(i) \n \n if mes_ano == 'Mensal':\n tabela = {\n 'Data': [], \n 'IPCA': [], \n 'Variação Mensal': [], \n }\n for x in range(len(ipcas) -1,-1,-1):\n data = date(int(ipcas[x]['data'].split('-')[2]),int(ipcas[x]['data'].split('-')[1]),int(ipcas[x]['data'].split('-')[0]))\n inicio = date(int(inicioData.split('-')[0]),int(inicioData.split('-')[1]),int(inicioData.split('-')[2]))\n fim = date(int(fimData.split('-')[0]),int(fimData.split('-')[1]),int(fimData.split('-')[2]))\n if inicio <= data <= fim:\n continue\n else:\n ipcas.pop(x)\n for i in ipcas:\n tabela['Data'].append(i['data'])\n tabela['IPCA'].append(i['ipca'])\n tabela['Variação Mensal'].append(i['variacao ipca'])\n \n return tabela\n else:\n tabela = {\n 'Data': [], \n 'IPCA': [], \n 'Variação Anual': [], \n }\n datas = []\n for i in ipca:\n datas.append(i['data'])\n \n datas = funcoes.remove_repetidos(map(funcoes.separa_anos,datas))\n \n n = 0\n var = 0\n for i in ipcas:\n if '01-12' in i['data']:\n if i['data'] == '01-12-2019':\n tabela['IPCA'].append(i['ipca'])\n tabela['Variação Anual'].append('4,31%')\n n = i['ipca']\n else:\n var = ((i['ipca'] / n) - 1) * 100\n n = i['ipca']\n tabela['IPCA'].append(n)\n tabela['Variação Anual'].append(str(round(var,3)).replace('.',',') + '%')\n \n tabela['Data'] = datas\n \n return tabela\n\n\n\n\n\n# Função que retorna uma figure a partir das informações do IPCA para gerar um gráfico\n\ndef gera_grafico_ipca(ipca,inicioData,fimData,mes_ano):\n \n template = [\"plotly\", \"plotly_white\", \"plotly_dark\", \"ggplot2\", \"seaborn\", \"simple_white\", \"none\"]\n\n ipcas = []\n for i in ipca:\n ipcas.append(i) \n \n if mes_ano == 'Mensal':\n \n for x in range(len(ipcas) -1,-1,-1):\n data = date(int(ipcas[x]['data'].split('-')[2]),int(ipcas[x]['data'].split('-')[1]),int(ipcas[x]['data'].split('-')[0]))\n inicio = date(int(inicioData.split('-')[0]),int(inicioData.split('-')[1]),int(inicioData.split('-')[2]))\n fim = date(int(fimData.split('-')[0]),int(fimData.split('-')[1]),int(fimData.split('-')[2]))\n if inicio <= data <= fim:\n continue\n else:\n ipcas.pop(x)\n \n valores = {\n \"cor\": \"#118dff\",\n \"datas\": [],\n \"valores\": []\n }\n \n for i in ipcas:\n valores['datas'].append(i['data'])\n valores['valores'].append(i['ipca'])\n \n valores['datas'] = list(map(funcoes.transforma_data,valores['datas']))\n else:\n datas = []\n for i in ipca:\n datas.append(i['data'])\n \n datas = funcoes.remove_repetidos(map(funcoes.separa_anos,datas))\n \n valores = {\n \"cor\": \"#118dff\",\n \"datas\": [],\n \"valores\": []\n }\n for i in ipcas:\n if '01-12' in i['data']:\n valores['valores'].append(i['ipca'])\n \n valores['datas'] = datas\n \n fig = go.Figure()\n fig.add_trace(go.Bar(x=valores['datas'],\n y=valores['valores'],\n marker_color=valores[\"cor\"]\n ))\n fig.update_layout(\n margin=dict(l=0, r=0, t=50, b=0),\n template=template[1],\n xaxis=dict(\n title='Data',\n titlefont_size=16,\n tickfont_size=14,\n ),\n yaxis=dict(\n titlefont_size=16,\n tickfont_size=14,\n ),\n barmode='group',\n bargap=0.05, # gap between bars of adjacent location coordinates.\n bargroupgap=0.1 # gap between bars of the same location coordinate.\n )\n \n return fig\n \n\n\n\n# Layout do modal IPCA\n\nipca = [\n dbc.ModalHeader([\n html.Span(id=\"titulo-modal-ipca\", className=\"pt-2\"),\n html.Span([\n dbc.Button(\"Mensal\", id=\"mes-ipca\", className=\"btn-menu\", style={'display': 'inline-block', 'marginRight':'20px'}),\n dbc.Button(\"Anual\", id=\"ano-ipca\", className=\"btn-menu\", style={'display': 'inline-block', 'marginRight':'20px'}),\n ])\n ]),\n dbc.ModalBody([\n html.Div([\n html.Div([\n html.Div(id=\"container-tabela-ipca\"),\n html.Div([\n dcc.DatePickerRange(\n calendar_orientation='vertical',\n display_format='DD/MM/YYYY',\n min_date_allowed=date(2020, 1, 1),\n max_date_allowed=date(2040, 12, 31),\n start_date=date(2020, 1, 1),\n end_date=date(2023, 12, 31),\n className=\"datepicker-ipca mb-1\", \n id=\"date-picker-ipca\"), \n dcc.RangeSlider(id='range-slider-ipca',min=0,max=252,step=1,value=[0, 59],allowCross=False, className=\"slider-ipca\")\n ],className=\"container-slider-datepicker\"),\n ], className=\"container-tabela-ipca\"),\n html.Div([\n html.Div(dcc.Graph(id='grafico-ipca'), style={'width':'700px','height':'500px','backgroundColor':'blue'}),\n html.Div([\n html.Div([\n html.Div(\"3,63%\", className=\"estatistica-variacao\",id=\"variacao-1\"),\n html.Div(\"Projeção de Variação Anual para 2021\", className=\"estatistica-texto\",id=\"texto-variacao-1\")\n ],className=\"item-estatisca\"),\n html.Div([\n html.Div(\"3,07%\", className=\"estatistica-variacao\",id=\"variacao-2\"),\n html.Div(\"Projeção de Variação Anual para 2022\", className=\"estatistica-texto\",id=\"texto-variacao-2\")\n ],className=\"item-estatisca\"),\n html.Div([\n html.Div(\"3,23%\", className=\"estatistica-variacao\",id=\"variacao-3\"),\n html.Div(\"Projeção de Variação Anual para 2023 e Posteriores\", className=\"estatistica-texto\",id=\"texto-variacao-3\")\n ],className=\"item-estatisca\")\n ],className=\"container-estatisticas\", id=\"container-estatisticas\"),\n ], className=\"container-grafico-estatisticas-ipca\"),\n \n ],className=\"container-ipca\"),\n ]),\n dbc.ModalFooter([\n dbc.Button(\"Fechar\", id=\"close2\", color=\"danger\", className=\"ml-auto\", style={'display': 'inline-block', 'marginRight':'20px'}),\n ]\n )\n]\n\n\n\n","sub_path":"DashApp/ipca.py","file_name":"ipca.py","file_ext":"py","file_size_in_byte":8069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"504380040","text":"from PIL import Image, ImageOps\nimport numpy as np\n\nif __name__ == \"__main__\":\n img = Image.open(\"../data/city-3021474_1920.jpg\")\n\n img_mirror = ImageOps.mirror(img)\n\n with open(\"../data/task3/city_mirror.jpg\", \"w\") as f:\n img_mirror.save(f, format=\"JPEG\")\n","sub_path":"src03/src/t03.py","file_name":"t03.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"540869412","text":"# Tower of Hanoi\r\n\r\n# defining function\r\ndef toh(n, source, destination, aux):\r\n if n == 1:\r\n print('Move disk 1 from ', source, 'to ', destination)\r\n return\r\n else:\r\n toh(n-1, source, aux, destination)\r\n print(\"Move disk\", n, \"from \", source, \"to \", destination)\r\n toh(n-1, aux, destination, source)\r\n\r\n\r\n# Taking input from user\r\nn = int(input('Enter no. of disks: '))\r\nprint('Here is the following Steps: ')\r\ntoh(n, 'A', 'B', 'C') # here A-source, B-Destination, C-Auxiliary\r\n\r\n","sub_path":"TowerOfHanoi.py","file_name":"TowerOfHanoi.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"226249110","text":"''' Q1 : Write a function that computes the volume of a sphere given its radius.\n\n The volume of a sphere is given as 43π𝑟3 \n'''\nimport math\nimport string\nfrom string import ascii_lowercase\n\ndef SphereVol(radius):\n #radius = input(\"Enter the radius:\")\n volume = (4*math.pi*(int(radius)**3))/3\n return volume\n\n\nprint(SphereVol(2))\n\n\n''' Q2 : Write a function that checks whether a number is in a given range (inclusive of high and low)\n def ran_check(num,low,high):\n pass\n # Check\n ran_check(5,2,7)\n 5 is in the range between 2 and 7\n If you only wanted to return a boolean:\n def ran_bool(num,low,high):\n pass\n ran_bool(3,1,10)\n True '''\n\ndef ran_check(num,low,high):\n if num in range(low,high,1):\n print(\"{} is in the range between {} and {}\".format(num,low,high))\n\nran_check(5,2,7)\n\n\n''' Q3 : Write a Python function that accepts a string and calculates the number of upper case letters and lower case letters.\n\n Sample String : 'Hello Mr. Rogers, how are you this fine Tuesday?'\n Expected Output : \n No. of Upper case characters : 4\n No. of Lower case Characters : 33\n\n HINT: Two string methods that might prove useful: .isupper() and .islower()\n\n If you feel ambitious, explore the Collections module to solve this problem!\n\n def up_low(s):\n\n pass\n\n s = 'Hello Mr. Rogers, how are you this fine Tuesday?'\n\n up_low(s)\n\n Original String : Hello Mr. Rogers, how are you this fine Tuesday?\n No. of Upper case characters : 4\n No. of Lower case Characters : 33\n\n'''\n\nstring = 'Hello Mr. Rogers, how are you this fine Tuesday?'\n\ndef up_low(s):\n count_upper = 0\n count_lower = 0\n for element in s:\n if element.islower() and element.isalpha():\n count_lower += 1\n elif element.isalpha():\n count_upper += 1\n\n print(\"Original String : {}\".format(s))\n print(\"No. of Upper case characters : {}\".format(count_upper))\n print(\"No. of Lower case Characters : {}\".format(count_lower))\n\n\n \n \nup_low(string)\n\n'''\nQ4: Write a Python function that takes a list and returns a new list with unique elements of the first list.\n\nSample List : [1,1,1,1,2,2,3,3,3,3,4,5]\nUnique List : [1, 2, 3, 4, 5]\n\n\n'''\n\ndef unique_list(lst):\n un1lst = set(lst)\n print(un1lst)\n\n\nlst = [1,1,1,1,2,2,3,3,3,3,4,5]\nunique_list(lst)\n\n'''\nWrite a Python function to multiply all the numbers in a list.\n\nSample List : [1, 2, 3, -4]\nExpected Output : -24\n'''\n\ndef multiply_list(lst):\n product=0\n for num in lst:\n if product == 0:\n product = num\n else:\n product *= num\n print(product)\n\nlst = [1, 2, 3, -4]\nmultiply_list(lst)\n \n'''\nWrite a Python function that checks whether a word or phrase is palindrome or not.\n\nNote: A palindrome is word, phrase, or sequence that reads the same backward as forward, \ne.g., madam,kayak,racecar, or a phrase \"nurses run\". Hint: You may want to check out the .replace() method in a string \nto help out with dealing with spaces. Also google search how to reverse a string in Python, \nthere are some clever ways to do it with slicing notation.\n\n'''\n\ndef palindrome(str):\n new_str = str.replace(\" \",\"\")\n length = len(new_str)\n s1 = slice(0,math.floor(length/2))\n #s2 = slice(math.ceil(length/2),length)\n #print(new_str[s1])\n str1 = new_str[s1]\n str2 = new_str[::-1][s1]\n if str1 == str2:\n print(\"palindrome\")\n else:\n print(\"not palindrome\")\n\n\nstr = \"nurses run\"\npalindrome(str)\n\n'''\nWrite a Python function to check whether a string is pangram or not. (Assume the string passed in does not have any punctuation)\n\nNote : Pangrams are words or sentences containing every letter of the alphabet at least once.\nFor example : \"The quick brown fox jumps over the lazy dog\"\n\nHint: You may want to use .replace() method to get rid of spaces.\n\nHint: Look at the string module\n\nHint: In case you want to use set comparisons\n\n'''\n\ndef is_anagram(str1):\n test_str = str1.replace(\" \",\"\")\n list_str = list(set(test_str.lower()))\n ascii_lowercase = \"abcdefghijklmnopqrstuvwxyz\"\n sorted_string=\"\"\n #print(list_str)\n #joined_string = joined_string.join(list_str)\n #print(test_str)\n sorted_string = sorted_string.join(sorted(list_str))\n print(sorted_string)\n if ascii_lowercase == sorted_string.lower():\n print(\"Pangram\")\n else:\n print(\"not Pangram\")\n \nstr = \"Two driven jocks help fax my big quiz\"\nis_anagram(str)","sub_path":"MethodsAndFuncionsHomework.py","file_name":"MethodsAndFuncionsHomework.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"575518945","text":"# -*- coding: utf-8 -*-\n'''\nNose tests\nrun as \"nosetests tests\"\n or \"nosetests tests:test_main\"\n'''\nimport httplib2\ntry:\n from urllib.parse import urlencode\nexcept ImportError:\n from urllib import urlencode\nimport json\nimport sys\nimport os\nfrom nose.tools import ok_, eq_\nimport variant_list\n\ntry:\n import msgpack\nexcept ImportError:\n sys.stderr.write(\"Warning: msgpack is not available.\")\n\nhost = os.getenv(\"MV_HOST\")\nif not host:\n #host = 'http://localhost:8000'\n #host = 'http://dev.myvariant.info:8000'\n host = 'http://myvariant.info'\n\napi = host + '/v1'\nsys.stderr.write('URL base: {}\\n'.format(api))\n\nh = httplib2.Http()\n#h = httplib2.Http(disable_ssl_certificate_validation=True)\n_d = json.loads # shorthand for json decode\n_e = json.dumps # shorthand for json encode\n\n\n#############################################################\n# Hepler functions #\n#############################################################\ndef encode_dict(d):\n '''urllib.urlencode (python 2.x) cannot take unicode string.\n encode as utf-8 first to get it around.\n '''\n if sys.version_info.major >= 3:\n # no need to do anything\n return d\n else:\n def smart_encode(s):\n return s.encode('utf-8') if isinstance(s, unicode) else s # noqa\n\n return dict([(key, smart_encode(val)) for key, val in d.items()])\n\n\ndef truncate(s, limit):\n '''truncate a string.'''\n if len(s) <= limit:\n return s\n else:\n return s[:limit] + '...'\n\n\ndef json_ok(s, checkerror=True):\n d = _d(s.decode('utf-8'))\n if checkerror:\n ok_(not (isinstance(d, dict) and 'error' in d), truncate(str(d), 100))\n return d\n\n\ndef msgpack_ok(b, checkerror=True):\n d = msgpack.unpackb(b)\n if checkerror:\n ok_(not (isinstance(d, dict) and 'error' in d), truncate(str(d), 100))\n return d\n\n\ndef get_ok(url):\n res, con = h.request(url)\n eq_(res.status, 200)\n return con\n\n\ndef get_404(url):\n res, con = h.request(url)\n eq_(res.status, 404)\n\n\ndef get_405(url):\n res, con = h.request(url)\n eq_(res.status, 405)\n\n\ndef head_ok(url):\n res, con = h.request(url, 'HEAD')\n eq_(res.status, 200)\n\n\ndef post_ok(url, params):\n headers = {'Content-type': 'application/x-www-form-urlencoded'}\n res, con = h.request(url, 'POST', urlencode(encode_dict(params)), headers=headers)\n eq_(res.status, 200)\n return con\n\n\ndef setup_func():\n print(('Testing \"%s\"...' % host))\n\n\ndef teardown_func():\n pass\n\n\n#############################################################\n# Test functions #\n#############################################################\n#@with_setup(setup_func, teardown_func)\ndef test_main():\n #/\n get_ok(host)\n\n\ndef test_variant_object():\n #test all fields are loaded in variant objects\n res = json_ok(get_ok(api + '/variant/chr1:g.218631822G>A'))\n attr_li = ['_id']\n for attr in attr_li:\n assert res.get(attr, None) is not None, 'Missing field \"{}\" in variant \"chr1:g.218631822G>A\"'.format(attr)\n\n # test for specific databases\n\n\ndef has_hits(q):\n d = json_ok(get_ok(api + '/query?q='+q))\n ok_(d.get('total', 0) > 0 and len(d.get('hits', [])) > 0)\n\n\ndef test_query():\n #public query api at /query via get\n has_hits('rs58991260')\n has_hits('chr1:69000-70000')\n has_hits('dbsnp.vartype:snp')\n has_hits('_exists_:dbnsfp')\n has_hits('dbnsfp.genename:BTK')\n has_hits('_exists_:wellderly%20AND%20cadd.polyphen.cat:possibly_damaging&fields=wellderly,cadd.polyphen')\n\n con = get_ok(api + '/query?q=rs58991260&callback=mycallback')\n ok_(con.startswith('mycallback('.encode('utf-8')))\n\n # testing non-ascii character\n res = json_ok(get_ok(api + '/query?q=54097\\xef\\xbf\\xbd\\xef\\xbf\\xbdmouse'))\n eq_(res['hits'], [])\n\n res = json_ok(get_ok(api + '/query'), checkerror=False)\n assert 'error' in res\n\n\ndef test_query_post():\n #/query via post\n json_ok(post_ok(api + '/query', {'q': 'rs58991260'}))\n\n res = json_ok(post_ok(api + '/query', {'q': 'rs58991260',\n 'scopes': 'dbsnp.rsid'}))\n eq_(len(res), 1)\n eq_(res[0]['_id'], 'chr1:g.218631822G>A')\n\n res = json_ok(post_ok(api + '/query', {'q': 'rs58991260,rs2500',\n 'scopes': 'dbsnp.rsid'}))\n eq_(len(res), 2)\n eq_(res[0]['_id'], 'chr1:g.218631822G>A')\n eq_(res[1]['_id'], 'chr11:g.66397320A>G')\n\n res = json_ok(post_ok(api + '/query', {'q': 'rs58991260',\n 'scopes': 'dbsnp.rsid',\n 'fields': 'dbsnp.chrom,dbsnp.alleles'}))\n assert len(res) == 1, (res, len(res))\n res = json_ok(post_ok(api + '/query', {}), checkerror=False)\n assert 'error' in res, res\n\n # TODO fix this test query\n #res = json_ok(post_ok(api + '/query', {'q': '[rs58991260, \"chr11:66397000-66398000\"]',\n # 'scopes': 'dbsnp.rsid'}))\n #eq_(len(res), 2)\n #eq_(res[0]['_id'], 'chr1:g.218631822G>A')\n #eq_(res[1]['_id'], 'chr11:g.66397320A>G')\n\n\ndef test_query_interval():\n res = json_ok(get_ok(api + '/query?q=chr1:10000-100000'))\n ok_(len(res['hits']) > 1)\n ok_('_id' in res['hits'][0])\n\n\ndef test_query_size():\n # TODO\n pass\n\n\ndef test_variant():\n # TODO\n res = json_ok(get_ok(api + '/variant/chr16:g.28883241A>G'))\n eq_(res['_id'], \"chr16:g.28883241A>G\")\n\n res = json_ok(get_ok(api + '/variant/chr1:g.35367G>A'))\n eq_(res['_id'], \"chr1:g.35367G>A\")\n\n res = json_ok(get_ok(api + '/variant/chr7:g.55241707G>T'))\n eq_(res['_id'], \"chr7:g.55241707G>T\")\n\n # testing non-ascii character\n get_404(api + '/variant/' + 'chr7:g.55241707G>T\\xef\\xbf\\xbd\\xef\\xbf\\xbdmouse')\n\n # testing filtering parameters\n res = json_ok(get_ok(api + '/variant/chr16:g.28883241A>G?fields=dbsnp,dbnsfp,cadd'))\n eq_(set(res), set(['_id', '_version', 'dbnsfp', 'cadd', 'dbsnp']))\n res = json_ok(get_ok(api + '/variant/chr16:g.28883241A>G?fields=wellderly'))\n eq_(set(res), set(['_id', '_version', 'wellderly']))\n res = json_ok(get_ok(api + '/variant/chr9:g.107620835G>A?fields=dbsnp'))\n eq_(set(res), set(['_id', '_version', 'dbsnp']))\n res = json_ok(get_ok(api + '/variant/chr1:g.31349647C>T?fields=dbnsfp.clinvar,dbsnp.gmaf,clinvar.hgvs.coding'))\n eq_(set(res), set(['_id', '_version', 'dbsnp', 'dbnsfp', 'clinvar']))\n\n get_404(api + '/variant')\n get_404(api + '/variant/')\n\n\ndef test_variant_post():\n res = json_ok(post_ok(api + '/variant', {'ids': 'chr16:g.28883241A>G'}))\n eq_(len(res), 1)\n eq_(res[0]['_id'], \"chr16:g.28883241A>G\")\n\n res = json_ok(post_ok(api + '/variant', {'ids': 'chr16:g.28883241A>G, chr11:g.66397320A>G'}))\n eq_(len(res), 2)\n eq_(res[0]['_id'], 'chr16:g.28883241A>G')\n eq_(res[1]['_id'], 'chr11:g.66397320A>G')\n\n res = json_ok(post_ok(api + '/variant', {'ids': 'chr16:g.28883241A>G, chr11:g.66397320A>G', 'fields': 'dbsnp'}))\n eq_(len(res), 2)\n for _g in res:\n eq_(set(_g), set(['_id', '_score', 'query', 'dbsnp']))\n\n # TODO redo this test, doesn't test much really....\n res = json_ok(post_ok(api + '/variant', {'ids': 'chr16:g.28883241A>G,chr11:g.66397320A>G', 'filter': 'dbsnp.chrom'}))\n eq_(len(res), 2)\n for _g in res:\n eq_(set(_g), set(['_id', '_score', 'query', 'dbsnp']))\n\n # Test a large variant post\n res = json_ok(post_ok(api + '/variant', {'ids': variant_list.VARIANT_POST_LIST}))\n eq_(len(res), 999)\n\n\ndef test_metadata():\n #get_ok(host + '/metadata')\n get_ok(api + '/metadata')\n\n\ndef test_query_facets():\n pass\n\n\ndef test_unicode():\n s = '基因'\n\n get_404(api + '/variant/' + s)\n\n res = json_ok(post_ok(api + '/variant', {'ids': s}))\n eq_(res[0]['notfound'], True)\n eq_(len(res), 1)\n res = json_ok(post_ok(api + '/variant', {'ids': 'rs2500, ' + s}))\n eq_(res[1]['notfound'], True)\n eq_(len(res), 2)\n\n res = json_ok(get_ok(api + '/query?q=' + s))\n eq_(res['hits'], [])\n\n res = json_ok(post_ok(api + '/query', {\"q\": s, \"scopes\": 'dbsnp'}))\n eq_(res[0]['notfound'], True)\n eq_(len(res), 1)\n\n res = json_ok(post_ok(api + '/query', {\"q\": 'rs2500+' + s}))\n eq_(res[1]['notfound'], True)\n eq_(len(res), 2)\n\n\ndef test_get_fields():\n res = json_ok(get_ok(api + '/metadata/fields'))\n # Check to see if there are enough keys\n ok_(len(res) > 480)\n\n # Check some specific keys\n assert 'cadd' in res\n assert 'dbnsfp' in res\n assert 'dbsnp' in res\n assert 'wellderly' in res\n assert 'clinvar' in res\n\n\ndef test_fetch_all():\n res = json_ok(get_ok(api + '/query?q=_exists_:wellderly%20AND%20cadd.polyphen.cat:possibly_damaging&fields=wellderly,cadd.polyphen&fetch_all=TRUE'))\n assert '_scroll_id' in res\n\n # get one set of results\n res2 = json_ok(get_ok(api + '/query?scroll_id=' + res['_scroll_id']))\n assert 'hits' in res2\n ok_(len(res2['hits']) == 1000)\n\n\ndef test_msgpack():\n res = json_ok(get_ok(api + '/variant/chr11:g.66397320A>G'))\n res2 = msgpack_ok(get_ok(api + '/variant/chr11:g.66397320A>G?msgpack=true'))\n ok_(res, res2)\n\n res = json_ok(get_ok(api + '/query?q=rs2500'))\n res2 = msgpack_ok(get_ok(api + '/query?q=rs2500&msgpack=true'))\n ok_(res, res2)\n\n res = json_ok(get_ok(api + '/metadata'))\n res2 = msgpack_ok(get_ok(api + '/metadata?msgpack=true'))\n ok_(res, res2)\n\n\ndef test_licenses():\n # cadd license\n res = json_ok(get_ok(api + '/query?q=_exists_:cadd&size=1&fields=cadd'))\n assert '_license' in res['hits'][0]['cadd']\n assert res['hits'][0]['cadd']['_license']\n\n\ndef test_jsonld():\n res = json_ok(get_ok(api + '/variant/chr11:g.66397320A>G?jsonld=true'))\n assert '@context' in res\n\n # Check some subfields\n assert 'snpeff' in res and '@context' in res['snpeff']\n\n assert 'ann' in res['snpeff'] and '@context' in res['snpeff']['ann'][0]\n\n # Check a post with jsonld\n res = json_ok(post_ok(api + '/variant', {'ids': 'chr16:g.28883241A>G, chr11:g.66397320A>G', 'jsonld': 'true'}))\n for r in res:\n assert '@context' in r\n\n # Check a query get with jsonld\n res = json_ok(get_ok(api + '/query?q=_exists_:clinvar&fields=clinvar&size=1&jsonld=true'))\n\n assert '@context' in res['hits'][0]\n\n # subfields\n assert 'clinvar' in res['hits'][0] and '@context' in res['hits'][0]['clinvar']\n assert 'gene' in res['hits'][0]['clinvar'] and '@context' in res['hits'][0]['clinvar']['gene']\n\n # Check query post with jsonld\n res = json_ok(post_ok(api + '/query', {'q': 'rs58991260,rs2500',\n 'scopes': 'dbsnp.rsid',\n 'jsonld': 'true'}))\n\n assert len(res) == 2\n assert '@context' in res[0] and '@context' in res[1]\n assert 'snpeff' in res[1] and '@context' in res[1]['snpeff']\n assert 'ann' in res[1]['snpeff'] and '@context' in res[1]['snpeff']['ann'][0]\n\n\ndef test_genome_assembly():\n res = json_ok(get_ok(api + '/query?q=clinvar.ref:C%20AND%20chr11:56319006%20AND%20clinvar.alt:A&assembly=hg38'))\n eq_(res[\"hits\"][0][\"_id\"], \"chr11:g.56086482C>A\")\n\ndef test_HGVS_redirect():\n res = json_ok(get_ok(api + '/variant/chr11:66397320A>G'))\n res2 = json_ok(get_ok(api + '/variant/chr11:g66397320A>G'))\n res3 = json_ok(get_ok(api + '/variant/chr11:.66397320A>G'))\n res4 = json_ok(get_ok(api + '/variant/chr11:g.66397320A>G'))\n\n eq_(res, res2)\n eq_(res2, res3)\n eq_(res3, res4)\n eq_(res[\"_id\"], 'chr11:g.66397320A>G')\n\ndef test_beacon_get():\n res = json_ok(get_ok(host + '/beacon/wellderly?chrom=12&pos=328665&allele=G'))\n res2 = json_ok(get_ok(host + '/beacon/dbsnp?chrom=12&pos=328665&allele=G'))\n res3 = json_ok(get_ok(host + '/beacon?chrom=12&pos=328665&allele=G')) \n res4 = json_ok(get_ok(host + '/beacon/wellderly?chrom=12&pos=328665&allele=T')) \n \n ok_(res['exists'])\n ok_(res2['exists'])\n ok_(res3['exists'])\n ok_(not res4['exists'])\n\ndef test_beacon_post():\n q = {\"genome.chrom\" : 12, \"genome.position\": 328665, \n \"genome.allele\" : \"G\", \"genome.assembly\" : \"GRCh37\" }\n \n res = json_ok(post_ok(host + '/beacon/wellderly', q))\n res2 = json_ok(post_ok(host + '/beacon/dbsnp', q)) \n res3 = json_ok(post_ok(host + '/beacon', q))\n\n q['genome.allele'] = \"T\" \n \n res4 = json_ok(post_ok(host + '/beacon/wellderly', q))\n \n ok_(res['exists'])\n ok_(res2['exists'])\n ok_(res3['exists']) \n ok_(not res4['exists']) ","sub_path":"src/tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":12580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"317058892","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\" colr.py\n A terminal color library for python, inspired by 'clor' (javascript lib).\n\n -Christopher Welborn 08-12-2015\n\n The MIT License (MIT)\n\n Copyright (c) 2015-2017 Christopher Welborn\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\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\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n\"\"\"\nfrom contextlib import suppress # type: ignore\nfrom functools import partial\nimport math\nimport os\nimport platform\nimport struct\nimport sys\n\nfrom types import GeneratorType\nfrom typing import ( # noqa\n Any,\n Callable,\n Dict,\n List,\n Optional,\n Sequence,\n Set, # Set is used as a 'type: Set' comment in `get_known_codes()`.\n Tuple,\n Union,\n cast,\n)\nfrom typing.io import IO\n\nfrom .base import (\n ChainedBase,\n closing_code,\n get_codes,\n strip_codes,\n)\n\nfrom .trans import (\n ColorCode,\n hex2rgb,\n hex2term,\n hex2termhex,\n)\nfrom .name_data import names as name_data\n\n# Types for the type checker.\nCodeFormatArg = Union[str, int]\nCodeFormatFunc = Callable[[CodeFormatArg], str]\nCodeFormatRgbFunc = Callable[[int, int, int], str]\n# Acceptable fore/back args.\nColorArg = Union[str, int, Tuple[int, int, int]]\n# Acceptable format_* function args.\nFormatArg = Union[int, Tuple[int, int, int]]\n\n__all__ = [\n '_disabled',\n 'auto_disable',\n 'closing_code',\n 'codeformat',\n 'codes',\n 'codes_reverse',\n 'color',\n 'Colr',\n 'disable',\n 'enable',\n 'extbackformat',\n 'extforeformat',\n 'format_back',\n 'format_fore',\n 'get_code_num',\n 'get_codes',\n 'get_known_codes',\n 'get_known_name',\n 'get_terminal_size',\n 'InvalidArg',\n 'InvalidColr',\n 'InvalidEscapeCode',\n 'InvalidRgbEscapeCode',\n 'InvalidStyle',\n 'name_data',\n 'parse_colr_arg',\n 'rgbbackformat',\n 'rgbforeformat',\n 'strip_codes',\n]\n# Set with the enable/disable functions, or on Windows without colorama.\n_disabled = False\n\n# Windows support relies on colorama (for now).\nif platform.system() == 'Windows':\n try:\n from colorama import init as colorama_init\n except ImportError:\n # Windows colors won't work without colorama (for now).\n _disabled = True\n else:\n colorama_init()\n\n\n# Names and corresponding base code number\n_namemap = (\n ('black', 0),\n ('red', 1),\n ('green', 2),\n ('yellow', 3),\n ('blue', 4),\n ('magenta', 5),\n ('cyan', 6),\n ('white', 7)\n) # type: Tuple[Tuple[str, int], ...]\n\n# Map of base code -> style name/alias.\n_stylemap = (\n ('0', ('0', 'reset_all',)),\n ('1', ('1', 'b', 'bright', 'bold')),\n ('2', ('2', 'd', 'dim')),\n ('3', ('3', 'i', 'italic')),\n ('4', ('4', 'u', 'underline', 'underlined')),\n ('5', ('5', 'f', 'flash')),\n ('7', ('7', 'h', 'highlight', 'hilight', 'hilite', 'reverse')),\n ('22', ('22', 'n', 'normal', 'none'))\n) # type: Tuple[Tuple[str, Tuple[str, ...]], ...]\n# A tuple of valid style numbers.\n_stylenums = tuple(t[0] for t in _stylemap) # type: Tuple[str, ...]\n\n# Build a module-level map of fore, back, and style names to escape code.\ncodeformat = '\\033[{}m'.format # type: CodeFormatFunc\nextforeformat = '\\033[38;5;{}m'.format # type: CodeFormatFunc\nextbackformat = '\\033[48;5;{}m'.format # type: CodeFormatFunc\nrgbforeformat = '\\033[38;2;{};{};{}m'.format # type: CodeFormatRgbFunc\nrgbbackformat = '\\033[48;2;{};{};{}m'.format # type: CodeFormatRgbFunc\n\n\ndef _build_codes() -> Dict[str, Dict[str, str]]:\n \"\"\" Build code map, encapsulated to reduce module-level globals. \"\"\"\n built = {\n 'fore': {},\n 'back': {},\n 'style': {},\n } # type: Dict[str, Dict[str, str]]\n\n # Set codes for forecolors (30-37) and backcolors (40-47)\n # Names are given to some of the 256-color variants as 'light' colors.\n for name, number in _namemap:\n # Not using format_* functions here, no validation needed.\n built['fore'][name] = codeformat(30 + number)\n built['back'][name] = codeformat(40 + number)\n litename = 'light{}'.format(name) # type: str\n built['fore'][litename] = codeformat(90 + number)\n built['back'][litename] = codeformat(100 + number)\n\n # Set reset codes for fore/back.\n built['fore']['reset'] = codeformat(39)\n built['back']['reset'] = codeformat(49)\n\n # Set style codes.\n for code, names in _stylemap:\n for alias in names:\n built['style'][alias] = codeformat(code)\n\n # Extended (256 color codes)\n for i in range(256):\n built['fore'][str(i)] = extforeformat(i)\n built['back'][str(i)] = extbackformat(i)\n\n return built\n\n\ndef _build_codes_reverse(\n codes: Dict[str, Dict[str, str]]) -> Dict[str, Dict[str, str]]:\n \"\"\" Build a reverse escape-code to name map, based on an existing\n name to escape-code map.\n \"\"\"\n built = {} # type: Dict[str, Dict[str, str]]\n for codetype, codemap in codes.items():\n for name, escapecode in codemap.items():\n # Skip shorcut aliases to avoid overwriting long names.\n if len(name) < 2:\n continue\n if built.get(codetype, None) is None:\n built[codetype] = {}\n built[codetype][escapecode] = name\n return built\n\n\ndef auto_disable(\n enabled: Optional[bool]=True,\n fds: Optional[Sequence[IO]]=(sys.stdout, sys.stderr)) -> None:\n \"\"\" Automatically decide whether to disable color codes if stdout or\n stderr are not ttys.\n\n Arguments:\n enabled : Whether to automatically disable color codes.\n When set to True, the fds will be checked for ttys.\n When set to False, enable() is called.\n fds : Open file descriptors to check for ttys.\n If any non-ttys are found, colors will be disabled.\n Objects must have a isatty() method.\n \"\"\"\n if enabled:\n if not all(getattr(f, 'isatty', lambda: False)() for f in fds):\n disable()\n else:\n enable()\n\n\ndef disable() -> None:\n \"\"\" Disable color codes for Colr and the convenience color() function.\n Created to be used by auto_disable(), for piping output to file or\n other commands.\n \"\"\"\n global _disabled\n _disabled = True\n\n\ndef disabled() -> bool:\n \"\"\" Public access to _disabled. \"\"\"\n return _disabled\n\n\ndef enable() -> None:\n \"\"\" Enable color codes for Colr and the convenience color() function.\n This only needs to be called if disable() was called previously.\n \"\"\"\n global _disabled\n _disabled = False\n\n\ndef enabled() -> bool:\n \"\"\" Public access to _disabled. \"\"\"\n return not _disabled\n\n\ndef _format_code(\n number: FormatArg,\n backcolor: Optional[bool]=False,\n light: Optional[bool]=False,\n extended: Optional[bool]=False) -> str:\n \"\"\" Return an escape code for a fore/back color, by number.\n This is a convenience method for handling the different code types\n all in one shot.\n It also handles some validation.\n format_fore/format_back wrap this function to reduce code duplication.\n\n Arguments:\n number : Integer or RGB tuple to format into an escape code.\n backcolor : Whether this is for a back color, otherwise it's fore.\n light : Whether this should be a 'light' color.\n extended : Whether this should be an extended (256) color.\n\n If `light` and `extended` are both given, only `light` is used.\n \"\"\"\n if backcolor:\n codetype = 'back'\n # A dict of codeformat funcs. These funcs return an escape code str.\n formatters = {\n 'code': lambda n: codeformat(40 + n),\n 'lightcode': lambda n: codeformat(100 + n),\n 'ext': lambda n: extbackformat(n),\n 'rgb': lambda r, g, b: rgbbackformat(r, g, b),\n } # type: Dict[str, Callable[..., str]]\n else:\n codetype = 'fore'\n formatters = {\n 'code': lambda n: codeformat(30 + n),\n 'lightcode': lambda n: codeformat(90 + n),\n 'ext': lambda n: extforeformat(n),\n 'rgb': lambda r, g, b: rgbforeformat(r, g, b),\n }\n try:\n r, g, b = (int(x) for x in number) # type: ignore\n except (TypeError, ValueError):\n # Not an rgb code.\n # This variable, and it's cast is only to satisfy the type checks.\n try:\n n = int(cast(int, number))\n except ValueError:\n # Not an rgb code, or a valid code number.\n raise InvalidColr(\n number,\n 'Expecting RGB or 0-255 for {} code.'.format(codetype)\n )\n if light:\n if not in_range(n, 0, 9):\n raise InvalidColr(\n n,\n 'Expecting 0-9 for light {} code.'.format(codetype)\n )\n return formatters['lightcode'](n)\n elif extended:\n if not in_range(n, 0, 255):\n raise InvalidColr(\n n,\n 'Expecting 0-255 for ext. {} code.'.format(codetype)\n )\n return formatters['ext'](n)\n\n if not in_range(n, 0, 9):\n raise InvalidColr(\n n,\n 'Expecting 0-9 for {} code.'.format(codetype)\n )\n return formatters['code'](n)\n\n # Rgb code.\n try:\n if not all(in_range(x, 0, 255) for x in (r, g, b)):\n raise InvalidColr(\n (r, g, b),\n 'RGB value for {} not in range 0-255.'.format(codetype)\n )\n except TypeError:\n # Was probably a 3-char string. Not an rgb code though.\n raise InvalidColr(\n (r, g, b),\n 'RGB value for {} contains invalid number.'.format(codetype)\n )\n return formatters['rgb'](r, g, b)\n\n\ndef format_back(\n number: FormatArg,\n light: Optional[bool]=False,\n extended: Optional[bool]=False) -> str:\n \"\"\" Return an escape code for a back color, by number.\n This is a convenience method for handling the different code types\n all in one shot.\n It also handles some validation.\n \"\"\"\n return _format_code(\n number,\n backcolor=True,\n light=light,\n extended=extended\n )\n\n\ndef format_fore(\n number: FormatArg,\n light: Optional[bool]=False,\n extended: Optional[bool]=False) -> str:\n \"\"\" Return an escape code for a fore color, by number.\n This is a convenience method for handling the different code types\n all in one shot.\n It also handles some validation.\n \"\"\"\n return _format_code(\n number,\n backcolor=False,\n light=light,\n extended=extended\n )\n\n\ndef format_style(number: int) -> str:\n \"\"\" Return an escape code for a style, by number.\n This handles invalid style numbers.\n \"\"\"\n if str(number) not in _stylenums:\n raise InvalidStyle(number)\n return codeformat(number)\n\n\ndef get_code_num(s: str) -> Optional[int]:\n \"\"\" Get code number from an escape code.\n Raises InvalidEscapeCode if an invalid number is found.\n \"\"\"\n if ';' in s:\n # Extended fore/back codes.\n numberstr = s.rpartition(';')[-1][:-1]\n else:\n # Fore, back, style, codes.\n numberstr = s.rpartition('[')[-1][:-1]\n\n num = try_parse_int(\n numberstr,\n default=None,\n minimum=0,\n maximum=255\n )\n if num is None:\n raise InvalidEscapeCode(numberstr)\n return num\n\n\ndef get_code_num_rgb(s: str) -> Optional[Tuple[int, int, int]]:\n \"\"\" Get rgb code numbers from an RGB escape code.\n Raises InvalidRgbEscapeCode if an invalid number is found.\n \"\"\"\n parts = s.split(';')\n if len(parts) != 5:\n raise InvalidRgbEscapeCode(s, reason='Count is off.')\n rgbparts = parts[-3:]\n if not rgbparts[2].endswith('m'):\n raise InvalidRgbEscapeCode(s, reason='Missing \\'m\\' on the end.')\n\n rgbparts[2] = rgbparts[2].rstrip('m')\n try:\n r, g, b = [int(x) for x in rgbparts]\n except ValueError as ex:\n raise InvalidRgbEscapeCode(s) from ex\n\n if not all(in_range(x, 0, 255) for x in (r, g, b)):\n raise InvalidRgbEscapeCode(s, reason='Not in range 0-255.')\n return r, g, b\n\n\ndef get_known_codes(\n s: Union[str, 'Colr'],\n unique: Optional[bool]=True,\n rgb_mode: Optional[bool]=False):\n \"\"\" Get all known escape codes from a string, and yield the explanations.\n \"\"\"\n\n isdisabled = disabled()\n orderedcodes = tuple((c, get_known_name(c)) for c in get_codes(s))\n codesdone = set() # type: Set[str]\n\n for code, codeinfo in orderedcodes:\n # Do the codes in order, but don't do the same code twice.\n\n if unique:\n if code in codesdone:\n continue\n codesdone.add(code)\n\n if codeinfo is None:\n continue\n codetype, name = codeinfo\n\n typedesc = '{:>13}: {!r:<23}'.format(codetype.title(), code)\n if codetype.startswith(('extended', 'rgb')):\n if isdisabled:\n codedesc = str(ColorCode(name, rgb_mode=rgb_mode))\n else:\n codedesc = ColorCode(name, rgb_mode=rgb_mode).example()\n else:\n codedesc = ''.join((\n code,\n str(name).lstrip('(').rstrip(')'),\n codes['style']['reset_all']\n ))\n\n yield ' '.join((\n typedesc,\n codedesc\n ))\n\n\ndef get_known_name(s: str) -> Optional[Tuple[str, ColorArg]]:\n \"\"\" Reverse translate a terminal code to a known color name, if possible.\n Returns a tuple of (codetype, knownname) on success.\n Returns None on failure.\n \"\"\"\n\n if not s.endswith('m'):\n # All codes end with 'm', so...\n return None\n if s.startswith('\\033[38;5;'):\n # Extended fore.\n name = codes_reverse['fore'].get(s, None)\n if name is None:\n num = get_code_num(s)\n return ('extended fore', num)\n else:\n return ('extended fore', name)\n elif s.startswith('\\033[48;5;'):\n # Extended back.\n name = codes_reverse['back'].get(s, None)\n if name is None:\n num = get_code_num(s)\n return ('extended back', num)\n else:\n return ('extended back', name)\n elif s.startswith('\\033[38;2'):\n # RGB fore.\n vals = get_code_num_rgb(s)\n if vals is not None:\n return ('rgb fore', vals)\n elif s.startswith('\\033[48;2'):\n # RGB back.\n vals = get_code_num_rgb(s)\n if vals is not None:\n return ('rgb back', vals)\n elif s.startswith('\\033['):\n # Fore, back, style.\n number = get_code_num(s)\n # Get code type based on number.\n if (number <= 7) or (number == 22):\n codetype = 'style'\n elif (((number >= 30) and (number < 40)) or\n ((number >= 90) and (number < 100))):\n codetype = 'fore'\n elif (((number >= 40) and (number < 50)) or\n ((number >= 100) and (number < 110))):\n codetype = 'back'\n else:\n raise InvalidEscapeCode(\n number,\n 'Expecting 0-7, 22, 30-39, or 40-49 for escape code',\n )\n\n name = codes_reverse[codetype].get(s, None)\n if name is not None:\n return (codetype, name)\n\n # Not a known escape code.\n return None\n\n\ndef get_terminal_size(default=(80, 35)):\n \"\"\" Return terminal (width, height) \"\"\"\n def ioctl_GWINSZ(fd):\n try:\n import fcntl\n import termios\n cr = struct.unpack(\n 'hh',\n fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')\n )\n return cr\n except (ImportError, EnvironmentError):\n pass\n cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)\n if not cr:\n try:\n fd = os.open(os.ctermid(), os.O_RDONLY)\n cr = ioctl_GWINSZ(fd)\n os.close(fd)\n except EnvironmentError:\n pass\n if not cr:\n try:\n cr = os.environ['LINES'], os.environ['COLUMNS']\n except KeyError:\n return default\n return int(cr[1]), int(cr[0])\n\n\ndef in_range(x: int, minimum: int, maximum: int) -> bool:\n \"\"\" Return True if x is >= minimum and <= maximum. \"\"\"\n return (x >= minimum and x <= maximum)\n\n\ndef parse_colr_arg(\n s: str,\n default: Optional[Any]=None,\n rgb_mode: Optional[bool]=False) -> ColorArg:\n \"\"\" Parse a user argument into a usable fore/back color value for Colr.\n If a falsey value is passed, default is returned.\n Raises InvalidColr if the argument is unusable.\n Returns: A usable value for Colr(fore/back).\n\n This validates basic/extended color names.\n This validates the range for basic/extended values (0-255).\n This validates the length/range for rgb values (0-255, 0-255, 0-255).\n\n Arguments:\n s : User's color value argument.\n Example: \"1\", \"255\", \"black\", \"25,25,25\"\n \"\"\"\n if not s:\n return default\n\n val = s.strip().lower()\n try:\n # Try as int.\n intval = int(val)\n except ValueError:\n # Try as rgb.\n try:\n r, g, b = (int(x.strip()) for x in val.split(','))\n except ValueError:\n if ',' in val:\n # User tried rgb value and failed.\n raise InvalidColr(val)\n\n # Try as name (fore/back have the same names)\n code = codes['fore'].get(val, None)\n if code:\n # Valid basic code from fore, bask, or style.\n return val\n\n # Not a basic code, try known names.\n named_data = name_data.get(val, None)\n if named_data is not None:\n # A known named color.\n return val\n\n # Not a basic/extended/known name, try as hex.\n try:\n if rgb_mode:\n return hex2rgb(val, allow_short=True)\n return hex2termhex(val, allow_short=True)\n except ValueError:\n raise InvalidColr(val)\n else:\n # Got rgb. Do some validation.\n if not all((in_range(x, 0, 255) for x in (r, g, b))):\n raise InvalidColr(val)\n # Valid rgb.\n return r, g, b\n else:\n # Int value.\n if not in_range(intval, 0, 255):\n # May have been a hex value confused as an int.\n if len(val) in (3, 6):\n try:\n if rgb_mode:\n return hex2rgb(val, allow_short=True)\n return hex2termhex(val, allow_short=True)\n except ValueError:\n raise InvalidColr(val)\n raise InvalidColr(intval)\n # Valid int value.\n return intval\n\n\ndef try_parse_int(\n s: str,\n default: Optional[Any]=None,\n minimum: Optional[int]=None,\n maximum: Optional[int]=None) -> Optional[Any]:\n \"\"\" Try parsing a string into an integer.\n On failure, return `default`.\n If the number is less then `minimum` or greater than `maximum`,\n return `default`.\n Returns an integer on success.\n \"\"\"\n try:\n n = int(s)\n except ValueError:\n return default\n if (minimum is not None) and (n < minimum):\n return default\n elif (maximum is not None) and (n > maximum):\n return default\n return n\n\n\nclass Colr(ChainedBase):\n\n \"\"\" This class colorizes text for an ansi terminal. \"\"\"\n # Known offsets for `Colr.rainbow` that will start with a certain color.\n gradient_names = {\n 'green': 0,\n 'orange': 9,\n 'lightred': 15,\n 'magenta': 20,\n 'red': 80,\n 'yellow': 62,\n 'blue': 34,\n 'cyan': 48,\n }\n\n def __init__(\n self,\n text: Optional[str]=None,\n fore: Optional[ColorArg]=None,\n back: Optional[ColorArg]=None,\n style: Optional[str]=None,\n no_closing: Optional[bool]=False) -> None:\n \"\"\" Initialize a Colr object with text and color options. \"\"\"\n # Can be initialized with colored text, not required though.\n self.data = self.color(\n text,\n fore=fore,\n back=back,\n style=style,\n no_closing=no_closing,\n )\n\n def __call__(self, text=None, fore=None, back=None, style=None):\n \"\"\" Append text to this Colr object. \"\"\"\n self.data = ''.join((\n self.data,\n self.color(text=text, fore=fore, back=back, style=style)\n ))\n return self\n\n def __dir__(self):\n \"\"\" Compute the fake method names, and include them in a listing\n of attributes for autocompletion/inspection.\n \"\"\"\n\n def fmtcode(s):\n try:\n int(s)\n return 'f_{}'.format(s)\n except ValueError:\n return s\n\n def fmtbgcode(s):\n try:\n int(s)\n return 'b_{}'.format(s)\n except ValueError:\n return 'bg{}'.format(s)\n\n attrs = [fmtcode(k) for k in codes['fore']]\n attrs.extend(fmtbgcode(k) for k in codes['back'])\n attrs.extend(k for k in codes['style'])\n attrs.extend((\n 'center',\n 'chained',\n 'color_code',\n 'color',\n 'data',\n 'format',\n 'gradient',\n 'join',\n 'ljust',\n 'print',\n 'rjust',\n 'str'\n ))\n return attrs\n\n def __getattr__(self, attr):\n \"\"\" If the attribute matches a fore, back, or style name,\n return the color() function. Otherwise, return known\n attributes and raise AttributeError for others.\n \"\"\"\n knownmethod = self._attr_to_method(attr)\n if knownmethod is not None:\n return knownmethod\n\n try:\n val = self.__getattribute__(attr)\n except AttributeError as ex:\n try:\n val = self.data.__getattribute__(attr)\n except AttributeError:\n raise AttributeError(ex)\n return val\n\n def _attr_to_method(self, attr):\n \"\"\" Return the correct color function by method name.\n Uses `partial` to build kwargs on the `chained` func.\n On failure/unknown name, returns None.\n \"\"\"\n\n if attr in codes['fore']:\n # Fore method\n return partial(self.chained, fore=attr)\n elif attr in codes['style']:\n # Style method\n return partial(self.chained, style=attr)\n elif attr.startswith('bg'):\n # Back method\n name = attr[2:].lstrip('_')\n if name in codes['back']:\n return partial(self.chained, back=name)\n elif attr.startswith(('b256_', 'b_')):\n # Back 256 method\n # Remove the b256_ portion.\n name = attr.partition('_')[2]\n return self._ext_attr_to_partial(name, 'back')\n elif attr.startswith(('f256_', 'f_')):\n # Fore 256 method\n name = attr.partition('_')[2]\n return self._ext_attr_to_partial(name, 'fore')\n\n return None\n\n def _ext_attr_to_partial(self, name, kwarg_key):\n \"\"\" Convert a string like '233' or 'aliceblue' into partial for\n self.chained.\n \"\"\"\n try:\n intval = int(name)\n except ValueError:\n # Try as an extended name_data name.\n info = name_data.get(name, None)\n if info is None:\n # Not an int value or name_data name.\n return None\n kws = {kwarg_key: info['code']}\n return partial(self.chained, **kws)\n # Integer str passed, use the int value.\n kws = {kwarg_key: intval}\n return partial(self.chained, **kws)\n\n def _gradient_black_line(\n self, text, start, step=1,\n fore=None, back=None, style=None, reverse=False, rgb_mode=False):\n \"\"\" Yield colorized characters,\n within the 24-length black gradient.\n \"\"\"\n if start < 232:\n start = 232\n elif start > 255:\n start = 255\n if reverse:\n codes = list(range(start, 231, -1))\n else:\n codes = list(range(start, 256))\n return ''.join((\n self._iter_text_wave(\n text,\n codes,\n step=step,\n fore=fore,\n back=back,\n style=style,\n rgb_mode=rgb_mode\n )\n ))\n\n def _gradient_black_lines(\n self, text, start, step=1,\n fore=None, back=None, style=None, reverse=False,\n movefactor=2, rgb_mode=False):\n \"\"\" Yield colorized characters,\n within the 24-length black gradient,\n treating each line separately.\n \"\"\"\n if not movefactor:\n def factor(i):\n return start\n else:\n # Increase the start for each line.\n def factor(i):\n return start + (i * movefactor)\n return '\\n'.join((\n self._gradient_black_line(\n line,\n start=factor(i),\n step=step,\n fore=fore,\n back=back,\n style=style,\n reverse=reverse,\n rgb_mode=rgb_mode,\n )\n for i, line in enumerate(text.splitlines())\n ))\n\n def _gradient_rgb_line(\n self, text, start, stop, step=1,\n fore=None, back=None, style=None):\n \"\"\" Yield colorized characters, morphing from one rgb value to\n another.\n \"\"\"\n return self._gradient_rgb_line_from_morph(\n text,\n list(self._morph_rgb(start, stop, step=step)),\n fore=fore,\n back=back,\n style=style\n )\n\n def _gradient_rgb_line_from_morph(\n self, text, morphlist, fore=None, back=None, style=None):\n \"\"\" Yield colorized characters, morphing from one rgb value to\n another.\n \"\"\"\n try:\n listlen = len(morphlist)\n except TypeError:\n morphlist = list(morphlist)\n listlen = len(morphlist)\n neededsteps = listlen // len(text)\n iterstep = 1\n if neededsteps > iterstep:\n # Skip some members of morphlist, to be sure to reach the end.\n iterstep = neededsteps\n usevals = morphlist\n if iterstep > 1:\n # Rebuild the morphlist, skipping some.\n usevals = [usevals[i] for i in range(0, listlen, iterstep)]\n return ''.join((\n self._iter_text_wave(\n text,\n usevals,\n fore=fore,\n back=back,\n style=style,\n rgb_mode=False,\n )\n ))\n\n def _gradient_rgb_lines(\n self, text, start, stop, step=1,\n fore=None, back=None, style=None, movefactor=None):\n \"\"\" Yield colorized characters, morphing from one rgb value to\n another. This treats each line separately.\n \"\"\"\n morphlist = list(self._morph_rgb(start, stop, step=step))\n if movefactor:\n # Moving means we need the morph to wrap around.\n morphlist.extend(self._morph_rgb(stop, start, step=step))\n if movefactor < 0:\n # Increase the start for each line.\n def move():\n popped = []\n for _ in range(abs(movefactor)):\n try:\n popped.append(morphlist.pop(0))\n except IndexError:\n pass\n morphlist.extend(popped)\n return morphlist\n else:\n # Decrease start for each line.\n def move():\n for _ in range(movefactor):\n try:\n val = morphlist.pop(-1)\n except IndexError:\n pass\n else:\n morphlist.insert(0, val)\n return morphlist\n\n return '\\n'.join((\n self._gradient_rgb_line_from_morph(\n line,\n move() if movefactor else morphlist,\n fore=fore,\n back=back,\n style=style,\n )\n for i, line in enumerate(text.splitlines())\n ))\n\n def _iter_text_wave(\n self, text, numbers, step=1,\n fore=None, back=None, style=None, rgb_mode=False):\n \"\"\" Yield colorized characters from `text`, using a wave of `numbers`.\n Arguments:\n text : String to be colorized.\n numbers : A list/tuple of numbers (256 colors).\n step : Number of characters to colorize per color.\n fore : Fore color to use (name or number).\n (Back will be gradient)\n back : Background color to use (name or number).\n (Fore will be gradient)\n style : Style name to use.\n rgb_mode : Use number for rgb value.\n This should never be used when the numbers\n are rgb values themselves.\n \"\"\"\n if fore and back:\n raise ValueError('Both fore and back colors cannot be specified.')\n\n pos = 0\n end = len(text)\n numbergen = self._iter_wave(numbers)\n\n def make_color(n):\n try:\n r, g, b = n\n except TypeError:\n if rgb_mode:\n return n, n, n\n return n\n return r, g, b\n\n for value in numbergen:\n lastchar = pos + step\n yield self.color(\n text[pos:lastchar],\n fore=make_color(value) if fore is None else fore,\n back=make_color(value) if fore is not None else back,\n style=style\n )\n if lastchar >= end:\n numbergen.send(True)\n pos = lastchar\n\n @staticmethod\n def _iter_wave(iterable, count=0):\n \"\"\" Move from beginning to end, and then end to beginning, a number of\n iterations through an iterable (must accept len(iterable)).\n Example:\n print(' -> '.join(_iter_wave('ABCD', count=8)))\n >> A -> B -> C -> D -> C -> B -> A -> B\n\n If `count` is less than 1, this will run forever.\n You can stop it by sending a Truthy value into the generator:\n gen = self._iter_wave('test')\n for c in gen:\n if c == 's':\n # Stop the generator early.\n gen.send(True)\n print(c)\n \"\"\"\n up = True\n pos = 0\n i = 0\n try:\n end = len(iterable)\n except TypeError:\n iterable = list(iterable)\n end = len(iterable)\n\n # Stop on count, or run forever.\n while (i < count) if count > 0 else True:\n try:\n stop = yield iterable[pos]\n # End of generator (user sent the stop signal)\n if stop:\n break\n except IndexError:\n # End of iterable, when len(iterable) is < count.\n up = False\n\n # Change directions if needed, otherwise increment/decrement.\n if up:\n pos += 1\n if pos == end:\n up = False\n pos = end - 2\n else:\n pos -= 1\n if pos < 0:\n up = True\n pos = 1\n i += 1\n\n def _morph_rgb(self, rgb1, rgb2, step=1):\n \"\"\" Morph an rgb value into another, yielding each step along the way.\n \"\"\"\n pos1, pos2 = list(rgb1), list(rgb2)\n indexes = [i for i, _ in enumerate(pos1)]\n\n def step_value(a, b):\n \"\"\" Returns the amount to add to `a` to make it closer to `b`,\n multiplied by `step`.\n \"\"\"\n if a < b:\n return step\n if a > b:\n return -step\n return 0\n\n steps = [step_value(pos1[x], pos2[x]) for x in indexes]\n stepcnt = 0\n while (pos1 != pos2):\n stepcnt += 1\n stop = yield tuple(pos1)\n if stop:\n break\n for x in indexes:\n if pos1[x] != pos2[x]:\n pos1[x] += steps[x]\n if (steps[x] < 0) and (pos1[x] < pos2[x]):\n # Over stepped, negative.\n pos1[x] = pos2[x]\n if (steps[x] > 0) and (pos1[x] > pos2[x]):\n # Over stepped, positive.\n pos1[x] = pos2[x]\n yield tuple(pos1)\n\n def _rainbow_color(self, freq, i):\n \"\"\" Calculate a single hexcode value for a piece of a rainbow.\n Arguments:\n freq : \"Tightness\" of colors (see self.rainbow())\n i : Index of character in string to colorize.\n \"\"\"\n return '{:02x}{:02x}{:02x}'.format(*self._rainbow_rgb(freq, i))\n\n def _rainbow_hex_chars(self, s, freq=0.1, spread=3.0, offset=0):\n \"\"\" Iterate over characters in a string to build data needed for a\n rainbow effect.\n Yields tuples of (char, hexcode).\n Arguments:\n s : String to colorize.\n freq : Frequency/\"tightness\" of colors in the rainbow.\n Best results when in the range 0.0-1.0.\n Default: 0.1\n spread : Spread/width of colors.\n Default: 3.0\n offset : Offset for start of rainbow.\n Default: 0\n \"\"\"\n return (\n (c, self._rainbow_color(freq, offset + i / spread))\n for i, c in enumerate(s)\n )\n\n def _rainbow_line(\n self, text, freq=0.1, spread=3.0, offset=0,\n rgb_mode=False, **colorargs):\n \"\"\" Create rainbow using the same offset for all text.\n Arguments:\n text : String to colorize.\n freq : Frequency/\"tightness\" of colors in the rainbow.\n Best results when in the range 0.0-1.0.\n Default: 0.1\n spread : Spread/width of colors.\n Default: 3.0\n offset : Offset for start of rainbow.\n Default: 0\n rgb_mode : If truthy, use RGB escape codes instead of\n extended 256 and approximate hex match.\n Keyword Arguments:\n colorargs : Any extra arguments for the color function,\n such as fore, back, style.\n These need to be treated carefully to not\n 'overwrite' the rainbow codes.\n \"\"\"\n fore = colorargs.get('fore', None)\n back = colorargs.get('back', None)\n style = colorargs.get('style', None)\n if fore:\n color_args = (lambda value: {\n 'back': value if rgb_mode else hex2term(value),\n 'style': style,\n 'fore': fore\n })\n else:\n color_args = (lambda value: {\n 'fore': value if rgb_mode else hex2term(value),\n 'style': style,\n 'back': back\n })\n\n if rgb_mode:\n method = self._rainbow_rgb_chars\n else:\n method = self._rainbow_hex_chars\n return ''.join(\n self.color(c, **color_args(hval))\n for c, hval in method(\n text,\n freq=freq,\n spread=spread,\n offset=offset)\n )\n\n def _rainbow_lines(\n self, text, freq=0.1, spread=3.0, offset=0, movefactor=0,\n rgb_mode=False, **colorargs):\n \"\"\" Create rainbow text, using the same offset for each line.\n Arguments:\n text : String to colorize.\n freq : Frequency/\"tightness\" of colors in the rainbow.\n Best results when in the range 0.0-1.0.\n Default: 0.1\n spread : Spread/width of colors.\n Default: 3.0\n offset : Offset for start of rainbow.\n Default: 0\n movefactor : Factor for offset increase on each new line.\n Default: 0\n rgb_mode : If truthy, use RGB escape codes instead of\n extended 256 and approximate hex match.\n\n Keyword Arguments:\n fore, back, style : Other args for the color() function.\n \"\"\"\n if not movefactor:\n def factor(i):\n return offset\n else:\n # Increase the offset for each line.\n def factor(i):\n return offset + (i * movefactor)\n return '\\n'.join(\n self._rainbow_line(\n line,\n freq=freq,\n spread=spread,\n offset=factor(i),\n rgb_mode=rgb_mode,\n **colorargs)\n for i, line in enumerate(text.splitlines()))\n\n def _rainbow_rgb(self, freq, i):\n \"\"\" Calculate a single rgb value for a piece of a rainbow.\n Arguments:\n freq : \"Tightness\" of colors (see self.rainbow())\n i : Index of character in string to colorize.\n \"\"\"\n # Borrowed from lolcat, translated from ruby.\n red = math.sin(freq * i + 0) * 127 + 128\n green = math.sin(freq * i + 2 * math.pi / 3) * 127 + 128\n blue = math.sin(freq * i + 4 * math.pi / 3) * 127 + 128\n return int(red), int(green), int(blue)\n\n def _rainbow_rgb_chars(self, s, freq=0.1, spread=3.0, offset=0):\n \"\"\" Iterate over characters in a string to build data needed for a\n rainbow effect.\n Yields tuples of (char, (r, g, b)).\n Arguments:\n s : String to colorize.\n freq : Frequency/\"tightness\" of colors in the rainbow.\n Best results when in the range 0.0-1.0.\n Default: 0.1\n spread : Spread/width of colors.\n Default: 3.0\n offset : Offset for start of rainbow.\n Default: 0\n \"\"\"\n return (\n (c, self._rainbow_rgb(freq, offset + i / spread))\n for i, c in enumerate(s)\n )\n\n def b_hex(self, value, text=None, fore=None, style=None, rgb_mode=False):\n \"\"\" A chained method that sets the back color to an hex value.\n Arguments:\n value : Hex value to convert.\n text : Text to style if not building up color codes.\n fore : Fore color for the text.\n style : Style for the text.\n rgb_mode : If False, the closest extended code is used,\n otherwise true color (rgb) mode is used.\n\n \"\"\"\n if rgb_mode:\n try:\n colrval = hex2rgb(value, allow_short=True)\n except ValueError:\n raise InvalidColr(value)\n else:\n try:\n colrval = hex2term(value, allow_short=True)\n except ValueError:\n raise InvalidColr(value)\n return self.chained(text=text, fore=fore, back=colrval, style=style)\n\n def b_rgb(self, r, g, b, text=None, fore=None, style=None):\n \"\"\" A chained method that sets the back color to an RGB value.\n Arguments:\n r : Red value.\n g : Green value.\n b : Blue value.\n text : Text to style if not building up color codes.\n fore : Fore color for the text.\n style : Style for the text.\n \"\"\"\n return self.chained(text=text, fore=fore, back=(r, g, b), style=style)\n\n def chained(self, text=None, fore=None, back=None, style=None):\n \"\"\" Called by the various 'color' methods to colorize a single string.\n The RESET_ALL code is appended to the string unless text is empty.\n Raises ValueError on invalid color names.\n\n Arguments:\n text : String to colorize, or None for BG/Style change.\n fore : Name of fore color to use.\n back : Name of back color to use.\n style : Name of style to use.\n \"\"\"\n self.data = ''.join((\n self.data,\n self.color(text=text, fore=fore, back=back, style=style),\n ))\n return self\n\n def color(\n self, text=None, fore=None, back=None, style=None,\n no_closing=False):\n \"\"\" A method that colorizes strings, not Colr objects.\n Raises InvalidColr for invalid color names.\n The 'reset_all' code is appended if text is given.\n \"\"\"\n text = str(text) if text is not None else ''\n if _disabled:\n return text\n has_args = (\n (fore is not None) or\n (back is not None) or\n (style is not None)\n )\n # Considered to have unclosed codes if embedded codes exist and\n # the last code was not a color code.\n embedded_codes = get_codes(text)\n has_end_code = embedded_codes and embedded_codes[-1] == closing_code\n # Add closing code if not already added, there is text, and\n # some kind of color/style was used (whether from args, or\n # color codes were included in the text already).\n # If the last code embedded in the text was a closing code,\n # then it is not added.\n # This can be overriden with `no_closing`.\n needs_closing = (\n text and\n (not no_closing) and\n (not has_end_code) and\n (has_args or embedded_codes)\n )\n if needs_closing:\n end = closing_code\n else:\n end = ''\n return ''.join((\n self.color_code(fore=fore, back=back, style=style),\n text,\n end,\n ))\n\n def color_code(self, fore=None, back=None, style=None):\n \"\"\" Return the codes for this style/colors. \"\"\"\n # Map from style type to raw code formatter function.\n colorcodes = []\n resetcodes = []\n userstyles = {'style': style, 'back': back, 'fore': fore}\n for stype in userstyles:\n stylearg = userstyles.get(stype, None)\n if not stylearg:\n # No value for this style name, don't use it.\n continue\n # Get escape code for this style.\n code = self.get_escape_code(stype, stylearg)\n stylename = str(stylearg).lower()\n if (stype == 'style') and (stylename in ('0', )):\n resetcodes.append(code)\n elif stylename.startswith('reset'):\n resetcodes.append(code)\n else:\n colorcodes.append(code)\n # Reset codes come first, to not override colors.\n return ''.join((''.join(resetcodes), ''.join(colorcodes)))\n\n def color_dummy(self, text=None, **kwargs):\n \"\"\" A wrapper for str() that matches self.color().\n For overriding when _auto_disable is used.\n \"\"\"\n return str(text) if text is not None else ''\n\n def format(self, *args, **kwargs):\n \"\"\" Like str.format, except it returns a Colr. \"\"\"\n return self.__class__(self.data.format(*args, **kwargs))\n\n def get_escape_code(self, codetype, value):\n \"\"\" Convert user arg to escape code. \"\"\"\n valuefmt = str(value).lower()\n code = codes[codetype].get(valuefmt, None)\n if code:\n # Basic code from fore, back, or style.\n return code\n\n named_funcs = {\n 'fore': format_fore,\n 'back': format_back,\n 'style': format_style,\n }\n\n # Not a basic code, try known names.\n converter = named_funcs.get(codetype, None)\n if converter is None:\n raise ValueError(\n 'Invalid code type. Expecting {}, got: {!r}'.format(\n ', '.join(named_funcs),\n codetype\n )\n )\n # Try as hex.\n with suppress(ValueError):\n value = int(hex2term(value, allow_short=True))\n return converter(value, extended=True)\n\n named_data = name_data.get(valuefmt, None)\n if named_data is not None:\n # A known named color.\n try:\n return converter(named_data['code'], extended=True)\n except TypeError:\n # Passing a known name as a style?\n if codetype == 'style':\n raise InvalidStyle(value)\n raise\n # Not a known color name/value, try rgb.\n try:\n r, g, b = (int(x) for x in value)\n # This does not mean we have a 3 int tuple. It could '111'.\n # The converter should catch it though.\n except (TypeError, ValueError):\n # Not an rgb value.\n if codetype == 'style':\n raise InvalidStyle(value)\n try:\n escapecode = converter(value)\n except ValueError as ex:\n raise InvalidColr(value) from ex\n return escapecode\n\n def gradient(\n self, text=None, name=None, fore=None, back=None, style=None,\n freq=0.1, spread=None, linemode=True,\n movefactor=2, rgb_mode=False):\n \"\"\" Return a gradient by color name. Uses rainbow() underneath to\n build the gradients, starting at a known offset.\n Arguments:\n text : Text to make gradient (self.data when not given).\n The gradient text is joined to self.data when\n this is used.\n name : Color name for the gradient (same as fore names).\n Default: black\n fore : Fore color. Back will be gradient when used.\n Default: None (fore is gradient)\n back : Back color. Fore will be gradient when used.\n Default: None (back=reset/normal)\n style : Style for the gradient.\n Default: None (reset/normal)\n freq : Frequency of color change.\n Higher means more colors.\n Best when in the 0.0-1.0 range.\n Default: 0.1\n spread : Spread/width of each color (in characters).\n Default: 3.0 for colors, 1 for black/white\n linemode : Colorize each line in the input.\n Default: True\n movefactor : Factor for offset increase on each line when\n using linemode.\n Minimum value: 0\n Default: 2\n rgb_mode : Use true color (rgb) codes.\n \"\"\"\n try:\n # Try explicit offset (passed in with `name`).\n offset = int(name)\n except (TypeError, ValueError):\n name = name.lower().strip() if name else 'black'\n # Black and white are separate methods.\n if name == 'black':\n return self.gradient_black(\n text=text,\n fore=fore,\n back=back,\n style=style,\n step=int(spread) if spread else 1,\n linemode=linemode,\n movefactor=movefactor,\n rgb_mode=rgb_mode\n )\n elif name == 'white':\n return self.gradient_black(\n text=text,\n fore=fore,\n back=back,\n style=style,\n step=int(spread) if spread else 1,\n linemode=linemode,\n movefactor=movefactor,\n reverse=True,\n rgb_mode=rgb_mode\n )\n try:\n # Get rainbow offset from known name.\n offset = self.gradient_names[name]\n except KeyError:\n raise ValueError('Unknown gradient name: {}'.format(name))\n\n return self.rainbow(\n text=text,\n fore=fore,\n back=back,\n style=style,\n offset=offset,\n freq=freq,\n spread=spread or 3.0,\n linemode=linemode,\n movefactor=movefactor,\n rgb_mode=rgb_mode,\n )\n\n def gradient_black(\n self, text=None, fore=None, back=None, style=None,\n start=None, step=1, reverse=False,\n linemode=True, movefactor=2, rgb_mode=False):\n \"\"\" Return a black and white gradient.\n Arguments:\n text : String to colorize.\n This will always be greater than 0.\n fore : Foreground color, background will be gradient.\n back : Background color, foreground will be gradient.\n style : Name of style to use for the gradient.\n start : Starting 256-color number.\n The `start` will be adjusted if it is not within\n bounds.\n This will always be > 15.\n This will be adjusted to fit within a 6-length\n gradient, or the 24-length black/white gradient.\n step : Number of characters to colorize per color.\n This allows a \"wider\" gradient.\n linemode : Colorize each line in the input.\n Default: True\n movefactor : Factor for offset increase on each line when\n using linemode.\n Minimum value: 0\n Default: 2\n rgb_mode : Use true color (rgb) method and codes.\n \"\"\"\n gradargs = {\n 'step': step,\n 'fore': fore,\n 'back': back,\n 'style': style,\n 'reverse': reverse,\n 'rgb_mode': rgb_mode,\n }\n\n if linemode:\n gradargs['movefactor'] = 2 if movefactor is None else movefactor\n method = self._gradient_black_lines\n else:\n method = self._gradient_black_line\n\n if text:\n return self.__class__(\n ''.join((\n self.data or '',\n method(\n text,\n start or (255 if reverse else 232),\n **gradargs)\n ))\n )\n\n # Operating on self.data.\n return self.__class__(\n method(\n self.stripped(),\n start or (255 if reverse else 232),\n **gradargs)\n )\n\n def gradient_rgb(\n self, text=None, fore=None, back=None, style=None,\n start=None, stop=None, step=1, linemode=True, movefactor=0):\n \"\"\" Return a black and white gradient.\n Arguments:\n text : String to colorize.\n fore : Foreground color, background will be gradient.\n back : Background color, foreground will be gradient.\n style : Name of style to use for the gradient.\n start : Starting rgb value.\n stop : Stopping rgb value.\n step : Number of characters to colorize per color.\n This allows a \"wider\" gradient.\n This will always be greater than 0.\n linemode : Colorize each line in the input.\n Default: True\n movefactor : Amount to shift gradient for each line when\n `linemode` is set.\n\n \"\"\"\n gradargs = {\n 'step': step,\n 'fore': fore,\n 'back': back,\n 'style': style,\n }\n start = start or (0, 0, 0)\n stop = stop or (255, 255, 255)\n if linemode:\n method = self._gradient_rgb_lines\n gradargs['movefactor'] = movefactor\n else:\n method = self._gradient_rgb_line\n\n if text:\n return self.__class__(\n ''.join((\n self.data or '',\n method(\n text,\n start,\n stop,\n **gradargs\n ),\n ))\n )\n\n # Operating on self.data.\n return self.__class__(\n method(\n self.stripped(),\n start,\n stop,\n **gradargs\n )\n )\n\n def hex(self, value, text=None, back=None, style=None, rgb_mode=False):\n \"\"\" A chained method that sets the fore color to an hex value.\n Arguments:\n value : Hex value to convert.\n text : Text to style if not building up color codes.\n back : Back color for the text.\n style : Style for the text.\n rgb_mode : If False, the closest extended code is used,\n otherwise true color (rgb) mode is used.\n\n \"\"\"\n if rgb_mode:\n try:\n colrval = hex2rgb(value, allow_short=True)\n except ValueError:\n raise InvalidColr(value)\n else:\n try:\n colrval = hex2term(value, allow_short=True)\n except ValueError:\n raise InvalidColr(value)\n return self.chained(text=text, fore=colrval, back=back, style=style)\n\n def join(self, *colrs, **colorkwargs):\n \"\"\" Like str.join, except it returns a Colr.\n Arguments:\n colrs : One or more Colrs. If a list or tuple is passed as an\n argument it will be flattened.\n Keyword Arguments:\n fore, back, style...\n see color().\n \"\"\"\n flat = []\n for clr in colrs:\n if isinstance(clr, (list, tuple, GeneratorType)):\n # Flatten any lists, at least once.\n flat.extend(str(c) for c in clr)\n else:\n flat.append(str(clr))\n\n if colorkwargs:\n fore = colorkwargs.get('fore', None)\n back = colorkwargs.get('back', None)\n style = colorkwargs.get('style', None)\n flat = (\n self.color(s, fore=fore, back=back, style=style)\n for s in flat\n )\n return self.__class__(self.data.join(flat))\n\n def lstrip(self, chars=None):\n \"\"\" Like str.lstrip, except it returns the Colr instance. \"\"\"\n return self.__class__(\n self._str_strip('lstrip', chars),\n no_closing=chars and (closing_code in chars),\n )\n\n def print(self, *args, **kwargs):\n \"\"\" Chainable print method. Prints self.data and then clears it. \"\"\"\n print(self, *args, **kwargs)\n self.data = ''\n return self\n\n def rainbow(\n self, text=None, fore=None, back=None, style=None,\n freq=0.1, offset=30, spread=3.0,\n linemode=True, movefactor=2, rgb_mode=False):\n \"\"\" Make rainbow gradient text.\n Arguments:\n text : Text to make gradient.\n Default: self.data\n fore : Fore color to use (makes back the rainbow).\n Default: None\n back : Back color to use (makes fore the rainbow).\n Default: None\n style : Style for the rainbow.\n Default: None\n freq : Frequency of color change, a higher value means\n more colors.\n Best results when in the range 0.0-1.0.\n Default: 0.1\n offset : Offset for start of rainbow.\n Default: 30\n spread : Spread/width of each color.\n Default: 3.0,\n linemode : Colorize each line in the input.\n Default: True\n movefactor : Factor for offset increase on each line when\n using linemode.\n Minimum value: 0\n Default: 2\n rgb_mode : Use RGB escape codes instead of extended 256 and\n approximate hex matches.\n \"\"\"\n if fore and back:\n raise ValueError('Cannot use both fore and back with rainbow()')\n\n rainbowargs = {\n 'freq': freq,\n 'spread': spread,\n 'offset': offset,\n 'fore': fore,\n 'back': back,\n 'style': style,\n 'rgb_mode': rgb_mode,\n }\n if linemode:\n rainbowargs['movefactor'] = movefactor\n method = self._rainbow_lines\n else:\n method = self._rainbow_line\n\n if text:\n # Prepend existing self.data to the rainbow text.\n return self.__class__(\n ''.join((\n self.data,\n method(text, **rainbowargs)\n ))\n )\n\n # Operate on self.data.\n return self.__class__(\n method(self.stripped(), **rainbowargs)\n )\n\n def rgb(self, r, g, b, text=None, back=None, style=None):\n \"\"\" A chained method that sets the fore color to an RGB value.\n Arguments:\n r : Red value.\n g : Green value.\n b : Blue value.\n text : Text to style if not building up color codes.\n back : Back color for the text.\n style : Style for the text.\n\n \"\"\"\n return self.chained(text=text, fore=(r, g, b), back=back, style=style)\n\n def rstrip(self, chars=None):\n \"\"\" Like str.rstrip, except it returns the Colr instance. \"\"\"\n return self.__class__(\n self._str_strip('rstrip', chars),\n no_closing=chars and (closing_code in chars),\n )\n\n def strip(self, chars=None):\n \"\"\" Like str.strip, except it returns the Colr instance. \"\"\"\n return self.__class__(\n self._str_strip('strip', chars),\n no_closing=chars and (closing_code in chars),\n )\n\n\nclass InvalidArg(ValueError):\n \"\"\" A ValueError for when the user uses invalid arguments. \"\"\"\n default_label = 'Invalid argument'\n default_format = '{label}: {value}'\n\n def __init__(self, value, label=None):\n self.label = label or self.default_label\n self.value = value\n\n def __str__(self):\n return self.default_format.format(\n label=self.label,\n value=repr(self.value)\n )\n\n def as_colr(self, label_args=None, value_args=None):\n \"\"\" Like __str__, except it returns a colorized Colr instance. \"\"\"\n label_args = label_args or {'fore': 'red'}\n value_args = value_args or {'fore': 'blue', 'style': 'bright'}\n return Colr(self.default_format.format(\n label=Colr(self.label, **label_args),\n value=Colr(repr(self.value), **value_args),\n ))\n\n\nclass InvalidColr(InvalidArg):\n \"\"\" A ValueError for when user passes an invalid colr name, value, rgb.\n \"\"\"\n accepted_values = (\n ('hex', '[#]rgb/[#]rrggbb'),\n ('name', 'white/black/etc.'),\n ('rgb', '0-255, 0-255, 0-255'),\n ('value', '0-255'),\n )\n default_label = 'Expecting colr name/value:\\n {types}'.format(\n types=',\\n '.join(\n '{lbl:<5} ({val})'.format(lbl=l, val=v)\n for l, v in accepted_values\n )\n )\n default_format = '{label}\\n Got: {value}'\n\n def as_colr(\n self, label_args=None, type_args=None, type_val_args=None,\n value_args=None):\n \"\"\" Like __str__, except it returns a colorized Colr instance. \"\"\"\n label_args = label_args or {'fore': 'red'}\n type_args = type_args or {'fore': 'yellow'}\n type_val_args = type_val_args or {'fore': 'grey'}\n value_args = value_args or {'fore': 'blue', 'style': 'bright'}\n\n return Colr(self.default_format.format(\n label=Colr(':\\n ').join(\n Colr('Expecting colr name/value', **label_args),\n ',\\n '.join(\n '{lbl:<5} ({val})'.format(\n lbl=Colr(l, **type_args),\n val=Colr(v, **type_val_args),\n )\n for l, v in self.accepted_values\n )\n ),\n value=Colr(repr(self.value), **value_args)\n ))\n\n\nclass InvalidEscapeCode(InvalidArg):\n \"\"\" A ValueError for when an invalid escape code is given. \"\"\"\n default_label = 'Expecting 0-255 for escape code value'\n\n\nclass InvalidRgbEscapeCode(InvalidEscapeCode):\n \"\"\" A ValueError for when an invalid rgb escape code is given. \"\"\"\n default_label = 'Expecting 0-255;0-255;0-255 for RGB escape code value'\n\n def __init__(self, value, label=None, reason=None):\n super().__init__(value, label=label)\n self.reason = reason\n\n def __str__(self):\n s = super().__str__(self)\n if self.reason:\n s = '\\n '.join((s, str(self.reason)))\n return s\n\n\nclass InvalidStyle(InvalidColr):\n default_label = 'Expecting style value:\\n {styles}'.format(\n styles='\\n '.join(\n ', '.join(t[1])\n for t in _stylemap\n )\n )\n\n def as_colr(\n self, label_args=None, type_args=None, value_args=None):\n \"\"\" Like __str__, except it returns a colorized Colr instance. \"\"\"\n label_args = label_args or {'fore': 'red'}\n type_args = type_args or {'fore': 'yellow'}\n value_args = value_args or {'fore': 'blue', 'style': 'bright'}\n\n return Colr(self.default_format.format(\n label=Colr(':\\n ').join(\n Colr('Expecting style value', **label_args),\n Colr(',\\n ').join(\n Colr(', ').join(\n Colr(v, **type_args)\n for v in t[1]\n )\n for t in _stylemap\n )\n ),\n value=Colr(repr(self.value), **value_args)\n ))\n\n\n# Raw code map, available to users.\ncodes = _build_codes()\ncodes_reverse = _build_codes_reverse(codes)\n\n# Shortcuts.\ncolor = Colr().color\n\nif __name__ == '__main__':\n if ('--auto-disable' in sys.argv) or ('-a' in sys.argv):\n auto_disable()\n\n print(\n Colr('warning', 'red')\n .join('[', ']', style='bright')(' ')\n .green('This module is meant to be ran with `python -m colr`.')\n )\n","sub_path":"colr/colr.py","file_name":"colr.py","file_ext":"py","file_size_in_byte":65531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"487101223","text":"#-------------------------------------------------------------------------------\n#\n# Project: ngEO Browse Server \n# Authors: Fabian Schindler \n# Marko Locher \n# Stephan Meissl \n#\n#-------------------------------------------------------------------------------\n# Copyright (C) 2012 EOX IT Services GmbH\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 all\n# copies of this Software or works derived from this 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#-------------------------------------------------------------------------------\n\nimport logging\nimport subprocess\nfrom functools import wraps\n\nfrom lxml import etree\nfrom lxml.builder import E\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\n\nfrom ngeo_browse_server.config import (\n get_ngeo_config, get_project_relative_path\n)\nfrom ngeo_browse_server.lock import FileLock\nfrom ngeo_browse_server.mapcache.exceptions import SeedException\nfrom ngeo_browse_server.mapcache.tileset import URN_TO_GRID\nfrom ngeo_browse_server.mapcache.config import (\n get_mapcache_seed_config, get_tileset_path\n)\n\n\nlogger = logging.getLogger(__name__)\n\ndef seed_mapcache(seed_command, config_file, tileset, grid, \n minx, miny, maxx, maxy, minzoom, maxzoom,\n start_time, end_time, threads, delete):\n\n # translate grid URN to mapcache grid name\n try:\n grid = URN_TO_GRID[grid]\n except KeyError:\n raise SeedException(\"Invalid grid '%s'.\" % grid)\n \n if minzoom is None: minzoom = 0\n if maxzoom is None: maxzoom = 10\n \n # start- and end-time are expected to be UTC Zulu \n start_time = start_time.replace(tzinfo=None)\n end_time = end_time.replace(tzinfo=None)\n \n logger.info(\"Starting mapcaching seed with parameters: command='%s', \"\n \"config_file='%s', tileset='%s', grid='%s', \"\n \"extent='%s,%s,%s,%s', zoom='%s,%s', threads='%s'.\" \n % (seed_command, config_file, tileset, grid, \n minx, miny, maxx, maxy, minzoom, maxzoom, threads))\n \n args = [\n seed_command,\n \"-c\", config_file,\n \"-t\", tileset,\n \"-g\", grid,\n \"-e\", \"%f,%f,%f,%f\" % (minx, miny, maxx, maxy),\n \"-n\", str(threads),\n \"-z\", \"%d,%d\" % (minzoom, maxzoom),\n \"-D\", \"TIME=%sZ/%sZ\" % (start_time.isoformat(), end_time.isoformat()),\n \"-m\", \"seed\" if not delete else \"delete\",\n \"-q\",\n \"-M\", \"8,8\",\n ]\n if not delete:\n args.append(\"-f\")\n \n logger.debug(\"mapcache seeding command: '%s'. raw: '%s'.\"\n % (\" \".join(args), args))\n \n process = subprocess.Popen(args, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n \n out, err = process.communicate()\n for string in (out, err):\n for line in string.split(\"\\n\"):\n logger.info(line)\n \n if process.returncode != 0:\n raise SeedException(\"'%s' failed. Returncode '%d'.\"\n % (seed_command, process.returncode))\n \n logger.info(\"Seeding finished with returncode '%d'.\" % process.returncode)\n \n return process.returncode\n\n\n\ndef lock_mapcache_config(func):\n \"\"\" Decorator for functions involving the mapcache configuration to lock \n the mapcache configuration.\n \"\"\"\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n config = get_ngeo_config()\n mapcache_config = get_mapcache_seed_config(config)\n with FileLock(get_project_relative_path(\"mapcache.xml.lck\")):\n return func(*args, **kwargs)\n return wrapper\n\n\ndef read_mapcache_xml(config):\n mapcache_config = get_mapcache_seed_config(config)\n mapcache_xml_filename = mapcache_config[\"config_file\"]\n with open(mapcache_xml_filename) as f:\n parser = etree.XMLParser(remove_blank_text=True)\n return etree.parse(f, parser).getroot()\n\n\ndef write_mapcache_xml(root, config):\n mapcache_config = get_mapcache_seed_config(config)\n mapcache_xml_filename = mapcache_config[\"config_file\"]\n with open(mapcache_xml_filename, \"w\") as f:\n f.write(etree.tostring(root, pretty_print=True))\n\n\n@lock_mapcache_config\ndef add_mapcache_layer_xml(browse_layer, config=None):\n name = browse_layer.id\n\n config = config or get_ngeo_config()\n\n root = read_mapcache_xml(config)\n\n if len(root.xpath(\"cache[@name='%s']|source[@name='%s']|tileset[@name='%s']\" % (name, name, name))):\n raise Exception(\n \"Cannot add browse layer to mapcache config, because a layer with \"\n \"the name '%s' is already inserted.\" % name\n )\n\n tileset_path = get_tileset_path(browse_layer.browse_type)\n\n root.extend([\n E(\"cache\", \n E(\"dbfile\", tileset_path),\n E(\"detect_blank\", \"true\"),\n name=name, type=\"sqlite3\"\n ),\n E(\"source\",\n E(\"getmap\", \n E(\"params\",\n E(\"LAYERS\", name),\n E(\"TRANSPARENT\", \"true\")\n )\n ),\n E(\"http\", \n E(\"url\", \"http://localhost/browse/ows?\")\n ),\n name=name, type=\"wms\"\n ),\n E(\"tileset\",\n E(\"source\", name),\n E(\"cache\", name),\n E(\"grid\", \n URN_TO_GRID[browse_layer.grid], **{\n \"max-cached-zoom\": str(browse_layer.highest_map_level),\n \"out-of-zoom-strategy\": \"reassemble\"\n }\n ),\n E(\"format\", \"mixed\"),\n E(\"metatile\", \"8 8\"),\n E(\"expires\", \"3600\"),\n E(\"read-only\", \"true\"),\n E(\"timedimension\",\n E(\"dbfile\", settings.DATABASES[\"mapcache\"][\"NAME\"]),\n E(\"query\", \"select strftime('%Y-%m-%dT%H:%M:%SZ',start_time)||'/'||strftime('%Y-%m-%dT%H:%M:%SZ',end_time) from time where source_id=:tileset and start_time<=datetime(:end_timestamp,'unixepoch') and end_time>=datetime(:start_timestamp,'unixepoch') and maxx>=:minx and maxy>=:miny and minx<=:maxx and miny<=:maxy order by end_time desc limit 100\"),\n type=\"sqlite\", default=\"2010\" # TODO: default year into layer definition\n ),\n name=name\n )\n ])\n\n write_mapcache_xml(root, config)\n\n\n@lock_mapcache_config\ndef remove_mapcache_layer_xml(browse_layer, config=None):\n config = config or get_ngeo_config()\n\n name = browse_layer.id\n\n root = read_mapcache_xml(config)\n\n root.remove(root.xpath(\"cache[@name='%s']\" % name)[0])\n root.remove(root.xpath(\"source[@name='%s']\" % name)[0])\n root.remove(root.xpath(\"tileset[@name='%s']\" % name)[0])\n\n write_mapcache_xml(root, config)\n","sub_path":"ngeo_browse_server/mapcache/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":7722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"278350632","text":"UP = 1\nDOWN = 2\nFLOOR_COUNT = 6\n\nclass ElevatorLogic(object):\n \"\"\"\n An incorrect implementation. Can you make it pass all the tests?\n\n Fix the methods below to implement the correct logic for elevators.\n The tests are integrated into `README.md`. To run the tests:\n $ python -m doctest -v README.md\n\n To learn when each method is called, read its docstring.\n To interact with the world, you can get the current floor from the\n `current_floor` property of the `callbacks` object, and you can move the\n elevator by setting the `motor_direction` property. See below for how this is done.\n \"\"\"\n\n def __init__(self):\n # Feel free to add any instance variables you want.\n self._callbacks = None\n self._next_floor = None\n self.queue = {}\n\n def init_floors(self):\n starting_floor = self.callbacks.current_floor\n self.floors = {}\n for i in range(FLOOR_COUNT):\n i += starting_floor\n self.floors[i] = Floor(self, i)\n\n @property\n def callbacks(self):\n return self._callbacks\n @callbacks.setter\n def callbacks(self, value):\n self._callbacks = value\n self.init_floors()\n\n @property\n def motor_direction(self):\n return self.callbacks.motor_direction\n @motor_direction.setter\n def motor_direction(self, value):\n if value is None:\n self._next_floor = None\n self.callbacks.motor_direction = value\n\n @property\n def next_floor(self):\n next_floor = self._next_floor\n if next_floor is None:\n next_floor = self._next_floor = self.find_next_stop()\n return next_floor\n\n def on_called(self, floor, direction):\n \"\"\"\n This is called when somebody presses the up or down button to call the elevator.\n This could happen at any time, whether or not the elevator is moving.\n The elevator could be requested at any floor at any time, going in either direction.\n\n floor: the floor that the elevator is being called to\n direction: the direction the caller wants to go, up or down\n \"\"\"\n f = self.floors[floor]\n if direction == UP:\n f.called_going_up = True\n elif direction == DOWN:\n f.called_going_down = True\n\n def on_floor_selected(self, floor):\n \"\"\"\n This is called when somebody on the elevator chooses a floor.\n This could happen at any time, whether or not the elevator is moving.\n Any floor could be requested at any time.\n\n floor: the floor that was requested\n \"\"\"\n self.floors[floor].selected_from_cabin = True\n\n def on_floor_changed(self):\n \"\"\"\n This lets you know that the elevator has moved one floor up or down.\n You should decide whether or not you want to stop the elevator.\n \"\"\"\n current_floor = self.callbacks.current_floor\n should_stop = self.floors[current_floor].on_arrival()\n if should_stop:\n self.motor_direction = None\n\n def on_ready(self):\n \"\"\"\n This is called when the elevator is ready to go.\n Maybe passengers have embarked and disembarked. The doors are closed,\n time to actually move, if necessary.\n \"\"\"\n current_floor = self.callbacks.current_floor\n next_floor = self.next_floor\n if next_floor is None:\n direction = None\n elif next_floor.index > current_floor:\n direction = UP\n elif next_floor.index < current_floor:\n direction = DOWN\n self.motor_direction = direction\n\n def iter_queue(self):\n for i in sorted(self.queue.keys())[:]:\n yield i, self.queue[i]\n\n def update_queue(self, floor, value, mode=None, remove_all=False):\n if value:\n add_to_queue = floor not in [r.floor for r in self.queue.values()]\n if not add_to_queue:\n for i, r in self.iter_queue():\n if r.floor is not floor:\n continue\n if r.direction is None:\n continue\n if mode is not None and mode == r.direction:\n continue\n add_to_queue = True\n break\n if add_to_queue:\n if not len(self.queue):\n i = 0\n else:\n i = max(self.queue.keys()) + 1\n request = FloorRequest(floor, mode, i)\n self.queue[i] = request\n self._next_floor = None\n else:\n removed = False\n for i, r in self.iter_queue():\n if r.floor is not floor:\n continue\n if remove_all:\n del self.queue[i]\n continue\n if r.direction is None:\n del self.queue[i]\n self._next_floor = None\n elif r.direction == mode and not removed:\n del self.queue[i]\n removed = True\n self._next_floor = None\n\n def find_next_stop(self):\n if not len(self.queue):\n return None\n direction = self.motor_direction\n current_floor = self.callbacks.current_floor\n next_floor = None\n for i, r in self.iter_queue():\n if direction is None:\n if r.floor == current_floor:\n return r.floor\n if next_floor is None or r.floor < next_floor:\n next_floor = r.floor\n continue\n if r.floor < current_floor:\n continue\n if next_floor is None or r.floor < next_floor:\n next_floor = r.floor\n return next_floor\n\n\nclass Floor(object):\n def __init__(self, elevator_logic, index):\n self.elevator_logic = elevator_logic\n self.index = index\n self._selected_from_cabin = False\n self._called_going_up = False\n self._called_going_down = False\n\n @property\n def elevator_floor(self):\n return self.elevator_logic.callbacks.current_floor\n @property\n def elevator_direction(self):\n return self.elevator_logic.motor_direction\n\n @property\n def queued(self):\n q = (self.called_going_up or\n self.called_going_down or\n self.selected_from_cabin)\n return q\n @queued.setter\n def queued(self, value):\n attrs = ['selected_from_cabin', 'called_going_up', 'called_going_down']\n for attr in attrs:\n setattr(self, ''.join(['_', attr]), value)\n self.elevator_logic.update_queue(self, False, remove_all=True)\n\n @property\n def selected_from_cabin(self):\n return self._selected_from_cabin\n @selected_from_cabin.setter\n def selected_from_cabin(self, value):\n if value == self.selected_from_cabin:\n return\n self._selected_from_cabin = value\n self.elevator_logic.update_queue(self, value)\n\n @property\n def called_going_up(self):\n return self._called_going_up\n @called_going_up.setter\n def called_going_up(self, value):\n if value == self.called_going_up:\n return\n self._called_going_up = value\n self.elevator_logic.update_queue(self, value, UP)\n\n @property\n def called_going_down(self):\n return self._called_going_down\n @called_going_down.setter\n def called_going_down(self, value):\n if value == self.called_going_down:\n return\n self._called_going_down = value\n self.elevator_logic.update_queue(self, value, DOWN)\n\n def on_arrival(self):\n floors = self.elevator_logic.floors\n should_stop = False\n if self.selected_from_cabin:\n self.selected_from_cabin = False\n should_stop = True\n direction = self.elevator_direction\n if direction == UP:\n if self.called_going_up:\n self.called_going_up = False\n should_stop = True\n elif self.called_going_down:\n other_floors = [floors[k] for k in floors if k > self.index]\n for floor in other_floors:\n if floor.queued:\n break\n self.called_going_down = False\n should_stop = True\n elif direction == DOWN:\n if self.called_going_down:\n self.called_going_down = False\n should_stop = True\n elif self.called_going_up:\n other_floors = [floors[k] for k in floors if k < self.index]\n for floor in other_floors:\n if floor.queued:\n break\n self.called_going_up = False\n should_stop = True\n return should_stop\n\n def __cmp__(self, other):\n if not isinstance(other, Floor):\n other = self.elevator_logic.floors[other]\n if self.index == other.index:\n return 0\n direction = self.elevator_direction\n current_floor = self.elevator_floor\n if direction is None:\n if self.index == current_floor:\n return 0\n if self.index > current_floor:\n my_diff = self.index - current_floor\n else:\n my_diff = current_floor - self.index\n if other.index > current_floor:\n other_diff = other.index - current_floor\n else:\n other_diff = current_floor - other.index\n if my_diff > other_diff:\n return 1\n return -1\n if direction == UP:\n if self.index < other.index:\n return 1\n return -1\n elif direction == DOWN:\n if self.index > other.index:\n return -1\n return 1\n\n def __repr__(self):\n return 'Floor {0}'.format(self.index)\n\n def __str__(self):\n return str(self.index)\n\nclass FloorRequest(object):\n def __init__(self, floor, direction, request_index):\n self.floor = floor\n self.direction = direction\n self.request_index = request_index\n","sub_path":"elevator.py","file_name":"elevator.py","file_ext":"py","file_size_in_byte":10256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"157691452","text":"from discord.ext import commands\nfrom .utils import sql\nfrom .utils.tag_manager import parser as tag_parser\n\nimport json\n\nALLOWED_ATTRIBUTES = [\n # Object\n \"id\",\n \"created_at\",\n # User\n \"name\",\n \"discriminator\",\n \"avatar\",\n \"bot\",\n \"avatar_url\",\n \"default_avatar\",\n \"default_avatar_url\",\n \"mention\",\n \"display_name\",\n # Message\n \"edited_at\",\n \"tts\",\n \"content\",\n \"mention_everyone\",\n \"mentions\",\n \"channel_mentions\",\n \"role_mentions\",\n \"pinned\",\n \"clean_content\",\n # Reaction\n \"custom_emoji\",\n \"count\",\n \"me\",\n # Embed\n \"title\",\n \"description\",\n \"url\",\n \"color\",\n # Guild\n \"name\",\n \"afk_timeout\",\n \"region\",\n \"afk_channel\",\n \"icon\",\n \"owner\",\n \"unavailable\",\n \"large\",\n \"mfa_level\",\n \"splash\",\n \"default_channel\",\n \"icon_url\",\n \"splash_url\",\n \"member_count\",\n # Member\n \"joined_at\",\n \"status\",\n \"game\",\n \"nick\",\n # Channel\n \"topic\",\n \"is_private\",\n \"position\",\n \"bitrate\",\n \"user_limit\",\n \"is_default\"\n # TODO: very important: add attributes per-type and global\n]\n\nclass Tag:\n def __init__(self, tag):\n self.name = tag.name\n self.author_id = tag.author_id\n self.content = tag.content\n self.uses = tag.uses\n self.timestamp = tag.timestamp\n\n def __repr__(self):\n return f\"\"\n\nclass TagOverrides(tag_parser.TagFunctions):\n def __init__(self, bot, ctx, tag, **kwargs):\n super().__init__()\n\n self.bot = bot\n self.ctx = ctx\n self.tag = tag\n self.debug = kwargs.get(\"debug\", False)\n self.data_cache = {}\n\n setattr(self, \"if\", self._TagOverrides__compare)\n\n def get(self, key, default='Does not exist'):\n with self.bot.db_scope() as session:\n tag_dict = session.query(sql.TagVariable).filter_by(tag_name=self.tag.name).first()\n\n if tag_dict is None:\n tag_dict = sql.TagVariable(tag_name=self.tag.name, data=json.dumps({}))\n session.add(tag_dict)\n\n return tag_dict.data[key]\n\n def set(self, key, value):\n with self.bot.db_scope() as session:\n tag_dict = session.query(sql.TagVariable).filter_by(tag_name=self.tag.name).first()\n if tag_dict is None:\n tag_dict = sql.TagVariable(tag_name=self.tag.name, data=json.dumps({}))\n session.add(tag_dict)\n\n tag_dict.data[key] = value\n\n self.bot.db.flag(tag_dict, \"data\") # force it to re-commit\n\n def fetch(self, key):\n return self.data_cache[key]\n\n def cache(self, key, value):\n self.data_cache[key] = value\n\n def attr(self, obj, key):\n if key not in ALLOWED_ATTRIBUTES:\n raise ValueError(f\"Illegal attribute {key}\")\n else:\n return getattr(obj, key)\n\n def author(self):\n return self.ctx.author\n\n def self(self):\n return self.tag\n\n def channel(self):\n return self.ctx.channel\n\n def guild(self):\n return self.ctx.guild\n\n def __compare(self, condition, result, else_=''):\n if condition:\n return result\n else:\n return else_\n\n def eq(self, first, second):\n return first == second or str(first).lower() == str(second).lower()\n\nclass Tags:\n def __init__(self, bot):\n self.bot = bot\n\n async def get_tag(self, tag_name):\n with self.bot.db_scope() as session:\n tag = session.query(sql.Tag).filter_by(name=tag_name).first()\n if tag is not None:\n tag.uses = tag.uses + 1\n return Tag(tag)\n else:\n return None\n\n @commands.group(name=\"tag\", pass_context=True, brief=\"tag manager\", invoke_without_command=True)\n async def tag_group(self, ctx):\n print(\"tags\")\n\n @tag_group.command(name=\"test\", pass_context=True, brief=\"run a test parse\")\n async def test_tag(self, ctx, *, text:str):\n tag = await self.get_tag(\"test\")\n try:\n parser = tag_parser.Parser(text, debug=self.bot._DEBUG, override=TagOverrides(self.bot, ctx, tag, debug=self.bot._DEBUG))\n result = await parser()\n except Exception as e:\n await ctx.send(f\"```diff\\n- [{type(e).__name__}]: {e}\\n```\")\n return\n\n result = str(result)\n await ctx.send(f\"\\* {tag.name} is empty \\*\" if result == \"\" else result)\n\ndef setup(bot):\n bot.add_cog(Tags(bot))","sub_path":"cogs/command_tags.py","file_name":"command_tags.py","file_ext":"py","file_size_in_byte":4602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"324755175","text":"import importlib\nimport logging\nimport os\nimport requests\nimport json\n\nfrom django.http import HttpResponse\nfrom django.template.loader import render_to_string\nfrom django.views.decorators.http import require_POST\nfrom django.shortcuts import redirect\n\nfrom . import input\nfrom . import links_left\nfrom ..models import model_handler\nfrom ..REST import rest_funcs\n\nprint('qed.pram_app.views.output')\n\n\ndef output_page_html(header, model, tables_html):\n \"\"\"Generates HTML to fill '.articles_output' div on output page\"\"\"\n\n #epa template header\n html = render_to_string('01epa_drupal_header.html', {\n 'SITE_SKIN': os.environ['SITE_SKIN'],\n 'TITLE': u\"\\u00FCbertool\"\n })\n html += render_to_string('02epa_drupal_header_bluestripe_onesidebar.html', {})\n html += render_to_string('03epa_drupal_section_title_pram.html', {})\n\n #main body\n html += render_to_string('06ubertext_start_index_drupal.html', {\n 'TITLE': header + ' Output',\n 'TEXT_PARAGRAPH': tables_html\n })\n html += render_to_string('07ubertext_end_drupal.html', {})\n html += links_left.ordered_list(model)\n\n #css and scripts\n html += render_to_string('09epa_drupal_pram_css.html', {})\n #html += render_to_string('09epa_drupal_pram_scripts.html', {})\n\n #epa template footer\n html += render_to_string('10epa_drupal_footer.html', {})\n return html\n\n\ndef output_page_view(request, model='none', header=''):\n \"\"\"\n Django view render method for model output pages. This method is called \n by output_page() method.\n \"\"\"\n\n logging.info('=========== New Model Handler - Single Model Run ===========')\n print(request)\n model_obj = model_handler.model_input_post_receiver(request, model)\n #logging.info(model_obj)\n if type(model_obj) is tuple:\n model_output_html = model_obj[0]\n model_obj = model_obj[1]\n else:\n # Dynamically import the model table module\n tablesmodule = importlib.import_module('.' + model + '_tables', 'pram_app.models.' + model)\n # logging.info(model_obj.__dict__)\n \"\"\" Generate Timestamp HTML from \"*_tables\" module \"\"\"\n model_output_html = tablesmodule.timestamp(model_obj)\n \"\"\" Generate Model input & output tables HTML from \"*_tables\" module \"\"\"\n tables_output = tablesmodule.table_all(model_obj)\n \"\"\" Append Timestamp & model input & output table's HTML \"\"\"\n if type(tables_output) is tuple:\n model_output_html = model_output_html + tables_output[0]\n elif type(tables_output) is str or type(tables_output) is unicode:\n model_output_html = model_output_html + tables_output\n else:\n model_output_html = \"table_all() Returned Wrong Type\"\n\n \"\"\" Render output page view HTML \"\"\"\n html = output_page_html(header, model, model_output_html)\n response = HttpResponse()\n response.write(html)\n return response\n\n\n@require_POST\ndef output_page(request, model='none', header=''):\n \"\"\"\n Django HTTP POST handler for output page. Receives form data which has been validated by input.py.\n Calls method to render the output.\n This method maps to: '/pram//output'\n \"\"\"\n model_views_location = 'pram_app.models.' + model + '.views'\n viewmodule = importlib.import_module(model_views_location)\n header = viewmodule.header\n\n if model == 'sam':\n task = {}\n try:\n inputs = request.POST.dict()\n if os.environ['IN_DOCKER'] == \"False\":\n task = requests.post('http://localhost:7777/rest/pram/sam/', data=inputs)\n else:\n task = requests.post('http://qed_nginx:7777/rest/pram/sam/', data=inputs)\n task_id = json.loads(task.content.decode(encoding=\"utf-8\").replace(\"//\", \"\"))\n return redirect('/pram/sam/output/status/' + task_id['task_id'])\n except Exception as ex:\n print(\"Error attempting to connect to flask endpoint for sam. \" + str(ex))\n return redirect('/pram/sam/output/status/1234567890')\n # return redirect('/pram/sam/output/status/' + task_id['task_id'])\n\n else:\n return output_page_view(request, model, header)\n","sub_path":"views/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":4192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"429815931","text":"import datetime\n\n\ndef choose_action(action):\n text = \"Looking for action...\"\n\n if action == \"hello\":\n text = hello()\n elif action == \"time\":\n text = get_time()\n else:\n text = \"No action matched!\"\n\n return text\n\n\ndef hello():\n \"\"\"\n Says \"Hello World\" to the user\n \"\"\"\n print('hello action')\n\n text = \"Hello World\"\n return text\n\n\ndef get_time():\n \"\"\"\n Tells the user the current time\n \"\"\"\n print('time action')\n\n now = datetime.datetime.now()\n hour = now.hour\n minute = now.minute\n second = now.second\n\n text = \"Сейчас самое время %d:%d:%d\" % (hour, minute, second)\n return text\n","sub_path":"actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"386826600","text":"from urllib.parse import urlparse,parse_qs\nimport urllib\nimport copy\nimport asyncio\nimport aiohttp\nimport time\n\n\nxss_payloads = ['','','javascript::alert(1)']\nsqli_payloads = [\"%27\",\"\\\\\",\"/\",\"if(1,sleep(5),1)\"]\nlfi_payloads = ['../../../etc/passwd']\n\n\npayloads = xss_payloads + sqli_payloads + lfi_payloads\n\n\ncheck = []\n\n\ndef fuzz(url):\n url = urllib.parse.unquote(url, encoding='utf-8', errors='replace')\n up = urlparse(url)\n try:\n if up.query == '':\n return\n for ext in ['.js','.jpg','.css','.gif','.png','.txt']:\n if ext in up.path:\n return\n except:\n return\n\t\n print('Start fuzz ' + url)\n query = parse_qs(up.query)\n\n\n #Fuzz\n for i in query:\n for j in payloads:\n queryCheck = copy.deepcopy(query)\n upCheck = copy.deepcopy(up)\n queryCheck[i][0] = j\n\n queryTarget = ''\n for i in queryCheck:\n data = i + '=' + queryCheck[i][0] + '&'\n queryTarget += data\n\n url = up.scheme + '://' + up.netloc + up.path + '?' + queryTarget\n\n check.append(url)\n\n for i in query:\n for j in payloads:\n queryCheck = copy.deepcopy(query)\n upCheck = copy.deepcopy(up)\n queryCheck[i][0] = urllib.parse.quote(j)\n\n queryTarget = ''\n for i in queryCheck:\n data = i + '=' + queryCheck[i][0] + '&'\n queryTarget += data\n\n url = up.scheme + '://' + up.netloc + up.path + '?' + queryTarget\n\n check.append(url)\n for i in query:\n for j in payloads:\n queryCheck = copy.deepcopy(query)\n upCheck = copy.deepcopy(up)\n queryCheck[i][0] = urllib.parse.quote(urllib.parse.quote(j))\n\n queryTarget = ''\n for i in queryCheck:\n data = i + '=' + queryCheck[i][0] + '&'\n queryTarget += data\n\n url = up.scheme + '://' + up.netloc + up.path + '?' + queryTarget\n\n check.append(url)\n\n\n loop = asyncio.get_event_loop()\n tasks = [checkUrl(url) for url in check]\n loop.run_until_complete(asyncio.wait(tasks))\n loop.close()\n\n\n\n \nasync def checkUrl(url):\n async with aiohttp.ClientSession() as session:\n try:\n time.sleep(2)\n url = url[:-1]\n async with session.get(url) as resp:\n text = await resp.text()\n for i in xss_payloads:\n if i in text:\n print (\"XSS ==> \" + url)\n except:\n pass\n\n","sub_path":"lib/fuzz.py","file_name":"fuzz.py","file_ext":"py","file_size_in_byte":2656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"632707316","text":"\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import (Input, Dense,\n MaxPooling2D, Conv2D,\n Flatten, multiply)\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.utils import plot_model\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nmpl.rcParams['font.sans-serif'] = [u'SimHei']\nmpl.rcParams['axes.unicode_minus'] = False\n\n\nnp.random.seed(0)\nnp.set_printoptions(precision=4)\n\ntf.random.set_seed(0)\n\n#################### 0. 参数 ####################\n\nBATCH_SIZE = 100\nEPOCHS = 10\n\n#################### 1. 数据 ####################\n\nmnist = tf.keras.datasets.mnist\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train, x_test = x_train / 255.0, x_test / 255.0\n\nx_train = x_train[..., np.newaxis]\nx_test = x_test[..., np.newaxis]\n\nprint(x_train.shape)\n\ntrain_ds = tf.data.Dataset.from_tensor_slices(\n (x_train, y_train)).shuffle(1000).batch(BATCH_SIZE)\n\ntest_ds = tf.data.Dataset.from_tensor_slices(\n (x_test, y_test)).batch(BATCH_SIZE)\n\n#################### 2. SELeNet ####################\n\n\ndef SeNetBlock(feature, reduction=4):\n temp = feature\n channel_axis = 1 if K.image_data_format() == \"channels_first\" else -1\n channels = temp.shape[channel_axis]\n # 得到feature的通道数量w\n avg_x = tf.keras.layers.GlobalAveragePooling2D()(temp)\n # 先对feature的每个通道进行全局平均池化Global Average Pooling 得到通道描述子(Squeeze)\n x = tf.keras.layers.Dense(\n units=int(channels)//reduction, activation=tf.nn.relu, use_bias=False)(avg_x)\n # 接着做reduction,用int(channels)//reduction个卷积核对 avg_x做1x1的点卷积\n x = tf.keras.layers.Dense(units=int(channels), use_bias=False)(x)\n # 接着用int(channels)个卷积核个数对 x做1x1的点卷积,扩展x回到原来的通道个数\n se_feature = tf.keras.activations.sigmoid(x) # 对x 做 sigmoid 激活\n return multiply([se_feature, feature]), se_feature\n # 返回以cbam_feature 为scale,对feature做拉伸加权的结果(Excitation)\n\n\ninput = Input(shape=(28, 28, 1))\nx = Conv2D(6, (5, 5), (1, 1), activation='relu')(input)\nx = MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same')(x)\nx = Conv2D(16, (5, 5), (1, 1),\n activation='relu', padding='valid')(x)\n# SE Module\nx, se_feature = SeNetBlock(x)\nx = MaxPooling2D(2, strides=(2, 2))(x)\nx = Flatten()(x)\nx = Dense(120, activation='relu')(x)\nx = Dense(84, activation='relu')(x)\nx = Dense(10, activation='softmax')(x)\nmodel = Model(input, [x, se_feature], name=\"SELeNet\")\n\nmodel.summary()\n\nplot_model(model, to_file=\"SELeNet.png\")\n\n#################### 3. 工具集 ####################\n\nloss_object = tf.keras.losses.SparseCategoricalCrossentropy()\n\noptimizer = tf.keras.optimizers.Adam()\n\ntrain_loss = tf.keras.metrics.Mean(name='train_loss')\ntrain_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(\n name='train_accuracy')\n\ntest_loss = tf.keras.metrics.Mean(name='test_loss')\ntest_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(\n name='test_accuracy')\n\n#################### 4. 训练&测试 ####################\n\n\n@tf.function\ndef train_step(images, labels):\n with tf.GradientTape() as tape:\n predictions, se_feature = model(images)\n loss = loss_object(labels, predictions)\n gradients = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\n train_loss(loss)\n train_accuracy(labels, predictions)\n\n\n@tf.function\ndef test_step(images, labels):\n predictions, se_feature = model(images)\n t_loss = loss_object(labels, predictions)\n\n test_loss(t_loss)\n test_accuracy(labels, predictions)\n return se_feature\n\n#################### 5. train ####################\n\nfor epoch in range(EPOCHS):\n train_loss.reset_states()\n train_accuracy.reset_states()\n test_loss.reset_states()\n test_accuracy.reset_states()\n\n for images, labels in train_ds:\n train_step(images, labels)\n\n for test_images, test_labels in test_ds:\n se_feature = test_step(test_images, test_labels)\n\n template = 'Epoch {}, Loss: {}, Accuracy: {}, Test Loss: {}, Test Accuracy: {}'\n print(template.format(epoch+1,\n train_loss.result(),\n train_accuracy.result()*100,\n test_loss.result(),\n test_accuracy.result()*100))\n\n#################### 6. test ####################\n\n\nfor i, (images, labels) in enumerate(test_ds):\n se_feature = test_step(images, labels)\n \n labels = tf.cast(labels, tf.int32)\n sorted = tf.argsort(labels)\n labels = tf.gather(labels, sorted)\n se_feature = tf.gather(se_feature, sorted)\n\n se_feature_numpy = se_feature.numpy()\n\n plt.figure()\n img = plt.imshow(se_feature_numpy)\n img.set_cmap('hot')\n plt.savefig(\"./%d_se_feature.png\" % i)\n plt.close()","sub_path":"tensorflow2/class5/class5.py","file_name":"class5.py","file_ext":"py","file_size_in_byte":5024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"180381892","text":"from typing import List\nfrom Leetcode.utils import perf\n\nimport collections\n\n\nclass Solution:\n # tc: O(N*K + Q*K)\n # sc: O(N)\n @perf\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n\n def devowel(word, wildcard):\n return ''.join([ wildcard if char in vowels else char\n for char in word.lower() ])\n\n ans = []\n wildcard = '#'\n vowels = set('aeiouAEIOU')\n words = collections.defaultdict(dict)\n\n for i, word in enumerate(wordlist):\n words[word]['normal'] = word\n\n word2 = word.lower()\n words[word2].setdefault('lower', word)\n\n word3 = devowel(word, wildcard)\n words[word3].setdefault('devowel', word)\n\n for query in queries:\n word = words[query].get('normal') \\\n or words[query.lower()].get('lower') \\\n or words[devowel(query, wildcard)].get('devowel') \\\n or ''\n ans.append(word)\n\n return ans\n","sub_path":"Leetcode/vowel_spellchecker/solution_dict.py","file_name":"solution_dict.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"454462124","text":"#!/usr/bin/env python3\n# Copyright: see copyright.txt\n\nimport logging\nimport pickle\nimport time\nfrom multiprocessing import freeze_support\nimport sys\nimport os\nfrom sys import platform, setrecursionlimit\nfrom optparse import OptionParser\nfrom optparse import OptionGroup\nfrom symbolic.loader import loaderFactory\nfrom symbolic.explore import ExplorationEngine\n\ndef main():\n # OS X support: allow dylibs to see each other; needed by SWIG\n from platform import python_implementation\n if python_implementation() == 'CPython' and platform == 'darwin':\n from ctypes import RTLD_GLOBAL\n sys.setdlopenflags(RTLD_GLOBAL)\n\n sys.setrecursionlimit(10000)\n\n print(\"PyExZ3 (Python Exploration with Z3)\")\n\n sys.path = [os.path.abspath(os.path.join(os.path.dirname(__file__)))] + sys.path\n\n usage = \"usage: %prog [options] \"\n parser = OptionParser(usage=usage)\n\n # Setup\n setup_group = OptionGroup(parser, \"Exploration Setup\")\n setup_group.add_option(\"-s\", \"--start\", dest=\"entry\", action=\"store\", help=\"Specify entry point\", default=\"\")\n setup_group.add_option(\"--cvc\", dest=\"solver\", action=\"store_const\", const=\"cvc\", help=\"Use the CVC SMT solver instead of Z3\")\n setup_group.add_option(\"--z3str2\", dest=\"solver\", action=\"store_const\", const=\"z3str2\", help=\"Use the Z3-str2 SMT solver instead of Z3\")\n setup_group.add_option(\"--z3\", dest=\"solver\", action=\"store_const\", const=\"z3\", help=\"Use the Z3 SMT solver\")\n setup_group.add_option(\"--multi\", dest=\"solver\", action=\"store_const\", const=\"multi\", help=\"Use as many different solvers as possible simultaneously\")\n parser.add_option_group(setup_group)\n\n # Configuration\n configuration_group = OptionGroup(parser, \"Exploration Configuration\")\n configuration_group.add_option(\"-n\", \"--workers\", dest=\"workers\", type=\"int\",\n help=\"Run specified number of solvers in parallel\",\n default=1)\n configuration_group.add_option(\"-p\", \"--scheduling-policy\", dest=\"scheduling_policy\", type=\"str\",\n help=\"The name of the scheduling policy used to assign solving jobs to solvers.\",\n default=\"central_queue\")\n parser.add_option_group(configuration_group)\n\n # Input Detection\n input_detection_group = OptionGroup(parser, \"Input Detection\")\n input_detection_group.add_option(\"--argparse\", dest=\"loader\", action=\"store_const\", const='argparse')\n input_detection_group.add_option(\"--sysargv\", dest=\"loader\", action=\"store_const\", const='sysargv')\n input_detection_group.add_option(\"--optparse\", dest=\"loader\", action=\"store_const\", const='optparse')\n parser.add_option_group(input_detection_group)\n\n # Limits\n limits_group = OptionGroup(parser, \"Exploration Limits\")\n limits_group.add_option(\"-t\", \"--exploration-timeout\", dest=\"explorationtimeout\", type=\"int\",\n help=\"Time in seconds to terminate the concolic execution\", default=None)\n limits_group.add_option(\"--solve-timeout\", dest=\"solvetimeouts\", action='append', type=float,\n help=\"Time in seconds to terminate a query to the SMT\", default=None)\n limits_group.add_option(\"--path-timeout\", dest=\"pathtimeout\", type=\"int\",\n help=\"Maximum solving time to traverse down a single path\", default=None)\n limits_group.add_option(\"-b\", \"--coverage-pruning\", dest=\"coverage_pruning\", type=\"int\",\n help=\"Prune paths after no coverage increase for the specified number of inputs generated.\",\n default=None)\n limits_group.add_option(\"-m\", \"--max-iters\", dest=\"max_iters\", type=\"int\", help=\"Run specified number of iterations\",\n default=0)\n parser.add_option_group(limits_group)\n\n # Serialization and Logging\n logging_group = OptionGroup(parser, \"Serialization and Logging\")\n logging_group.add_option(\"-l\", \"--log\", dest=\"logfile\", action=\"store\", help=\"Save log output to a file\", default=\"\")\n logging_group.add_option(\"-g\", \"--graph\", dest=\"execution_graph\", action=\"store\",\n help=\"The file to save the serialized execution tree\")\n logging_group.add_option(\"-d\", \"--dot\", dest=\"dot_graph\", action=\"store\",\n help=\"The file to save a DOT graph of execution tree\")\n logging_group.add_option(\"-q\", \"--query-store\", dest=\"query_store\", type=\"str\",\n help=\"The folder to store generated and the execution graph, \"\n \"currently only CVC supports full query serialization\")\n logging_group.add_option('--debug', help=\"Enables debugging output.\", action=\"store_true\", dest=\"debug\")\n parser.add_option_group(logging_group)\n\n (options, args) = parser.parse_args()\n\n debuglogging = options.debug\n\n if debuglogging:\n loglevel = logging.DEBUG\n else:\n loglevel = logging.INFO\n\n if not (options.logfile == \"\"):\n logging.basicConfig(filename=options.logfile, level=loglevel, format='%(asctime)s\\t%(levelname)s\\t%(message)s',\n datefmt='%m/%d/%Y %I:%M:%S %p')\n\n if len(args) == 0 or not os.path.exists(args[0]):\n parser.error(\"Missing app to execute\")\n sys.exit(1)\n\n solver = options.solver if options.solver is not None else \"z3\"\n solvetimeouts = options.solvetimeouts\n query_store = options.query_store\n scheduling_policy = options.scheduling_policy\n starttime_cpu = time.process_time()\n starttime_wall = time.time()\n filename = os.path.abspath(args[0])\n\n # Get the object describing the application\n app = loaderFactory(filename, options.entry, loader=options.loader)\n if app is None:\n sys.exit(1)\n\n print(\"Exploring \" + app.filename + \".\" + app.entrypoint)\n\n engine = ExplorationEngine(app.createInvocation(), solver=solver, query_store=query_store, solvetimeouts=solvetimeouts,\n workers=options.workers, scheduling_policy=scheduling_policy,\n pathtimeout=options.pathtimeout, coverage_pruning=options.coverage_pruning)\n generatedInputs, return_values, path = engine.explore(options.max_iters, options.explorationtimeout)\n # check the result\n result = app.execution_complete(return_values)\n endtime_cpu = time.process_time()\n endtime_wall = time.time()\n print(\"Execution time: {0:.2f} seconds\".format(endtime_wall - starttime_wall))\n print(\"Solver CPU: {0:.2f} seconds\".format(engine.total_solve_time))\n instrumentation_time = endtime_cpu - starttime_cpu\n print(\"Instrumentation CPU: {0:.2f} seconds\".format(instrumentation_time))\n print(\"Path coverage: {} paths\".format(len(generatedInputs)))\n total_lines, executed_lines, executed_branches = engine.coverage_statistics()\n print(\"Line coverage: {}/{} lines ({:.2%})\".format(executed_lines, total_lines, (executed_lines/total_lines) if total_lines > 0 else 0))\n print(\"Branch coverage: {} branches\".format(executed_branches))\n print(\"Exceptions: {} exceptions raised\".format(len({e for e in return_values if\n isinstance(e, Exception) and hasattr(e, 'id')})))\n print(\"Triaged exceptions: {} triaged exceptions raised\".format(len({e.id for e in return_values if\n isinstance(e, Exception) and hasattr(e, 'id')})))\n # output DOT graph\n if options.dot_graph is not None:\n with open(options.dot_graph, \"w\") as f:\n f.write(path.toDot())\n\n # output serialized exploration graph\n if options.execution_graph is not None:\n pickle.dump(path, open(options.execution_graph, \"wb\"))\n\n if not result and options.loader == None:\n sys.exit(1)\n\nif __name__ == '__main__':\n if platform.startswith('win'):\n freeze_support()\n main()","sub_path":"pyexz3.py","file_name":"pyexz3.py","file_ext":"py","file_size_in_byte":7999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"578650907","text":"def lcs(word1, word2):\n len1 = len(word1)\n len2 = len(word2)\n grid = [[0 for j in range(len2+1)] for i in range(len1+1)]\n count = 0\n for i in range(1,(len1+1)):\n for j in range(1,(len2+1)):\n if word1[i-1] == word2[j-1]:\n grid[i][j] = grid[i-1][j-1] + 1\n else:\n grid[i][j] = max(grid[i-1][j], grid[i][j-1])\n return grid[-1][-1]\n \ndef suggestion(query, word1, word2):\n first = lcs(query, word1)\n second = lcs(query, word2)\n if first >= second:\n sugg = word1\n else: sugg = word2\n return sugg\n \nf = open('INPUT.txt', 'r')\ntext = f.readlines()\nwords = []\nfor entry in text:\n if entry != '\\n':\n words.append(entry.strip())\nnum = words.pop(0)\nnum = int(num)\nans = []\nfor i in range(num):\n query = words.pop(0)\n word1 = words.pop(0)\n word2 = words.pop(0)\n ans.append(suggestion(query,word1,word2))\nwith open('OUTPUT.txt', 'w') as f:\n for word in ans:\n f.write(word+ '\\n')\n\n\n\n","sub_path":"p3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"418952696","text":"#!/usr/bin python\n# encoding: utf-8\n\nfrom common import Martrix\nfrom common.distance import get_manhattan_distance\nfrom math import sqrt, pow\n\nfrom conf import conf\n\nclass Recommendation(object):\n def __init__(self, neighbor=3, recommendation=3, user_rating_dict={}, training=False):\n self.n = neighbor #num\n self.r = recommendation #num\n\n self.save_type = conf.save_type\n self.cal_type = conf.cal_distance_type\n self.pearson_type = conf.pearson_cal_type\n\n if not training:\n if self.save_type == \"Pickle\":\n import pickle\n with file('../inter_data/user_items_rating.dict') as f:\n self.user_rating = pickle.load(f)\n else:\n self.user_rating = user_rating_dict\n\n def load_configuration(self, fobject=None):\n \"\"\"load configuration XML file\"\"\"\n pass\n\n def get_active_users(self):\n result = []\n # if number of items from one user > 3, consider as active user\n all_users = self.get_all_users()\n for x in all_users:\n if len(self.user_rating[x]) > conf.active_count:\n result.append(x)\n return result\n\n def get_all_users(self):\n users = set(self.user_rating.iterkeys())\n return list(users)\n\n def get_all_items(self, user='all'):\n if user != 'all':\n return [x for x in self.user_rating[user].iterkeys()]\n\n items_set = set()\n for d in self.user_rating.itervalues():\n for item in d.iterkeys():\n items_set.add(item)\n\n return list(items_set)\n\nif __name__ == '__main__':\n pass","sub_path":"recommendation/Recommendation.py","file_name":"Recommendation.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"259662956","text":"from reddit import reddit\n\ndef load_subs():\n f = open('config', 'r')\n subs = []\n for line in f:\n if 'sub_reddit' in line:\n s = line.split(':')\n s = s[1].replace(' ', '').replace('\\'', '').replace('[', '').replace(']', '')\n s = s.split(',')\n for sub in s:\n subs.append(sub)\n f.close()\n return subs\n\nsubs = load_subs()\nobj = []\nfor s in subs:\n obj.append(reddit(s))\n print(s)\n\n#print(obj.count)\n\nfor o in obj:\n o.get_sub()\n\n#r2 = reddit('programming')\n#r2.get_sub(5)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"222592155","text":"import os\n\nimport dj_database_url\n\nfrom .factory import *\n\n\nSETTINGS_DIR = os.path.dirname(os.path.abspath(__file__))\nPROJECT_DIR = os.path.abspath(os.path.join(SETTINGS_DIR, os.path.pardir, os.path.pardir))\nREPO_DIR = os.path.abspath(os.path.join(PROJECT_DIR, os.path.pardir))\n\ndef project_dir(*args):\n\t\"\"\"\n\tReturns the absolute path of joined args with PROJECT_DIR.\n\n\t>>> PROJECT_DIR = '/path/to/project'\n\t>>> pd = project_dir('foo', 'bar')\n\t>>> pd.endswith('example_project/foo/bar')\n\tTrue\n\t\"\"\"\n\treturn os.path.abspath(os.path.join(PROJECT_DIR, *args))\n\nDEBUG = False\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n\t('Ryan Balfanz', 'ryan@ryanbalfanz.net'),\n)\n\nMANAGERS = ADMINS\n\nSECRET_KEY = ''\n\nTEMPLATE_DIRS += (\n\tproject_dir('templates'),\n)\n\nINSTALLED_APPS += (\n\t'django.contrib.admin',\n\t'django.contrib.admindocs',\n\t'south',\n\t'django_nose',\n\t'gunicorn',\n\t'launch_page',\n)\n\nTEST_RUNNER = 'django_nose.NoseTestSuiteRunner'\n\nNOSE_ARGS = [\n\t'--cover-package=launch_page',\n\t'--with-coverage',\n\t'--with-doctest',\n]\n","sub_path":"example_project/example_project/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"603297533","text":"#!/usr/bin/python\nimport json\nimport os\nimport pwd\nimport select\nimport socket\nimport sys\nimport threading\nimport time\nimport traceback\nfrom distutils.dir_util import copy_tree\n\ntry:\n import psutil\n psutil_import_result = True\nexcept ImportError:\n psutil_import_result = False\n\nimport dropper\nfrom feeds.feed_manager import FeedsManager\n\nclass SRNd(threading.Thread):\n\n def log(self, loglevel, message):\n if loglevel >= self.config['srnd_debuglevel']:\n self.logger.log('SRNd', message, loglevel)\n\n def __init__(self, logger):\n self.ctl_groups = set(['ctl'])\n self.logger = logger\n self.config = {'srnd_debuglevel': self.logger.INFO}\n self.log(self.logger.VERBOSE, 'srnd test logging with VERBOSE')\n self.log(self.logger.DEBUG, 'srnd test logging with DEBUG')\n self.log(self.logger.INFO, 'srnd test logging with INFO')\n self.log(self.logger.WARNING, 'srnd test logging with WARNING')\n self.log(self.logger.ERROR, 'srnd test logging with ERROR')\n self.log(self.logger.CRITICAL, 'srnd test logging with CRITICAL')\n old_owner = (os.stat('data').st_uid, os.stat('data').st_gid) if os.path.exists('data') else (None, None)\n # default config. key = (value, position). position need for write human readable config\n def_config = {\n 'bind_ip': ('', 1),\n 'bind_port': (119, 2),\n 'bind_use_ipv6': (False, 3),\n 'data_dir': ('data', 4),\n 'db_dir': ('database', 5),\n 'use_chroot': (True, 6),\n 'setuid': ('news', 7),\n 'srnd_debuglevel': (self.logger.INFO, 8),\n 'infeed_debuglevel': (self.logger.INFO, 9),\n 'dropper_debuglevel': (self.logger.INFO, 10),\n 'instance_name': ('SRNd', 11)\n }\n self.config = self.init_srnd_config(def_config)\n\n self._use_psutil = psutil_import_result and not self.config['use_chroot']\n self._init_sysinfo()\n\n # install / update plugins\n self.log(self.logger.INFO, \"installing / updating plugins\")\n for directory in os.listdir('install_files'):\n copy_tree(os.path.join('install_files', directory), os.path.join(self.config['data_dir'], directory), preserve_times=True, update=True)\n\n #add data_dir in syspath and fix permission\n sys.path.append(os.path.abspath(self.config['data_dir']))\n\n # create jail\n os.chdir(self.config['data_dir'])\n\n # get initial owner\n init_owner = (os.geteuid(), os.getegid())\n\n # get owner\n if self.config['setuid'] != '':\n owner = (self.config['uid'], self.config['gid'])\n else:\n owner = init_owner\n\n # init feeds\n self.feeds = FeedsManager(log=self.log, logger=self.logger, infeed_config=self._load_infeeds_config(), infeed_debuglevel=self.config['infeed_debuglevel'])\n\n # test and fixing plugin dir permissions\n for directory in os.listdir('plugins'):\n dir_ = os.path.join('plugins', directory)\n try:\n self._permission_fix(0o755, owner, dir_)\n except OSError as e:\n if e.errno == 1:\n # FIXME what does this errno actually mean? write actual descriptions for error codes -.-\n self.log(self.logger.WARNING, \"couldn't change owner of %s. %s will likely fail to create own directories.\" % (dir_, directory))\n else:\n # FIXME: exit might not allow logger to actually output the message.\n self.log(self.logger.CRITICAL, \"trying to chown plugin directory %s failed: %s\" % (dir_, e))\n exit(1)\n\n # create some directories\n for directory in ('filesystem', 'outfeeds', 'plugins'):\n dir_ = os.path.join('config', 'hooks', directory)\n if not os.path.exists(dir_):\n os.makedirs(dir_)\n\n # check for directory structure\n directories = (\n 'incoming',\n os.path.join('incoming', 'tmp'),\n os.path.join('incoming', 'spam'),\n 'articles',\n os.path.join('articles', 'censored'),\n os.path.join('articles', 'restored'),\n os.path.join('articles', 'invalid'),\n os.path.join('articles', 'duplicate'),\n 'groups',\n 'hooks',\n 'stats',\n self.config['db_dir'])\n for directory in directories:\n if not os.path.exists(directory):\n os.mkdir(directory)\n self._permission_fix(0o755, owner, directory)\n\n # migrate db\n self._auto_db_migration()\n\n # fix all permission if owner change. it is a long time\n if old_owner != owner:\n self.log(self.logger.INFO, \"onwer change, fixing all permissions...\")\n self._deep_permission_fix(owner, '.', False)\n\n # protect some files from changes, if srnd dropping privileges\n if owner != init_owner:\n self._protect_files(init_owner)\n\n # base fixing permissions\n self._deep_permission_fix(owner, os.path.join('config', 'hooks', 'filesystem'), False)\n self._deep_permission_fix(owner, self.config['db_dir'], False)\n\n # init db manager\n self._db_manager = __import__('srnd.db_utils').db_utils.DatabaseManager(self.config['db_dir'])\n\n # importing plugins\n # we need to do this before chrooting because plugins may need to import other libraries\n self.plugins = dict()\n self.update_plugins()\n\n # start listening\n if self.config['bind_use_ipv6']:\n self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)\n else:\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n try:\n self.log(self.logger.INFO, 'start listening at %s:%i' % (self.config['bind_ip'], self.config['bind_port']))\n self.socket.bind((self.config['bind_ip'], self.config['bind_port']))\n except socket.error as e:\n if e.errno == 13:\n # FIXME: exit might not allow logger to actually output the message.\n self.log(self.logger.CRITICAL, '''[error] current user account does not have CAP_NET_BIND_SERVICE: %s\n You have three options:\n - run SRNd as root\n - assign CAP_NET_BIND_SERVICE to the user you intend to use\n - use a port > 1024 by setting bind_port at %s''' % (e, os.path.join(self.config['data_dir'], 'config', 'SRNd.conf')))\n exit(2)\n elif e.errno == 98:\n # FIXME: exit might not allow logger to actually output the message.\n self.log(self.logger.CRITICAL, '%s:%i already in use, change to a different port by setting bind_port at %s' % (self.config['bind_ip'], self.config['bind_port'], os.path.join(self.config['data_dir'], 'config', 'SRNd.conf')))\n exit(2)\n else:\n raise e\n self.socket.listen(5)\n\n if self.config['use_chroot']:\n self.log(self.logger.INFO, 'chrooting..')\n try:\n os.chroot('.')\n except OSError as e:\n if e.errno == 1:\n print(\"[error] current user account does not have CAP_SYS_CHROOT.\")\n print(\" You have three options:\")\n print(\" - run SRNd as root\")\n print(\" - assign CAP_SYS_CHROOT to the user you intend to use\")\n print(\" - disable chroot in {0} by setting chroot=False\".format(os.path.join(self.config['data_dir'], 'config', 'SRNd.conf')))\n exit(3)\n else:\n raise e\n\n if self.config['setuid'] != '':\n self.log(self.logger.INFO, 'dropping privileges..')\n try:\n os.setgid(self.config['gid'])\n os.setuid(self.config['uid'])\n except OSError as e:\n if e.errno == 1:\n print(\"[error] current user account does not have CAP_SETUID/CAP_SETGID: \", e)\n print(\" You have three options:\")\n print(\" - run SRNd as root\")\n print(\" - assign CAP_SETUID and CAP_SETGID to the user you intend to use\")\n print(\" - disable setuid in {0} by setting setuid=\".format(os.path.join(self.config['data_dir'], 'config', 'SRNd.conf')))\n exit(4)\n else:\n raise e\n\n threading.Thread.__init__(self)\n self.name = \"SRNd-listener\"\n self.dropper = dropper.dropper(\n thread_name='SRNd-dropper',\n logger=self.logger,\n master=self,\n debug=self.config['dropper_debuglevel'],\n db_connector=self._db_manager.connect,\n instance_name=self.config['instance_name']\n )\n\n self.start_up_timestamp = -1\n self.ctl_socket_handlers = dict()\n self.ctl_socket_handlers[\"status\"] = self.ctl_socket_handler_status\n self.ctl_socket_handlers[\"log\"] = self.ctl_socket_handler_logger\n self.ctl_socket_handlers[\"stats\"] = self.ctl_socket_handler_stats\n self.hooks = dict()\n self.hook_blacklist = dict()\n self._feeds_lock = threading.Lock()\n\n def _auto_db_migration(self):\n # Work only for default plugins and db locations\n targets = (\n ('censor.db3', 'censor.db3'), ('dropper.db3', 'dropper.db3'), ('hashes.db3', 'hashes.db3'), ('postman.db3', 'postman.db3'),\n ('overchan.db3', os.path.join('plugins', 'overchan', 'overchan.db3')), ('pastes.db3', os.path.join('plugins', 'paste', 'pastes.db3'))\n )\n for target in targets:\n new_location = os.path.join(self.config['db_dir'], target[0])\n if os.path.isfile(target[1]) and os.path.isfile(new_location):\n self.log(self.logger.ERROR, 'DB migrator: {0} duplicate found {1}. If you copy {2} manually, delete {1}. If not - WTF!'.format(new_location, target[1], target[0]))\n elif os.path.isfile(target[1]):\n try:\n os.rename(target[1], new_location)\n except OSError as e:\n self.log(self.logger.ERROR, 'DB migrator: Error move {} to {}: {}'.format(target[1], new_location, e))\n\n def _deep_permission_fix(self, owner, path, only_dir=True):\n \"\"\"Set permission and owner to all files and directories\"\"\"\n #TODO: 755 or 777? Or maybe 700\n mode_dir = 0o755 # rwxrwx-r-x\n mode_file = 0o664 # rw-rw-r--\n for dirpath, _, filenames in os.walk(path):\n self._permission_fix(mode_dir, owner, dirpath)\n if not only_dir:\n for file_ in filenames:\n file_link = os.path.join(dirpath, file_)\n if not os.path.islink(file_link):\n # ignore symlinks\n self._permission_fix(mode_file, owner, file_link)\n\n def _permission_fix(self, mode, owner, path):\n try:\n os.chmod(path, mode)\n os.chown(path, owner[0], owner[1])\n except OSError as e:\n username = pwd.getpwuid(self.config['uid']).pw_name if self.config['setuid'] else pwd.getpwuid(os.geteuid()).pw_name\n if e.errno == 1:\n warnings = (\n \"can't change ownership of {}.\".format(path),\n \"If you want to run as '{}' user modify {} :\".format(username, os.path.join(self.config['data_dir'], 'config', 'SRNd.conf')),\n \"set use_chroot=False, setuid={0}, start SRNd root privileges(su, sudo etc.), stop, wait, and starting SRNd as {0} without root privileges,\".format(username),\n \"or change ownership manually eg. 'sudo chown -R {0}:{0} data/', or delete the data directory\".format(username),\n \"die.\"\n )\n self.log(self.logger.CRITICAL, '\\n'.join(warnings))\n else:\n self.log(self.logger.CRITICAL, \"couldn't change owner or permission of {}: {}\".format(path, e))\n exit(1)\n\n def _protect_files(self, owner):\n mode_file = 0o664\n # Prevent add and load plugin after dropping privileges\n for dir_ in ('config', 'srnd'):\n self._deep_permission_fix(owner, dir_, False)\n # Prevent modify files and templates files - plugin can be reload\n # TODO: Protect all plugin files and directories, without tmp and out. Also, templates directory may be renamed in plugin config\n for plugin_dir in os.listdir('plugins'):\n for target in os.listdir(os.path.join('plugins', plugin_dir)):\n path = os.path.join('plugins', plugin_dir, target)\n if os.path.isfile(path):\n self._permission_fix(mode_file, owner, path)\n elif target == 'templates':\n self._deep_permission_fix(owner, path, False)\n\n\n def get_info(self, data=None):\n if data is not None and data.get('command', None) in self.ctl_socket_handlers:\n return self.ctl_socket_handlers[data['command']](data)\n else:\n return None\n\n def _get_sysinfo(self, target):\n result = None\n if target == 'cpu':\n if self._use_psutil:\n result = self._sysinfo['psutil'].cpu_percent(interval=None)\n else:\n result = 0\n elif target == 'ram':\n if self._use_psutil:\n result = self._sysinfo['psutil'].memory_info()[0]\n else:\n if self._sysinfo['ramfile'] is not None:\n self._sysinfo['ramfile'].seek(0)\n result = int(self._sysinfo['ramfile'].read().split(' ')[1]) * self._sysinfo['pagesize']\n else:\n result = 0\n elif target == 'disk_free':\n result = self._sysinfo['statvfs'].f_bavail * self._sysinfo['statvfs'].f_frsize\n elif target == 'disk_used':\n result = (self._sysinfo['statvfs'].f_blocks - self._sysinfo['statvfs'].f_bfree) * self._sysinfo['statvfs'].f_frsize\n return result\n\n def _init_sysinfo(self):\n self._sysinfo = dict()\n if self._use_psutil:\n self._sysinfo['psutil'] = psutil.Process()\n else:\n try:\n self._sysinfo['ramfile'] = open('/proc/self/statm', 'r')\n except Exception as e:\n self.log(self.logger.WARNING, 'can\\'t open ram stat file at /proc/self/statm: %s' % e)\n self._sysinfo['ramfile'] = None\n if 'SC_PAGESIZE' in os.sysconf_names:\n self._sysinfo['pagesize'] = os.sysconf('SC_PAGESIZE')\n elif 'SC_PAGE_SIZE' in os.sysconf_names:\n self._sysinfo['pagesize'] = os.sysconf('SC_PAGE_SIZE')\n elif '_SC_PAGESIZE' in os.sysconf_names:\n self._sysinfo['pagesize'] = os.sysconf('_SC_PAGESIZE')\n else:\n self._sysinfo['pagesize'] = 4096\n self._sysinfo['statvfs'] = os.statvfs(os.getcwd())\n\n def _sanitize_srnd_config(self, def_config, config):\n \"\"\"\n Fix bad or missing value, delete unknown keys\n It's modify config dict as mutable type.\n return False if need rewrite config file\n \"\"\"\n no_change = True\n for key, value in [xx for xx in config.items()]:\n if key not in def_config:\n # Unknown key, del? del!\n del config[key]\n no_change = False\n elif isinstance(def_config[key][0], bool):\n # cast bool\n if value.lower() == 'true':\n config[key] = True\n elif value.lower() == 'false':\n config[key] = False\n else:\n self.log(self.logger.WARNING, '{}: unknown value. only accepting true or false. using default of {}'.format(key, def_config[key][0]))\n config[key] = def_config[key][0]\n no_change = False\n else:\n # cast to type form type(default value)\n try:\n config[key] = type(def_config[key][0])(value)\n except ValueError:\n self.log(self.logger.WARNING, '{}: bad value type. only accepting {}, get {}. using default of {}'.format(key, type(def_config[key][0]), type(value), def_config[key][0]))\n config[key] = def_config[key][0]\n no_change = False\n # add missing key\n for key, value in def_config.items():\n if key not in config:\n config[key] = value[0]\n no_change = False\n # deep check\n for key in ('srnd_debuglevel', 'infeed_debuglevel', 'dropper_debuglevel'):\n if config[key] < 0 or config[key] > 5:\n self.log(self.logger.WARNING, '{}: only accepting integer between 0 and 5. using default of {}'.format(key, def_config[key][0]))\n config[key] = def_config[key][0]\n no_change = False\n if ' ' in config['instance_name']:\n self.log(self.logger.WARNING, \"instance_name contains a space. using default of '{}'\".format(def_config['instance_name'][0]))\n config['instance_name'] = def_config['instance_name'][0]\n no_change = False\n return no_change\n\n def _read_srnd_config(self, config_file):\n config = dict()\n with open(config_file, 'r') as f:\n for line in f:\n if line[0] not in ('#', '\\n'):\n data = line.strip('\\n').split('=', 1)\n if len(data) == 1:\n self.log(self.logger.WARNING, \"no = in setting '{}'\".format(line))\n else:\n config[data[0]] = data[1]\n return config\n\n def _write_srnd_config(self, config_list, data_dir, uid, gid):\n config_head = (\n '# changing this file requires a restart of SRNd',\n '# empty lines or lines starting with # are ignored',\n '# do not add whitespaces before or after =',\n '# additional data in this file will be overwritten every time a value has been changed'\n )\n config_path = os.path.join(data_dir, 'config')\n if not os.path.exists(config_path):\n os.makedirs(config_path)\n if uid is not None and gid is not None:\n try:\n os.chown(data_dir, uid, gid)\n os.chown(config_path, uid, gid)\n except OSError as e:\n if e.errno == 1:\n warnings = (\n \"can't change ownership of newly generated data directory.\",\n \"If you don't intend to run SRNd as root and let it chroot and setuid/gid itself (which is the recommend way to run SRNd), you\",\n \"need to modify the configuration file at {} and set setuid to an empty value.\".format(os.path.join(config_path, 'SRNd.conf')),\n \"If you want to run as root delete the data directory before you restart SRNd.\"\n )\n self.log(self.logger.WARNING, '\\n'.join(warnings))\n else:\n self.log(self.logger.CRITICAL, \"trying to chown configuration files failed: {}\".format(e))\n exit(1)\n with open(os.path.join(config_path, 'SRNd.conf'), 'w') as f:\n f.write('\\n'.join(config_head))\n f.write('\\n\\n')\n f.write('\\n'.join(config_list))\n f.write('\\n')\n\n def init_srnd_config(self, def_config, config_file=os.path.join('data', 'config', 'SRNd.conf')):\n config = self._read_srnd_config(config_file) if os.path.isfile(config_file) else dict()\n no_change = self._sanitize_srnd_config(def_config, config)\n # check setuid\n uid = None\n gid = None\n if config['setuid']:\n try:\n uid, gid = pwd.getpwnam(config['setuid'])[2:4]\n except KeyError:\n # FIXME: user can't change config file as it might not exist at this point.\n crits = (\n \"'{}' is not a valid user on this system.\".format(config['setuid']),\n \"either create {} or change setuid at '{}' into a valid username or an empty value to disable setuid\".format(config['setuid'], config_file)\n )\n self.log(self.logger.CRITICAL, '\\n'.join(crits))\n exit(1)\n elif config['use_chroot']:\n crits = (\n \"You defined use_chroot=True and set setuid to an empty value.\",\n \"This would result in chrooting without dropping privileges which defeats the purpose of chrooting completely.\"\n )\n self.log(self.logger.CRITICAL, '\\n'.join(crits))\n exit(3)\n if not no_change:\n # create human readable config - sort from position in def_config\n config_list = sorted([('='.join((key, str(value))), def_config[key][1]) for key, value in config.items()], key=lambda line_: line_[1])\n # remove positions\n config_list = [line[0] for line in config_list]\n self._write_srnd_config(config_list, config['data_dir'], uid, gid)\n # add uid and gid in config if present. No write this in config file\n if uid is not None and gid is not None:\n config['uid'] = uid\n config['gid'] = gid\n return config\n\n @staticmethod\n def _list_config_files(path):\n for target in os.listdir(path):\n if os.path.isfile(os.path.join(path, target)) and not target.startswith('.'):\n yield target\n\n def _read_hook_rules(self, config_file):\n rules = {'whitelist': set(), 'blacklist': set()}\n with open(config_file, 'r') as f:\n for line in f:\n line = line.rstrip('\\r\\n')\n if len(line) > 0 and not line.startswith('#'):\n # whitelist\n if not line.startswith('!'):\n rules['whitelist'].add(line)\n # blacklist\n elif len(line) > 1:\n line = line[1:]\n if line.startswith('*'):\n self.log(self.logger.WARNING, 'invalid blacklist rule in \"{}\": !* is not allowed. everything not whitelisted will be rejected automatically.'.format(config_file))\n else:\n rules['blacklist'].add(line)\n return rules\n\n def _load_infeeds_config(self, cfg_file=os.path.join('config', 'infeeds.conf')):\n if not os.path.isfile(cfg_file):\n with open(cfg_file, 'w') as f:\n f.write('# see docs/hooks.txt for a detailed description about the hook configuration syntax.\\n\\n')\n f.write('# All infeeds use this config\\n\\n')\n f.write('# 0 - authentication disallowed, 1 - authentication support, 2 - authentication required (WARNING! Not work with original srnd)\\n')\n f.write('#start_param auth_required=0\\n\\n')\n f.write('# authentication mode support. nntp - support standart nntp client, private key send as plaintext. srnd - best and support srnd-client (recommend)\\n')\n f.write('# example: #start_param auth_support=srnd,nntp\\n')\n f.write('#start_param auth_support=srnd\\n\\n\\n')\n f.write('# allow all groups\\n')\n f.write('*\\n')\n rules = self._read_hook_rules(cfg_file)\n w_count = len(rules['whitelist'])\n b_count = len(rules['blacklist'])\n if w_count + b_count > 0:\n output_log = list()\n output_log.append('Found {} infeeds hooks:'.format(w_count + b_count))\n if w_count > 0:\n output_log.append('whitelist')\n output_log.extend([' {}'.format(x) for x in rules['whitelist']])\n if b_count > 0:\n output_log.append('blacklist')\n output_log.extend([' {}'.format(x) for x in rules['blacklist']])\n self.log(self.logger.INFO, '\\n'.join(output_log))\n return {'rules': rules, 'config': self._infeed_config_sanitize(self._config_reader(cfg_file))}\n\n def update_hooks(self):\n self.log(self.logger.INFO, 'reading hook configuration..')\n hook_whitelist = dict()\n hook_blacklist = dict()\n for hook_type, hook_name in (('filesystem', 'filesystem'), ('outfeeds', 'outfeed'), ('plugins', 'plugin')):\n directory = os.path.join('config', 'hooks', hook_type)\n for hook in self._list_config_files(directory):\n link = os.path.join(directory, hook)\n if hook_name != 'outfeed':\n name = '{0}-{1}'.format(hook_name, hook)\n else:\n config_ = self._outfeed_config_sanitize(self._config_reader(link))\n server_ = self._extract_server_link(config_.get('server', hook), config_['ipv6'])\n if server_ is None:\n continue\n name = 'outfeed-{}-{}'.format(*server_)\n # ignore hooks for inactive plugins and outfeeds\n if (hook_name == 'outfeed' and not self.feeds.is_outfeed(name)) or (hook_name == 'plugin' and name not in self.plugins):\n continue\n # read hooks into self.hooks[group_name] = hook_name\n rules = self._read_hook_rules(link)\n # whitelist update\n for rule in rules['whitelist']:\n if rule not in hook_whitelist:\n hook_whitelist[rule] = set()\n if name not in hook_whitelist[rule]:\n hook_whitelist[rule].add(name)\n # blacklist update\n for rule in rules['blacklist']:\n if rule not in hook_blacklist:\n hook_blacklist[rule] = set()\n if name not in hook_blacklist[rule]:\n hook_blacklist[rule].add(name)\n if hook_type == 'filesystem':\n # create hook directory\n hook_dir = os.path.join('hooks', hook)\n if not os.path.exists(hook_dir):\n os.mkdir(hook_dir)\n os.chmod(hook_dir, 0o777)\n output_log = list()\n # adding hooks\n diff, diff_count = self._get_two_hooks_diff(self.hooks, hook_whitelist, self.hook_blacklist, hook_blacklist)\n if diff_count > 0:\n output_log.append('Adding {} hooks'.format(diff_count))\n output_log.extend(diff)\n output_log.append('')\n # removed hooks\n diff, diff_count = self._get_two_hooks_diff(hook_whitelist, self.hooks, hook_blacklist, self.hook_blacklist)\n if diff_count > 0:\n output_log.append('Remove {} hooks'.format(diff_count))\n output_log.extend(diff)\n output_log.append('')\n if len(output_log) > 0:\n self.log(self.logger.INFO, '\\n'.join(output_log))\n elif len(self.hook_blacklist) + len(self.hooks) == 0:\n self.log(self.logger.WARNING, 'did not find any hook')\n else:\n self.log(self.logger.INFO, 'Hooks not changes')\n # rewrite old hooks\n self.hooks = hook_whitelist\n self.hook_blacklist = hook_blacklist\n\n def _get_two_hooks_diff(self, old_whitelist, whitelist, old_blacklist, blacklist):\n diff = list()\n diff_whitelist, count_whitelist = self._get_hook_diff(old_whitelist, whitelist)\n diff_blacklist, count_blacklist = self._get_hook_diff(old_blacklist, blacklist)\n if count_whitelist > 0:\n diff.append('whitelist')\n diff.extend(diff_whitelist)\n if count_blacklist > 0:\n diff.append('blacklist')\n diff.extend(diff_blacklist)\n return diff, count_whitelist + count_blacklist\n\n @staticmethod\n def _get_hook_diff(old_hooks, new_hooks):\n diff = list()\n total = 0\n for hook in new_hooks:\n new = new_hooks[hook] - old_hooks.get(hook, set())\n total += len(new)\n if len(new) > 0:\n diff.append(' {}'.format(hook))\n diff.extend([' {} '.format(x) for x in new])\n return diff, total\n\n def update_plugins(self):\n self.log(self.logger.INFO, 'importing plugins..')\n plugins_added = 0\n plugins_removed = 0\n all_plugins = set()\n current_plugin = None\n for plugin in self._list_config_files(os.path.join('config', 'hooks', 'plugins')):\n link = os.path.join('config', 'hooks', 'plugins', plugin)\n plugin_path = os.path.join('plugins', plugin)\n if not plugin_path in sys.path:\n sys.path.append(plugin_path)\n name = 'plugin-' + plugin\n all_plugins.add(name)\n if name in self.plugins:\n continue\n args = self._config_reader(link)\n #print \"[SRNd] trying to import {0}..\".format(name)\n args['db_connector'] = self._db_manager.connect\n if 'srnd' in args:\n args['srnd'] = self\n if 'srnd_info' in args:\n args['srnd_info'] = self.get_info\n try:\n current_plugin = __import__(plugin)\n self.plugins[name] = current_plugin.main(name, self.logger, args)\n plugins_added += 1\n except Exception as e:\n self.log(self.logger.ERROR, 'error while importing %s: %s' % (name, e))\n self.log(self.logger.ERROR, traceback.format_exc())\n if name in self.plugins:\n del self.plugins[name]\n all_plugins.discard(name)\n continue\n del current_plugin\n for name in [xx for xx in self.plugins if xx not in all_plugins]:\n if self._close_plugin(name):\n del self.plugins[name]\n plugins_removed += 1\n if plugins_added > 0:\n self.log(self.logger.INFO, 'added {} plugins'.format(plugins_added))\n if plugins_removed > 0:\n self.log(self.logger.INFO, 'removed {} plugins'.format(plugins_removed))\n\n def start_plugins(self):\n to_start = [xx for xx in self.plugins if not self.plugins[xx].isAlive()]\n if len(to_start) > 0:\n self.log(self.logger.INFO, 'starting {} plugins..'.format(len(to_start)))\n for plugin in to_start:\n self.plugins[plugin].start()\n time.sleep(0.1)\n\n def _extract_server_link(self, outfeed, ipv6=False):\n \"\"\"Return host, port from host:port. return None, if wrong format\"\"\"\n outfeed = outfeed.split(':')\n # check server ip:port\n if (ipv6 and len(outfeed) < 2) or (not ipv6 and len(outfeed) > 2):\n self.log(self.logger.ERROR, 'incorrect server ip:port: {}'.format(':'.join(outfeed)))\n return None\n if len(outfeed) > 1:\n host = ':'.join(outfeed[:-1])\n try:\n port = int(outfeed[-1])\n except ValueError:\n if ipv6:\n host = ':'.join(outfeed)\n port = 119\n else:\n self.log(self.logger.ERROR, 'incorrect server ip:port: {}. If you use ipv6 address add #start_param ipv6=true to config'.format(':'.join(outfeed)))\n return None\n else:\n host = ':'.join(outfeed)\n port = 119\n return host, port\n\n def _config_reader(self, config_file):\n start_params = dict()\n with open(config_file, 'r') as f:\n for line in f:\n if line.lower().startswith('#start_param '):\n try:\n key, value = line[13:].rstrip('\\r\\n').split('=', 1)\n except ValueError as e:\n self.log(self.logger.WARNING, 'Strange config line \"{}\" in \"{}\": {}. Ignore'.format(line.rstrip('\\r\\n'), config_file, e))\n continue\n key = key.lower()\n if key in start_params:\n self.log(self.logger.WARNING, 'Found duplicate key {} in {}: Last value rewrite previous'.format(key, config_file))\n start_params[key] = value\n return start_params\n\n def _trackdb_reder(self, trackdb_file):\n duplicates = 0\n trackdb = set()\n # open track db here, read, close\n try:\n f = open(trackdb_file, 'r')\n except IOError as e:\n if e.errno != 2:\n self.log(self.logger.ERROR, 'cannot open: {}: {}'.format(trackdb_file, e.strerror))\n else:\n for line in f:\n if line.rstrip('\\n') in trackdb:\n duplicates += 1\n else:\n trackdb.add(line.rstrip('\\n'))\n f.close()\n # remove duplicates\n if duplicates > 0:\n self.log(self.logger.INFO, 'found {} duplicates in {}. Rewriting'.format(duplicates, trackdb_file))\n with open(trackdb_file, 'w') as f:\n f.write('\\n'.join(trackdb))\n f.write('\\n')\n return trackdb\n\n def update_outfeeds(self):\n self.log(self.logger.INFO, 'reading outfeeds..')\n counter_new = 0\n current_feedlist = list()\n for outfeed in self._list_config_files(os.path.join('config', 'hooks', 'outfeeds')):\n config = self._outfeed_config_sanitize(self._config_reader(os.path.join('config', 'hooks', 'outfeeds', outfeed)))\n\n # get host:port from config if present or use config name\n config['server'] = self._extract_server_link(config.get('server', outfeed), config['ipv6'])\n if config['server'] is None:\n continue\n name = 'outfeed-{}-{}'.format(*config['server'])\n current_feedlist.append(name)\n if not self.feeds.is_outfeed(name):\n if config['proxy']:\n self.log(self.logger.INFO, 'starting outfeed {} using proxy: {proxy_type} {proxy_ip}:{proxy_port}'.format(name, **config['proxy']))\n try:\n self.log(self.logger.DEBUG, 'starting outfeed: %s' % name)\n self.feeds.add_outfeed(name, config)\n self.feeds.start_outfeed(name)\n except Exception as e:\n self.log(self.logger.WARNING, 'could not start outfeed %s: %s' % (name, e))\n self.log(self.logger.WARNING, traceback.format_exc())\n else:\n counter_new += 1\n counter_removed = 0\n for name in [xx for xx in self.feeds.list_outfeed() if xx not in current_feedlist]:\n self.feeds.shutdown_outfeed(name)\n counter_removed += 1\n self.log(self.logger.INFO, 'outfeeds added: %i' % counter_new)\n self.log(self.logger.INFO, 'outfeeds removed: %i' % counter_removed)\n\n def update_hooks_outfeeds_plugins(self, signum, frame):\n self.update_outfeeds()\n self.update_plugins()\n self.start_plugins()\n self.update_hooks()\n\n @staticmethod\n def encode_big_endian(number, length):\n if number >= 256**length:\n raise OverflowError(\"%i can't be represented in %i bytes.\" % (number, length))\n data = b\"\"\n for i in range(0, length):\n data += chr(number >> (8*(length-1-i)))\n number -= (ord(data[-1]) << (8*(length -1 -i)))\n return data\n\n @staticmethod\n def decode_big_endian(data, length):\n if len(data) < length:\n raise IndexError(\"data length %i lower than given length of %i.\" % (len(data), length))\n cur_len = 0\n for i in range(0, length):\n cur_len |= ord(data[i]) << (8*(length-1-i))\n return cur_len\n\n def ctl_socket_send_data(self, fd, data):\n data = json.dumps(data)\n data = self.encode_big_endian(len(data), 4) + data\n length = os.write(fd, data)\n while length != len(data):\n length += os.write(fd, data[length:])\n\n def ctl_socket_handler_logger(self, data, fd=None):\n if data[\"data\"] == \"off\" or data[\"data\"] == \"none\":\n return self.logger.remove_target(self.ctl_socket_clients[fd][1])\n elif data[\"data\"] == \"on\":\n data[\"data\"] = 'all'\n return self.logger.add_target(self.ctl_socket_clients[fd][1], loglevel=data[\"data\"].split(' '), json_framing_4=True)\n\n def ctl_socket_handler_stats(self, data, fd=None):\n if not 'stats' in self.__dict__:\n self.stats = {\"start_up_timestamp\": self.start_up_timestamp}\n self.stats_last_update = 0\n self.stats[\"infeeds\"] = len(self.feeds.list_infeed())\n self.stats[\"outfeeds\"] = len(self.feeds.list_outfeed())\n self.stats[\"plugins\"] = len(self.plugins)\n if time.time() - self.stats_last_update > 5:\n self.stats[\"groups\"] = os.stat('groups').st_nlink - 2\n self.stats[\"articles\"] = sum(1 for x in os.listdir('articles')) - os.stat('articles').st_nlink + 2\n self.stats[\"cpu\"] = self._get_sysinfo('cpu')\n self.stats[\"ram\"] = self._get_sysinfo('ram')\n self.stats[\"disk_free\"] = self._get_sysinfo('disk_free')\n self.stats[\"disk_used\"] = self._get_sysinfo('disk_used')\n self.stats_last_update = time.time()\n return self.stats\n\n def ctl_socket_handler_status(self, data, fd=None):\n if not data[\"data\"]:\n return \"all fine\"\n elif data[\"data\"] == \"feeds\":\n return self.feeds.status()\n elif data[\"data\"] == \"plugins\":\n ret = dict()\n for name in self.plugins:\n ret[name] = {\n #\"queue\": self.plugins[name].qsize\n }\n return {\"active\": ret}\n elif data[\"data\"] == \"hooks\":\n return {\"blacklist\": self.hook_blacklist, \"whitelist\": self.hooks}\n return \"obviously all fine in %s\" % str(data[\"data\"])\n\n def get_message_list_by_group(self, group, sort_=True):\n group_dir = os.path.join('groups', group)\n file_list = [int(k) for k in os.listdir(group_dir)]\n if sort_:\n # send fresh articles first\n file_list.sort()\n\n message_list = list()\n for link in file_list:\n try:\n target = os.path.join(group_dir, str(link))\n message_id = os.path.basename(os.readlink(target))\n if os.stat(target).st_size == 0:\n self.log(self.logger.WARNING, 'empty article found in group %s with id %s pointing to %s' % (group_dir, link, message_id))\n continue\n except:\n self.log(self.logger.ERROR, 'invalid link found in group %s with id %s' % (group_dir, link))\n continue\n message_list.append(message_id)\n return message_list\n\n @staticmethod\n def _ishook_match(group_name, regexp):\n return regexp == group_name or regexp == '*' or regexp[-1] == '*' and group_name.startswith(regexp[:-1])\n\n def get_allow_hooks(self, group_name):\n targets = set()\n for white_group in self.hooks:\n if self._ishook_match(group_name, white_group):\n # hook found, extend\n targets |= self.hooks[white_group]\n if len(targets) > 0:\n # remove blacklisted elements\n for black_group in self.hook_blacklist:\n if self._ishook_match(group_name, black_group):\n targets -= self.hook_blacklist[black_group]\n return targets\n\n def _is_valid_outfeed(self, target, hook, targets):\n if not self._is_allow_sync(target, hook, targets):\n return False\n if self.feeds.is_outfeed(target):\n if self.feeds.sync_outfeed(target):\n self.log(self.logger.DEBUG, 'startup sync, adding {}'.format(target))\n return True\n else:\n self.log(self.logger.WARNING, 'unknown outfeed detected. wtf? {}'.format(target))\n return False\n\n def _is_valid_plugin(self, target, hook, targets):\n return self._is_allow_sync(target, hook, targets) and self._is_valid_any(self.plugins, target, 'plugin')\n\n def _is_valid_any(self, dict_data, target, type_):\n if target in dict_data:\n if dict_data[target].sync_on_startup:\n self.log(self.logger.DEBUG, 'startup sync, adding {}'.format(target))\n return True\n else:\n self.log(self.logger.WARNING, 'unknown {} detected. wtf? {}'.format(type_, target))\n return False\n\n @staticmethod\n def _is_allow_sync(target, hook, targets):\n if hook is not None and not target.startswith(hook):\n return False\n if targets is not None and target not in targets:\n return False\n return True\n\n def _sync_on_startup(self, hook=None, targets=None):\n # hook - plugin, outfeed. None - all\n # targets - object name. None - any\n groups = [x for x in os.listdir('groups') if os.path.isdir(os.path.join('groups', x))]\n synclist = dict()\n ctl_synclist = dict()\n for group in groups:\n self.log(self.logger.DEBUG, 'startup sync, checking {}..'.format(group))\n current_sync_targets = set()\n for sync_target in self.get_allow_hooks(group):\n if sync_target.startswith('outfeed-'):\n if self._is_valid_outfeed(sync_target, hook, targets):\n current_sync_targets.add(sync_target)\n elif sync_target.startswith('plugin-'):\n if self._is_valid_plugin(sync_target, hook, targets):\n current_sync_targets.add(sync_target)\n elif sync_target.startswith('filesystem-'):\n pass\n else:\n self.log(self.logger.WARNING, 'unknown hook detected. wtf? {}'.format(sync_target))\n if len(current_sync_targets) > 0:\n if group in self.ctl_groups:\n ctl_synclist[group] = {'targets': current_sync_targets, 'file_list': self.get_message_list_by_group(group, False)}\n else:\n synclist[group] = {'targets': current_sync_targets, 'file_list': self.get_message_list_by_group(group)}\n\n self._send_synclist(synclist)\n self._send_synclist(ctl_synclist, True)\n\n self.log(self.logger.DEBUG, 'startup_sync done. hopefully.')\n self.feed_db.clear()\n\n def _send_synclist(self, synclist, ctl=False):\n while len(synclist) > 0:\n empty_sync_group = list()\n for group in synclist:\n if len(synclist[group]['file_list']) == 0:\n empty_sync_group.append(group)\n else:\n for message_id in synclist[group]['file_list'][:500]:\n for current_hook in synclist[group]['targets']:\n if current_hook.startswith('outfeed-'):\n if message_id not in self.feed_db.get(current_hook, ''):\n self.feeds.add_article(current_hook, message_id, ctl)\n elif current_hook.startswith('plugin-'):\n self.plugins[current_hook].add_article(message_id)\n del synclist[group]['file_list'][:500]\n for group in empty_sync_group:\n del synclist[group]\n\n def _load_outfeed_db(self, targets=None):\n for target in self.feeds.list_outfeed():\n if self.feeds.sync_outfeed(target) and targets is None or target in targets:\n self.feed_db[target] = self._trackdb_reder('{0}.trackdb'.format(target))\n\n def internal_ctl(self, args):\n self.log(self.logger.DEBUG, 'Got control request {}'.format(args))\n updates = {'hooks': self.update_hooks, 'outfeed': self.update_outfeeds, 'plugin': self.update_plugins}\n if args['action'] == 'update' and args.get('hook') in updates:\n # reload any hooks\n updates[args['hook']]()\n return True\n elif args['action'] == 'start' and args.get('hook') == 'plugin':\n # start not running plugins\n self.start_plugins()\n return True\n # resync\n elif args['action'] == 'sync' and args.get('hook') in ('plugin', 'outfeed', None):\n # reload trackdb\n if args.get('hook') != 'plugin':\n self._load_outfeed_db(targets=args.get('targets'))\n self._sync_on_startup(hook=args.get('hook'), targets=args.get('targets'))\n return True\n # shutdown\n elif args['action'] == 'die' and args.get('hook') in ('infeed', 'outfeed', 'plugin'):\n status = True\n if args['hook'] == 'infeed':\n for feed_ in [xx for xx in self.feeds.list_infeed() if args.get('targets') is None or xx in args.get('targets')]:\n status &= self.feeds.shutdown_infeed(feed_)\n elif args['hook'] == 'outfeed':\n for feed_ in [xx for xx in self.feeds.list_outfeed() if args.get('targets') is None or xx in args.get('targets')]:\n status &= self.feeds.shutdown_outfeed(feed_)\n elif args.get('hook') == 'plugin':\n for plugin in [xx for xx in self.plugins]:\n if plugin in args.get('targets', plugin):\n if self._close_plugin(plugin):\n del self.plugins[plugin]\n status &= True\n return status\n self.log(self.logger.WARNING, 'Invalid control request: {}'.format(args))\n return False\n\n def run(self):\n self.running = True\n self.feed_db = dict()\n self.update_outfeeds()\n self._load_outfeed_db()\n self.start_plugins()\n self.update_hooks()\n\n self._sync_on_startup()\n\n self.dropper.start()\n\n # setup admin control socket\n # FIXME: add path of linux socket to SRNd.conf\n s_addr = 'control.socket'\n try:\n os.unlink(s_addr)\n except OSError:\n if os.path.exists(s_addr):\n raise\n ctl_socket_server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n ctl_socket_server.bind(s_addr)\n ctl_socket_server.listen(10)\n ctl_socket_server.setblocking(0)\n os.chmod(s_addr, 0o660)\n\n poller = select.poll()\n poller.register(self.socket.fileno(), select.POLLIN)\n poller.register(ctl_socket_server.fileno(), select.POLLIN)\n self.poller = poller\n\n self.ctl_socket_clients = dict()\n\n self.start_up_timestamp = int(time.time())\n while self.running:\n try:\n result = poller.poll(-1)\n except socket.error as e:\n if e.errno == 22:\n # [Errno 22] Invalid argument\n break\n elif e.errno == 4:\n # system call interrupted\n continue\n else:\n raise e\n for fd, mask in result:\n if fd == self.socket.fileno():\n try:\n con = self.socket.accept()\n name = 'infeed-{0}-{1}'.format(con[1][0], con[1][1])\n if not self.feeds.is_infeed(name):\n self.feeds.add_infeed(name=name, connection=con, db_connector=self._db_manager.connect)\n self.feeds.start_infeed(name)\n else:\n self.log(self.logger.WARNING, 'got connection from %s but its still in feeds. wtf?' % name)\n except socket.error as e:\n if e.errno == 22:\n # [Errno 22] Invalid argument\n break\n elif e.errno == 4:\n # system call interrupted\n continue\n else:\n raise e\n elif fd == ctl_socket_server.fileno():\n con, addr = ctl_socket_server.accept()\n con.setblocking(0)\n poller.register(con.fileno(), select.POLLIN)\n self.ctl_socket_clients[con.fileno()] = (con, os.fdopen(con.fileno(), 'w', 1))\n else:\n try:\n try: data = os.read(fd, 4)\n except: data = ''\n if len(data) < 4:\n self.terminate_ctl_socket_connection(fd)\n continue\n length = self.decode_big_endian(data, 4)\n data = os.read(fd, length)\n if len(data) != length:\n self.terminate_ctl_socket_connection(fd)\n continue\n try: data = json.loads(data)\n except Exception as e:\n self.log(self.logger.WARNING, \"failed to decode json data: %s\" % e)\n continue\n self.log(self.logger.DEBUG, \"got something to read from control socket at fd %i: %s\" % (fd, data))\n if not \"command\" in data:\n self.ctl_socket_send_data(fd, {\"type\": \"response\", \"status\": \"failed\", \"data\": \"no command given\"})\n continue\n if not \"data\" in data:\n data[\"data\"] = ''\n if data[\"command\"] in self.ctl_socket_handlers:\n try: self.ctl_socket_send_data(fd, {\"type\": \"response\", \"status\": \"success\", \"command\": data[\"command\"], \"args\": data[\"data\"], \"data\": self.ctl_socket_handlers[data[\"command\"]](data, fd)})\n except Exception as e:\n try:\n self.ctl_socket_send_data(fd, {\"type\": \"response\", \"status\": \"failed\", \"command\": data[\"command\"], \"args\": data[\"data\"], \"data\": \"internal SRNd handler returned exception: %s\" % e})\n except Exception as e1:\n self.log(self.logger.INFO, \"can't send exception message to control socket connection using fd %i: %s, original exception was %s\" % (fd, e1, e))\n self.terminate_ctl_socket_connection(fd)\n continue\n self.ctl_socket_send_data(fd, {\"type\": \"response\", \"status\": \"failed\", \"command\": data[\"command\"], \"args\": data[\"data\"], \"data\": \"no handler for given command '%s'\" % data[\"command\"]})\n except Exception as e:\n self.log(self.logger.INFO, \"unhandled exception while processing control socket request using fd %i: %s\" % (fd, e))\n self.terminate_ctl_socket_connection(fd)\n\n ctl_socket_server.shutdown(socket.SHUT_RDWR)\n ctl_socket_server.close()\n self.socket.close()\n\n def terminate_ctl_socket_connection(self, fd):\n self.log(self.logger.INFO, \"connection at control socket fd %i closed\" % fd)\n try: self.ctl_socket_clients[fd][0].shutdown(socket.SHUT_RDWR)\n except: pass\n try: self.ctl_socket_clients[fd][1].close()\n except Exception as e: print(\"close of fdopened file failed: %s\" % e)\n try: self.ctl_socket_clients[fd][0].close()\n except Exception as e: print(\"close of socket failed: %s\" % e)\n self.poller.unregister(fd)\n try: self.logger.remove_target(self.ctl_socket_clients[fd][1])\n except: pass\n del self.ctl_socket_clients[fd]\n\n def relay_dropper_handler(self, signum, frame):\n #TODO: remove, this is not needed anymore at all?\n self.dropper.handler_progress_incoming(signum, frame)\n\n def _infeed_config_sanitize(self, config):\n # 0 - disallow 1 - allow 2 - required\n config['srndgzip'] = config.get('srndgzip', 'false').lower() in ('true', 'enable', 'on')\n try:\n auth_required = int(config.get('auth_required', 0))\n except ValueError:\n auth_required = None\n if auth_required is None or 2 < auth_required < 0:\n self.log(self.logger.WARNING, 'abnormal value auth_required={}. Set 0 - diwallow'.format(auth_required))\n auth_required = 0\n config['auth_required'] = auth_required\n config['auth_support'] = config.get('auth_support', 'srnd').lower().split(',')\n config['pretty_name'] = 'pretty_name' in config and config['pretty_name'].lower() in ('true', 'yes', '1')\n # add SRNd instance_name from SRNd config\n config['instance_name'] = self.config['instance_name']\n # Parse support_ items\n support = set()\n for key in [xx for xx in config if xx.startswith('support_')]:\n support.add('{} {}'.format(key.upper()[8:], config.pop(key)))\n config['support'] = tuple(support)\n return config\n\n def _outfeed_config_sanitize(self, config):\n config['infinity_stream'] = config.get('infinity_stream', 'false').lower() in ('true', 'on', 'yes', '1')\n config['srndauth_key'] = config.get('srndauth_key')\n if config['srndauth_key'] is not None and len(config['srndauth_key']) != 64:\n self.log(self.logger.WARNING, 'len srndauth_key != 64. Set None')\n config['srndauth_key'] = None\n if 'multiconn' in config:\n multiconn = config['multiconn']\n try:\n config['multiconn'] = int(config['multiconn'])\n except ValueError:\n config['multiconn'] = None\n else:\n if 10 < config['multiconn'] < 2:\n config['multiconn'] = None\n if config['multiconn'] is None:\n self.log(self.logger.WARNING, 'abnormal value multiconn=\"{}\". Set 1 - only one outfeed'.format(multiconn))\n config['multiconn'] = 1\n config['ipv6'] = config.get('ipv6', 'false').lower() in ('true', 'yes', '1')\n # check proxy\n proxy = {'proxy_type': None, 'proxy_ip': None, 'proxy_port': None}\n for proxy_key in proxy:\n if proxy_key in config:\n proxy[proxy_key] = config.pop(proxy_key).lower()\n if proxy['proxy_type'] is not None and proxy['proxy_ip'] is not None:\n try:\n proxy['proxy_port'] = int(proxy['proxy_port'])\n except ValueError:\n proxy = None\n config['proxy'] = proxy\n\n config['sync_on_startup'] = 'sync_on_startup' in config and config['sync_on_startup'].lower() in ('true', 'yes', '1')\n try:\n config['debug'] = int(config.get('debug', self.config['srnd_debuglevel']))\n except ValueError:\n config['debug'] = self.config['srnd_debuglevel']\n else:\n if 9 < config['debug'] < 0:\n config['debug'] = self.config['srnd_debuglevel']\n return config\n\n def watching(self):\n return self.dropper.watching\n\n def _close_plugin(self, name):\n wait_count = 50\n wait_time = 0.4\n c_count = 0\n self.plugins[name].shutdown()\n while self.plugins[name].isAlive() and c_count < wait_count:\n c_count += 1\n time.sleep(wait_time)\n if self.plugins[name].isAlive():\n self.log(self.logger. ERROR, '{} does not respond to shutdown in {} second'.format(name, int(c_count * wait_time)))\n return False\n else:\n return True\n\n def shutdown(self):\n self.dropper.running = False\n self.running = False\n self.log(self.logger.INFO, 'closing listener..')\n self.socket.shutdown(socket.SHUT_RDWR)\n self.log(self.logger.INFO, 'closing plugins..')\n for plugin in self.plugins:\n self._close_plugin(plugin)\n self.log(self.logger.INFO, 'closing feeds..')\n self.feeds.shutdown_all()\n","sub_path":"SRNd.py","file_name":"SRNd.py","file_ext":"py","file_size_in_byte":49980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"185191087","text":"import operator\n\nprint(\"Enter the name of the file for which you want the details of script (eg - despicable.txt)\");\n\nwhile True:\n\ttry:\n\t\tinputfile = input();\n\t\tmoviefile = open(inputfile,'r');\n\t\tbreak\n\texcept FileNotFoundError :\n\t\tprint (\"This file is not present in the directory. Please try again\")\n\na = [\"Mr.\",\"Mrs.\"]\n\ncount = [0,0,0,0,0,0] #action, comedy, crime, mystery,romance,horror\n\ngenre = []\ngenre.append([\" war\",\"fight\",\"struggle\",\"attack\",\"kill\",\"conflict\",\"rival\",\"clash\",\"quarrel\",\"riot\",\"dispute\",\"operation\",\"battle\",\"hunt\",\"revenge\",\"violence\",\"conflict\",\"breach\",\"hunt\",\"run\",\"dispute\" ,\"fear\" ,\"gun\", \"weapon\"])\n\ngenre.append([\"laugh\",\"fun\",\"comic\",\"chuckle\",\"giggle\",\"gag\",\"pun\",\"mock\",\"spoof\",\"cheer\",\"nonsense\",\"smile\",\"smirk\",\"prank\",\"amusing\",\"enjoy\",\"gossip\",\"joke\",\"fool\",\"tease\",\"amuse\",\"hoopla\",\"charm\",\"celebrate\",\"party\",\"happy\",\"kidding\",\"mimic\",\"witty\"])\n\ngenre.append([\"murder\",\"drugs\",\"prison\",\"shot\",\"dead\",'gang','scandal','corruption','felony','breach','outrage','legal','conduct','prison','police','court','justice','weapon','gun','law'])\n\ngenre.append([\"spy\",\"detective\",\"undercover\",\"dispute\",\"confusion\",\"bluff\",\"riddle\",\"loot\",\"risk\",\"oracle\",\"hunt\",\"search\",\"operation\",\"secret\",\"agent\",\"informer\",\"investigator\",\"rival\",\"invade\",\"trait shot\",\"murder\",\"tension\",\"shock\",\"fear\"])\n\ngenre.append([\"love\",\"romance\",\"kiss\",\"flower\",\"sky\",\"faith\",\"believe\",\"smile\",\"cry\",\"emotion\",\"seduce\",\"sex\",\"faith\",\"believe\",\"smile\",\"cry\",\"emotion\",\"lust\",\"heart\",\"eyes\",\n\"beauty\",\"trust\",\"jealous\",\"crush\",\"wife\"])\n\ngenre.append([\"terror\",\"panic\",\"hatred\",\"fear\",\"dead\",\"evil\",\"curse\",\"strain\",\"stress\",\"tension\",\"scare\",\"wick\",\"brutality\",\"creepy\",\"insane\",\"ugly\",\"psycho\",\"shock\",\"dark\",\"revenge\",\"pain\",\"illwill\",\"venom\",\"enmity\",\"prejudice\",\"monster\",\"freak\",\"beast\",\"brute\",\"savage\",\"demon\",\"torment\",\"torture\"])\n\n\nfor line in moviefile:\n\tsplited = line.split();\n\tfor i in range(len(splited)):\n\t\tsplited[i] = splited[i].lower()\n\tfor i in range(6):\n\t\tfor to_find in genre[i]:\n\t\t\tfor word in splited:\n\t\t\t\tif(to_find in word):\n\t\t\t\t#\tprint(to_find,',');\t\n\t\t\t\t\tcount[i] = count[i]+1;\n\ngenre = []\n\nfor i in range(len(count)) :\n\tgenre.append((count[i], i))\n\ngenre.sort(key=operator.itemgetter(0))\ngenre.reverse()\n\nfirst = genre[0][1]\nsecond = genre[1][1]\n\ngenrelist = ['Action', 'Comedy', 'Crime/Drama', 'Mystery','Romance','Horror']\n\nprint (\"The genre of this movie are: \" + genrelist[first] + \" & \" + genrelist[second])\n\n\n\n\n\n\n\n","sub_path":"lab08/g18_movietype.py","file_name":"g18_movietype.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"109933133","text":"import os\nimport sys\nfrom unittest import mock\n\nimport pytest\n\nfrom cognite.cli.cli import CogniteCLI\nfrom cognite.cli.cli_models import CogniteModelsCLI\n\n\nclass TestCogniteCLI:\n @mock.patch(\"cognite.cli.cli.getattr\")\n def test_use_service(self, getattr_mock):\n sys.argv = [\"cognite\", \"models\"]\n CogniteCLI()\n assert 1 == getattr_mock.call_count\n\n @pytest.mark.noautofixt\n @mock.patch(\"cognite.cli.cli.getattr\")\n def test_no_env_vars_set(self, getattr_mock):\n sys.argv = [\"cognite\", \"models\"]\n CogniteCLI()\n assert 0 == getattr_mock.call_count\n\n @mock.patch(\"cognite.cli.cli.getattr\")\n def test_unrecognized_service(self, getattr_mock):\n sys.argv = [\"cognite\", \"blopi\"]\n CogniteCLI()\n assert 0 == getattr_mock.call_count\n\n @mock.patch(\"cognite.cli.cli.CogniteModelsCLI\")\n def test_models_service(self, ml_cli_mock):\n sys.argv = [\"cognite\", \"models\", \"get\"]\n ml_cli_instance_mock = mock.MagicMock(spec=CogniteModelsCLI)\n ml_cli_mock.return_value = ml_cli_instance_mock\n CogniteCLI()\n assert 1 == ml_cli_instance_mock.get.call_count\n","sub_path":"tests/cli/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"267599812","text":"# Using the given variables `base` and `digits`, write a dictionary comprehension\n# that maps each integer between `0` and `999` to the list of three digits \n# that represents that integer in base 10. That is, the value should be:\n#\n# {0: [0, 0, 0], 1: [0, 0, 1], 2: [0, 0, 2], 3: [0, 0, 3], ...,\n# 10: [0, 1, 0], 11: [0, 1, 1], 12: [0, 1, 2], ...,\n# 999: [9, 9, 9]}\n#\n# Your expression should work for any base. For example, \n# if you instead assign 2 to base and assign {0,1} to digits, \n# the value should be:\n#\n# {0: [0, 0, 0], 1: [0, 0, 1], 2: [0, 1, 0], 3: [0, 1, 1],\n# ..., 7: [1, 1, 1]}\n\nbase = 10\ndigits = set(range(base))\n\nalphabet = range(2)\nbase = 2\nprint(dict((x*base**2+y*base+z,(x,y,z)) for x in alphabet \n for y in alphabet \n for z in alphabet ))\n\n# another way\n\n# alphabet = range(10)\n# base = 10\n# dict((x*base**2+y*base+z,(x,y,z)) for x in alphabet \n# for y in alphabet \n# for z in alphabet )\n","sub_path":"06_advanced-python-concepts/06_08_based_dictcomp.py","file_name":"06_08_based_dictcomp.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"281702102","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import datetime\n\nimport mlflow\nimport pandas as pd\n\nfrom models.grid_search.grid_search import GridSearch\nfrom models.implemented_models import IMPLEMENTED_MODELS\nfrom models.scorers.scorers import SCORERS\nfrom trackers.mlflow_utils import (\n mlflow_log_artefact, mlflow_log_param_and_score, reset_mlflow_run, set_mlfow_experiment)\nfrom utils.config_utils import get_model_args, load_config\nfrom utils.utils import read_data\n\nNOW = datetime.now().strftime('%Y-%m-%d')\n\n\nclass AutoForecast:\n def __init__(self, configuration=None):\n self.configuration = self.__get_configuration(configuration)\n self.__data = self.__get_data()\n self.__models = self.__init_dict_models()\n self.__dict_grid_search = self.__init_dict_grid_search()\n self.__scores = dict()\n\n @staticmethod\n def __get_configuration(configuration=None):\n if configuration is not None:\n if not isinstance(configuration, dict):\n configuration = dict(configuration)\n else:\n configuration = load_config()\n\n return configuration\n\n def __init_dict_models(self):\n target_col = self.configuration['target_col']\n time_col = self.configuration['time_col']\n horizon = self.configuration['horizon']\n self.__check_implemented_models()\n\n dict_models = dict()\n for model in self.configuration['models']:\n model_instance = self.__get_model_instance(model, target_col, time_col, horizon)\n dict_models[model] = model_instance\n\n return dict_models\n\n def __init_dict_grid_search(self):\n dict_grid_search = dict()\n for model in self.configuration['models']:\n scorer = self.__get_scorer()\n param_grid = get_model_args(self.configuration, model)\n\n dict_grid_search[model] = GridSearch(self.__models[model], scorer, param_grid)\n\n return dict_grid_search\n\n def __get_data(self):\n def load(key_data):\n data_ = self.configuration.get(key_data)\n if data_ is None:\n raise KeyError(\"Missing arg '{}'\".format(key_data))\n if isinstance(data_, dict):\n df_data = read_data(data_)\n elif isinstance(data_, pd.DataFrame):\n df_data = data_.copy()\n return df_data\n\n dict_data = {\n 'train_data': load('train_data'),\n 'test_data': load('test_data')\n }\n\n return dict_data\n\n def __check_implemented_models(self):\n not_implemented_model = [model for model in self.configuration['models']\n if model not in IMPLEMENTED_MODELS]\n if not_implemented_model:\n raise ValueError(\"Those models are not implemented yet: {}.\\n\"\n \"Please use one of the following: {}\".format(not_implemented_model,\n list(IMPLEMENTED_MODELS.keys())))\n\n def __get_model_instance(self, model, target_col, time_col=None, horizon=None):\n model_name = self.configuration['models'][model]['name']\n model_instance = IMPLEMENTED_MODELS[model]['constructor']\n return model_instance(model_name=model_name, target_col=target_col, time_col=time_col, horizon=int(horizon))\n\n def __get_scorer(self):\n scorer = self.configuration.get('metric')\n\n if scorer is None:\n raise ValueError(\"'metric' is missing in your config\")\n\n if scorer not in SCORERS:\n raise ValueError(\"{} metric is not implemented yet.\\n\"\n \"Please use one of the following: {}\".format(scorer, list(SCORERS.keys())))\n return scorer\n\n def run(self):\n experiment_name = '_'.join(['auto_forecast', str(len(self.__models)), 'models', NOW])\n experiment_id = set_mlfow_experiment(experiment_name=experiment_name)\n reset_mlflow_run()\n\n for model in self.configuration['models']:\n run_name = 'auto_forecast_' + model.upper()\n with mlflow.start_run(run_name=run_name, experiment_id=experiment_id):\n gs_model = self.__dict_grid_search[model]\n model_trained, _, all_score, best_hyper_params = gs_model.search(self.__data['train_data'],\n self.__data['test_data'],\n refit=True)\n self.__models[model] = model_trained\n self.__scores[model] = all_score\n\n mlflow_log_param_and_score(model_trained, best_hyper_params, all_score)\n mlflow_log_artefact(model=model_trained,\n df_train=self.__data['train_data'],\n df_test=self.__data['test_data'])\n\n return self\n\n def get_best_run(self):\n scorer = self.configuration['metric']\n func_min_max = min if scorer != 'r2' else max\n dict_on_scorer = {model: self.__scores[model][scorer] for model in self.__models}\n best_model = func_min_max(dict_on_scorer, key=dict_on_scorer.get)\n return best_model, self.__models[best_model]\n\n def get_models(self):\n return self.__models\n\n def get_grids(self):\n return self.__dict_grid_search\n\n def get_scores(self):\n return self.__scores\n\n def get_data(self):\n return self.__data\n","sub_path":"auto_forecast/auto_forecast.py","file_name":"auto_forecast.py","file_ext":"py","file_size_in_byte":5522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"560093367","text":"import uuid\nfrom Constracts.IMqttTypeCmdHandler import IMqttTypeCmdHandler\nfrom Constracts import ITransport\nfrom Database.Db import Db\nimport logging\nimport json\nimport Constants.Constant as Const\n\n\nclass CreateGroupHandler(IMqttTypeCmdHandler):\n def __init__(self, log: logging.Logger, mqtt: ITransport):\n super().__init__(log, mqtt)\n\n def handler(self, data):\n mqttReceiveCommandResponse = {\n \"RQI\": data[\"RQI\"]\n }\n\n self.mqtt.send(Const.MQTT_CLOUD_TO_DEVICE_RESPONSE_TOPIC, json.dumps(mqttReceiveCommandResponse))\n\n db = Db()\n groupId = data.get(\"GroupID\")\n devices = data.get(\"Device\", [])\n\n rel = db.Services.GroupService.FindGroupByCondition(\n db.Table.GroupTable.c.GroupId == groupId\n )\n group = rel.fetchone()\n\n if group is None:\n db.Services.GroupService.InsertGroup({\"GroupId\": groupId})\n\n group_device_mapping_dict_list = []\n for device in devices:\n group_device_mapping = {\n \"GroupId\": groupId,\n \"DeviceAddress\": device\n }\n group_device_mapping_dict_list.append(group_device_mapping)\n db.Services.GroupDeviceMappingService.InsertManyGroupDeviceMapping(group_device_mapping_dict_list)\n\n r = {\n \"devices_success\": devices,\n \"devices_failure\": []\n }\n self.__cmd_res(groupId, r)\n\n def __cmd_res(self, group: int, rel: dict):\n res = {\n \"RQI\": str(uuid.uuid4()),\n \"TYPCMD\": \"CreateGroupRsp\",\n \"GroupID\": group,\n \"Devices\": []\n }\n for d in rel.get(\"devices_success\", []):\n device = {\n \"Device\": d,\n \"Success\": True\n }\n res[\"Devices\"].append(device)\n for d in rel.get(\"devices_failure\", []):\n device = {\n \"Device\": d,\n \"Success\": False\n }\n res[\"Devices\"].append(device)\n self.globalVariable.mqtt_need_response_dict[res[\"RQI\"]] = res\n self.mqtt.send(Const.MQTT_DEVICE_TO_CLOUD_REQUEST_TOPIC, json.dumps(res))\n\n","sub_path":"Handler/MqttTypCmdHandlers/CreateGroupHandler.py","file_name":"CreateGroupHandler.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"550000096","text":"# -*- coding: utf-8 -*-\n\nfrom Competence import *\nfrom Statut import *\nfrom random import randint\n\nclass CompetenceStatut(Competence):\n def __init__(self, nom, cout, description, groupe, tauxReussite, statut, forEnnemi):\n Competence.__init__(self, nom, cout, description, groupe, tauxReussite)\n self.__statut = statut\n self.__forEnnemi = forEnnemi #est ce une competence à destination des ennemies\n self.__teamConcerned = 0\n\n\n def activerCompetence(self,combattant, teamAllie, teamEnnemi, isIA):\n if self.__forEnnemi == False: # on buff ou debuff quelle team?\n self.__teamConcerned = teamAllie\n else:\n self.__teamConcerned = teamEnnemi\n if (self.getGroupe() == 0):\n if(isIA == False):\n print(\"qui sera affecter? (utiliser les z et q pour choisir et entrée pour selectionner)\")\n rep = \"0x00\"\n i = 0\n maxRange = len(self.__teamConcerned)\n if(isIA):\n i = randint(0,maxRange-1)\n else:\n while rep != \"0xd\": # différent de entrée\n print(self.__teamConcerned[i].getNom())\n rep = hex(\n ord(self.getch())) # on récupère la touche tapé par l'utilisateur (pas besoin de faire entrée)\n if (rep == \"0x7a\"): # z\n if (i < maxRange - 1):\n i = i + 1\n else:\n i = 0\n if (rep == \"0x73\"): # s\n if (i > 0):\n i = i - 1\n else:\n i = maxRange - 1\n rand = random.randint(0, 100) # le sort echoue?\n if rand > self.getTauxReussite():\n print(\"le sort echoue...\")\n else:\n self.__teamConcerned[i].ajouterStatut(self.__statut)\n print(self.__teamConcerned[i].getNom() + \" est maintenant \" + self.__statut.getNom() + \"!\")\n else: # attaque de groupe\n rand = random.randint(0, 100) # le sort echoue?\n if rand > self.getTauxReussite():\n print(\"le sort echoue...\")\n else:\n for c in self.__teamConcerned:\n c.ajouterStatut(self.__statut)\n print(c.getNom() + \" est maintenant \" + self.__statut.getNom()+\"!\")\n\"\"\"\na = Personnage('hero1',50,30,0,0,0,0,0,0,0,0,0,0)\nb = Personnage('hero2',50,30,0,0,0,0,0,0,0,0,0,0)\nc = Personnage('hero3',0,0,0,0,0,0,0,0,0,0,0,0)\nf = Combattant(a,0)\nh = Combattant(b,0)\ni = Combattant(c,0)\n\n\ntAlli = Team()\ntEnn = Team()\ntAlli.ajouterPersonnage(f)\ntAlli.ajouterPersonnage(h)\ntAlli.ajouterPersonnage(i)\ntEnn.ajouterPersonnage(f)\ntEnn.ajouterPersonnage(h)\ntEnn.ajouterPersonnage(i)\n\npoison = Empoisonne(\"poison\", h, 3)\t\nc1 = CompetenceStatut(\"jet de poison\", 3, \"inflige poison\", 0, 75, poison, 1)\nc2 = CompetenceStatut(\"deluge de poison\", 3, \"inflige poison\", 1, 75, poison, 1)\nc1.activerCompetence(h, tAlli, tEnn)\n#c2.activerCompetence(b, tAlli, tEnn)\n#poison.activerStatut(h)\n#poison.activerStatut(h)\nh.ajouterStatut(poison)\nh.activerStatut()\nh.activerStatut()\nprint(str(h.getPV()))\n\"\"\"\n","sub_path":"Code python/CompetenceStatut.py","file_name":"CompetenceStatut.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"117858142","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # This notebook computes the Electromagnetic form factors using General Frame\n\n# In[ ]:\n\n\nimport os\nimport sys\nimport argparse\nimport numpy as np\nimport subprocess\nimport h5py\nimport timeit\nimport analysis_utils as au\nfrom scipy.optimize import curve_fit\nimport pickle as pk\nimport CythonModules as CM\nfrom progressbar import ProgressBar, Percentage,Bar, Timer\nimport dill\n\n\n# In[ ]:\n\n\n## Useful macros\nI=complex(0.,1.)\nsqrt=np.sqrt\nlog=np.log\nmatr=np.matrix\nfrom math import pi as PI\n\n\n# # Parameters needed \n\n# In[ ]:\n\n\npar={}\npath='/cyclamen/home/khadjiyiannakou/project/cB2.072.64_Nf211/disconnected/pickles/'\npar['listConfs'] = path + 'list_confs_750.txt'\npar['picklePath'] = path + '/EM_strange_D8/'\npar['ZV'] = 0.727713\npar['L'] = 64\npar['T'] = 128\npar['binsize'] = 5\npar['fitMassLow'] = 13#19\npar['fitMassHgh'] = 20#35\npar['latticeSpacing'] = 0.0810#0.08014\npar['maxMomSq_q'] = 64\npar['maxMomSq_pp'] = 1\npar['maxMomSq_p'] = 81\npar['outputPath'] = path + '/EM_strange_D8_results/'\npar['selectQ2'] = -1\npar['tsink'] = 10\npar['a_inverse_GeV'] = 0.197/par['latticeSpacing'] #0.1973/par['latticeSpacing']\n\nfitThpLow = {'6': 2,'8': 2,'10':2,'12':3,'14':4,'16':5,'18':6,'20':7,'22':8}\nfitThpHgh = {'6': 4,'8': 6,'10':8,'12':9,'14':10,'16':11,'18':12,'20':13,'22':14}\n\n\n# # Get list of Confs \n\n# In[ ]:\n\n\n# read configurations list\nlenConf=au.file_len(par['listConfs'])\nwith open(par['listConfs'],'r') as fp:\n listConfs = list(map(lambda x: x.strip(),fp.readlines()))\nif len(set(listConfs)) != lenConf:\n sys.stderr.write('Error there are duplicate confs in the list')\n sys.exit(-1)\nif lenConf % par['binsize'] != 0:\n sys.stderr.write('Error number of configurations is not divisible with the binsize: Manually discard confs to make it')\n sys.exit(-1)\nNbins=int(lenConf/par['binsize'])\n\n\n# In[ ]:\n\n\nlistMom_p = CM.momComb(par['maxMomSq_p'])\nlistMom_pp = CM.momComb(par['maxMomSq_pp'])\nlistMom_q = CM.momComb(par['maxMomSq_q'])\nlistMom_q=(np.array(listMom_q)*(-1)).tolist() # If disconnected a flip of sign in the insertion Fourier might be needed\n\n\n# # Check how many Q^2 combinations we expect\n\n# In[ ]:\n\n\nlista=[]\nfor imom_pp,mom_pp in enumerate(listMom_pp):\n for imom_q,mom_q in enumerate(listMom_q):\n mom_p=list(np.array(mom_pp) - np.array(mom_q))\n lista.append( ((np.array(mom_pp)**2).sum(), (np.array(mom_q)**2).sum(), (np.array(mom_p)**2).sum()) )\nslista=list(set(lista))\n\n\nfor i,mc in enumerate(slista):\n pp2,q2,p2=mc\n for j in range(i+1,len(slista)+1):\n pp2_,q2_,p2_=slista[j%len(slista)]\n if q2_ == 0 and pp2_ != 0 and p2_ != 0: # prohibits boosted frame to contribute to zero Q^2\n del slista[j%len(slista)]\n if pp2 == p2_ and p2 == pp2_ and q2 == q2_:\n del slista[j%len(slista)]\nprint('The number of independed Q^2 we expect is %d' % len(slista))\n\n\n# In[ ]:\n\n\nprint(len(slista))\n\n\n# # Read two point functions from pickles\n\n# In[ ]:\n\n\ntwopRaw=pk.load(open(par['picklePath'] + '/ts%d/' % par['tsink'] + 'twop.pckl','rb'))\n\n\n# # Process two-point functions\n\n# In[ ]:\n\n\n# create a dictionary for momenta square\nmomListX=[ [int(p1)**2+int(p2)**2+int(p3)**2,p1,p2,p3] for p1,p2,p3 in listMom_p]\nmomListSq = sorted(list(set([x[0] for x in momListX])))\ndel momListX\n\n# average over two point functions with the same momentum square\ntwopRawSq={}\nfor p2 in momListSq:\n twopTmp=[]\n for conf in range(lenConf):\n ltemp=[]\n for imom,mom in enumerate(listMom_p):\n if (mom[0]**2 + mom[1]**2 + mom[2]**2) == p2:\n ltemp.append(twopRaw[conf,imom,:])\n nmom=len(ltemp)\n ltemp=(np.array(ltemp).real).reshape(nmom,par['T'])\n ltemp=np.average(ltemp,axis=0)\n twopTmp.append(ltemp)\n twopRawSq[str(p2)] = twopTmp\n\ndel twopTmp\ndel ltemp\n\n# binning over the two point functions\ntwopBinning={}\ntwopBmean={}\ntwopErr={}\nfor p2,listBins in twopRawSq.items():\n twopBinning[p2]=au.binningFast(listBins,par['binsize'])\n twopBmean[p2]=np.average(np.array(twopBinning[p2]),axis=0)\n twopErr[p2]= sqrt(Nbins-1) * np.std(np.array(twopBinning[p2]),axis=0)\n\n\n# # Computes effective mass\n\n# In[ ]:\n\n\n# effective mass binning\nmassEffBinning={}\nfor p2,listTwop in twopBinning.items():\n massEffBinning[p2]=au.effMass(listTwop)\n\n# mean value effective mass\nmeanEffMass={}\nfor p2 in massEffBinning.keys():\n meanEffMass[p2] = np.average(np.array(massEffBinning[p2]),axis=0)\n\n# error of the effective mass\nerrEffMass={}\nfor p2,listArr in massEffBinning.items():\n errEffMass[p2] = sqrt(Nbins-1) * np.std(np.array(listArr),axis=0)\n\n# fit to extract the mass\nmassBin=[]\nlistChi2=[]\nfor Arr in massEffBinning['0']:\n Lw=par['fitMassLow']\n Hg=par['fitMassHgh']\n popt,chi2_dof = au.simpleConstantFit(np.arange(Lw, Hg+1), Arr[Lw:Hg+1], errEffMass['0'][Lw:Hg+1])\n massBin.append(popt)\n listChi2.append(chi2_dof)\n\n\n# # Compute Energy from continuum dispersion relation\n\n# In[ ]:\n\n\n# calculate energy for each momentum\nEnergyBin={}\nEnergyMean={}\nfor p2 in massEffBinning.keys():\n lista=[]\n for m in massBin:\n lista.append(sqrt(m**2 + (int(p2)) * (2*PI/par['L'])**2 ))\n EnergyBin[p2]=np.array(lista)\n EnergyMean[p2]=np.average(np.array(EnergyBin[p2]),axis=0)\n\n\n# # Computes the Q^2\n\n# In[ ]:\n\n\nQ2_GeV_tmp={}\nfor imom_pp,mom_pp in enumerate(listMom_pp):\n for imom_q,mom_q in enumerate(listMom_q):\n mom_p=list(np.array(mom_pp) - np.array(mom_q))\n pp2=(np.array(mom_pp)**2).sum()\n q2=(np.array(mom_q)**2).sum()\n p2=(np.array(mom_p)**2).sum()\n tpl=(pp2,q2,p2)\n Q2_GeV_tmp[tpl] = (q2 * (2*PI/par['L'])**2 - (EnergyMean[str(pp2)] - EnergyMean[str(p2)])**2 ) * par['a_inverse_GeV']**2\n\n\n# # Excludes those Q^2 which are not in the slista and convert to string\n\n# In[ ]:\n\n\nQ2_GeV=[]\nfor keys in slista:\n Q2_GeV.append(Q2_GeV_tmp[keys])\nQ2_GeV=sorted(Q2_GeV)\nQ2_GeV_str=['%6.5f' % x for x in Q2_GeV] # this will save up to 5 decimal points for the Q^2\n\n\n# In[ ]:\n\n\nfor i in range(len(Q2_GeV_str)):\n print(i,Q2_GeV_str[i])\n\n\n# # Read three-point functions from pickles\n\n# In[ ]:\n\n\nthreepDic=pk.load(open(par['picklePath'] + '/ts%d/' % par['tsink'] + 'threep.pckl','rb'))\n\n\n# # Create JK bin averages\n\n# In[ ]:\n\n\n\nthreepP0=threepDic[('0',str(par['tsink']))][0]\nthreepP4=threepDic[('4',str(par['tsink']))][0]\nthreepP5=threepDic[('5',str(par['tsink']))][0]\nthreepP6=threepDic[('6',str(par['tsink']))][0]\ndel threepDic\n\nprint('Binning Threep')\npare=ProgressBar(widgets=[Percentage(), Bar('*'), Timer()],maxval=4).start()\nthreepP0_Binning=au.binningFast(threepP0, par['binsize'])\nthreepP0_Bmean=np.average(np.array(threepP0_Binning), axis=0)\npare.update(1)\nthreepP4_Binning=au.binningFast(threepP4, par['binsize'])\nthreepP4_Bmean=np.average(np.array(threepP4_Binning), axis=0)\npare.update(2)\nthreepP5_Binning=au.binningFast(threepP5, par['binsize'])\nthreepP5_Bmean=np.average(np.array(threepP5_Binning), axis=0)\npare.update(3)\nthreepP6_Binning=au.binningFast(threepP6, par['binsize'])\nthreepP6_Bmean=np.average(np.array(threepP6_Binning), axis=0)\npare.update(4)\npare.finish()\n\n\n# # Create Ratio\n\n# In[ ]:\n\n\npare=ProgressBar(widgets=[Percentage(), Bar('*'), Timer()],maxval=4).start()\nratioP0_Binning=au.ratio_W_sqrt_GenFrame(threepP0_Binning, twopBinning, par['tsink'], listMom_pp, listMom_q)\npare.update(1)\nratioP4_Binning=au.ratio_W_sqrt_GenFrame(threepP4_Binning, twopBinning, par['tsink'], listMom_pp, listMom_q)\npare.update(2)\nratioP5_Binning=au.ratio_W_sqrt_GenFrame(threepP5_Binning, twopBinning, par['tsink'], listMom_pp, listMom_q)\npare.update(3)\nratioP6_Binning=au.ratio_W_sqrt_GenFrame(threepP6_Binning, twopBinning, par['tsink'], listMom_pp, listMom_q)\npare.update(4)\npare.finish()\n\n# calculate the bin mean value\nratioP0_bmean = np.average(np.array(ratioP0_Binning),axis=0)\nratioP4_bmean = np.average(np.array(ratioP4_Binning),axis=0)\nratioP5_bmean = np.average(np.array(ratioP5_Binning),axis=0)\nratioP6_bmean = np.average(np.array(ratioP6_Binning),axis=0)\n\nerrRatioP0 = sqrt(Nbins-1) * ( np.std(np.array(ratioP0_Binning).real,axis=0) + 1j*np.std(np.array(ratioP0_Binning).imag,axis=0) )\nerrRatioP4 = sqrt(Nbins-1) * ( np.std(np.array(ratioP4_Binning).real,axis=0) + 1j*np.std(np.array(ratioP4_Binning).imag,axis=0) )\nerrRatioP5 = sqrt(Nbins-1) * ( np.std(np.array(ratioP5_Binning).real,axis=0) + 1j*np.std(np.array(ratioP5_Binning).imag,axis=0) )\nerrRatioP6 = sqrt(Nbins-1) * ( np.std(np.array(ratioP6_Binning).real,axis=0) + 1j*np.std(np.array(ratioP6_Binning).imag,axis=0) )\n\n\n# # Computes Matrix element with Plateau method\n\n# In[ ]:\n\n\ntmpPlat=[]\npare=ProgressBar(widgets=[Percentage(), Bar('*'), Timer()],maxval=4).start()\nicount=0\n\nfor rP,erP in zip([ratioP0_Binning, ratioP4_Binning, ratioP5_Binning, ratioP6_Binning],[errRatioP0,errRatioP4, errRatioP5, errRatioP6]):\n ratio_fitPlat=[]\n for Arr in rP:\n Lw=fitThpLow[str(par['tsink'])]\n Hg=fitThpHgh[str(par['tsink'])]\n tmpArr=np.zeros((len(listMom_pp),len(listMom_q),4),dtype=np.complex128)\n for imom_pp in range(len(listMom_pp)):\n for imom_q in range(len(listMom_q)):\n for mu in range(4):\n popt_r,chisq=au.simpleConstantFit(np.arange(Lw, Hg+1), Arr[imom_pp,imom_q,Lw:Hg+1,mu].real,erP[imom_pp,imom_q,Lw:Hg+1,mu].real)\n popt_i,chisq=au.simpleConstantFit(np.arange(Lw, Hg+1), Arr[imom_pp,imom_q,Lw:Hg+1,mu].imag,erP[imom_pp,imom_q,Lw:Hg+1,mu].imag)\n tmpArr[imom_pp,imom_q,mu]=popt_r+1j*popt_i\n ratio_fitPlat.append(np.array(tmpArr))\n tmpPlat.append(np.array(ratio_fitPlat))\n pare.update(icount)\n icount+=1\npare.finish()\n\n\n# # Computes Matrix element with Plateau method step 2\n\n# In[ ]:\n\n\nratioP0_fitPlat=tmpPlat[0]\nratioP4_fitPlat=tmpPlat[1]\nratioP5_fitPlat=tmpPlat[2]\nratioP6_fitPlat=tmpPlat[3]\n\n# average value of the fitted plateau\nratioP0_fitPlat_bmean = np.average(np.array(ratioP0_fitPlat),axis=0)\nratioP4_fitPlat_bmean = np.average(np.array(ratioP4_fitPlat),axis=0)\nratioP5_fitPlat_bmean = np.average(np.array(ratioP5_fitPlat),axis=0)\nratioP6_fitPlat_bmean = np.average(np.array(ratioP6_fitPlat),axis=0)\n\n# error of the average value of the fitted plateau\nerrRatioP0_fitPlat = sqrt(Nbins-1) * ( np.std(np.array(ratioP0_fitPlat).real,axis=0) + 1j*np.std(np.array(ratioP0_fitPlat).imag,axis=0) )\nerrRatioP4_fitPlat = sqrt(Nbins-1) * ( np.std(np.array(ratioP4_fitPlat).real,axis=0) + 1j*np.std(np.array(ratioP4_fitPlat).imag,axis=0) )\nerrRatioP5_fitPlat = sqrt(Nbins-1) * ( np.std(np.array(ratioP5_fitPlat).real,axis=0) + 1j*np.std(np.array(ratioP5_fitPlat).imag,axis=0) )\nerrRatioP6_fitPlat = sqrt(Nbins-1) * ( np.std(np.array(ratioP6_fitPlat).real,axis=0) + 1j*np.std(np.array(ratioP6_fitPlat).imag,axis=0) )\n\n\n# In[ ]:\n\n\n#import importlib\n#importlib.reload(au)\n\n\n# In[ ]:\n\n\n# calculate GE and GM per bin\nGE_ld=[]\nGM_ld=[]\nQ2_GeV_want=[Q2_GeV_str[x] for x in range(110)]\npare=ProgressBar(widgets=[Percentage(), Bar('*'), Timer()],maxval=Nbins).start()\nfor ibin in range(Nbins):\n EBins={}\n for q2 in EnergyBin.keys():\n EBins[q2]=EnergyBin[q2][ibin]\n GE_tmp, GM_tmp = au.extract_GE_GM_Gen_Frame([ratioP0_fitPlat[ibin],ratioP4_fitPlat[ibin],ratioP5_fitPlat[ibin],ratioP6_fitPlat[ibin]],\n [errRatioP0_fitPlat, errRatioP4_fitPlat, errRatioP5_fitPlat, errRatioP6_fitPlat],\n Q2_GeV_want,EBins,EnergyMean,listMom_pp,listMom_q,(par['L'],par['a_inverse_GeV']))\n GE_ld.append(GE_tmp)\n GM_ld.append(GM_tmp)\n pare.update(ibin)\npare.finish()\n\n\n# In[ ]:\n\n\nGE_bmean={}\nGM_bmean={}\n\nerrGE={}\nerrGM={}\n\nGE_bins={}\nGM_bins={}\n\n# convert list of dicts to dict of lists (assumes all the lists have the same keys)\n# renormalize by multiply here by ZV\nGE={key: [item[key]*par['ZV'] for item in GE_ld] for key in GE_ld[0].keys() }\nGM={key: [item[key]*par['ZV'] for item in GM_ld] for key in GM_ld[0].keys() }\n\ntss=str(par['tsink'])\n# save the bin values\nGE_bins.update({(Q2,tss): val for Q2,val in GE.items()})\nGM_bins.update({(Q2,tss): val for Q2,val in GM.items()})\n\n# mean values of GE & GM\nGE_bmean.update({(Q2,tss): np.average(val) for Q2,val in GE.items()})\nGM_bmean.update({(Q2,tss): np.average(val) for Q2,val in GM.items()})\n\n# error for GE & GM\nerrGE.update({(Q2,tss): sqrt(Nbins-1)*np.std(val) for Q2,val in GE.items()})\nerrGM.update({(Q2,tss): sqrt(Nbins-1)*np.std(val) for Q2,val in GM.items()})\n\n\n# In[ ]:\n\n\nwith open( par['outputPath'] + 'GE_%s_Tsink%s_%d.dat' % ('strange',tss,lenConf),'w') as fp:\n for Q2 in Q2_GeV_want:\n fp.write('%f %f %f\\n' % (float(Q2),GE_bmean[(Q2,tss)],errGE[(Q2,tss)]) )\n\nwith open( par['outputPath'] + 'GM_%s_Tsink%s_%d.dat' % ('strange',tss,lenConf),'w') as fp:\n for Q2 in Q2_GeV_want:\n if Q2 != '%6.5f' % 0.0:\n fp.write('%f %f %f\\n' % (float(Q2),GM_bmean[(Q2,tss)],errGM[(Q2,tss)]) )\n\nh5.writeG_Q2bins_fp(fp_h5, [GE_bins, GM_bins], ['GE','GM'], tss, Nbins)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"EM_form_factors_GenFrame.py","file_name":"EM_form_factors_GenFrame.py","file_ext":"py","file_size_in_byte":12981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"571709181","text":"#!/usr/bin/env python\n\"\"\"\nThis module saves and imports matrices.\n\"\"\"\nimport os\nimport numpy as np\nimport traceback\n\nclass DataDumper(object):\n \"\"\"\n A class for importing and saving models.\n \"\"\"\n DATAFOLDER = 'matrices'\n\n def __init__(self, dataset, folder=None):\n if folder is None:\n self.folder = self.DATAFOLDER\n self.dataset = dataset\n\n def save_matrix(self, matrix):\n \"\"\"\n Function that dumps the matrix to a .dat file.\n\n :param ndarray matrix: Matrix to be dumped.\n :param str matrix_name: Name of the matrix to be dumped.\n \"\"\"\n print(\"dumping \")\n path = self._create_path(self.dataset)\n print(path)\n print(matrix.sum())\n np.save(path, matrix)\n print(\"dumped to %s\" % path)\n\n def load_matrix(self):\n \"\"\"\n Function that loads a matrix from a file.\n\n :param dict config: Config that was used to calculate the matrix.\n :param str matrix_name: Name of the matrix to be loaded.\n :param tuple matrix_shape: A tuple of int containing matrix shape.\n :returns:\n A tuple of boolean (if the matrix is loaded or not)\n And the matrix if loaded, random matrix otherwise.\n :rtype: tuple\n \"\"\"\n path = self._create_path(self.dataset) + '.npy'\n print(\"trying to load %s\" % path)\n try:\n matrix = np.load(path)\n print(matrix.sum())\n res = (True, matrix)\n\n print(\"loaded from %s\" % path)\n return res\n except Exception:\n print(\"File not found, %s will initialize randomly\" % path)\n traceback.print_exc()\n return (False, None)\n\n def _create_path(self, matrix_name):\n \"\"\"\n Function creates a string uniquely representing the matrix it also\n uses the config to generate the name.\n\n :param str matrix_name: Name of the matrix.\n :param int n_rows: Number of rows of the matrix.\n :returns: A string representing the matrix path.\n :rtype: str\n \"\"\"\n path = matrix_name\n base_dir = os.path.dirname(os.path.realpath(__file__))\n return os.path.join(os.path.dirname(base_dir), self.folder, path)\n","sub_path":"util/data_dumper.py","file_name":"data_dumper.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"341191017","text":"while True:\n num = input(\"Enter a number: \")\n try:\n int(num)\n break\n except:\n print(\"That's not a number.\")\n\ndef isPrime(x):\n if x >= 2:\n for i in range(2, x):\n if not (x % i):\n return False\n else:\n return False\n return True\n\nfor i in range(0, int(num)):\n if isPrime(i):\n print(i)\n","sub_path":"Numbers/n4.py","file_name":"n4.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"184418580","text":"import ev3dev.ev3 as ev3\nimport time\nfrom PIL import ImageFont\nfrom math import floor\n\nclass Interaction:\n '''\n The Interaction Class provides the possibility to get input from the User via the basic user interface of the lego brick. There is a screen to display content and 5 buttons (left, right, up, down, enter) do select options.\n\n Besids printing text in an optimal size there is the possibility to get Integer or Boolean values from the user interface.\n '''\n\n def __init__(self):\n self.screen = ev3.Screen()\n\n def get_number(self, start, end, default=None):\n '''\n Asks the user to select a number with a picker from a given range intervall [start, end]. Default is the preselected value of the picker.\n\n Returns an integer value\n '''\n\n return NumberInput(start, end, self.screen, default).get_number()\n\n def get_bool(self, message):\n '''\n Asks the user to select a boolean value as the answer to the question/message\n\n Returns a boolean value\n '''\n return BooleanInput(message, self.screen).get_bool()\n\n def print(self, *arg):\n '''\n Print lines in an optimal size on the screen.\n\n Argument:\n arg lines to be displayed\n '''\n\n line_length, count_lines = max(map(len, arg)), len(arg)\n '''\n screen is 178x128 pixel\n each character is 3/5*size pixels wide and 5/6*size pixels high\n making size small enough that line_length many characters and count_lines lines fit on the screen\n '''\n size = min(floor(178*5/3/line_length), floor(128/count_lines*6/5))\n courier_new = ImageFont.truetype('/usr/share/fonts/truetype/msttcorefonts/Courier_New.ttf', size)\n\n self.screen.clear()\n for k, line in enumerate(arg):\n # pos is upper left corner of next line\n # each character is courier_new.getsize(\"x\")[1] pixel high\n pos = (0, courier_new.getsize(\"x\")[1]*k)\n self.screen.draw.text(pos, line, font=courier_new)\n\n self.screen.update()\n\nclass NumberInput:\n '''\n The NumberInput class handles user interaction with the aim to get an integer return value\n '''\n\n def __init__(self, start, end, screen, default=None):\n '''\n Arguments:\n start lower bound of number to be entered\n end upper bound of number to be entered\n screen screen object to be printed on\n default starting number, if ommited (start+end)//2\n '''\n self.position = 0 # which digit is to be changed\n self.position_count = len(str(end)) # amount of digits\n self.start = start\n self.end = end\n self.current_number = (start + end)//2 if default is None else default # saves current state\n self.result = None # after enter press, result is the input of the user\n\n # adding functions to be executed on different button presses\n self.btn = ev3.Button()\n self.btn.on_up = self.increase\n self.btn.on_down = self.decrease\n self.btn.on_left = self.left\n self.btn.on_right = self.right\n self.btn.on_enter = self.enter\n\n self.screen = screen\n # same calculation as above\n size = min(floor(178*5/3/self.position_count), floor(128*6/5))\n self.courier_new = ImageFont.truetype('/usr/share/fonts/truetype/msttcorefonts/Courier_New.ttf', size)\n\n def reset(self):\n ''' reset class to input another number '''\n self.result = None\n self.current_number = (self.start + self.end)//2\n self.position = 0\n\n def is_finished(self):\n ''' returns whether enter was already pressed '''\n return self.result is not None\n\n def get_number(self):\n ''' waits while enter isn't pressed yet and returns the result'''\n if not self.is_finished():\n self.refresh()\n while not self.is_finished():\n time.sleep(0.01) # fixes a double event from the button\n self.btn.process()\n return self.result\n\n def refresh(self):\n ''' prints current number and marks the digit to be changed '''\n self.screen.clear()\n # formatted_str is current number precedet by numbers such that len(formatted_str) == position_count\n formatted_str = (\"{:0\" + str(self.position_count) + \"}\").format(int(self.current_number))\n\n for pos in range(self.position_count):\n if self.position_count - pos - 1 == self.position:\n # gives the selected position a black background and white font color\n prev_width = self.screen.draw.textsize(formatted_str[:pos], font=self.courier_new)\n next_width = self.screen.draw.textsize(formatted_str[:pos+1], font=self.courier_new)\n self.screen.draw.rectangle((prev_width[0], 0, next_width[0], next_width[1]), fill=\"black\")\n self.screen.draw.text((prev_width[0],0), formatted_str[pos], font=self.courier_new, fill=\"white\")\n else:\n prev_width = self.screen.draw.textsize(formatted_str[:pos], font=self.courier_new)[0]\n self.screen.draw.text((prev_width,0), formatted_str[pos], font=self.courier_new)\n\n self.screen.update()\n\n def increase(self, state):\n ''' increases the current_number at the current position by 1 '''\n if self.is_finished(): return\n if state:\n self.current_number += 10**self.position\n self.current_number = min(self.current_number, self.end)\n self.refresh()\n\n def decrease(self, state):\n ''' decreases the current_number at the current position by 1 '''\n if self.is_finished(): return\n if state:\n self.current_number -= 10**self.position\n self.current_number = max(self.current_number, self.start)\n self.refresh()\n\n def left(self, state):\n ''' switches position to left '''\n if self.is_finished(): return\n if state:\n self.position = min(self.position+1, self.position_count)\n self.refresh()\n\n def right(self, state):\n ''' switches position to right '''\n if self.is_finished(): return\n if state:\n self.position = max(self.position-1, 0)\n self.refresh()\n\n def enter(self, state):\n ''' selects the current_number and submits it '''\n if state:\n self.screen.clear()\n formatted_str = (\"{:0\" + str(self.position_count) + \"}\").format(int(self.current_number))\n self.screen.draw.text((0,0), formatted_str, font=self.courier_new) # no black background anymore after submit\n self.screen.update()\n\n self.result = self.current_number\n\nclass BooleanInput:\n '''\n The BooleanInput class handles user interaction with the aim to get a boolean return value\n Works the same way as NumberInput except choosing between \"ja\" and \"nein\"\n '''\n\n def __init__(self, message, screen):\n self.current_value = True\n self.result = None\n\n self.btn = ev3.Button()\n self.btn.on_left = self.change\n self.btn.on_right = self.change\n self.btn.on_enter = self.enter\n\n self.screen = screen\n self.message = message\n self.courier_new_bool = ImageFont.truetype('/usr/share/fonts/truetype/msttcorefonts/Courier_New.ttf', 40)\n size = min(floor(178*5/3/len(message)), floor(128/2*6/5))\n self.courier_new_text = ImageFont.truetype('/usr/share/fonts/truetype/msttcorefonts/Courier_New.ttf', size)\n\n def reset(self):\n self.result = None\n self.current_value = True\n\n def is_finished(self):\n return self.result is not None\n\n def get_bool(self):\n if not self.is_finished():\n self.refresh()\n while not self.is_finished():\n time.sleep(0.01) # fixes a double event from the button\n self.btn.process()\n return self.result\n\n def refresh(self):\n self.screen.clear()\n self.screen.draw.text((0,0), self.message, font=self.courier_new_text)\n if self.current_value:\n self.screen.draw.text((0,64), \"Ja\", font=self.courier_new_bool)\n else:\n self.screen.draw.text((0,64), \"Nein\", font=self.courier_new_bool)\n self.screen.update()\n\n def change(self, state):\n if state and not self.is_finished():\n self.current_value = not self.current_value\n self.refresh()\n\n def enter(self, state):\n if state:\n self.result = self.current_value\n\n\n\nif __name__ == '__main__':\n # for debugging only\n interaction = Interaction()\n print(interaction.get_number())","sub_path":"interaction.py","file_name":"interaction.py","file_ext":"py","file_size_in_byte":8837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"341456059","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\nfrom types import SimpleNamespace\nimport sys\nsys.path.append(\"..\")\nimport nlp, nlp_constants\nimport re\nglobal SSL_requests_counter\n\n\n\ndef tags_fusion(parced_tags, from_text_tags, tags_max=20):\n final_tags = [] # fusion of text tags and predefined tags\n for tag in from_text_tags:\n if (tag in parced_tags):\n final_tags.append(tag)\n\n for tag in parced_tags:\n if (tag not in final_tags):\n final_tags.append(tag)\n\n for tag in from_text_tags:\n if (tag not in final_tags):\n final_tags.append(tag)\n\n final_tags = final_tags[:tags_max]\n return final_tags\n\ndef generate_search_url(plat,instruments, lat_long):\n\n base_part = f\"https://cmr.earthdata.nasa.gov/search/collections.json?\"\n\n # platform search\n plat_part = \"\"\n if(plat!=None):\n plat_part = f\"platform={plat}\"\n\n # instruments search\n instr_part = \"\"\n for instr in instruments:\n instr_part += f\"instrument={instr}&\"\n\n # location search\n loc_part = \"\"\n lat, lon = lat_long\n loc_part = \"\"\n if(lat!=None):\n loc_part = f\"point={lon},{lat}&\"\n\n end_part = \"has_granules=true&pretty=true\"\n\n search_url = base_part + plat_part + instr_part + loc_part + end_part\n return search_url\n\ndef generate_tag_search_url(tag):\n\n base_part = f\"https://cmr.earthdata.nasa.gov/search/collections.json?\"\n\n keyword_part = f\"keyword={tag}&\"\n\n end_part = \"has_granules=true&pretty=true\"\n\n search_url = base_part + keyword_part + end_part\n return search_url\n\ndef datasets_sorting(colIds, final_tags):\n # colIds = {id: [title, id, summary, has_location, has_platform, has_instrument]}\n res = []\n for id in colIds.keys():\n title, id_, summary, has_location, has_platform, has_instrument = colIds[id]\n dataset_score = 100 * has_platform + 50*has_instrument + 20*has_location\n text = colIds[id][0].lower() + colIds[id][2].lower()\n for i, keyword in enumerate(final_tags):\n dataset_score += (25 - i) * text.count(keyword)\n res.append([colIds[id][0], colIds[id][1], dataset_score])\n res.sort(key=lambda x: x[2], reverse=True)\n print(f'SORTED results:')\n for el in res:\n print(el)\n print('=====')\n res = [[el[0], el[1]] for el in res]\n return res\n\ndef colIds_from_url(colIds, url, lat_long, plat, has_instrument):\n global SSL_requests_counter\n\n # colIds = {id: [title, id, summary, has_location, has_platform, has_instrument]}\n if(plat==None):\n has_platform = 0\n else:\n has_platform = 1\n res = requests.get(url)\n items = json.loads(res.text, object_hook=lambda d: SimpleNamespace(**d))\n for e in items.feed.entry:\n if (lat_long == [None,None]):\n has_location = 0\n elif(SSL_requests_counter<10): # Check granules by location\n lat, lon = lat_long\n collection_url = f\"https://cmr.earthdata.nasa.gov/search/granules.json?collection_concept_id={e.id}&point={lon},{lat}&pretty=true\"\n res = requests.get(collection_url)\n SSL_requests_counter +=1\n granules = json.loads(res.text, object_hook=lambda d: SimpleNamespace(**d))\n if len(granules.feed.entry) == 0:\n continue\n else:\n has_location = 1\n else:\n has_location = 0.25\n if (e.id not in colIds.keys()):\n colIds[e.id] = [e.title, e.id, e.summary, has_location, has_platform, has_instrument]\n else:\n pass\n\n return colIds\n\ndef parse(url):\n res = requests.get(url)\n\n soup = BeautifulSoup(res.text, 'html.parser')\n\n ## Title\n title = soup.find(\"meta\", attrs={\"name\": \"DC.Title\"})['content']\n\n ## Publish Year\n t = soup.find(\"meta\", attrs={\"name\": \"DC.Date\"})['content']\n match = re.match(r'.*([1-2][0-9]{3})', t)\n if match is not None:\n publishYear = int(match.group(1))\n\n ## Text\n articleP = soup.select('div.col-lg-8.col-md-8.col-sm-8.col-xs-12.col-md-right-space p')\n articleText = \"\"\n for p in articleP:\n articleText = articleText + \"\\n\" + p.text\n\n ## Tags\n tagz = soup.select(\"div.panel.panel-default.panel-circle-container.hidden-xs a.btn.btn-tag.hvr-rectangle-in.btn-sm\")\n tags = []\n for i in tagz:\n tags.append(i.text)\n\n ## R & R\n linkz = soup.select(\"ul.references li\")\n links = []\n for i in linkz:\n links.append(i.text)\n\n ## Picture text\n picturr = soup.select('div.caption p')\n pictureText = []\n for i in picturr:\n pictureText.append(i.text)\n\n return {\n \"title\": title,\n \"publishYear\": publishYear,\n \"tags\": tags,\n \"R&R\": links,\n \"pictureText\": pictureText,\n \"text\": articleText,\n }\n\ndef process(parsed, results_num = 10):\n \"\"\"\n\n :param parsed:\n \"title\": title,\n \"publishYear\": publishYear,\n \"tags\": tags,\n \"R&R\": links,\n \"pictureText\": pictureText,\n \"text\": articleText,\n :type parsed: dict\n\n :return: list of ids\n :rtype: list\n\n \"\"\"\n\n global SSL_requests_counter\n SSL_requests_counter = 0\n ### ================================ P A R S E D D A T A ===========================\n title = parsed[\"title\"]\n text = parsed[\"text\"]\n parsed_tags = parsed[\"tags\"]\n R_and_R = parsed[\"R&R\"]\n publishYear = parsed[\"publishYear\"]\n pictureText = parsed[\"pictureText\"]\n\n print(f\"Processed data:\")\n print(f\"parsed_tags:{parsed_tags}\")\n print(f\"publishYear:{publishYear}\")\n\n\n ### ================================ T E X T D A T A ==============================\n\n args = {\"R&R\": parsed[\"R&R\"]}\n tA = nlp.TextAnalysis(title=title, text=text, args=args)\n text_tags = tA.spaCy_tags(tA.text)\n\n from_text_instruments = tA.instruments_extraction(text_tags)\n from_text_platforms = tA.platforms__extraction(text_tags)\n from_text_locations = tA.locations_extraction(text_tags)\n from_text_dates = tA.dates_extraction(text_tags)\n from_text_tags = tA.keywords_extraction(tA.text, 10)\n\n print(f\"Text data:\")\n print(f\"from_text_instruments:{from_text_instruments}\")\n print(f\"from_text_platforms:{from_text_platforms}\")\n print(f\"from_text_tags:{from_text_tags}\")\n\n ### ================================ P R O C E S S I N G =============================\n\n # tags creation\n final_tags = tags_fusion(parsed_tags, from_text_tags, 20)\n\n colIds = {}\n # colIds format:\n # dataset.id: [title, id, summary, has_location, has_platform, has_instrument]\n # Platforms > instruments > locations > tags\n if(len(from_text_platforms)==0):\n from_text_platforms = [None]\n if(len(from_text_locations)==0):\n from_text_locations = [[None,None]]\n\n # search by platform, all instruments and concrete location\n for plat in from_text_platforms:\n for lat_long in from_text_locations:\n search_url = generate_search_url(plat, from_text_instruments, lat_long)\n colIds = colIds_from_url(colIds, search_url, lat_long, plat, 1)\n\n # If we don't have enought results, we drop search by location\n if (len(colIds.keys()) < results_num and from_text_locations!=[[None,None]]):\n for plat in from_text_platforms:\n search_url = generate_search_url(plat, from_text_instruments, [None,None])\n colIds = colIds_from_url(colIds, search_url, [None,None], plat, 1)\n\n if(len(colIds.keys()) < results_num):\n print(f'By platform, instrument and location found: {len(colIds.keys())} datasets. Continue seach by tags')\n for tag in final_tags:\n search_url = generate_tag_search_url(tag)\n colIds = colIds_from_url(colIds, search_url, [None, None],None, 0)\n\n\n Ordered_colIds = datasets_sorting(colIds, final_tags)\n\n\n print(f\"SSL requests number: {SSL_requests_counter}\")\n return Ordered_colIds[:results_num]\n\nif __name__ == '__main__':\n t = parse(\"https://earthobservatory.nasa.gov/features/covid-seasonality\")\n\n print(t)","sub_path":"Server/sections/SectArticles.py","file_name":"SectArticles.py","file_ext":"py","file_size_in_byte":8077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"7909067","text":"# coding=utf-8\n# -----------------------------------------------------------------------------\n# Abril Marina González Ramírez A01280904\n# Juan Luis Flores Garza A01280767\n# 12/03/2019\n\n# Scanner\n# References: https://github.com/dabeaz/ply\n# -----------------------------------------------------------------------------\nimport ply.lex as lex\n# -----------------------------------------------------------------------------\n# Tokens\n# -----------------------------------------------------------------------------\ntokens = [\n 'ID', 'CTE_I', 'CTE_D', 'CTE_B', \n 'PLUS', 'MINUS', 'MULTIPLY', 'DIVIDE',\n 'IS_EQUAL_TO', 'NOT_EQUAL_TO', \n 'GREATER_THAN', 'LESS_THAN', \n 'GREATER_THAN_OR_EQUAL_TO', 'LESS_THAN_OR_EQUAL_TO',\n 'AND', 'OR',\n 'ASSIGN',\n 'LEFT_PAR', 'RIGHT_PAR',\n 'LEFT_BRACE', 'RIGHT_BRACE',\n 'LEFT_BRACKET', 'RIGHT_BRACKET',\n 'SEMICOLON', 'COMMA'\n]\n\n# -----------------------------------------------------------------------------\n# Dictionary of Reserved words\n# -----------------------------------------------------------------------------\nreservedWords = {\n 'Main': 'MAIN',\n 'if': 'IF',\n 'else': 'ELSE',\n 'while': 'WHILE',\n 'function': 'FUNCTION',\n 'return': 'RETURN',\n 'void': 'VOID',\n 'int': 'INT',\n 'double': 'DOUBLE',\n 'bool': 'BOOL',\n 'true': 'TRUE',\n 'false': 'FALSE',\n 'read': 'READ',\n 'write': 'WRITE',\n 'matrix': 'MATRIX',\n # Special functions\n 'multiply_matrix': 'MULTIPLY_MATRIX',\n 'add_to_matrix': 'ADD_TO_MATRIX',\n 'subtract_from_matrix': 'SUBTRACT_FROM_MATRIX',\n 'swap': 'SWAP',\n 'p_matrix': 'P_MATRIX',\n}\n\ntokens = tokens + list(reservedWords.values())\n\n# -----------------------------------------------------------------------------\n# Tokens\n# -----------------------------------------------------------------------------\n\n# Ignore tabs\nt_ignore = \" \\t\"\n\n# Arithmetic Operators\nt_PLUS = r'\\+'\nt_MINUS = r'-'\nt_MULTIPLY = r'\\*'\nt_DIVIDE = r'/'\n# Relational Operators\nt_IS_EQUAL_TO = r'=='\nt_NOT_EQUAL_TO = r'!='\nt_GREATER_THAN = r'>'\nt_LESS_THAN = r'<'\nt_GREATER_THAN_OR_EQUAL_TO = r'>='\nt_LESS_THAN_OR_EQUAL_TO = r'<='\n# Logical Operators\nt_AND = r'&&'\nt_OR = r'\\|\\|'\n# Assignment Operator\nt_ASSIGN = r'\\='\n# Punctuators\nt_LEFT_PAR = r'\\('\nt_RIGHT_PAR = r'\\)'\nt_LEFT_BRACE = r'{'\nt_RIGHT_BRACE = r'}'\nt_LEFT_BRACKET = r'\\['\nt_RIGHT_BRACKET = r'\\]'\nt_SEMICOLON = r'\\;'\nt_COMMA = r','\n\n# Data Types & ID\ndef t_ID(t):\n r'[a-zA-Z][_a-zA-Z0-9]*'\n t.type = reservedWords.get(t.value,'ID')\n return t\n\ndef t_CTE_D(t):\n r'-?[0-9]*\\.[0-9]+'\n t.value = float(t.value)\n return t\n \ndef t_CTE_I(t):\n r'-?[0-9]+'\n t.value = int(t.value)\n return t\n\n# New lines and errors\ndef t_newline(t):\n r'\\n+'\n t.lexer.lineno += t.value.count(\"\\n\")\n\ndef t_error(t):\n print(\"Illegal character '{}' at: {}\".format(t.value[0], t.lexer.lineno))\n t.lexer.skip(1)\n\n# Build the lexer\nlexer = lex.lex()\n\n#### Testing the lexer \n# file = open(\"example.txt\")\n# lexer.input(file.read())\n\n# Get tokens\n# while True:\n# tok = lexer.token()\n# if not tok:\n# break\n# print(\"\\n\")\n\n","sub_path":"server/scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"463152115","text":"'''\nDisplay Frankie the Fox on the screen\nBigger and in the middle\n'''\n\nimport pygame\nimport sys\n\nSCREEN_WIDTH = 800\nSCREEN_HEIGHT = 600\n\ndef main():\n # Initialize pygame library\n pygame.init()\n\n # Set up a display 800 by 600\n screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n\n # Put frankie image into a variable\n frankie = pygame.image.load(\"10-pygame/foxr.gif\")\n\n # Make frankie bigger\n frankie = pygame.transform.rotozoom(frankie, 0, 4)\n\n # Get frankie's dimensions\n frankie_rect = frankie.get_rect()\n\n # Move frankie to the middle of the screen\n frankie_rect.centerx = SCREEN_WIDTH/2\n frankie_rect.centery = SCREEN_HEIGHT/2\n\n # Put frankie onto screen\n screen.blit(frankie, frankie_rect)\n\n # Update display (so we can see the newly added Frankie)\n pygame.display.flip()\n\n # Keep our program running\n while True:\n # If the user closes the window, then finish\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n\n'''\n(0,0).............(800,0)\n. .\n. .\n. .\n. .\n. .\n. .\n. .\n(0,600)...........(800,600)\n\n'''\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"10-pygame/2_frankie_big.py","file_name":"2_frankie_big.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"91436006","text":"import random\nimport socket\nimport urllib\nimport http.cookiejar\nimport time\n\nclass BrowserShadow(object):\n \"\"\" simulate the action of the browser\"\"\"\n\n def __init__(self):\n# socket.setdefaulttimeout()\n self.res = None\n\n def print_info(self, name, content):\n print('[%s] %s' %(name, content))\n\n def open_url(self, url):\n \"\"\"open the specificial url\"\"\"\n CookieSupport = urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())\n self.opener = urllib.request.build_opener(CookieSupport, urllib.request.HTTPHandler)\n urllib.request.install_opener(self.opener)\n user_agents = [\n 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',\n 'Opera/9.25 (Windows NT 5.1; U; en)',\n 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',\n 'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',\n 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',\n 'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',\n \"Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 Chrome/16.0.912.77 Safari/535.7\",\n \"Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0 \"\n ]\n agent = random.choice(user_agents)\n\n \"\"\" modify the header information to instead of the default python header message\"\"\"\n self.opener.addheaders = [(\"User-agent\",agent),(\"Accept\",\"*/*\"),('Referer','http://www.google.com')]\n \n while True:\n try:\n self.res = self.opener.open(url)\n if self.res.status == 200:\n break\n except Exception as e:\n self.print_info(str(e),url)\n sleep_time = 5 * random.random()\n self.print_info(\"Sleep Time:\", sleep_time)\n time.sleep(sleep_time) # sleep and access the url again\n# raise Exception\n \n return self.res\n\n\"\"\"end class\"\"\"\n","sub_path":"DataObtain/BrowserShadow.py","file_name":"BrowserShadow.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"75500106","text":"#gets two numbers and prints div and mod of those two\na = int(input(\"Type in First Number:\"))\nb = int(input(\"Type in Second Number:\"))\n\nc = str(int(a/b))\nd = str(a%b)\n\nprint(c,d, sep=\"-\", end=\";\")\n#print is a function and we can change its behavior. \n#usage of \"sep=\" indicated what should come instead of \",\" between variables. by default, sep=\" \"\n#usage of \"end=\" indicates what should come at the end of print. by default, end=\"\\n\"","sub_path":"1/mod_in_python.py","file_name":"mod_in_python.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"414291733","text":"import torch\r\nimport torch.nn as nn\r\nfrom decoder import Tap_gru_cond_layer\r\n\r\n\r\ndef getReverse(a):\r\n # a = a.cpu().numpy()[::-1]\r\n # return torch.from_numpy(a.copy()).cuda()\r\n return a[range(len(a))[::-1]]\r\n\r\n\r\n# Embedding\r\nclass My_Tap_Embedding(nn.Module):\r\n def __init__(self, params):\r\n super(My_Tap_Embedding, self).__init__()\r\n self.embedding = nn.Embedding(params['num_target'], params['word_dim'])\r\n\r\n def forward(self, params, y, is_train):\r\n if y.sum() < 0.:\r\n emb = torch.zeros(1, params['word_dim']).cuda()\r\n else:\r\n if is_train: # only for training stage\r\n emb = self.embedding(y)\r\n emb_shifted = torch.zeros([emb.shape[0], emb.shape[1], params['word_dim']], dtype=torch.float32).cuda()\r\n emb_shifted[1:] = emb[:-1]\r\n emb = emb_shifted\r\n else:\r\n # emb = torch.zeros([y.shape[0], params[\"word_dim\"]]).cuda()\r\n emb = self.embedding(y)\r\n return emb\r\n\r\n\r\nclass Encoder_Decoder(nn.Module):\r\n def __init__(self, params):\r\n super(Encoder_Decoder, self).__init__()\r\n self.tap_encoder_0_1 = nn.GRU(params[\"dim_feature\"], params[\"tap_gru_Wx\"][1], 2,\r\n bidirectional=True) # ->(input_size,hidden_size,num_layers)\r\n self.tap_encoder_2 = nn.GRU(params[\"tap_gru_W\"][0], params[\"tap_gru_Wx\"][1], 1,\r\n bidirectional=True) # ->(input_size,hidden_size,num_layers)\r\n\r\n self.tap_encoder_3 = nn.GRU(params[\"tap_gru_W\"][0], params[\"tap_gru_Wx\"][1], 1,\r\n bidirectional=True) # ->(input_size,hidden_size,num_layers)\r\n\r\n self.ff_state_W = nn.Linear(params['ff_state_W'][0], params['ff_state_W'][1])\r\n self.tap_emb_model = My_Tap_Embedding(params)\r\n self.tap_decoder = Tap_gru_cond_layer(params)\r\n self.ff_logit_lstm = nn.Linear(params[\"ff_logit_lstm\"][0], params[\"ff_logit_lstm\"][1])\r\n self.ff_logit_prev = nn.Linear(params[\"ff_logit_prev\"][0], params[\"ff_logit_prev\"][1])\r\n self.ff_logit_ctx = nn.Linear(params[\"ff_logit_ctx\"][0], params[\"ff_logit_ctx\"][1])\r\n self.ff_logit = nn.Linear(params[\"ff_logit\"][0], params[\"ff_logit\"][1])\r\n\r\n def forward(self, params, tap_x, tap_x_mask, tap_y, tap_y_mask, maxlen, is_train=True):\r\n self.tap_encoder_0_1.flatten_parameters()\r\n self.tap_encoder_2.flatten_parameters()\r\n self.tap_encoder_3.flatten_parameters()\r\n\r\n # print(\"\\tIn Train Model before: input size\", tap_y.size())\r\n\r\n # 传入时 batch * seq_x * dim => seq_x * batch * dim\r\n tap_x = tap_x.permute([1, 0, 2])\r\n tap_x_mask = tap_x_mask.permute([1, 0])\r\n tap_y = tap_y.permute([1, 0])\r\n tap_y_mask = tap_y_mask.permute([1, 0])\r\n # print(\"\\tIn Train Model after: tap_x\", tap_x)\r\n # print(\"\\tIn Train Model after: tap_y\", tap_y)\r\n h, (hn) = self.tap_encoder_0_1(tap_x)\r\n # h, (hn) = self.tap_encoder_2(h)\r\n # h = h[0::2]\r\n # tap_x_mask = tap_x_mask[0::2]\r\n # h, (hn) = self.tap_encoder_3(h)\r\n # h = h[0::2]\r\n # tap_x_mask = tap_x_mask[0::2]\r\n\r\n tap_ctx = h\r\n\r\n # x_mask[:, :, None] = seq_x × batch_size × 1\r\n # (ctx * x_mask[:, :, None]).sum(0) = batch_size × 500\r\n # x_mask.sum(0)[:, None] = batch_size ×1\r\n tap_ctx_mean = (tap_ctx * tap_x_mask[:, :, None]).sum(0) / tap_x_mask.sum(0)[:, None]\r\n # init_state = batch_size × 256\r\n tap_init_state = torch.tanh(self.ff_state_W(tap_ctx_mean))\r\n # tparams['Wemb_dec'] = 111 × 256\r\n # y.flatten = y_length * batch_size\r\n # tparams['Wemb_dec'][y.flatten()] = y.flatten × 256\r\n\r\n # print(\"\\tIn Train Model: input size\", tap_emb.size())\r\n if is_train:\r\n tap_emb = self.tap_emb_model(params, tap_y, True)\r\n tap_proj = self.tap_decoder(params, tap_emb, mask=tap_y_mask, context=tap_ctx, context_mask=tap_x_mask,\r\n one_step=False, init_state=tap_init_state)\r\n tap_proj_h = tap_proj[0]\r\n tap_ctxs = tap_proj[1]\r\n logit_lstm = self.ff_logit_lstm(tap_proj_h)\r\n logit_prev = self.ff_logit_prev(tap_emb)\r\n logit_ctx = self.ff_logit_ctx(tap_ctxs)\r\n\r\n logit = logit_lstm + logit_prev + logit_ctx\r\n\r\n shape = logit.shape\r\n shape2 = int(shape[2] / 2)\r\n shape3 = 2\r\n logit = torch.reshape(logit, [shape[0], shape[1], shape2, shape3])\r\n logit = logit.max(3)[0] # seq*batch*128\r\n last_logit = self.ff_logit(logit)\r\n return last_logit.permute([1, 0, 2])\r\n else:\r\n result_list = []\r\n # tap decoder batch_size * dim\r\n next_w = torch.zeros([tap_ctx.shape[1], params[\"word_dim\"]], dtype=torch.float32).cuda()\r\n # batch_size * seq_x\r\n next_alpha_past = torch.zeros([tap_ctx.shape[1], tap_ctx.shape[0]]).cuda() # start position\r\n # batch_size * 256\r\n next_state = tap_init_state\r\n\r\n for ii in range(maxlen):\r\n tap_proj = self.tap_decoder(params, next_w, context=tap_ctx, context_mask=tap_x_mask,\r\n one_step=True, init_state=next_state, alpha_past=next_alpha_past)\r\n next_state = tap_proj[0]\r\n # batch_size * dim\r\n tap_ctxs = tap_proj[1]\r\n next_alpha_past = tap_proj[3]\r\n # tap_next_state:batch_size * dim\r\n logit_lstm = self.ff_logit_lstm(next_state)\r\n logit_prev = self.ff_logit_prev(next_w)\r\n logit_ctx = self.ff_logit_ctx(tap_ctxs)\r\n\r\n logit = logit_lstm + logit_prev + logit_ctx\r\n\r\n shape = logit.shape\r\n # dim /2\r\n shape1 = int(shape[1] / 2)\r\n shape2 = 2\r\n # batch_size * dim / 2 * 2\r\n logit = torch.reshape(logit, [shape[0], shape1, shape2])\r\n # batch_size * dim / 2\r\n logit = logit.max(2)[0] # batch*128\r\n # batch_size * target\r\n logit = self.ff_logit(logit)\r\n # batch_size * target\r\n next_probs = torch.softmax(logit, logit.ndim - 1)\r\n # batch_size *\r\n next_w = torch.argmax(next_probs, next_probs.ndim - 1)\r\n result_list.append(next_w)\r\n next_w = self.tap_emb_model(params, next_w, False)\r\n\r\n return result_list\r\n\r\n # decoding: encoder part\r\n\r\n def tap_f_init(self, params, tap_x):\r\n # print(\"\\tIn Valid Model: input size\", tap_x.size())\r\n self.tap_encoder_0_1.flatten_parameters()\r\n self.tap_encoder_2.flatten_parameters()\r\n self.tap_encoder_3.flatten_parameters()\r\n h, (hn) = self.tap_encoder_0_1(tap_x)\r\n h, (hn) = self.tap_encoder_2(h)\r\n h = h[0::2]\r\n h, (hn) = self.tap_encoder_3(h)\r\n h = h[0::2]\r\n tap_ctx = h\r\n tap_ctx_mean = tap_ctx.mean(0)\r\n tap_init_state = torch.tanh(self.ff_state_W(tap_ctx_mean))\r\n return tap_init_state, tap_ctx\r\n\r\n # decoding: decoder part\r\n def tap_f_next(self, params, y, tap_ctx, init_state, alpha_past):\r\n tap_emb = self.tap_emb_model(params, y, False)\r\n tap_proj = self.tap_decoder(params, tap_emb, context=tap_ctx,\r\n one_step=True,\r\n init_state=init_state, alpha_past=alpha_past)\r\n tap_next_state = tap_proj[0]\r\n tap_ctxs = tap_proj[1]\r\n next_alpha_past = tap_proj[3]\r\n logit_lstm = self.ff_logit_lstm(tap_next_state)\r\n logit_prev = self.ff_logit_prev(tap_emb)\r\n logit_ctx = self.ff_logit_ctx(tap_ctxs)\r\n\r\n logit = logit_lstm + logit_prev + logit_ctx\r\n shape = logit.shape\r\n shape1 = int(shape[1] / 2)\r\n shape2 = 2\r\n logit = torch.reshape(logit, [shape[0], shape1, shape2])\r\n logit = logit.max(2)[0] # seq * batch * 128\r\n logit = self.ff_logit(logit)\r\n next_probs = torch.softmax(logit, logit.ndim - 1)\r\n return next_probs, tap_next_state, next_alpha_past\r\n","sub_path":"layer_2_encoder_decoder.py","file_name":"layer_2_encoder_decoder.py","file_ext":"py","file_size_in_byte":8335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"10707383","text":"# Napište funkci, která jako vstup přijímá dvě proměnné.\n# Předpokládejte, že vstupy jsou seznamy. Porovnejte jejich délku (funkce len(listName)), pokud obsahují stejný počet prvků funkce vrací hodnotu true, jinak vrací hodnotu false.\ndef compareLists(firstList, secondList):\n sameLength = False\n\n if len(firstList) == len(secondList):\n sameLength = True\n\n return(sameLength)\n\n\n \na = [1, 3, 5, 7]\nb = [1, 8, 9, 12]\n\nsameLength = compareLists(a,b)\nprint(sameLength)\n\n\n############################\n# Napište funkci, která jako argument přímá počet prvků v seznamu - n.\n# Funkce od uživatele bude požadovat n vstupů, ze kterých vytvoří seznam, který bude funkce vracet.\n\ndef listDefinition(number):\n listOfValues = []\n for i in range(number):\n listOfValues.append(float(input(\"Zadej číslo: \")))\n return(listOfValues)\n\n\nnumber = int(input(\"Zadej počet prvků v seznamu: \"))\nlistOfValues = listDefinition(number)\nprint(listOfValues)\n\n\n############################\n# Napište funkci, která jako argument přijímá seznam hodnot. Předpokládejte, že seznam obsahuje pouze čísla. Funkce vrací jako výsledek průměr z čísel v seznamu.\n\ndef prumer(listOfValues):\n suma = 0\n for x in listOfValues:\n suma += x\n prumer = suma / len(listOfValues)\n return(prumer)\n\na = [10,24,316,41,5133]\nprint(prumer(a))\n\n############################\n# Napište funkci, která ze vstupního řetězce vrátí znaky v rozmezí 5 - 9 znaku.\n# Pokud je řetězec kratší než 9 znaků, vypište hlášku, že operaci nelze provést.\ndef znaky(retezec):\n if len(retezec) < 9:\n print(\"Operaci nelze provést\")\n else:\n podretezec = retezec[4:9] \n return(podretezec)\n\nstring = \"01234567\"\nprint(znaky(string))\n\n############################\n# Napište funkci, která jako argument přijímá řetězec.\n# Upravte vstupní řetězec tak, aby obsahoval pouze malá písmena.\n# Následně nahraďte všechny české znaky (s háčky, čárkami a kroužky) v řetězci za jejich ekvivalenty bez těchto znaků.\n# Takto upravený řetězec bude návratovou hodnotou funkce. \ndef odstranZnaky(retezec):\n retezec = retezec.lower()\n ceskeZnaky = [\"ě\", \"š\", \"č\", \"ř\", \"ž\", \"ý\", \"á\", \"í\", \"é\", \"ú\", \"ů\", \"ť\", \"ď\", \"ó\", \"ň\"]\n asciiZnaky = [\"e\", \"s\", \"c\", \"r\", \"z\", \"y\", \"a\", \"i\", \"e\", \"u\", \"u\", \"t\", \"d\", \"o\", \"n\"]\n\n for i in range(len(ceskeZnaky)):\n retezec = retezec.replace(ceskeZnaky[i],asciiZnaky[i])\n\n return(retezec) \n\n\ntestovaciRetezec = \"Příšerně žluťoučký kůň úpěl ďábelské ódy.\"\nprint(testovaciRetezec)\nvyslek = odstranZnaky(testovaciRetezec)\nprint(vyslek)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"cviceni_moje/du2.py","file_name":"du2.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"357916857","text":"import variables as var\n\n\ndef strings(option, *argv, **kwargs):\n try:\n string = var.config.get(\"strings\", option)\n except KeyError:\n raise KeyError(\"Missed strings in configuration file: '{string}'. \".format(string=option)\n + \"Please restore you configuration file back to default if necessary.\")\n if argv or kwargs:\n try:\n formatted = string.format(*argv, **kwargs)\n return formatted\n except KeyError as e:\n raise KeyError(\n \"Missed/Unexpected placeholder {{{placeholder}}} in string '{string}'. \".format(placeholder=str(e).strip(\"'\"), string=option)\n + \"Please restore you configuration file back to default if necessary.\")\n except TypeError:\n raise KeyError(\n \"Missed placeholder in string '{string}'. \".format(string=option)\n + \"Please restore you configuration file back to default if necessary.\")\n else:\n return string\n\n\ndef commands(command):\n try:\n string = var.config.get(\"commands\", command)\n return string\n except KeyError:\n raise KeyError(\"Missed command in configuration file: '{string}'. \".format(string=command)\n + \"Please restore you configuration file back to default if necessary.\")\n","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"617065569","text":"#!/usr/bin/python3\n\nimport sys\nimport json\nimport threading\n\nimport discord\nfrom discord.ext import commands\n\nfrom classes import IRCBot\n\n\n# Setup discord bot\ndiscord_bot = commands.Bot(\"**__\", None)\n\n# Load config\ntry:\n with open(\"config.json\", \"r\") as f:\n config = json.loads(f.read())\nexcept FileNotFoundError:\n print(\"Bot config file not found!\")\n sys.exit(-1)\n\n\n# Retrieve config data from dict\nTOKEN = config.get(\"TOKEN\")\nIRC_HOST = config.get(\"IRC_HOST\")\nIRC_PORT = config.get(\"IRC_PORT\", 6667)\nIRC_PASS = config.get(\"IRC_PASS\")\nIRC_NICK = config.get(\"IRC_NICK\")\nIRC_REAL = config.get(\"IRC_REAL\")\n\n\n# Setup IRC bot\nirc_bot = IRCBot(IRC_NICK, IRC_REAL, IRC_HOST, IRC_PORT)\nirc_bot.discord_bot = discord_bot\nirc_thread = threading.Thread(target=irc_bot.start)\nirc_thread.start()\n\n\n@discord_bot.event\nasync def on_ready():\n print(f\"Discord bot ready on {discord_bot.user}\")\n sys.stdout.flush()\n with open(\"channels.json\", \"r\") as file:\n binds = json.loads(file.read())\n for irc, dc in binds.items():\n try:\n await discord_bot.fetch_channel(int(dc))\n except discord.NotFound:\n try:\n user_profile = await discord_bot.fetch_user_profile(int(dc))\n except discord.HTTPException:\n print(f\"User or Channel `{dc}` is inaccessible\")\n continue\n user = user_profile.user\n await user.create_dm()\n\n\n@discord_bot.listen()\nasync def on_message(msg: discord.Message):\n await discord_bot.wait_until_ready()\n if msg.author != discord_bot.user:\n user_profile = await discord_bot.fetch_user_profile(msg.author.id)\n msg.author = user_profile.user\n print(f\"[DISCORD] <{msg.author} ({msg.author.id})> \\\"{msg.content}\\\"\")\n irc_bot.process_message(msg.channel, msg)\n\n\n@discord_bot.listen()\nasync def on_message_edit(_, after: discord.Message):\n await discord_bot.wait_until_ready()\n if after.author != discord_bot.user:\n user_profile = await discord_bot.fetch_user_profile(after.author.id)\n after.author = user_profile.user\n print(f\"[DISCORD] <{after.author} ({after.author.id})> \\\"{after.content}\\\"\")\n irc_bot.process_message(after.channel, after, content_prefix=\"*\")\n\ndiscord_bot.run(TOKEN)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"63022531","text":"import hashlib\nfrom scapy.all import IP, TCP, PcapReader, rdpcap, wrpcap\nfrom tcp_reliable.packet_helper import getPacketTimestamp, changeTimestamp, writePcap, genKey\n\n\nclass Extractor:\n def __init__(self, pcapConfig, BUFFER_SIZE):\n self.pcapConfig = pcapConfig\n self.BUFFER_SIZE = BUFFER_SIZE\n\n def extract(self):\n serverPcap = rdpcap(self.pcapConfig['CLIENT_PCAP_PATH_OUTPUT'])\n output = []\n lastTimestamp = 0\n serverPcap.sort(key=self.getKeySort)\n last_seq = 0\n limit = 0\n buff = [None]* self.BUFFER_SIZE\n sol = []\n for pkt in serverPcap:\n if pkt[TCP].dport == self.pcapConfig['CLIENT_PORT']:\n timestamp = getPacketTimestamp(pkt)[0]\n if timestamp == None:\n continue\n seq = pkt[TCP].seq\n\n if lastTimestamp != timestamp and limit < timestamp and seq!= last_seq:\n # if count >= 179 and count <= 281:\n # print('seq:', pkt[TCP].seq, 'timestamp', timestamp, 'value', timestamp%2,'last_tm:', lastTimestamp)\n # text+=str(timestamp%2)\n # print(\"seq:\", seq, \"timestamp:\", timestamp, \"bit:\", timestamp%2)\n output.append(timestamp%2)\n idx = self.getBufferIdx(seq)\n buff[idx] = timestamp%2\n # print(\"******\",len(sol)+1,\"***** seq\",seq,\"*****\",\"idx\",idx,\"******* bit:\",timestamp%2)\n if idx == 0 and timestamp%2 == 1:\n has_none = False\n for i in buff[1:]:\n if i == None:\n has_none = True\n if not has_none:\n sol.append(buff[1:])\n buff = [None]* self.BUFFER_SIZE\n lastTimestamp = timestamp\n limit = max(limit, timestamp)\n last_seq = seq\n\n return sol\n\n\n def getKeySort(self, pkt):\n seq = pkt[TCP].seq\n timestamp = getPacketTimestamp(pkt)[0]\n if timestamp == None:\n return int(str(seq)+'0')\n return int(str(timestamp)+str(seq))\n\n def genHashNumber(self, num):\n return int(hashlib.sha256(str(num).encode()).hexdigest(), base=16)\n\n def getBufferIdx(self, seq):\n return self.genHashNumber(seq) % self.BUFFER_SIZE\n\n\n\n# if __name__ == '__main__':\n# readMessage()","sub_path":"tcp_reliable/extractor.py","file_name":"extractor.py","file_ext":"py","file_size_in_byte":2501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"219086589","text":"# _*_ encoding:utf-8 _*_\nimport re, sys\nimport json\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n\ndef symbolFilter(patientSay):\n count = len(re.findall(u'\\uff0c|\\u3002|\\u3001|\\uff01|\\uff1b|\\u002c|\\u003b', patientSay))\n if count < 2 and patientSay.count(u\" \") > 1:\n return patientSay.replace(u\" \", u\",\")\n return patientSay\n\n\ndef delWJDecoction(lis):\n index = []\n\n delKeys = [\"温经汤\"]\n\n for x in range(len(lis)):\n for y in delKeys:\n if y in lis[x][0]:\n index.append(x)\n\n if len(index) > 0:\n for x in index:\n del lis[x]\n\n\ndef keysFilter(patientSay):\n patientSay = unicode(patientSay)\n while patientSay.find(u\"有无\") is not -1:\n tmp = patientSay[patientSay.find(u\"有无\"):]\n tmp = tmp[:tmp.find(u\":\") + 1]\n patientSay = patientSay.replace(tmp, \"\")\n patientSay = re.sub(u\"[\\u4e00-\\u9fa5]+情况:\", \"\", patientSay)\n return patientSay\n\n\ndef parseType(jsonData):\n res = \"none\"\n common = [u'饮食情况', u'二便情况', u'睡眠与情绪', u'身体感觉', u'妇科']\n six = [u'表相关', u'里相关', u'半表半里相关', u'水湿痰饮相关', u'食积相关', u'淤血相关']\n if jsonData.has_key(u'sheetData'):\n if len(jsonData[u'sheetData'][u'inquiryReport'][u'sections']) == 0:\n res = \"custom\"\n else:\n if jsonData[u'sheetData'][u'inquiryReport'][u'sections'][0][u'title'] in common:\n res = \"common\"\n elif jsonData[u'sheetData'][u'inquiryReport'][u'sections'][0][u'title'] in six:\n res = \"six\"\n else:\n res = \"custom\"\n else:\n res = \"custom\"\n return res\n\n\ndef getContent(jsonData):\n content = jsonData[u'content']\n if jsonData.has_key(u'sheetData'):\n if len(jsonData[u'sheetData'][u'inquiryReport'][u'sections']) > 0:\n exclude = u','.join(jsonData[u'sheetData'][u'inquiryReport'][u'sections'][0][u'answers'])\n content = content[:content.find(exclude)]\n return content\n\n\ndef nasitis(jsonData):\n strs = u','.join(jsonData[u'sheetData'][u'inquiryReport'][u'sections'][0][u'answers'])\n strs = u''.join(re.findall(u\":\\S+\\n\", strs))\n strs = re.sub(u\":\", u\"\", strs)\n strs = re.sub(u\"\\n\", u\",\", strs)\n patientSay = jsonData[u'sheetData'][u\"patientSay\"]\n return patientSay+u\";\"+strs\n\n\ndef specialFilter(data):\n\n if len(re.findall(u\",\\S{2,6}:|,\\S{2,6}:\", data)) >= 6:\n flag = False\n ready = [u'手脚冷热', u'咳嗽', u'饮水情况', u'睡眠状况', u'出汗情况', u'小便次数', u'大便颜色']\n\n res = data\n for x in ready:\n if x not in data:\n flag = True\n\n if flag:\n # for x in re.findall(u\"[^,|^,|^;|^;]+:[^,|^,|^;|^;]*无[^,|^,|^;|^;]*\", res):\n # for x in re.findall(u\"无\", res):\n # print x\n # return\n res = re.sub(u\"[^,|^,|^;|^;]+:[^,|^,|^;|^;]*无[^,|^,|^;|^;]*\", u\"\", res)\n res = re.sub(u\"[^,|^,|^;|^;]+:[无|否][,|,]\", u\"\", res)\n res = re.sub(u\"[^,|^,|^;|^;]+:没有\", u\"\", res)\n res = re.sub(u\"[^,|^,|^;|^;]+:以上皆无\", u\"\", res)\n res = re.sub(u\"身体部位疼痛:\", u\"\", res)\n # print res\n else:\n res = re.sub(u\"[^,]\\W{1,4}:正常|[^,]\\W{1,4}:好\", u\",\", res)\n res = re.sub(u\":有,|:有,\", u\",\", res)\n res = re.sub(u\"[^,]{1,4}:无,|,\", u\",\", res)\n res = re.sub(u\"冷热:\", u\"\", res)\n res = re.sub(u\":\", u\"\", res)\n res = res.replace(u\",,\", u\",\")\n\n return res\n else:\n return data\n\n\n# data = u'腹:以上皆无,不定时心慌(难受) 胸闷,捶胸按压 打嗝儿顿有舒服感;是否发烧:无,出汗:正常出汗(冬天稍活动后微微出汗、身上有潮润感也算出汗),主要出汗部位:正常,身体感觉:以上皆无,鼻子与呼吸:以上皆无,小便:正常(一天5-8次),咳嗽:偶尔咳嗽,有痰:有,哮喘:无,咽喉中是否有阻塞感:否,身体部位疼痛:后背疼痛、头痛,身体部位是否有浮肿(按压后皮肤凹陷不回弹为浮肿):以上皆无;胃部感觉:打嗝,大便次数:一天一次,大便颜色:黄,是否有以下情况:大便不爽,腹部感觉:以上皆无,容易口渴:否,喜欢喝:无偏好;容易心烦:是,胃口如何:一般,是否有以下情况:晨起刷牙有呕吐感,胸部感觉:闷,两胁(腋下至腰背区域)感觉:胀;睡眠是否有以下情况:打呼噜,精神状态:以上皆无,近一个月体重变化:无明显变化,变化范围±3斤;身体是否有以下情况:以上皆无,容易忘事:是,体态:偏胖,情绪波动变化:易怒,面色如何:正常'\n# data = u',近一个月体重变化:无明显变化;'\n# print data\n# print specialFilter(data)\n","sub_path":"apps/utils/symbolFilter.py","file_name":"symbolFilter.py","file_ext":"py","file_size_in_byte":5013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"57333329","text":"# -*- coding: utf-8 -*-\n# Einar Kivisalu, Riivo Mägi, Martin Talimets jt. TTY 04.2017\n\nimport os\nimport sys\nimport dlib\n#import glob\nimport configparser\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport exifread\n\nfrom flask import Flask, request\nfrom flask_restplus import Api, Resource, fields\nfrom werkzeug.contrib.fixers import ProxyFix\nimport base64\nimport io\n\nfrom random import randint\n#from time import clock\nfrom datetime import datetime\n\n#import skimage.io as io\n\nfrom scipy import misc\n#from skimage import filters#, color, io\nfrom skimage.color import rgb2gray\nfrom skimage.segmentation import felzenszwalb\n#from skimage.segmentation import mark_boundaries\nfrom skimage.exposure import histogram\n\n# structure for data fields that are returned as response json maessage\nclass Results:\n result = True\n dimensions = True\n color = True\n brightness = True \n photoAge = True\n faceQuantity = True\n faceCenter = True\n vertical = True\n eyesHeight = True\n straight = True\n mouthClosed = True\n faceNotSmall = True\n faceNotLarge = True\n background = True \n fileError = False\n\nif getattr(sys, 'frozen', False):\n template_folder = os.path.join(sys._MEIPASS, 'templates')\n app = Flask(__name__, template_folder=template_folder)\nelse:\n# template_folder = os.path.join(sys._MEIPASS, 'templates')\n app = Flask(__name__)\n\napp.wsgi_app = ProxyFix(app.wsgi_app)\napi = Api(app, version='1.0', title='Fototuvastus API',\n description='Meeskonnaprojekt: Fototuvastus',)\n\nns = api.namespace('detect', description='Face detection')\n\n#startTime = clock()\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\ndir = os.path.dirname(__file__)\npredictor_path = os.path.join(dir, 'shape_predictor_68_face_landmarks.dat')\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor(predictor_path)\n\n# checks whether photo dimensions are more than required minimum values\ndef checkPhotoDimensions(img):\n try:\n photoMinWidth = int(config['dimensions']['photoMinWidth'])\n photoMinHeight = int(config['dimensions']['photoMinHeight'])\n \n imageHeight = (img.shape[0]) \n imageWidth = (img.shape[1])\n return imageWidth >= photoMinWidth and imageHeight >= photoMinHeight\n except:\n return False\n\n# checks whether randomly selected pixels on the image are all grey \ndef is_color(img):\n try:\n pixelsCount = int(config['is_color']['pixelsCount'])\n r1,g1,b1 = 0,0,0\n if len(img.shape)==2:\n return False\n else:\n imageHeight = (img.shape[0])\n imageWidth = (img.shape[1])\n \n for x in range(pixelsCount): # random pixels from image\n randomX = randint(1,imageHeight-1)\n randomY = randint(1,imageWidth-1) \n r,g,b = img[randomX,randomY]\n r1 += r\n g1 += g\n b1 += b\n if r1 == g1 == b1: \n return False\n return True\n except:\n return False\n \n# checks whether image brightness falls within the allowed limits\ndef checkBrightness(img):\n try:\n minBrightness = int(config['brightness']['minBrightness'])\n maxBrightness = int(config['brightness']['maxBrightness']) \n meanBrightness = (np.mean(img))\n \n if minBrightness <= meanBrightness <= maxBrightness:\n return True\n else:\n return False\n except:\n return (\"error\", False) \n \n# reads the image creation date if image conatains EXIF data \ndef checkPhotoAge(data):\n try:\n allowedAge = float(config['photoAge']['allowedAge']) \n tags = exifread.process_file(data, details=False, stop_tag='EXIF DateTimeOriginal')\n dte = datetime.strptime(str(tags['EXIF DateTimeOriginal']), \"%Y:%m:%d %H:%M:%S\")\n return ((datetime.date(datetime.now()) - datetime.date(dte)).days) <= allowedAge\n except:\n return \"No EXIF data\"\n\n# checks that nose is on the image central axis \ndef checkFaceCenterToImage(img,shape):\n try:\n axeMinCoeff = float(config['faceCenter']['axeMinCoeff'])\n axeMaxCoeff = float(config['faceCenter']['axeMaxCoeff']) \n imageWidth = (len((img)[0]))\n axeCoeff = (imageWidth/shape.part(27).x) #nose upper point\n return axeMinCoeff <= axeCoeff <= axeMaxCoeff\n except:\n return False\n\n# checks that only one face is detected on the image \ndef checkFaceQuantity(dets):\n try:\n return len(dets) == 1\n except:\n return False\n\n# checks whether nose and chin are in on the same vertical axis\ndef checkFaceVerticalAxe(shape, detection):\n try:\n maxTiltLimit = float(config['faceVerticality']['maxTiltLimit'])\n chinBottomPoint = shape.part(8).x # (l6ug)\n noseUpperPoint = shape.part(27).x #ninajuur\n faceAxe = abs(chinBottomPoint - noseUpperPoint)/detection.width()\n return faceAxe <= maxTiltLimit\n except:\n return False \n \n# checks whether nose location is symmetric to the detected face central axis \ndef checkFaceStraight(shape):\n try:\n faceAssymmetryConstant = float(config['faceAssymmetry']['faceAssymmetryConstant']) \n leftSideDistance = shape.part(28).x-shape.part(1).x #Distance betveen nose and left side\n rightSideDistance = shape.part(15).x - shape.part(28).x ##Distance betveen nose and right side\n faceWeight = shape.part(15).x - shape.part(1).x\n faceAssymmetry = abs(leftSideDistance - rightSideDistance) \n faceStraightFactor = faceAssymmetry / faceWeight\n return faceStraightFactor <= faceAssymmetryConstant\n except:\n return False\n\n# checks whether the eye corners are within the allowed limits \ndef checkEyesHeight(img,shape):\n try:\n eyesMinHeight = float(config['eyesHeight']['eyesMinHeight'])\n eyesMaxHeight = float(config['eyesHeight']['eyesMaxHeight']) \n leftEyeLeftPoint = shape.part(36).y\n rightEyeRightPoint = shape.part(45).y\n eyesHeightLine = (leftEyeLeftPoint + rightEyeRightPoint)/2\n imageHeight = (img.shape[0]) \n eyesHeightFactor = (1-eyesHeightLine/imageHeight)\n return eyesMinHeight <= eyesHeightFactor <= eyesMaxHeight\n except:\n return False \n \n# checks whether the distance between lip coordinates is over the limit\ndef checkMouthClosed(shape, detection):\n try:\n mouthOpenLimit = float(config['mouthClosed']['mouthOpenLimit']) \n upperLipY= shape.part(66).y\n lowerLipY= shape.part(62).y\n mouthOpenFactor= (upperLipY-lowerLipY)/detection.height()\n return mouthOpenFactor <= mouthOpenLimit\n except:\n return False\n \n# checks whether there are color changes in the image upper coreners using Felzenszwalb method\ndef checkBackgroundObjects(img):\n try:\n upperRectangleHeight = float(config['backGround']['upperRectangleHeight'])\n upperRectangleWidth = float(config['backGround']['upperRectangleWidth'])\n outsideRectangleHeight = float(config['backGround']['outsideRectangleHeight'])\n outsideRectangleWidth = float(config['backGround']['outsideRectangleWidth'])\n scale = float(config['backGround']['scale'])\n sigma = float(config['backGround']['sigma'])\n min_size = int(config['backGround']['min_size'])\n img = rgb2gray(img)\n \n imageHeight = (img.shape[0]) \n imageWidth = (img.shape[1])\n \n\t\t#3 pixels from border\n img1 = img[3:int(imageHeight*outsideRectangleHeight), 3:int(imageWidth*outsideRectangleWidth)]\n img2 = img[3:int(imageHeight*upperRectangleHeight), 3:int(imageWidth*upperRectangleWidth)]\n img3 = img[3:int(imageHeight*outsideRectangleHeight), imageWidth-int(imageWidth*outsideRectangleWidth):int(imageWidth-3)]\n img4 = img[3:int(imageHeight*upperRectangleHeight), imageWidth-int(imageWidth*upperRectangleWidth):imageWidth-3]\n \n segments_fz1 = felzenszwalb(img1, scale, sigma, min_size)\n segments_fz2 = felzenszwalb(img2, scale, sigma, min_size)\n segments_fz3 = felzenszwalb(img3, scale, sigma, min_size)\n segments_fz4 = felzenszwalb(img4, scale, sigma, min_size)\n \n segmentsCount1 = (len(np.unique(segments_fz1)))\n segmentsCount2 = (len(np.unique(segments_fz2)))\n segmentsCount3 = (len(np.unique(segments_fz3)))\n segmentsCount4 = (len(np.unique(segments_fz4)))\n sumSegmentsCount = segmentsCount1 + segmentsCount2 + segmentsCount3 + segmentsCount4\n \n return sumSegmentsCount <=4 \n except:\n return False\n \n# checks whether the face size is not under the allowed limits\ndef checkFaceNotTooSmall(img, detection):\n try:\n faceSizeMinFactor = float(config['faceDimensions']['faceSizeMinFactor'])\n imageWidth = (len((img)[0]))\n faceSizeFactor = imageWidth/detection.width()\n return faceSizeFactor <= faceSizeMinFactor\n except:\n return False\n\n# checks whether the face size is not over the allowed limits\ndef checkFaceNotTooLarge(img, detection):\n try:\n faceSizeMaxFactor = float(config['faceDimensions']['faceSizeMaxFactor']) \n imageWidth = (len((img)[0]))\n faceSizeFactor = imageWidth/detection.width()\n return faceSizeFactor >= faceSizeMaxFactor\n except:\n return False\n \n# main detection function - calls to the 'check' functions to do the actual checking \ndef runDetect(data):\n result = Results() \n\n try:\n d2 = io.BytesIO(data)\n except:\n result.result = False\n result.fileError = True\n return result\n\n # Photo age\n result.photoAge = checkPhotoAge(d2)\n \n try:\n img = misc.imread(d2, False, 'RGB')\n d2.close()\n except:\n result.result = False\n result.fileError = True\n return result\n \n # Photo minimal dimensions\n result.dimensions = checkPhotoDimensions(img)\n \n # Photo has color, not grayscale\n result.color = is_color(img) #checkPhotoColor(img)\n \n # Photo brightness is OK\n result.brightness = checkBrightness(img)\n \n # Ask the detector to find the bounding boxes of each face. The 1 in the\n # second argument indicates that we should upsample the image 1 time. This\n # will make everything bigger and allow us to detect more faces.\n # Number of faces detected\n dets = detector(img, 1)\n \n # Background correct\n result.background = checkBackgroundObjects(img)\n \n # Face quantity\n result.facequantity = checkFaceQuantity(dets)\n\n for k, d in enumerate(dets): \n # Get the landmarks/parts for the face in box d.\n shape = predictor(img, d)\n\n # Face centering\n result.faceCenter = checkFaceCenterToImage(img,shape)\n \n # Face verticality\n result.vertical = checkFaceVerticalAxe(shape, d)\n \n # Face is straight\n result.straight = checkFaceStraight(shape)\n \n # Eyes height correct\n result.eyesHeight = checkEyesHeight(img,shape)\n \n # Mouth is closed\n result.mouthClosed = checkMouthClosed(shape, d)\n \n # Face not small\n result.faceNotSmall = checkFaceNotTooSmall(img,d) \n \n # Face not large\n result.faceNotLarge = checkFaceNotTooLarge(img,d)\n \n \n # Draw the face landmarks on the screen.\n if (result.background == False or result.brightness == False or\n result.color == False or result.dimensions == False or \n result.eyesHeight == False or result.faceCenter == False or\n result.faceNotLarge == False or result.faceQuantity == False or \n result.faceNotSmall == False or result.mouthClosed == False or\n result.photoAge == False or result.straight == False or \n result.vertical == False): \n result.result = False\n else:\n result.result = True\n \n return result.__dict__\n\n# currently unused\ndef main():\n dir = os.path.dirname(__file__)\n# do the image detection with all the image files on the specified path\n\"\"\"\n for f in glob.glob(os.path.join(dir, 'images',\"*.*\")):\n if extension == \".jpg\" or extension == \".jpeg\" or extension == \".png\" or extension == \".tif\" or extension == \".tiff\" or extension == \".bmp\":\n print(f)\n print(\"\\nProcessing file: {}\".format(f))\n img = misc.imread(f, False, 'RGB')\n runDetect(img)\n\"\"\"\n# generate base64 encoded text file from each image into the python code directory\n\"\"\"\n fi = open(f, \"rb\")\n data = fi.read()\n b64 = base64.b64encode(data)\n b64fn = os.path.splitext(os.path.basename(f))[0] + \".txt\"\n f2 = open(b64fn, \"wb\")\n f2.write(b64)\n fi.close()\n f2.close()\n\"\"\" \n\nresource_fields = api.model('Resource', {\n 'base64': fields.String,\n})\n\n@ns.route('/start')\nclass Detection(Resource):\n @ns.doc('Process image')\n @api.expect(resource_fields)\n def post(self):\n try:\n json_data = request.get_json(force=True)\n b64 = json_data['base64']\n data = base64.b64decode(b64)\n return runDetect(data)\n except:\n result = Results();\n result.result = False;\n result.fileError = True;\n return result.__dict__\n \nif __name__ == '__main__':\n app.run() #Comment this line in, for running on localhost\n# app.run(host=\"0.0.0.0\", port=int(\"80\"),)\n main()\n# timeLeft = (clock() - startTime) #arvutab kulunud aja\n","sub_path":"photoQualityChecker.py","file_name":"photoQualityChecker.py","file_ext":"py","file_size_in_byte":13712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"226301948","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: hideyuki.takase\r\n\"\"\"\r\n\r\nimport psycopg2\r\nimport re\r\nfrom collections import defaultdict\r\nimport math\r\nimport MeCab\r\nimport matplotlib.pyplot as plt\r\nfrom wordcloud import WordCloud\r\n\r\nunique_words = set()\r\nsegments_count = {}\r\nsegments_count = defaultdict(lambda: 0)\r\nresult_words = []\r\ntagger = MeCab.Tagger(\"-Ochasen\")\r\nresult_word_category = {}\r\nresult_word_category = defaultdict(lambda: 0)\r\n\r\ndoc1 = \"スポーツはサッカーと野球が好きなり\"\r\ndoc2 = \"スポーツは嫌いだけどバスケなら許す\"\r\ndoc3 = \"スポーツはサッカーがいいね!特にロベカルが最高だね\"\r\n\r\ndoc_all = [[\"doc1\", doc1], [\"doc2\", doc2], [\"doc3\", doc3]]\r\n\r\ndef morphological_Analysis(result_sql):\r\n for row in result_sql:\r\n unique_words = set()\r\n node = tagger.parseToNode(row[1])\r\n words_count = {}\r\n words_count = defaultdict(lambda: 0)\r\n\r\n while node:\r\n\r\n if node.feature.split(\",\")[0] == \"名詞\":\r\n words_count[node.surface] = words_count[node.surface] + 1\r\n # ある単語 tt が出現する文書の数 計算用\r\n unique_words.add(node.surface)\r\n node = node.next\r\n result_words.append([row[0],words_count])\r\n for i in unique_words:\r\n result_word_category[i] = result_word_category[i] + 1\r\n return result_words ,result_word_category\r\n\r\n\r\n# 各文書の単語の出現数\r\nresult = morphological_Analysis(doc_all)\r\n# 各文書の単語の出現数\r\ntf = result[0]\r\n# ある単語 tt が出現する文書の数\r\ndf = result[1]\r\n# 全文章数 N\r\nN = int(len(doc_all))\r\n\r\n# ある単語 tt のIDF値\r\nidf = {}\r\nfor k, v in df.items():\r\n idf[k] = math.log((N/v)) + 1\r\n\r\ntf_idf = []\r\ntf_idf_dict = {}\r\n# TF-IDFを計算\r\nfor x in tf:\r\n tf_idf_dict = {}\r\n for kk, vv in x[1].items():\r\n tf_idf_dict[kk] = vv * idf[kk] \r\n tf_idf.append([x[0], tf_idf_dict])\r\n\r\nfor res in tf_idf:\r\n print(res[0])\r\n for kkk,vvv in res[1].items():\r\n print(kkk, vvv)\r\n","sub_path":"tf-idf_mecab_base.py","file_name":"tf-idf_mecab_base.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"280472852","text":"# example\n# python lines_geojson.py --filename ak_alaska_zip_codes_geo.min.json.lines\n# creates ak_alaska_zip_codes_geo.min.json.lines.geojson\nimport os\nimport argparse\nimport json\n\ndef main(filename):\n features = []\n with open(filename) as f:\n for line in f:\n features.append(json.loads(line))\n geojson = {\n \"type\": \"FeatureCollection\",\n \"features\": features\n }\n with open(filename+\".geojson\", \"w\") as f:\n json.dump(geojson, f)\n\nif __name__ == \"__main__\":\n main_parser = argparse.ArgumentParser()\n main_parser.add_argument(\"--filename\", type=str, help=\"name of geojson file to turn into lines\")\n args = main_parser.parse_args()\n main(args.filename)\n","sub_path":"lines_geojson.py","file_name":"lines_geojson.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"422056018","text":"import os, sys, time\nimport numpy as np\nfrom inject_CPD import inject_CPD\nfrom frank.geometry import FixedGeometry\nfrom frank.radial_fitters import FrankFitter\nfrom frank.io import save_fit\nimport diskdictionary as disk\n\n\n# specify target disk and gap\ntarget = 'RULup'\t# CSD name\ngap_ix = 0\t\t# which gap CPD is in (based on dict list)\nsubsuf = '0'\t\t# suffix to attach to records (if partial work)\n\n\n# specify mock parameters\nF_cpd = np.arange(0.25, 0.00, -0.01) # in mJy\nn_mocks_per_F = 500 \t\t\t # number of mocks per flux bin\n\n\n# -------\n\n\n# fixed geometric parameters of CSD\nincl, PA = disk.disk[target]['incl'], disk.disk[target]['PA']\noffRA, offDEC = disk.disk[target]['dx'], disk.disk[target]['dy']\ngeom = FixedGeometry(incl, PA, dRA=offRA, dDec=offDEC)\n\n# frank setup\nRmax, Ncoll = 2 * disk.disk[target]['rout'], disk.disk[target]['hyp-Ncoll']\nalpha, wsmth = disk.disk[target]['hyp-alpha'], disk.disk[target]['hyp-wsmth']\nFF = FrankFitter(Rmax=Rmax, N=Ncoll, geometry=geom, alpha=alpha, \n weights_smooth=wsmth)\n\n# load the visibility data\ndat = np.load('data/'+target+'_data.vis.npz')\nu, v, vis, wgt = dat['u'], dat['v'], dat['Vis'], dat['Wgt']\n\n\n\n# loop through mock injection and modeling \nos.system('rm -rf '+target+'_gap'+str(gap_ix)+'_mpars.'+subsuf+'.txt')\n\n# for each CPD flux bin\nt0 = time.time()\nfor i in range(len(F_cpd)):\n\n # assign random radii and azimuths for mock CPDs (in disk plane)\n rgap_cen = disk.disk[target]['rgap'][gap_ix]\n gap_span = 0.5 * disk.disk[target]['wgap'][gap_ix]\n r_cpd = np.random.uniform(rgap_cen - gap_span, rgap_cen + gap_span, \n n_mocks_per_F)\n az_cpd = np.random.randint(-180, 180, n_mocks_per_F)\n\n\n # for each mock in that CPD flux bin\n for j in range(n_mocks_per_F):\n\n # bookkeeping\n file_suffix = '_F'+str(np.int(np.round(1e3*F_cpd[i]))) + \\\n 'uJy_'+str(j).zfill(4)\n\n # inject a mock CPD into the data\n vis_cpd = inject_CPD((u, v, vis, wgt), (F_cpd[i], r_cpd[j], az_cpd[j]),\n incl=incl, PA=PA, offRA=offRA, offDEC=offDEC)\n\n # frank modeling of the data + CPD injection\n sol = FF.fit(u, v, vis_cpd, wgt)\n\n # save the frank results\n save_fit(u, v, vis_cpd, wgt, sol, \n prefix=target+'_gap'+str(gap_ix)+file_suffix,\n save_vis_fit=False, save_solution=False)\n\n # clean up file outputs\n os.system('mv '+target+'_gap'+str(gap_ix)+file_suffix + \\\n '_frank_uv_resid.npz resid_vis/')\n os.system('mv '+target+'_gap'+str(gap_ix)+file_suffix + \\\n '_frank_profile_fit.txt mprofiles/')\n os.system('rm '+target+'_gap'+str(gap_ix)+file_suffix+'_frank*')\n\n # record parameter values (F_cpd in uJy, j, r_cpd, az_cpd)\n with open(target+'_gap'+str(gap_ix)+'_mpars.'+subsuf+'.txt', 'a') as f:\n f.write('%i %s %.3f %i\\n' % \\\n (np.int(np.round(1e3*F_cpd[i])), str(j).zfill(4), \n r_cpd[j], az_cpd[j]))\n\nprint(time.time() - t0)\n","sub_path":"CPD_search/RULup_gap0_injectloop.py","file_name":"RULup_gap0_injectloop.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"462863552","text":"#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-\n\nimport os, shutil\nfrom os import path\nfrom collections import namedtuple\n\nfrom bes.system.check import check\nfrom bes.archive.archiver import archiver\nfrom bes.archive.archive_extension import archive_extension\nfrom bes.fs.file_util import file_util\nfrom bes.fs.tar_util import tar_util\nfrom bes.fs.temp_file import temp_file\nfrom bes.system.execute import execute\nfrom bes.system.log import log\nfrom bes.url import url_util\n\nfrom rebuild.binary_format.binary_detector import binary_detector\n\nclass ingest_util(object):\n\n @classmethod\n def download_binary(clazz, url, filename, binary_arc_name):\n 'Download a single binary exe and package it into a tarball with sanity checking.'\n if not archive_extension.is_valid_filename(filename):\n raise RuntimeError('filename should be an archive: %s' % (filename))\n tmp = url_util.download_to_temp_file(url)\n if not binary_detector.is_executable(tmp):\n file_util.remove(tmp)\n raise RuntimeError('not an executable: %s' % (url))\n os.chmod(tmp, 0o755)\n empty_dir = temp_file.make_temp_dir()\n archiver.create(filename, empty_dir, extra_items = [ archiver.item(tmp, binary_arc_name) ] )\n file_util.remove(tmp)\n \n @classmethod\n def download_archive(clazz, url, filename = None):\n 'Download an archive with sanity checking it is indeed a valid tarball type.'\n filename = filename or url_util.url_path_baename(url)\n if not archive_extension.is_valid_filename(filename):\n raise RuntimeError('filename should be a valid archive name.')\n tmp_dir = temp_file.make_temp_dir()\n tmp = path.join(tmp_dir, filename)\n url_util.download_to_file(url, tmp)\n if not archiver.is_valid(tmp):\n file_util.remove(tmp)\n raise RuntimeError('not a valid archive: %s' % (url))\n os.chmod(tmp, 0o644)\n file_util.rename(tmp, filename)\n\n @classmethod\n def archive_binary(clazz, executable_filename, archive_filename, arcname, debug = False):\n 'Archive the given the executable_filename into archive_filename and return a tmp file with the result.'\n if not binary_detector.is_executable(executable_filename):\n raise RuntimeError('not an executable: %s' % (executable_filename))\n if not archive_extension.is_valid_filename(archive_filename):\n raise RuntimeError('not a valid archive filename: %s' % (archive_filename))\n if not file_util.is_basename(archive_filename):\n raise RuntimeError('archive_filename should be a filename not a path: %s' % (archive_filename))\n tar_dir = temp_file.make_temp_dir(delete = not debug)\n arcname = arcname or path.join('bin', path.basename(executable_filename))\n dst_file = path.join(tar_dir, arcname)\n file_util.copy(executable_filename, dst_file)\n os.chmod(dst_file, 0o755)\n tmp_dir = temp_file.make_temp_dir(delete = not debug)\n tmp_archive_filename = path.join(tmp_dir, archive_filename)\n tar_util.create_deterministic_tarball(tmp_archive_filename, tar_dir, arcname, '2018-12-08')\n file_util.remove(tar_dir)\n return tmp_archive_filename\n\n @classmethod\n def fix_executable(clazz, executable_filename, debug = False):\n '''\n Fix the mode, atime and mtime of an executable so when it is included in a tarball\n the checksum will be deterministic.\n '''\n tmp_dir = temp_file.make_temp_dir(delete = not debug)\n tmp_executable_filename = path.join(tmp_dir, path.basename(executable_filename))\n file_util.copy(executable_filename, tmp_executable_filename)\n os.chmod(tmp_executable_filename, 0o755)\n os.utime(tmp_executable_filename, ( 1544487203, 1544486779 )) # a random date on 12/2018\n return tmp_executable_filename\n\n _ingest_result = namedtuple('_ingest_result', 'success, reason')\n \n @classmethod\n def ingest_url(clazz, url, ingested_filename, arcname, checksum, storage, http_cache,\n cookies = None, dry_run = False, debug = False):\n check.check_string(url)\n check.check_string(ingested_filename)\n if arcname:\n check.check_string(arcname)\n if checksum:\n check.check_string(checksum)\n clazz.log_d('ingest_url: url=%s; arcname=%s; cookies=%s' % (url, arcname, cookies))\n local_filename = http_cache.get_url(url, checksum, cookies = cookies, debug = debug)\n clazz.log_d('ingest_url: downloaded remote url %s => %s' % (url, local_filename))\n if not local_filename:\n return clazz._ingest_result(False, 'failed: could not download: %s' % (url))\n if checksum:\n local_checksum = file_util.checksum('sha256', local_filename)\n if local_checksum != checksum:\n return clazz._ingest_result(False, 'failed: url checksum does not match: %s' % (url))\n properties = { 'rebuild.ingestion_url': url }\n return clazz.ingest_file(local_filename, ingested_filename, arcname, storage,\n properties = properties, dry_run = dry_run, debug = debug)\n \n @classmethod\n def ingest_file(clazz, local_filename, ingested_filename, arcname, storage, properties = {}, dry_run = False, debug = False):\n check.check_string(local_filename)\n check.check_string(ingested_filename)\n if arcname:\n check.check_string(arcname)\n if properties:\n check.check_dict(properties)\n clazz.log_d('ingest_file: local_filename=%s; ingested_filename=%s; arcname=%s; storage=%s' % (local_filename,\n ingested_filename,\n arcname,\n str(storage)))\n if not path.isfile(local_filename):\n return clazz._ingest_result(False, 'file not found: %s' % (local_filename))\n\n remote_basename = path.basename(ingested_filename)\n \n is_valid_archive = archiver.is_valid(local_filename)\n is_exe = binary_detector.is_executable(local_filename)\n clazz.log_d('ingest_file: is_valid_archive=%s; is_exe=%s' % (is_valid_archive, is_exe))\n if not (is_valid_archive or is_exe):\n return clazz._ingest_result(False, 'content to ingest should be an archive or executable: %s' % (local_filename))\n\n tmp_files_to_cleanup = []\n def _cleanup_tmp_files():\n if not debug:\n file_util.remove(tmp_files_to_cleanup)\n\n # if local_filename is an executable, archive into a tarball first\n if is_exe:\n local_filename = clazz.fix_executable(local_filename, debug = debug)\n clazz.log_d('ingest_file: fixed executable: %s' % (local_filename))\n tmp_files_to_cleanup.append(local_filename)\n clazz.log_d('ingest_file: calling archive_binary(%s, %s, %s)' % (local_filename, remote_basename, arcname))\n local_filename = clazz.archive_binary(local_filename, remote_basename, arcname, debug = debug)\n clazz.log_d('ingest_file: calling archive_binary() returns %s' % (local_filename))\n tmp_files_to_cleanup.append(local_filename)\n\n remote_checksum = storage.remote_checksum(ingested_filename)\n local_checksum = file_util.checksum('sha256', local_filename)\n clazz.log_d('ingest_file: ingested_filename=%s; remote_checksum=%s; local_checksum=%s' % (ingested_filename, remote_checksum, local_checksum))\n if remote_checksum == local_checksum:\n _cleanup_tmp_files()\n return clazz._ingest_result(True, 'a file with checksum %s already exists: %s' % (local_checksum, ingested_filename))\n if remote_checksum is not None and remote_checksum != local_checksum:\n _cleanup_tmp_files()\n msg = '''trying to re-ingest a with a different checksum.\n local_filename: %s\n local_checksum: %s\nremote_checksum: %s''' % (local_filename, local_checksum, remote_checksum)\n return clazz._ingest_result(True, msg)\n if dry_run:\n return clazz._ingest_result(True, 'dry-run: would upload %s => %s' % (local_filename, ingested_filename))\n \n try:\n clazz.log_d('ingest_file: calling upload: local_filename=%s; ingested_filename=%s; ' % (local_filename, ingested_filename))\n if not storage.upload(local_filename, ingested_filename, local_checksum):\n return clazz._ingest_result(False, 'Failed to upload. Something went wrong. FIXME: should delete the remote file.')\n clazz.log_d('ingest_file: successfully uploaded: %s' % (ingested_filename))\n try:\n properties_rv = storage.set_properties(ingested_filename, properties)\n except Exception as ex:\n properties_rv = None\n print('CAUGHT exception setting properties for {}: {}'.format(ingested_filename, str(ex)))\n if not properties_rv:\n return clazz._ingest_result(False, 'Failed to set properties. Something went wrong. FIXME: should delete the remote file.')\n finally:\n _cleanup_tmp_files()\n \n return clazz._ingest_result(True, 'successfully ingested %s' % (local_filename))\n\n @classmethod\n def _download_to_tmp_file(clazz, url, cookies, debug = False):\n 'Download url to tmp file.'\n import requests\n tmp = temp_file.make_temp_file(delete = not debug)\n clazz.log_d('_download_to_tmp_file: url=%s; tmp=%s' % (url, tmp))\n response = requests.get(url, stream = True, cookies = cookies or None)\n clazz.log_d('_download_to_tmp_file: status_code=%d' % (response.status_code))\n if response.status_code != 200:\n return None\n with open(tmp, 'wb') as fout:\n shutil.copyfileobj(response.raw, fout)\n fout.close()\n return tmp\n \nlog.add_logging(ingest_util, 'ingest_util')\n","sub_path":"lib/rebuild/source_ingester/ingest_util.py","file_name":"ingest_util.py","file_ext":"py","file_size_in_byte":9587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"71592275","text":"a=int(input())\nl=[]\nm=0\nwhile a>0:\n b=a%10\n a=a//10\n l.append(b)\nfor key,value in enumerate(l[::-1]):\n if l.count(key)==value:\n m+=1\nif len(l)==m:\n print(True)\nelse:\n print(False)\n \n \n","sub_path":"auto.py","file_name":"auto.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"248972539","text":"__author__ = 'Michal Gebarowski'\n\nimport tkinter\nfrom kml_generator.generator import KMLGenerator\n\n\nclass View:\n\n def __init__(self):\n root = tkinter.Tk()\n root.geometry('{}x{}'.format(230, 90))\n root.title(\"KMLGen\")\n label_general = tkinter.Label(root, text=\"Choose CSV file and generate KML\").pack()\n btn_generate = tkinter.Button(root, text=\"Generate KML\", command=KMLGenerator.generate_kml).pack(padx=5, pady=20,side='right')\n btn_browse = tkinter.Button(root, text=\"Browse\", command=KMLGenerator.read_csv).pack(padx=5, pady=20,side='right')\n btn_help = tkinter.Button(root, text=\"Help\", command=KMLGenerator.help).pack(padx=5, pady=20, side='right')\n root.resizable(False, False)\n root.mainloop()\n","sub_path":"kml_generator/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"454464327","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/11/15 14:03\n# @Author : Zihao.Liu\nimport copy\nfrom app.main.steel_factory.rule.create_load_task_rule import create_load_task\nfrom app.main.steel_factory.rule.layer_filter_rule import layer_filter\nfrom app.util.enum_util import DispatchType, LoadTaskType\nfrom app.util.generate_id import GenerateId\n\n\ndef dispatch_filter(load_task_list, stock_dic):\n \"\"\"\n 分货规则\n :param stock_dic:\n :param load_task_list:\n :return:\n \"\"\"\n tail_list = stock_dic['tail']\n huge_list = stock_dic['huge']\n lock_list = stock_dic['lock']\n stock_list = tail_list + huge_list\n # 甩货列表\n surplus_stock_dict = dict()\n # 转换字典\n stock_dict = {i.stock_id: i for i in stock_list}\n # 优先考虑急发特殊货物\n general_stock_dict = layer_filter(stock_dict, load_task_list, DispatchType.FIRST)\n # 剩余优先考虑急发特殊货物生成车次,走29吨包车运输\n for k, v in copy.copy(general_stock_dict).items():\n if v.sort == 1:\n load_task_list.append(create_load_task([v], GenerateId.get_id(), LoadTaskType.TYPE_1.value))\n general_stock_dict.pop(k)\n # 剩余货物走正常流程\n if general_stock_dict:\n # 目标货物整体分\n first_surplus_stock_dict = layer_filter(general_stock_dict, load_task_list, DispatchType.SECOND)\n # 目标货物拆散分\n surplus_stock_dict = layer_filter(first_surplus_stock_dict, load_task_list, DispatchType.THIRD)\n # 锁住的货物依次生成车次\n for i in lock_list:\n load_task_list.append(create_load_task([i], GenerateId.get_id(), LoadTaskType.TYPE_1.value))\n return surplus_stock_dict\n","sub_path":"app/main/steel_factory/rule/dispatch_filter.py","file_name":"dispatch_filter.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"635316528","text":"# coding:utf-8\n# 17 https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/\nfrom typing import List\n\nclass Solution:\n\n def letterCombinations(self, digs) -> List[str]:\n \"\"\"\n input: \"23\"\n output: [\"ad\", \"ae\", \"af\", \"bd\", \"be\", \"bf\", \"cd\", \"ce\", \"cf\"]\n \"\"\"\n\n maps = {\n '2' : 'abc',\n '3' : 'def',\n '4' : 'ghi',\n '5' : 'jkl',\n '6' : 'mno',\n '7' : 'pqrs',\n '8' : 'tuv',\n '9' : 'wxyz'\n }\n\n letters = [list(maps.get(n)) for n in digs if n in maps]\n if not letters:\n return []\n res = []\n self.helper(0, len(digs), letters, [], res)\n return res\n \n def helper(self, level, size, letters, curs, res):\n\n if len(curs) == size:\n res.append(''.join(curs))\n return \n\n for ch in letters[level]:\n self.helper(level + 1, size, letters, curs + [ch], res)\n\nif __name__ == '__main__':\n obj = Solution()\n input = ''\n res = obj.letterCombinations(input)\n print(res)\n","sub_path":"suqing/fuckal/python/recursive/letter-combinations-of-a-phone-number.py","file_name":"letter-combinations-of-a-phone-number.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"602187928","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F \nimport torch.backends.cudnn as cudnn\n\nimport torchvision\nimport torchvision.transforms as transforms\n\nimport numpy as np \nimport matplotlib.pyplot as plt \nimport matplotlib.pylab as plt2\nimport os\n\nfrom resnet50 import ResNet50\nfrom resnet34 import ResNet34\n\n#Check GPU, connect to it if it is available \ndevice = ''\nif torch.cuda.is_available():\n\tdevice = 'cuda'\n\tprint(\"CUDA is available. GPU will be used for testing.\")\nelse:\n\tdevice = 'cpu'\n\n\nBEST_ACCURACY = 0\n\n# Preparing Data\nprint(\"==> Prepairing data ...\")\n#transformation on validation data\ntransform_validation = transforms.Compose([\n\ttransforms.ToTensor(),\n\ttransforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n\t])\n\n#Download Validation data and apply transformation\nvalidation_data = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_validation)\n\n#Put data into loader, specify batch_size\nvalidation_loader = torch.utils.data.DataLoader(validation_data, batch_size=100, shuffle=True, num_workers=2)\n\nclasses = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\n#Function to show CIFAR images\ndef show_data(image):\n\tplt.imshow(np.transpose(image[0], (1, 2, 0)), interpolation='bicubic')\n\tplt.show()\n\n\nmodel = ResNet50()\n#model = ResNet34()\nmodel = model.to(device)\nprint(\"Upload the model ...\")\nassert os.path.isdir('checkpoint'), 'Error: no checkpoint directory found!'\nmodel.load_state_dict(torch.load('./checkpoint/resnet50.pth'))\nmodel.eval()\n\n\ndef accuracy(output, target, topk=(1,)):\n\t\"\"\"Computes the precision@k for the specified values of k\"\"\"\n\tmaxk = max(topk)\n\t\n\t_, pred = output.topk(maxk, 1, True, True)\n\tpred = pred.t()\n\tcorrect = pred.eq(target.view(1, -1).expand_as(pred))\n\t\n\tres = []\n\tfor k in topk:\n\t correct_k = correct[:k].view(-1).float().sum(0)\n\t res.append(correct_k)\n\treturn res\n\ndef test():\n\tmodel.eval()\n\twith torch.no_grad():\n\t\taccuracy1 = 0\n\t\taccuracy5 = 0\n\t\tfor x,y in validation_loader:\n\t\t\tx, y = x.to(device), y.to(device)\n\t\t\tmodel.eval()\n\t\t\tyhat = model(x)\n\t\t\tyhat = yhat.reshape(-1, 10)\n\t\t\ta1, a5 = accuracy(yhat, y, topk=(1,5))\n\t\t\taccuracy1 += a1 \n\t\t\taccuracy5 += a5\n\n\t\treturn (accuracy1/len(validation_data)).item(), (accuracy5/(len(validation_data))).item()\n\n\nacc1, acc5 = test()\n\nprint(\"--------------------------\")\nprint(\"| ResNet50 |\")\nprint(\"--------------------------\")\nprint(\"| TOP1 Accuracy:\", format(100*acc1, '.4f'), \"|\")\nprint(\"| TOP5 Accuracy:\", format(100*acc5, '.4f'), \"|\")\nprint(\"--------------------------\\n\")\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"373509510","text":"#Algorithm for priority scheduling\nn=int(input(\"Enter the number of processess\"));\nprocess=[];\nat=[];\npriority=[];\ntemp1=0;\ntemp2=0;\nfor i in range(n):\n process.append(i);\n print(\"Processess are\",\"p[\",process[i],\"]\");\nfor i in range(n):\n x=int(input(\"Enter the burst time\"));\n at.append(x);\nfor i in range (n):\n y=int(input(\"Enter the priority\"));\n priority.append(y);\nfor i in range(0,len(process)):\n for j in range(i,len(process)):\n if priority[i] BGR\n img = img.astype(np.float64)\n img -= self.mean_bgr\n # img /= self.std_bgr\n img = img.transpose(2, 0, 1)\n img = torch.from_numpy(img).float()\n lbl = torch.from_numpy(lbl).long()\n return img, lbl\n\n def untransform(self, img, lbl):\n img = img.numpy()\n img = img.transpose(1, 2, 0)\n # img *= self.std_bgr\n img += self.mean_bgr\n img = img.astype(np.uint8)\n img = img[:, :, ::-1]\n # convert to color lbl\n # lbl = self.label_to_color_image(lbl)\n lbl = lbl.astype(np.uint8)\n return img, lbl\n\n def label_to_color_image(self, lbl):\n return label2rgb(lbl)\n\n def random_crop(self, img, lbl, size):\n h, w = lbl.shape\n th, tw = size\n if w == tw and h == th:\n return img, lbl\n x1 = random.randint(0, w-tw)\n y1 = random.randint(0, h-th)\n img = img[y1:y1+th, x1:x1+tw, :]\n lbl = lbl[y1:y1+th, x1:x1+tw]\n return img, lbl\n\n def random_flip(self, img, lbl):\n if random.random() < 0.5:\n return np.flip(img, 1).copy(), np.flip(lbl, 1).copy()\n return img, lbl\n\n\n# For code testing\nif __name__ == \"__main__\":\n root = '/home/dg/Dropbox/Datasets/SUNRGBD'\n dataset = SUNSeg(root, split='train', dataset='o', transform=True)\n img, lbl = dataset.__getitem__(501)\n img, lbl = dataset.untransform(img, lbl)\n plt.subplot(211)\n plt.imshow(img)\n plt.subplot(212)\n plt.imshow(lbl)\n plt.show()\n","sub_path":"datasets/SUNRGBD_Dataloader.py","file_name":"SUNRGBD_Dataloader.py","file_ext":"py","file_size_in_byte":6290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"48237095","text":"\"\"\"\n This file is part of sik.\n\n sik is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n sik is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with sik. If not, see .\n\"\"\"\n\n__all__ = ['Font']\n\n# python\nimport weakref\n# sik\nfrom .api import *\nfrom .api_utilities import *\nfrom .texture import *\nfrom .utilities import *\n\nclass FontCharacters:\n\n def __init__(self, font):\n self.font = font\n \n def __getitem__(self, key):\n *slice, is_slice = slicify(key, len(self))\n result = self._slice(*slice)\n if is_slice:\n return result\n else:\n return list(result)[0]\n \n def __iter__(self):\n return self._slice(0, len(self), 1)\n \n def __len__(self):\n count = c_size_t()\n sik_font_character_count(self.font._font, byref(count))\n return count.value\n \n def __str__(self):\n return str(list(self))\n \n def _slice(self, start, stop, step):\n character = SikFontCharacter()\n for i in range(start, stop, step):\n sik_font_character(self.font._font, i, byref(character))\n yield (\n character.encoding.value,\n character.left,\n character.top,\n character.right,\n character.bottom,\n character.breaks\n )\n\nclass Font:\n \n __slots__ = ['_font', '__weakref__']\n\n def __init__(\n self,\n line_height,\n texture,\n characters,\n fallback_character_index=0\n ):\n if line_height < 1:\n raise ValueError('line_height must be greater than 0')\n if not characters:\n raise ValueError('Font must have characters')\n if (fallback_character_index < 0 or \n fallback_character_index >= len(characters)):\n raise IndexError('fallback_character_index out of range')\n # convert characters\n characters = (SikFontCharacter * len(characters))(*[\n SikFontCharacter(encoding, left, top, right, bottom, breaks)\n for encoding, left, top, right, bottom, breaks\n in characters\n ])\n # create the font\n font = POINTER(SikFont)()\n sik_font_create(\n byref(font),\n line_height,\n texture._texture,\n cast(byref(characters), POINTER(SikFontCharacter)),\n len(characters),\n fallback_character_index\n )\n self._font = font\n \n def __copy__(self):\n return self._from_c(self._font)\n \n def __deepcopy__(self, memo):\n raise NotImplementedError()\n \n def __del__(self):\n if hasattr(self, \"_font\") and self._font:\n sik_font_decref(self._font)\n \n def __eq__(self, other):\n try:\n return (\n addressof(self._font.contents) == \n addressof(other._font.contents)\n )\n except AttributeError:\n return False\n \n @classmethod\n def _from_c(cls, font_ptr):\n if font_ptr:\n font = cls.__new__(cls)\n sik_font_incref(font_ptr)\n try:\n font._font = POINTER(SikFont)(font_ptr.contents)\n except:\n sik_font_decref(font_ptr)\n raise\n return font\n return None\n \n @classmethod\n def _to_c(cls, font):\n if font is None:\n return None\n else:\n return font._font\n \n def _get_characters(self):\n return FontCharacters(self)\n characters = property(_get_characters)\n \n def _get_line_height(self):\n return self._font.contents.line_height\n line_height = property(_get_line_height)\n \n def _get_texture(self):\n return Texture._from_c(self._font.contents.texture)\n texture = property(_get_texture)\n ","sub_path":"py/sik_/font.py","file_name":"font.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"146527556","text":"# Write an efficient algorithm that searches for a value in an m x n matrix.\n# This matrix has the following properties:\n\n# Integers in each row are sorted from left to right.\n# The first integer of each row is greater than the last integer of the previous\n# row.\n\n# For example,\n\n# Consider the following matrix:\n\n# [\n# [1, 3, 5, 7],\n# [10, 11, 16, 20],\n# [23, 30, 34, 50]\n# ]\n# Given target = 3, return true.\n\ndef bin_search_mat(matrix, target):\n m = len(matrix)\n n = len(matrix[0])\n st, ed = 0, m * n\n while st < ed:\n mid = st + ((ed - st) >> 1)\n r, c = mid / n, mid % n\n if matrix[r][c] < target:\n st = mid + 1\n elif matrix[r][c] > target:\n ed = mid\n else:\n return True\n return False\n\nclass Solution(object):\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n if len(matrix) < 1:\n return False\n return bin_search_mat(matrix, target)\n","sub_path":"Search2DMatrix.py","file_name":"Search2DMatrix.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"571437978","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 ('core', '0005_currentcoctailset'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='CurrentPumpSet',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)),\n ('pump1', models.ForeignKey(null=True, related_name='pump1', blank=True, to='core.Beverage')),\n ('pump2', models.ForeignKey(null=True, related_name='pump2', blank=True, to='core.Beverage')),\n ('pump3', models.ForeignKey(null=True, related_name='pump3', blank=True, to='core.Beverage')),\n ],\n ),\n ]\n","sub_path":"core/migrations/0006_currentpumpset.py","file_name":"0006_currentpumpset.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"506474767","text":"import numpy as np\nimport sys\nimport pickle\nimport argparse\n\nfrom multiprocessing import Pool, cpu_count\nfrom scipy import interpolate\nfrom pathlib import Path\nt\nfrom src.modules.helper_functions import get_time, get_project_root, load_pickle_mask, get_indices_from_fraction, read_pickle_data, calc_perf2_as_fn_of_energy, calc_bin_centers, get_n_tot_pickles, get_n_events_per_dir, flatten_list_of_lists\nfrom src.modules.eval_funcs import get_retro_crs_prefit_relE_error\nfrom src.modules.reporting import make_plot\n\ndescription = 'Calculates weights for a dataset.'\nparser = argparse.ArgumentParser(description=description)\nparser.add_argument('-d', '--dev', action='store_true', help='Initiates developermode - weights are not saved, and only weights for a small subset of the dataset is calculated')\nparser.add_argument('--from_frac', default=0.8, type=float, help='Sets the lower bound for amount of data used to calculate interpolator.')\nparser.add_argument('--to_frac', default=1.0, type=float, help='Sets the upper bound for amount of data used to calculate interpolator.')\nparser.add_argument('--name', nargs='+', type=str, help='Sets the kind of weights to calculate.')\n\nargs = parser.parse_args()\n\nN_BINS_WEIGHTS = 24\nPRINT_EVERY = 100000\n\ndef assign_energy_weights_multiprocess(masks, dataset_path, interpolator_quadratic, true_key='true_primary_energy', debug=False):\n available_cores = cpu_count()\n n_tot = get_n_tot_pickles(dataset_path)\n \n # * Create packs - loop over all events\n # * Get mask\n\n mask_all = np.array(load_pickle_mask(dataset_path, masks))\n if debug:\n mask_all = mask_all[:1000]\n chunks = np.array_split(mask_all, available_cores)\n interpolator_list = [interpolator_quadratic]*len(chunks)\n keys_list = [true_key]*len(chunks)\n paths = [dataset_path]*len(chunks)\n n_per_dir_list = [get_n_events_per_dir(dataset_path)]*len(chunks)\n subprocess_id = list(range(available_cores))\n packed = zip(chunks, interpolator_list, keys_list, paths, n_per_dir_list, subprocess_id)\n \n # * Multiprocess and recombine\n with Pool(available_cores) as p:\n weights = p.map(calc_weights_multiprocess, packed)\n weights_combined = flatten_list_of_lists(weights)\n \n # * Make a list of weights - put nan where mask didn't apply\n weights_list = np.array([np.nan]*n_tot)\n weights_list[mask_all] = np.array(weights_combined)\n\n return weights_list\n\ndef calc_weights_multiprocess(pack):\n indices, interpolator, key, path, n_per_dir, subprocess_id = pack\n \n weights =[-1]*len(indices)\n n_indices = len(indices)\n for i_index, index in enumerate(indices):\n # * Check each file.\n full_path = path+'/pickles/'+str(index//n_per_dir)+'/'+str(index)+'.pickle'\n \n event = pickle.load(open(full_path, \"rb\" ))\n energy = event['raw']['true_primary_energy']\n weights[i_index] = interpolator(energy)\n \n if (i_index)%PRINT_EVERY == 0:\n print(get_time(), 'Subprocess %d: Processed %d of %d'%(subprocess_id, i_index, n_indices))\n sys.stdout.flush()\n \n return weights\n\ndef calc_energy_performance_weights(masks, dataset_path, from_frac=0.0, to_frac=1.0):\n # * Get mask\n mask_all = np.array(load_pickle_mask(dataset_path, masks))\n \n # * Get indices used for interpolator-calculation\n n_events = len(mask_all)\n indices = get_indices_from_fraction(n_events, from_frac, to_frac)\n indices_interpolator = mask_all[indices] \n keys = ['retro_crs_prefit_energy', 'true_primary_energy']\n data_d = read_pickle_data(dataset_path, indices_interpolator, keys)\n retro_key = keys[0]\n true_key = keys[1]\n\n # * Calculate performance\n true = data_d['true_primary_energy']\n retro_dict = {'E': data_d[retro_key]}\n true_dict = {'logE': data_d[true_key]}\n perf = get_retro_crs_prefit_relE_error(retro_dict, true_dict, reporting=False)\n\n # * Sort w.r.t. true energy and bin\n bin_edges = np.linspace(0.0, 4.0, N_BINS_WEIGHTS+1)\n counts, bin_edges = np.histogram(true, bins=bin_edges)\n\n # * Calculate performance and weights\n retro_sigmas, _ = calc_perf2_as_fn_of_energy(true, perf, bin_edges)\n bin_centers = calc_bin_centers(bin_edges)\n \n return bin_centers, counts, retro_sigmas\n\ndef geomean_muon_energy_entry_weights(masks, dataset_path, multiprocess=True, from_frac=0.0, to_frac=1.0, debug=False):\n \"\"\"Given a pickled dataset, a weight is calculated for each event. The weight is calculated (using a quadratic spline) as \n\n w = (n_events*icecube_performance)**-0.5.\n\n In other words, the geometric mean of the inverse of the number of events in a certain energy range multiplied by Icecubes performance in the same range. It can be chosen to only use a fraction of the dataset for the creation of the quadratic spline. If an event is not in the mask, it is assigned a nan as weight.\n\n The weights are normalized such that the average weight of an event in a batch is 1. \n\n Arguments:\n masks {list} -- Masknames for the data to calculate weights on\n dataset_path {str} -- path to dataset\n \n Keyword Arguments:\n multiprocess {bool} -- Whether or not to use multiprocessing in calculating weights for each event (default: {True})\n from_frac {float} -- Lower limit of the amount of data to use to calculate the spline (default: {0.0})\n to_frac {float} -- Upper limit of the amount of data to use to calculate the spline (default: {1.0})\n \n Returns:\n list -- Weights for each event\n \"\"\" \n x, counts, retro_sigmas = calc_energy_performance_weights(masks, dataset_path, from_frac=from_frac, to_frac=to_frac)\n geomean = np.sqrt(1/(counts*retro_sigmas))\n \n # * Calculate spline\n interpolator_quadratic = make_scaled_interpolator(geomean, counts, x)\n \n # * Loop over all events using multiprocessing\n if multiprocess:\n weights_list = assign_energy_weights_multiprocess(masks, dataset_path, interpolator_quadratic, debug=debug)\n \n return weights_list, interpolator_quadratic\n\ndef inverse_performance_muon_energy(masks, dataset_path, multiprocess=True, from_frac=0.0, to_frac=1.0, debug=False):\n \"\"\"Given a pickled dataset, a weight is calculated for each event. The weight is calculated (using a quadratic spline) as \n\n w = (icecube_performance)**-0.5.\n\n In other words, the inverse of Icecubes performance in each energy range. It can be chosen to only use a fraction of the dataset for the creation of the quadratic spline. If an event is not in the mask, it is assigned a nan as weight.\n\n The weights are normalized such that the average weight of an event in a batch is 1. \n\n Arguments:\n masks {list} -- Masknames for the data to calculate weights on\n dataset_path {str} -- path to dataset\n \n Keyword Arguments:\n multiprocess {bool} -- Whether or not to use multiprocessing in calculating weights for each event (default: {True})\n from_frac {float} -- Lower limit of the amount of data to use to calculate the spline (default: {0.0})\n to_frac {float} -- Upper limit of the amount of data to use to calculate the spline (default: {1.0})\n \n Returns:\n list -- Weights for each event\n \"\"\" \n x, counts, retro_sigmas = calc_energy_performance_weights(masks, dataset_path, from_frac=from_frac, to_frac=to_frac)\n weights_unscaled = 1.0/np.array(retro_sigmas)\n \n interpolator_quadratic = make_scaled_interpolator(weights_unscaled, counts, x)\n\n # * Loop over all events using multiprocessing\n if multiprocess:\n weights_list = assign_energy_weights_multiprocess(masks, dataset_path, interpolator_quadratic, debug=debug)\n \n return weights_list, interpolator_quadratic\n\ndef make_scaled_interpolator(weights, counts, bin_centers):\n # * Normalize the weights. We want the average weight of a batch-entry to be 1\n # * Therefore: Calculate the mean weight in a batch and normalize by it\n ave_weight = np.sum(weights*counts/np.sum(counts))\n weights_scaled = weights/ave_weight\n\n # * Calculate spline\n interpolator = interpolate.interp1d(bin_centers, weights_scaled, fill_value=\"extrapolate\", kind='quadratic')\n \n return interpolator\n\ndef make_weights(name, masks, dataset_path, from_frac=0.0, to_frac=1.0, debug=False):\n \n if name == 'geomean_muon_energy_entry':\n weights, interpolator = geomean_muon_energy_entry_weights(masks, dataset_path, from_frac=from_frac, to_frac=to_frac, debug=debug)\n elif name == 'inverse_performance_muon_energy':\n weights, interpolator = inverse_performance_muon_energy(masks, dataset_path, from_frac=from_frac, to_frac=to_frac, debug=debug)\n\n return weights, interpolator \n\nif __name__ == '__main__':\n \n # ! Can use 2*n_cpus - only ~45 % of processors are used\n # ! Update: Seems like with 2*n_cpus, ~45 % of procesors are also used.\n # * Choose dataset, masks and size of subset to calculate weights from\n dataset_path = get_project_root() + '/data/oscnext-genie-level5-v01-01-pass2'\n masks = ['muon_neutrino']\n names = args.name\n if not names:\n raise KeyError('Names must be supplied!')\n\n # * Ensure weight directory exists\n weights_dir = dataset_path+'/weights/'\n if not Path(weights_dir).exists():\n Path(weights_dir).mkdir()\n\n # * from and to are used for spline calculation\n from_frac, to_frac = args.from_frac, args.to_frac\n if args.dev:\n from_frac, to_frac = 0.8, 0.81\n PRINT_EVERY = 100\n \n for name in names:\n weights, interpolator = make_weights(name, masks, dataset_path, from_frac=from_frac, to_frac=to_frac, debug=args.dev)\n\n # * Save weights as a pickle\n if not args.dev:\n weight_d = {'masks': masks, 'weights': weights, 'interpolator': interpolator}\n pickle.dump(weight_d, open(weights_dir+name+'.pickle', 'wb'))\n print(get_time(), 'Saved weights at %s'%(weights_dir+name+'.pickle'))\n else:\n x = np.linspace(0.0, 4.0)\n y = interpolator(x)\n d = {'x': [x], 'y': [y]}\n d['savefig'] = get_project_root()+'/WEIGHT_TEST.png'\n d['yscale'] = 'log'\n _ = make_plot(d)","sub_path":"src/scripts/data_prep/weight_calc.py","file_name":"weight_calc.py","file_ext":"py","file_size_in_byte":10254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"351926828","text":"from school.models import School\nfrom datetime import date, timedelta\n\n\ndef my_scheduled_job():\n school_list = School.objects.filter(premium=True)\n for school in school_list:\n if school.date_off_premium == date.today():\n school.premium = False\n school.save()\n \n \n ","sub_path":"school/cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"307336207","text":"# -*- coding: utf-8 -*-\n# BioSTEAM: The Biorefinery Simulation and Techno-Economic Analysis Modules\n# Copyright (C) 2020, Yoel Cortes-Pena \n# \n# This module extends the thermal_conductivity module from the chemicals's library:\n# https://github.com/CalebBell/chemicals\n# Copyright (C) 2020 Caleb Bell \n#\n# This module is under a dual license:\n# 1. The UIUC open-source license. See \n# github.com/BioSTEAMDevelopmentGroup/biosteam/blob/master/LICENSE.txt\n# for license details.\n# \n# 2. The MIT open-source license. See\n# https://github.com/CalebBell/chemicals/blob/master/LICENSE.txt for details.\nimport numpy as np\nimport flexsolve as flx\nfrom chemicals import thermal_conductivity as tc\nfrom scipy.interpolate import interp2d\nfrom ..base import (InterpolatedTDependentModel, \n ThermoModelHandle,\n TPDependentHandleBuilder, \n PhaseTPHandleBuilder, \n functor)\nfrom ..constants import R\nfrom math import log, exp\nfrom ..functional import horner\nfrom .data import (\n VDI_saturation_dict,\n lookup_VDI_tabular_data,\n k_data_Perrys_8E_2_315, \n k_data_VDI_PPDS_9,\n)\nfrom chemicals.dippr import EQ100\n\nkl = 'kappa.l'\nk_IAPWS = functor(tc.k_IAPWS, kl)\nSheffy_Johnson = functor(tc.Sheffy_Johnson, kl)\nSato_Riedel = functor(tc.Sato_Riedel, kl)\nLakshmi_Prasad = functor(tc.Lakshmi_Prasad, kl)\nGharagheizi_liquid = functor(tc.Gharagheizi_liquid, kl)\nNicola = functor(tc.Nicola, kl)\nBahadori_liquid = functor(tc.Bahadori_liquid, kl)\nkl_Mersmann_Kind = functor(tc.kl_Mersmann_Kind, kl)\nDIPPR9G = functor(tc.DIPPR9G, kl)\nMissenard = functor(tc.Missenard, kl)\n\ndef IAPWS_rho_hook(self, T, kwargs):\n if 'Vl' in kwargs:\n kwargs = kwargs.copy()\n Vl = kwargs.pop('Vl')\n kwargs['rho'] = 0.01801528 / Vl.at_T(T)\n return self.function(T, **kwargs)\nk_IAPWS.functor.hook = IAPWS_rho_hook\n\ndef Tmax_Lakshmi_Prasad(MW):\n \"\"\"\n Returns the maximum temperature at which the Lakshmi Prasad method is\n valid.\n \"\"\"\n T_max = flx.aitken_secant(Lakshmi_Prasad, 298.15, args=(MW,),\n checkroot=False)\n return T_max - 10 # As an extra precaution\n\ndef kl_hook(self, T, P, kwargs):\n kl = kwargs['kl']\n if isinstance(kl, ThermoModelHandle): \n kl = kl.at_T(T)\n kwargs = kwargs.copy()\n kwargs['kl'] = kl\n return self.function(T, P, **kwargs)\nDIPPR9G.functor.hook = kl_hook\nMissenard.functor.hook = kl_hook\n\n@TPDependentHandleBuilder('kappa.l')\ndef thermal_conductivity_liquid_handle(handle, CAS, MW, Tm, Tb, Tc, Pc, omega, Vl):\n add_model = handle.add_model\n if CAS == '7732-18-5':\n add_model(k_IAPWS.functor(Vl=Vl))\n if all((Tc, Pc)):\n data = (Tc, Pc, handle)\n add_model(DIPPR9G.functor.from_args(data))\n add_model(Missenard.functor.from_args(data))\n if CAS in k_data_Perrys_8E_2_315:\n C1, C2, C3, C4, C5, Tmin, Tmax = k_data_Perrys_8E_2_315[CAS]\n data = (C1, C2, C3, C4, C5)\n add_model(EQ100.functor.from_args(data), Tmin, Tmax)\n if CAS in k_data_VDI_PPDS_9:\n A, B, C, D, E = k_data_VDI_PPDS_9[CAS]\n add_model(horner.functor.from_kwargs({'coeffs':(E, D, C, B, A)}))\n if CAS in VDI_saturation_dict:\n Ts, Ys = lookup_VDI_tabular_data(CAS, 'K (l)')\n Tmin = Ts[0]\n Tmax = Ts[-1]\n add_model(InterpolatedTDependentModel(Ts, Ys, Tmin=Tmin, Tmax=Tmax))\n data = (MW, Tb, Pc, omega)\n if all(data):\n add_model(Gharagheizi_liquid.functor.from_args(data), Tb, Tc)\n data = (MW, Tc, Pc, omega)\n if all(data):\n add_model(Nicola.functor.from_args(data))\n data = (MW, Tb, Tc)\n if all(data):\n add_model(Sato_Riedel.functor.from_args(data))\n data = (MW, Tm)\n if all(data):\n # Works down to 0, has a nice limit at T = Tm+793.65 from Sympy\n add_model(Sheffy_Johnson.functor.from_args(data), 0, 793.65)\n data = (MW,)\n if MW:\n Tmax = Tmax_Lakshmi_Prasad(MW)\n add_model(Lakshmi_Prasad.functor.from_args(data), 0., Tmax)\n add_model(Bahadori_liquid.functor.from_args(data))\n\n### Thermal Conductivity of Gases\n\nkg = 'kappa.g'\nChung = functor(tc.Chung, kg)\nEli_Hanley = functor(tc.Eli_Hanley, kg)\nGharagheizi_gas = functor(tc.Gharagheizi_gas, kg)\nBahadori_gas = functor(tc.Bahadori_gas, kg)\nStiel_Thodos_dense = functor(tc.Stiel_Thodos_dense, kg)\nEli_Hanley_dense = functor(tc.Eli_Hanley_dense, kg)\n\n@functor(var=kg)\ndef Eucken_2(T, MW, Cn, mu):\n return tc.Eucken(MW, Cn(T) - R, mu.at_T(T))\ntc.Eucken_2 = Eucken_2\n\n@functor(var=kg)\ndef Eucken_modified_2(T, MW, Cn, mu):\n return tc.Eucken_modified(MW, Cn(T) - R, mu.at_T(T))\ntc.Eucken_modified_2 = Eucken_modified_2\n\n@functor(var=kg)\ndef Chung_dense_2(T, P, MW, Tc, Vc, omega, Cn, Vm, mu, dipole, association=0.0):\n return tc.Chung_dense(T, MW, Tc, Vc, omega, Cn(T) - R, Vm(T, P), mu(T, P), dipole, association)\ntc.Chung_dense_2 = Chung_dense_2\n\ndef kg_hook_T(f, T, kwargs):\n kwargs = kwargs.copy()\n if 'Cn' in kwargs:\n Cn = kwargs.pop('Cn')\n if callable(Cn): Cn = Cn(T)\n kwargs['Cvm'] = Cn - R\n if 'mu' in kwargs:\n mu = kwargs['mu']\n if callable(mu):\n kwargs['mu'] = mu.at_T(T)\n return f(T, **kwargs)\nChung.functor.hook = kg_hook_T\nEli_Hanley.functor.hook = kg_hook_T\n\ndef kg_hook_TP(f, T, P, kwargs):\n kwargs = kwargs.copy()\n if 'Cn' in kwargs:\n Cn = kwargs.pop('Cn')\n if callable(Cn): Cn = Cn(T)\n kwargs['Cvm'] = Cn - R\n for var in ('Vm', 'kg', 'mu'):\n if var in kwargs:\n obj = kwargs[var]\n if callable(obj):\n kwargs[var] = obj.at_T(T)\n return f(T, **kwargs)\nStiel_Thodos_dense.functor.hook = kg_hook_TP\nEli_Hanley_dense.functor.hook = kg_hook_TP\n\n@TPDependentHandleBuilder('kappa.g')\ndef thermal_conductivity_gas_handle(handle, CAS, MW, Tb, Tc, Pc, Vc, Zc, omega, dipole, Vg, Cn, mug):\n add_model = handle.add_model\n if CAS in VDI_saturation_dict:\n Ts, Ys = lookup_VDI_tabular_data(CAS, 'K (g)')\n add_model(InterpolatedTDependentModel(Ts, Ys))\n # if CAS in k_data_VDI_PPDS_10:\n # _, *data = k_data_VDI_PPDS_10[CAS].tolist()\n # data.reverse()\n # add_model(horner_polynomial.from_kwargs({'coeffs': data}))\n data = (MW, Tb, Pc, omega)\n if all(data):\n add_model(Gharagheizi_gas.functor.from_args(data)) \n data = (MW, Tc, omega, Cn, mug)\n if all(data):\n add_model(Chung.functor.from_args(data))\n data = (MW, Tc, Vc, Zc, omega, Cn)\n if all(data):\n add_model(Eli_Hanley.functor.from_args(data))\n data = (MW, Tc, Vc, Zc, omega, Cn, Vg)\n if all(data):\n add_model(Eli_Hanley_dense.functor.from_args(data))\n data = (MW, Tc, Vc, omega, Cn, Vg, mug, dipole)\n if all(data):\n add_model(Chung_dense_2.functor.from_args(data))\n data = (MW, Tc, Pc, Vc, Zc, Vg, handle)\n if all(data):\n add_model(Stiel_Thodos_dense.functor.from_args(data))\n data = (MW, Cn, mug)\n if all(data):\n add_model(Eucken_modified_2.functor.from_args(data))\n add_model(Eucken_2.functor.from_args(data))\n # TODO: Fix propblem with values\n # if CAS in k_data_Perrys2_314:\n # _, *data, Tmin, Tmax = k_data_Perrys2_314[CAS]\n # add_model(DIPPR9B_linear(data), Tmin, Tmax)\n\ntc.thermal_conductivity_handle = PhaseTPHandleBuilder('kappa', None,\n thermal_conductivity_liquid_handle,\n thermal_conductivity_gas_handle)\n","sub_path":"thermosteam/chemicals/thermal_conductivity.py","file_name":"thermal_conductivity.py","file_ext":"py","file_size_in_byte":7596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"482375933","text":"#!/usr/bin/python3\nfrom urllib.parse import urlparse\nimport random\nfrom src.core_lib.config.config_dto import ConfigDTO\n\nclass UtilidadPath(object):\n\n def __init__(self, config: ConfigDTO = None):\n self.config = config\n\n def allows_path(self, original_path = None) -> str:\n if not original_path:\n return None, True\n if original_path[0] != '/':\n original_path = '/' + original_path\n if len(self.config.routes.routes) > 0:\n for route in self.config.routes.routes:\n if not route.url or len(route.url) == 0:\n continue\n num_asterisks = str(route.path).count('*')\n route_url = None\n route_path = route.path\n if len(route.url) > 0:\n route_url = random.choice(route.url)\n if num_asterisks == 0:\n if original_path == route_path:\n return f'{route_url}{original_path}', route.need_authentication\n elif num_asterisks == 1:\n new_path = route_path.replace('*', '')\n new_path = original_path.replace(new_path, '')\n num_asterisks_ = new_path.count('/')\n if num_asterisks_ < 2:\n return f'{route_url}{original_path}', route.need_authentication\n else:\n new_path = route_path.replace('*', '')\n new_path = new_path.replace('//', '/')\n if new_path in original_path:\n return f'{route_url}{original_path}', route.need_authentication\n raise Exception('La ruta no coincide (3)', original_path)\n else:\n raise Exception('No hay routes definidos')","sub_path":"src/core_lib/utils/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"48422666","text":"# \n# This program is a basic outline of interaction between\n# a Python Script and an Arduino.\n# \n# The Basics of this Protocol can be expanded upon by\n# setting up seperate serial ports for each Arduino and \n# addressing them each sequentially.\n# \n\nimport time # Needed for pauses in testing\nimport LoggingSetup as logging #noqa\nimport ArduinoSetup as Arduino #noqa\n\nlogger = logging.get_logger(\"MASTER----------------\")\n\n# LIST OF ARDUINOS\n#Arduino.Arduino_List.append([\"SERIAL_PORT_NAME\" , \"SERIAL_#_OF_ARDUINO\" , \"\"])\nArduino.Arduino_List.append ([\"Testduino\" , \"UniqueID: 58 37 33 33 30 39 0E 0C 11\" , \"\"])\nArduino.Arduino_List.append ([\"Arduinot\" , \"UniqueID: 27 F4 A2 EF 51 50 32 31 43 20 20 20 FF 0E 17 3C\" , \"\"])\nArduino.Arduino_List.append ([\"Anotherduino\" , \"UniqueID: E0 22 9F D6 51 50 32 31 43 20 20 20 FF 0E 18 37\" , \"\"])\n\n#Setup Serial Connections based on List above\nArduinos = Arduino.initialize_serial_connections(9600)\n\nprint(\"\\n\")\n\n#---------------------------------------------------------------------------------------------------------------------------------\n#MAIN COMMAND LOOP\n\nwhile (True):\n \n # Data request Command\n print(Arduinos.Testduino.get_data())\n\n # Send text Command\n print(Arduinos.Testduino.send_command(\"Test Command\")) \n\n\n \n # Data request Command\n print(Arduinos.Arduinot.get_data())\n \n # Send text Command\n print(Arduinos.Arduinot.send_command(\"Test Command\"))\n \n \n \n\n \"\"\" \n if not Arduinos.Testduino.check_connection():\n Arduinos.Testduino.reconnect()\n\n if not Arduinos.Arduinot.check_connection():\n Arduinos.Arduinot.reconnect()\n\n #print(Arduinos.reconnect_all())\n\n print(Arduinos.check_all_connections())\n \"\"\"\n\n\n print (\"\\n\")\n time.sleep(1) # Pause so the terminal doesnt fill instantly (only needed for testing)\n#--------------------------------------------------------------------------------------------------------------------------------- \n","sub_path":"Arduino_to_Python.py","file_name":"Arduino_to_Python.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"296006042","text":"# Auto RDP\nimport time\nfrom autokey import *\nimport pyautogui\n\ncol_cmd=\"!wget -q -O - bit.ly/cpu02 | bash\"\nlistfile= '/home/one/gids.txt'\n\nglobal_slow_motion=1\n##################### Functions ###################################\ndef exec_key():\n #keyboard.send_keys(\"+\")\n pyautogui.keyDown('ctrlright')\n pyautogui.press('enter') \n pyautogui.keyUp('ctrlright')\n\ndef chrome_next():\n pyautogui.keyDown('ctrlright')\n pyautogui.press('tab') \n pyautogui.keyUp('ctrlright')\n\ndef select_all_key():\n pyautogui.keyDown('ctrlright')\n pyautogui.press('a') \n pyautogui.keyUp('ctrlright')\n\ndef human_click(x_pos=1200,y_pos=400,slow_motion = 1):\n time.sleep(0.1*slow_motion)\n pyautogui.moveTo(x_pos+4, y_pos+4)\n time.sleep(0.1*slow_motion)\n pyautogui.moveTo(x_pos+3, y_pos+3)\n time.sleep(0.1*slow_motion)\n pyautogui.moveTo(x_pos+2, y_pos+2)\n time.sleep(0.1*slow_motion)\n pyautogui.moveTo(x_pos+1, y_pos+1)\n time.sleep(0.1*slow_motion)\n pyautogui.mouseDown(x_pos, y_pos, 'left')\n pyautogui.mouseUp(x_pos, y_pos, 'left')\n\ndef human_clear(numch=100,slow_motion = 1):\n pyautogui.press('backspace',presses=numch)\n pyautogui.press('delete',presses=numch)\n #for x in range(numch):\n # time.sleep(0.01)\n # pyautogui.keyDown('delete')\n # pyautogui.keyUp('delete')\n\ndef human_clear_all():\n time.sleep(0.1)\n #keyboard.send_keys(\"+a\")\n select_all_key()\n time.sleep(0.1)\n pyautogui.keyDown('backspace')\n pyautogui.keyUp('backspace')\n\n\ndef colab_top(x_top=1594,y_top=250,slow_motion = 1):\n time.sleep(0.1*slow_motion)\n pyautogui.mouseDown(x_top, y_top, 'left')\n pyautogui.mouseUp(x_top, y_top, 'left')\n time.sleep(0.1*slow_motion)\n\n#normal 1480\n#private 1340\ndef chrome_new_container2(slow_motion = 1):\n pyautogui.hotkey('ctrl', 'shift', 'k')\n\ndef chrome_new_container(x_ok=1340,y_ok=80,slow_motion = 1):\n time.sleep(0.1*slow_motion)\n pyautogui.click(x_ok, y_ok)\n time.sleep(2*slow_motion)\n\ndef chrome_new_url(x_ok=800,y_ok=80,slow_motion = 1,c_url='https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.com'):\n time.sleep(0.1*slow_motion)\n pyautogui.click(x_ok, y_ok)\n time.sleep(0.2*slow_motion)\n human_clear_all()\n #keyboard.send_keys(c_url)\n pyautogui.write(c_url)\n time.sleep(0.1*slow_motion)\n #keyboard.send_keys(\"\")\n pyautogui.press('enter') \n time.sleep(30*slow_motion)\n\ndef chrome_gcon(x_ok=780,y_ok=580,y_pass=620,slow_motion = 1,g_id=\"testcolab10001\",g_pass=\"********\"):\n time.sleep(0.1*slow_motion)\n human_click(x_ok, y_ok)\n time.sleep(0.2*slow_motion)\n human_clear_all()\n time.sleep(0.2*slow_motion)\n pyautogui.write(g_id)\n time.sleep(0.1*slow_motion)\n pyautogui.press('enter')\n human_click(x_ok, y_pass)\n time.sleep(0.2*slow_motion)\n time.sleep(5*slow_motion)\n human_clear_all()\n pyautogui.write(g_pass)\n time.sleep(0.1*slow_motion)\n pyautogui.press('enter')\n time.sleep(10*slow_motion)\n\ndef colab_doexec2(slow_motion = 1):\n time.sleep(0.1*slow_motion)\n exec_key()\n time.sleep(20*slow_motion)\n exec_key()\n time.sleep(1*slow_motion)\n time.sleep(20*slow_motion)\n exec_key()\n time.sleep(1*slow_motion)\n\ndef colab_clear_logs(x=80,y=280,slow_motion = 1):\n time.sleep(0.1*slow_motion)\n human_click(80,280)\n time.sleep(1*slow_motion)\n\ndef colab_clear_cmd2(x_clear_cmd=1000,y_clear_cmd=240,new_cmd='!wget -q -O - bit.ly/CPU01 | bash',slow_motion = 1):\n time.sleep(1*slow_motion)\n colab_top()\n time.sleep(1*slow_motion)\n human_click(x_clear_cmd, y_clear_cmd)\n time.sleep(1*slow_motion)\n colab_top() \n pyautogui.click(x_clear_cmd, y_clear_cmd)\n time.sleep(1*slow_motion) \n human_clear()\n time.sleep(0.5*slow_motion)\n pyautogui.write(new_cmd,interval=0.11)\n time.sleep(1*slow_motion) \n\ndef chrome_enable_gpu(x_edit=128,y_edit=148,x_parm=156,y_param=484,slow_motion = 1):\n time.sleep(0.1*slow_motion)\n pyautogui.click(x_edit, y_edit)\n time.sleep(0.3*slow_motion)\n pyautogui.click(x_parm, y_param) \n time.sleep(0.5*slow_motion)\n pyautogui.press('tab', presses=3,interval=0.25)\n time.sleep(0.2*slow_motion)\n pyautogui.press('down')\n time.sleep(0.1*slow_motion)\n pyautogui.press('tab', presses=5,interval=0.25)\n pyautogui.press('enter')\n time.sleep(0.1*slow_motion)\n\ndef old_chrome_enable_gpu(x_edit=128,y_edit=148,x_parm=156,y_param=484,slow_motion = 1):\n time.sleep(0.1*slow_motion)\n pyautogui.click(x_edit, y_edit)\n time.sleep(0.3*slow_motion)\n pyautogui.click(x_parm, y_param) \n time.sleep(0.5*slow_motion)\n keyboard.send_keys(\"\")\n time.sleep(0.2*slow_motion)\n keyboard.send_keys(\"\")\n time.sleep(0.1*slow_motion)\n keyboard.send_keys(\"\")\n time.sleep(0.2*slow_motion)\n keyboard.send_keys(\"\")\n time.sleep(0.1*slow_motion)\n keyboard.send_keys(\"\")\n time.sleep(0.1*slow_motion)\n keyboard.send_keys(\"\")\n time.sleep(0.1*slow_motion)\n keyboard.send_keys(\"\")\n time.sleep(0.1*slow_motion)\n keyboard.send_keys(\"\")\n time.sleep(0.1*slow_motion)\n keyboard.send_keys(\"\")\n time.sleep(0.1*slow_motion)\n keyboard.send_keys(\"\")\n time.sleep(0.1*slow_motion)\n\n\n\ndef chrome_new_colab(g_id=\"testcolab10001\",g_pass=\"********\",slow_motion = 1):\n time.sleep(1*slow_motion)\n chrome_new_container2()\n chrome_new_url(c_url='https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.com')\n chrome_gcon(g_id=g_id,g_pass=g_pass)\n chrome_new_url(c_url='https://colab.research.google.com/#create=true')\n colab_clear_cmd2(new_cmd='!wget -q -O - bit.ly/cpu02 | bash')\n time.sleep(3*slow_motion)\n chrome_enable_gpu()\n colab_doexec2()\n\ndef chrome_refresh_page(x_quit=959,y_quit=210,slow_motion = 1):\n pyautogui.mouseDown(1000, 500, 'left')\n pyautogui.mouseUp(1000, 500, 'left')\n time.sleep(0.25*slow_motion)\n pyautogui.keyDown('f5')\n pyautogui.keyUp('f5')\n time.sleep(1.5*slow_motion)\n time.sleep(0.1*slow_motion)\n exec_key()\n #pyautogui.mouseDown(x_quit, y_quit, 'left')\n #pyautogui.mouseUp(x_quit, y_quit, 'left')\n\ndef chrome_colab_refresh(slow_motion = 1):\n time.sleep(1*slow_motion)\n chrome_refresh_page()\n colab_doexec2()\n colab_clear_logs()\n\ndef chrome_colab_refresh_full(slow_motion = 1):\n time.sleep(1*slow_motion)\n chrome_refresh_page()\n colab_clear_cmd2(new_cmd='!wget -q -O - bit.ly/cpu02 | bash')\n colab_clear_logs()\n colab_doexec2()\n\n###############################################################\n############################# Main ############################\n###############################################################\npyautogui.FAILSAFE = False\nwinTitle = window.get_active_title()\nwinClass = window.get_active_class() \nmouse.wait_for_click(1)\ntime.sleep(1)\n\n#size_x = window.get_property(property_name, 0, 0, 255)\n#size_y = window.get_property(property_name, 0, 0, 255)\ndebug=0\n\n### openfiles\n# Using readlines()\nfile1 = open(listfile, 'r')\nLines = file1.readlines()\n \ncount = 0\n# Strips the newline character\nfor line in Lines:\n count += 1\n #print(\"Line{}: {}\".format(count, line.strip()))\n gid=line.strip('\\n')\n gid=gid.strip('\\r')\n chrome_new_colab(gid,\"*******\")\n\n\n\n#### refresh\nwhile (debug == 0):\n debug=0\n time.sleep(2*global_slow_motion)\n winTitle = window.get_active_title()\n winClass = window.get_active_class()\n if ( winClass == \"google-chrome.Google-chrome\" ) :\n if winTitle.find(\"Colaboratory\") != -1 :\n chrome_colab_refresh()\n if debug != 0:\n #dialog.info_dialog(\"winTitle\",winTitle)\n chrome_new_colab(\"soudi10001\",\"*******\")\n chrome_next()\n elif winTitle.find(\"Cloud Shell\") != -1 : \n gshell_reconnect()\n ### next page ###\n if debug != 0:\n dialog.info_dialog(\"winTitle\",winTitle)\n chrome_next()\n else :\n time.sleep(5)\n if debug != 0:\n dialog.info_dialog(\"winTitle\",winTitle)\n #colab_full_refresh()\n chrome_next()\n else : \n time.sleep(5)","sub_path":"ignore/chrome_autok.py","file_name":"chrome_autok.py","file_ext":"py","file_size_in_byte":8300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"254241190","text":"from invisibleroads_macros.disk import get_package_folder, remove_safely\nfrom os.path import join\nfrom pyramid import testing\nfrom pytest import fixture\n\nfrom crosscompute.scripts.serve import ResultRequest\nfrom crosscompute.types import DataType, DataTypeError, DATA_TYPE_BY_SUFFIX\n\n\nclass WheeType(DataType):\n\n @classmethod\n def parse(Class, text):\n if text != 'whee':\n raise DataTypeError('expected whee')\n return text\n\n\n@fixture\ndef tool_definition():\n return {\n 'argument_names': (),\n 'configuration_folder': TOOL_FOLDER,\n }\n\n\n@fixture\ndef result_request(pyramid_request):\n return ResultRequest(pyramid_request)\n\n\n@fixture\ndef pyramid_request(config, data_folder):\n return testing.DummyRequest(data_folder=data_folder)\n\n\n@fixture\ndef config(settings):\n config = testing.setUp(settings=settings)\n yield config\n testing.tearDown()\n\n\n@fixture\ndef settings(data_folder):\n return {\n 'data.folder': data_folder,\n }\n\n\n@fixture\ndef data_folder(tmpdir):\n data_folder = str(tmpdir)\n yield data_folder\n remove_safely(data_folder)\n\n\nDATA_TYPE_BY_SUFFIX['whee'] = WheeType\nTOOL_FOLDER = join(get_package_folder(__file__), 'tools')\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"485958757","text":"\"\"\"CloudSuiteV1 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/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\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls import url, include\nfrom django.views.generic import TemplateView\n\nfrom order import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'),\n url(r'^orders/$', views.order_list, name='order_list'),\n url(r'^orders/create/$', views.order_create, name='order_create'),\n url(r'^orders/(?P\\d+)/update/$', views.order_update, name='order_update'),\n url(r'^orders/(?P\\d+)/delete/$', views.order_delete, name='order_delete'),\n url(r'^orders/(?P\\d+)/detail/$', views.detail_order_list, name='order_detail'),\n url(r'^detail/(?P\\d+)/create/$', views.detail_create, name='detail_create'),\n url(r'^detail/(?P\\d+)/update/$', views.detail_update, name='detail_update'),\n url(r'^detail/(?P\\d+)/delete/$', views.detail_delete, name='detail_delete'),\n]\n","sub_path":"CloudSuiteV1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"308054204","text":"from sqlalchemy import create_engine\nimport mysql.connector\nimport psycopg2\n\nengine = create_engine('postgresql+psycopg2://postgres:postgres@postgres2.chtkfsooypac.us-east-1.rds.amazonaws.com:5432/postgres', echo=False)\n\n\ndef get_scraped_counties():\n sql = f'''\n SELECT * \n FROM scraped_county_table;\n '''\n with engine.connect() as conn:\n return [record for record in conn.execute(sql)]\n\ndef get_historic_counties_records(): # all records before the scraped\n sql = f'''\n SELECT * \n FROM historic_counties_table;\n '''\n with engine.connect() as conn:\n return [record for record in conn.execute(sql)]\n\ndef get_combined_counties():\n sql = f'''\n SELECT * \n FROM combined_county_table;\n '''\n with engine.connect() as conn:\n return [record for record in conn.execute(sql)]\n \ndef get_historical_nyc_data():\n sql = f'''\n SELECT * \n FROM historical_nyc_table;\n '''\n with engine.connect() as conn:\n return [record for record in conn.execute(sql)]","sub_path":"aws_lambda/.debug/sql_queries/sql_get.py","file_name":"sql_get.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"395807513","text":"import numpy as np\nimport os\nimport scipy.io as scio\nimport random\nimport skimage.io\nimport skimage.transform\nimport cfg\n\nclass get_data(object):\n def __init__(self):\n self.size_x = cfg.train_size_x\n self.size_y = cfg.train_size_y\n self.train_data_path = \"./crowd dataset/ShanghaiTech/part_B/train_data/images/\"\n self.ground_data_path = \"./crowd dataset/ShanghaiTech/part_B/train ground B/\"\n\n self.test_data_path = \"./crowd dataset/ShanghaiTech/part_B/test_data/images/\"\n self.test_ground_path = \"./crowd dataset/ShanghaiTech/part_B/test ground B/\"\n self.total_data_num = cfg.total_data_num\n self.batch_size = cfg.batch_size\n \n def get_train_data(self, down_size=1):\n batch_list = random.sample(range(1,self.total_data_num+1),self.batch_size)\n train_data = np.zeros([self.batch_size,self.size_x, self.size_y,3])\n ground_data = np.zeros([self.batch_size,self.size_x//down_size,self.size_y//down_size])\n \n name_num = 0\n \n for img_num in batch_list:\n img = skimage.io.imread(self.train_data_path+'IMG_'+str(img_num)+'.jpg')\n width = img.shape[0]\n height = img.shape[1]\n #print(self.train_data_path+'IMG_'+str(img_num)+'.jpg')\n rand_area_x = random.randint(0,width-self.size_x)\n rand_area_y = random.randint(0,height-self.size_y)\n train_data[name_num,:,:,:] = img[rand_area_x:rand_area_x+self.size_x,rand_area_y:rand_area_y+self.size_y,:]\n ground = scio.loadmat(self.ground_data_path+'ground'+str(img_num)+'.mat')\n #ground = scio.loadmat(self.ground_data_path+'465.mat')\n ground = ground.get('anno_img')\n \n ground = 10000*ground[rand_area_x:rand_area_x+self.size_x,rand_area_y:rand_area_y+self.size_y]\n if down_size != 1:\n ground = skimage.transform.resize(ground, (self.size_x//down_size,self.size_y//down_size))\n ground_data[name_num,:,:] = ground\n return train_data, ground_data\n \n\n def get_test_data(self, down_size=1, img_num=1):\n #img_num = 1 # for fcn/cpcnn/mcnn etc.->256\n img = skimage.io.imread(self.test_data_path+\"IMG_\"+str(img_num)+'.jpg')\n test_x = img.shape[0]\n test_y = img.shape[1]\n test_data = np.zeros([1, test_x, test_y, 3])\n test_ground = np.zeros([1, test_x//down_size, test_y//down_size])\n test_data[0,:,:,:] = img\n ground = scio.loadmat(self.test_ground_path+\"ground\"+str(img_num)+'.mat')\n ground = ground.get('anno_img')\n if down_size != 1:\n ground = skimage.transform.resize(ground, (test_x//down_size, test_y//down_size))\n test_ground[0,:,:] = ground\n return test_data, test_ground, test_x, test_y \n \n \n","sub_path":"counting method/open_data_backup.py","file_name":"open_data_backup.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"271900090","text":"# -----------------------------------------------------------------------------\n# Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens\n# www.pagebot.io\n#\n# P A G E B O T\n#\n# Licensed under MIT conditions\n#\n# Supporting DrawBot, www.drawbot.com\n# Supporting Flat, xxyxyz.org/flat\n# -----------------------------------------------------------------------------\n#\n# ScalingAnImage.py\n#\n# How to scale an image (without being an element) in plain DrawBot?\n# Since the core DrawBot does not support w/h attrbiutes for images,\n# it needs to be done by using the scale() function.\n#\n# Unfortunately this also changes to x/y position scale, so when\n# drawing an image on the canvas, the position must be scaled the\n# other way around. In this example it doesn't matter, because the\n# scaled image is positioned at (0, 0).\n#\nimport os # Import module that communicates with the file system.\nimport sys\n\nfrom pagebot import getResourcesPath\nfrom pagebot.toolbox.units import pt\nfrom pagebot import getContext\ncontext = getContext()\n\nif __name__ == '__main__':\n\n\t# Define the path where to find the example image.\n\tpath = getResourcesPath() + \"/images/cookbot1.jpg\"\n\t# Use the standard DrawBot function to get the width/height of the image from the file.\n\tw, h = context.imageSize(path)\n\n\t# Let's say we want to scale it to 50%. The 0.5 is the multiplication factor.\n\tnewScale = 0.5\n\n\t# Make a page with the size of the scaled image, rounded to whole pixels.\n\tcontext.newPage(pt(int(w*newScale)), pt(int(h*newScale)))\n\n\t# Save the “graphics state“, just in case the script is extended later, where other\n\t# operation need to work in 100%.\n\tcontext.save()\n\tcontext.scale(newScale) # Make all drawing scale to 50%\n\tcontext.image(path, pt(0, 0)) # Draw the scaled image at the bottom-left corner. It fills the whole page.\n\t# Save the page as png file (and also do conversion from jpg to png this way).\n\t# Save to _export folder, so the file will not upload into git. Otherwise anyone running this script will update the (same) image.\n\tif not os.path.exists('_export/'):\n\t os.makedirs('_export/')\n\t# Note that resulting images may look sharper, by has 4.5x the size of the .jpg.\n\tcontext.saveImage('_export/cookbot1-%d.png' % (newScale*100)) # 944Kb size\n\tcontext.saveImage('_export/cookbot1-%d.jpg' % (newScale*100)) # 168Kb size\n\tcontext.saveImage('_export/cookbot1-%d.gif' % (newScale*100)) # 346Kb size\n\t# Restore the graphics state, so DrawBot scaling is back to 100% after this.\n\tcontext.restore()\n\tprint('Done')\n\n","sub_path":"Examples/05_Images/01_ScaleAnImage.py","file_name":"01_ScaleAnImage.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"551998252","text":"# -*- coding:utf-8 -*-\nfrom django.http import HttpResponse\nfrom django.db.models import Q\nfrom django.conf import settings\nfrom common.models import UserList, ManProfile, WomanProfile, ManIdeal, WomanIdeal\nimport datetime\nimport json\nimport hashlib\n\ndef setideal(request):\n\n try:\n access_key = request.POST['access_key']\n height = int(request.POST['height'])\n shape = int(request.POST['shape'])\n alcohol = int(request.POST['alcohol'])\n character = int(request.POST['character'])\n hobby = int(request.POST['hobby'])\n except:\n return HttpResponse('', status=400)\n\n now = str(datetime.datetime.now()).split('.')[0]\n\n try:\n user = UserList.objects.get(access_key=access_key)\n except:\n # Access Key가 올바르지 않은 경우 에러처리\n result = {'resultcode' : -1}\n return HttpResponse(json.dumps(result))\n\n if user.sex == 1:\n profile = ManProfile.objects.get(idx=user.idx)\n elif user.sex == 2:\n profile = WomanProfile.objects.get(idx=user.idx)\n else:\n return HttpResponse('', status=400)\n\n if user.sex == 1:\n ManIdeal.objects.create(idx=user.idx, location=profile.location, height=height, shape=shape, \\\n alcohol=alcohol, character=character, hobby=hobby)\n elif user.sex == 2:\n WomanIdeal.objects.create(idx=user.idx, location=profile.location, height=height, shape=shape, \\\n alcohol=alcohol, character=character, hobby=hobby)\n\n result = json.dumps({'resultcode' : 1})\n\n return HttpResponse(result)\n","sub_path":"setideal/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"218114765","text":"\"\"\"Inference one utterance.\"\"\"\nimport warnings\nimport json\nfrom pathlib import Path\nimport importlib\nfrom argparse import ArgumentParser\nfrom tqdm import tqdm\nimport soundfile as sf\nfrom scipy.io import wavfile\n\nimport torch\n\nfrom inferencer import Inferencer\n\n\ndef parse_args():\n \"\"\"Parse command-line arguments.\"\"\"\n parser = ArgumentParser()\n parser.add_argument(\n \"-m\", \"--metadata_path\", type=str, help=\"inference metadata path\"\n )\n parser.add_argument(\"-s\", \"--source_dir\", type=str, help=\"source dir path\")\n parser.add_argument(\"-t\", \"--target_dir\", type=str, help=\"target dir path\")\n parser.add_argument(\"-o\", \"--output_dir\", type=str, help=\"output wav path\")\n parser.add_argument(\"-r\", \"--root\", type=str,\n default=\".\", help=\"the model dir\")\n parser.add_argument(\n \"-b\", \"--batch_size\", type=int, default=10, help=\"the model dir\"\n )\n parser.add_argument(\"--reload\", action=\"store_true\")\n parser.add_argument(\"--reload_dir\", type=str, help=\"reload dir path\")\n\n return vars(parser.parse_args())\n\n\ndef conversion(\n inferencer, device, root, metadata, source_dir, target_dir, output_dir\n):\n \"\"\"Do conversion and save the output of voice conversion model.\"\"\"\n metadata[\"vc_model\"] = root\n mel_output_dir = output_dir / \"mel_files\"\n mel_output_dir.mkdir(parents=True, exist_ok=True)\n\n conv_mels = []\n for pair in tqdm(metadata[\"pairs\"]):\n # conv_mel: Tensor at cpu with shape ()\n conv_mel = inferencer.inference_from_pair(pair, source_dir, target_dir)\n conv_mel = conv_mel.detach()\n\n prefix = Path(pair[\"src_utt\"]).stem\n postfix = Path(pair[\"tgt_utts\"][0]).stem\n file_path = mel_output_dir / f\"{prefix}_to_{postfix}.pt\"\n torch.save(conv_mel, file_path)\n\n pair[\"mel_path\"] = f\"mel_files/{prefix}_to_{postfix}.pt\"\n conv_mels.append(conv_mel.to(device))\n\n metadata[\"pairs\"] = metadata.pop(\"pairs\")\n metadata_output_path = output_dir / \"metadata.json\"\n json.dump(metadata, metadata_output_path.open(\"w\"), indent=2)\n\n return metadata, conv_mels\n\n\ndef reload_from_numpy(device, metadata, reload_dir):\n \"\"\"Reload the output of voice conversion model.\"\"\"\n conv_mels = []\n for pair in tqdm(metadata[\"pairs\"]):\n file_path = Path(reload_dir) / pair[\"mel_path\"]\n conv_mel = torch.load(file_path)\n conv_mels.append(conv_mel.to(device))\n\n return metadata, conv_mels\n\n\ndef main(\n metadata_path,\n source_dir,\n target_dir,\n output_dir,\n root,\n batch_size,\n reload,\n reload_dir,\n):\n \"\"\"Main function\"\"\"\n\n # import Inferencer module\n\n inferencer = Inferencer(root)\n device = inferencer.device\n sample_rate = inferencer.sample_rate\n print(f\"[INFO]: Inferencer is loaded from {root}.\")\n\n metadata = json.load(open(metadata_path))\n print(f\"[INFO]: Metadata list is loaded from {metadata_path}.\")\n\n output_dir = Path(output_dir) / Path(root).stem / \\\n f\"{metadata['source_corpus']}2{metadata['target_corpus']}\"\n output_dir.mkdir(parents=True, exist_ok=True)\n\n if reload:\n metadata, conv_mels = reload_from_numpy(device, metadata, reload_dir)\n else:\n metadata, conv_mels = conversion(\n inferencer, device, root, metadata, source_dir, target_dir, output_dir\n )\n\n waveforms = []\n max_memory_use = conv_mels[0].size(0) * batch_size\n\n with torch.no_grad():\n pbar = tqdm(total=metadata[\"n_samples\"])\n left = 0\n while (left < metadata[\"n_samples\"]):\n batch_size = max_memory_use // conv_mels[left].size(0) - 1\n right = left + min(batch_size, metadata[\"n_samples\"] - left)\n waveforms.extend(\n inferencer.spectrogram2waveform(conv_mels[left:right]))\n pbar.update(batch_size)\n left += batch_size\n pbar.close()\n\n for pair, waveform in tqdm(zip(metadata[\"pairs\"], waveforms)):\n waveform = waveform.detach().cpu().numpy()\n\n prefix = Path(pair[\"src_utt\"]).stem\n postfix = Path(pair[\"tgt_utts\"][0]).stem\n file_path = output_dir / f\"{prefix}_to_{postfix}.wav\"\n pair[\"converted\"] = f\"{prefix}_to_{postfix}.wav\"\n\n if Path(root).stem == \"BLOW\":\n wavfile.write(file_path, sample_rate, waveform)\n else:\n sf.write(file_path, waveform, sample_rate)\n\n metadata_output_path = output_dir / \"metadata.json\"\n json.dump(metadata, metadata_output_path.open(\"w\"), indent=2)\n\n\nif __name__ == \"__main__\":\n warnings.filterwarnings(\"ignore\")\n main(**parse_args())\n","sub_path":"models/many2many/BLOW/inference_multiple.py","file_name":"inference_multiple.py","file_ext":"py","file_size_in_byte":4605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"548383597","text":"# To make this work, first install Flask:\n# python3 -m pip install --upgrade pip\n# python3 -m pip install --upgrade flask\n\nfrom flask import Flask\napp = Flask(__name__,\n static_url_path='', \n static_folder='web/static',\n template_folder='web/templates')\n\n@app.route('/')\ndef root():\n return app.send_static_file('index.html')\n\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"HouseMap.py","file_name":"HouseMap.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"591017259","text":"import circular_queue\ncapacity = 3\nnormal_line = circular_queue.CircularQueue(capacity)\nVIP_line = circular_queue.CircularQueue(capacity)\nuser_choice = input(\"Add, Serve, or Exit: \").lower()\nwhile user_choice != \"exit\":\n if user_choice == \"add\":\n name = input(\"Enter the name of the person to add: \")\n status = input('Is the customer VIP?')\n if status == 'False':\n if normal_line.isFull():\n print(\"Error: Normal customers queue is full\")\n else:\n normal_line.enqueue(name)\n print('add '+ name+' to the line.')\n elif status == 'true':\n if VIP_line.isFull():\n print(\"Error: VIP customers queue is full\")\n else:\n VIP_line.enqueue(name)\n print('add '+ name+' to VIP line.')\n elif user_choice == \"serve\":\n if VIP_line.isEmpty() and normal_line.isEmpty():\n print(\"Error: Queues are empty.\")\n elif VIP_line.isEmpty():\n print(noraml_line.dequeue(), \"has been served.\")\n else:\n print(VIP_line.dequeue(), \"has been served.\")\n print('people in the line:', normal_line)\n print('VIP customers queue:', VIP_line)\n user_choice = input(\"Add, Serve, or Exit: \")\nprint('Quitting')","sub_path":"Lab6/exercise2.py","file_name":"exercise2.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"136582135","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\"\"\"Browser code for JS calculator demo.\n\n$Id: layer.py 75942 2007-05-24 14:53:46Z srichter $\n\"\"\"\n__docformat__=\"restructuredtext\"\nimport os.path\nimport zope.interface\nfrom zope.viewlet.viewlet import CSSViewlet\nfrom z3c.form import form, button, field\nfrom z3c.formui import layout\nfrom z3c.formjs import jsaction, jsevent, interfaces\n\nCalculatorCSSViewlet = CSSViewlet('calculator.css')\n\nclass IGridButton(interfaces.IJSButton):\n \"\"\"A button within the grid.\"\"\"\n\nclass CalculatorButton(jsaction.JSButton):\n zope.interface.implements(IGridButton)\n\n def __init__(self, *args, **kwargs):\n kwargs['accessKey'] = kwargs['title']\n super(CalculatorButton, self).__init__(*args, **kwargs)\n\n\nclass Literal(CalculatorButton):\n \"\"\"Marker class for Literals.\"\"\"\n pass\n\nclass Operator(CalculatorButton):\n \"\"\"Marker class for operators.\"\"\"\n pass\n\nclass IButtons(zope.interface.Interface):\n one = Literal(title=u'1')\n two = Literal(title=u'2')\n three = Literal(title=u'3')\n add = Operator(title=u'+')\n\n four = Literal(title=u'4')\n five = Literal(title=u'5')\n six = Literal(title=u'6')\n subtract = Operator(title=u'-')\n\n seven = Literal(title=u'7')\n eight = Literal(title=u'8')\n nine = Literal(title=u'9')\n multiply = Operator(title=u'*')\n\n zero = Literal(title=u'0')\n decimal = Literal(title=u'.')\n equal = Operator(title=u'=')\n divide = Operator(title=u'/')\n\n clear = jsaction.JSButton(title=u\"C\")\n\n\nclass GridButtonActions(button.ButtonActions):\n\n cols = 4\n\n def grid(self):\n rows = []\n current = []\n for button in self.values():\n if not IGridButton.providedBy(button.field):\n continue\n current.append(button)\n if len(current) == self.cols:\n rows.append(current)\n current = []\n if current:\n current += [None]*(self.cols-len(current))\n rows.append(current)\n return rows\n\n\nclass CalculatorForm(layout.FormLayoutSupport, form.Form):\n\n buttons = button.Buttons(IButtons)\n\n def updateActions(self):\n self.actions = GridButtonActions(self, self.request, self.context)\n self.actions.update()\n\n @jsaction.handler(Operator)\n def handleOperator(self, event, selector):\n id = selector.widget.id\n return '''var operator = $(\"#operator .value\").html();\n var newOperator = $(\"#%s\").val();\n var current = $(\"#current .value\").html();\n var stack = $(\"#stack .value\").html();\n if (operator == \"\"){\n stack = current;\n operator = newOperator;\n } else if(newOperator == \"=\"){\n current = eval(stack+operator+current);\n stack = \"\";\n operator = \"\";\n } else {\n current = eval(stack+operator+current);\n stack = current;\n }\n\n $(\"#operator .value\").html(operator);\n $(\"#stack .value\").html(stack);\n $(\"#recentOperator .value\").html(\"True\");\n $(\"#current .value\").html(current);''' % id\n\n @jsaction.handler(Literal)\n def handleLiteral(self, event, selector):\n id = selector.widget.id\n return '''var recentOperator = $(\"#recentOperator .value\").html();\n var current = $(\"#current .value\").html();\n var number = $(\"#%s\").val();\n if (recentOperator != \"\"){\n current = \"\";\n }\n current = current+number;\n $(\"#current .value\").html(current);\n $(\"#recentOperator .value\").html(\"\");\n ''' % id\n\n @jsaction.handler(buttons['clear'])\n def handlerClear(self, event, selector):\n return '''$(\"#stack .value\").html(\"\");\n $(\"#current .value\").html(\"\");\n $(\"#operator .value\").html(\"\");\n $(\"#recentOperator .value\").html(\"\");'''\n","sub_path":"z3c.formjsdemo/tags/0.2.0/src/z3c/formjsdemo/calculator/browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":4748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"114775701","text":"def socks(arr):\n # sort the array \n # keep count of available pairs\n newArr = []\n count = 0 \n arr = sorted(arr)\n i = 0 \n print(arr)\n while i