diff --git "a/4411.jsonl" "b/4411.jsonl" new file mode 100644--- /dev/null +++ "b/4411.jsonl" @@ -0,0 +1,728 @@ +{"seq_id":"18445389794","text":"\"\"\"\nCreate a Markov model of English language text.\nThis is for testing various Markov model algorithms.\nThis module is horribly obsolete.\n\"\"\"\n\nimport unittest\nimport os\nfrom StringIO import StringIO\nimport logging\nimport sys\nimport Config\n\n# a directory readable and writable from the web\ndata_directory = Config.data_path\n\n# a module-wide logging object\nlogger = logging.getLogger('EnglishModel')\n\n# these letters are the possible states in the simple text model\nsimple_text_states = 'abcdefghijklmnopqrstuvwxyz '\n\n# do not show debugging messages when running as an imported module\nlogger.setLevel(logging.ERROR)\nlogger.addHandler(logging.StreamHandler(sys.stdout))\n\n\ndef get_transition_matrix():\n \"\"\"\n @return: a transition matrix in convenient dictionary form\n \"\"\"\n count_matrix = _get_count_matrix()\n transition_matrix = {}\n for a in simple_text_states:\n row_sum = float(sum(count_matrix[(a, b)] for b in simple_text_states))\n for b in simple_text_states:\n pair = (a, b)\n transition_matrix[pair] = count_matrix[pair] / row_sum\n return transition_matrix\n\ndef _get_count_matrix():\n \"\"\"\n Get the count matrix with caching.\n @return: a count matrix in convenient dictionary form\n \"\"\"\n file_path = os.path.join(data_directory, 'tale_of_two_cities_counts.dat')\n if os.path.isfile(file_path):\n logger.debug('found the cached count matrix file')\n with open(file_path, 'r') as fin:\n count_matrix = _read_count_matrix(fin)\n else:\n logger.debug('failed to find the cached count matrix file')\n raw_text = _get_raw_text()\n sio = StringIO(raw_text)\n simple_text = _raw_text_to_simple_text(sio)\n logger.debug('processed the raw text into simple text')\n count_matrix = dict(((a, b), 1) for a in simple_text_states for b in simple_text_states)\n for a, b in zip(simple_text[:-1], simple_text[1:]):\n count_matrix[(a, b)] += 1\n logger.debug('created the count matrix')\n with open(file_path, 'w') as fout:\n _write_count_matrix(fout, count_matrix)\n logger.debug('cached the count matrix')\n return count_matrix\n\ndef _write_count_matrix(fout, cm):\n \"\"\"\n @param fout: an open file for writing\n @param cm: a count matrix in convenient dictionary form\n \"\"\"\n for (a, b), count in sorted(cm.items()):\n print >> fout, '%s%s:%d' % (a, b, count)\n\ndef _read_count_matrix(fin):\n \"\"\"\n @param fin: an open file for reading\n @return: a count matrix in convenient dictionary form\n \"\"\"\n cm = {}\n for line in fin:\n if line.count(':') != 1:\n continue\n transition_str, count_str = line.split(':')\n assert len(transition_str) == 2, transition_str\n a, b = transition_str\n cm[(a, b)] = int(count_str)\n return cm\n\n\ndef _raw_text_to_simple_text(fin):\n \"\"\"\n @param fin: an ascii text file open for reading\n @return: a simplified text string\n \"\"\"\n arr = []\n space = True\n for c in fin.read():\n if c == \"'\":\n continue\n elif c.isalpha():\n if space:\n arr.append(' ')\n arr.append(c.lower())\n space = False\n else:\n space = True\n if space:\n arr.append(' ')\n return ''.join(arr)\n\ndef _get_raw_text():\n \"\"\"\n Get some text with caching.\n @return: the text string of Tale of Two Cities.\n \"\"\"\n file_path = os.path.join(data_directory, 'tale_of_two_cities.txt')\n if os.path.isfile(file_path):\n logger.debug('found the cached raw text file')\n with open(file_path, 'r') as fin:\n text_string = fin.read()\n logger.debug('read %d characters from the cached file' % len(text_string))\n else:\n logger.debug('failed to find the cached raw text file')\n text_string = _download_raw_text()\n logger.debug('read %d characters from project gutenberg' % len(text_string))\n with open(file_path, 'w') as fout:\n fout.write(text_string)\n logger.debug('cached the raw text file')\n return text_string\n\ndef _download_raw_text():\n \"\"\"\n @return: the text string of Tale of Two Cities.\n \"\"\"\n import urllib\n url = 'http://www.gutenberg.org/files/98/98.txt'\n furl = urllib.urlopen(url)\n text_string = furl.read()\n furl.close()\n return text_string\n\nclass TestEnglishModel(unittest.TestCase):\n def test_foo(self):\n pass\n def test_bar(self):\n pass\n\ndef main():\n logger.debug('hello')\n transition_matrix = get_transition_matrix()\n logger.debug('got a transition matrix with %d transitions' % len(transition_matrix))\n logger.debug('goodbye')\n\nif __name__ == '__main__':\n from optparse import OptionParser\n parser = OptionParser()\n parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False)\n #parser.add_option('-o', '--output', dest='output_filename', metavar='FILE', help='output file')\n parser.add_option('--test', action='store_true', dest='test', default=False)\n options, args = parser.parse_args()\n if options.test:\n suite = unittest.TestLoader().loadTestsFromTestCase(TestEnglishModel)\n unittest.TextTestRunner(verbosity=2).run(suite)\n else:\n if options.verbose:\n logger.setLevel(logging.DEBUG)\n main()\n\n\n","repo_name":"argriffing/xgcode","sub_path":"EnglishModel.py","file_name":"EnglishModel.py","file_ext":"py","file_size_in_byte":5389,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"43391949455","text":"import os\nimport time\nfrom pprint import pprint\nfrom config.sj import COINONE_API_KEY as API_KEY\n\nfrom coin_trader.coin.coinone.coinone import Coinone\n\nfrom db_models.coin.model_tr_coinone import ModelTrCoinone\nfrom db_models.coin.model_currency import ModelCurrency\nfrom db_models.coin.model_exchange import ModelExchange\nfrom mysql.connector.pooling import MySQLConnectionPool\nfrom config.db_config import mysql_config as db_conf\n\n\nclass ExchangeDataCrawler(object):\n\n def __init__(self, cnx_pool):\n self.model_tr = ModelTrCoinone(cnx_pool)\n self.model_currency = ModelCurrency(cnx_pool)\n self.coinone = Coinone()\n\n self.id_currency_dict, self.currency_id_dict = self.model_currency.get_exchange_currency_dict(\n exchange_id=1)\n\n def run(self):\n while True:\n view = {}\n for currency_id, currency_name in self.id_currency_dict.items():\n tr_list = self.coinone.get_tr(currency=currency_name)[\"tr_list\"]\n self.model_tr.insert_tr(currency_id, tr_list)\n view[currency_name] = tr_list[-1]['price']\n \n time.sleep(5)\n os.system('clear')\n print(view)\n\n\ndef run():\n cnx_pool = MySQLConnectionPool(\n pool_name='default_cnx_pool', **db_conf)\n\n exchange_data_crawler = ExchangeDataCrawler(cnx_pool)\n exchange_data_crawler.run()\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"goddoe/coin-trader","sub_path":"app/exchange_data_crawler/exchange_data_crawler.py","file_name":"exchange_data_crawler.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"37579053238","text":"import sys\nfrom collections import deque\n\ninput = sys.stdin.readline\n\n\ndef bfs(lst):\n q = deque(lst)\n while q:\n x = q.popleft()\n visit[x] = 1\n for i in adj[x]:\n if not visit[i]:\n q.append(i)\n visit[i] = 1\n return visit.count(1)\n\n\nn, m = map(int, input().split(' '))\nadj = [[] for _ in range(n + 1)]\nfor _ in range(m):\n a, b = map(int, input().split(' '))\n adj[b].append(a)\n\nres = []\nmax_v = 0\nfor i in range(1, n + 1):\n visit = [0] * (n + 1)\n visit[i] = 1\n if adj[i]:\n tmp = bfs(adj[i])\n if tmp > max_v:\n max_v = tmp\n res = [i]\n elif tmp == max_v:\n res.append(i)\n\nprint(*res)\n","repo_name":"yezyvibe/Algorithm_PS","sub_path":"Backjoon/b_1325_효율적인 해킹.py","file_name":"b_1325_효율적인 해킹.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"26833479708","text":"# We create a bunch of helpful functions throughout the course.\n# Storing them here so they're easily accessible.\n\nimport itertools\nimport os\nimport shutil\nimport subprocess\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.metrics import confusion_matrix, accuracy_score, precision_recall_fscore_support\n\n\ndef load_and_preprocess_image(filename, img_shape=224, scale=True) -> tf.Tensor:\n \"\"\"\n Reads in an image from filename, turns it into a tensor and reshapes into (224, 224, 3).\n\n Args: \n filename (str): string filename of target image\n img_shape (int): size to resize target image to, default 224\n scale (bool): whether to scale pixel values to range(0, 1), default True\n \n Return:\n tf.Tensor: Returns the image after loading and preprocessing\n \"\"\"\n # Read in the image\n img = tf.io.read_file(filename)\n # Decode it into a tensor\n img = tf.image.decode_jpeg(img)\n # Resize the image\n img = tf.image.resize(img, [img_shape, img_shape])\n # Rescale the image (get all values between 0 and 1)\n return img / 255. if scale else img\n\n\n# Note: The following confusion matrix code is a remix of Scikit-Learn's\n# plot_confusion_matrix function - https://scikit-learn.org/stable/modules/generated/sklearn.metrics.plot_confusion_matrix.html\ndef make_confusion_matrix(y_true, y_pred, classes=None, figsize=(10, 10), text_size=15, norm=False, savefig=False):\n \"\"\"\n Makes a labelled confusion matrix comparing predictions and ground truth labels.\n\n If classes is passed, confusion matrix will be labelled, if not, integer \n class values will be used.\n\n Args:\n y_true: Array of truth labels (must be same shape as y_pred).\n y_pred: Array of predicted labels (must be same shape as y_true).\n classes: Array of class labels (e.g. string form). If `None`, integer labels are used.\n figsize: Size of output figure (default=(10, 10)).\n text_size: Size of output figure text (default=15).\n norm: normalize values or not (default=False).\n savefig: save confusion matrix to file (default=False).\n\n Returns:\n A labelled confusion matrix plot comparing y_true and y_pred.\n\n Example usage:\n make_confusion_matrix(y_true=test_labels, # ground truth test labels\n y_pred=y_preds, # predicted labels\n classes=class_names, # array of class label names\n figsize=(15, 15),\n text_size=10)\n \"\"\"\n # Create the confustion matrix\n cm = confusion_matrix(y_true, y_pred)\n cm_norm = cm.astype(\"float\") / \\\n cm.sum(axis=1)[:, np.newaxis] # normalize it\n n_classes = cm.shape[0] # find the number of classes we're dealing with\n\n # Plot the figure and make it pretty\n fig, ax = plt.subplots(figsize=figsize)\n # colors will represent how 'correct' a class is, darker == better\n cax = ax.matshow(cm, cmap=plt.cm.Blues)\n fig.colorbar(cax)\n\n # Are there a list of classes?\n if classes:\n labels = classes\n else:\n labels = np.arange(cm.shape[0])\n\n # Label the axes\n ax.set(title=\"Confusion Matrix\",\n xlabel=\"Predicted label\",\n ylabel=\"True label\",\n xticks=np.arange(n_classes), # create enough axis slots for each class\n yticks=np.arange(n_classes),\n xticklabels=labels, # axes will labeled with class names (if they exist) or ints\n yticklabels=labels)\n\n # Make x-axis labels appear on bottom\n ax.xaxis.set_label_position(\"bottom\")\n ax.xaxis.tick_bottom()\n\n # Set the threshold for different colors\n threshold = (cm.max() + cm.min()) / 2.\n\n # Plot the text on each cell\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n if norm:\n plt.text(j, i, f\"{cm[i, j]} ({cm_norm[i, j] * 100:.1f}%)\",\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > threshold else \"black\",\n size=text_size)\n else:\n plt.text(j, i, f\"{cm[i, j]}\",\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > threshold else \"black\",\n size=text_size)\n\n # Save the figure to the current working directory\n if savefig:\n fig.savefig(\"confusion_matrix.png\")\n\n\n# Make a function to predict on images and plot them (works with multi-class)\ndef predict_and_plot(model, filename, class_names):\n \"\"\"\n Imports an image located at filename, makes a prediction on it with a trained model and plots the image with \\\n the predicted class as the title.\n \"\"\"\n # Import the target image and preprocess it\n img = load_and_preprocess_image(filename)\n\n # Make a prediction\n pred = model.predict(tf.expand_dims(img, axis=0))\n\n # Get the predicted class\n if len(pred[0]) > 1: # check for multi-class\n # if more than one output, take the max\n pred_class = class_names[pred.argmax()]\n else:\n # if only one output, round\n pred_class = class_names[int(tf.round(pred)[0][0])]\n\n # Plot the image and predicted class\n plt.imshow(img)\n plt.title(f\"Prediction: {pred_class}\")\n plt.axis(False)\n\n\ndef plot_loss_curves(history):\n \"\"\"\n Returns separate loss curves for training and validation metrics.\n\n Args:\n history: TensorFlow model History object \\\n (see: https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/History)\n \"\"\"\n loss = history.history['loss']\n val_loss = history.history['val_loss']\n\n accuracy = history.history['accuracy']\n val_accuracy = history.history['val_accuracy']\n\n epochs = range(len(history.history['loss']))\n\n # Plot loss\n plt.plot(epochs, loss, label='training_loss')\n plt.plot(epochs, val_loss, label='val_loss')\n plt.title('Loss')\n plt.xlabel('Epochs')\n plt.legend()\n\n # Plot accuracy\n plt.figure()\n plt.plot(epochs, accuracy, label='training_accuracy')\n plt.plot(epochs, val_accuracy, label='val_accuracy')\n plt.title('Accuracy')\n plt.xlabel('Epochs')\n plt.legend()\n\n\ndef compare_histories(original_history, new_history, initial_epochs=5):\n \"\"\"\n Compares two TensorFlow model History objects.\n\n Args:\n original_history: History object from original model (before new_history)\n new_history: History object from continued model training (after original_history)\n initial_epochs: Number of epochs in original_history (new_history plot starts from here) \n \"\"\"\n\n # Get original history measurements\n acc = original_history.history[\"accuracy\"]\n loss = original_history.history[\"loss\"]\n\n val_acc = original_history.history[\"val_accuracy\"]\n val_loss = original_history.history[\"val_loss\"]\n\n # Combine original history with new history\n total_acc = acc + new_history.history[\"accuracy\"]\n total_loss = loss + new_history.history[\"loss\"]\n\n total_val_acc = val_acc + new_history.history[\"val_accuracy\"]\n total_val_loss = val_loss + new_history.history[\"val_loss\"]\n\n # Make plots\n plt.figure(figsize=(8, 8))\n plt.subplot(2, 1, 1)\n plt.plot(total_acc, label='Training Accuracy')\n plt.plot(total_val_acc, label='Validation Accuracy')\n plt.plot([initial_epochs - 1, initial_epochs - 1],\n plt.ylim(), label='Start Fine Tuning') # reshift plot around epochs\n plt.legend(loc='lower right')\n plt.title('Training and Validation Accuracy')\n\n plt.subplot(2, 1, 2)\n plt.plot(total_loss, label='Training Loss')\n plt.plot(total_val_loss, label='Validation Loss')\n plt.plot([initial_epochs - 1, initial_epochs - 1],\n plt.ylim(), label='Start Fine Tuning') # reshift plot around epochs\n plt.legend(loc='upper right')\n plt.title('Training and Validation Loss')\n plt.xlabel('epoch')\n plt.show()\n\n\ndef run_cmd(cmd, verbose=False, *args, **kwargs):\n \"\"\"\n Run system command as a subprocess\n \"\"\"\n process = subprocess.Popen(cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n text=True,\n shell=True)\n std_out, std_err = process.communicate()\n if verbose:\n print(std_out.strip(), std_err)\n\n\ndef download_and_extract_data(storage_url: str) -> None:\n \"\"\"\n Download and extract zip files from urls. \n\n If the zip file is already downloaded or the zip file is already extracted the file and/or folder will \\\n be deleted before downloading and unzipping the file. \n\n Args:\n storage_url (str): Zip file storage url\n \"\"\"\n zip_file_basename = os.path.basename(storage_url)\n # Remove previously downloaded file with the same name\n if zip_file_basename in os.listdir():\n os.remove(zip_file_basename)\n\n print(f\"Downloading zip file from storage URL: {storage_url}\")\n run_cmd(f\"wget -q {storage_url}\")\n\n # Remove previously extracted directory\n if os.path.isdir(zip_file_basename[:-4]):\n shutil.rmtree(zip_file_basename[:-4])\n\n print(f\"Extracting from zip file: {zip_file_basename}\")\n run_cmd(f\"unzip -q {zip_file_basename} -d {zip_file_basename[:-4]}\")\n\n\ndef walk_through_directory(dir_path):\n \"\"\"\n Walks through directory path returning its contents.\n\n Args:\n dir_path (str): Target directory\n\n Returns:\n A print out of:\n number of subdirectories in dir_path\n number of images (files) in each subdirectory\n name of each subdirectory\n \"\"\"\n for dirpath, dirnames, filenames in os.walk(dir_path):\n dirnames = [d for d in dirnames if not d.startswith(\"__\")]\n filenames = [f for f in filenames if not f.startswith(\".\")]\n print(f\"There are {len(dirnames)} directories and {len(filenames)} images in '{dirpath}'.\")\n\n\n# Function to evaluate: accuracy, precision, recall, f1-score\ndef calculate_results(y_true, y_pred):\n \"\"\"\n Calculates model accuracy, precision, recall and f1 score of a binary classification model.\n\n Args:\n y_true: true labels in the form of a 1D array\n y_pred: predicted labels in the form of a 1D array\n\n Returns a dictionary of accuracy, precision, recall, f1-score.\n \"\"\"\n # Calculate model accuracy\n model_accuracy = accuracy_score(y_true, y_pred) * 100\n # Calculate model precision, recall and f1 score using \"weighted average\n model_precision, model_recall, model_f1, _ = precision_recall_fscore_support(y_true,\n y_pred,\n average=\"weighted\")\n model_results = {\"accuracy\": model_accuracy,\n \"precision\": model_precision,\n \"recall\": model_recall,\n \"f1\": model_f1}\n return model_results\n\n\n# Create a function to plot time series data\ndef plot_time_series(timesteps, values, format='.', start=0, end=None, label=None):\n \"\"\"\n Plots a timesteps (a series of points in time) against values (a series of values across timesteps).\n \n Args:\n timesteps (float): array of timesteps\n values (float): array of values across time\n format (str): style of plot, default \".\"\n start (int): where to start the plot (setting a value will index from start of timesteps & values)\n end (int): where to end the plot (setting a value will index from end of timesteps & values)\n label (str): label to show on plot of values\n \"\"\"\n # Plot the series\n plt.plot(timesteps[start:end], values[start:end], format, label=label)\n plt.xlabel(\"Time\")\n plt.ylabel(\"BTC Price\")\n if label:\n plt.legend(fontsize=14) # make label bigger\n plt.grid(True)\n\n\ndef mean_absolute_scaled_error(y_true, y_pred):\n \"\"\"\n Implement MASE (assuming no seasonality of data).\n\n # MASE implemented courtesy of sktime - https://github.com/alan-turing-institute/sktime/blob/ee7a06843a44f4aaec7582d847e36073a9ab0566/sktime/performance_metrics/forecasting/_functions.py#L16\n\n \"\"\"\n mae = tf.reduce_mean(tf.abs(y_true - y_pred))\n\n # Find MAE of naive forecast (no seasonality)\n mae_naive_no_season = tf.reduce_mean(tf.abs(y_true[1:] - y_true[:-1])) # our seasonality is 1 day (hence the shifting of 1 day)\n\n return mae / mae_naive_no_season\n\n\ndef evaluate_time_series_preds(y_true, y_pred):\n \"\"\"\n Evaluate Time Series Predictions and return metrics.\n\n Returns:\n dict: Metrics dictionary with keys 'mae', 'mse', 'mape', and 'mase'\n \"\"\"\n # Make sure float32 (for metric calculations)\n y_true = tf.cast(y_true, dtype=tf.float32)\n y_pred = tf.cast(y_pred, dtype=tf.float32)\n\n # Calculate various metrics\n mae = tf.keras.metrics.mean_absolute_error(y_true, y_pred)\n mse = tf.keras.metrics.mean_squared_error(y_true, y_pred) # puts and emphasis on outliers (all errors get squared)\n rmse = tf.sqrt(mse)\n mape = tf.keras.metrics.mean_absolute_percentage_error(y_true, y_pred)\n mase = mean_absolute_scaled_error(y_true, y_pred)\n\n # If metric isn't already a scalar, reduce it to one by aggregating tensors to mean\n if mae.ndim > 0:\n mae = tf.reduce_mean(mae)\n mse = tf.reduce_mean(mse)\n rmse = tf.reduce_mean(rmse)\n mape = tf.reduce_mean(mape)\n mase = tf.reduce_mean(mase)\n \n return {\"mae\": mae.numpy(),\n \"mse\": mse.numpy(),\n \"rmse\": rmse.numpy(),\n \"mape\": mape.numpy(),\n \"mase\": mase.numpy()}\n","repo_name":"Mathews-Tom/Deep-Learning-with-TensorFlow","sub_path":"Extras/custom_helpers.py","file_name":"custom_helpers.py","file_ext":"py","file_size_in_byte":13702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"8336482697","text":"# Converges approximately to the book example\n# Using one-step policy update or TD(0)\n\nimport numpy as np\nimport random\n\n# 0 - L, 1 - U, 2 - R, 3 - D\nclass Agent:\n def __init__(self, maxx, maxy, iters, episodes, discount):\n self.maxx = maxx\n self.maxy = maxy\n self.currx = 0\n self.curry = 0\n self.discount = discount\n self.iters = iters\n self.episodes = episodes\n self.state_value = np.zeros(shape=(maxx, maxy))\n self.state_visit = np.zeros(shape=(maxx, maxy))\n\n def reset(self):\n self.currx = np.random.choice(self.maxx)\n self.curry = np.random.choice(self.maxy)\n\n def run(self):\n for i in range(self.iters):\n for j in range(self.episodes):\n self.take_step()\n print(\"State Value after \" + str(i+1) + \" iterations: \")\n print(self.state_value)\n self.reset()\n\n def take_step(self):\n # all random policy \n action = np.random.choice(4)\n self.move(action)\n \n def move(self, action):\n next_x = self.currx\n next_y = self.curry\n if(action == 0):\n next_x += -1\n elif(action == 1):\n next_y += -1\n elif(action == 2):\n next_x += 1\n elif(action == 3):\n next_y += 1\n\n if(next_x < 0 or next_x >= self.maxx or next_y < 0 or next_y >= self.maxy):\n self.update_state(self.currx, self.curry, -1)\n else:\n self.update_state(next_x, next_y, 0)\n \n if(next_x==0 and next_y==1):\n self.update_state(4, 1, 10) \n if(next_x==0 and next_y==3):\n self.update_state(2, 3, 5)\n \n def update_state(self, next_x, next_y, reward):\n self.state_visit[self.currx][self.curry] += 1\n self.state_value[self.currx][self.curry] += (self.state_value[next_x][next_y] * self.discount + reward - \n self.state_value[self.currx][self.curry]) / self.state_visit[self.currx][self.curry]\n self.currx = next_x\n self.curry = next_y\n\ndef main():\n agent_obj = Agent(5, 5, 100, 1000, 0.9)\n agent_obj.run()\n print(agent_obj.state_value)\n \nif __name__ == '__main__':\n main()\n","repo_name":"ygutgutia/Reinforcement-Learning-2nd-Edition-by-Sutton-Codes","sub_path":"Ch3/Gridworld.py","file_name":"Gridworld.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"7558252427","text":"\"\"\"不可变数据类型\"\"\"\n# 数字 int, bool, float, complex\n# 字符串 str\n# 元组 tuple\n\n\"\"\"可变数据类型\"\"\"\n# 列表\n# 字典\n\na = [1, 2, 3]\nprint(id(a))\na.append(99)\nprint(a)\nprint(id(a))\n\nkey = (1,'k',True)\n\nDictionary = {\n key: '元组可以作为字典的key'\n}\nprint(Dictionary)\n\n# 哈希\n\"\"\"\n接收一个不可变类型作为参数\n返回一个整数\n哈希是一种算法,其作用是提取数据的特征码\n相同的内容 得到 相同的结果\n不同的内容 得到 不同的结果\n在py中,设置字典的键值对,会首先对key进行 hash 处理已决定如何在内存中保存字典数据,以方便后续的CRUD\n\n\"\"\"","repo_name":"ruoduan-hub/myPython","sub_path":"py语法/py_00数据类型.py","file_name":"py_00数据类型.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"40557100947","text":"\"\"\"给定两个二进制字符串,返回他们的和(用二进制表示)。输入为非空字符串且只包含数字 1 和 0。\n示例 1:\n输入: a = \"11\", b = \"1\"\n输出: \"100\"\n示例 2:\n输入: a = \"1010\", b = \"1011\"\n输出: \"10101\"\n\"\"\"\n\n\nclass Solution:\n def addBinary(self, a, b):\n \"\"\" :type a: str :type b: str :rtype: str \"\"\"\n return bin(int(a, 2) + int(b, 2))[2:]\n\n \"\"\" # int(x, base=10) x--字符串或数字, int(3.6): 返回整型数据。\n # int('12',16) 18 # 如果是带参数base的话,12要以字符串的形式进行输入,12 为 16进制,转换为10进制\"\"\"\n\n\nprint(bin(10)[2:]) # bin()返回str字符串类型\nprint(int(\"1010\", 2)) # 转换为十进制的 返回int类型的10\n","repo_name":"cp4011/Algorithms","sub_path":"LeetCode/67_二进制求和.py","file_name":"67_二进制求和.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"20782222484","text":"hyperparameters = {\n # 'seed': 42,\n # 'fast': \"\",\n # 'mixup': \"\",\n # 'balance': \"\",\n # 'balance-datasets': \"\",\n # 'swa': \"\",\n # 'show': \"\",\n # 'use-idrid':\"\",\n # 'use-messidor':\"\",\n # 'use-aptos-2015': \"\",\n # 'use-aptos-2019': \"\",\n # 'verbose': \"\",\n # 'coarse': \"\",\n 'accumulation-steps': 1,\n 'data-dir': \"/opt/ml/input/data\",\n 'model': 'efficientb6_max',\n 'batch-size': 64,\n 'epochs': 100,\n 'early-stopping': 20,\n 'fold': 0, # not more than 4 fold\n # 'freeze-encoder': \"\",\n 'learning-rate': 1e-4,\n # 'criterion-log': ['mse'],\n # 'criterion-crd': None,\n # 'criterion-cls': None,\n # 'l1': 2e-4,\n # 'l2': 0,\n 'optimizer': 'Adam',\n # 'preprocessing': None,\n # 'checkpoint': None,\n # 'workers': 4,\n 'augmentations': 'medium',\n # 'tta': None,\n # 'transfer': None,\n # 'fp16': \"\",\n 'scheduler': 'multistep',\n 'size': 512,\n # 'weight-decay': 0.0,\n # 'weight-decay-step': None,\n 'dropout': 0.4,\n 'warmup': 0,\n # 'experiment': None,\n}\n","repo_name":"Ramstein/Diabetic-Retinopathy-Blindness-Detection","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"72834112391","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals, print_function, absolute_import\n\nimport click\n\nfrom nidaba import lex\n\n\n@click.command()\n@click.option('--input', help='Input text', type=click.Path(exists=True,\n dir_okay=False), required=True)\n@click.option('--del_dict', help='Path to the output deletion dictionary',\n type=click.Path(writable=True, dir_okay=False), required=True)\n@click.option('--dictionary', help='Path to the output word list',\n type=click.Path(writable=True, dir_okay=False), required=True)\n@click.option('--depth', default=1, help='Maximum precalculated edit distance '\n 'in deletion dictionary')\n@click.version_option()\ndef main(input, del_dict, dictionary, depth):\n click.echo('Reading input file\\t[', nl=False)\n words = lex.cleanuniquewords(input)\n click.secho(u'\\u2713', fg='green', nl=False)\n click.echo(']')\n click.echo('Writing dictionary\\t[', nl=False)\n lex.make_dict(dictionary, words)\n click.secho(u'\\u2713', fg='green', nl=False)\n click.echo(']')\n click.echo('Writing deletions\\t[', nl=False)\n lex.make_deldict(del_dict, words, depth)\n click.secho(u'\\u2713', fg='green', nl=False)\n click.echo(']')\n","repo_name":"OpenPhilology/nidaba","sub_path":"nidaba/contrib/mkdict.py","file_name":"mkdict.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":84,"dataset":"github-code","pt":"27"} +{"seq_id":"22305187409","text":"\"\"\"\nA basic scrapper which receives a domain name and returns all of the links in the domain.\n\"\"\"\nimport argparse\nfrom datetime import datetime as dt, datetime\n\nfrom sqlalchemy.orm import Session\n\nfrom dotmap import DotMap\nfrom sqlalchemy import exists\n\nfrom cookieMuncher.spiders.cookie_muncher import crawl\nimport os\nimport json\nfrom urllib.parse import urlparse\nfrom db import engine, MuncherConfig, MuncherSchedule, MuncherStats\nfrom utils import check_directory_exists, LOG_FIXTURE, create_parser\n\n\ndef generate_file_name(folder, schedule_id, fixture):\n \"\"\"\n Creates the file name from the folder and domains that the crawler will crawl.\n the file name will be: [datetime] [net locations of domains given].[fixture]\n :param folder: The folder where the file we be saved\n :param domains: The domains the crawler will crawl.\n :param fixture: The fixture of the file.\n :return: The full path to the file.\n \"\"\"\n return os.path.join(folder,\n \"urls_scan_schedule_{}_{}.{}\".format(schedule_id, str(dt.now()).replace(':', '.'),\n fixture))\n\n\ndef generate_netlocations_from_domains(domains):\n return list({urlparse(domain).netloc for domain in domains.split()})\n\n\ndef format_arguments(args, schedule_id):\n \"\"\"\n Formats the arguments given to the script.\n :param args: The args given to the script.\n :return: The formatted args.\n \"\"\"\n allowed_domains = []\n if args.domain_only:\n allowed_domains = generate_netlocations_from_domains(args.domains)\n if args.silent:\n args.log_file = None\n else:\n args.log_file = generate_file_name(args.logs_folder, schedule_id, LOG_FIXTURE)\n args.domains = args.domains.split()\n check_directory_exists(args.logs_folder)\n return args, allowed_domains\n\n\ndef create_muncher_stats(session, schedule_id):\n \"\"\"\n Creates the stats table for this schedule, if a table already exists for this schedule aborts the run.\n :param Session session: The session with the mysql db.\n :param schedule_id: The schedule id for this run.\n :return: True if the stats was created successfully false otherwise.\n \"\"\"\n if session.query(exists().where(MuncherStats.schedule_id == schedule_id)).scalar():\n print(\"There is already a muncher stats with the schedule id of {}\".format(schedule_id))\n return None\n else:\n stats = MuncherStats(schedule_id=schedule_id)\n session.add(stats)\n session.commit()\n return stats\n\n\ndef run(parser):\n \"\"\"\n Creates the crawler using the parser to parse the cli arguments.\n :param parser: A configured instance of argsParser\n :return: A configured crawler instance.\n \"\"\"\n start = datetime.now()\n session = Session(engine)\n id = parser.parse_args().id\n schedule = session.query(MuncherSchedule).get(id)\n config = session.query(MuncherConfig).get(schedule.config_id)\n stats = create_muncher_stats(session, id)\n if stats:\n args, allowed_domains = format_arguments(DotMap(json.loads(config.json_params)), id)\n stats.urls_log_path = args.log_file\n session.commit()\n crawl(id, args.domains, allowed_domains, args.depth, args.silent, args.log_file, args.delay, args.user_agent)\n stats.url_scan_duration = (datetime.now() - start).seconds\n session.commit()\n session.close()\n\n\nif __name__ == '__main__':\n parser = create_parser()\n run(parser)\n","repo_name":"gnir-work/cookie-muncher","sub_path":"process1.py","file_name":"process1.py","file_ext":"py","file_size_in_byte":3484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"32885213060","text":"from dataclasses import dataclass\n\nfrom .baseflatliner import BaseFlatliner\n\nclass AlertFrequencyCluster(BaseFlatliner):\n\n \"\"\"\n This class contains the code for correlation of alerts for every cluster\n\n \"\"\"\n\n def __init__(self):\n super().__init__()\n # Hold the values for different clusters\n # For maxsize, it should be bigger than the number of new cluster ids coming\n # in during the time window (30 mins)\n # promql: count(sum(count_over_time(cluster_version[30m])) by (_id))\n self.clusters = self.create_cache_dict(maxsize=1000)\n\n def on_next(self, x):\n \"\"\" On each entry we will update the frequency of alerts for a 30 minute time window\n \"\"\"\n\n if not self.metric_name(x) == 'alerts':\n return\n\n alert_name = self.metric_label(x, 'alertname')\n cluster_id = self.cluster_id(x)\n time_stamp = self.metric_values(x)[0][0]\n time_window = 30 # in minutes\n\n if cluster_id not in self.clusters:\n self.clusters[cluster_id] = dict()\n\n if alert_name not in self.clusters[cluster_id]:\n self.intilize_freqency(x, alert_name,cluster_id)\n\n else:\n self.calculate_frequency(alert_name,cluster_id, time_window, time_stamp)\n\n self.normalize_cluster(cluster_id, alert_name)\n self.publish(self.clusters[cluster_id][alert_name])\n\n\n def intilize_freqency(self, x, alert_name, cluster_id):\n\n state = self.State()\n state.cluster = self.cluster_id(x)\n state.alert = self.metric_label(x,'alertname')\n state.version = self.cluster_version(x)\n state.frequency = 1.0\n state.timestamp = self.metric_values(x)[0][0]\n state.time_stamps = [self.metric_values(x)[0][0]]\n\n self.clusters[cluster_id][alert_name] = state\n\n def calculate_frequency(self, alert_name,cluster_id, time_window, time_stamp):\n\n time_limit = time_window * 60\n self.clusters[cluster_id][alert_name].timestamp = time_stamp\n self.clusters[cluster_id][alert_name].time_stamps = [x for x in self.clusters[cluster_id][alert_name].time_stamps\n if x >= (time_stamp-time_limit)]\n\n self.clusters[cluster_id][alert_name].time_stamps.append(time_stamp)\n\n # using the length of the timestamps should suffice to determine the frequency as the value is always 1\n self.clusters[cluster_id][alert_name].frequency = float(len(self.clusters[cluster_id]\n [alert_name].time_stamps))\n\n\n def normalize_cluster(self, cluster_id, alert):\n # get the values:\n alert_names = list(self.clusters[cluster_id].keys())\n alert_vector_length = len(alert_names)\n alert_list = []\n\n if alert_vector_length == 1:\n self.clusters[cluster_id][alert].frequency = 1.0\n return\n\n for i in alert_names:\n alert_list.append(self.clusters[cluster_id][i].frequency)\n max_value = max(alert_list)\n min_value = min(alert_list)\n\n for value, name in zip(alert_list, alert_names):\n if max_value != min_value:\n self.clusters[cluster_id][name].frequency = ((value - min_value)/(max_value - min_value))\\\n / (alert_vector_length)**(0.5)\n else:\n self.clusters[cluster_id][name].frequency = 1.0\n\n\n @dataclass\n class State:\n\n cluster: str = \"\"\n alert: str = \"\"\n version: str = \"\"\n frequency: float = 0.0\n timestamp: float = 0.0\n time_stamps: str = \"\"\n","repo_name":"AICoE/prometheus-flatliner","sub_path":"flatliners/alertfrequencycluster.py","file_name":"alertfrequencycluster.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"27"} +{"seq_id":"15970377291","text":"from selenium import webdriver\nfrom sys import argv\nimport csv\nimport time\nimport os\nbaseURL = \"C:/Users/parthShinojiya/Desktop/ISTE2k19/receipt/\"\ndriver = webdriver.Chrome(baseURL + 'browser_driver/chromedriver')\ndriver.set_window_size(725,440) #(width,hight)\ndriver.get(baseURL + 'receipt.html')\nfile_name = 'CSVFiles/' + argv[1] + '.csv'\nform_date = argv[1]\n#file_name = 'CSVFiles/' + input(\"Enter csv file name with extension:\")\n#form_date = input(\"Enter date for form like, 31-08-2019 :\")\nos.mkdir(baseURL + 'images/' + form_date)\n\nparticipated_no = 0\nprevious_sr_no = 'initial'\niste_number = ''\nname = ''\nmobile_no = ''\ntotal_amount = ''\nemail = ''\n#input('Press any key to start')\n\nwith open(file_name, 'r') as csvfile:\n\treader_master = csv.reader(csvfile, delimiter='|')\n\tfor row in reader_master:\n\t\tstatus = row[14] #12\n\t\tif status == 'Ok-2':\n\t\t\tsr_no = row[0]\n\t\t\tif sr_no == previous_sr_no:\n\t\t\t\tparticipated_no += 1\n\t\t\t\tevent_name = row[10] #9\n\t\t\t\tevent_element_name = 'event' + str(participated_no)\n\t\t\t\tevent_name_element = driver.find_element_by_name(event_element_name)\n\t\t\t\tevent_name_element.send_keys(event_name)\n\t\t\telse:\n\t\t\t\tparticipated_no_element = driver.find_element_by_name('participated_no')\n\t\t\t\tparticipated_no_element.send_keys(participated_no)\n\t\t\t\ttotal_amount_element = driver.find_element_by_name('total_amount')\n\t\t\t\ttotal_amount_element.send_keys(total_amount)\n\t\t\t\theader_element=driver.find_element_by_name('header')\n\t\t\t\theader_element.click()\n\t\t\t\tss_name = previous_sr_no+ '_' + email\n\t\t\t\t#ss_name = previous_sr_no\n\t\t\t\tdriver.save_screenshot('images/' + form_date + '/' + str(ss_name) + \".png\")\n\n\t\t\t\tdate_element = driver.find_element_by_name('date')\n\t\t\t\tdate_element.clear()\n\t\t\t\tsr_no_element = driver.find_element_by_name('srno')\n\t\t\t\tsr_no_element.clear()\n\t\t\t\tname_element = driver.find_element_by_name('name')\n\t\t\t\tname_element.clear()\n\t\t\t\tmobile_no_element = driver.find_element_by_name('mobile')\n\t\t\t\tmobile_no_element.clear()\n\t\t\t\tiste_number_element = driver.find_element_by_name('iste_no')\n\t\t\t\tiste_number_element.clear()\n\t\t\t\tevent_name_element = driver.find_element_by_name('event1')\n\t\t\t\tevent_name_element.clear()\n\t\t\t\tdriver.find_element_by_name('event2').clear()\n\t\t\t\tdriver.find_element_by_name('event3').clear()\n\t\t\t\tdriver.find_element_by_name('event4').clear()\n\t\t\t\tdriver.find_element_by_name('event5').clear()\n\t\t\t\tdriver.find_element_by_name('event6').clear()\n\t\t\t\tparticipated_no_element.clear()\n\t\t\t\ttotal_amount_element.clear()\n\n\t\t\t\tprevious_sr_no = sr_no\n\t\t\t\tparticipated_no = 1\n\t\t\t\tname = row[4] #3\n\t\t\t\temail = row[7] #6\n\t\t\t\tmobile_no = row[8] #7\n\t\t\t\tiste_number = row[2] #2\n\t\t\t\tevent_name = row[10] #9\n\t\t\t\ttotal_amount = row[12] #10\n\n\t\t\t\tdate_element.send_keys(form_date)\n\t\t\t\tsr_no_element.send_keys(sr_no)\n\t\t\t\tname_element.send_keys(name)\n\t\t\t\tmobile_no_element.send_keys(mobile_no)\n\t\t\t\tiste_number_element.send_keys(iste_number)\n\t\t\t\tevent_name_element.send_keys(event_name)\nos.remove('images/' + form_date + '/initial_.png')","repo_name":"sparth62/PythonProjects","sub_path":"Automation of Registration process/receipt/receipt.py","file_name":"receipt.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"7452465389","text":"'''\n어떠한 수 N이 1이 될 때까지 다음의 두 과정 중 하나를 반복적으로 선택하여 수행하려고한다.\n단, 두 번째 연산은 N이 K로 나누어떨어질 때만 선택할 수 있다.\n\n1. N에서 1을 뺀다.\n2. N을 K로 나눈다.\n'''\ncount = 0\nn, m = map(int, input().split())\n\nwhile True:\n if n % m == 0 :\n n = int(n / m)\n count += 1\n elif n == 1:\n break\n else :\n n -= 1\n count += 1\n\n \n\nprint(count)\n","repo_name":"NohGaSeong/Algorithm","sub_path":"이것이 코테다/1이 될 때까지.py","file_name":"1이 될 때까지.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"72609496071","text":"\"\"\"\nThis contains the tools for finding reports in the downloads folder\nand moving them to the appropriate locations\n\nCreated by adam on 3/24/20\n\"\"\"\n__author__ = 'adam'\n\nimport os\nimport re\nimport shutil\nfrom functools import wraps\nfrom CanvasHacks import environment as env\nfrom CanvasHacks.PeerReviewed.Definitions import Unit\nfrom CanvasHacks.TimeTools import current_utc_timestamp, timestamp_for_unique_filenames\n\n\nUNIT_RX = re.compile( r\"(\\bunit\\b) (\\d+)\" )\n\nDOWNLOAD_FOLDER = \"{}/Downloads\".format(env.ROOT)\n\n\ndef normalize_filename( f ):\n @wraps( f )\n def d( *args, **kwargs ):\n fname = args[ 0 ].strip().lower()\n return f( fname, **kwargs )\n\n return d\n\n\n@normalize_filename\ndef is_csv( filename ):\n \"\"\"\n Returns true if filename ends in csv\n :param filename:\n :return:\n \"\"\"\n # f = filename.strip().lower()\n return filename[ -4: ] == '.csv'\n\n\n@normalize_filename\ndef is_report( filename ):\n \"\"\"\n Returns true if seems to be a report, false otherwise\n :param filename:\n :return:\n \"\"\"\n # f = filename.strip().lower()\n\n return UNIT_RX.search( filename ) is not None\n\n\n@normalize_filename\ndef get_unit_number( filename ):\n # f = filename.strip().lower()\n match = UNIT_RX.search( filename )\n # start = match.span[0]\n # stop = match.span[1]\n return int( match.group( 2 ) )\n\n\n@normalize_filename\ndef get_activity_type( filename ):\n for c in Unit.component_types:\n if c.is_activity_type( filename ):\n return c\n\n\ndef report_file_iterator( folderPath, exclude=[ ] ):\n exclude = exclude if any( exclude ) else [ '.DS_Store' ]\n for root, dirs, files in os.walk( folderPath ):\n for name in files:\n if name not in exclude:\n if is_csv( name ) and is_report( name ):\n path = os.path.join( root, name )\n d = {\n 'unit_number': get_unit_number( name ),\n 'file_name': name,\n 'path': path,\n 'activity': get_activity_type( name )\n }\n yield d\n\n\ndef file_reports(download_folder_path, unit_start=1, unit_stop=6):\n \"\"\"\n Moves reports found in the download folder to the\n correct folder\n :param download_folder_path:\n :return:\n \"\"\"\n\n units = { u: Unit( env.CONFIG.course, u ) for u in range(unit_start, unit_stop + 1) }\n fiter = report_file_iterator( download_folder_path )\n moved_files = []\n try:\n while True:\n f = next(fiter)\n if f['activity'] is not None:\n unit = units.get(f['unit_number'])\n activity = unit.get_by_class(f['activity'])\n src = f['path']\n\n # Rename with timestamp so no collisions\n # THIS DOES NOT GUARANTEE THAT THE NEWEST FILE CAN BE DETERMINED BY\n # TIMESTAMP!\n to = \"{}/{} {}\".format(activity.folder_path, timestamp_for_unique_filenames(), f['file_name'])\n shutil.move(src, to)\n moved_files.append({'from': src, 'to': to})\n\n except StopIteration:\n for f in moved_files:\n print(\"\\n----\\n FROM: {from} \\n TO: {to}\".format(**f))\n return moved_files\n\n\nif __name__ == '__main__':\n DOWNLOAD_FOLDER = \"{}/Downloads\".format( env.ROOT )\n\n file_reports(DOWNLOAD_FOLDER)\n","repo_name":"AdamSwenson/CanvasHacks","sub_path":"CanvasHacks/Files/FromDownloadFolder.py","file_name":"FromDownloadFolder.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"72643668553","text":"\"\"\"Mapping like data structures\"\"\"\n\nfrom collections import abc\n\n\nclass DotDict:\n \"\"\"\n Dictionary that allows for the retrival of items via dot notation\n\n Can only access keys that are valid identifiers as defined by\n ``str.isidentifier``\n \"\"\"\n\n def __init__(self, mapping):\n if isinstance(mapping, abc.MutableMapping):\n self.__dict = dict(mapping)\n else:\n raise TypeError(\"Requires mapping type\")\n\n self.unallowed_attributes = []\n for name in mapping.keys():\n if name.isidentifier():\n value = self.__dict[name]\n\n # if the element is a dict, recurse\n if isinstance(value, abc.MutableMapping):\n value = DotDict(value)\n\n setattr(self, name, value)\n else:\n self.unallowed_attributes.append(name)\n\n def __repr__(self): # pragma: no cover\n return str(self.__dict)\n","repo_name":"alysivji/sivtools","sub_path":"sivtools/data_structures/mapping.py","file_name":"mapping.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"27"} +{"seq_id":"7019445328","text":"\"\"\"\nCzemu?\na^11 = a^(1 + 2 + 8) = a * a^2 * ((a^2)^2)^2)\n\n\"\"\"\n\ndef potega(a, b):\n\twynik = 1\n\twhile b:\n\t\tif b % 2:\n\t\t\twynik *= a\n\t\ta *= a\n\t\tb //= 2\n\treturn wynik\n","repo_name":"Teletrup/maturka","sub_path":"algorytmy/python/szybka_potega.py","file_name":"szybka_potega.py","file_ext":"py","file_size_in_byte":161,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"26688779047","text":"# NOT FINALIZED and not needed right now\n# this file reads the json data the Landesmuseum Baden provided\n# and saves the index images with the corresponding metadata in a new json file\n\nfrom absl import app\nfrom absl import flags\n\n#import ijson\nimport json \nimport csv\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string(\n 'index_path', 'delg/workspace/data/index.csv',\n 'Path to .csv file where all index images are listed, each in a separate row.'\n)\nflags.DEFINE_string(\n 'json_path', 'delg/workspace/metadata/blmki_bildarchivstaufen.json',\n 'Path to Baden\\'s \"Staufen\" .json file with metadata.'\n)\ndef main(argv):\n extension='.jpg'\n # jsonFile = open(FLAGS.json_path, 'rb')\n \n all_images=[]\n index_list = []\n\n with open(FLAGS.index_path) as csv_file:\n reader = csv.reader(csv_file)\n for row in reader: # each row is a list\n index_list.append(row[0])\n # use ijson when everything in one line\n #for i in ijson.items(j, 'records.item.medium.item.name', multiple_values=True):\n \"\"\" for record in ijson.items(jsonFile, 'records.item', multiple_values=True):\n if 'medium' in record:\n for i in record['medium']:\n print(i)\n for image_name in index_list:\n if i[\"name\"] == image_name+extension:\n image_name = i\n # loc_name = record['ort']\n hist_image = HistImage(name=\"i\")\n all_images.append(hist_image)\n print(i)\n else:\n print(record['objektid']) \"\"\"\n with open(FLAGS.json_path, 'r') as json_file:\n data = json.load(json_file)\n for record in data['records']:\n if 'medium' in record:\n for i in record['medium']:\n for image_name in index_list:\n if i[\"name\"] == image_name+extension:\n #image_name = i\n # loc_name = record['ort']\n for o in record[\"ort\"]:\n if o[\"typ\"] == 'Herstellungsort' and 'lat' in o:\n loc_name = o[\"term\"]\n lat = o[\"lat\"]\n lon = o[\"lon\"]\n \n hist_image = {\n \"name\": image_name,\n \"loc_name\": loc_name,\n \"lat\": lat,\n \"lon\": lon,\n }\n # hist_image = HistImage(name=\"i\")\n all_images.append(hist_image)\n print(hist_image)\n \"\"\" else:\n print(record) \"\"\"\n \n print(all_images) \n \nclass HistImage:\n def __init__(self, name=\"\", loc_name=\"\", lat=None, lon=None, construction=\"\", demolition=\"\"):\n self.image_name = name\n self.location_name = loc_name\n self.lat = lat\n self.lon = lon\n self.construction = construction\n self.demolition = demolition \t\n \t\nif __name__ == '__main__':\n app.run(main)\n","repo_name":"93Dennis/photo-geolocalization","sub_path":"read_data.py","file_name":"read_data.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"15513219770","text":"import pytest\nimport subprocess\nimport server\nfrom random import SystemRandom\nimport string\nfrom unittest import mock\nfrom multiprocessing import Process\nfrom time import sleep\nfrom sparkbot import SparkBot, receiver\nfrom sparkbot.exceptions import CommandSetupError\nfrom wsgiref import simple_server\nimport requests\nfrom requests.exceptions import ConnectionError\nfrom ciscosparkapi import CiscoSparkAPI\n\nclass TestAPI:\n\n def random_bytes(self, length):\n \"\"\"Returns a random bytes array with uppercase and lowercase letters, of length length\"\"\"\n cryptogen = SystemRandom()\n my_random_string = ''.join([cryptogen.choice(string.ascii_letters) for _ in range(length)])\n my_random_bytes = my_random_string.encode(encoding='utf_8')\n\n return my_random_bytes\n\n @pytest.fixture(scope=\"session\")\n def emulator_prereqs(self):\n \"\"\" Ensures that the WebEx API emulator can be run \"\"\"\n\n # Make sure we can start node\n try:\n subprocess.run(\"node -v\", shell=True, check=True)\n except subprocess.CalledProcessError:\n pytest.fail(\"Unable to execute Node. I won't be able to test the bot. Please install node.js and try again.\")\n\n return True\n\n @pytest.fixture(scope=\"session\")\n def emulator_server_zip(self, tmpdir_factory, emulator_prereqs):\n \"\"\" Returns a zipfile.ZipFile containing an installed emulator server \"\"\"\n\n from subprocess import CalledProcessError\n import zipfile\n import shutil\n from urllib.request import urlretrieve\n import os\n\n tmpdir = tmpdir_factory.mktemp(\"emulator\")\n\n fresh_emulator_zip = \".testcache/webex-api-emulator-fresh.zip\"\n fresh_emulator_zip_extract_dir = tmpdir.join(\"webex-api-emulator\")\n installed_emulator_zip_filename = \".testcache/webex-api-emulator-installed\"\n\n try:\n os.mkdir(\".testcache\")\n except FileExistsError:\n pass\n\n urlretrieve(\"https://github.com/webex/webex-api-emulator/archive/master.zip\", fresh_emulator_zip)\n\n with zipfile.ZipFile(fresh_emulator_zip) as myzip:\n first_member = myzip.namelist()[0]\n myzip.extractall(path=str(fresh_emulator_zip_extract_dir))\n\n built_server_directory = fresh_emulator_zip_extract_dir.join(first_member)\n\n print(\"Building zip\")\n try:\n subprocess.run([\"npm install\"], shell=True, check=True, cwd=str(built_server_directory))\n except CalledProcessError:\n pytest.fail(\"Failed to run `npm install`. Try again in a few seconds, then try deleting the '.testcache' folder.\")\n\n # Pack the installed files into a new zip\n installed_emulator_zip = shutil.make_archive(installed_emulator_zip_filename,\n \"zip\",\n str(built_server_directory))\n\n newzip_read = zipfile.ZipFile(installed_emulator_zip)\n yield newzip_read\n newzip_read.close()\n\n @pytest.fixture\n def emulator_server_files(self, tmpdir, emulator_server_zip):\n \"\"\" Returns a path to a WebEx API emulator in temporary storage as a `py._path.local`_\n\n .. _py._path.local:https://py.readthedocs.io/en/latest/path.html#py._path.local.LocalPath\n \"\"\"\n\n emulator_server_zip.extractall(path=str(tmpdir))\n\n # Python 3.6+ had a behavior change for zip files. Zipfiles created on\n # 3.5 have `webex-api-emulator-master` as their first component. 3.6+\n # zipfiles do not have this.\n\n zip_component = \"\"\n\n if emulator_server_zip.namelist()[0] == \"webex-api-emulator-master/\":\n zip_component = \"webex-api-emulator-master/\"\n\n return tmpdir.join(zip_component)\n\n @pytest.fixture(scope=\"session\")\n def unique_port(self):\n \"\"\" Returns a generator that counts up, used for port numbers for the emulator server.\n\n To use this counter, use 'unique_port.__next()'\n \"\"\"\n\n from itertools import count\n\n return count(start=10001)\n\n @pytest.fixture\n def emulator_server(self, emulator_server_files, unique_port):\n \"\"\" Starts up and returns a WebEx API emulator as a server.WebexAPIEmulator \"\"\"\n\n port = unique_port.__next__()\n\n emulator = server.WebexAPIEmulator(emulator_server_files, port)\n\n emulator.start()\n yield emulator\n emulator.stop()\n\n def get_spark_api(self, server):\n \"\"\"\n Returns a ciscosparkapi.CiscoSparkAPI object for the server.WebexAPIEmulator\n specified by 'server'\n \"\"\"\n return CiscoSparkAPI(base_url=server.url, access_token=server.bot_token)\n\n @pytest.fixture\n def full_bot_setup(self, emulator_server, unique_port):\n \"\"\" Sets up everything needed to test a bot, including a set-up webhook and receiver\n\n To use this fixture, first run ``full_bot_setup[\"receiver_process\"].start()`` to run the\n receiver AFTER you have added commands to the bot. Next, ``GET receiver_webhook_url`` to\n prevent a race condition between the server startup and your test. Then, use\n ``self.invoke_bot()`` or your preferred method to get a response from the bot.\n\n :returns: Dict with the format\n {\n \"bot\": sparkbot.SparkBot,\n \"receiver\": sparkbot.receiver,\n \"bot_api\": ciscosparkapi.CiscoSparkAPI,\n \"aux_api\": ciscosparkapi.CiscoSparkAPI,\n \"emulator\": server.WebexAPIEmulator,\n \"receiver_process\": subprocessing.Process,\n \"receiver_webhook_url\": str\n }\n ``aux_api`` is a second Spark API set up for the given emulator.\n \"\"\"\n from logging import getLogger\n\n return_items = {}\n\n return_items[\"bot_api\"] = self.get_spark_api(emulator_server)\n receiver_port = unique_port.__next__()\n return_items[\"receiver_webhook_url\"] = \"http://127.0.0.1:\" + str(receiver_port)\n return_items[\"aux_api\"] = CiscoSparkAPI(base_url=emulator_server.url,\n access_token=\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n return_items[\"bot\"] = SparkBot(return_items[\"bot_api\"],\n root_url = return_items[\"receiver_webhook_url\"],\n logger = getLogger(name=\"Bot\"))\n secret = self.random_bytes(32)\n return_items[\"receiver\"] = receiver.create(return_items[\"bot\"])\n return_items[\"emulator\"] = emulator_server\n return_items[\"bot_api\"].webhooks.create(\"myBot\",\n return_items[\"receiver_webhook_url\"],\n \"messages\",\n \"created\",\n secret=secret.decode())\n\n receiver_server = simple_server.make_server(\"localhost\",\n receiver_port,\n return_items[\"receiver\"])\n\n receiver_process = Process(target=receiver_server.serve_forever)\n return_items[\"receiver_process\"] = receiver_process\n\n yield return_items\n\n receiver_process.terminate()\n receiver_process.join()\n\n def start_receiver(self, receiver_process, url):\n \"\"\" Starts the receiver held by receiver_process and waits for it to come up.\n\n receiver_process should be a multiprocessing.Process, its target should be receiver.run().\n\n url is the receiver URL that this method will expect to be able to reach when the receiver\n is up.\n \"\"\"\n\n # It would be simpler to start the server in the full_bot_setup fixture, but that isn't\n # possible due to the way that Python multiprocessing works. Specifically, trying to add\n # new commands to the bot after starting a receiver will always fail since the process\n # \"holds\" the old version of the bot.\n\n receiver_process.start()\n\n while True:\n try:\n r = requests.get(url)\n print(r.status_code)\n break\n except ConnectionError:\n pass\n\n def invoke_bot(self, spark_api, bot_id, bot_displayname, markdown, room_name=\"Test\", expected_replies=1, timeout=10):\n \"\"\" Creates a new room, adds the bot, and messages the bot using the markdown specified.\n\n :param spark_api: ciscosparkapi.CiscoSparkAPI of another user (not the bot we're testing)\n\n :param bot_id: ID of the bot that we are invoking\n\n :param bot_displayname: Display name of the bot that we are invoking\n\n :param markdown: markdown-formatted message to send to the bot\n\n :param room_name: The name of the room to create. Must be provided unique within each test.\n Failure to provide a unique name will cause unexpected results.\n\n :param expected_replies: The number of replies to wait for from the bot\n\n :param timeout: Maximum number of seconds to wait for the bot to respond.\n\n :returns: Response from bot as a ciscosparkapi.Message if ``expected_replies`` is 1,\n list of responses from bot if it is greater than 1.\n \"\"\"\n\n message = \"<@personId:{}|{}> \".format(bot_id, bot_displayname) + markdown\n room = spark_api.rooms.create(room_name)\n spark_api.memberships.create(roomId=room.id, personId=bot_id)\n spark_api.messages.create(roomId=room.id, markdown=message)\n\n sleep(1)\n\n bot_replies = []\n\n # Timeout*2 because we're sleeping for 0.5 seconds and incrementing i by 1 each time\n for i in range(0, timeout*2):\n\n # Pull each message from the test room. If we match one that's already in bot_replies,\n # go on to the next one. Otherwise, if the reply came from the bot, store it.\n for message in spark_api.messages.list(room.id):\n if message.personId == bot_id and not message.id in [stored_message.id for stored_message in bot_replies]:\n bot_replies.append(message)\n next\n\n if len(bot_replies) == expected_replies or i >= timeout:\n break\n else:\n sleep(0.5)\n\n # Order the replies by their send time\n bot_replies.sort(key=lambda r: r.created)\n\n if expected_replies == 1:\n return bot_replies[0]\n else:\n return bot_replies\n\n def test_server_sanity(self, emulator_server):\n \"\"\"Ensures the API server is sane\"\"\"\n\n spark_api = self.get_spark_api(emulator_server)\n\n me = spark_api.people.me()\n\n assert me.displayName == emulator_server.bot_displayname\n assert me.lastName == emulator_server.bot_lastname\n assert me.firstName == emulator_server.bot_firstname\n assert me.orgId == emulator_server.bot_org\n assert me.nickName == emulator_server.bot_nickname\n assert me.emails == emulator_server.bot_emails\n assert me.id == emulator_server.bot_id\n\n def test_add_command(self, emulator_server):\n \"\"\"Tests use of the @SparkBot.command() decorator to add a command to the bot\"\"\"\n from sparkbot import SparkBot\n\n spark_api = self.get_spark_api(emulator_server)\n\n bot = SparkBot(spark_api)\n\n @bot.command(\"ping\")\n def ping(caller, room_id):\n return 'pong'\n\n assert bot.commands[\"ping\"].execute() == \"pong\"\n\n def test_callback(self, emulator_server):\n \"\"\"Tests the bot's ability to give a callback function\"\"\"\n\n spark_api = self.get_spark_api(emulator_server)\n bot = SparkBot(spark_api)\n room_id = \"ASDF1234\"\n\n temp_respond = mock.MagicMock()\n\n @bot.command(\"callback\")\n def callingback(callback):\n callback(\"Some markdown\")\n\n bot.commands[\"callback\"].execute(room_id=room_id, callback=temp_respond)\n\n assert temp_respond.called_with(room_id, \"Some markdown\")\n\n def test_full_nocommand(self, full_bot_setup):\n \"\"\"Tests the bot's error handling when an incorrect command is given\"\"\"\n\n bot = full_bot_setup[\"bot\"]\n aux_api = full_bot_setup[\"aux_api\"]\n emulator = full_bot_setup[\"emulator\"]\n\n self.start_receiver(full_bot_setup[\"receiver_process\"], full_bot_setup[\"receiver_webhook_url\"])\n\n bot_reply = self.invoke_bot(full_bot_setup[\"aux_api\"],\n emulator.bot_id,\n emulator.bot_displayname,\n \"ping\")\n\n assert \"Command not found\" in bot_reply.text\n\n def test_full_ping(self, full_bot_setup):\n \"\"\"Tests a ping command through the emulator\"\"\"\n\n bot = full_bot_setup[\"bot\"]\n emulator = full_bot_setup[\"emulator\"]\n\n @bot.command(\"ping\")\n def ping():\n return \"pong\"\n\n self.start_receiver(full_bot_setup[\"receiver_process\"], full_bot_setup[\"receiver_webhook_url\"])\n\n bot_reply = self.invoke_bot(full_bot_setup[\"aux_api\"],\n emulator.bot_id,\n emulator.bot_displayname,\n \"ping\")\n\n assert \"pong\" in bot_reply.text\n\n def test_full_bad_formatting(self, full_bot_setup):\n \"\"\"Tests that an incorrectly formatted command returns an error safely\"\"\"\n\n emulator = full_bot_setup[\"emulator\"]\n\n self.start_receiver(full_bot_setup[\"receiver_process\"], full_bot_setup[\"receiver_webhook_url\"])\n\n # Wait for server to come up\n requests.get(full_bot_setup[\"receiver_webhook_url\"])\n\n bot_reply = self.invoke_bot(full_bot_setup[\"aux_api\"],\n emulator.bot_id,\n emulator.bot_displayname,\n \"Command 'without completed quotes\")\n\n assert \"format\" in bot_reply.text\n\n def test_command_strings_list(self, full_bot_setup):\n \"\"\"Tests that a command can be called by multiple names\"\"\"\n\n bot = full_bot_setup[\"bot\"]\n aux_api = full_bot_setup[\"aux_api\"]\n emulator = full_bot_setup[\"emulator\"]\n\n @bot.command([\"ping\", \"ding\"])\n def ping():\n return \"pong\"\n\n self.start_receiver(full_bot_setup[\"receiver_process\"], full_bot_setup[\"receiver_webhook_url\"])\n\n bot_reply_1 = self.invoke_bot(aux_api,\n emulator.bot_id,\n emulator.bot_displayname,\n \"ping\",\n room_name=\"test1\")\n\n bot_reply_2 = self.invoke_bot(aux_api,\n emulator.bot_id,\n emulator.bot_displayname,\n \"ding\",\n room_name=\"test2\")\n\n assert \"pong\" in bot_reply_1.text and \"pong\" in bot_reply_2.text\n\n def test_full_help(self, full_bot_setup):\n \"\"\"Tests the default help-all command (and the default help command's ability to call it)\"\"\"\n\n aux_api = full_bot_setup[\"aux_api\"]\n emulator = full_bot_setup[\"emulator\"]\n\n self.start_receiver(full_bot_setup[\"receiver_process\"], full_bot_setup[\"receiver_webhook_url\"])\n\n bot_reply_1 = self.invoke_bot(aux_api,\n emulator.bot_id,\n emulator.bot_displayname,\n \"help\",\n room_name=\"test1\")\n\n bot_reply_2 = self.invoke_bot(aux_api,\n emulator.bot_id,\n emulator.bot_displayname,\n \"help all\",\n room_name=\"test3\")\n\n assert bot_reply_1.markdown == (\n\"\"\"Type `help [command]` for more specific help about any of these commands:\n - help\"\"\"\n )\n\n assert bot_reply_1.markdown == bot_reply_2.markdown\n\n def test_full_internal_error_text(self, full_bot_setup):\n \"\"\"Tests that unhandled exceptions in commands with error text are handled safely\"\"\"\n\n bot = full_bot_setup[\"bot\"]\n aux_api = full_bot_setup[\"aux_api\"]\n emulator = full_bot_setup[\"emulator\"]\n\n @bot.command(\"exception\")\n def cause_exception():\n raise ValueError(\"Whoops\", \"Hey, an exception\")\n\n self.start_receiver(full_bot_setup[\"receiver_process\"], full_bot_setup[\"receiver_webhook_url\"])\n\n bot_reply = self.invoke_bot(aux_api, emulator.bot_id, emulator.bot_displayname, \"exception\", room_name=\"test1\")\n\n assert bot_reply.text == \"⚠️ Error: Hey, an exception\"\n\n def test_full_internal_error(self, full_bot_setup):\n \"\"\"Tests that unhandled exceptions in commands without error text are handled safely\"\"\"\n\n bot = full_bot_setup[\"bot\"]\n aux_api = full_bot_setup[\"aux_api\"]\n emulator = full_bot_setup[\"emulator\"]\n\n @bot.command(\"exception\")\n def cause_exception():\n raise ValueError(\"Whoops\")\n\n self.start_receiver(full_bot_setup[\"receiver_process\"], full_bot_setup[\"receiver_webhook_url\"])\n\n bot_reply = self.invoke_bot(aux_api, emulator.bot_id, emulator.bot_displayname, \"exception\", room_name=\"test1\")\n\n assert bot_reply.text == \"⚠️ Error: Something happened internally. For more information, contact the bot author.\"\n\n def test_full_yield_results(self, full_bot_setup):\n \"\"\"Tests that ``yield``ing from a function causes multiple replies\"\"\"\n\n bot = full_bot_setup[\"bot\"]\n aux_api = full_bot_setup[\"aux_api\"]\n emulator = full_bot_setup[\"emulator\"]\n\n @bot.command(\"two-replies\")\n def two_replies(callback):\n yield \"Reply 1!\"\n yield \"Reply 2!\"\n\n self.start_receiver(full_bot_setup[\"receiver_process\"], full_bot_setup[\"receiver_webhook_url\"])\n\n bot_replies = self.invoke_bot(aux_api, emulator.bot_id, emulator.bot_displayname, \"two-replies\", expected_replies=2, room_name=\"test1\")\n\n assert bot_replies[0].text == \"Reply 1!\"\n assert bot_replies[1].text == \"Reply 2!\"\n\n def test_full_fallback(self, full_bot_setup):\n \"\"\"Tests fallback commands\"\"\"\n\n bot = full_bot_setup[\"bot\"]\n aux_api = full_bot_setup[\"aux_api\"]\n emulator = full_bot_setup[\"emulator\"]\n\n @bot.command(fallback=True)\n def fallback():\n return \"This is the fallback command\"\n\n self.start_receiver(full_bot_setup[\"receiver_process\"], full_bot_setup[\"receiver_webhook_url\"])\n\n bot_reply = self.invoke_bot(aux_api, emulator.bot_id, emulator.bot_displayname, \"exception\", room_name=\"test1\")\n\n assert bot_reply.text == \"This is the fallback command\"\n\n def test_full_remove_help(self, full_bot_setup):\n \"\"\"Tests that the Help command can be removed from the bot\"\"\"\n\n bot = full_bot_setup[\"bot\"]\n aux_api = full_bot_setup[\"aux_api\"]\n emulator = full_bot_setup[\"emulator\"]\n\n bot.remove_help()\n\n self.start_receiver(full_bot_setup[\"receiver_process\"], full_bot_setup[\"receiver_webhook_url\"])\n\n bot_reply = self.invoke_bot(aux_api, emulator.bot_id, emulator.bot_displayname, \"help\", room_name=\"test1\")\n\n assert bot_reply.text == \"⚠️ Error: Command not found.\"\n\n def test_help_multiple_command_names(self, emulator_server):\n \"\"\"Tests the default help command's ability to group commands\"\"\"\n\n # Since we've already tested help and help_all with the full setup, we\n # only need to call the function on the bot directly.\n\n spark_api = self.get_spark_api(emulator_server)\n bot = SparkBot(spark_api)\n\n @bot.command([\"name1\", \"name2\"])\n def multiple_names():\n pass\n\n @bot.command(\"z\")\n def z_command():\n pass\n\n bot_reply = bot.my_help_all()\n\n assert bot_reply == (\n\"\"\"Type `help [command]` for more specific help about any of these commands:\n - help\n - name1, name2\n - z\"\"\"\n )\n\n def test_fallback_failure_on_multiple(self, emulator_server):\n \"\"\"Tests that trying to set more than one fallback command fails\"\"\"\n\n spark_api = self.get_spark_api(emulator_server)\n bot = SparkBot(spark_api)\n\n @bot.command(fallback=True)\n def fallback():\n return \"This is the fallback command\"\n\n with pytest.raises(CommandSetupError):\n @bot.command(fallback=True)\n def second_fallback():\n return \"This isn't going to work.\"\n\n def test_receiver_incorrect_hmac(self, emulator_server, unique_port):\n \"\"\"Tests that the receiver will reject a message with an incorrect signature\"\"\"\n\n spark_api = self.get_spark_api(emulator_server)\n bot = SparkBot(spark_api)\n receiver_port = unique_port.__next__()\n webhook_url = ''.join([\"http://127.0.0.1:\", str(receiver_port), \"/sparkbot\"])\n\n # Give the receiver an incorrect key\n bot.webhook_secret = b\"1234\"\n my_receiver = receiver.create(bot)\n\n # Now, start the receiver in another process...\n receiver_server = simple_server.make_server(\"localhost\",\n receiver_port,\n my_receiver)\n\n receiver_process = Process(target=receiver_server.serve_forever)\n\n self.start_receiver(receiver_process, webhook_url)\n\n try:\n # Send a good request to the server with a junk signature.\n payload = {\n \"id\": \"Y2lzY29zcGFyazovL3VzL1dFQkhPT0svZjRlNjA1NjAtNjYwMi00ZmIwLWEyNWEtOTQ5ODgxNjA5NDk3\",\n \"name\": \"New message in 'Project Unicorn' room\",\n \"resource\": \"messages\",\n \"event\": \"created\",\n \"filter\": \"roomId=Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0\",\n \"orgId\": \"OTZhYmMyYWEtM2RjYy0xMWU1LWExNTItZmUzNDgxOWNkYzlh\",\n \"createdBy\": \"Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY\",\n \"appId\": \"Y2lzY29zcGFyazovL3VzL0FQUExJQ0FUSU9OL0MyNzljYjMwYzAyOTE4MGJiNGJkYWViYjA2MWI3OTY1Y2RhMzliNjAyOTdjODUwM2YyNjZhYmY2NmM5OTllYzFm\",\n \"ownedBy\": \"creator\",\n \"status\": \"active\",\n \"actorId\": \"Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY\",\n \"data\":{\n \"id\": \"Y2lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk\",\n \"roomId\": \"Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0\",\n \"personId\": \"Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY\",\n \"personEmail\": \"matt@example.com\",\n \"created\": \"2015-10-18T14:26:16.000Z\"\n }\n }\n r = requests.post(webhook_url, json=payload, headers={\"x-spark-signature\":\"asdf1234\"})\n\n finally:\n receiver_process.terminate()\n receiver_process.join()\n\n assert r.status_code == 403\n\n def test_receiver_junk_data(self, emulator_server, unique_port):\n \"\"\"Tests that the receiver will reject an incorrectly crafted message\"\"\"\n\n spark_api = self.get_spark_api(emulator_server)\n bot = SparkBot(spark_api)\n receiver_port = unique_port.__next__()\n webhook_url = ''.join([\"http://127.0.0.1:\", str(receiver_port) + \"/sparkbot\"])\n\n # Give the receiver an incorrect key\n bot.webhook_secret = b\"1234\"\n my_receiver = receiver.create(bot)\n\n # Now, start the receiver in another process...\n receiver_server = simple_server.make_server(\"localhost\",\n receiver_port,\n my_receiver)\n\n receiver_process = Process(target=receiver_server.serve_forever)\n\n self.start_receiver(receiver_process, webhook_url)\n\n try:\n # Send nothing.\n r = requests.post(webhook_url)\n finally:\n receiver_process.terminate()\n receiver_process.join()\n\n assert r.status_code == 400\n\n def test_incorrect_init(self, emulator_server):\n \"\"\"Tests that the bot will fail to run when given incorrect arguments\"\"\"\n\n spark_api = self.get_spark_api(emulator_server)\n\n with pytest.raises(TypeError):\n SparkBot(\"This is not a CiscoSparkAPI\")\n\n with pytest.raises(TypeError):\n SparkBot(spark_api, logger=\"This is not a logger\")\n\n def test_bad_command_strings(self, emulator_server):\n \"\"\"Tests that the bot will fail to add a command with the incorrect argument\"\"\"\n\n spark_api = self.get_spark_api(emulator_server)\n bot = SparkBot(spark_api)\n\n with pytest.raises(CommandSetupError):\n @bot.command(\"\")\n def ping():\n return \"pong\"\n\n def test_bad_decorator_call(self, emulator_server):\n \"\"\"Tests that the bot will fail to add a command when command() is called with no arguments\"\"\"\n\n spark_api = self.get_spark_api(emulator_server)\n bot = SparkBot(spark_api)\n\n with pytest.raises(CommandSetupError):\n @bot.command\n def ping():\n return \"pong\"\n\n def test_bad_decorator_type(self, emulator_server):\n \"\"\"Tests that the bot will fail to add a command with the incorrect argument type\"\"\"\n\n spark_api = self.get_spark_api(emulator_server)\n bot = SparkBot(spark_api)\n\n with pytest.raises(TypeError):\n @bot.command(bot)\n def ping(bot):\n return \"pong\"\n\n def test_bad_decorator_embedded_type(self, emulator_server):\n \"\"\"Tests that the bot will fail to add a command with the incorrect argument type\"\"\"\n\n spark_api = self.get_spark_api(emulator_server)\n bot = SparkBot(spark_api)\n\n with pytest.raises(TypeError):\n @bot.command([bot, \"stuff\"])\n def ping():\n return \"pong\"\n","repo_name":"UniversalSuperBox/SparkBot","sub_path":"tests/test_all.py","file_name":"test_all.py","file_ext":"py","file_size_in_byte":26319,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"27"} +{"seq_id":"5936940821","text":"# This program demonstrates the mean RMSE and worst-case ROI RMSE metrics\r\n# The phantom images are taken as the ground truth\r\n\r\nimport numpy as np, sys, os\r\nimport pdb\r\n\r\nINPUT = sys.argv[1] # INPUT which has both ./ref and ./res - user submission\r\nOUT = sys.argv[2] # OUTPUT\r\n\r\nREFERENCE = os.path.join(INPUT, \"ref\") # Phantom GT\r\nPREDICTION_OUTPUT = os.path.join(INPUT, \"res\") # user submission wll be available from here\r\n\r\n# Ground Truth\r\n# filtered back-projection reconstruction from the 128-view sinogram\r\n# users will try to recreate these. They serve as the input data.\r\nif len(os.listdir(REFERENCE)) == 1 and os.listdir(REFERENCE)[0][-4:] == \".npy\":\r\n phantom_gt_file_name = os.listdir(REFERENCE)[0]\r\nelse:\r\n raise Exception('Organizer, either you have more than one file in your ref directory or it doesn\\'t end in .npy')\r\n\r\n# User Images\r\n# The goal is to train a network that accepts the FBP128 image (and/or the 128-view sinogram)\r\n# to yield an image that is as close as possible to the corresponding Phantom image.\r\nif len(os.listdir(PREDICTION_OUTPUT)) == 1 and os.listdir(PREDICTION_OUTPUT)[0][-4:] == \".npy\":\r\n prediction_file_name = os.listdir(PREDICTION_OUTPUT)[0]\r\nelse:\r\n raise Exception('You either have more than one file in your submission or it doesn\\'t end in .npy')\r\n\r\nphantom_gt = np.load(os.path.join(REFERENCE, phantom_gt_file_name))\r\nprediction_phantoms = np.load(os.path.join(PREDICTION_OUTPUT,prediction_file_name))\r\n\r\n# get the number of prediction_phantoms and number of pixels in x and y\r\nnim, nx, ny = prediction_phantoms.shape\r\n\r\n# mean RMSE computation\r\ndiffsquared = (phantom_gt-prediction_phantoms)**2\r\nnum_pix = float(nx*ny)\r\n\r\nmeanrmse = np.sqrt( ((diffsquared/num_pix).sum(axis=2)).sum(axis=1) ).mean()\r\nprint(\"The mean RSME over %3i images is %8.6f \"%(nim,meanrmse))\r\n\r\n# worst-case ROI RMSE computation\r\nroisize = 25 #width and height of test ROI in pixels\r\nx0 = 0 #tracks x-coordinate for the worst-case ROI\r\ny0 = 0 #tracks x-coordinate for the worst-case ROI\r\nim0 = 0 #tracks image index for the worst-case ROI\r\n\r\nmaxerr = -1.\r\nfor i in range(nim): # For each image\r\n print(\"Searching image %3i\"%(i))\r\n phantom = phantom_gt[i].copy() # GT\r\n prediction = prediction_phantoms[i].copy() # Pred\r\n # These for loops cross every pixel in image (from region of interest)\r\n for ix in range(nx-roisize):\r\n for iy in range(ny-roisize):\r\n roiGT = phantom[ix:ix+roisize,iy:iy+roisize].copy() # GT\r\n roiPred = prediction[ix:ix+roisize,iy:iy+roisize].copy() # Pred\r\n if roiGT.max()>0.01: #Don't search ROIs in regions where the truth image is zero\r\n roirmse = np.sqrt( (((roiGT-roiPred)**2)/float(roisize**2)).sum() )\r\n if roirmse>maxerr:\r\n maxerr = roirmse\r\n x0 = ix\r\n y0 = iy\r\n im0 = i\r\nprint(\"Worst-case ROI RMSE is %8.6f\"%(maxerr))\r\nprint(\"Worst-case ROI location is (%3i,%3i) in image number %3i \"%(x0,y0,im0+1))\r\n\r\nwith open(os.path.join(OUT,\"scores.txt\"), \"w\") as results:\r\n results.write(\"score_1: {}\\n\".format(meanrmse))\r\n results.write(\"score_2: {}\".format(maxerr))","repo_name":"vintagewtj/sparse_view_CT","sub_path":"sparse_view_CT/src/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"5563609259","text":"from typing import Any, Awaitable, Union\n\nfrom strawberry.permission import BasePermission\nfrom strawberry.types import Info\n\nfrom auth import validate_token\n\n\nclass AdminPermission(BasePermission):\n message = \"User doesn't have enough rights to perform this action\"\n\n def has_permission(\n self, source: Any, info: Info, **kwargs\n ) -> Union[bool, Awaitable[bool]]:\n authorization = info.context[\"request\"].headers.get(\n \"authorization\", None\n )\n if not authorization:\n return False\n is_admin = False\n if authorization:\n payload = validate_token(authorization.split()[1])\n is_admin = payload.get(\"admin\", False)\n if \"error\" in payload.keys():\n self.message = payload[\"error\"]\n return is_admin\n","repo_name":"arche-ma/fastapi_naive","sub_path":"permissions/admin_permission.py","file_name":"admin_permission.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"36387805564","text":"import os\n\nfilename = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"input.txt\")\n\n\nwith open(filename) as f:\n content = f.readlines()\ncontent = [list(x.strip()) for x in content]\ncontent = [[int(x) for x in row] for row in content]\n\nstep = 0\nways = [(0, 0), (0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, -1), (-1, 1), (1, -1)]\n\n\ndef find_nbrs(content, i, j):\n for way in ways:\n x = i + way[0]\n y = j + way[1]\n max = len(content)\n if x < max and y < max and x >= 0 and y >= 0:\n nbr = content[x][y]\n if nbr > 9:\n content[x][y] = 0\n find_nbrs(content, x, y)\n elif nbr == 0:\n continue\n else:\n content[x][y] += 1\n\n\nfor i, row in enumerate(content):\n for j, cell in enumerate(row):\n # find_nbrs(content, i, j)\n # if cell == 9:\n # continue\n # # content[i][j] = 0\n # # find_nbrs(content, i, j)\n # else:\n content[i][j] += 1\n\nstep += 1\n\nwhile (9 in sum(content, [])) or (10 in sum(content, [])):\n for i, row in enumerate(content):\n for j, cell in enumerate(row):\n if cell > 9:\n find_nbrs(content, i, j)\n\n# for i, row in enumerate(content):\n# for j, cell in enumerate(row):\n# if cell == 0:\n# find_nbrs(content, i, j)\n\nprint(content)\n","repo_name":"marekvi95/adventofcode20","sub_path":"2021/day11/puzzle1.py","file_name":"puzzle1.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"767317839","text":"import os\nimport sys\nimport unittest\nsys.path.insert(0, os.path.abspath('..'))\nimport pullstring\n\n# API Key and Project ID for the example PullString Web API content\nAPI_KEY = \"9fd2a189-3d57-4c02-8a55-5f0159bff2cf\"\nPROJECT = \"e50b56df-95b7-4fa1-9061-83a7a9bea372\"\n\nclass TestClass(unittest.TestCase):\n \"\"\"\n Play through the Rock Paper Scissors example content.\n \"\"\"\n\n def does_contain(self, response, text):\n if response is None:\n return False\n all_lines = [x.text.lower() for x in response.outputs if x.type == pullstring.OUTPUT_DIALOG]\n return text.lower() in \" \".join(all_lines)\n\n def assert_contains(self, response, text):\n self.assertNotEqual(response, None)\n all_lines = [x.text.lower() for x in response.outputs if x.type == pullstring.OUTPUT_DIALOG]\n self.assertIn(text.lower(), \" \".join(all_lines))\n\n def test_rock_paper_scissors(self):\n \"\"\"\n Start the default activity and parse out a name from the user\n \"\"\"\n\n # start a new conversation\n conv = pullstring.Conversation()\n response = conv.start(PROJECT, pullstring.Request(api_key=API_KEY))\n self.assert_contains(response, \"Do you want to play\")\n \n # say that we don't want to play to start with\n response = conv.send_text(\"no\")\n self.assert_contains(response, \"was that a yes\")\n\n # now concede and accept to play\n response = conv.send_text(\"yes\")\n self.assert_contains(response, \"great!\")\n self.assert_contains(response, \"rock, paper or scissors?\")\n\n # ask how to play the game to get some information\n response = conv.send_text(\"how do I play this game?\")\n self.assert_contains(response, \"a game of chance\")\n\n # query the current value of the Player Score counter (it's 4 at the start)\n response = conv.get_entities([pullstring.Counter(\"Player Score\")])\n self.assertEqual(len(response.entities), 1)\n self.assertEqual(response.entities[0].name, 'Player Score')\n self.assertEqual(response.entities[0].value, 4)\n\n # let's start playing... keep choosing until we win or lose\n finished = False\n choices = ['paper', 'rock', 'scissors', 'paper']\n for choice in choices:\n response = conv.send_text(choice)\n if self.does_contain(response, \"lost\") or \\\n self.does_contain(response, \"won\") or \\\n self.does_contain(response, \"good game\"):\n finished = True\n break\n if not finished:\n self.fail(\"Game did not finish after %d iterations\" % len(choices))\n\n # set the Name label and confirm that we can get back the new value\n conv.set_entities([pullstring.Label(\"NAME\", \"Jack\")])\n response = conv.get_entities([pullstring.Label(\"NAME\")])\n self.assertEqual(len(response.entities), 1)\n self.assertEqual(response.entities[0].value, \"Jack\")\n\n # trigger a custom event to restart the experience\n response = conv.send_event('restart_game')\n self.assert_contains(response, \"Do you want to play\")\n\n # start a new conversation but carry over the participant from above\n participant_id = conv.get_participant_id()\n response = conv.start(PROJECT, pullstring.Request(api_key=API_KEY, participant_id=participant_id))\n self.assert_contains(response, \"Do you want to play\")\n\n # because we preserved the participant state, the Name should be the same as above\n response = conv.get_entities([pullstring.Label(\"NAME\")])\n self.assertEqual(len(response.entities), 1)\n self.assertEqual(response.entities[0].value, \"Jack\")\n\n # say that we're done\n response = conv.send_text(\"quit\")\n self.assert_contains(response, \"Bye\")\n\n\nif __name__ == '__main__':\n print(\"Running test...\")\n unittest.main()\n","repo_name":"chenjic215/nickvoice","sub_path":"pullstring-python/tests/test_webapi.py","file_name":"test_webapi.py","file_ext":"py","file_size_in_byte":3913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"40556657097","text":"'''固定和的元素对\nDescription\n输入一个数组和一个数字,在数组中查找两个数,使得它们的和正好是输入的那个数字,统计这样两个数的对数。\nInput\n输入第一行是数组,每一个数用空格隔开;第二行是数字和。\nOutput\n输出这样两个数有几对。\nSample Input 1\n1 2 4 7 11 0 9 15\n11\nSample Output 1\n3\n'''\nc = input().split()\nL = [int(i) for i in c]\nsum = int(input())\ncount = 0\n\nfor i in range(len(L)):\n a = sum - L[i]\n if a == L[i] and L.count(a) >= 2:\n count += 1\n if a in L:\n count +=1\nprint(int(count/2))\n\n","repo_name":"cp4011/Algorithms","sub_path":"Course/Homework_1/6_固定和的元素对.py","file_name":"6_固定和的元素对.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"46453737044","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread(\"../resources/img/img.png\")\nkernel = np.ones((5, 5), np.uint8)\n\nimgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nimgBlur = cv2.GaussianBlur(imgGray, (15, 15), 0)\nimgCanny = cv2.Canny(img, 100, 100)\nimgDilation = cv2.dilate(imgCanny, kernel, iterations=1)\nimgEroded = cv2.erode(imgDilation, kernel, iterations=1)\n\ncv2.imshow(\"Output - gray\", imgGray)\ncv2.imshow(\"Output - grayBlur\", imgBlur)\ncv2.imshow(\"Output - canny\", imgCanny)\ncv2.imshow(\"Output - cannyDilation\", imgDilation)\ncv2.imshow(\"Output - cannyEroded\", imgEroded)\ncv2.waitKey(0)","repo_name":"yeonfish6040/openCV2","sub_path":"chapter_002/practice_01-img_converting.py","file_name":"practice_01-img_converting.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"42768655037","text":"#Exercício 3\r\n# Uma loja utiliza o código V para transação à vistae P para transaçãoa prazo.\r\n# Faça um programa que receba código e valor de 15transações.\r\n# Calcule e mostre:\r\n# * O valor total das compras à vista\r\n# * O valor total das compras a prazo.\r\n# * O valor total das compras efetuadas\r\n# Extra\r\n# * O valor da primeira prestação das compras a prazo,\r\n# sabendo-se que essas serão pagas em três vezes\r\n\r\nvista = []\r\nprazo = []\r\nfor i in range(0,15):\r\n print(\"Compra numero:\",i+1)\r\n valor = float(input(\"Qual o valor da transação?\"))\r\n codigo = str(input(\"Irá pagar as vista ou a prazo?(V/P\"))\r\n if codigo == 'v' or codigo == 'V':\r\n vista.append(valor)\r\n elif codigo == 'p' or codigo == 'P':\r\n prazo.append(valor)\r\ndef AVista():\r\n total = 0\r\n for i in vista:\r\n total += i\r\n return total\r\ndef APrazo():\r\n total = 0\r\n for i in prazo:\r\n total += i\r\n return total\r\ndef Total():\r\n total = 0\r\n for i in prazo+vista:\r\n total += i\r\n return total\r\nprint(\"Total das transações a vista:\",AVista())\r\nprint(\"Total das transações a prazo:\",APrazo())\r\nprint(\"Total das transações totais:\",Total())\r\nprint(\"Primeira prestação das compras a prazo é de:\",APrazo()/3)\r\n","repo_name":"BrunoMartinsGameDev/JovemProgramador","sub_path":"Exercicios 6/Ex03.py","file_name":"Ex03.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"23111286172","text":"import numpy as np\nimport pandas as pd\n\n\ndef set_axis_alias(cls, axis, alias):\n if axis not in cls._AXIS_NUMBERS:\n raise Exception(\"invalid axis [%s] for alias [%s]\" % (axis, alias))\n cls._AXIS_ALIASES[alias] = axis\n\n\ndef clear_axis_alias(cls, axis, alias):\n if axis not in cls._AXIS_NUMBERS:\n raise Exception(\"invalid axis [%s] for alias [%s]\" % (axis, alias))\n cls._AXIS_ALIASES.pop(alias, None)\n\n\nset_axis_alias(pd.DataFrame, 'columns', 'myaxis2')\ndf2 = pd.DataFrame(np.random.randn(3, 2), columns=['c1', 'c2'], index=['i1', 'i2', 'i3'])\nprint(df2.sum(axis='myaxis2'))\nclear_axis_alias(pd.DataFrame, 'columns', 'myaxis2')\n","repo_name":"sunjiaxin111/pandas_learn","sub_path":"Pandas指南(Cookbook)/轴别名(Aliasing Axis Names).py","file_name":"轴别名(Aliasing Axis Names).py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"36104298297","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Overview\n# ---\n#\n# ## Using a Jupyter Notebook\n#\n# For this portion of the Mythical Mysfits tutorial, you will be interacting directly with this Jupyter notebook in order to build a machine learning model using sample data that we have provided. A notebook gives you the ability to create rich documentation alongside code and its output, helping describe and execute the steps taken towards your machine learning objectives in a single place.\n#\n# Each independently executable portion of a notebook is represented as a distinct **cell**. A cell be one of three types:\n# * Markdown (rich text)\n# * Code (Python in this notebook)\n# * Raw (contents used directly out the cell output of itself, note used in this notebook)\n#\n# If you click around this notebook document on various portions of it, you will see a border highlight a portion of the document, which represents a cell.\n#\n# Selecting a cell and clicking the **Run** button in the tool bar will execute that cell, as will pressing Ctrl+Enter on your keyboard. For a Markdown cell, this will format the text written and display it according to Markdown syntax. For a Code cell, the Python code will be executed on the underlying kernel and the output of the code will be displayed underneath the cell.\n#\n# For Code cells, you may notice `In [ ]:` to the right of each cell. This is used to indicate the execution status and sequence of each code block within the notebook. The empty brackets (`[ ]`) indicate a code block has note yet been executed. When a code block is in the middle of being executed, but has yet to complete, you will see `[*]` be displayed. And finally, once a code block has finished executing, you will see a specific number displayed like `[1]`. This number represents the sequence in which that code block was executed in relation to those before it inside the notebook. This is to help you keep track of the current state of code execution within the entirety of the notebook document (as you may execute one cell and then read some documentation and not quite remember which cell you last executed!).\n#\n# Should you need to revert processing for any reason, you can use the **Kernel** menu above in the notebook tool bar to reset the kernel, clear output, etc.\n#\n# ## The Mysfits Recommendations Notebook\n#\n# The code required to use the sample data and build a machine learning model has already been written and is contained within the following cells below in this notebook. It is your task to read over the documentation to gain an understanding of the steps taken, and get familiar with interacting with this notebook in order to curate data, build and train and machine learning model, and deploy that model for use by our application.\n\n# # Part 1: Downloading the Sample Data\n# ---\n# The below code cell downloads the sample data that has been staged in S3.\n#\n# The data set contains the responses to a questionnaire by nearly one million imaginary users of the Mythical Mysfits website and which Mysfit is their favorite. For use cases like this where the algorithm being used expects numerical inputs, we have mapped each possible questionnaire response and the chosen mysfit to a numerical value. The result of the five question questionnaire and a favorite mysfit is a CSV file where each line contains 6 comma separate values (Example: `1,0,2,7,0,11`). Please visit the [Mythical Mysfits website](http://www.mythicalmysfits.com) to try the questionnaire for yourself.\n#\n# Click the code cell below so that it is bordered, then click **Run** above in the tool bar, or press Ctrl+Enter on your keyboard to download the sample data set and store it in the listed directory.\n\n# In[ ]:\n\n\n# COMMENTED OUT get_ipython().run_cell_magic('bash', '', \"\\nwget 'https://s3.amazonaws.com/mysfit-recommendation-training-data/mysfit-preferences.csv.gz'\\nmkdir -p /tmp/mysfit/raw\\nmv mysfit-preferences.csv.gz /tmp/mysfit/raw/mysfit-preferences.csv.gz\")\n\n# NEW start ####################################################################################\n# This code segment creates an execution role to access SageMaker when not running on a SageMaker notebook.\n# (On a Sagemaker notebook the role is created automatically)\nimport boto3\nfrom botocore.exceptions import ClientError\nimport json\n\nrole = 'MysfitsSageMakerRole'\nassume_role_policy_document = json.dumps({\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Service\": [\n \"sagemaker.amazonaws.com\",\n ]\n },\n \"Action\": \"sts:AssumeRole\"\n }\n ]\n})\n\nclient = boto3.client('iam')\ntry:\n get_role_response = client.get_role(\n RoleName=role\n )\nexcept ClientError as e:\n if e.response['Error']['Code'] == 'NoSuchEntity':\n create_role_response = client.create_role(\n RoleName=role,\n AssumeRolePolicyDocument=assume_role_policy_document,\n )\n attach_role_policy_response = client.attach_role_policy(\n RoleName=role,\n PolicyArn='arn:aws:iam::aws:policy/AmazonSageMakerFullAccess'\n )\n else:\n raise e\n# NEW end #####################################################################################\n\n# # Part 2: Data Preparation\n# ---\n# \n# ## Pre-Processing the Data\n# Now that we have the raw data, let's process it. \n# We'll first load the data into numpy arrays, and randomly split it into train and test with a 90/10 split.\n\n# In[ ]:\n\n\nimport numpy as np\nimport os\n\ndata_dir = \"tmp/mysfit/\" # changed from /tmp/mysfit/\nprocessed_subdir = \"standardized\"\nraw_data_file = os.path.join(data_dir, \"raw\", \"mysfit-preferences.csv.gz\")\ntrain_features_file = os.path.join(data_dir, processed_subdir, \"train/csv/features.csv\")\ntrain_labels_file = os.path.join(data_dir, processed_subdir, \"train/csv/labels.csv\")\ntest_features_file = os.path.join(data_dir, processed_subdir, \"test/csv/features.csv\")\ntest_labels_file = os.path.join(data_dir, processed_subdir, \"test/csv/labels.csv\")\n\n# read raw data\nprint(\"Reading raw data from {}\".format(raw_data_file))\nraw = np.loadtxt(raw_data_file, delimiter=',')\n\n# split into train/test with a 90/10 split\nnp.random.seed(0)\nnp.random.shuffle(raw)\ntrain_size = int(0.9 * raw.shape[0])\ntrain_features = raw[:train_size, :-1]\ntrain_labels = raw[:train_size, -1]\ntest_features = raw[train_size:, :-1]\ntest_labels = raw[train_size:, -1]\n\n\n# ## Upload to Amazon S3\n# Now, since typically the dataset will be large and located in Amazon S3, let's write the data to Amazon S3 in recordio-protobuf format. We first create an io buffer wrapping the data, next we upload it to Amazon S3. Notice that the choice of bucket and prefix should change for different users and different datasets\n\n# In[ ]:\n\n\nimport io\nimport sagemaker.amazon.common as smac\n\nprint('train_features shape = ', train_features.shape)\nprint('train_labels shape = ', train_labels.shape)\n\nbuf = io.BytesIO()\nsmac.write_numpy_to_dense_tensor(buf, train_features, train_labels)\nbuf.seek(0)\n\n\n# In[ ]:\n\n\nimport boto3\nimport os\nimport sagemaker\n\nbucket = sagemaker.Session().default_bucket() # modify to your bucket name\nprefix = 'mysfit-recommendation-dataset'\nkey = 'recordio-pb-data'\n\nboto3.resource('s3').Bucket(bucket).Object(os.path.join(prefix, 'train', key)).upload_fileobj(buf)\ns3_train_data = 's3://{}/{}/train/{}'.format(bucket, prefix, key)\nprint('uploaded training data location: {}'.format(s3_train_data))\n\n\n# It is also possible to provide test data. This way we can get an evaluation of the performance of the model from the training logs. In order to use this capability let's upload the test data to Amazon S3 as well\n\n# In[ ]:\n\n\nprint('test_features shape = ', test_features.shape)\nprint('test_labels shape = ', test_labels.shape)\n\nbuf = io.BytesIO()\nsmac.write_numpy_to_dense_tensor(buf, test_features, test_labels)\nbuf.seek(0)\n\nboto3.resource('s3').Bucket(bucket).Object(os.path.join(prefix, 'test', key)).upload_fileobj(buf)\ns3_test_data = 's3://{}/{}/test/{}'.format(bucket, prefix, key)\nprint('uploaded test data location: {}'.format(s3_test_data))\n\n\n# # Part 3: Training\n# ---\n# \n# We take a moment to explain at a high level, how Machine Learning training and prediction works in Amazon SageMaker. First, we need to train a model. This is a process that given a labeled dataset and hyper-parameters guiding the training process, outputs a model. Once the training is done, we set up what is called an **endpoint**. An endpoint is a web service that given a request containing an unlabeled data point, or mini-batch of data points, returns a prediction(s).\n# \n# In Amazon SageMaker the training is done via an object called an **estimator**. When setting up the estimator we specify the location (in Amazon S3) of the training data, the path (again in Amazon S3) to the output directory where the model will be serialized, generic hyper-parameters such as the machine type to use during the training process, and kNN-specific hyper-parameters such as the index type, etc. Once the estimator is initialized, we can call its **fit** method in order to do the actual training.\n# \n# Now that we are ready for training, we start with a convenience function that starts a training job.\n\n# In[ ]:\n\n\n# COMMENTED OUT import matplotlib.pyplot as plt\n\nimport sagemaker\n# COMMENTED OUT from sagemaker import get_execution_role, which only works on SageMaker notebooks\nfrom sagemaker.predictor import csv_serializer, json_deserializer\nfrom sagemaker.amazon.amazon_estimator import get_image_uri\n\n\ndef trained_estimator_from_hyperparams(s3_train_data, hyperparams, output_path, s3_test_data=None):\n \"\"\"\n Create an Estimator from the given hyperparams, fit to training data, \n and return a deployed predictor\n \n \"\"\"\n # set up the estimator\n knn = sagemaker.estimator.Estimator(get_image_uri(boto3.Session().region_name, \"knn\"),\n role, # COMMENTED OUT get_execution_role() and replaced with the created role\n train_instance_count=1,\n train_instance_type='ml.m5.2xlarge',\n output_path=output_path,\n sagemaker_session=sagemaker.Session())\n knn.set_hyperparameters(**hyperparams)\n \n # train a model. fit_input contains the locations of the train and test data\n fit_input = {'train': s3_train_data}\n if s3_test_data is not None:\n fit_input['test'] = s3_test_data\n knn.fit(fit_input)\n return knn\n\n\n# Now, we run the actual training job. For now, we stick to default parameters.\n\n# In[ ]:\n\n\nhyperparams = {\n 'feature_dim': 5,\n 'k': 10,\n 'sample_size': 100000,\n 'predictor_type': 'classifier' \n}\noutput_path = 's3://' + bucket + '/' + prefix + '/default_example/output'\nknn_estimator = trained_estimator_from_hyperparams(s3_train_data, hyperparams, output_path, \n s3_test_data=s3_test_data)\n\n\n# Notice that we mentioned a test set in the training job. When a test set is provided the training job doesn't just produce a model but also applies it to the test set and reports the accuracy. In the logs you can view the accuracy of the model on the test set.\n\n# # Part 4: Deploying the Model to a SageMaker Endpoint\n# ---\n# \n# ## Setting up the endpoint\n# \n# Now that we have a trained model, we are ready to run inference. The **knn_estimator** object above contains all the information we need for hosting the model. Below we provide a convenience function that given an estimator, sets up and endpoint that hosts the model. Other than the estimator object, we provide it with a name (string) for the estimator, and an **instance_type**. The **instance_type** is the machine type that will host the model. It is not restricted in any way by the parameter settings of the training job.\n\n# In[ ]:\n\n\ndef predictor_from_estimator(knn_estimator, estimator_name, instance_type, endpoint_name=None): \n knn_predictor = knn_estimator.deploy(initial_instance_count=1, instance_type=instance_type,\n endpoint_name=endpoint_name)\n # COMMENTED OUT Let's use the defaults\n # knn_predictor.content_type = 'text/csv'\n # knn_predictor.serializer = csv_serializer\n # knn_predictor.deserializer = json_deserializer\n return knn_predictor\n\n\n\n\nimport time\n\ninstance_type = 'ml.m4.xlarge'\nmodel_name = 'mysfits-knn_%s'% instance_type\nendpoint_name = 'mysfits-knn-ml-m4-xlarge-%s'% (str(time.time()).replace('.','-'))\nprint('setting up the endpoint..')\npredictor = predictor_from_estimator(knn_estimator, model_name, instance_type, endpoint_name=endpoint_name)\n\n# COMMENTED OUT The following part is ignored since it is more relevant for interactive use, and\n# the SageMaker artifacts (endpoints etc.) can be removed using clean_utils.py\n#\n# # ## Inference\n# #\n# # Now that we have our predictor, let's use it on our test dataset. The following code runs on the test dataset, computes the accuracy and the average latency. It splits up the data into 100 batches. Then, each batch is given to the inference service to obtain predictions. Once we have all predictions, we compute their accuracy given the true labels of the test set.\n#\n# # In[ ]:\n#\n#\n#\n# batches = np.array_split(test_features, 100)\n# print('data split into 100 batches, of size %d.' % batches[0].shape[0])\n# # obtain an np array with the predictions for the entire test set\n# start_time = time.time()\n# predictions = []\n# for batch in batches:\n# result = predictor.predict(batch)\n# cur_predictions = np.array([result['predictions'][i]['predicted_label'] for i in range(len(result['predictions']))])\n# predictions.append(cur_predictions)\n# predictions = np.concatenate(predictions)\n# run_time = time.time() - start_time\n#\n# test_size = test_labels.shape[0]\n# num_correct = sum(predictions == test_labels)\n# accuracy = num_correct / float(test_size)\n# print('time required for predicting %d data point: %.2f seconds' % (test_size, run_time))\n# print('accuracy of model: %.1f%%' % (accuracy * 100) )\n#\n#\n# # **Note**: Remember that this sample data set was generated randomly. Therefore, you'll notice the very low accuracy that this model is able to achieve (because there is very little pattern at all within the data being used to create the model).\n# #\n# # For your own future use cases using machine learning and SageMaker, it will be up to you to determine the level of accuracy required in order for the model to be beneficial for your application. Not all use cases require 90+% accuracy in order for benefits to be gained. Though for some use cases, especially where customer safety or security is part of your application, you may determine that a model must have extreme levels of accuracy in order for it to be leveraged in Production.\n#\n# # # STOP!\n# #\n# # ## Mythical Mysfits Workshop Next Steps\n# # You have just deployed a prediction endpoint to SageMaker. It can be invoked via HTTP directly. However, rather than directly have our application frontend integrate with the native SageMaker endpoint, we're going to wrap our own RESTful and serverless API around that prediction endpoint. Please return to the workshop instructions and proceed to the next step to continue the tutorial.\n# #\n# # ***\n#\n# # ---\n# # # Clean-Up When Complete with Module 7\n# #\n# # ## Deleting the endpoint\n# #\n# # We're now done with the example except a final clean-up act. By setting up the endpoint we started a machine in the cloud and as long as it's not deleted the machine is still up and we are paying for it. Once the endpoint is no longer necessary, we delete it. The following code does exactly that.\n#\n# # In[ ]:\n#\n#\n# def delete_endpoint(predictor):\n# try:\n# boto3.client('sagemaker').delete_endpoint(EndpointName=predictor.endpoint)\n# print('Deleted {}'.format(predictor.endpoint))\n# except:\n# print('Already deleted: {}'.format(predictor.endpoint))\n#\n# delete_endpoint(predictor)\n \n\n","repo_name":"roebius/cdk-python-maw","sub_path":"webgen/sagemaker/mysfit_recommendations_knn.py","file_name":"mysfit_recommendations_knn.py","file_ext":"py","file_size_in_byte":16176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70851707911","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nyolo = cv2.dnn.readNet(\"./yolov3_training_last_1000.weights\", \"./yolov3_testing.cfg\")\nclasses = [\"garbage\"]\nimg = glob.glob(\"C:/archit_3/yolo-trash/yolo_custom_detection/images/00a40ac0-1a14-4b3a-a1ce-d8c89d37d1cd_6afde6c9-bbbb-47c6-acf5-8b0392c59fba.jpg\")\n# img = cv2.dnn.readNetFromTensorflow(\"./files_for_pb/retrained_graph.pb\", \"./files_for_pb/retrained_labels.pbtxt\")\nblob = cv2.dnn.blobFromImage(img,1/255,(320,320),(0,0,0),swapRB=True,crop=False)\n\ni= blob[0].reshape(320,320,3)\nyolo.setInput(blob)\noutput_layers_name = yolo.getUnconnectedOutLayersNames()\nlayeroutput = yolo.forward(output_layers_name)\n\n\nboxs = []\nconfidences = []\nclass_ids = []\nfor output in layeroutput:\n for detection in output:\n score = detection[5:]\n class_id = np.argmax(score)\n confidence = score[class_id]\n if confidence > 0.7:\n center_x = int(detection[0]*width)\n center_x = int(detection[0]*height)\n w = int(detection[0]*width)\n h = int(detection[0]*height)\n\n x = int(center_x - w/2)\n x = int(center_y - h/2)\n\n boxes.append([x,y,w,h])\n confidences.append(float(confidence))\n class_ids.append(class_id)\n\nindexes = cv2.dnn.NMSBoxes(boxs,confidences,0.5,0.4)\nfont = cv2.FONT_HERSHEY_PLAIN\ncolors = np.random.uniform(0,255,size=(len(boxs),3))\n\nif len(indexes) > 0:\n for i in indexes.flatten():\n x,y,w,h = boxs[i]\n\n label = str(classes[class_ids[i]])\n confi = str(round(confidences[i],2))\n color = colors[i]\n\n cv2.rectangle(img,(x,y),(x+w,y+h),color,1)\n cv2.putText(img,label+\" \"+confi,(x,y+20),font,2,(255,255,255),5)\ncv2.imwrite(\"./image111.jpg\",img)","repo_name":"architjain2002/garbage-detector","sub_path":"attempt2.py","file_name":"attempt2.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"6601874035","text":"from selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import NoSuchElementException\nimport pandas as pd\nimport undetected_chromedriver as uc\n\noptions = uc.ChromeOptions()\noptions.binary_location = \"C:\\\\Users\\\\Lazaro B\\\\AppData\\\\Local\\\\Chromium\\\\Application\\\\chrome.exe\"\ndriver = uc.Chrome(options=options)\n\nurl = 'https://bo3.gg/matches/into-the-breach-vs-espionage-16-08-2023'\ndriver.get(url)\n\nWebDriverWait(driver, 30).until(EC.presence_of_element_located((By.CLASS_NAME, \"u-relative.c-widget-match-scoreboard-wrap\")))\n\nparent_div = driver.find_element(By.CLASS_NAME, \"u-relative.c-widget-match-scoreboard-wrap\")\ngroup_divs = parent_div.find_elements(By.CLASS_NAME, \"c-widget-match-scoreboard\")\nprint(\"Number of table-groups found: \", len(group_divs))\n\nplayer_data = []\n\nfor group_div in group_divs:\n print(\"Processing table-group\")\n rows = group_div.find_elements(By.CLASS_NAME, \"table-row\")\n print(f'Number of rows found: {len(rows)}')\n\n span_elements = group_div.find_elements(By.CLASS_NAME, \"nickname\")\n nicknames = [span.text for span in span_elements]\n print(f'Nicknames found: {nicknames}')\n\n nickname_index = 0\n\n for i, row in enumerate(rows):\n if 'total' in row.get_attribute('class'):\n print(f\"Skipping 'Total' row at index {i}.\")\n continue\n\n # Skip the first row of each table-group\n if i == 0:\n print(f\"Skipping header-like row at index {i}.\")\n continue\n\n print(f\"Processing row at index {i}\")\n\n # Check if the row contains the necessary information (like 'kills', 'deaths' etc.)\n try:\n row.find_element(By.CSS_SELECTOR, \".table-cell.kills p\")\n except NoSuchElementException:\n print(f\"Skipping unusual row at index {i}.\")\n continue\n\n try:\n nickname = nicknames[nickname_index]\n except IndexError:\n print(f\"IndexError at row index {i}. Nickname index was {nickname_index}.\")\n continue\n\n nickname_index += 1\n\n kills = row.find_element(By.CSS_SELECTOR, \".table-cell.kills p\").text\n deaths = row.find_element(By.CSS_SELECTOR, \".table-cell.deaths p\").text\n assists = row.find_element(By.CSS_SELECTOR, \".table-cell.assists p\").text\n adr = row.find_element(By.CSS_SELECTOR, \".table-cell.adr p\").text\n\n player_data.append({\n \"Nickname\": nickname,\n \"Kills\": kills,\n \"Deaths\": deaths,\n \"Assists\": assists,\n \"ADR\": adr,\n })\n\ndriver.quit()\n\ndf = pd.DataFrame(player_data)\ntry:\n df.to_csv('C:\\\\Users\\\\Lazaro B\\\\Documents\\\\GitHub\\\\CSGOProject\\\\data\\\\Espionage\\\\IntoTheBreachVersusEspionage16-08-2023.csv', index=False)\n print(\"CSV file has been saved.\")\nexcept Exception as e:\n print(\"An error occurred while saving the CSV file: \", str(e))\n\nprint(df)\n","repo_name":"lazarobeas/CSGOProject","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"71564994312","text":"\"\"\"\r\nDesign and implement a HitCounter class that keeps track of requests (or hits). It should support the following operations:\r\n\r\n record(timestamp): records a hit that happened at timestamp\r\n total(): returns the total number of hits recorded\r\n range(lower, upper): returns the number of hits that occurred between timestamps lower and upper (inclusive)\r\n\r\nFollow-up: What if our system has limited memory?\r\n\"\"\"\r\nimport time\r\n\r\n#No podemos suponer que lleguen ordenados (Rito question here, el lag es rey)\r\n#Linked list con timemarks, ya se mejorará eficiencia luego\r\n#Supongo que se usa la biblioteca time, cuya unidad son los segundos\r\n\r\nclass TimestampList():\r\n\tdef __init__(self):\r\n\t\tself.head = null\r\n\t\tself.length = 0\r\n\t\tself.timemarks = []\r\n\r\n\r\nif __name__ == '__main__':\r\n\tfor i in range(5):\r\n\t\tprint(time.time())\r\n\t\ttime.sleep(1)\r\n","repo_name":"AlvarTR/DCP","sub_path":"Code/#132 Hit counter.py","file_name":"#132 Hit counter.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70457854473","text":"# -*- coding: utf-8 -*-\n# @Author : Erwin\nimport numpy as np\nimport tensorflow as tf\n\nembedding_dim = 5\nvocab_size = 100\n\n# ================================== method 1 ==================================\nprint(\"=\" * 40, \"method 1\", \"=\" * 40)\ntest = np.asarray([[1, 2, 3, 4], [4, 5, 6, 7]])\n\nembedding_matrix = np.random.uniform(-1, 1, (vocab_size, embedding_dim))\n\nemb_model = tf.keras.Sequential()\nembedder = tf.keras.layers.Embedding(vocab_size,\n embedding_dim,\n trainable=False,\n weights=[embedding_matrix],\n input_shape=(None,))\nemb_model.add(embedder)\nres = emb_model(tf.convert_to_tensor(test))\n\nwith tf.Session() as session:\n session.run(tf.global_variables_initializer())\n print(session.run(res))\n\n# ================================== method 2 ==================================\nprint(\"=\" * 40, \"method 2\", \"=\" * 40)\nembedding_matrix = np.random.uniform(-1, 1, (vocab_size, embedding_dim))\n\nW = tf.Variable(tf.constant(0.0, shape=[vocab_size, embedding_dim]), trainable=False, name=\"W\")\nembedding_placeholder = tf.placeholder(tf.float32, [vocab_size, embedding_dim])\nembedding_init = W.assign(embedding_placeholder)\n\nwith tf.Session() as session:\n print(session.run(embedding_init, feed_dict={embedding_placeholder: embedding_matrix}))\n\"\"\"\n参考:\n1. https://stackoverflow.com/questions/35687678/using-a-pre-trained-word-embedding-word2vec-or-glove-in-tensorflow\n2. https://stackoverflow.com/questions/62217537/tensorflow-keras-embedding-layer-applied-to-a-tensor\n\"\"\"\n# ================================== method 3 ==================================\nembedding_layer = tf.keras.layers.Embedding(1000, 5)\nresult = embedding_layer(tf.constant([1, 2, 3]))\nwith tf.Session() as session:\n session.run(tf.global_variables_initializer())\n print(session.run(result))\n\"\"\"\n参考:https://www.tensorflow.org/text/guide/word_embeddings\n\"\"\"","repo_name":"caserwin/daily-deep-learning","sub_path":"demo_tensorflow1/demo_common_op/tf_demo11_emb_pretrian.py","file_name":"tf_demo11_emb_pretrian.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"23283198695","text":"from django.urls import path,re_path\nfrom mp import views\n\nurlpatterns = [\n path('', views.index),\n path('conf',views.mconfig),\n path('countdown', views.countdown),\n path('navigate', views.navigate),\n path('about', views.about),\n path('out', views.outimg)\n]","repo_name":"jokerwho/zfnew_webApi","sub_path":"zfnweb/mp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"27"} +{"seq_id":"72305371272","text":"\"\"\"empty message\n\nRevision ID: cece18b25f57\nRevises: e11462fc1ae2\nCreate Date: 2018-11-01 18:29:29.612926\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'cece18b25f57'\ndown_revision = 'e11462fc1ae2'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('like',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('count', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('like')\n # ### end Alembic commands ###\n","repo_name":"RoyTester/myBlog","sub_path":"migrations/versions/cece18b25f57_.py","file_name":"cece18b25f57_.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"30096277359","text":"import sys\r\nfrom PyQt5.QtWidgets import QMainWindow,QLabel,QApplication,QPushButton,QLineEdit,QGridLayout,QWidget\r\nfrom PyQt5.QtCore import Qt\r\nfrom PyQt5.QtGui import QIntValidator\r\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\r\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom matplotlib.patches import Polygon\r\nfrom scipy.spatial import Voronoi,voronoi_plot_2d\r\nclass MainWindow(QMainWindow):\r\n\r\n def __init__(self,parent=None):\r\n super(MainWindow, self).__init__(parent)\r\n\r\n self.setWindowTitle('Diagram Voronoi by Damian Jancewicz') \r\n\r\n self.label=QLabel('Ile komorek Voronoi chcesz wygenerowac?')\r\n self.label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\r\n\r\n self.inputLine=QLineEdit()\r\n self.inputLine.setValidator(QIntValidator(1,9999))\r\n self.inputLine.setMaxLength(4)\r\n self.inputLine.setPlaceholderText('Podaj liczbe')\r\n\r\n self.button=QPushButton('Generuj')\r\n self.button.clicked.connect(self.buttonClicked)\r\n\r\n self.figure=plt.figure()\r\n self.figure.set_facecolor('#f0f0f0')\r\n self.canvas=FigureCanvas(self.figure)\r\n self.toolbar=NavigationToolbar(self.canvas,self)\r\n\r\n layout=QGridLayout()\r\n layout.addWidget(self.toolbar,0,0)\r\n layout.addWidget(self.canvas,1,0)\r\n layout.addWidget(self.label,2,0)\r\n layout.addWidget(self.inputLine,3,0)\r\n layout.addWidget(self.button,4,0)\r\n\r\n widget=QWidget()\r\n widget.setLayout(layout)\r\n self.setCentralWidget(widget)\r\n cid = self.figure.canvas.mpl_connect('pick_event', self.on_pick)\r\n\r\n def on_pick(self,event):\r\n if (isinstance(event.artist,Polygon) and len(self.points)>5):\r\n poly = event.artist\r\n arr=[]\r\n handle=0\r\n for x in poly.get_xy():\r\n arr.append(x)\r\n arr=tuple(map(tuple,arr))\r\n for p in self.points:\r\n if(self.point_inside_polygon(x=p[0],y=p[1],poly=arr)):\r\n p=np.asarray(p)\r\n handle=p\r\n self.points=[x for x in self.points if not (handle==x).all()]\r\n if(event.mouseevent.button==3):\r\n plt.cla()\r\n self.Voronoi_refresh()\r\n elif(event.mouseevent.button==1):\r\n poly.remove()\r\n self.canvas.draw()\r\n\r\n def point_inside_polygon(self,x,y,poly):\r\n n=len(poly)\r\n inside=False\r\n p1x,p1y=poly[0]\r\n for i in range(n+1):\r\n p2x,p2y=poly[i % n]\r\n if y>min(p1y,p2y):\r\n if y<=max(p1y,p2y):\r\n if x<=max(p1x,p2x):\r\n if p1y!=p2y:\r\n xinters=(y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x\r\n if p1x==p2x or x<=xinters:\r\n inside=not inside\r\n p1x,p1y=p2x,p2y\r\n return inside\r\n\r\n def buttonClicked(self):\r\n if self.inputLine.text()!=\"\":\r\n self.plot(int(self.inputLine.text()))\r\n\r\n def plot(self,liczba=5):\r\n self.points=np.random.rand(liczba,2)\r\n self.points=np.append(self.points, [[0,-999], [999,0], [0,999], [-999,0]], axis = 0) \r\n self.figure.clear()\r\n self.ax=self.figure.add_subplot(111)\r\n self.Voronoi_refresh()\r\n self.canvas.draw()\r\n\r\n def Voronoi_refresh(self):\r\n vor=Voronoi(self.points)\r\n voronoi_plot_2d(vor,ax=self.ax,line_colors='#f0f0f0',line_width=5,show_points=False,show_vertices=False)\r\n for region in vor.regions:\r\n if not -1 in region:\r\n polygon=[vor.vertices[i] for i in region]\r\n self.ax.fill(*zip(*polygon),joinstyle='round',capstyle='round',picker=True)\r\n self.ax.axis('off')\r\n self.ax.axis('equal')\r\n self.ax.set_xlim([0,1])\r\n self.ax.set_ylim([0,1])\r\n #self.ax.plot(np.array(vor.vertices)[:,0],np.array(vor.vertices)[:,1],'ko') \r\n #self.ax.plot(np.array(self.points)[:,0],np.array(self.points)[:,1],'kx')\r\n\r\nif __name__ == '__main__': \r\n app = QApplication(sys.argv)\r\n window = MainWindow()\r\n window.show() \r\n app.exec_()","repo_name":"dilejt/Voronoi-diagram","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70093139272","text":"import random, timeit\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n#quick_sort\ndef quick_sort(A, first, last):\n global Qc, Qs\n if first >= last: return\n left, right = first+1, last\n pivot = A[first]\n while left <= right:\n while left <= last and A[left] < pivot:\n Qc += 1 #비교횟수 + 1\n left += 1\n while right > first and A[right] > pivot:\n Qc += 1 #비교횟수 + 1\n right -= 1\n if left <= right:\n A[left], A[right] = A[right], A[left]\n Qs += 1 #교환횟수 + 1\n left += 1\n right -= 1\n \n A[first], A[right] = A[right], A[first]\n Qs += 1 #교환횟수 + 1\n \n quick_sort(A, first, right-1)\n quick_sort(A, right+1, last)\n \n#quick_sort + insertion_sort\ndef quick_sort_insertion(A, first, last):\n global Qsi, Qci\n k = 20\n if first >= last: \n return\n elif last - first < k:\n for i in range(last - first + 1): # (5, 25)\n for j in range(i,0,-1):\n Qci += 1\n if A[first+j] < A[first+j-1]:\n Qsi += 1\n A[first+j], A[first+j-1] = A[first+j-1], A[first+j]\n else:\n break\n return\n left, right = first+1, last\n pivot = A[first]\n while left <= right:\n while left <= last and A[left] < pivot:\n Qci += 1\n left += 1\n while right > first and A[right] > pivot:\n Qci += 1\n right -= 1\n if left <= right:\n Qsi += 1\n A[left], A[right] = A[right], A[left]\n left += 1\n right -= 1\n \n A[first], A[right] = A[right], A[first]\n Qsi += 1\n quick_sort_insertion(A, first, right-1)\n quick_sort_insertion(A, right+1, last)\n\n#merge_sort\ndef merge_sort(A, first, last):\n global Mc, Ms\n if first >= last: return\n merge_sort(A, first, (first+last)//2) #A의 앞부분 재귀 정렬\n merge_sort(A, (first+last)//2+1, last) #A의 뒷 부분 재귀 정렬\n merge_two_sorted_lists(A, first, last) #정렬된 두 부분 합병\n\ndef merge_two_sorted_lists(A, first, last):\n global Mc, Ms\n m = (first + last) // 2\n i, j = first, m+1\n B = []\n while i <= m and j <= last:\n Mc += 1 #비교 횟수 + 1\n if A[i] <= A[j]: #A[i]가 더 작을경우 B에 A[i] append\n B.append(A[i])\n i += 1\n else: #A[j]가 더 작을 경우 B에 A[j] append\n B.append(A[j])\n j += 1\n #while문을 나왔다는 것은 한쪽 부분의 원소가 다 B에 추가 됬다는 뜻. 따라서 아래 For문 두개중 하나만 실행하여 나머지 원소를 B에 append\n for k in range(i, m+1):\n B.append(A[k])\n Ms += 1 #교환횟수 + 1\n for k in range(j, last+1):\n B.append(A[k])\n Ms += 1 #교환횟수 + 1\n for i in range(first, last+1): # B에 있는 값(정렬된 A)를 A로 이동\n A[i] = B[i - first]\n Ms += 1 #교환횟수 + 1\n \n#3way merge_sort\ndef three_merge_sort(A, first, last):\n global Mc3, Ms3\n if last - first < 2: return\n three_merge_sort(A, first, first + ((last - first) // 3))\n three_merge_sort(A, first + ((last - first) // 3), first + 2 * ((last - first) // 3) + 1)\n three_merge_sort(A, first + 2 * ((last - first) // 3) + 1, last)\n merge_three_sorted_lists(A, first, last)\n\ndef merge_three_sorted_lists(A, first, last):\n global Mc3, Ms3\n m1 = first + ((last - first) // 3)\n m2 = first + 2 * ((last - first) // 3) + 1\n i, j, r= first, m1, m2\n B =[]\n\n while ((i < m1) and (j < m2) and (r < last)):\n Mc3 += 1\n if A[i] < A[j]:\n Mc3 += 1\n if A[i] < A[r]:\n B.append(A[i])\n Ms3 += 1 #교환횟수 + 1\n i += 1\n else:\n B.append(A[r])\n Ms3 += 1 #교환횟수 + 1\n r += 1\n else:\n Mc3 += 1\n if A[j] < A[r]:\n B.append(A[j])\n Ms3 += 1 #교환횟수 + 1\n j += 1\n else:\n B.append(A[r])\n Ms3 += 1 #교환횟수 + 1\n r += 1\n\n while ((i < m1) and (j < m2)):\n Mc3 += 1\n if A[i] < A[j]:\n B.append(A[i])\n Ms3 += 1 #교환횟수 + 1\n i += 1\n else:\n B.append(A[j])\n Ms3 += 1 #교환횟수 + 1\n j += 1\n while ((j < m2) and (r < last)):\n Mc3 += 1\n if A[j] < A[r]:\n B.append(A[j])\n Ms3 += 1 #교환횟수 + 1\n j += 1\n else:\n B.append(A[r])\n Ms3 += 1 #교환횟수 + 1\n r += 1\n\n while ((i < m1) and (r < last)):\n Mc3 += 1\n if A[i] < A[r]:\n B.append(A[i])\n Ms3 += 1 #교환횟수 + 1\n i += 1\n else:\n B.append(A[r])\n Ms3 += 1 #교환횟수 + 1\n r += 1\n\n #while문을 나옴 나머지 원소들 B에 추가.\n for k in range(i, m1):\n B.append(A[k])\n Ms3 += 1 #교환횟수 + 1\n for k in range(j, m2):\n B.append(A[k])\n Ms3 += 1 #교환횟수 + 1\n for k in range(r, last):\n B.append(A[k])\n Ms3 += 1 #교환횟수 + 1\n \n for i in range(first, last): # B에 있는 값(정렬된 A)를 A로 이동\n A[i] = B[i - first]\n Ms3 += 1\n\n\n#heap sort\ndef heap_sort(A):\n global Hc, Hs\n n=len(A)\n make_heap(A)\n for k in range(n-1, -1, -1):\n Hs += 1\n A[0],A[k] = A[k],A[0]\n n = n - 1\n heapify_down(A,0,n)\n\ndef make_heap(A):\n n=len(A)\n for k in range(n-1,-1,-1):\n heapify_down(A,k,n)\n\ndef heapify_down(A,k,n):\n global Hc, Hs\n while 2*k+1 < n:\n L, R = 2*k + 1, 2*k + 2\n Hc += 1\n if L < n and A[L] > A[k]:\n m = L\n else:\n m = k\n Hc += 1\n if R < n and A[R] > A[m]:\n m = R # m = A[k], A[L], A[R] 중 최대값의 인덱스\n if m != k: # A[k]가 최대값이 아니라면 힙 성질 위배\n Hs += 1\n A[k], A[m] = A[m], A[k]\n k = m\n else: \n break\n \n\n\n\n\n# #\n# # Qc는 quick sort에서 리스트의 두 수를 비교한 횟수 저장\n# # Qs는 quick sort에서 두 수를 교환(swap)한 횟수 저장\n# # Qci는 quick sort + insertion에서 리스트의 두 수를 비교한 횟수 저장\n# # Qsi는 quick sort + insertion에서 두 수를 교환(swap)한 횟수 저장\n# # Mc, Ms는 merge sort에서 비교, 교환(또는 이동) 횟수 저장\n# # Mc3, Ms3는 three_merge sort에서 비교, 교환(또는 이동) 횟수 저장\n# # Hc, Hs는 heap sort에서 비교, 교환(또는 이동) 횟수 저장\n# #\n\nQc, Qs, Mc, Ms, Hc, Hs, Qci, Qsi, Mc3, Ms3 = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n\n#수행시간 저장 리스트\ntimeQs = []\ntimeQsi = []\ntimeMs = []\ntimeTMs = []\ntimeHs = []\n#교환횟수 저장 리스트\ncountswapQs = []\ncountswapQsi = []\ncountswapMs = []\ncountswapTMs = []\ncountswapHs = []\n#비교횟수 저장 리스트\ncountcompareQs = []\ncountcompareQsi = []\ncountcompareMs = []\ncountcompareTMs = []\ncountcompareHs = []\n#비교+교환횟수 저장 리스트\ncountswapcompareQs = []\ncountswapcompareQsi = []\ncountswapcompareMs = []\ncountswapcompareTMs = []\ncountswapcompareHs = []\n\np = [1, 10, 50, 100, 200, 300, 400, 500, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000, 100000, 150000, 200000, 250000, 300000, 350000, 400000, 450000, 500000]\n\nfor k in p:\n random.seed()\n data = []\n for i in range(k):\n data.append(random.randint(-1000,1000))\n A = data[:]\n B = data[:]\n C = data[:]\n D = data[:]\n E = data[:]\n n = len(data)\n \n quick_sort(A, 0, n-1)\n quick_sort_insertion(D, 0, n-1)\n merge_sort(B, 0, n-1)\n three_merge_sort(E, 0, n)\n heap_sort(C)\n \n #교환횟수 비교\n countswapQs.append(Qs)\n countswapQsi.append(Qsi)\n countswapMs.append(Ms)\n countswapTMs.append(Ms3)\n countswapHs.append(Hs)\n \n \n \"\"\"\n #비교횟수 비교\n countcompareQs.append(Qc)\n countcompareQsi.append(Qci)\n countcompareMs.append(Mc)\n countcompareTMs.append(Mc3)\n countcompareHs.append(Hc)\n plt.plot(p, countcompareQs, color = \"black\", label='quick_sort')\n plt.plot(p, countcompareQsi, color = \"purple\", label='quick_sort_insertion')\n plt.plot(p, countcompareMs, color = \"yellow\", label='merge_sort')\n plt.plot(p, countcompareTMs, color = \"green\", label='three_merge_sort')\n plt.plot(p, countcompareHs, color = \"red\", label='heap_sort')\n plt.title('Compare')\n \"\"\" \n \"\"\"\n #교환+비교횟수 비교\n countswapcompareQs.append(Qs + Qc)\n countswapcompareQsi.append(Qsi + Qci)\n countswapcompareMs.append(Ms + Mc)\n countswapcompareTMs.append(Ms3 + Mc3)\n countswapcompareHs.append(Hs + Hc)\n plt.plot(p, countswapcompareQs, color = \"black\", label='quick_sort')\n plt.plot(p, countswapcompareQsi, color = \"purple\", label='quick_sort_insertion')\n plt.plot(p, countswapcompareMs, color = \"yellow\", label='merge_sort')\n plt.plot(p, countswapcompareTMs, color = \"green\", label='three_merge_sort')\n plt.plot(p, countswapcompareHs, color = \"red\", label='heap_sort')\n plt.title('Swap + compare')\n \"\"\"\n \"\"\"\n #수행시간 비교\n timeQs.append(timeit.timeit(\"quick_sort(A, 0, n-1)\", globals=globals(), number=1))\n timeQsi.append(timeit.timeit(\"quick_sort_insertion(D, 0, n-1)\", globals=globals(), number=1))\n timeMs.append(timeit.timeit(\"merge_sort(B, 0, n-1)\", globals=globals(), number=1))\n timeTMs.append(timeit.timeit(\"three_merge_sort(E, 0, n)\", globals=globals(), number=1))\n timeHs.append(timeit.timeit(\"heap_sort(C)\", globals=globals(), number=1))\n plt.plot(p, timeQs, color = \"black\", label='quick_sort')\n plt.plot(p, timeQsi, color = \"purple\", label='quick_sort_insertion')\n plt.plot(p, timeMs, color = \"yellow\", label='merge_sort')\n plt.plot(p, timeTMs, color = \"green\", label='three_merge_sort')\n plt.plot(p, timeHs, color = \"red\", label='heap_sort')\n plt.title('Running Time Analysis')\n \"\"\"\n\nplt.plot(p, countswapQs, color = \"black\", label='quick_sort')\nplt.plot(p, countswapQsi, color = \"purple\", label='quick_sort_insertion')\nplt.plot(p, countswapMs, color = \"yellow\", label='merge_sort')\nplt.plot(p, countswapTMs, color = \"green\", label='three_merge_sort')\nplt.plot(p, countswapHs, color = \"red\", label='heap_sort')\nplt.title('Swap')\n\n\nplt.xlabel('n')\nplt.ylabel('Swap Count')\nplt.legend(loc='upper right')\n\n\n\n# plt.xscale(\"log\")\n# plt.yscale(\"log\")\n\nplt.show()\n\n","repo_name":"leew0nseok/PythonStudy","sub_path":"Algorithm/algorithmClass/assignment/assignment4/assignment4_graph.py","file_name":"assignment4_graph.py","file_ext":"py","file_size_in_byte":9798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"39534774514","text":"import unittest\nimport pandas as pd\n\nfrom unittest.mock import patch\nfrom managealooma.events import Events\n\n\nclass TestEvents(unittest.TestCase):\n \"\"\" Tests the functions that retrieve and manipulate events from the API\n \"\"\"\n\n @patch('managealooma.events.Events')\n def setUp(self, events_class):\n \"\"\" Set up the event class and mocked API response with the event list\n\n :param events_class:\n :return: None\n \"\"\"\n self.events = Events(api=None)\n self.mock_get_events()\n\n @patch('managealooma.events.Events.get_all_events')\n def mock_get_events(self, mock_get_events):\n \"\"\" Create the mocked event list of dictionaries\n\n :param mock_get_mapping:\n :return: The mocked event list\n \"\"\"\n\n sample_event_list = [{'name': 'SOURCE_ONE.TABLE_ONE',\n 'mappingMode': 'AUTO_MAP',\n 'mapping': {'isDiscarded': False,\n 'outputHint': None,\n 'outputId': '12345-a1a1-b2b2-c2c2-12345asdf',\n 'tableName': 'TABLE_ONE',\n 'schema': 'SOURCE_ONE',\n 'readOnly': False},\n 'consolidation': {'consolidatedTableName': None,\n 'consolidatedSchema': None,\n 'viewSchema': None, 'consolidationKeys': []},\n 'stats': {'count': 10},\n 'state': 'MAPPED',\n 'usingDefaultMappingMode': False,\n 'schemaUrls': [],\n 'origInputLabel': 'source_one',\n 'inputObjects': {},\n 'autoMappingError': None},\n {'name': 'SOURCE_ONE.TABLE_TWO',\n 'mappingMode': 'STRICT',\n 'mapping': {'isDiscarded': False,\n 'outputHint': None,\n 'outputId': '98765-z9z9-4aa9-ba47-27274891c496',\n 'tableName': 'TABLE_TWO',\n 'schema': 'SOURCE_ONE',\n 'readOnly': False},\n 'consolidation': {'consolidatedTableName': None,\n 'consolidatedSchema': None,\n 'viewSchema': None,\n 'consolidationKeys': None},\n 'stats': None,\n 'state': 'MAPPED',\n 'usingDefaultMappingMode': True,\n 'schemaUrls': ['schema?id=43l43l-9876-543l-kjh1-1234asdf12&schema_object=two'],\n 'origInputLabel': 'source_one',\n 'inputObjects': {},\n 'autoMappingError': None},\n {'name': 'SOURCE_TWO.TABLE_ONE',\n 'mappingMode': 'STRICT',\n 'mapping': {'isDiscarded': False,\n 'outputHint': None,\n 'outputId': '201dd975-a7e1-4aa9-ba47-27274891c496',\n 'tableName': 'TABLE_ONE_LOG',\n 'schema': 'SOURCE_TWO',\n 'readOnly': False},\n 'consolidation': {'consolidatedTableName': 'TABLE_ONE',\n 'consolidatedSchema': 'SOURCE_TWO',\n 'viewSchema': None,\n 'consolidationKeys': ['ID']},\n 'stats': {'count': 5763},\n 'state': 'MAPPED',\n 'usingDefaultMappingMode': True,\n 'schemaUrls': ['schema?id=afd6e39c-2045-4fab-8f75-673cab5a3846&schema_object=three'],\n 'origInputLabel': 'source_tWO',\n 'inputObjects': {'opiuyt-l4l4-p3p3-9876-asdf1234tr': ['qwer98-2l2l-1234-2345-aa99akjlh']},\n 'autoMappingError': None}\n ]\n\n mock_get_events.return_value = sample_event_list\n return mock_get_events.return_value\n\n # Test 1\n @patch('managealooma.events.Events.get_all_events', mock_get_events)\n def test_view_events_dataframe_success(self):\n events = self.events.view_events()\n self.assertTrue(isinstance(events, pd.DataFrame))\n\n # Test 2\n @patch('managealooma.events.Events.get_all_events', mock_get_events)\n def test_view_events_dataframe_failure(self):\n events = self.events.view_events(print_format='json')\n self.assertFalse(isinstance(events, pd.DataFrame))\n\n # Test 3\n @patch('managealooma.events.Events.get_all_events', mock_get_events)\n def test_view_events_json_success(self):\n events = self.events.view_events(print_format='json')\n self.assertTrue(isinstance(events, list))\n\n # Test 4\n @patch('managealooma.events.Events.get_all_events', mock_get_events)\n def test_view_events_json_failure(self):\n events = self.events.view_events(print_format='table')\n self.assertFalse(isinstance(events, list))\n\n # Test 5\n @patch('managealooma.events.Events.get_all_events', mock_get_events)\n def test_list_events_all_inputs(self):\n event_list = self.events.list_events()\n\n expected_list = ['SOURCE_ONE.TABLE_ONE', 'SOURCE_ONE.TABLE_TWO', 'SOURCE_TWO.TABLE_ONE']\n self.assertEqual(expected_list, event_list)\n\n # Test 6\n @patch('managealooma.events.Events.get_all_events', mock_get_events)\n def test_list_events_single_input(self):\n event_list = self.events.list_events(input_labels='source_one')\n\n expected_list = ['SOURCE_ONE.TABLE_ONE', 'SOURCE_ONE.TABLE_TWO']\n self.assertEqual(expected_list, event_list)\n\n\n\n\n","repo_name":"hoverinc/ManageAlooma","sub_path":"tests/test_events.py","file_name":"test_events.py","file_ext":"py","file_size_in_byte":6353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"23485217779","text":"\"\"\"concent_api URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\n\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\n\nfrom concent_api.constants import AVAILABLE_CONCENT_FEATURES\n\n\nif not hasattr(settings, 'CONCENT_FEATURES'):\n raise ImproperlyConfigured(\"CONCENT_FEATURES setting is not defined\")\n\nif not set(settings.CONCENT_FEATURES) - set(AVAILABLE_CONCENT_FEATURES.keys()) == set():\n raise ImproperlyConfigured(\"Unrecognized feature(s) in CONCENT_FEATURES\")\n\nurlpatterns = [] # type: ignore\n\n# Run project only with features specified in CONCENT_FEATURES variable\nfor feature_name in settings.CONCENT_FEATURES:\n urlpatterns += AVAILABLE_CONCENT_FEATURES[feature_name]['url_patterns'] # type: ignore\n","repo_name":"golemfactory/concent","sub_path":"concent_api/concent_api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"27"} +{"seq_id":"27603930675","text":"import pygame, sys, random\n\ndef draw_floor():\n screen.blit(floor_surface,(floor_x_cor,900))\n screen.blit(floor_surface,(floor_x_cor+576,900))\n\ndef create_pipe():\n rand_height = random.choice(pipe_heights)\n new_bottom__pipe = pipe_surface.get_rect(midtop = (650,rand_height))\n new_top_pipe = pipe_surface.get_rect(midtop = (650,rand_height - 900 ))\n return new_bottom__pipe,new_top_pipe\n\ndef move_pipes(pipes):\n for pipe in pipes:\n pipe.centerx -= 5\n new_pipes = [pipe for pipe in pipes if pipe.right > -50]\n return new_pipes\n\ndef remove_pipes(pipes):\n for pipe in pipes:\n if pipe.centerx < -600:\n pipes.remove(pipe)\n\ndef draw_pipes(pipes):\n for pipe in pipes:\n if pipe.bottom >= 1024:\n screen.blit(pipe_surface, pipe)\n else:\n pipe_flipped = pygame.transform.flip(pipe_surface, False, True)\n screen.blit(pipe_flipped, pipe) \n\ndef check_collision(pipes):\n \n for pipe in pipes:\n if bird_rect.colliderect(pipe):\n return False\n \n if bird_rect.top <= -100 or bird_rect.bottom >=900:\n return False\n \n return True\n\ndef rotate_bird(bird):\n new_bird = pygame.transform.rotozoom(bird,-bird_movement*3,1)\n return new_bird\n\ndef flap_animation():\n new_bird = bird_frames[bird_index]\n new_bird_rect = new_bird.get_rect(center = (100,bird_rect.centery)) \n return new_bird,new_bird_rect \n \ndef display_score(game_state):\n if game_state == 'main_game':\n score_surface = game_font.render(f'Score : {int(score)}',True,(255,255,255))\n score_rect = score_surface.get_rect(center = (288,100))\n screen.blit(score_surface,score_rect)\n if game_state == 'game_over':\n score_surface = game_font.render(f'Score : {int(score)}',True,(255,255,255))\n score_rect = score_surface.get_rect(center = (288,100))\n screen.blit(score_surface,score_rect)\n \n high_score_surface = game_font.render(f'High Score : {int(high_score)}',True,(255,255,255))\n high_score_rect = high_score_surface.get_rect(center = (288,850))\n screen.blit(high_score_surface,high_score_rect)\n\ndef update_high_score(score, high_score):\n if score > high_score:\n high_score = score\n return high_score\n\ndef update_score():\n global score, score_flag\n if pipe_list:\n for pipe in pipe_list:\n if pipe.centerx < 105 and pipe.centerx > 95 and score_flag:\n score += 1 \n score_sound.play()\n score_flag = False\n if pipe.centerx < 20:\n score_flag = True \n\npygame.init()\nscreen = pygame.display.set_mode((576,1024))\nclock = pygame.time.Clock()\ngame_font = pygame.font.Font('04B_19.TTF',40)\n\n\n#Game Variables\n\n#Game_acitve\ngame_active = True\n\n#movemint variables\ngravity = 0.25\nbird_movement = 0\nscore = 0\nhigh_score = 0 \nscore_flag = True\n\n#Background variables\nbg_image = pygame.image.load('assets/background-day.png').convert()\nbg_image = pygame.transform.scale2x(bg_image)\n\n\n#Floor surface variables\nfloor_surface = pygame.image.load('assets/base.png').convert()\nfloor_surface = pygame.transform.scale2x(floor_surface)\nfloor_x_cor = 0\n\n\n#Bird variables\nbird_upflap = pygame.transform.scale2x(pygame.image.load('assets/bluebird-upflap.png').convert_alpha())\nbird_midflap = pygame.transform.scale2x(pygame.image.load('assets/bluebird-midflap.png').convert_alpha())\nbird_downflap = pygame.transform.scale2x(pygame.image.load('assets/bluebird-downflap.png').convert_alpha())\n\n#put bird frames in an array\nbird_frames = [bird_upflap,bird_midflap,bird_downflap]\nbird_index = 0\nbird_surface = bird_frames[bird_index]\nbird_rect = bird_surface.get_rect(center = (100,512))\n#Define birdflap event. set timer\nBIRDFLAP = pygame.USEREVENT +1\npygame.time.set_timer(BIRDFLAP, 250)\n\n#pipe variables\npipe_surface = pygame.image.load('assets/pipe-green.png')\npipe_surface = pygame.transform.scale2x(pipe_surface)\npipe_list = []\nSPAWNPIPE = pygame.USEREVENT\npygame.time.set_timer(SPAWNPIPE,1500)\npipe_heights = [400,600,800]\n#game loop\n\n#GAME OVER SCREEN\ngame_over_surface = pygame.transform.scale2x(pygame.image.load('assets/message.png').convert_alpha())\n\n#SOUNDS\nflap_sound = pygame.mixer.Sound('sound/sfx_wing.wav')\ndeath_sound = pygame.mixer.Sound('sound/sfx_hit.wav')\nscore_sound = pygame.mixer.Sound('sound/sfx_point.wav')\n\nSCOREVENT = pygame.USEREVENT +2\npygame.time.set_timer(SCOREVENT,100)\n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n \n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE and game_active == True:\n bird_movement = -8\n flap_sound.play()\n \n if event.key == pygame.K_SPACE and game_active == False:\n game_active = True\n score = 0\n \n #restart game\n bird_rect.center = (100,512)\n pipe_list.clear()\n bird_movement = 0\n \n \n if event.type == SPAWNPIPE:\n pipe_list.extend(create_pipe())\n \n if event.type == BIRDFLAP:\n if bird_index < 2:\n bird_index += 1\n else:\n bird_index = 0\n bird_surface,bird_rect = flap_animation()\n \n \n \n \n \n \n screen.blit(bg_image,(0,0))\n \n if game_active == True:\n bird_movement += gravity \n bird_rect.centery += bird_movement\n rotated_bird = rotate_bird(bird_surface)\n \n screen.blit(rotated_bird,bird_rect)\n #collisons\n if check_collision(pipe_list) == False:\n death_sound.play()\n game_active = check_collision(pipe_list)\n \n \n #SCORE\n update_score()\n display_score('main_game')\n high_score = update_high_score(score,high_score)\n \n #pipes\n pipe_list = move_pipes(pipe_list)\n remove_pipes(pipe_list)\n draw_pipes(pipe_list)\n \n #score += 0.01\n \n \n if game_active == False:\n display_score('game_over')\n game_over_rect = game_over_surface.get_rect(center = (288,512))\n screen.blit(game_over_surface,game_over_rect)\n pipe_list.clear()\n \n \n \n \n floor_x_cor += -1\n draw_floor()\n if floor_x_cor < -576:\n floor_x_cor = 0\n \n \n pygame.display.update()\n clock.tick(60)","repo_name":"utkjainiitk/Pygame-Flappy_bird","sub_path":"flappy_bird/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":6613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18461962888","text":"import websocket\nimport json\nfrom calculation import calculate_vwap\nimport pandas as pd\n\n\nclass BitfinexConn(websocket.WebSocketApp):\n def __init__(self, url, rsi_window):\n super().__init__(\n url,\n on_message=lambda ws, message: self.handle_message(message),\n on_open=lambda ws: self.send(\n '{ \"event\": \"subscribe\", '\n '\"channel\": \"candles\", \"key\": '\n '\"trade:1m:tBTCUSD\" }'\n ),\n on_error=lambda ws, error: print(error),\n on_close=lambda ws, close_status, close_msg: print(\n \"Connection closed\", close_msg\n )\n\n )\n self.rsi_window = rsi_window\n self.df = pd.DataFrame(\n columns=[\n 'close',\n 'high',\n 'low',\n 'volume',\n 'vwap'\n ]\n )\n\n def handle_message(self, message):\n data = json.loads(message)\n current_data = data[1]\n if current_data == \"hb\" and len(data) >= 2:\n pass\n else:\n candle_data = {\n 'close': current_data[2],\n 'high': current_data[3],\n 'low': current_data[4],\n 'volume': current_data[5]\n }\n self.df['close'] = candle_data['close']\n self.df['high'] = candle_data['high']\n self.df['low'] = candle_data['low']\n self.df['volume'] = candle_data['volume']\n\n if len(self.df) >= 2:\n vwap = calculate_vwap(self.df)\n self.df['vwap'] = vwap\n","repo_name":"califlaw/maddevs_code","sub_path":"stock-prices/bitfinex_stream.py","file_name":"bitfinex_stream.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"29557916902","text":"from decimal import *\n\nfrom django.test import TestCase\n\nfrom importer.parser import conversion_factor, parse_size, parse_year\n\n\nclass ConversionFactorTest(TestCase):\n def test_size_in_inches(self):\n size = '40 x 25 in.'\n factor = conversion_factor(size)\n self.assertEqual(Decimal('2.54'), factor)\n\n def test_size_in_feet(self):\n size = '3.75 ft.'\n factor = conversion_factor(size)\n self.assertEqual(Decimal('12.0') * Decimal('2.54'), factor)\n\n def test_size_in_meters(self):\n size = '5 meters tall'\n factor = conversion_factor(size)\n self.assertEqual(Decimal('1000.0'), factor)\n\n size = '1 meter tall'\n factor = conversion_factor(size)\n self.assertEqual(Decimal('1000.0'), factor)\n\n def test_size_in_gallons(self):\n \"\"\"\n Test of units not known to converter.\n \"\"\"\n size = '5 gal. per deciliter'\n factor = conversion_factor(size)\n self.assertEqual(Decimal('1.0'), factor)\n\n def test_ambiguous_units(self):\n \"\"\"\n Test where unit label occurs embedded in another word. Known to\n fail, need to switch conversion_factor to using regular expressions.\n \"\"\"\n size_meter = '5 kilometers to go'\n factor = conversion_factor(size_meter)\n self.assertEqual(Decimal('1.0'), factor)\n\n size_centimeter = '5 centimeters long'\n factor = conversion_factor(size_centimeter)\n self.assertEqual(Decimal('1.0'), factor)\n\n size_within = 'a word within another'\n factor = conversion_factor(size_within)\n self.assertEqual(Decimal('1.0'), factor)\n\n size_bereft = 'we are bereft. Bereft, I tell you'\n factor = conversion_factor(size_bereft)\n self.assertEqual(Decimal('1.0'), factor)\n\n\nclass YearParserTest(TestCase):\n def test_single_year(self):\n year = '1956'\n parsed_year = parse_year(year)\n self.assertEqual((1956, 1956), parsed_year)\n\n def test_nd(self):\n year = 'nd'\n parsed_year = parse_year(year)\n self.assertEqual((1, 1), parsed_year)\n\n def test_circa(self):\n year = 'c.1953'\n parsed_year = parse_year(year)\n self.assertEqual((1953, 1953), parsed_year)\n\n def test_multiple_year(self):\n year = '2011-12'\n parsed_year = parse_year(year)\n self.assertEqual((2011, 2012), parsed_year)\n\n year = '2011-2012'\n parsed_year = parse_year(year)\n self.assertEqual((2011, 2012), parsed_year)\n\n year = 'c.1950-53'\n parsed_year = parse_year(year)\n self.assertEqual((1950, 1953), parsed_year)\n\n\nclass SizeParserTest(TestCase):\n \"\"\"\n Test parse_size to make sure it captures dimensions properly. All sizes\n in centimeters, since we're not testing the conversion factor.\n \"\"\"\n def test_no_size(self):\n size = ''\n parsed_size = parse_size(size)\n self.assertEqual((Decimal('0.0'), Decimal('0.0'), Decimal('0.0')),\n parsed_size)\n\n def test_single_dimension(self):\n size = '4.5 cm tall'\n parsed_size = parse_size(size)\n self.assertEqual((Decimal('0.0'), Decimal('4.5'), Decimal('0.0')),\n parsed_size)\n\n def test_range(self):\n size = '6-8 cm. tall'\n parsed_size = parse_size(size)\n self.assertEqual((Decimal('0.0'), Decimal('8.0'), Decimal('0.0')),\n parsed_size)\n\n def test_height_width(self):\n size = '40 x 25 cm tall'\n parsed_size = parse_size(size)\n self.assertEqual((Decimal('0.0'), Decimal('40.0'), Decimal('25.0')),\n parsed_size)\n\n def test_depth_height_width(self):\n size = '12 x 40 x 25 cm'\n parsed_size = parse_size(size)\n self.assertEqual((Decimal('12.0'), Decimal('40.0'), Decimal('25.0')),\n parsed_size)\n","repo_name":"tpherndon/art_import","sub_path":"importer/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3869,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"71511338951","text":"\"\"\" Contains implementation of parametrized ShuffleNet model. \"\"\"\n\nfrom ..blocks import CShuffleUnit\nfrom ..bases import Sequential\nfrom .base_model import BaseModel\n\n\nclass ShuffleNetV1(BaseModel):\n\n @classmethod\n def default_config(cls):\n config = BaseModel.default_config()\n\n config['input'] = {\n 'layout': 'cnap',\n 'c': dict(kernel_size=3, stride=2, filters=24),\n 'p': dict(kernel_size=3, stride=2, mode='max')\n }\n\n config['body'] = {\n 'filters': (272, 544, 1088),\n 'num_blocks': (4, 8, 4),\n 'shuffle_unit': {\n 'groups': 4,\n 'factor': 4,\n 'pool_kernel': 3,\n 'pool_mode': 'avg',\n 'post_activation': True,\n 'layout': 'cna s cn cn'\n }\n }\n\n config['head'] = {\n 'layout': '> fa',\n '>': dict(mode='avg'),\n 'f': dict(out_features=10),\n 'a': dict(activation='linear')\n }\n return config\n\n def build_body(self, input_shape, config):\n shuffle_unit_config = config.get('shuffle_unit')\n filters = config.get('filters')\n num_blocks = config.get('num_blocks')\n shape = input_shape\n body = Sequential()\n for i, ifilters in enumerate(filters):\n for j, repeats in enumerate(range(num_blocks[i])):\n iconfig = {\n 'downsample': j == 0,\n 'filters': ifilters,\n 'block': self.conv_block,\n **shuffle_unit_config\n }\n if i == 0 and j == 0:\n iconfig.update({'groups': 1})\n x = CShuffleUnit(shape, **iconfig)\n\n body.add_module(\"Block_{}_{}\".format(i, j), x)\n shape = x.output_shape\n return body\n","repo_name":"kirillemilio/convblock","sub_path":"convblock/pytorch/models/shuffle_net_v1.py","file_name":"shuffle_net_v1.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"71463358793","text":"import pandas as pd\nimport csv\nimport click\n\n@click.command()\n@click.option('-file')\ndef main(file):\n df = pd.read_csv(file)\n df = df[[\"src\", \"mt\", \"ref\", \"score\"]]\n df[\"src\"] = df[\"src\"].astype(str)\n df[\"mt\"] = df[\"mt\"].astype(str)\n df[\"ref\"] = df[\"ref\"].astype(str)\n df[\"score\"] = df[\"score\"].astype(float)\n\n # refactorFile = open('post_rm_'+file, 'w')\n # csvwriter = csv.writer(refactorFile)\n # fields = [\"src\", \"mt\", \"ref\", \"score\"]\n # csvwriter.writerow(fields)\n\n for src, mt, ref, score in zip(df[\"src\"], df[\"mt\"], df[\"ref\"], df[\"score\"]):\n if len(mt.split()) - len(ref.split()) < -10:\n #print(len(ref.split()))\n if len(ref.split()) < 50:\n print(mt)\n print(ref)\n print('-----------------------------------')\n #Ecsvwriter.writerow([src, mt, ref, score])\n #\n # print(\"remove some severe error data!\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"xu1998hz/SEScore","sub_path":"util/len_diff_step.py","file_name":"len_diff_step.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"27"} +{"seq_id":"7278930896","text":"from twistedcaldav import carddavxml\nfrom twistedcaldav.query import addressbookqueryfilter\nimport twistedcaldav.test.util\nfrom twistedcaldav.query.addressbookquery import sqladdressbookquery\n\nclass Tests(twistedcaldav.test.util.TestCase):\n\n def test_query(self):\n \"\"\"\n Basic query test - single term.\n Only UID can be queried via sql.\n \"\"\"\n\n filter = carddavxml.Filter(\n *[carddavxml.PropertyFilter(\n carddavxml.TextMatch.fromString(\"Example\"),\n **{\"name\":\"UID\"}\n )]\n )\n filter = addressbookqueryfilter.Filter(filter)\n\n sql, args = sqladdressbookquery(filter)\n self.assertTrue(sql.find(\"UID\") != -1)\n self.assertTrue(\"*Example*\" in args)\n","repo_name":"abdyfranco/serveros","sub_path":"src/server/10.9/Payload/Applications/Server.app/Contents/ServerRoot/usr/share/caldavd/lib/python/twistedcaldav/query/test/test_addressbookquery.py","file_name":"test_addressbookquery.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"27"} +{"seq_id":"36515497073","text":"# coding=UTF-8\nfrom __future__ import unicode_literals\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.conf import settings\nfrom django.db import models\nfrom category_sys.choices.model_choices import top_type_choice, type_unit_choice\n\n\nclass ProductTopType(models.Model):\n t_top_name = models.CharField(max_length=20)\n in_use = models.BooleanField(default=True)\n operator = models.IntegerField(_(\"所属端类型\"), choices=top_type_choice.choice)\n create_time = models.DateTimeField(auto_now_add=True)\n icon = models.ImageField(upload_to=settings.UPLOAD_CATEGORY_ICON, null=True, blank=True)\n\n @property\n def product_sub_type(self):\n return ProductSubType.objects.filter(toptype_b=self)\n\n def __unicode__(self):\n return self.t_top_name\n\n\nclass ProductSubType(models.Model):\n t_sub_name = models.CharField(max_length=20)\n in_use = models.BooleanField(default=True)\n create_time = models.DateTimeField(auto_now_add=True)\n unit = models.IntegerField(_(\"计价单位\"), choices=type_unit_choice.choice)\n toptype_c = models.ForeignKey(\n ProductTopType,\n verbose_name=_(\"C端顶级品类\"),\n related_name=\"c_subtype\"\n )\n toptype_b = models.ForeignKey(\n ProductTopType,\n verbose_name=_(\"B端顶级品类\"),\n related_name=\"b_subtype\"\n )\n\n def __unicode__(self):\n return self.t_sub_name\n","repo_name":"49527/miniprogram_backend","sub_path":"category_sys/models/category_model.py","file_name":"category_model.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"16346078930","text":"import unittest\nfrom typing import Tuple\n\nimport numpy as np\nimport xarray as xr\nfrom numpy.testing import assert_array_almost_equal\n\nfrom test.sampledata import create_highroc_dataset, create_c2rcc_flag_var, create_cmems_sst_flag_var\nfrom xcube.core.maskset import MaskSet\n\n\nclass MaskSetTest(unittest.TestCase):\n def test_mask_set_with_flag_mask_str(self):\n flag_var = create_cmems_sst_flag_var().chunk(dict(lon=2, lat=2))\n mask_set = MaskSet(flag_var)\n\n self.assertEqual('mask(sea=(1, None), land=(2, None), lake=(4, None), ice=(8, None))',\n str(mask_set))\n\n expected_chunks = ((1,), (2, 1), (2, 2))\n self.assertMaskOk(mask_set, 'sea', expected_chunks)\n self.assertMaskOk(mask_set, 'land', expected_chunks)\n self.assertMaskOk(mask_set, 'lake', expected_chunks)\n self.assertMaskOk(mask_set, 'ice', expected_chunks)\n\n validation_data = ((0, 'sea', mask_set.sea, np.array([[[1, 0, 0, 0],\n [1, 1, 0, 0],\n [1, 1, 1, 0]]],\n dtype=np.uint8)),\n (1, 'land', mask_set.land, np.array([[[0, 1, 0, 0],\n [0, 0, 1, 1],\n [0, 0, 0, 1]]],\n dtype=np.uint8)),\n (2, 'lake', mask_set.lake, np.array([[[0, 0, 1, 1],\n [0, 0, 0, 0],\n [0, 0, 0, 0]]],\n dtype=np.uint8)),\n (3, 'ice', mask_set.ice, np.array([[[1, 1, 1, 0],\n [1, 0, 0, 0],\n [0, 0, 0, 0]]],\n dtype=np.uint8)))\n\n for index, name, mask, data in validation_data:\n self.assertIs(mask, mask_set[index])\n self.assertIs(mask, mask_set[name])\n assert_array_almost_equal(mask.values, data, err_msg=f'{index}, {name}, {mask.name}')\n\n def test_mask_set_with_flag_mask_int_array(self):\n flag_var = create_c2rcc_flag_var().chunk(dict(x=2, y=2))\n mask_set = MaskSet(flag_var)\n\n self.assertEqual('c2rcc_flags(F1=(1, None), F2=(2, None), F3=(4, None), F4=(8, None))',\n str(mask_set))\n\n expected_chunks = ((2, 1), (2, 2))\n self.assertMaskOk(mask_set, 'F1', expected_chunks)\n self.assertMaskOk(mask_set, 'F2', expected_chunks)\n self.assertMaskOk(mask_set, 'F3', expected_chunks)\n self.assertMaskOk(mask_set, 'F4', expected_chunks)\n\n validation_data = ((0, 'F1', mask_set.F1, np.array([[1, 1, 1, 1],\n [1, 0, 1, 0],\n [0, 1, 1, 1]],\n dtype=np.uint8)),\n (1, 'F2', mask_set.F2, np.array([[0, 0, 0, 0],\n [0, 0, 0, 1],\n [0, 0, 0, 0]],\n dtype=np.uint8)),\n (2, 'F3', mask_set.F3, np.array([[0, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 0, 0]],\n dtype=np.uint8)),\n (3, 'F4', mask_set.F4, np.array([[0, 0, 0, 0],\n [0, 0, 0, 0],\n [1, 0, 0, 0]],\n dtype=np.uint8)))\n\n for index, name, mask, data in validation_data:\n self.assertIs(mask, mask_set[index])\n self.assertIs(mask, mask_set[name])\n assert_array_almost_equal(mask.values, data)\n\n def assertMaskOk(self,\n mask_set: MaskSet,\n mask_name: str,\n expected_chunks: Tuple[Tuple[int, ...], ...] = None):\n\n mask = getattr(mask_set, mask_name)\n\n self.assertIsInstance(mask, xr.DataArray)\n\n if expected_chunks:\n import dask.array as da\n self.assertIsInstance(mask.data, da.Array)\n self.assertEqual(expected_chunks, mask.chunks)\n\n # assert same instance is returned\n self.assertIs(mask, getattr(mask_set, mask_name))\n\n self.assertIn(mask_name, mask_set)\n # assert same instance is returned\n self.assertIs(mask, mask_set[mask_name])\n\n def test_get_mask_sets(self):\n dataset = create_highroc_dataset()\n mask_sets = MaskSet.get_mask_sets(dataset)\n self.assertIsNotNone(mask_sets)\n self.assertEqual(len(mask_sets), 1)\n self.assertIn('c2rcc_flags', mask_sets)\n mask_set = mask_sets['c2rcc_flags']\n self.assertIsInstance(mask_set, MaskSet)\n\n def test_mask_set_with_flag_values(self):\n s2l2a_slc_meanings = ['no_data',\n 'saturated_or_defective',\n 'dark_area_pixels',\n 'cloud_shadows',\n 'vegetation',\n 'bare_soils',\n 'water',\n 'clouds_low_probability_or_unclassified',\n 'clouds_medium_probability',\n 'clouds_high_probability',\n 'cirrus',\n 'snow_or_ice']\n\n data = np.array([[1, 2, 8, 3],\n [7, 6, 0, 4],\n [9, 5, 11, 10]], dtype=np.uint8)\n flag_var = xr.DataArray(data,\n dims=('y', 'x'),\n name='SLC',\n attrs=dict(\n long_name=\"Scene classification flags\",\n flag_values=','.join(f'{i}' for i in range(len(s2l2a_slc_meanings))),\n flag_meanings=' '.join(s2l2a_slc_meanings),\n ))\n\n mask_set = MaskSet(flag_var)\n\n self.assertEqual('SLC(no_data=(None, 0), saturated_or_defective=(None, 1), dark_area_pixels=(None, 2), '\n 'cloud_shadows=(None, 3), vegetation=(None, 4), bare_soils=(None, 5), water=(None, 6), '\n 'clouds_low_probability_or_unclassified=(None, 7), clouds_medium_probability=(None, 8), '\n 'clouds_high_probability=(None, 9), cirrus=(None, 10), snow_or_ice=(None, 11))',\n str(mask_set))\n\n validation_data = ((0, 'no_data', mask_set.no_data, np.array([[0, 0, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 0]],\n dtype=np.uint8)),\n (4, 'vegetation', mask_set.vegetation, np.array([[0, 0, 0, 0],\n [0, 0, 0, 1],\n [0, 0, 0, 0]],\n dtype=np.uint8)),\n (10, 'cirrus', mask_set.cirrus, np.array([[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 1]],\n dtype=np.uint8)),\n (6, 'water', mask_set.water, np.array([[0, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 0, 0]],\n dtype=np.uint8)))\n\n for index, name, mask, data in validation_data:\n msg = f'index={index}, name={name!r}, data={data!r}'\n self.assertIs(mask, mask_set[index], msg=msg)\n self.assertIs(mask, mask_set[name], msg=msg)\n assert_array_almost_equal(mask.values, data, err_msg=msg)\n\n self.assertEqual(set(s2l2a_slc_meanings), set(dir(mask_set)))\n\n html = mask_set._repr_html_()\n self.assertTrue(html.startswith(''))\n self.assertTrue(html.endswith(''))\n\n def test_mask_set_with_missing_values_and_masks_attrs(self):\n flag_var = create_c2rcc_flag_var().chunk(dict(x=2, y=2))\n flag_var.attrs.pop('flag_masks', None)\n flag_var.attrs.pop('flag_values', None)\n with self.assertRaises(ValueError):\n MaskSet(flag_var)\n\n def test_mask_set_with_missing_meanings_attr(self):\n flag_var = create_c2rcc_flag_var().chunk(dict(x=2, y=2))\n flag_var.attrs.pop('flag_meanings', None)\n with self.assertRaises(ValueError):\n MaskSet(flag_var)\n","repo_name":"dcs4cop/xcube","sub_path":"test/core/test_maskset.py","file_name":"test_maskset.py","file_ext":"py","file_size_in_byte":9652,"program_lang":"python","lang":"en","doc_type":"code","stars":159,"dataset":"github-code","pt":"27"} +{"seq_id":"27454883159","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nfrom typing import List\n\nclass Solution:\n def letterCombinations(self, digits: str) -> List[str]:\n out = []\n if len(digits)>0:\n dct = {\"2\":['a','b','c'], \"3\":['d','e','f'], \"4\":['g','h','i'], \n \"5\":['j','k','l'], \"6\":['m', 'n', 'o'], \"7\":['p','q','r','s'], \n \"8\":['t','u','v'], \"9\":['w','x','y','z']}\n def dfs(i, s):\n if i>=len(digits):\n out.append(s)\n return\n else:\n for ch in dct[digits[i]]:\n dfs(i+1, s+ch)\n \n dfs(0, '')\n return out\n \n \n \n \n \n \n \n \n \n \n \n \ns = Solution()\nprint(s.letterCombinations(\"3\"))","repo_name":"ydzhang12345/LeetCode","sub_path":"17.Letter_Combinations_of_a_Phone_Number/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"21548334487","text":"from __future__ import absolute_import, division, print_function\n\nimport logging\nimport os\nimport re\n\nimport click\nimport click_log\n\nfrom . import (\n DEFAULT_CONTENT_THRESHOLD,\n DEFAULT_SIZE_THRESHOLD,\n DELETE_MATCHING_PATH,\n DELETE_NEWER,\n DELETE_NEWEST,\n DELETE_NON_MATCHING_PATH,\n DELETE_OLDER,\n DELETE_OLDEST,\n MD_SUBDIRS,\n STRATEGIES,\n TIME_SOURCES,\n Config,\n __version__,\n)\nfrom .deduplicate import Deduplicate\nfrom .mail import Mail\n\n\ncli_logger = logging.getLogger(__name__)\nlogger = click_log.basic_config('mdedup')\n@click.group(invoke_without_command=True)\n@click_log.simple_verbosity_option(\n 'mdedup',\n default='INFO', metavar='LEVEL',\n help='Either CRITICAL, ERROR, WARNING, INFO or DEBUG. Defaults to INFO.')\n@click.version_option(__version__)\n@click.pass_context\ndef cli(ctx):\n \"\"\" CLI for maildirs content analysis and deletion. \"\"\"\n level = logging.getLogger('mdedup').level\n try:\n level_to_name = logging._levelToName\n # Fallback to pre-Python 3.4 internals.\n except AttributeError:\n level_to_name = logging._levelNames\n level_name = level_to_name.get(level, level)\n logger.debug('Verbosity set to {}.'.format(level_name))\n\n # Print help screen and exit if no sub-commands provided.\n if ctx.invoked_subcommand is None:\n click.echo(ctx.get_help())\n ctx.exit()\n\n # Load up global options to the context.\n ctx.obj = {}\n\n\ndef validate_regexp(ctx, param, value):\n \"\"\" Validate and compile regular expression. \"\"\"\n if value:\n try:\n value = re.compile(value)\n except ValueError:\n raise click.BadParameter('invalid regular expression.')\n return value\n\n\ndef validate_maildirs(ctx, param, value):\n \"\"\" Check that folders are maildirs. \"\"\"\n for path in value:\n for subdir in MD_SUBDIRS:\n if not os.path.isdir(os.path.join(path, subdir)):\n raise click.BadParameter(\n '{} is not a maildir (missing {!r} sub-directory).'.format(\n path, subdir))\n return value\n\n\n@cli.command(short_help='Deduplicate maildirs content.')\n@click.option(\n '-s', '--strategy', type=click.Choice(STRATEGIES), required=True,\n help='Deletion strategy to apply within a subset of duplicates.')\n@click.option(\n '-t', '--time-source', type=click.Choice(TIME_SOURCES),\n help=\"Source of a mail's reference time. Required in time-sensitive \"\n 'strategies.')\n@click.option(\n '-r', '--regexp', callback=validate_regexp, metavar='REGEXP',\n help='Regular expression against a mail file path. Required in '\n 'delete-matching-path and delete-non-matching-path strategies.')\n@click.option(\n '-n', '--dry-run', is_flag=True, default=False,\n help='Do not actually delete anything; just show what would be removed.')\n@click.option(\n '-i', '--message-id', is_flag=True, default=False,\n help='Only use the Message-ID header as a hash key. Not recommended. '\n 'Replace the default behavior consisting in deriving the hash from '\n 'several headers.')\n@click.option(\n '-S', '--size-threshold', type=int, metavar='BYTES',\n default=DEFAULT_SIZE_THRESHOLD,\n help='Maximum allowed difference in size between mails. Whole subset of '\n 'duplicates will be rejected above threshold. Set to -1 to not allow any '\n 'difference. Defaults to {} bytes.'.format(DEFAULT_SIZE_THRESHOLD))\n@click.option(\n '-C', '--content-threshold', type=int, metavar='BYTES',\n default=DEFAULT_CONTENT_THRESHOLD,\n help='Maximum allowed difference in content between mails. Whole subset '\n 'of duplicates will be rejected above threshold. Set to -1 to not allow '\n 'any difference. Defaults to {} bytes.'.format(DEFAULT_CONTENT_THRESHOLD))\n@click.option(\n '-d', '--show-diff', is_flag=True, default=False,\n help='Show the unified diff of duplicates not within thresholds.')\n# TODO: add a show-progress option.\n@click.argument(\n 'maildirs', nargs=-1, callback=validate_maildirs,\n type=click.Path(exists=True, file_okay=False, resolve_path=True))\n@click.pass_context\ndef deduplicate(\n ctx, strategy, time_source, regexp, dry_run, message_id,\n size_threshold, content_threshold, show_diff, maildirs):\n \"\"\" Deduplicate mails from a set of maildir folders.\n\n Run a first pass computing the canonical hash of each encountered mail from\n their headers, then a second pass to apply the deletion strategy on each\n subset of duplicate mails.\n\n \\b\n Removal strategies for each subsets of duplicate mails:\n - delete-older: Deletes the olders, keeps the newests.\n - delete-oldest: Deletes the oldests, keeps the newers.\n - delete-newer: Deletes the newers, keeps the oldests.\n - delete-newest: Deletes the newests, keeps the olders.\n - delete-smaller: Deletes the smallers, keeps the biggests.\n - delete-smallest: Deletes the smallests, keeps the biggers.\n - delete-bigger: Deletes the biggers, keeps the smallests.\n - delete-biggest: Deletes the biggests, keeps the smallers.\n - delete-matching-path: Deletes all duplicates whose file path match the\n regular expression provided via the --regexp parameter.\n - delete-non-matching-path: Deletes all duplicates whose file path\n doesn't match the regular expression provided via the --regexp parameter.\n\n Deletion strategy on a duplicate set only applies if no major differences\n between mails are uncovered during a fine-grained check differences during\n the second pass. Limits can be set via the threshold options.\n \"\"\"\n # Print help screen and exit if no maildir folder provided.\n if not maildirs:\n click.echo(ctx.get_help())\n ctx.exit()\n\n # Validate exclusive options requirement depending on strategy.\n requirements = [\n (time_source, '-t/--time-source', [\n DELETE_OLDER, DELETE_OLDEST, DELETE_NEWER, DELETE_NEWEST]),\n (regexp, '-r/--regexp', [\n DELETE_MATCHING_PATH, DELETE_NON_MATCHING_PATH])]\n for param_value, param_name, required_strategies in requirements:\n if strategy in required_strategies:\n if not param_value:\n raise click.BadParameter(\n '{} strategy requires the {} parameter.'.format(\n strategy, param_name))\n elif param_value:\n raise click.BadParameter(\n '{} parameter not allowed in {} strategy.'.format(\n param_name, strategy))\n\n conf = Config(\n strategy=strategy,\n time_source=time_source,\n regexp=regexp,\n dry_run=dry_run,\n show_diff=show_diff,\n message_id=message_id,\n size_threshold=size_threshold,\n content_threshold=content_threshold,\n # progress=progress,\n )\n\n dedup = Deduplicate(conf)\n\n logger.info('=== Start phase #1: load mails and compute hashes.')\n for maildir in maildirs:\n dedup.add_maildir(maildir)\n\n logger.info('=== Start phase #2: deduplicate mails.')\n dedup.run()\n\n dedup.report()\n\n\n@cli.command(short_help='Hash a single mail.')\n# TODO: Deduplicate option definition.\n@click.option(\n '-i', '--message-id', is_flag=True, default=False,\n help='Only use the Message-ID header as a hash key. Not recommended. '\n 'Replace the default behavior consisting in deriving the hash from '\n 'several headers.')\n@click.argument('message', type=click.Path(\n exists=True, dir_okay=False, resolve_path=True))\n@click.pass_context\ndef hash(ctx, message_id, message):\n \"\"\" Take a single mail message and show its canonicalised form and hash.\n\n Mainly used to debug message hashing.\n \"\"\"\n conf = Config(message_id=message_id)\n\n mail = Mail(message, conf)\n\n logger.info(mail.header_text)\n logger.info('-' * 70)\n logger.info('Hash: {}'.format(mail.hash_key))\n","repo_name":"mistrey/maildir-deduplicate","sub_path":"maildir_deduplicate/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":7919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"27479827430","text":"def replaceElements(arr: list) -> list:\n if(arr==[]):\n return\n i=0\n while(i>> {senha}')\n\n print('Senha salva com sucesso! Verifique na pasta correspondente.')\n\n\nteste = GeradorDeSenha()\nteste.iniciar()\n","repo_name":"VictorGM01/interfaces_graficas","sub_path":"gerador_de_senha/gerador_de_senha.py","file_name":"gerador_de_senha.py","file_ext":"py","file_size_in_byte":6325,"program_lang":"python","lang":"pt","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"13330163910","text":"# -*- coding: utf-8 -*-\n'''pn_sale'''\nfrom odoo import api, fields, models, _\nfrom openerp.exceptions import Warning\nfrom odoo.addons import decimal_precision as dp\nimport logging\n\n_logger = logging.getLogger(__name__)\n\n\nclass SaleOrder(models.Model):\n '''inherit sale.order'''\n _inherit = \"sale.order\"\n\n @api.multi\n def total_terbilang(self, amount_total):\n '''function total terbilang'''\n for order in self:\n unit = [\"\", \"Satu\", \"Dua\", \"Tiga\", \"Empat\",\n \"Lima\", \"Enam\", \"Tujuh\", \"Delapan\",\n \"Sembilan\", \"Sepuluh\", \"Sebelas\"]\n result = \" \"\n total_terbilang = order.total_terbilang\n n = int(amount_total)\n if n >= 0 and n <= 11:\n result = result + unit[n]\n elif n < 20:\n result = total_terbilang(n % 10) + \" Belas\"\n elif n < 100:\n result = total_terbilang(n / 10) + \" Puluh\" + total_terbilang(n % 10)\n elif n < 200:\n result = \" Seratus\" + total_terbilang(n - 100)\n elif n < 1000:\n result = total_terbilang(n / 100) + \" Ratus\" + total_terbilang(n % 100)\n elif n < 2000:\n result = \" Seribu\" + total_terbilang(n - 1000)\n elif n < 1000000:\n result = total_terbilang(n / 1000) + \" Ribu\" + total_terbilang(n % 1000)\n elif n < 1000000000:\n result = total_terbilang(n / 1000000) + \" Juta\" + total_terbilang(n % 1000000)\n else:\n result = total_terbilang(n / 1000000000) + \" Miliar\" + total_terbilang(n % 1000000000)\n return result\n\n @api.multi\n def write(self, vals):\n '''extend function write to add warning if\n payment term customer is different with sale order'''\n for sale in self:\n partner_id = sale.partner_id\n payment_term_id = partner_id.property_payment_term_id\n sale_term_id = sale.payment_term_id\n _logger.warning(\"Payment term %s, %s: %s\", partner_id.name, payment_term_id and payment_term_id.name,\n sale_term_id.name)\n if sale.env.user.company_id != sale.company_id:\n actual_term = self.env['res.partner'].with_context(force_company=sale.company_id.id).browse(\n partner_id.id).property_payment_term_id\n if actual_term and actual_term.id != sale.payment_term_id.id:\n raise Warning(\"Cannot change Payment Term!\")\n else:\n if payment_term_id and payment_term_id.id != sale_term_id.id:\n actual_term = self.env['res.partner'].with_context(force_company=sale.company_id.id).browse(\n partner_id.id).property_payment_term_id\n if actual_term and actual_term.id != sale_term_id.id:\n if vals.get('payment_term_id'):\n if actual_term.id != vals.get('payment_term_id'):\n raise Warning(\"Cannot change Payment Term!\")\n else:\n raise Warning(\"Cannot change Payment Term!\")\n\n res = super(SaleOrder, self).write(vals)\n\n return res\n\n\n\n\n\nclass SaleOrder_msi(models.Model):\n '''inherit sale.order.line'''\n _inherit = \"sale.order.line\"\n\n discount1 = fields.Float(string='Discount (%)', digits=dp.get_precision('Discount'), default=0.0)\n\n @api.model\n def create(self, values):\n values['discount'] = values.get('discount1')\n values.update(self._prepare_add_missing_fields(values))\n line = super(SaleOrder_msi, self).create(values)\n if line.order_id.state == 'sale':\n msg = _(\"Extra line with %s \") % (line.product_id.display_name,)\n line.order_id.message_post(body=msg)\n # create an analytic account if at least an expense product\n if line.product_id.expense_policy != 'no' and not self.order_id.analytic_account_id:\n self.order_id._create_analytic_account()\n\n return line\n\n @api.onchange('product_id', 'price_unit', 'product_uom', 'product_uom_qty', 'tax_id')\n def _onchange_discount(self):\n self.discount = 0.0\n if not (self.product_id and self.product_uom and self.order_id.partner_id and self.order_id.pricelist_id and self.order_id.pricelist_id.discount_policy == 'without_discount' and self.env.user.has_group('sale.group_discount_per_so_line')):\n return\n\n product = self.product_id.with_context(\n lang=self.order_id.partner_id.lang,\n partner=self.order_id.partner_id.id,\n quantity=self.product_uom_qty,\n date=self.order_id.date_order,\n pricelist=self.order_id.pricelist_id.id,\n uom=self.product_uom.id,\n fiscal_position=self.env.context.get('fiscal_position')\n )\n\n product_context = dict(self.env.context, partner_id=self.order_id.partner_id.id, date=self.order_id.date_order, uom=self.product_uom.id)\n\n price, rule_id = self.order_id.pricelist_id.with_context(product_context).get_product_price_rule(self.product_id, self.product_uom_qty or 1.0, self.order_id.partner_id)\n new_list_price, currency_id = self.with_context(product_context)._get_real_price_currency(product, rule_id, self.product_uom_qty, self.product_uom, self.order_id.pricelist_id.id)\n\n if new_list_price != 0:\n if self.order_id.pricelist_id.currency_id.id != currency_id:\n # we need new_list_price in the same currency as price, which is in the SO's pricelist's currency\n new_list_price = self.env['res.currency'].browse(currency_id).with_context(product_context).compute(new_list_price, self.order_id.pricelist_id.currency_id)\n discount = (new_list_price - price) / new_list_price * 100\n if discount > 0:\n self.discount = discount\n self.discount1 = discount\n","repo_name":"robert8118/pennyu","sub_path":"pn_sale/models/sale.py","file_name":"sale.py","file_ext":"py","file_size_in_byte":6026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"74543046790","text":"class Solution(object):\n def combinationSum3(self, k, n):\n \"\"\"\n :type k: int\n :type n: int\n :rtype: List[List[int]]\n \"\"\"\n total_nums = [1,2,3,4,5,6,7,8,9]\n result = []\n def recursive(target, k, nums):\n if k==1:\n if target not in nums and target in total_nums:\n nums.append(target)\n nums.sort()\n if nums not in result:\n result.append(nums)\n else:\n for i in range(len(total_nums)):\n if total_nums[i] in nums:\n continue\n if target>total_nums[i]: \n recursive(target - total_nums[i], k-1, nums+[total_nums[i]])\n\n recursive(n,k,[]) \n return result \n\n\n ","repo_name":"TaekMinKim000406/Leetcode","sub_path":"0216-combination-sum-iii/0216-combination-sum-iii.py","file_name":"0216-combination-sum-iii.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"30244068737","text":"from Classes.Parser import Parser\nfrom Classes.HTMLWorker import HTMLWorker\nfrom Classes.GPA import GPA\nfrom Classes.Majors import Majors\nimport pyodbc\nimport re\n\ndef ConnectToTheDatabase():\n global cnxn, cursor\n cnxn = pyodbc.connect(r'Driver={SQL Server};Server=SUDB-DEV;Database=Spiderman;Trusted_Connection=yes;')\n cursor = cnxn.cursor()\n\n\ndef GetInfoFromDatabase():\n cursor.execute(\"SELECT ScholarshipPackageId, Elgibility FROM dbo.DepartmentTestCases\")\n\nConnectToTheDatabase()\nGetInfoFromDatabase()\n\nEligibilities = []\nScholarshipIds = []\nwhile 1:\n row = cursor.fetchone()\n if not row:\n break\n Eligibilities.append(row.Elgibility)\n ScholarshipIds.append(row.ScholarshipPackageId)\n\nfor e in range(len(Eligibilities)):\n print(ScholarshipIds[e])\n\n Eligibility = Eligibilities[e]\n Eligibility = re.sub('<.*?>| ', '', Eligibility)\n print(Eligibility)\n\n parseGPA = GPA(Eligibility, ScholarshipIds[e])\n # parseMajor = Majors(Eligibility)\n\n print(parseGPA.getGPA())\n # print(parseMajor.getMajors())\n","repo_name":"kyajpauley/cerebro","sub_path":"Kya Practice Files/MappingDBtoSPRPractice.py","file_name":"MappingDBtoSPRPractice.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70322546311","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('accounts', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='UserFollow',\n fields=[\n ('id', models.AutoField(primary_key=True, verbose_name='ID', serialize=False, auto_created=True)),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('from_user', models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='following_set')),\n ('to_user', models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='follower_set')),\n ],\n ),\n migrations.AlterUniqueTogether(\n name='userfollow',\n unique_together=set([('from_user', 'to_user')]),\n ),\n ]\n","repo_name":"lamiru/pystagram","sub_path":"accounts/migrations/0002_auto_20160525_0218.py","file_name":"0002_auto_20160525_0218.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"26085603217","text":"from rest_framework.serializers import ModelSerializer\nfrom rest_framework import serializers\nfrom .models import (\n Category,\n Discount,\n Promocode,\n Producer,\n ProductItem,\n RegistredUser,\n Order,\n Cashback,\n Comment,\n)\nfrom django.contrib.auth import authenticate\nimport datetime\n\n\nclass CategorySerializer(ModelSerializer):\n class Meta:\n model = Category\n fields = \"__all__\"\n\n\nclass DiscountSerializer(ModelSerializer):\n class Meta:\n model = Discount\n fields = \"__all__\"\n\n\nclass ProducerSerializer(ModelSerializer):\n class Meta:\n model = Producer\n fields = \"__all__\"\n\n\nclass PromocodeSerializer(ModelSerializer):\n class Meta:\n model = Promocode\n fields = \"__all__\"\n\n\nclass CommentSerializer(ModelSerializer):\n author = serializers.CharField(source=\"user.email\")\n text = serializers.CharField(source=\"comment\")\n\n class Meta:\n model = Comment\n fields = [\"author\", \"text\"]\n\n\nclass ProductItemDetailSerializer(ModelSerializer):\n category_name = serializers.CharField(source=\"category.name\")\n discount_name = serializers.CharField(source=\"discount.name\")\n discount_percent = serializers.IntegerField(source=\"discount.percent\")\n producer_name = serializers.CharField(source=\"producer.name\")\n comments = CommentSerializer(many=True, source=\"comment_set\")\n\n class Meta:\n model = ProductItem\n fields = [\n \"id\",\n \"name\",\n \"description\",\n \"producer_name\",\n \"category_name\",\n \"discount_name\",\n \"discount_percent\",\n \"price\",\n \"articul\",\n \"count_on_stock\",\n \"comments\",\n ]\n\n\nclass ProductItemSerializer(ModelSerializer):\n producer = ProducerSerializer()\n category = CategorySerializer()\n discount = DiscountSerializer()\n\n class Meta:\n model = ProductItem\n fields = [\n \"id\",\n \"name\",\n \"discount\",\n \"description\",\n \"producer\",\n \"category\",\n \"price\",\n \"articul\",\n \"count_on_stock\",\n ]\n\n\nclass RegistarationSerializer(ModelSerializer):\n password = serializers.CharField(\n max_length=100, min_length=8, write_only=True\n )\n\n token = serializers.CharField(max_length=255, read_only=True)\n\n class Meta:\n model = RegistredUser\n fields = [\"phone\", \"email\", \"password\", \"login\", \"token\", \"age\"]\n\n def create(self, validated_data):\n return RegistredUser.objects.create_user(**validated_data)\n\n\nclass LoginSerializer(serializers.Serializer):\n phone = serializers.CharField(max_length=13)\n password = serializers.CharField(max_length=100, write_only=True)\n token = serializers.CharField(max_length=255, read_only=True)\n\n def validate(self, data):\n phone = data.get(\"phone\", None)\n password = data.get(\"password\", None)\n\n if phone is None:\n raise serializers.ValidationError(\n \"Phone number is required to log in\"\n )\n\n if password is None:\n raise serializers.ValidationError(\"Password is required to log in\")\n\n user = authenticate(username=phone, password=password)\n\n if user is None:\n raise serializers.ValidationError(\n \"A user with this password and phone was not found\"\n )\n\n if not user.is_active:\n raise serializers.ValidationError(\"This account was not verified\")\n\n return {\"phone\": user.phone, \"token\": user.token}\n\n\nclass ProductInBasketSerializer(serializers.Serializer):\n name = serializers.CharField(max_length=200)\n price = serializers.DecimalField(max_digits=10, decimal_places=2)\n number_of_item = serializers.IntegerField()\n\n\nclass BasketSerializer(serializers.Serializer):\n products = ProductInBasketSerializer(many=True)\n result_price = serializers.SerializerMethodField()\n\n def get_result_price(self, data):\n result_price = 0\n\n for item in data.get(\"products\"):\n if item.get(\"discount\"):\n percent = item.get(\"discount_percent\")\n expire_date = item.get(\"discount_expire_date\")\n delta = expire_date - datetime.datetime.now(\n datetime.timezone.utc\n )\n if delta.days >= 0 and delta.seconds > 0:\n result_price += (\n float(item.get(\"price\"))\n * ((100 - percent) / 100)\n * item.get(\"number_of_item\")\n )\n else:\n result_price += item.get(\"price\") * item.get(\n \"number_of_item\"\n )\n else:\n result_price += item.get(\"price\") * item.get(\"number_of_item\")\n\n return result_price\n\n\nclass AddProductSerializer(serializers.Serializer):\n product_id = serializers.IntegerField()\n number_of_item = serializers.IntegerField()\n\n\nclass DeleteProductSerializer(serializers.Serializer):\n product_id = serializers.IntegerField()\n\n\nclass OrderSerializer(serializers.ModelSerializer):\n promocode = serializers.CharField(write_only=True)\n use_cashback = serializers.BooleanField(write_only=True)\n\n class Meta:\n model = Order\n fields = \"__all__\"\n extra_kwargs = {\n \"result_price\": {\"read_only\": True},\n \"result_number_of_items\": {\"read_only\": True},\n \"user\": {\"read_only\": True},\n }\n\n def calculate_result_price(self, data):\n product_items_dict = data.get(\"product_items\")\n product_items_ids = product_items_dict.keys()\n product_items = ProductItem.objects.filter(\n id__in=product_items_ids\n ).values(\"id\", \"price\", \"discount__percent\", \"discount__expire_date\")\n promocode_name = data.get(\"promocode\")\n promocode = Promocode.objects.filter(name=promocode_name).first()\n\n result_price = 0\n result_price_with_discounts = 0\n\n for item in product_items:\n number_of_items = product_items_dict.get(str(item.get(\"id\")))\n discount_percent = item.get(\"discount__percent\")\n price = float(item.get(\"price\"))\n result_price += price * number_of_items\n\n if discount_percent:\n discount_expire = item.get(\"discount__expire_date\")\n delta = discount_expire - datetime.datetime.now(\n datetime.timezone.utc\n )\n if delta.days >= 0 and delta.seconds > 0:\n result_price_with_discounts += (\n price\n * (100 - discount_percent)\n / 100\n * number_of_items\n )\n else:\n result_price_with_discounts += price * number_of_items\n else:\n result_price_with_discounts += price * number_of_items\n\n if promocode:\n delta = promocode.expire_date - datetime.datetime.now(\n datetime.timezone.utc\n )\n if delta.days >= 0 and delta.seconds > 0:\n if promocode.is_allowed_to_sum_with_discounts:\n result_price = (\n result_price_with_discounts\n * (100 - promocode.percent)\n / 100\n )\n else:\n result_price = (\n result_price * (100 - discount_percent) / 100\n )\n else:\n result_price = result_price_with_discounts\n else:\n result_price = result_price_with_discounts\n\n cashback = Cashback.objects.all().first()\n if cashback is not None:\n add_cashback_points = result_price * (cashback.percent / 100)\n user = self.context.get(\"request\").user\n\n if data.get(\"use_cashback\"):\n if user.cashback <= cashback.max_cashback_payment:\n result_price -= user.cashback\n user.cashback = 0\n else:\n result_price -= cashback.max_cashback_payment\n user.cashback -= cashback.max_cashback_payment\n\n user.cashback += add_cashback_points\n user.save()\n\n return result_price\n\n def result_number_of_items(self, data):\n return sum(data.get(\"product_items\").values())\n\n def get_user(self):\n request = self.context.get(\"request\")\n return request.user\n\n def validate(self, attrs):\n attrs[\"result_price\"] = self.calculate_result_price(attrs)\n attrs[\"result_number_of_items\"] = self.result_number_of_items(attrs)\n attrs[\"user\"] = self.get_user()\n attrs.pop(\"promocode\", None)\n attrs.pop(\"use_cashback\", None)\n\n return attrs\n","repo_name":"annett21/drf-shop","sub_path":"shop/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":8997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"34652887276","text":"import pandas as pd\nfrom bs4 import BeautifulSoup\nimport urllib2\nimport Claim as claim_obj\nimport dateparser\n\n\nignore_urls = ['https://apublica.org/2017/07/truco-7-fatos-sobre-a-reforma-trabalhista/',\n 'https://apublica.org/checagem/',\n 'https://apublica.org/2017/03/truco-6-fatos-sobre-a-reforma-da-previdencia/']\n\ndef get_all_claims(criteria):\n claims = []\n\n soup = get_soup('https://apublica.org/checagem/')\n\n # Get the number of pages\n pages_links = soup.findAll('a', {\"class\": \"page-link\"})\n number_of_pages = int(pages_links[::-1][1].text)\n print('Number of pages: ' + str(number_of_pages))\n\n # For each page\n for page_i in range(number_of_pages):\n if (criteria.maxClaims > 0 and len(claims)>= criteria.maxClaims):\n break\n page_i += 1\n print('Page ' + str(page_i) + '|' + str(number_of_pages))\n soup = get_soup('https://apublica.org/checagem/page/' + str(page_i) + '/')\n\n fact_links = [fl.a['href'] for fl in soup.findAll('div', {\"class\": \"card\"})]\n for f_link in fact_links:\n if f_link in ignore_urls:\n continue\n if (criteria.maxClaims > 0 and len(claims)>= criteria.maxClaims):\n break\n print(f_link)\n soup2 = get_soup(f_link)\n title_ = soup2.find('title').text\n tags_ = soup2.find('div', {'class', 'tags'}).text.split()\n\n contr = 0\n refered_links = []\n date_ = soup2.find('span', {'class': 'date'}).text\n claim_ = new_claim(f_link, date_, title_, tags_)\n stop = False\n for c in soup2.find('div', {'class', 'post-contents'}).contents:\n if (criteria.maxClaims > 0 and len(claims)>= criteria.maxClaims):\n break\n if c.name is None: continue\n if c.name == 'hr':\n if stop:\n claim_.setRefered_links(refered_links)\n claims.append(claim_.getDict())\n claim_ = new_claim(f_link, date_, title_, tags_)\n stop = False\n contr = 1\n continue\n if contr == 1:\n claim_.setClaim(c.text)\n contr = 2\n if c.find('img'):\n claim_.setConclusion(c.img['alt'])\n contr = 3\n stop = True\n continue\n if contr == 2:\n claim_.setConclusion(c.img['alt'])\n claim_.setBody(claim_.body + \"\\n\" + c.text)\n for l in c.findAll('a', href=True):\n refered_links.append(l['href'])\n contr = 3\n continue\n if contr == 3:\n for l in c.findAll('a', href=True):\n refered_links.append(l['href'])\n claim_.setBody(claim_.body + \"\\n\" + c.text)\n for l in c.findAll('a', href=True):\n refered_links.append(l['href'])\n if stop:\n if (criteria.maxClaims > 0 and len(claims) >= criteria.maxClaims):\n break\n claim_.setRefered_links(refered_links)\n claims.append(claim_.getDict())\n print('Number of claims: '+str(len(claims)))\n pdf = pd.DataFrame(claims)\n return pdf\n\n\ndef get_soup(url):\n user_agent = 'Mozilla/5.0'\n request = urllib2.urlopen(urllib2.Request(url, data=None, headers={'User-Agent': user_agent}))\n page = request.read()\n return BeautifulSoup(page, 'lxml')\n\n\ndef new_claim(f_link, date, title, tags):\n claim_ = claim_obj.Claim()\n claim_.setUrl(f_link)\n claim_.setTitle(title)\n claim_.setTags(tags)\n date_ = date.strip().split()\n date_ = \"-\".join([date_[4], date_[2], date_[0]])\n claim_.setDate(dateparser.parse(date_).strftime(\"%Y-%m-%d\"))\n claim_.setSource(\"publica\")\n claim_.setBody(\"\")\n return claim_\n","repo_name":"MaazAmjad/fake_news_extractor","sub_path":"ce/publica.py","file_name":"publica.py","file_ext":"py","file_size_in_byte":4071,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"43113722760","text":"from PyQt5 import QtWidgets, uic\r\nimport sys\r\nfrom one_d_modelling_window import Ui as oneDmod\r\n\r\n\r\nclass Ui(QtWidgets.QMainWindow):\r\n def __init__(self):\r\n super(Ui, self).__init__() # Call the inherited classes __init__ method\r\n uic.loadUi('main_window.ui', self) # Load the .ui file\r\n\r\n self.action1D_Modelling.triggered.connect(lambda: self.action1d_modelling_clicked())\r\n\r\n self.showMaximized()\r\n\r\n @staticmethod\r\n def action1d_modelling_clicked():\r\n window_one_d_mod = oneDmod()\r\n window_one_d_mod.show()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app = QtWidgets.QApplication(sys.argv)\r\n window = Ui()\r\n app.exec_()\r\n","repo_name":"riflab/rifGEM","sub_path":"src/main_window.py","file_name":"main_window.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"30672792781","text":"#!/usr/bin/env python3\r\n#\r\n# Copyright (c) 2021 Nordic Semiconductor ASA\r\n#\r\n# SPDX-License-Identifier: Apache-2.0\r\n#\r\n\r\nfrom unittest import TestCase, main\r\nfrom subprocess import Popen, PIPE\r\nfrom re import sub\r\nfrom pathlib import Path\r\nfrom pprint import pprint\r\n# from ecdsa import VerifyingKey\r\nfrom hashlib import sha256\r\nimport cbor2\r\n\r\n\r\ntry:\r\n import cddl_gen\r\nexcept ImportError:\r\n print(\"\"\"\r\nThe cddl_gen package must be installed to run these tests.\r\nDuring development, install with `python3 setup.py develop` to install in a way\r\nthat picks up changes in the files without having to reinstall.\r\n\"\"\")\r\n import sys\r\n sys.exit(1)\r\n\r\n\r\np_root = Path(__file__).absolute().parents[2]\r\np_tests = Path(p_root, 'tests')\r\np_manifest12 = Path(p_tests, 'cases', 'manifest12.cddl')\r\np_manifest14 = Path(p_tests, 'cases', 'manifest14.cddl')\r\np_test_vectors12 = tuple(Path(p_tests, 'cases', f'manifest12_example{i}.cborhex') for i in range(6))\r\np_test_vectors14 = tuple(Path(p_tests, 'cases', f'manifest14_example{i}.cborhex') for i in range(6))\r\np_optional = Path(p_tests, 'cases', 'optional.cddl')\r\np_cose = Path(p_tests, 'cases', 'cose.cddl')\r\np_manifest14_priv = Path(p_tests, 'cases', 'manifest14.priv')\r\np_manifest14_pub = Path(p_tests, 'cases', 'manifest14.pub')\r\n\r\n\r\nclass Testn(TestCase):\r\n def decode_file(self, data_path, *cddl_paths):\r\n data = bytes.fromhex(data_path.read_text().replace(\"\\n\", \"\"))\r\n self.decode_string(data, *cddl_paths)\r\n\r\n def decode_string(self, data_string, *cddl_paths):\r\n cddl_str = \" \".join((Path(p).read_text() for p in cddl_paths))\r\n self.my_types = cddl_gen.DataTranslator.from_cddl(cddl_str, 16).my_types\r\n cddl = self.my_types[\"SUIT_Envelope_Tagged\"]\r\n self.decoded = cddl.decode_str(data_string)\r\n\r\n\r\nclass Test0(Testn):\r\n def __init__(self, *args, **kwargs):\r\n super(Test0, self).__init__(*args, **kwargs)\r\n self.decode_file(p_test_vectors12[0], p_manifest12)\r\n\r\n def test_manifest_digest(self):\r\n self.assertEqual(\r\n bytes.fromhex(\"5c097ef64bf3bb9b494e71e1f2418eef8d466cc902f639a855ec9af3e9eddb99\"),\r\n self.decoded.suit_authentication_wrapper.SUIT_Digest_bstr.suit_digest_bytes)\r\n\r\n def test_signature(self):\r\n self.assertEqual(\r\n 1,\r\n self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].COSE_Sign1_Tagged.protected.uintint[0].uintint_key)\r\n self.assertEqual(\r\n -7,\r\n self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].COSE_Sign1_Tagged.protected.uintint[0].uintint)\r\n self.assertEqual(\r\n bytes.fromhex(\"a19fd1f23b17beed321cece7423dfb48c457b8f1f6ac83577a3c10c6773f6f3a7902376b59540920b6c5f57bac5fc8543d8f5d3d974faa2e6d03daa534b443a7\"),\r\n self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].COSE_Sign1_Tagged.signature)\r\n\r\n def test_validate_run(self):\r\n self.assertEqual(\r\n \"suit_condition_image_match\",\r\n self.decoded.suit_manifest.SUIT_Unseverable_Members.suit_validate[0].suit_validate.union[0].SUIT_Condition.union_choice)\r\n self.assertEqual(\r\n \"suit_directive_run\",\r\n self.decoded.suit_manifest.SUIT_Unseverable_Members.suit_run[0].suit_run.union[0].SUIT_Directive.union_choice)\r\n\r\n def test_image_size(self):\r\n self.assertEqual(34768, self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map[3].suit_parameter_image_size)\r\n\r\n\r\nclass Test1(Testn):\r\n def __init__(self, *args, **kwargs):\r\n super(Test1, self).__init__(*args, **kwargs)\r\n self.decode_file(p_test_vectors12[1], p_manifest12)\r\n\r\n def test_components(self):\r\n self.assertEqual(\r\n [b'\\x00'],\r\n self.decoded.suit_manifest.suit_common.suit_components[0][0].bstr)\r\n\r\n def test_uri(self):\r\n self.assertEqual(\r\n \"http://example.com/file.bin\",\r\n self.decoded.suit_manifest.SUIT_Severable_Manifest_Members.suit_install[0].suit_install.union[0].SUIT_Directive.suit_directive_set_parameters.map[0].suit_parameter_uri)\r\n\r\n\r\nclass Test2(Testn):\r\n def __init__(self, *args, **kwargs):\r\n super(Test2, self).__init__(*args, **kwargs)\r\n self.decode_file(p_test_vectors12[2], p_manifest12)\r\n\r\n def test_severed_uri(self):\r\n self.assertEqual(\r\n \"http://example.com/very/long/path/to/file/file.bin\",\r\n self.decoded.SUIT_Severable_Manifest_Members.suit_install[0].suit_install.union[0].SUIT_Directive.suit_directive_set_parameters.map[0].suit_parameter_uri)\r\n\r\n def test_severed_text(self):\r\n self.assertIn(\r\n \"Example 2\",\r\n self.decoded.SUIT_Severable_Manifest_Members.suit_text[0].suit_text.SUIT_Text_Keys.suit_text_manifest_description[0])\r\n self.assertEqual(\r\n [b'\\x00'],\r\n self.decoded.SUIT_Severable_Manifest_Members.suit_text[0].suit_text.SUIT_Component_Identifier[0].SUIT_Component_Identifier_key.bstr)\r\n self.assertEqual(\r\n \"arm.com\",\r\n self.decoded.SUIT_Severable_Manifest_Members.suit_text[0].suit_text.SUIT_Component_Identifier[0].SUIT_Component_Identifier.SUIT_Text_Component_Keys.suit_text_vendor_domain[0])\r\n self.assertEqual(\r\n \"This component is a demonstration. The digest is a sample pattern, not a real one.\",\r\n self.decoded.SUIT_Severable_Manifest_Members.suit_text[0].suit_text.SUIT_Component_Identifier[0].SUIT_Component_Identifier.SUIT_Text_Component_Keys.suit_text_component_description[0])\r\n\r\n\r\nclass Test3(Testn):\r\n def __init__(self, *args, **kwargs):\r\n super(Test3, self).__init__(*args, **kwargs)\r\n self.decode_file(p_test_vectors12[3], p_manifest12)\r\n\r\n def test_A_B_offset(self):\r\n self.assertEqual(\r\n 33792,\r\n self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[1].SUIT_Common_Commands.suit_directive_try_each.SUIT_Directive_Try_Each_Argument.SUIT_Command_Sequence_bstr[0].union[0].SUIT_Directive.suit_directive_override_parameters.map[0].suit_parameter_component_offset)\r\n self.assertEqual(\r\n 541696,\r\n self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[1].SUIT_Common_Commands.suit_directive_try_each.SUIT_Directive_Try_Each_Argument.SUIT_Command_Sequence_bstr[1].union[0].SUIT_Directive.suit_directive_override_parameters.map[0].suit_parameter_component_offset)\r\n\r\n\r\nclass Test4(Testn):\r\n def __init__(self, *args, **kwargs):\r\n super(Test4, self).__init__(*args, **kwargs)\r\n self.decode_file(p_test_vectors12[4], p_manifest12)\r\n\r\n def test_load_decompress(self):\r\n self.assertEqual(\r\n 0,\r\n self.decoded.suit_manifest.SUIT_Unseverable_Members.suit_load[0].suit_load.union[1].SUIT_Directive.suit_directive_set_parameters.map[3].suit_parameter_source_component)\r\n self.assertEqual(\r\n \"SUIT_Compression_Algorithm_zlib\",\r\n self.decoded.suit_manifest.SUIT_Unseverable_Members.suit_load[0].suit_load.union[1].SUIT_Directive.suit_directive_set_parameters.map[2].suit_parameter_compression_info.suit_compression_algorithm)\r\n\r\n\r\nclass Test5(Testn):\r\n def __init__(self, *args, **kwargs):\r\n super(Test5, self).__init__(*args, **kwargs)\r\n self.decode_file(p_test_vectors12[5], p_manifest12)\r\n\r\n def test_two_image_match(self):\r\n self.assertEqual(\r\n \"suit_condition_image_match\",\r\n self.decoded.suit_manifest.SUIT_Severable_Manifest_Members.suit_install[0].suit_install.union[3].SUIT_Condition.union_choice)\r\n self.assertEqual(\r\n \"suit_condition_image_match\",\r\n self.decoded.suit_manifest.SUIT_Severable_Manifest_Members.suit_install[0].suit_install.union[7].SUIT_Condition.union_choice)\r\n\r\n\r\ndef dumps(obj):\r\n return cbor2.dumps(obj, canonical=True)\r\n\r\n\r\ndef loads(string):\r\n return cbor2.loads(string)\r\n\r\n\r\nclass Test6(Testn):\r\n def __init__(self, *args, **kwargs):\r\n super(Test6, self).__init__(*args, **kwargs)\r\n self.decode_file(p_test_vectors14[0], p_manifest14, p_cose)\r\n\r\n def test_authentication(self):\r\n digest = bytes.fromhex(\"a6c4590ac53043a98e8c4106e1e31b305516d7cf0a655eddfac6d45c810e036a\")\r\n signature = bytes.fromhex(\"d11a2dd9610fb62a707335f584079225709f96e8117e7eeed98a2f207d05c8ecfba1755208f6abea977b8a6efe3bc2ca3215e1193be201467d052b42db6b7287\")\r\n sig_struct = bytes.fromhex(\"846a5369676e61747572653143a10126405820a6c4590ac53043a98e8c4106e1e31b305516d7cf0a655eddfac6d45c810e036a\")\r\n # key = VerifyingKey.from_pem(p_manifest14_pub.read_text())\r\n # key.verify_digest(signature, digest)\r\n # key.verify(signature, digest, hashfunc=sha256)\r\n # key.verify(signature, sig_struct, hashfunc=sha256)\r\n\r\n self.assertEqual(\"COSE_Sign1_Tagged\", self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].union_choice)\r\n self.assertEqual(-7, self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].COSE_Sign1_Tagged.Headers.protected.header_map_bstr.Generic_Headers.uint1union[0].int)\r\n manifest_signature = self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].COSE_Sign1_Tagged.signature\r\n sig_struct = [\"Signature\", self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].COSE_Sign1_Tagged.Headers.protected.header_map_bstr_bstr, b'', b'', b'']\r\n sig_struct_encoded = dumps(sig_struct)\r\n # self.assertEqual(dumps(self.decoded.suit_manifest.orig_obj), self.decoded.orig_obj[3])\r\n manifest_str = dumps(self.decoded.suit_manifest_bstr)\r\n # manifest_hash = sha256(manifest_str).digest()\r\n manifest_hash = dumps(sha256(manifest_str).digest())\r\n manifest_suit_digest = self.decoded.suit_authentication_wrapper.SUIT_Digest_bstr_bstr\r\n # manifest_suit_digest = dumps(dumps(self.decoded.suit_authentication_wrapper.SUIT_Digest_bstr.orig_obj))\r\n sig_struct_encoded = sig_struct_encoded[:-1] + manifest_hash\r\n # sig_struct_encoded = sig_struct_encoded[:-1] + dumps(manifest_hash)\r\n # sig_struct_encoded = sig_struct_encoded[:-1] + dumps(manifest_suit_digest)\r\n # sig_struct_encoded = sig_struct_encoded[:-1] + dumps(dumps(manifest_suit_digest))\r\n # res = self.my_types[\"Sig_structure\"].validate_str(sig_struct_encoded)\r\n # print (sig_struct_encoded.hex())\r\n loaded = loads(sig_struct_encoded)\r\n # key = VerifyingKey.from_pem(p_manifest14_pub.read_text())\r\n # print(sig_struct_encoded.hex())\r\n # print(key.to_string().hex())\r\n # print(manifest_signature.hex())\r\n # res = key.verify(manifest_signature, dumps(self.decoded.orig_obj[3]), hashfunc=sha256)\r\n # res = key.verify_digest(manifest_signature, manifest_hash)\r\n # res = key.verify(manifest_signature, manifest_hash, hashfunc=sha256)\r\n # res = key.verify(manifest_signature, dumps(manifest_hash), hashfunc=sha256)\r\n # res = key.verify(manifest_signature, manifest_suit_digest, hashfunc=sha256)\r\n # res = key.verify(manifest_signature, dumps(manifest_suit_digest), hashfunc=sha256)\r\n # res = key.verify(manifest_signature, dumps(sig_struct_encoded), hashfunc=sha256)\r\n # res = key.verify(manifest_signature, sig_struct_encoded, hashfunc=sha256)\r\n # print(res)\r\n\r\n\r\nclass Test7(Testn):\r\n def __init__(self, *args, **kwargs):\r\n super(Test7, self).__init__(*args, **kwargs)\r\n self.decode_file(p_test_vectors14[1], p_manifest14, p_cose)\r\n\r\n def test_structure(self):\r\n self.assertEqual(\"COSE_Sign1_Tagged\", self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].union_choice)\r\n self.assertEqual(-7, self.decoded.suit_authentication_wrapper.SUIT_Authentication_Block_bstr[0].COSE_Sign1_Tagged.Headers.protected.header_map_bstr.Generic_Headers.uint1union[0].int)\r\n self.assertEqual(bytes.fromhex(\"60c61d6eb7a1aaeddc49ce8157a55cff0821537eeee77a4ded44155b03045132\"), self.decoded.suit_authentication_wrapper.SUIT_Digest_bstr.suit_digest_bytes)\r\n self.assertEqual(1, self.decoded.suit_manifest.suit_manifest_sequence_number)\r\n self.assertEqual(bytes.fromhex(\"fa6b4a53d5ad5fdfbe9de663e4d41ffe\"), self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map[0].suit_parameter_vendor_identifier.RFC4122_UUID)\r\n self.assertEqual(bytes.fromhex(\"1492af1425695e48bf429b2d51f2ab45\"), self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map[1].suit_parameter_class_identifier)\r\n self.assertEqual(bytes.fromhex(\"00112233445566778899aabbccddeeff0123456789abcdeffedcba9876543210\"), self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map[2].suit_parameter_image_digest.suit_digest_bytes)\r\n self.assertEqual('cose_alg_sha_256', self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map[2].suit_parameter_image_digest.suit_digest_algorithm_id.union_choice)\r\n self.assertEqual(34768, self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map[3].suit_parameter_image_size)\r\n self.assertEqual(4, len(self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map))\r\n self.assertEqual(15, self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[1].SUIT_Condition.suit_condition_vendor_identifier.SUIT_Rep_Policy)\r\n self.assertEqual(15, self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[2].SUIT_Condition.suit_condition_class_identifier.SUIT_Rep_Policy)\r\n self.assertEqual(3, len(self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union))\r\n self.assertEqual(2, len(self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0]))\r\n self.assertEqual(2, len(self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands))\r\n self.assertEqual(1, len(self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters))\r\n self.assertEqual(4, len(self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map))\r\n self.assertEqual(2, len(self.decoded.suit_manifest.suit_common.suit_common_sequence[0].suit_common_sequence.union[0].SUIT_Common_Commands.suit_directive_override_parameters.map[0]))\r\n\r\n def test_cbor_pen(self):\r\n data = bytes.fromhex(p_test_vectors14[1].read_text().replace(\"\\n\", \"\"))\r\n struct = loads(data)\r\n struct2 = loads(struct.value[3]) # manifest\r\n struct3 = loads(struct2[3]) # common sequence\r\n struct4 = loads(struct3[4]) # override params\r\n self.assertEqual(struct4[0], 20)\r\n self.assertTrue(isinstance(struct4[1][1], bytes))\r\n struct4[1][1] = cbor2.CBORTag(112, struct4[1][1]) # Add the tag for cbor-pen\r\n struct3[4] = dumps(struct4)\r\n struct2[3] = dumps(struct3)\r\n struct.value[3] = dumps(struct2)\r\n data = dumps(struct)\r\n self.decode_string(data, p_manifest14, p_cose)\r\n\r\n\r\nclass Test7Inv(Testn):\r\n def test_inv0(self):\r\n data = bytes.fromhex(p_test_vectors14[1].read_text().replace(\"\\n\", \"\"))\r\n struct = loads(data)\r\n struct2 = loads(struct.value[2]) # authentication\r\n struct3 = loads(struct2[1])\r\n struct3.tag = 99999 # invalid tag for COSE_Sign1\r\n struct2[1] = dumps(struct3)\r\n struct.value[2] = dumps(struct2)\r\n data = dumps(struct)\r\n try:\r\n self.decode_string(data, p_manifest14, p_cose)\r\n except cddl_gen.CddlValidationError as e:\r\n return\r\n else:\r\n assert False, \"Should have failed validation\"\r\n\r\n def test_inv1(self):\r\n data = bytes.fromhex(p_test_vectors14[1].read_text().replace(\"\\n\", \"\"))\r\n struct = loads(data)\r\n struct2 = loads(struct.value[3]) # manifest\r\n struct2[1] += 1 # invalid manifest version\r\n struct.value[3] = dumps(struct2)\r\n data = dumps(struct)\r\n try:\r\n self.decode_string(data, p_manifest14, p_cose)\r\n except cddl_gen.CddlValidationError as e:\r\n return\r\n else:\r\n assert False, \"Should have failed validation\"\r\n\r\n def test_inv2(self):\r\n data = bytes.fromhex(p_test_vectors14[1].read_text().replace(\"\\n\", \"\"))\r\n struct = loads(data)\r\n struct.value[23] = b'' # Invalid integrated payload key\r\n data = dumps(struct)\r\n try:\r\n self.decode_string(data, p_manifest14, p_cose)\r\n except (cddl_gen.CddlValidationError, cbor2.CBORDecodeEOF) as e:\r\n return\r\n else:\r\n assert False, \"Should have failed validation\"\r\n\r\n def test_inv3(self):\r\n data = bytes.fromhex(p_test_vectors14[1].read_text().replace(\"\\n\", \"\"))\r\n struct = loads(data)\r\n struct2 = loads(struct.value[3]) # manifest\r\n struct3 = loads(struct2[3]) # common sequence\r\n struct4 = loads(struct3[4]) # override params\r\n self.assertEqual(struct4[0], 20)\r\n self.assertTrue(isinstance(struct4[1][1], bytes))\r\n struct4[1][1] += b'x' # vendor ID: wrong length\r\n struct3[4] = dumps(struct4)\r\n struct2[3] = dumps(struct3)\r\n struct.value[3] = dumps(struct2)\r\n data = dumps(struct)\r\n try:\r\n self.decode_string(data, p_manifest14, p_cose)\r\n except cddl_gen.CddlValidationError as e:\r\n return\r\n else:\r\n assert False, \"Should have failed validation\"\r\n\r\n\r\nclass Test8(Testn):\r\n def __init__(self, *args, **kwargs):\r\n super(Test8, self).__init__(*args, **kwargs)\r\n self.decode_file(p_test_vectors14[2], p_manifest14, p_cose)\r\n\r\n def test_text(self):\r\n self.assertEqual(\r\n bytes.fromhex('2bfc4d0cc6680be7dd9f5ca30aa2bb5d1998145de33d54101b80e2ca49faf918'),\r\n self.decoded.suit_manifest.SUIT_Severable_Members_Choice.suit_text[0].SUIT_Digest.suit_digest_bytes)\r\n self.assertEqual(\r\n bytes.fromhex('2bfc4d0cc6680be7dd9f5ca30aa2bb5d1998145de33d54101b80e2ca49faf918'),\r\n sha256(dumps(self.decoded.SUIT_Severable_Manifest_Members.suit_text[0].suit_text_bstr)).digest())\r\n self.assertEqual('arm.com', self.decoded.SUIT_Severable_Manifest_Members.suit_text[0].suit_text.SUIT_Component_Identifier[0].SUIT_Component_Identifier.SUIT_Text_Component_Keys.suit_text_vendor_domain[0])\r\n self.assertEqual('This component is a demonstration. The digest is a sample pattern, not a real one.', self.decoded.SUIT_Severable_Manifest_Members.suit_text[0].suit_text.SUIT_Component_Identifier[0].SUIT_Component_Identifier.SUIT_Text_Component_Keys.suit_text_component_description[0])\r\n\r\n # Check manifest description. The concatenation and .replace() call are there to add\r\n # trailing whitespace to all blank lines except the first.\r\n # This is done in this way to avoid editors automatically removing the whitespace.\r\n self.assertEqual('''## Example 2: Simultaneous Download, Installation, Secure Boot, Severed Fields\r\n''' + '''\r\n This example covers the following templates:\r\n\r\n * Compatibility Check ({{template-compatibility-check}})\r\n * Secure Boot ({{template-secure-boot}})\r\n * Firmware Download ({{firmware-download-template}})\r\n\r\n This example also demonstrates severable elements ({{ovr-severable}}), and text ({{manifest-digest-text}}).'''.replace(\"\\n\\n\", \"\\n \\n\"), self.decoded.SUIT_Severable_Manifest_Members.suit_text[0].suit_text.SUIT_Text_Keys.suit_text_manifest_description[0])\r\n\r\n\r\nclass Test9(Testn):\r\n def __init__(self, *args, **kwargs):\r\n super(Test9, self).__init__(*args, **kwargs)\r\n self.decode_file(p_test_vectors14[3], p_manifest14, p_cose)\r\n\r\n def test_try_each(self):\r\n self.assertEqual(2, len(self.decoded.suit_manifest.SUIT_Severable_Members_Choice.suit_install[0].SUIT_Command_Sequence_bstr.union[0].SUIT_Directive.suit_directive_try_each.SUIT_Directive_Try_Each_Argument.SUIT_Command_Sequence_bstr))\r\n self.assertEqual(33792, self.decoded.suit_manifest.SUIT_Severable_Members_Choice.suit_install[0].SUIT_Command_Sequence_bstr.union[0].SUIT_Directive.suit_directive_try_each.SUIT_Directive_Try_Each_Argument.SUIT_Command_Sequence_bstr[0].union[0].SUIT_Directive.suit_directive_set_parameters.map[0].suit_parameter_component_slot)\r\n self.assertEqual(541696, self.decoded.suit_manifest.SUIT_Severable_Members_Choice.suit_install[0].SUIT_Command_Sequence_bstr.union[0].SUIT_Directive.suit_directive_try_each.SUIT_Directive_Try_Each_Argument.SUIT_Command_Sequence_bstr[1].union[0].SUIT_Directive.suit_directive_set_parameters.map[0].suit_parameter_component_slot)\r\n\r\n\r\nclass Test10(Testn):\r\n def __init__(self, *args, **kwargs):\r\n super(Test10, self).__init__(*args, **kwargs)\r\n self.decode_file(p_test_vectors14[4], p_manifest14, p_cose)\r\n\r\n def test_components(self):\r\n self.assertEqual(3, len(self.decoded.suit_manifest.suit_common.suit_components[0]))\r\n self.assertEqual(b'\\x00', self.decoded.suit_manifest.suit_common.suit_components[0][0].bstr[0])\r\n self.assertEqual(b'\\x02', self.decoded.suit_manifest.suit_common.suit_components[0][1].bstr[0])\r\n self.assertEqual(b'\\x01', self.decoded.suit_manifest.suit_common.suit_components[0][2].bstr[0])\r\n\r\n\r\nclass Test11(Testn):\r\n def __init__(self, *args, **kwargs):\r\n super(Test11, self).__init__(*args, **kwargs)\r\n self.decode_file(p_test_vectors14[5], p_manifest14, p_cose)\r\n\r\n def test_validate(self):\r\n self.assertEqual(4, len(self.decoded.suit_manifest.SUIT_Unseverable_Members.suit_validate[0].suit_validate.union))\r\n self.assertEqual(15, self.decoded.suit_manifest.SUIT_Unseverable_Members.suit_validate[0].suit_validate.union[1].SUIT_Condition.suit_condition_image_match.SUIT_Rep_Policy)\r\n\r\n\r\nclass Test11Inv(Testn):\r\n def test_invalid_rep_policy(self):\r\n data = bytes.fromhex(p_test_vectors14[5].read_text().replace(\"\\n\", \"\"))\r\n struct = loads(data)\r\n struct2 = loads(struct.value[3]) # manifest\r\n struct3 = loads(struct2[10]) # suit_validate\r\n struct3[3] += 16 # invalid Rep_Policy\r\n struct2[10] = dumps(struct3)\r\n struct.value[3] = dumps(struct2)\r\n data = dumps(struct)\r\n try:\r\n self.decode_string(data, p_manifest14, p_cose)\r\n except cddl_gen.CddlValidationError as e:\r\n return\r\n else:\r\n assert False, \"Should have failed validation\"\r\n\r\n\r\nclass TestCLI(TestCase):\r\n def get_std_args(self, input):\r\n return [\"cddl-gen\", \"--cddl\", p_manifest12, \"--default-max-qty\", \"16\", \"convert\", \"--input\", input, \"-t\", \"SUIT_Envelope_Tagged\"]\r\n\r\n def do_testn(self, n):\r\n call0 = Popen(self.get_std_args(p_test_vectors12[n]) + [\"--output\", \"-\", \"--output-as\", \"cbor\"], stdout=PIPE)\r\n stdout0, _ = call0.communicate()\r\n self.assertEqual(0, call0.returncode)\r\n\r\n call1 = Popen(self.get_std_args(\"-\") + [\"--input-as\", \"cbor\", \"--output\", \"-\", \"--output-as\", \"json\"], stdin=PIPE, stdout=PIPE)\r\n stdout1, _ = call1.communicate(input=stdout0)\r\n self.assertEqual(0, call1.returncode)\r\n\r\n call2 = Popen(self.get_std_args(\"-\") + [\"--input-as\", \"json\", \"--output\", \"-\", \"--output-as\", \"yaml\"], stdin=PIPE, stdout=PIPE)\r\n stdout2, _ = call2.communicate(input=stdout1)\r\n self.assertEqual(0, call2.returncode)\r\n\r\n call3 = Popen(self.get_std_args(\"-\") + [\"--input-as\", \"yaml\", \"--output\", \"-\", \"--output-as\", \"cbor\"], stdin=PIPE, stdout=PIPE)\r\n stdout3, _ = call3.communicate(input=stdout2)\r\n self.assertEqual(0, call3.returncode)\r\n\r\n self.assertEqual(stdout0, stdout3)\r\n\r\n call4 = Popen(self.get_std_args(\"-\") + [\"--input-as\", \"cbor\", \"--output\", \"-\", \"--output-as\", \"cborhex\"], stdin=PIPE, stdout=PIPE)\r\n stdout4, _ = call4.communicate(input=stdout3)\r\n self.assertEqual(0, call4.returncode)\r\n\r\n call5 = Popen(self.get_std_args(\"-\") + [\"--input-as\", \"cborhex\", \"--output\", \"-\", \"--output-as\", \"json\"], stdin=PIPE, stdout=PIPE)\r\n stdout5, _ = call5.communicate(input=stdout4)\r\n self.assertEqual(0, call5.returncode)\r\n\r\n self.assertEqual(stdout1, stdout5)\r\n\r\n self.maxDiff = None\r\n\r\n with open(p_test_vectors12[n], 'r') as f:\r\n self.assertEqual(sub(r\"\\W+\", \"\", f.read()), sub(r\"\\W+\", \"\", stdout4.decode(\"utf-8\")))\r\n\r\n def test_0(self):\r\n self.do_testn(0)\r\n\r\n def test_1(self):\r\n self.do_testn(1)\r\n\r\n def test_2(self):\r\n self.do_testn(2)\r\n\r\n def test_3(self):\r\n self.do_testn(3)\r\n\r\n def test_4(self):\r\n self.do_testn(4)\r\n\r\n def test_5(self):\r\n self.do_testn(5)\r\n\r\n\r\nclass TestOptional(TestCase):\r\n def test_0(self):\r\n with open(p_optional, 'r') as f:\r\n cddl_res = cddl_gen.DataTranslator.from_cddl(f.read(), 16)\r\n cddl = cddl_res.my_types['cfg']\r\n test_yaml = \"\"\"\r\n mem_config:\r\n - 0\r\n - 5\"\"\"\r\n decoded = cddl.decode_str_yaml(test_yaml)\r\n self.assertEqual(decoded.mem_config[0].READ.union_choice, \"uint0\")\r\n self.assertEqual(decoded.mem_config[0].N, [5])\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"stevenatom/nrf_v1.9.1","sub_path":"modules/lib/cddl-gen/tests/scripts/run_tests.py","file_name":"run_tests.py","file_ext":"py","file_size_in_byte":26266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"34922497902","text":"import torch\nimport random\nimport numpy as np\nimport time\nfrom collections import deque\nfrom deep_q_learning_model import Linear_QNet, QTrainer\nimport agent_interpreter\nfrom matplotlib import pyplot as plt\n\nMAX_MEMORY = 100_000\nBATCH_SIZE = 1000\nLR = 0.0012\n\nclass Agent:\n def __init__(self):\n self.n_game = 0\n self.epsilon = 0.1 # Randomness\n self.gamma = 0.9 # discount rate\n self.memory = deque(maxlen=MAX_MEMORY) # popleft()\n self.model = Linear_QNet(11,256,3)\n self.model.to('cuda')\n self.trainer = QTrainer(self.model,lr=LR,gamma=self.gamma)\n\n def remember(self, state, action, reward, next_state, done):\n self.memory.append((state, action, reward, next_state, done)) # popleft if MAX_MEMORY is reached\n \n def train_long_memory(self):\n if len(self.memory) > BATCH_SIZE:\n mini_sample = random.sample(self.memory, BATCH_SIZE) # list of tuples\n else:\n mini_sample = self.memory\n states, actions, rewards, next_states, dones = zip(*mini_sample)\n self.trainer.train_step(states, actions, rewards, next_states, dones)\n \n def train_short_memory(self, state, action, reward, next_state, done):\n self.trainer.train_step(state, action, reward, next_state, done)\n \n def get_action(self, state):\n self.epsilon = 80 - self.n_game\n final_move = [0,0,0]\n if(random.randint(0,200) 0 then game will be rendered\n run = []\n record_run = []\n while agent.n_game < 200 and record < 42:\n # Save state \n run.append(game.env.get_state())\n # Get Old state\n state_old = game.get_state()\n # get move\n final_move = agent.get_action(state_old)\n # perform move and get new state\n reward, done, score = game.step(final_move)\n game.render() # anythin else as 'human' will not render the game\n state_new = game.get_state()\n # train short memory\n agent.train_short_memory(state_old,final_move,reward,state_new,done)\n\n #remember\n agent.remember(state_old,final_move,reward,state_new,done)\n\n if done:\n # save last state\n run.append(game.env.get_state())\n # Train long memory,plot result\n game.reset()\n agent.n_game += 1\n agent.train_long_memory()\n if(score > record): # new High score \n record = score\n record_run.clear()\n record_run = run.copy()\n run.clear()\n run = []\n else:\n run.clear()\n run = []\n print('Game:',agent.n_game,'Score:',score,'Record:',record)\n \n plot_scores.append(score)\n total_score+=score\n mean_score = total_score / agent.n_game\n plot_mean_scores.append(mean_score)\n \n agent.model.save()\n save_record_run(record_run, record)\n \ndef test_model():\n agent = Agent()\n agent.model.load_state_dict(torch.load('C:\\CODING\\PROJECTS\\SNAKE_AI\\models\\dql_model.pth'))\n game = agent_interpreter.dq_agent_interpreter(sleep=0.1)\n while True:\n # Get Old state\n state_old = game.get_state()\n\n # get move\n final_move = agent.get_action(state_old)\n # perform move and get new state\n reward, done, score = game.step(final_move)\n game.render() # anythin else as 'human' will not render the game\n state_new = game.get_state()\n\n if done:\n # Train long memory,plot result\n game.reset()\n agent.n_game += 1\n print('Game:',agent.n_game,'Score:',score)\n if(score > 40):\n break\n\n\n\nif(__name__==\"__main__\"):\n \n #train()\n #test_model()\n play_record_run('record_run_46')\n #pass\n \n","repo_name":"bensalo/SNAKE_AI","sub_path":"src/dense_nn/deep_q_learning_agent.py","file_name":"deep_q_learning_agent.py","file_ext":"py","file_size_in_byte":4842,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"21320190102","text":"'''\r\n1) Observe o trecho de código abaixo:\r\nint INDICE = 13, SOMA = 0, K = 0;\r\nenquanto K < INDICE faça\r\n\r\n{\r\nK = K + 1;\r\nSOMA = SOMA + K;\r\n}\r\nimprimir(SOMA);\r\nAo final do processamento, qual será o valor da variável SOMA?\r\n'''\r\n\r\nINDICE = 13\r\nSOMA = 0\r\nK = 0\r\n\r\nwhile K < INDICE:\r\n K = K + 1\r\n SOMA = SOMA + K\r\n\r\nprint(SOMA)\r\n\r\n'''\r\n2- Dado a sequência de Fibonacci, onde se inicia por 0 e 1 e o próximo valor sempre será a soma dos 2 valores anteriores (exemplo: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...), escreva um programa na linguagem que desejar onde, informado um número, ele calcule a sequência de Fibonacci e retorne uma mensagem avisando se o número informado pertence ou não a sequência.\r\n\r\nIMPORTANTE:\r\nEsse número pode ser informado através de qualquer entrada de sua preferência ou pode ser previamente definido no código;\r\n'''\r\n# Função para verificar se um número pertence à sequência de Fibonacci\r\n\r\n\r\ndef pertence_fibonacci(num):\r\n # Inicializa os dois primeiros números da sequência\r\n fib1, fib2 = 0, 1\r\n\r\n # Itera pela sequência de Fibonacci até o número informado ou até ultrapassá-lo\r\n while fib2 <= num:\r\n if fib2 == num:\r\n return True # Número pertence à sequência de Fibonacci\r\n fib1, fib2 = fib2, fib1 + fib2 # Atualiza os valores da sequência\r\n return False # Número não pertence à sequência de Fibonacci\r\n\r\n\r\n# Recebe o número informado pelo usuário\r\nnum = int(input(\"Informe um número: \"))\r\n\r\n# Verifica se o número pertence à sequência de Fibonacci e exibe a mensagem correspondente\r\nif pertence_fibonacci(num):\r\n print(f\"{num} pertence à sequência de Fibonacci.\")\r\nelse:\r\n print(f\"{num} não pertence à sequência de Fibonacci.\")\r\n\r\n'''\r\n3- Descubra a lógica e complete o próximo elemento:\r\na) 1, 3, 5, 7, ___\r\nb) 2, 4, 8, 16, 32, 64, ____\r\nc) 0, 1, 4, 9, 16, 25, 36, ____\r\nd) 4, 16, 36, 64, ____\r\ne) 1, 1, 2, 3, 5, 8, ____\r\nf) 2,10, 12, 16, 17, 18, 19, ____\r\n'''\r\n'''\r\na) A lógica é adicionar 2 ao número anterior. O próximo elemento é 9.\r\nb) A lógica é multiplicar por 2 o número anterior. O próximo elemento é 128.\r\nc) A lógica é elevar ao quadrado o índice do número na sequência. O próximo elemento é 49.\r\nd) A lógica é elevar ao quadrado o índice do número na sequência e somar 12. O próximo elemento é 100.\r\ne) A lógica é somar os dois números anteriores para obter o próximo número. O próximo elemento é 13.\r\nf) A lógica é somar 2 ao primeiro número, 2 ao segundo, 4 ao terceiro, 1 ao quarto, 1 ao quinto e 1 ao sexto. O próximo elemento é 20.\r\n'''\r\n\r\n'''A'''\r\nfor i in range(1, 6):\r\n print(2*i - 1)\r\n'''B'''\r\nx = 2\r\nfor i in range(1, 8):\r\n print(x)\r\n x *= 2\r\n'''C'''\r\nfor i in range(8):\r\n print(i**2)\r\n'''D'''\r\nfor i in range(1, 6):\r\n print((2*i)**2)\r\n'''E'''\r\na, b = 1, 1\r\nfor i in range(7):\r\n print(a)\r\n a, b = b, a+b\r\n'''F'''\r\nnumeros = [2, 10, 12, 16, 17, 18, 19]\r\nproximo = numeros[-1] + 1\r\nnumeros.append(proximo)\r\nprint(numeros)\r\n\r\n'''\r\n4- Dois veículos (um carro e um caminhão) saem respectivamente de cidades opostas pela mesma rodovia. O carro de Ribeirão Preto em direção a Franca, a uma velocidade constante de 110 km/h e o caminhão de Franca em direção a Ribeirão Preto a uma velocidade constante de 80 km/h. Quando eles se cruzarem na rodovia, qual estará mais próximo a cidade de Ribeirão Preto?\r\nIMPORTANTE:\r\n\r\na) Considerar a distância de 100km entre a cidade de Ribeirão Preto <-> Franca.\r\n\r\nb) Considerar 2 pedágios como obstáculo e que o caminhão leva 5 minutos a mais para passar em cada um deles e o carro possui tag de pedágio (Sem Parar)\r\n\r\nc) Explique como chegou no resultado.\r\n\r\n'''\r\n# Distância entre Ribeirão Preto e Franca (km)\r\ndistancia = 100\r\n\r\n# Velocidade do carro (km/h)\r\nvelocidade_carro = 110\r\n\r\n# Velocidade do caminhão (km/h)\r\nvelocidade_caminhao = 80\r\n\r\n# Tempo extra do caminhão em cada pedágio (minutos)\r\ntempo_extra_caminhao = 5\r\n\r\n# Tempo total extra do caminhão (horas)\r\ntempo_total_extra_caminhao = tempo_extra_caminhao / 60 * 2\r\n\r\n# Tempo que o carro leva para percorrer a distância entre as cidades (horas)\r\ntempo_carro = distancia / velocidade_carro\r\n\r\n# Tempo que o caminhão leva para percorrer a distância entre as cidades (horas)\r\ntempo_caminhao = distancia / velocidade_caminhao + tempo_total_extra_caminhao\r\n\r\n# Verifica qual veículo está mais próximo de Ribeirão Preto\r\nif tempo_carro < tempo_caminhao:\r\n print(\"O carro está mais próximo de Ribeirão Preto\")\r\nelse:\r\n print(\"O caminhão está mais próximo de Ribeirão Preto\")\r\n\r\n'''\r\n5) Escreva um programa que inverta os caracteres de um string.\r\nIMPORTANTE:\r\n\r\na) Essa string pode ser informada através de qualquer entrada de sua preferência ou pode ser previamente definida no código;\r\nb) Evite usar funções prontas, como, por exemplo, reverse;\r\n\r\n'''\r\n# Exemplo de string\r\ns = \"hello world\"\r\n\r\n# Inicializa a string invertida\r\ns_invertida = \"\"\r\n\r\n# Percorre a string de trás para frente e adiciona cada caractere na string invertida\r\nfor i in range(len(s)-1, -1, -1):\r\n s_invertida += s[i]\r\n\r\n# Imprime a string invertida\r\nprint(s_invertida)\r\n\r\n'''OU'''\r\nstring = \"hello world\"\r\nstring_invertida = string[::-1]\r\nprint(string_invertida)\r\n","repo_name":"FialaMoises/testjob","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5291,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"13528710014","text":"\n# 함수\n # 1. isqueuefull() 큐가 다 찼는지 확인 함수\n # 2. isqueueempty() 큐가 다 비어있는지 확인 함수\n # 3. enqueue() 큐에 데이터 삽입 함수\n # 4. dequeue() 큐에 데이터 삭제 함수\n # 5. peek() front 위치에 데이터 확인 함수\n\n#1.\ndef isqueuefull() : # 큐가 다 찾는 확인 함수\n global SIZE , queue , front , rear # 전역변수\n if rear != SIZE-1 : # 다 찬 경우가 아니면\n return False\n elif rear == SIZE-1 and front == -1 :\n return True # 다 찬 경우\n else:\n for i in range( front+1 , SIZE ): # 남아있는 데이터를 한칸씩 이동\n queue[i-1] = queue[ i ]\n queue[i] = None\n front -= 1 # 데이터 삭제시\n rear -= 1 # 데이터 삭제시\n return False\n#2.\ndef isqueueempty() : # 큐가 다 비어있는지 확인 함수\n global SIZE , queue , front , rear\n if front == rear : # front rear 같을경우\n return True\n else:\n return False\n#3.\ndef enqueue(data) : # 큐에 데이터 추가\n global SIZE, queue, front, rear\n if isqueuefull() :\n print(\" 큐가 다 찼습니다. \")\n return\n rear += 1 # rear 1 증가\n queue[rear] = data # rear 위치에 값넣기\n#4.\ndef dequeue() : # 큐에 데이터 삭제\n global SIZE, queue, front, rear\n if isqueueempty() :\n print(\"큐가 비어있습니다\")\n return None\n front += 1 # front 1 증가\n data = queue[front]\n queue[front] = None # front 위치에 데이터 삭제\n return data\n#5.\ndef peek() : # front+1 위치의 데이터를 확인 하는 함수\n global SIZE, queue, front, rear\n if isqueueempty() :\n print(\"큐가 비어 있습니다 \")\n return None\n return queue[front+1]\n\n#전연변수\nSIZE = int( input(\" 큐의 크기를 입력 : \"))\nqueue =[ None for _ in range(SIZE) ]\nfront = -1 # 시작위치 의 초기값\nrear = -1 #\n\n#메뉴\nselect = input(\"삽입[I] / 추출[E] / 확인[V] / 종료[X] 중 하나 선택 : \")\n\nwhile select !=\"x\" and select !=\"X\" :\n if select ==\"I\" or select == \"i\" :\n data = input(\" 입력할 데이터 : \")\n enqueue(data)\n print( \" 큐 상태 : \",queue )\n elif select == \"E\" or select == \"e\":\n data = dequeue()\n print(\" 추출된 데이터 : \", data)\n print(\" 큐 상태 : \", queue)\n elif select == \"V\" or select == \"v\":\n data = peek()\n print(\" 확인된 데이터 : \", data)\n print(\" 큐 상태 : \", queue)\n else:\n print(\"알수없는 행동입니다\")\n select = input(\"삽입[I] / 추출[E] / 확인[V] / 종료[X] 중 하나 선택 : \")\n\nprint(\" 큐 프로그램 종료 \")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"itdanja/python0706","sub_path":"Day17/day17_queue.py","file_name":"day17_queue.py","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"42494078666","text":"from cmu_112_graphics import *\nimport random, string, math, time\nfrom dataclasses import make_dataclass\nimport decimal\nfrom riskMap import *\nfrom riskAI import *\nfrom riskInstructions import *\nfrom PIL import ImageTk, Image\n\ndef gameMode_mousePressed(app, event):\n\n for continent in app.territories:\n for territory in app.territories[continent]:\n distance = math.sqrt((event.x - territory.x)**2 + (event.y - territory.y)**2)\n \n #checks if territory has been selected\n if distance <= app.radius2:\n \n if territory in app.player.bordering or territory in app.player.territories:\n #checks what mode the game is in\n if app.deployMode:\n if territory in app.player.territories:\n app.eventText = \"\"\n app.current = (territory.continent, app.territories[territory.continent].index(territory))\n app.player.formDeploy(app, territory)\n else:\n app.eventText = f\"{continent} {territory.number} not in your territories!\"\n\n elif app.attackMode:\n if app.player.attack == None and territory not in app.player.territories:\n app.eventText = f\"{continent} {territory.number} not in your territories!\"\n else:\n app.eventText = \"\"\n app.current = (continent, territory.number - 1)\n app.neighbors = findNeighbors(app, territory.continent, territory.number - 1)\n app.player.formAttack(app, territory)\n\n elif app.moveMode:\n if app.player.move == None and territory not in app.player.territories:\n app.eventText = f\"{continent} {territory.number} not in your territories!\"\n else:\n app.eventText = \"\"\n app.current = (continent, territory.number - 1)\n app.neighbors = findNeighbors(app, territory.continent, territory.number - 1)\n app.player.formMove(app, territory)\n \n else:\n if territory.owner != None:\n app.eventText = f\"{continent} {territory.number} ({territory.owner.name}): {territory.troops} troops\"\n else:\n app.eventText = f\"{continent} {territory.number} (unclaimed): {territory.troops} troops\"\n \n else:\n if app.deployMode:\n app.eventText = f\"{continent} {territory.number} not in your territories!\"\n elif app.attackMode or app.moveMode:\n app.eventText = f\"{continent} {territory.number} not in bordering!\"\n else:\n app.eventText = f\"{continent} {territory.number}\"\n\n#states territory if hovering over it\ndef gameMode_mouseMoved(app, event):\n for continent in app.territories:\n for territory in app.territories[continent]:\n distance = math.sqrt((event.x - territory.x)**2 + (event.y - territory.y)**2)\n \n #checks if territory has been selected\n if distance <= app.radius2:\n app.eventText = f\"{territory.continent} {territory.number}\" \n\ndef gameMode_keyPressed(app, event):\n\n #restarts game\n if event.key == \"r\":\n gameStarted(app)\n\n #activates deploy mode\n if event.key == \"d\":\n app.deployMode = True\n app.attackMode = False\n app.moveMode = False\n\n #activates attack mode\n if event.key == \"a\":\n app.attackMode = True\n app.deployMode = False\n app.moveMode = False\n\n #activates move mode\n if event.key == \"m\":\n app.moveMode = True\n app.deployMode = False\n app.attackMode = False\n \n #starts the playing of the moves\n if event.key == \"p\":\n app.moveMode = False\n app.deployMode = False\n app.attackMode = False\n\n app.startTurn = True\n app.showMoves = True\n\n #does a step\n if event.key == \"Enter\":\n if app.startTurn:\n doStep(app)\n checkWin(app)\n \n #forfeit\n if event.key == \"f\":\n gameOver(app, \"loss\")\n \n #autowin\n if event.key == \"w\":\n gameOver(app, \"win\")\n \n #get to instructions page\n if event.key == \"i\":\n app.mapBackground = app.mapBackground.resize((app.width, app.height))\n app.mode = \"instructionsMode\"\n\n #sets it to \"standard mode\" aka just checking the territories\n if event.key == \"s\":\n app.moveMode = False\n app.deployMode = False\n app.attackMode = False\n \n if event.key == \"h\":\n app.cheat = not app.cheat\n \n if event.key == \"l\":\n app.letsgo = not app.letsgo\n \n app.neighbors = set()\n app.current = tuple()\n\ndef doStep(app):\n\n #checks to see if this is the first move or end\n if app.step == 0:\n #if this is the first move\n if app.showMoves:\n #form moves of the ais and deploys troops\n for i in range(app.ai1.troops):\n app.ai1.formDeploy(app)\n for j in range(app.ai2.troops):\n app.ai2.formDeploy(app)\n \n app.ai1.formMoves(app)\n app.ai2.formMoves(app)\n \n app.player.deployTroops(app)\n app.ai1.deployTroops(app)\n app.ai2.deployTroops(app)\n\n app.deployDone = True\n\n app.step += 1\n\n #this is for the end and to reset for the next turn\n else:\n app.moveMode = False\n app.deployMode = False\n app.attackMode = False\n\n app.player.findTroops(app)\n app.ai1.findTroops(app)\n app.ai2.findTroops(app)\n \n app.player.formDeployOrdersFramework(app)\n app.ai1.formDeployOrdersFramework(app)\n app.ai2.formDeployOrdersFramework(app)\n \n app.showMoves = False\n app.deployDone = False\n app.startTurn = False\n \n #if its not first or last, it just does one of the steps\n else:\n performAttacksAndMoves(app, app.player.orders, app.ai1.orders, app.ai2.orders, app.step - 1)\n\n\n#do the steps\ndef performAttacksAndMoves(app, playerMoves, ai1Moves, ai2Moves, step):\n combined = sorted([playerMoves, ai1Moves, ai2Moves], key = len)\n\n app.player.done = True\n app.ai1.done = True\n app.ai2.done = True\n \n if len(combined[0]) != 0:\n doAttackMove(app, combined[0][step])\n if combined[0][step][0].owner == combined[0][step][3]:\n combined[0][step][3].gameLogMoves.insert(0, combined[0][step])\n combined[0][step][3].done = False\n combined[0].pop(step)\n \n if len(combined[1]) != 0:\n doAttackMove(app, combined[1][step])\n if combined[1][step][0].owner == combined[1][step][3]:\n combined[1][step][3].gameLogMoves.insert(0, combined[1][step])\n combined[1][step][3].done = False\n combined[1].pop(step)\n \n if len(combined[2]) != 0:\n doAttackMove(app, combined[2][step])\n if combined[2][step][0].owner == combined[2][step][3]:\n combined[2][step][3].gameLogMoves.insert(0, combined[2][step])\n combined[2][step][3].done = False\n combined[2].pop(step)\n\n #checks if it is over, and puts out the dashes in the game log to signify end\n elif step == len(combined[2]):\n app.step = 0\n app.player.gameLogMoves.insert(0, \"----------------------------\")\n app.ai1.gameLogMoves.insert(0, \"----------------------------\")\n app.ai2.gameLogMoves.insert(0, \"----------------------------\")\n\n app.player.formDeployOrdersFramework(app)\n app.ai1.formDeployOrdersFramework(app)\n app.ai2.formDeployOrdersFramework(app)\n\n app.eventText = \"\"\n \n app.showMoves = False\n\n\n#determins if it is attack or move\ndef doAttackMove(app, instructions):\n if instructions[1] == \"attack\":\n attack(app, instructions[3], instructions[0], instructions[2])\n\n else:\n move(app, instructions[3], instructions[0], instructions[2])\n\n\ndef attack(app, player, predator, prey):\n\n if predator.owner == player and prey.owner != player:\n #checks to see if attack takes over that territory\n if predator.troops >= prey.troops * 2:\n predator.troops = predator.troops - (prey.troops // 2)\n prey.troops = 0\n\n #checks to see if attack is a loss for the attacker\n elif predator.troops < prey.troops:\n prey.troops = prey.troops - (predator.troops // 2)\n predator.troops = 0\n\n #checks to see if attack is neither win nor loss, but both lose troops\n else:\n temp = prey.troops\n prey.troops = prey.troops - (predator.troops // 2)\n predator.troops = predator.troops - (temp // 2)\n\n #if it is a win, gives the new territory to attacker\n if prey.troops == 0:\n if prey.owner != None:\n prey.owner.territories.remove(prey)\n prey.troops = predator.troops\n predator.troops = 0\n player.territories.add(prey)\n prey.owner = player\n if prey.owner == app.player:\n app.eventText = f\"You took {prey.continent} {app.territories[prey.continent].index(prey) + 1}!\"\n \n #changes event text if attack occurs but no one wins\n elif prey.troops != 0 and prey.owner == app.player:\n app.eventText = f\"You attacked {prey.continent} {app.territories[prey.continent].index(prey) + 1}!\"\n\n #if the territory that is being attacked is now owned by the player, changes the attack to a move\n elif predator.owner == player and prey.owner == player:\n move(app, player, predator, prey)\n\n app.neighbors = set()\n app.current = tuple()\n player.bordering = set()\n app.player.findBorderingTerritories(app)\n\n\ndef move(app, player, predator, prey):\n\n #makes sure that the move occurs between two territoires owned by same player\n if predator.owner == player and prey.owner == player:\n temp = predator.troops\n prey.troops = predator.troops + prey.troops\n predator.troops = 0\n\n app.neighbors = set()\n app.current = tuple()\n player.bordering = set()\n app.player.findBorderingTerritories(app)\n #only prints eventText if it is the app.player\n if prey.owner == app.player:\n app.eventText = f\"You moved {temp} troops to {prey.continent} {app.territories[prey.continent].index(prey) + 1}!\"\n \n #changes move to attack if the prey is no longer owned by same player\n elif predator.owner == player and prey.owner != player:\n attack(app, player, predator, prey)\n\n#checks for win or loss (from player's perspective)\ndef checkWin(app):\n if len(app.player.territories) == 42:\n gameOver(app, \"win\")\n if len(app.ai1.territories) == 42 or len(app.ai2.territories) == 42:\n gameOver(app, \"loss\")\n\n#helps draw the win or loss\ndef gameOver(app, WoL):\n if WoL == \"win\":\n app.win = True\n else:\n app.loss = True\n \n\n#hard coded a dictionary of all territories and their neighbors\ndef findNeighbors(app, continent, number):\n neighbors = {\n (\"N. America\", 0): {(\"N. America\", 1), (\"N. America\", 5), (\"Asia\", 5)},\n (\"N. America\", 1): {(\"N. America\", 0), (\"N. America\", 5), (\"N. America\", 6), (\"N. America\", 8)},\n (\"N. America\", 2): {(\"N. America\", 3), (\"N. America\", 8), (\"S. America\", 3)},\n (\"N. America\", 3): {(\"N. America\", 2), (\"N. America\", 6), (\"N. America\", 7), (\"N. America\", 8)},\n (\"N. America\", 4): {(\"N. America\", 5), (\"N. America\", 6), (\"N. America\", 7), (\"Europe\", 1)},\n (\"N. America\", 5): {(\"N. America\", 0), (\"N. America\", 1), (\"N. America\", 4), (\"N. America\", 6)},\n (\"N. America\", 6): {(\"N. America\", 1), (\"N. America\", 3), (\"N. America\", 4), (\"N. America\", 5), (\"N. America\", 7), (\"N. America\", 8)},\n (\"N. America\", 7): {(\"N. America\", 3), (\"N. America\", 4), (\"N. America\", 6)},\n (\"N. America\", 8): {(\"N. America\", 1), (\"N. America\", 2), (\"N. America\", 3), (\"N. America\", 6)},\n (\"S. America\", 0): {(\"S. America\", 1), (\"S. America\", 2)},\n (\"S. America\", 1): {(\"S. America\", 0), (\"S. America\", 2), (\"S. America\", 3), (\"Africa\", 4)},\n (\"S. America\", 2): {(\"S. America\", 0), (\"S. America\", 1), (\"S. America\", 2), (\"S. America\", 3)},\n (\"S. America\", 3): {(\"N. America\", 2), (\"S. America\", 1), (\"S. America\", 2)},\n (\"Europe\", 0): {(\"Europe\", 1), (\"Europe\", 2), (\"Europe\", 3), (\"Europe\", 6)},\n (\"Europe\", 1): {(\"N. America\", 4), (\"Europe\", 0), (\"Europe\", 3)},\n (\"Europe\", 2): {(\"Europe\", 0), (\"Europe\", 3), (\"Europe\", 4), (\"Europe\", 5), (\"Europe\", 6)},\n (\"Europe\", 3): {(\"Europe\", 0), (\"Europe\", 1), (\"Europe\", 2), (\"Europe\", 5)},\n (\"Europe\", 4): {(\"Europe\", 2), (\"Europe\", 5), (\"Europe\", 6), (\"Africa\", 2), (\"Africa\", 4), (\"Asia\", 6)},\n (\"Europe\", 5): {(\"Europe\", 2), (\"Europe\", 3), (\"Europe\", 4), (\"Asia\", 0), (\"Asia\", 6), (\"Asia\", 10)},\n (\"Europe\", 6): {(\"Europe\", 0), (\"Europe\", 2), (\"Europe\", 4), (\"Africa\", 4)},\n (\"Africa\", 0): {(\"Africa\", 1), (\"Africa\", 4), (\"Africa\", 5)},\n (\"Africa\", 1): {(\"Africa\", 0), (\"Africa\", 2), (\"Africa\", 3), (\"Africa\", 4), (\"Africa\", 5), (\"Asia\", 6)},\n (\"Africa\", 2): {(\"Europe\", 4), (\"Africa\", 1), (\"Africa\", 4), (\"Asia\", 6)},\n (\"Africa\", 3): {(\"Africa\", 1), (\"Africa\", 5)},\n (\"Africa\", 4): {(\"S. America\", 1), (\"Europe\", 4), (\"Europe\", 6), (\"Africa\", 0), (\"Africa\", 1), (\"Africa\", 2)},\n (\"Africa\", 5): {(\"Africa\", 0), (\"Africa\", 1), (\"Africa\", 3)},\n (\"Asia\", 0): {(\"Europe\", 5), (\"Asia\", 1), (\"Asia\", 2), (\"Asia\", 6), (\"Asia\", 10)},\n (\"Asia\", 1): {(\"Asia\", 0), (\"Asia\", 2), (\"Asia\", 7), (\"Asia\", 8), (\"Asia\", 9), (\"Asia\", 10)},\n (\"Asia\", 2): {(\"Asia\", 0), (\"Asia\", 1), (\"Asia\", 6), (\"Asia\", 8)},\n (\"Asia\", 3): {(\"Asia\", 5), (\"Asia\", 7), (\"Asia\", 9), (\"Asia\", 11)},\n (\"Asia\", 4): {(\"Asia\", 5), (\"Asia\", 7)},\n (\"Asia\", 5): {(\"N. America\", 0), (\"Asia\", 3), (\"Asia\", 4), (\"Asia\", 7), (\"Asia\", 11)},\n (\"Asia\", 6): {(\"Europe\", 4), (\"Europe\", 5), (\"Africa\", 1), (\"Africa\", 2), (\"Asia\", 0), (\"Asia\", 2)},\n (\"Asia\", 7): {(\"Asia\", 1), (\"Asia\", 3), (\"Asia\", 4), (\"Asia\", 5), (\"Asia\", 9)},\n (\"Asia\", 8): {(\"Asia\", 1), (\"Asia\", 2), (\"Australia\", 1)},\n (\"Asia\", 9): {(\"Asia\", 1), (\"Asia\", 3), (\"Asia\", 7), (\"Asia\", 10), (\"Asia\", 11)},\n (\"Asia\", 10): {(\"Europe\", 5), (\"Asia\", 0), (\"Asia\", 1), (\"Asia\", 9)},\n (\"Asia\", 11): {(\"Asia\", 3), (\"Asia\", 5), (\"Asia\", 9)},\n (\"Australia\", 0): {(\"Australia\", 2), (\"Australia\", 3)},\n (\"Australia\", 1): {(\"Asia\", 8), (\"Australia\", 2), (\"Australia\", 3)},\n (\"Australia\", 2): {(\"Australia\", 0), (\"Australia\", 1), (\"Australia\", 3)},\n (\"Australia\", 3): {(\"Australia\", 0), (\"Australia\", 1), (\"Australia\", 2)}\n }\n return neighbors[(continent, number)]\n \n\n","repo_name":"stzphen/Uncertainty","sub_path":"riskGame.py","file_name":"riskGame.py","file_ext":"py","file_size_in_byte":15755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"41452806385","text":"from flask import Blueprint, render_template, request, redirect\nfrom .extensions import db\nfrom .models import Link\n\nshortener = Blueprint('shortener',__name__)\n\n@shortener.route('/tier.app/')\ndef index():\n return render_template(\"index.html\")\n\n@shortener.route('/tier.app/create_link', methods=['POST'])\ndef create_link():\n if(request.form['original_url'] ):\n original_url = request.form['original_url'] \n link = Link(original_url=original_url) \n print(\"Link1 is\", link) \n db.session.add(link)\n db.session.commit() \n return render_template(\"link_success.html\", new_url=link.short_url, original_url=link.original_url) \n\n@shortener.route('/')\ndef redirect_to_url(short_url):\n if(short_url):\n link = Link.query.filter_by(short_url=short_url).first_or_404()\n link.views = link.views + 1\n db.session.commit()\n return redirect(link.original_url) \n\n@shortener.route('/tier.app/show', methods=['GET','POST'])\ndef show():\n if(request.method=='POST'): \n short_url = request.form['short_url'] \n link = Link.query.filter_by(short_url=short_url).first_or_404()\n return render_template(\"show_both_link.html\", short_url=link.short_url, original_url=link.original_url) \n return render_template(\"show_link.html\") \n\n@shortener.route('/tier.app/views')\ndef analytics():\n links = Link.query.all()\n return render_template('analytics.html', links=links)\n\n@shortener.errorhandler(404)\ndef page_not_found(e):\n return ('

Page Not Found 404

', 404)\n","repo_name":"komaldesaikd/kd_url_shortener","sub_path":"url_shortener/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"74012661513","text":"from application import app, db\nfrom flask import render_template, request, redirect\nfrom application.forms import AddEmployee, AddOrder, UpdateEmployee, UpdateOrder\nfrom application.models import Employee, Order\n\n@app.route('/')\ndef home():\n employees = Employee.query.all()\n return render_template('homepage.html', records = employees)\n\n@app.route(\"/filterRecords\",methods=[\"POST\"])\ndef filterRecords():\n if request.form[\"role\"]==\"all\":\n return redirect(\"/\")\n else:\n data = Employee.query.filter_by(role=request.form[\"role\"]).all()\n return render_template(\"homepage.html\",records=data)\n\n@app.route('/editEmployee/', methods=['GET', 'POST'])\ndef editEmployee(employee_id):\n form = UpdateEmployee()\n employees = Employee.query.filter_by(employee_id=employee_id).first()\n if request.method == \"POST\":\n employees.name = form.name.data\n employees.role = form.role.data\n employees.email = form.email.data\n employees.mobile_num = form.mobile_num.data\n db.session.commit()\n return redirect('/')\n return render_template('edit_employee_form.html', form=form)\n\n@app.route(\"/saveEmployee\",methods=[\"GET\",\"POST\"])\ndef saveEmployee():\n form = AddEmployee()\n if request.method == 'POST':\n name=form.name.data\n role=form.role.data\n email=form.email.data\n mobile_num=form.mobile_num.data\n new_employee = Employee(name=name, role=role, email=email, mobile_num=mobile_num)\n db.session.add(new_employee)\n db.session.commit()\n return redirect(\"/\")\n return render_template(\"input_employee_form.html\", form=form)\n\n@app.route(\"/employeeInformation/\")\ndef employeeInformation(employee_id):\n\tdata = Employee.query.filter_by(employee_id=employee_id).first()\n\treturn render_template(\"employee_information.html\",record=data)\n\n@app.route(\"/deleteEmployee/\")\ndef deleteEmployee(employee_id):\n employee = Employee.query.filter_by(employee_id=employee_id).first()\n db.session.delete(employee)\n db.session.commit()\n return redirect(\"/\")\n\n@app.route(\"/viewOrders\")\ndef viewOrders():\n orders = Order.query.all()\n #Employee.query.all()\n employee_data = Employee.query.with_entities(Employee.employee_id)\n employee_string=[]\n for i in employee_data:\n employee_string.append(\"\".join(filter(str.isdigit, str(i))))\n return render_template('orders.html', employee_records=employee_string, order_records=orders)\n\n@app.route(\"/filterOrders\",methods=[\"POST\"])\ndef filterOrders():\n if request.form[\"employee_id\"]==\"all\":\n print(\"i run\")\n return redirect(\"/viewOrders\")\n else:\n employee_data = Employee.query.with_entities(Employee.employee_id)\n employee_string=[]\n for i in employee_data:\n employee_string.append(\"\".join(filter(str.isdigit, str(i)))) \n order_data = Order.query.filter_by(employee_id=request.form[\"employee_id\"]).all()\n return render_template(\"orders.html\", employee_records=employee_string, order_records=order_data)\n\n@app.route('/editOrder/', methods=['GET', 'POST'])\ndef editOrder(order_id):\n form = UpdateOrder()\n orders = Order.query.filter_by(order_id=order_id).first()\n if request.method == \"POST\":\n orders.order_name = form.order_name.data\n orders.cost = form.cost.data\n orders.cust_name = form.cust_name.data\n employee_string = filter(str.isdigit, str(form.employee_id.data))\n orders.employee_id=\"\".join(employee_string)\n db.session.commit()\n return redirect('/viewOrders')\n return render_template('edit_order_form.html', form=form)\n\n@app.route(\"/saveOrder\",methods=[\"GET\",\"POST\"])\ndef saveOrder():\n form = AddOrder()\n if request.method == 'POST':\n order_name=form.order_name.data\n cost=form.cost.data\n cust_name=form.cust_name.data\n employee_string = filter(str.isdigit, str(form.employee_id.data))\n employee_id=\"\".join(employee_string)\n new_order = Order(order_name=order_name, cost=cost, cust_name=cust_name, employee_id=employee_id)\n db.session.add(new_order)\n db.session.commit()\n return redirect(\"/viewOrders\")\n return render_template(\"input_order_form.html\", form=form)\n\n@app.route(\"/orderInformation/\")\ndef orderInformation(order_id):\n\tdata = Order.query.filter_by(order_id=order_id).first()\n\treturn render_template(\"order_information.html\",record=data)\n\n@app.route(\"/deleteOrder/\")\ndef deleteOrder(order_id):\n orders = Order.query.filter_by(order_id=order_id).first()\n db.session.delete(orders)\n db.session.commit()\n return redirect(\"/viewOrders\")","repo_name":"JayRowlands/Project","sub_path":"application/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":4730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"11515516806","text":"## SI 364\n## Winter 2018\n## HW 2 - Part 1\n\n## This homework has 3 parts, all of which should be completed inside this file (and a little bit inside the /templates directory).\n\n## Add view functions and any other necessary code to this Flask application code below so that the routes described in the README exist and render the templates they are supposed to (all templates provided are inside the templates/ directory, where they should stay).\n\n## As part of the homework, you may also need to add templates (new .html files) to the templates directory.\n\n#############################\n##### IMPORT STATEMENTS #####\n#############################\nfrom flask import Flask, request, render_template, url_for, redirect, flash\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField, RadioField, ValidationError\nfrom wtforms.validators import Required\nimport requests\nimport json \n\n#####################\n##### APP SETUP #####\n#####################\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'hardtoguessstring'\n\n####################\n###### FORMS #######\n####################\n\n### Part 1 ###\n\n@app.route('/artistform')\ndef artistForm():\n\treturn render_template('artistform.html')\n\n\n@app.route('/artistinfo')\ndef artistInfo():\n\tif request.method == 'GET':\n\t\tartist = request.args.get('artist')\n\t\tbase_url = \"https://itunes.apple.com/search\"\n\t\tparams_diction = {}\n\t\tparams_diction[\"term\"] = artist\n\t\tparams_diction[\"country\"] = 'US'\n\t\tresp = requests.get(base_url, params = params_diction)\n\t\ttext = resp.text\n\t\tpython_obj = json.loads(text)\n\t\tresult_obj = python_obj[\"results\"]\n\treturn render_template('artist_info.html', objects = result_obj)\n\n\n@app.route('/specific/song/')\ndef specific(artist_name):\n\tif request.method == 'GET':\n\t\tbase_url = \"https://itunes.apple.com/search\"\n\t\tparams_diction = {}\n\t\tparams_diction[\"term\"] = artist_name\n\t\tparams_diction[\"country\"] = 'US'\n\t\tresp = requests.get(base_url, params = params_diction)\n\t\ttext = resp.text\n\t\tpython_obj = json.loads(text)\n\t\tresult_obj = python_obj[\"results\"]\n\n\treturn render_template('specific_artist.html', results = result_obj)\n\n\n@app.route('/artistlinks')\ndef artistLinks():\n\treturn render_template('artist_links.html')\n\n### Part 2 ###\n\nclass AlbumEntryForm(FlaskForm):\n\talbum_name = StringField('Enter the name of an album:', validators = [Required()])\n\trating = RadioField('How much do you like this album? (1 low, 3 high)', choices = [('1', '1'), ('2', '2'), ('3', '3')], validators = [Required()])\n\tsubmit = SubmitField('Submit')\n\n@app.route('/album_entry')\ndef albumEntry():\n\tthis_form = AlbumEntryForm()\n\treturn render_template('album_entry.html', form = this_form)\n\n@app.route('/album_result', methods = ['GET', 'POST'])\ndef albumResults():\n\tthis_form = AlbumEntryForm()\n\tprint(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n\tif this_form.validate_on_submit():\n\t\tprint(\"**********************************\")\n\t\talbum_title = this_form.album_name.data\n\t\tuser_rating = this_form.rating.data\n\t\treturn render_template('album_data.html', album_name = album_title, rating = user_rating)\n\tflash('All fields are required!')\n\treturn redirect(url_for('albumEntry'))\n\n####################\n###### ROUTES ######\n####################\n\n@app.route('/')\ndef hello_world():\n return 'Hello World!'\n\n\n@app.route('/user/')\ndef hello_user(name):\n return '

Hello {0}

'.format(name)\n\n\nif __name__ == '__main__':\n app.run(use_reloader=True,debug=True)\n","repo_name":"danimeye/HW2","sub_path":"SI364W18_HW2.py","file_name":"SI364W18_HW2.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"22397220295","text":"def p006(n):\n \"\"\"\n Finds the difference between the sum of squares of\n the first n natural numbers and the square of the sum.\n \"\"\"\n sumsq = n * (n + 1) * (2 * n + 1) / 6\n sqsum = (n ** 2) * ((n + 1) ** 2) / 4\n return sqsum - sumsq\n\n\nif __name__ == \"__main__\":\n print(p006(100))\n","repo_name":"leonlan/projecteuler","sub_path":"python/p006.py","file_name":"p006.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"74402093832","text":"'''\nYou are given an array prices where prices[i] is the price of a given stock on the ith day.\n\nYou want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.\n\nReturn the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.\n'''\nfrom time import time\nfrom typing import List\n\n\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n max_profit = 0\n l = 0\n for r in range(1, len(prices)):\n if prices[l] > prices[r]:\n # Reset when profit negative\n l = r\n continue\n max_profit = max(max_profit, prices[r] - prices[l])\n\n return max_profit\n\n def reference(self, prices: List[int]) -> int:\n res = 0\n l = 0\n for r in range(1, len(prices)):\n if prices[r] < prices[l]:\n l = r\n res = max(res, prices[r] - prices[l])\n\n return res\n\n def quantify(self, test_cases, runs=50000):\n sol_start = time()\n for i in range(runs):\n for case in test_cases:\n if i == 0:\n print(self.maxProfit(case))\n else:\n self.maxProfit(case)\n print(f'Runtime for our solution: {time() - sol_start}\\n')\n\n ref_start = time()\n for i in range(0, runs):\n for case in test_cases:\n if i == 0:\n print(self.reference(case))\n else:\n self.reference(case)\n print(f'Runtime for reference: {time() - ref_start}')\n\n\nif __name__ == '__main__':\n test = Solution()\n test_cases = [[7, 1, 5, 3, 6, 4], [7, 6, 4, 3, 1]]\n test.quantify(test_cases)\n","repo_name":"stevenxchung/lc-library","sub_path":"Blind 75/03 - Sliding Window/121-best-time-to-buy-and-sell-stock.py","file_name":"121-best-time-to-buy-and-sell-stock.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"6692405803","text":"##########################################################################\n## GetTweets.py v0.1\n##\n## Get/Scrape all the tweets using GetOldTweets3 library as the Tweepy API gives data only for latest 7 days\n## Here we extracted all the tweets for a specific time range and working with the subset\n##\n## Team Name: ANA\n## Team Members : Anandh Varadarajan, Nithish Kolli, Abhiram Karri\n##########################################################################\n\nimport GetOldTweets3 as got\n#tweetCriteria = got.manager.TweetCriteria().setQuerySearch(\"vehicle OR crash OR road OR accident OR hit OR collision OR casualty OR mishap OR ambulance OR traffic\").setSince(\"2014-12-31\").setUntil(\"2015-01-01\").setNear('England').setWithin('46814mi')#.setMaxTweets(10)\ntweetCriteria = got.manager.TweetCriteria().setSince(\"2014-12-30\").setUntil(\"2014-12-31\").setNear('England').setWithin('46814mi')#.setMaxTweets(10)\n\ntweet = got.manager.TweetManager.getTweets(tweetCriteria)\n\nfor tw in tweet:\n print(tw.text)\n#Write all the tweets extracted to the csv file\nwith open('train.csv','a+',encoding=\"utf-8\") as file:\n for tw in tweet:\n print(tw.text)\n file.write(tw.text.replace(',','')+'\\n')\nfile.close()\n","repo_name":"avaradarajan/HotSpot","sub_path":"GetTweets.py","file_name":"GetTweets.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"14210869811","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth import login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import RegForm, LoginForm\nfrom django.contrib.auth.forms import AuthenticationForm, UserCreationForm\nfrom django.contrib import messages\nfrom django.http import HttpResponse\nfrom django.contrib.auth.models import User\nfrom autos.models import Auto, Request\nfrom django.core.mail import send_mail\n# Create your views here.\n\n\ndef signin_view(request, *args, **kwargs):\n form = AuthenticationForm(request, data=request.POST or None)\n #form = LoginForm()\n #if request.method == 'POST':\n #form = LoginForm(request.POST)\n if form.is_valid():\n user_ = form.get_user()\n login(request, user_)\n return redirect(\"/account/profile\")\n else:\n messages.error(request, \"Invalid entries\")\n context = {'form': form, \"btn_label\": \"Login\", \"title\": \"Signin\"}\n return render(request, \"account/signin.html\", context)\n\n\ndef signup_view(request, *args, **kwargs):\n #form = UserCreationForm(request.POST or None)\n form = RegForm()\n if request.method == 'POST':\n form = RegForm(request.POST)\n if form.is_valid():\n user = form.save()\n #user.set_password = form.cleaned_data.get(\"password1\")\n #username = form.cleaned_data.gt(\"username\")\n #login(request, user)\n return redirect(\"/account/signin\")\n else:\n messages.error(request, \"Invalid entries\")\n context = {'form': form, \"btn_label\": \"Register\", \"title\": \"Signup\"}\n return render(request, \"account/signup.html\", context)\n\n\ndef signout_view(request, *args, **kwargs):\n if request.method == \"POST\":\n logout(request)\n return redirect('/')\n context = {\n 'form': None,\n 'description': \"are you sure you want to logout?\",\n \"btn_label\": \"Signin\",\n \"title\": \"Logout\"\n }\n return render(request, \"account/signout.html\", context)\n\n\n@login_required\ndef profile_view(request, *args, **kwargs):\n requests = []\n if request.user.is_authenticated:\n requests = Request.objects.filter(\n user=request.user).order_by('created_at').reverse()\n context = {'requests': requests}\n return render(request, \"account/profile.html\", context)\n\n\n@login_required\ndef send_contact_email(request):\n firstname = request.POST['first_name']\n lastname = request.POST['last_name']\n subject = request.POST['subject']\n email = request.user.email\n message = request.POST['message']\n\n #Send email to owner\n send_mail(\n subject,\n 'From ' + firstname + lastname + '
' + 'Email' + email + '
' +\n message,\n email,\n ['gmeyer49s@gmail.com'],\n fail_silently=False,\n )\n messages.success(request, \"Contact email sent successfully\")\n return redirect('/contacts')\n # return JsonResponse(\"Car saved in you inquires\")\n","repo_name":"jsgeorge/techshedapi","sub_path":"account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70407140871","text":"import matplotlib.pyplot as plt\nfrom scipy.stats import expon\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfig, ax = plt.subplots(1, 1)\n\nr = expon.rvs(size=1000)\n\nx = np.linspace(expon.ppf(0.01),\n expon.ppf(0.99), 100)\n\nax.hist(r, density=True, bins=100, histtype='stepfilled', alpha=0.2)\nax.set_xlim([x[0], x[-1]])\nax.legend(loc='best', frameon=False)\nplt.show()\n\n\n# x = np.random.rand(100)\nplt.hist(r)\n# plt.show()\nax2 = plt.gca() # get axis handle\n\np = ax2.patches\np[0].get_height()\n\nheights = [patch.get_height() for patch in p]\nprint('Initial exp condition', heights)","repo_name":"njs59/clusters","sub_path":"gillespie/test_exp.py","file_name":"test_exp.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19433251947","text":"import sys\nsys.stdin = open('input.txt')\n\n\nT = int(input())\nfor tc in range(1,T+1):\n F = int(input())\n numbers = list(map(int,input().split()))\n max_cnt = 0\n for i in range(F):\n cnt = 0\n for j in range(F-i-1):\n if numbers[i] > numbers[i+j+1]:\n cnt +=1\n\n if max_cnt < cnt:\n max_cnt = cnt\n\n print('#{} {}'.format(tc,max_cnt))\n\n","repo_name":"ssongkim2/algorithm","sub_path":"gravity/sol4.py","file_name":"sol4.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"71901343431","text":"#!/usr/bin/python3\nimport os\nfrom printkit import cprint\n\ndataSeperator=';'\nindexMemory=0\n\ndef makeJSONTemplate(labels):\n\tJSON_TEMPLATE='\"{}\":\"{}\"'\n\tRESULT=''\n\tLIMITER=int(len(labels)-1)\n\tfor i in range(0,len(labels)):\n\t\tRESULT=RESULT+JSON_TEMPLATE.format(labels[i],'{}')\n\t\tif(i!=LIMITER):\n\t\t\tRESULT=RESULT+','\n\treturn RESULT\n\ndef getInitialInputs():\n\ttry:\n\t\tcprint.yellow('\\n(Use \",\" as seperators)')\n\t\tlabelNames=\"id,\"+str(input(\"Enter the labelnames:~\"))\n\t\tlabelNames=labelNames.replace(' ','').split(',')\n\t\tentryCount=int(input(\"Enter the number of entries:~\"))\n\n\t\tcprint.green(\"[!]Preparing JSON Template for entries....\")\n\t\tjsonTemplate=makeJSONTemplate(labelNames)\n\t\tgetEntries(jsonTemplate,entryCount,labelNames)\n\n\texcept ValueError:\n\t\tos.system('clear')\n\t\tcprint.red('Invalid Inputs')\n\t\tgetInitialInputs()\n\ndef getEntries(jsonTemplate,entryCount,labelNames):\n\ttry:\n\t\tentries=[]\n\t\tglobal filename, dataSeperator, indexMemory\n\t\tfilter=[dataSeperator+' ',' '+dataSeperator,' '+dataSeperator+' ']\n\t\tformat_string=''\n\t\tfor label in labelNames[1:]:\n\t\t\tformat_string=format_string+label+dataSeperator\n\t\tformat_string=format_string[:-1]\n\t\tcprint.yellow('\\nINPUT FORMAT: {}'.format(format_string))\n\n\t\tfor entryIndex in range(indexMemory,entryCount+indexMemory):\n\t\t\tentryCache=str(id(entryIndex))+';'+str(input(\"Enter data for entry {}:\\n:> \".format(entryIndex+1)))\n\t\t\tfor pattern in filter:\n\t\t\t\tentryCache=entryCache.replace(pattern,dataSeperator)\n\t\t\tif(entryCache[-1]==' '):\n\t\t\t\tentryCache=entryCache[:-1]\n\t\t\tentries.append(entryCache.split(dataSeperator))\n\n\t\tgenerate(jsonTemplate,entries)\n\t\tcprint.green(\"\\nSuccessfully generated JSON file!\\nFile Location:{}/{}\".format(os.getcwd(),filename))\n\n\texcept:\n\t\tos.system('clear')\n\t\tcprint.red(\"[!]BAD inputs! try again\")\n\t\tgetEntries(jsonTemplate,entryCount,labelNames)\n\ndef generate(jsonTemplate,entries):\n\tresult=''\n\tmainResult='['\n\tglobal filemode\n\tif(filemode=='a'):\n\t\tfilereader=open(filename,'r')\n\t\tcache=filereader.read()[:-2]+',\\n'\n\t\tfilereader.close()\n\t\tmainResult=cache\n\t\tfilemode='w'\n\tfor entry in entries:\n\t\tresult=result+jsonTemplate.format(*entry)+','\n\t\tresult='{'+result[:-1]+'},\\n'\n\t\tmainResult=mainResult+result\n\t\tmainWriteToFile(mainResult)\n\t\tresult=''\n\tmainWriteToFile(mainResult[:-2]+']')\n\ndef mainWriteToFile(data):\n\tglobal filename,filemode\n\tcache=''\n\tif(filemode=='a'):\n\t\tfilereader=open(filename,'r')\n\t\tcache=filereader.read()[:-1]\n\t\tfilereader.close()\n\t\tmainResult=cache\n\t\tfilemode='w'\n\tmainfile=open(filename,'w')\n\tmainfile.write(cache)\n\tmainfile.write(data)\n\tmainfile.close()\n\ndef getMetaInputs():\n\tfilename=str(input('Enter the name of the file:~'))\n\tcprint.yellow(\"\\nFILE MODES\\n[1]Overwrite Mode(first time)\\n[2]Append Mode(to add)\")\n\tmode=int(input(\"Use file mode:~\"))\n\tif(mode==1):\n\t\tfilemode='w'\n\telif(mode==2):\n\t\tfilemode='a'\n\treturn filename,filemode\n\ndef remember():\n\ttry:\n\t\tglobal indexMemory,filename,filemode\n\t\tfile=open(filename,'r')\n\t\tindexMemory=len(file.readlines())\n\t\tfile.close()\n\texcept:\n\t\tcprint.red('[!]Old file not found! Creating new file.')\n\t\tfilemode='w'\n\t\tindexMemory=0\n\nfilename,filemode=getMetaInputs()\nremember()\ngetInitialInputs()\n","repo_name":"CipherKill/JSONmaker","sub_path":"JSONmaker.py","file_name":"JSONmaker.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"10001853705","text":"\r\nfrom __future__ import unicode_literals\r\n\r\nimport argparse\r\nimport datetime \r\nimport os\r\nimport time\r\nimport pyaudio\r\nimport wave\r\nfrom src.utils import Audio\r\nfrom scipy.io import wavfile\r\nimport noisereduce as nr\r\nimport numpy as np\r\n\r\nFORMAT = pyaudio.paInt16\r\nCHANNELS = 1\r\nRATE = 16000\r\nCHUNK = 1024\r\nRECORD_SECONDS = 2.5\r\nSNR_TRIM = 18\r\nFOLDER_BASE = \"\"\r\nMAX_RECORD_DURATION = 2\r\nMAX_DIFFERENCE_DURATION = 0.3\r\nDATE_FORMAT = '%Y_%m_%dT%H_%M_%S'\r\n\r\n\r\ndef record_one(directory, i):\r\n dest_path = os.path.join(directory, \"{0}.wav\".format(i))\r\n \r\n audio = pyaudio.PyAudio()\r\n\r\n print(\r\n \"\"\"\\n\\nPress enter to record one sample, say your hotword when \"recording...\" shows up\"\"\")\r\n time.sleep(0.2)\r\n\r\n stream = audio.open(format=FORMAT, channels=CHANNELS,\r\n rate=RATE, input=True,\r\n frames_per_buffer=CHUNK)\r\n print(\"recording...\")\r\n frames = []\r\n\r\n for j in range(0, int(RATE / CHUNK * RECORD_SECONDS)):\r\n data = stream.read(CHUNK)\r\n frames.append(data)\r\n print(\"finished recording\\n\")\r\n\r\n stream.stop_stream()\r\n stream.close()\r\n audio.terminate()\r\n while(True):\r\n try:\r\n waveFile = wave.open(dest_path, 'wb')\r\n waveFile.setnchannels(CHANNELS)\r\n waveFile.setsampwidth(2)\r\n waveFile.setframerate(RATE)\r\n waveFile.writeframes(b''.join(frames))\r\n waveFile.close()\r\n break\r\n except Exception:\r\n pass\r\n\r\n noisereduction(directory,i)\r\ndef noisereduction(dir,i):\r\n inp_path = os.path.join(dir, \"{0}.wav\".format(i))\r\n sample_rate,data = wavfile.read(inp_path)\r\n dest_path = os.path.join(dir, \"{0}.wav\".format(i))\r\n data = nr.reduce_noise(data,sr=sample_rate)\r\n while(True):\r\n try:\r\n wavfile.write(dest_path, RATE, data.astype(np.int16))\r\n break\r\n except Exception:\r\n pass\r\n return dest_path \r\ndef check_audios(durations):\r\n if any([d > MAX_RECORD_DURATION for d in durations]):\r\n print(\"WARNING: at least one your record seems to have a too long \" \\\r\n \"duration, you are going to have\")\r\n\r\ndef validate(i,queue):\r\n directory = \"temp\"\r\n dest_path = os.path.join(directory, \"{0}.wav\".format(i))\r\n audio = Audio.from_file(dest_path)\r\n audio.trim_silences(SNR_TRIM)\r\n if audio.duration() > MAX_RECORD_DURATION:\r\n print(\"WARNING: there seems to be too much noise in your\" \\\r\n \" environment please retry to record this sample by \" \\\r\n \"following the instructions.\")\r\n return 2\r\n if any([abs(audio_1.duration() - audio_2.duration()) > MAX_DIFFERENCE_DURATION for i, audio_1 in enumerate(queue) for j, audio_2 in enumerate(queue) if i < j]):\r\n print(\"WARNING: there seems to be too much difference between \" \\\r\n \"your records please retry to record all of them by following \" \\\r\n \"the instructions.\")\r\n return 1\r\n\r\n queue.append(audio)\r\n return 0\r\n \r\ndef record_and_trim(hotword_key, nb_records=3):\r\n print(\"Your will have to record your personal hotword.\" \\\r\n \" Please be sure to be in a quiet environment.\" \\\r\n \" Press enter once you are ready.\\n\".format(\r\n nb_records))\r\n\r\n directory = os.path.join(FOLDER_BASE, \"personal_{0}\".format(str(datetime.datetime.now().strftime(DATE_FORMAT))))\r\n os.makedirs(directory)\r\n\r\n is_validated = False\r\n while not is_validated:\r\n audios = []\r\n for i in range(nb_records):\r\n record_one(directory, i)\r\n dest_path = os.path.join(directory, \"{0}.wav\".format(i))\r\n audio = Audio.from_file(dest_path)\r\n audio.trim_silences(SNR_TRIM)\r\n while audio.duration() > MAX_RECORD_DURATION:\r\n print(\"WARNING: there seems to be too much noise in your\" \\\r\n \" environment please retry to record this sample by \" \\\r\n \"following the instructions.\")\r\n record_one(directory, i)\r\n audio = Audio.from_file(dest_path)\r\n audio.trim_silences(SNR_TRIM)\r\n audios.append(audio)\r\n\r\n if any([abs(\r\n audio_1.duration() - audio_2.duration()) > MAX_DIFFERENCE_DURATION\r\n for i, audio_1 in enumerate(audios) for j, audio_2 in\r\n enumerate(audios) if i < j]):\r\n print(\"WARNING: there seems to be too much difference between \" \\\r\n \"your records please retry to record all of them by following \" \\\r\n \"the instructions.\")\r\n audios = []\r\n else:\r\n is_validated = True\r\n\r\n for i, audio in enumerate(audios):\r\n dest_path = os.path.join(directory, \"{0}.wav\".format(i))\r\n audio.write(dest_path)\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--hotword_key', type=str,\r\n help=\"the name of your personal hotword (no special characters)\")\r\n args = parser.parse_args()\r\n record_and_trim(args.hotword_key)\r\n","repo_name":"nguyenbao2301/gui","sub_path":"src/keyword_recording.py","file_name":"keyword_recording.py","file_ext":"py","file_size_in_byte":5178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"34623211116","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom .cart import Cart\nfrom .forms import CartAddProductForm\n\n# Create your views here.\n\nfrom django.views import generic\n\nfrom accounts.models import Ouser\nfrom customize.forms import save_quotation_form\nfrom customize.models import Quotation, Category\nfrom order.models import Cartmaster\n\n\ndef cartmasterview(request, user_id):\n cartmaster = Cartmaster.objects.filter(customer_id=user_id)\n context = {'Cartlist': cartmaster}\n return render(request, 'order/cart.html', context)\n\n\nclass checkout(generic.TemplateView):\n template_name = \"order/checkout.html\"\n\n\ndef cart_add(request, product_id):\n print(\"product_id in add\", product_id)\n cartmaster = Cartmaster.objects.filter(customer_id=request.user.id)\n context = {'Cartlist': cartmaster}\n cart = Cart(request) # create a new cart object passing it the request object\n print(\"cart_add\", request)\n print(\"=====>cart\", cart.session)\n incart = get_object_or_404(Cartmaster, cart_id=product_id)\n # form = CartAddProductForm(request.POST)\n # print(\"product_id in add\",form.errors)\n # if form.is_valid():\n # cd = form.cleaned_data\n cart.add(product=incart, quantity=10, update_quantity=10)\n print(\"product_id in add\", cart)\n # return redirect('shop:list.html')\n return redirect('order:cart_detail')\n\n\ndef cart_detail(request):\n cart = Cart(request)\n for item in cart:\n item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'update': True})\n return render(request, 'order/detail.html', {'cart': cart})\n\n\ndef checkcart(request):\n cart = Cart(request)\n print(\"======>cart\", Cart.__iter__)\n print(\"======>cart1\", Cart.__len__)\n # print(\"======>product_ids\",cart.key())\n return render(request, 'order/checkout.html')\n\n\ndef SaveToCart(request, slug):\n ouser_name = Ouser.objects.get(id=request.user.id)\n\n print(\"ouser_name\", type(ouser_name))\n quotationlist = Quotation.objects.filter(quotation_id=slug)\n\n for items in quotationlist:\n execstr = Cartmaster.objects.create(cart_id=items.quotation_id,\n quotation_id=items.quotation_id,\n sleeve=items.sleeve,\n color=items.color,\n size=items.size,\n req_image=items.req_image,\n gender=items.gender,\n part_number=items.part_number,\n quantity=items.quantity,\n description=items.description,\n category_name=items.category_name,\n customer_id=items.customer_id,\n rep_id=ouser_name.username)\n execstr.save()\n return redirect(\"order:cartmaster\", user_id=request.user.id)\n\n\ndef Deletecartitem(request, slug):\n Cartdelitem = Cartmaster.objects.get(cart_id=slug)\n Cartdelitem.delete()\n return redirect(\"order:cartmaster\", user_id=request.user.id)","repo_name":"syitzhm/freedomclouth.github.io","sub_path":"order/views_old.py","file_name":"views_old.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"25605556397","text":"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('tratores/', include('trator.urls')),\n path('', include('usuario.urls')),\n path('dispositivos/', include('dispositivo.urls')),\n path('trabalhos/', include('trabalho.urls')),\n path('areas/', include('area.urls')),\n path('imagens/', include('imagem.urls')),\n path('rotas/', include('rota.urls'))\n]\n\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT)\n","repo_name":"marceleta/geosensor","sub_path":"geosensor/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"31014651513","text":"\"\"\"Evaluate policies: render policy interactively, save videos, log episode return.\"\"\"\n\nimport logging\nimport os\nimport os.path as osp\nimport time\nfrom typing import Any, Mapping, Optional\n\nimport gym\nfrom sacred.observers import FileStorageObserver\nfrom stable_baselines3.common.vec_env import VecEnvWrapper\n\nimport imitation.util.sacred as sacred_util\nfrom imitation.data import rollout\nfrom imitation.policies import serialize\nfrom imitation.rewards.serialize import load_reward\nfrom imitation.scripts.config.eval_policy import eval_policy_ex\nfrom imitation.util import reward_wrapper, util, video_wrapper\n\n\nclass InteractiveRender(VecEnvWrapper):\n \"\"\"Render the wrapped environment(s) on screen.\"\"\"\n\n def __init__(self, venv, fps):\n super().__init__(venv)\n self.render_fps = fps\n\n def reset(self):\n ob = self.venv.reset()\n self.venv.render()\n return ob\n\n def step_wait(self):\n ob = self.venv.step_wait()\n if self.render_fps > 0:\n time.sleep(1 / self.render_fps)\n self.venv.render()\n return ob\n\n\ndef video_wrapper_factory(log_dir: str, **kwargs):\n \"\"\"Returns a function that wraps the environment in a video recorder.\"\"\"\n\n def f(env: gym.Env, i: int) -> gym.Env:\n \"\"\"Wraps `env` in a recorder saving videos to `{log_dir}/videos/{i}`.\"\"\"\n directory = os.path.join(log_dir, \"videos\", str(i))\n return video_wrapper.VideoWrapper(env, directory=directory, **kwargs)\n\n return f\n\n\n@eval_policy_ex.main\ndef eval_policy(\n _run,\n _seed: int,\n env_name: str,\n eval_n_timesteps: Optional[int],\n eval_n_episodes: Optional[int],\n num_vec: int,\n parallel: bool,\n render: bool,\n render_fps: int,\n videos: bool,\n video_kwargs: Mapping[str, Any],\n log_dir: str,\n policy_type: str,\n policy_path: str,\n reward_type: Optional[str] = None,\n reward_path: Optional[str] = None,\n max_episode_steps: Optional[int] = None,\n):\n \"\"\"Rolls a policy out in an environment, collecting statistics.\n\n Args:\n _seed: generated by Sacred.\n env_name: Gym environment identifier.\n eval_n_timesteps: Minimum number of timesteps to evaluate for. Set exactly\n one of `eval_n_episodes` and `eval_n_timesteps`.\n eval_n_episodes: Minimum number of episodes to evaluate for. Set exactly\n one of `eval_n_episodes` and `eval_n_timesteps`.\n num_vec: Number of environments to run simultaneously.\n parallel: If True, use `SubprocVecEnv` for true parallelism; otherwise,\n uses `DummyVecEnv`.\n max_episode_steps: If not None, then environments are wrapped by\n TimeLimit so that they have at most `max_episode_steps` steps per\n episode.\n render: If True, renders interactively to the screen.\n render_fps: The target number of frames per second to render on screen.\n videos: If True, saves videos to `log_dir`.\n video_kwargs: Keyword arguments passed through to `video_wrapper.VideoWrapper`.\n log_dir: The directory to log intermediate output to, such as episode reward.\n policy_type: A unique identifier for the saved policy,\n defined in POLICY_CLASSES.\n policy_path: A path to the serialized policy.\n reward_type: If specified, overrides the environment reward with\n a reward of this.\n reward_path: If reward_type is specified, the path to a serialized reward\n of `reward_type` to override the environment reward with.\n\n Returns:\n Return value of `imitation.util.rollout.rollout_stats()`.\n \"\"\"\n os.makedirs(log_dir, exist_ok=True)\n sacred_util.build_sacred_symlink(log_dir, _run)\n\n logging.basicConfig(level=logging.INFO)\n logging.info(\"Logging to %s\", log_dir)\n sample_until = rollout.make_sample_until(eval_n_timesteps, eval_n_episodes)\n post_wrappers = [video_wrapper_factory(log_dir, **video_kwargs)] if videos else None\n venv = util.make_vec_env(\n env_name,\n num_vec,\n seed=_seed,\n parallel=parallel,\n log_dir=log_dir,\n max_episode_steps=max_episode_steps,\n post_wrappers=post_wrappers,\n )\n\n try:\n if render:\n # As of July 31, 2020, DummyVecEnv rendering only works with num_vec=1\n # due to a bug on Stable Baselines 3.\n venv = InteractiveRender(venv, render_fps)\n\n if reward_type is not None:\n reward_fn = load_reward(reward_type, reward_path, venv)\n venv = reward_wrapper.RewardVecEnvWrapper(venv, reward_fn)\n logging.info(f\"Wrapped env in reward {reward_type} from {reward_path}.\")\n\n policy = serialize.load_policy(policy_type, policy_path, venv)\n trajs = rollout.generate_trajectories(policy, venv, sample_until)\n return rollout.rollout_stats(trajs)\n finally:\n venv.close()\n\n\ndef main_console():\n observer = FileStorageObserver(osp.join(\"output\", \"sacred\", \"eval_policy\"))\n eval_policy_ex.observers.append(observer)\n eval_policy_ex.run_commandline()\n\n\nif __name__ == \"__main__\": # pragma: no cover\n main_console()\n","repo_name":"sen-pai/InfoGAIL","sub_path":"imitation/src/imitation/scripts/eval_policy.py","file_name":"eval_policy.py","file_ext":"py","file_size_in_byte":5109,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"27"} +{"seq_id":"26229023153","text":"from django.urls import path\nfrom webapp.views.base import IndexView\nfrom webapp.views.products import ProductCreate, ProductView, ProductUpdateView, ProductDeleteView\nfrom webapp.views.reviews import ReviewCreate, ReviewUpdateView, ReviewDeleteView\n\n\nurlpatterns= [\n path(\"\", IndexView.as_view(), name='index'),\n path('products/add', ProductCreate.as_view(), name='product_add'),\n path('product/', ProductView.as_view(), name='product_detail'),\n path('product//update', ProductUpdateView.as_view(), name='product_update'),\n path('product//delete', ProductDeleteView.as_view(), name='delete_product'),\n path('product//add_review', ReviewCreate.as_view(), name='add_review'),\n path('product//review/update', ReviewUpdateView.as_view(), name='update_review'),\n path('product//review/delete', ReviewDeleteView.as_view(), name='delete_review')\n]\n","repo_name":"Daniarbekov/exam_8","sub_path":"source/webapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"34689724056","text":"from __future__ import print_function\r\nimport pyVmomi\r\nfrom vconnector.core import VConnector\r\nclient = VConnector(\r\n user='root',\r\n pwd='p4ssw0rd',\r\n host='vc01.example.org'\r\n )\r\nclient.connect()\r\ndatastores = client.get_datastore_view()\r\nresult = client.collect_properties(\r\n view_ref=datastores,\r\n obj_type=pyVmomi.vim.Datastore,\r\n path_set=['name', 'summary.capacity']\r\n)\r\nprint(result)\r\nclient.disconnect()","repo_name":"subhshetty/Vsphere","sub_path":"vsphere-detailed.py","file_name":"vsphere-detailed.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"71931030791","text":"from random import choice\n\n\nclass Game:\n def __init__(self, game_questions):\n self.questions = game_questions\n self.score = 0\n self.t_f = {\"t\": \"true\", \"f\": \"false\", \"T\": \"true\", \"F\": \"false\"}\n\n def question(self):\n try:\n q = choice(self.questions)\n self.questions.remove(q)\n return q\n except Exception:\n print(\"Game Over!\")\n return \"Game Over!\"\n\n def answer(self, x, y):\n if y in self.t_f:\n y = self.t_f[y]\n\n if y.lower() == x.lower():\n self.score += 1\n else:\n pass\n","repo_name":"nico-Zero/Python","sub_path":"New_Shit__/Angela_Yu__/Day_17_Quize_game/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"41403746343","text":"import argparse\nimport numpy as np\nimport numpy.ma as ma\nimport pickle\nimport os\n\nimport msgpack\nimport msgpack_numpy\n\nfrom nav.file import (fixup_byte_to_str,\n results_path,\n yield_image_filenames)\n\nimport julian\n\nfrom imgdisp import ImageDisp\nfrom PIL import Image\n\nRING_FILENAMES = None\n\nCB_SOURCE_ROOT = os.environ['CB_SOURCE_ROOT']\nCB_RESULTS_ROOT = os.environ['CB_RESULTS_ROOT']\n\ndef file_clean_join(*args):\n ret = os.path.join(*args)\n return ret.replace('\\\\', '/')\n\nRING_RESULTS_ROOT = file_clean_join(CB_RESULTS_ROOT, 'ring_mosaic')\n\nRING_SOURCE_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nRING_LISTS_ROOT = file_clean_join(RING_SOURCE_ROOT, 'ring_mosaic_lists')\nRING_REPROJECT_PY = file_clean_join(RING_SOURCE_ROOT, 'ring_ui_reproject.py')\nRING_MOSAIC_PY = file_clean_join(RING_SOURCE_ROOT, 'ring_ui_mosaic.py')\nRING_BKGND_PY = file_clean_join(RING_SOURCE_ROOT, 'ring_ui_bkgnd.py')\n\n################################################################################\n#\n# Data structures used for each pass\n#\n################################################################################\n\nclass OffRepData(object):\n \"\"\"Offset and Reprojection data for one image.\"\"\"\n def __init__(self):\n self.obsid = None # Observation ID\n self.image_name = None # The image basename\n self.image_path = None # The full image path\n self.obs = None # The image data from image_path\n self.bad_pixel_map = None # Optional mask of user-defined\n # bad pixels\n\n self.offset_path = None # The path of the offset file\n self.the_offset = None # The offset being used (x,y)\n self.manual_offset = None # The manual offset, if any\n self.off_metadata = None # Full metadata from offset process\n\n self.repro_path = None # The path of the repro file\n self.repro_img = None # The repro data from repro_path\n self.repro_long_mask = None # The mask of used longitudes\n self.repro_longitudes = None # The actual used longitudes\n self.repro_resolutions = None # Resolution by longitude bin #\n self.repro_phase_angles = None # Phase angle by longitude bin #\n self.repro_emission_angles = None # Emission angle by longitude bin #\n self.repro_incidence_angle = None # Incidence angle (scalar)\n self.repro_time = None # The time the repro was produced\n\n self.image_log_filehandler = None # Logger\n self.subprocess_run = None # True if run in a subprocess\n\nclass MosaicData(object):\n \"\"\"Mosaic metadata for one mosaic.\"\"\"\n def __init__(self):\n self.img = None\n\nclass BkgndData(object):\n \"\"\"Background metadata for one mosaic.\"\"\"\n def __init__(self, obsid=None, arguments=None):\n self.obsid = obsid\n if arguments is None:\n self.mosaic_img = None\n self.mosaic_data_filename = None\n self.mosaic_metadata_filename = None\n self.reduced_mosaic_data_filename = None\n self.reduced_mosaic_metadata_filename = None\n self.bkgnd_model_filename = None # NPZ\n self.bkgnd_metadata_filename = None\n self.full_png_path = None\n self.small_png_path = None\n else:\n (self.mosaic_data_filename,\n self.mosaic_metadata_filename) = mosaic_paths(arguments, obsid)\n (self.reduced_mosaic_data_filename,\n self.reduced_mosaic_metadata_filename,\n self.bkgnd_model_filename,\n self.bkgnd_metadata_filename) = bkgnd_paths(arguments, obsid,\n make_dirs=True)\n (self.bkgnd_sub_mosaic_filename,\n self.bkgnd_sub_mosaic_metadata_filename) = bkgnd_sub_mosaic_paths(\n arguments, obsid,\n make_dirs=True)\n self.full_png_path = bkgnd_png_path(arguments, obsid, 'full',\n make_dirs=True)\n self.small_png_path = bkgnd_png_path(arguments, obsid, 'small',\n make_dirs=True)\n\n self.row_cutoff_sigmas = None\n self.row_ignore_fraction = None\n self.row_blur = None\n self.ring_lower_limit = None\n self.ring_upper_limit = None\n self.column_cutoff_sigmas = None\n self.column_inside_background_pixels = None\n self.column_outside_background_pixels = None\n self.degree = None\n self.corrected_mosaic_img = None\n\n self.radius_resolution = None\n self.longitude_resolution = None\n self.mosaic_img = None\n self.long_mask = None\n self.image_numbers = None\n self.ETs = None\n self.emission_angles = None\n self.incidence_angle = None\n self.phase_angles = None\n self.resolutions = None\n self.longitudes = None\n self.obsid_list = None\n self.image_name_list = None\n self.image_path_list = None\n self.repro_path_list = None\n\n\n################################################################################\n#\n# Argument parsing\n#\n################################################################################\n\n_VALID_INSTRUMENT_HOSTS = ('cassini', 'voyager')\n\ndef _validate_instrument_host(instrument_host):\n \"\"\"Routine for argparse to validate an instrument host.\"\"\"\n if not instrument_host in ('cassini', 'voyager'):\n raise argparse.ArgumentTypeError(\n f\"{instrument_host} is not a valid instrument host - must be one of \"\n f\"{_VALID_INSTRUMENT_HOSTS}\")\n return instrument_host\n\ndef ring_add_parser_arguments(parser):\n parser.add_argument(\n 'obsid', action='append', nargs='*',\n help='Specific OBSIDs to process')\n parser.add_argument(\n '--ring-type', type=str, default='FMOVIE',\n help='The type of ring mosaics; use to retrieve the file lists')\n parser.add_argument(\n '--corot-type', type=str, default='',\n help='The type of co-rotation frame to use')\n parser.add_argument(\n '--all-obsid', '-a', action='store_true', default=False,\n help='Process all OBSIDs of the given type')\n parser.add_argument(\n '--start-obsid', default='',\n help='The first obsid to process')\n parser.add_argument(\n '--end-obsid', default='',\n help='The last obsid to process')\n parser.add_argument(\n '--ring-radius', type=int, default=0,\n help='The main ring radius; by default loaded from the ring type')\n parser.add_argument(\n '--radius-inner-delta', type=int, default=0,\n help='''The inner delta from the main ring radius;\n by default loaded from the ring type''')\n parser.add_argument(\n '--radius-outer-delta', type=int, default=0,\n help='''The outer delta from the main ring radius;\n by default loaded from the ring type''')\n parser.add_argument(\n '--radius-resolution', type=float, default=0.,\n help='The radial resolution for reprojection')\n parser.add_argument(\n '--longitude-resolution', type=float, default=0.,\n help='The longitudinal resolution for reprojection')\n parser.add_argument(\n '--radial-zoom-amount', type=int, default=0,\n help='The amount of radial zoom for reprojection')\n parser.add_argument(\n '--longitude-zoom-amount', type=int, default=0,\n help='The amount of longitude zoom for reprojection')\n parser.add_argument('--verbose', action='store_true', default=False)\n parser.add_argument('--instrument-host', default='cassini',\n type=_validate_instrument_host,\n help=f'''Which spacecraft to process: {_VALID_INSTRUMENT_HOSTS}\n (cassini is the default)''')\n\n\n################################################################################\n#\n# Initialization of globals\n#\n################################################################################\n\ndef ring_init(arguments):\n global RING_FILENAMES\n RING_FILENAMES = {}\n type_dir = file_clean_join(RING_LISTS_ROOT, 'FILELIST_'+\n arguments.ring_type.upper())\n\n default_filename = file_clean_join(type_dir, 'defaults.txt')\n assert os.path.exists(default_filename), default_filename\n default_fp = open(default_filename, 'r')\n default_corot = default_fp.readline().strip()\n default_radius = int(default_fp.readline().strip())\n default_radius_inner = int(default_fp.readline().strip())\n default_radius_outer = int(default_fp.readline().strip())\n default_radius_resolution = float(default_fp.readline().strip())\n default_longitude_resolution = float(default_fp.readline().strip())\n default_radial_zoom_amount = int(default_fp.readline().strip())\n default_longitude_zoom_amount = int(default_fp.readline().strip())\n default_fp.close()\n if arguments.corot_type == '':\n arguments.corot_type = default_corot\n if arguments.ring_radius == 0:\n arguments.ring_radius = default_radius\n if arguments.radius_inner_delta == 0:\n arguments.radius_inner_delta = default_radius_inner\n if arguments.radius_outer_delta == 0:\n arguments.radius_outer_delta = default_radius_outer\n if arguments.radius_resolution == 0:\n arguments.radius_resolution = default_radius_resolution\n if arguments.longitude_resolution == 0:\n arguments.longitude_resolution = default_longitude_resolution\n if arguments.radial_zoom_amount == 0:\n arguments.radial_zoom_amount = default_radial_zoom_amount\n if arguments.longitude_zoom_amount == 0:\n arguments.longitude_zoom_amount = default_longitude_zoom_amount\n\n for obsid_file in sorted(os.listdir(type_dir)):\n if not obsid_file.endswith('.list'):\n continue\n obsid = obsid_file[:-5]\n fp = open(file_clean_join(type_dir, obsid_file), 'r')\n filenames = fp.readlines()\n filenames = [x.strip() for x in filenames if x[0] != '#']\n fp.close()\n # Accept both Nxxxxxx_x and\n # path/path/path/Nxxxxx_x.IMG\n filenames = [f.split('/')[-1].split('.')[0]\n for f in filenames\n if f[0] != '#']\n RING_FILENAMES[obsid] = filenames\n\n\n################################################################################\n#\n# Enumerate files based on the command line arguments\n#\n################################################################################\n\ndef ring_enumerate_files(arguments, force_obsid=None, yield_obsid_only=False):\n if force_obsid:\n obsid_db = {force_obsid: RING_FILENAMES[force_obsid]}\n elif (arguments.all_obsid or arguments.start_obsid or arguments.end_obsid or\n len(arguments.obsid[0]) == 0):\n obsid_db = RING_FILENAMES\n else:\n obsid_db = {}\n for arg in arguments.obsid[0]:\n if '/' in arg:\n # OBSID/FILENAME\n obsid, filename = arg.split('/')\n if not obsid in obsid_db:\n obsid_db[obsid] = []\n obsid_db[obsid].append(filename)\n else:\n # OBSID\n obsid_db[arg] = RING_FILENAMES[arg]\n\n for obsid in sorted(obsid_db.keys()):\n obsid_db[obsid].sort(key=lambda x: (x[1:8] if x [0] == 'C' else\n x[1:13]+x[0]))\n\n found_start_obsid = True\n if arguments.start_obsid:\n found_start_obsid = False\n\n for obsid in sorted(obsid_db.keys()):\n if not found_start_obsid:\n if obsid != arguments.start_obsid:\n continue\n found_start_obsid = True\n if yield_obsid_only:\n yield obsid, None, None\n else:\n filename_list = obsid_db[obsid]\n for full_path in yield_image_filenames(\n restrict_list=filename_list,\n instrument_host=arguments.instrument_host):\n _, filename = os.path.split(full_path)\n if filename[0] == 'C': # Voyager\n yield obsid, filename[:8], full_path\n else:\n yield obsid, filename[:13], full_path\n if obsid == arguments.end_obsid:\n break\n\n\n################################################################################\n#\n# Create command line arguments for any sub-program\n#\n################################################################################\n\ndef ring_basic_cmd_line(arguments):\n ret = ['--ring-type', arguments.ring_type]\n ret += ['--corot-type', arguments.corot_type]\n ret += ['--ring-radius', str(arguments.ring_radius)]\n ret += ['--radius-inner', str(arguments.radius_inner_delta)]\n ret += ['--radius-outer', str(arguments.radius_outer_delta)]\n ret += ['--radius-resolution', str(arguments.radius_resolution)]\n ret += ['--longitude-resolution', str(arguments.longitude_resolution)]\n ret += ['--radial-zoom-amount', str(arguments.radial_zoom_amount)]\n ret += ['--longitude-zoom-amount', str(arguments.longitude_zoom_amount)]\n ret += ['--instrument-host', arguments.instrument_host]\n\n return ret\n\n\n################################################################################\n#\n# Create path names for various file types and read and write the files\n#\n################################################################################\n\ndef img_to_repro_path_spec(ring_radius,\n radius_inner, radius_outer,\n radius_resolution, longitude_resolution,\n radial_zoom_amount, longitude_zoom_amount,\n image_path, instrument_host,\n make_dirs=False):\n repro_res_data = ('_%06d_%06d_%06d_%06.3f_%05.3f_%d_%d-REPRO.dat' % (\n ring_radius, radius_inner, radius_outer,\n radius_resolution, longitude_resolution,\n radial_zoom_amount, longitude_zoom_amount))\n repro_path = results_path(image_path+repro_res_data,\n instrument_host,\n 'ring_repro',\n root=RING_RESULTS_ROOT,\n make_dirs=make_dirs)\n return repro_path\n\ndef img_to_repro_path(arguments, image_path, instrument_host, make_dirs=False):\n return img_to_repro_path_spec(arguments.ring_radius,\n arguments.radius_inner_delta,\n arguments.radius_outer_delta,\n arguments.radius_resolution,\n arguments.longitude_resolution,\n arguments.radial_zoom_amount,\n arguments.longitude_zoom_amount,\n image_path, instrument_host,\n make_dirs=make_dirs)\n\ndef read_repro(repro_path):\n if not os.path.exists(repro_path):\n return None\n try:\n with open(repro_path, 'rb') as repro_fp:\n repro_data = msgpack.unpackb(repro_fp.read(),\n max_str_len=40*1024*1024,\n object_hook=msgpack_numpy.decode)\n except UnicodeDecodeError:\n with open(repro_path, 'rb') as repro_fp:\n repro_data = msgpack.unpackb(repro_fp.read(),\n max_str_len=40*1024*1024,\n object_hook=msgpack_numpy.decode,\n raw=True)\n repro_data = fixup_byte_to_str(repro_data)\n\n if repro_data is None:\n repro_data = {}\n if 'bad_pixel_map' not in repro_data:\n repro_data['bad_pixel_map'] = None\n if 'mean_resolution' in repro_data: # Old format\n repro_data['mean_radial_resolution'] = res = repro_data['mean_resolution']\n del repro_data['mean_resolution']\n repro_data['mean_angular_resolution'] = np.zeros(res.shape)\n if 'long_mask' in repro_data: # Old format\n repro_data['long_antimask'] = repro_data['long_mask']\n del repro_data['long_mask']\n\n return repro_data\n\ndef write_repro(repro_path, repro_data):\n with open(repro_path, 'wb') as repro_fp:\n repro_fp.write(msgpack.packb(repro_data,\n default=msgpack_numpy.encode))\n\n\ndef mosaic_paths_spec(ring_radius, radius_inner, radius_outer,\n radius_resolution, longitude_resolution,\n radial_zoom_amount, longitude_zoom_amount,\n obsid, ring_type, make_dirs=False):\n mosaic_res_data = ('_%06d_%06d_%06d_%06.3f_%05.3f_%d_%d' % (\n ring_radius, radius_inner, radius_outer,\n radius_resolution, longitude_resolution,\n radial_zoom_amount, longitude_zoom_amount))\n mosaic_dir = file_clean_join(RING_RESULTS_ROOT, 'mosaic_'+ring_type)\n if make_dirs and not os.path.exists(mosaic_dir):\n os.mkdir(mosaic_dir)\n data_path = file_clean_join(mosaic_dir, obsid+mosaic_res_data+'-MOSAIC')\n metadata_path = file_clean_join(mosaic_dir,\n obsid+mosaic_res_data+\n '-MOSAIC-METADATA.dat')\n return (data_path, metadata_path)\n\ndef mosaic_paths(arguments, obsid, make_dirs=False):\n return mosaic_paths_spec(arguments.ring_radius,\n arguments.radius_inner_delta,\n arguments.radius_outer_delta,\n arguments.radius_resolution,\n arguments.longitude_resolution,\n arguments.radial_zoom_amount,\n arguments.longitude_zoom_amount,\n obsid, arguments.ring_type,\n make_dirs=make_dirs)\n\ndef read_mosaic(data_path, metadata_path):\n img = np.load(data_path+'.npy')\n\n try:\n with open(metadata_path, 'rb') as mosaic_metadata_fp:\n metadata = msgpack.unpackb(mosaic_metadata_fp.read(),\n object_hook=msgpack_numpy.decode)\n except UnicodeDecodeError:\n with open(metadata_path, 'rb') as mosaic_metadata_fp:\n metadata = msgpack.unpackb(mosaic_metadata_fp.read(),\n object_hook=msgpack_numpy.decode,\n raw=True)\n metadata = fixup_byte_to_str(metadata)\n\n metadata['img'] = img\n\n if 'mean_resolution' in metadata: # Old format\n metadata['mean_radial_resolution'] = res = metadata['mean_resolution']\n del metadata['mean_resolution']\n metadata['mean_angular_resolution'] = np.zeros(res.shape)\n if 'long_mask' in metadata: # Old format\n metadata['long_antimask'] = metadata['long_mask']\n del metadata['long_mask']\n\n return metadata\n\ndef write_mosaic(data_path, img, metadata_path, metadata):\n # Save mosaic image array in binary\n np.save(data_path, img)\n\n # Save metadata\n metadata = metadata.copy() # Everything except img\n del metadata['img']\n mosaic_metadata_fp = open(metadata_path, 'wb')\n mosaic_metadata_fp.write(msgpack.packb(\n metadata, default=msgpack_numpy.encode))\n mosaic_metadata_fp.close()\n\n\ndef mosaic_png_path_spec(ring_radius, radius_inner, radius_outer,\n radius_resolution, longitude_resolution,\n radial_zoom_amount, longitude_zoom_amount,\n obsid, ring_type, png_type, make_dirs=False):\n mosaic_res_data = ('_%06d_%06d_%06d_%06.3f_%05.3f_%d_%d' % (\n ring_radius, radius_inner, radius_outer,\n radius_resolution, longitude_resolution,\n radial_zoom_amount, longitude_zoom_amount))\n png_dir = file_clean_join(RING_RESULTS_ROOT,\n 'png_mosaic_'+png_type+'_'+ring_type)\n if make_dirs and not os.path.exists(png_dir):\n os.mkdir(png_dir)\n png_path = file_clean_join(png_dir,\n obsid+mosaic_res_data+'-'+png_type+'.png')\n return png_path\n\ndef mosaic_png_path(arguments, obsid, png_type, make_dirs=False):\n return mosaic_png_path_spec(arguments.ring_radius,\n arguments.radius_inner_delta,\n arguments.radius_outer_delta,\n arguments.radius_resolution,\n arguments.longitude_resolution,\n arguments.radial_zoom_amount,\n arguments.longitude_zoom_amount,\n obsid, arguments.ring_type,\n png_type,\n make_dirs=make_dirs)\n\ndef write_mosaic_pngs(full_png_path, small_png_path, img, mask_fill_value=-999):\n if mask_fill_value is not None:\n img = img.copy()\n img[img == mask_fill_value] = 0\n valid_cols = np.sum(img, axis=0) != 0\n subimg = img[:, valid_cols]\n blackpoint = max(np.min(subimg), 0)\n whitepoint_ignore_frac = 0.995\n img_sorted = sorted(list(subimg.flatten()))\n whitepoint = img_sorted[np.clip(int(len(img_sorted)*\n whitepoint_ignore_frac),\n 0, len(img_sorted)-1)]\n gamma = 0.5\n\n print('***', blackpoint, whitepoint, gamma)\n # The +0 forces a copy - necessary for PIL\n scaled_mosaic = np.cast['int8'](ImageDisp.scale_image(img, blackpoint,\n whitepoint,\n gamma))[::-1,:]+0\n pil_img = Image.frombuffer('L', (scaled_mosaic.shape[1],\n scaled_mosaic.shape[0]),\n scaled_mosaic, 'raw', 'L', 0, 1)\n\n pil_img.save(full_png_path, 'PNG')\n\n # Reduced mosaic for easier viewing\n scale = max(img.shape[1] // 1920, 1)\n scaled_mosaic = np.cast['int8'](ImageDisp.scale_image(img[:,::scale],\n blackpoint,\n whitepoint,\n gamma))[::-1,:]+0\n pil_img = Image.frombuffer('L', (scaled_mosaic.shape[1],\n scaled_mosaic.shape[0]),\n scaled_mosaic, 'raw', 'L', 0, 1)\n\n pil_img.save(small_png_path, 'PNG')\n\n\ndef bkgnd_paths_spec(ring_radius, radius_inner, radius_outer,\n radius_resolution, longitude_resolution,\n radial_zoom_amount, longitude_zoom_amount,\n obsid, ring_type, make_dirs=False):\n bkgnd_res_data = ('_%06d_%06d_%06d_%06.3f_%05.3f_%d_%d_1' % (\n ring_radius, radius_inner, radius_outer,\n radius_resolution, longitude_resolution,\n radial_zoom_amount, longitude_zoom_amount))\n bkgnd_dir = file_clean_join(RING_RESULTS_ROOT, 'bkgnd_'+ring_type)\n if make_dirs and not os.path.exists(bkgnd_dir):\n os.mkdir(bkgnd_dir)\n data_path = file_clean_join(bkgnd_dir, obsid+bkgnd_res_data+'-MOSAIC')\n reduced_mosaic_data_path = file_clean_join(\n bkgnd_dir,\n obsid+bkgnd_res_data+'-REDUCED-MOSAIC')\n reduced_mosaic_metadata_path = file_clean_join(\n bkgnd_dir,\n obsid+bkgnd_res_data+'-REDUCED-MOSAIC-METADATA.dat')\n bkgnd_model_path = file_clean_join(\n bkgnd_dir,\n obsid+bkgnd_res_data+'-BKGND-MODEL.npz')\n bkgnd_metadata_path = file_clean_join(\n bkgnd_dir,\n obsid+bkgnd_res_data+'-BKGND-METADATA.dat')\n\n return (reduced_mosaic_data_path, reduced_mosaic_metadata_path,\n bkgnd_model_path, bkgnd_metadata_path)\n\ndef bkgnd_paths(arguments, obsid, make_dirs=False):\n return bkgnd_paths_spec(arguments.ring_radius,\n arguments.radius_inner_delta,\n arguments.radius_outer_delta,\n arguments.radius_resolution,\n arguments.longitude_resolution,\n arguments.radial_zoom_amount,\n arguments.longitude_zoom_amount,\n obsid, arguments.ring_type,\n make_dirs=make_dirs)\n\ndef bkgnd_sub_mosaic_paths_spec(ring_radius, radius_inner, radius_outer,\n radius_resolution, longitude_resolution,\n radial_zoom_amount, longitude_zoom_amount,\n obsid, ring_type, make_dirs=False):\n bkgnd_res_data = ('_%06d_%06d_%06d_%06.3f_%05.3f_%d_%d_1' % (\n ring_radius, radius_inner, radius_outer,\n radius_resolution, longitude_resolution,\n radial_zoom_amount, longitude_zoom_amount))\n bkgnd_dir = file_clean_join(RING_RESULTS_ROOT,\n 'bkgnd_sub_mosaic_'+ring_type)\n if make_dirs and not os.path.exists(bkgnd_dir):\n os.mkdir(bkgnd_dir)\n data_path = file_clean_join(bkgnd_dir,\n obsid+bkgnd_res_data+'-BKGND-SUB-MOSAIC.npz')\n metadata_path = file_clean_join(\n bkgnd_dir,\n obsid+bkgnd_res_data+'-BKGND-SUB-METADATA.dat')\n\n return (data_path, metadata_path)\n\ndef bkgnd_sub_mosaic_paths(arguments, obsid, make_dirs=False):\n return bkgnd_sub_mosaic_paths_spec(arguments.ring_radius,\n arguments.radius_inner_delta,\n arguments.radius_outer_delta,\n arguments.radius_resolution,\n arguments.longitude_resolution,\n arguments.radial_zoom_amount,\n arguments.longitude_zoom_amount,\n obsid, arguments.ring_type,\n make_dirs=make_dirs)\n\ndef write_bkgnd(model_filename, model, metadata_filename, bkgnddata):\n np.savez_compressed(model_filename, data=model.data, mask=ma.getmaskarray(model))\n\n bkgnd_metadata_fp = open(metadata_filename, 'wb')\n bkgnd_data = (bkgnddata.row_cutoff_sigmas, bkgnddata.row_ignore_fraction,\n bkgnddata.row_blur,\n bkgnddata.ring_lower_limit, bkgnddata.ring_upper_limit,\n bkgnddata.column_cutoff_sigmas,\n bkgnddata.column_inside_background_pixels,\n bkgnddata.column_outside_background_pixels,\n bkgnddata.degree)\n bkgnd_data = pickle.dump(bkgnd_data, bkgnd_metadata_fp)\n bkgnd_metadata_fp.close()\n\ndef write_bkgnd_sub_mosaic(mosaic_filename, img, metadata_filename, bkgnddata):\n np.savez_compressed(mosaic_filename, data=img, mask=bkgnddata.bkgnd_model_mask)\n\n metadata = {}\n metadata['ring_lower_limit'] = bkgnddata.ring_lower_limit\n metadata['ring_upper_limit'] = bkgnddata.ring_upper_limit\n metadata['radius_resolution'] = bkgnddata.radius_resolution\n metadata['longitude_resolution'] = bkgnddata.longitude_resolution\n metadata['long_mask'] = bkgnddata.long_mask\n metadata['image_number'] = bkgnddata.image_numbers\n metadata['time'] = bkgnddata.ETs\n metadata['mean_emission'] = bkgnddata.emission_angles\n metadata['mean_incidence'] = bkgnddata.incidence_angle\n metadata['mean_phase'] = bkgnddata.phase_angles\n metadata['mean_radial_resolution'] = bkgnddata.radial_resolutions\n metadata['mean_angular_resolution'] = bkgnddata.angular_resolutions\n metadata['longitudes'] = bkgnddata.longitudes\n metadata['obsid_list'] = bkgnddata.obsid_list\n metadata['image_name_list'] = bkgnddata.image_name_list\n metadata['image_path_list'] = bkgnddata.image_path_list\n metadata['repro_path_list'] = bkgnddata.repro_path_list\n\n mosaic_metadata_fp = open(metadata_filename, 'wb')\n mosaic_metadata_fp.write(msgpack.packb(\n metadata, default=msgpack_numpy.encode))\n mosaic_metadata_fp.close()\n\ndef read_bkgnd_metadata(metadata_filename, bkgnddata):\n print(metadata_filename)\n bkgnd_metadata_fp = open(metadata_filename, 'rb')\n bkgnd_data = pickle.load(bkgnd_metadata_fp)\n (bkgnddata.row_cutoff_sigmas, bkgnddata.row_ignore_fraction, bkgnddata.row_blur,\n bkgnddata.ring_lower_limit, bkgnddata.ring_upper_limit, bkgnddata.column_cutoff_sigmas,\n bkgnddata.column_inside_background_pixels, bkgnddata.column_outside_background_pixels, bkgnddata.degree) = bkgnd_data\n bkgnd_metadata_fp.close()\n\n\ndef bkgnd_png_path_spec(ring_radius, radius_inner, radius_outer,\n radius_resolution, longitude_resolution,\n radial_zoom_amount, longitude_zoom_amount,\n obsid, ring_type, png_type, make_dirs=False):\n bkgnd_res_data = ('_%06d_%06d_%06d_%06.3f_%05.3f_%d_%d' % (\n ring_radius, radius_inner, radius_outer,\n radius_resolution, longitude_resolution,\n radial_zoom_amount, longitude_zoom_amount))\n png_dir = file_clean_join(RING_RESULTS_ROOT,\n 'png_bkgnd_'+png_type+'_'+ring_type)\n if make_dirs and not os.path.exists(png_dir):\n os.mkdir(png_dir)\n png_path = file_clean_join(png_dir,\n obsid+bkgnd_res_data+'-bkgnd-'+png_type+'.png')\n return png_path\n\ndef bkgnd_png_path(arguments, obsid, png_type, make_dirs=False):\n return bkgnd_png_path_spec(arguments.ring_radius,\n arguments.radius_inner_delta,\n arguments.radius_outer_delta,\n arguments.radius_resolution,\n arguments.longitude_resolution,\n arguments.radial_zoom_amount,\n arguments.longitude_zoom_amount,\n obsid, arguments.ring_type,\n png_type,\n make_dirs=make_dirs)\n\ndef ew_paths_spec(ring_radius, radius_inner, radius_outer,\n radius_resolution, longitude_resolution,\n radial_zoom_amount, longitude_zoom_amount,\n obsid, ring_type, make_dirs=False):\n ew_res_data = ('_%06d_%06d_%06d_%06.3f_%05.3f_%d_%d_1' % (\n ring_radius, radius_inner, radius_outer,\n radius_resolution, longitude_resolution,\n radial_zoom_amount, longitude_zoom_amount))\n ew_dir = file_clean_join(RING_RESULTS_ROOT, 'ew_'+ring_type)\n if make_dirs and not os.path.exists(ew_dir):\n os.mkdir(ew_dir)\n data_path = file_clean_join(ew_dir, obsid+ew_res_data)\n metadata_path = file_clean_join(ew_dir, obsid+ew_res_data+'-METADATA.dat')\n\n return data_path, metadata_path\n\ndef ew_paths(arguments, obsid, make_dirs=False):\n return ew_paths_spec(arguments.ring_radius,\n arguments.radius_inner_delta,\n arguments.radius_outer_delta,\n arguments.radius_resolution,\n arguments.longitude_resolution,\n arguments.radial_zoom_amount,\n arguments.longitude_zoom_amount,\n obsid, arguments.ring_type,\n make_dirs=make_dirs)\n\ndef write_ew(ew_filename, ew, ew_metadata_filename, ew_metadata):\n np.save(ew_filename, ew)\n\n ew_metadata_fp = open(ew_metadata_filename, 'wb')\n pickle.dump(ew_metadata, ew_metadata_fp)\n ew_metadata_fp.close()\n\n\n################################################################################\n#\n# F Ring computations\n#\n################################################################################\n\nROTATING_ET = julian.tdb_from_tai(julian.tai_from_iso(\"2007-01-01\"))\nFRING_MEAN_MOTION = 581.964\nFRING_A = 140221.3\nFRING_E = 0.00235\nFRING_W0_DEG = 24.2\nFRING_DW_DEGDAY = 2.70025\n\ndef f_ring_longitude_shift(img_ET):\n return - (FRING_MEAN_MOTION * ((img_ET - ROTATING_ET) / 86400.)) % 360.\n\ndef f_ring_inertial_to_corotating(longitude, ET):\n return (longitude + f_ring_longitude_shift(ET)) % 360.\n\ndef f_ring_corotating_to_inertial(co_long, ET):\n return (co_long - f_ring_longitude_shift(ET)) % 360.\n\ndef f_ring_corotating_to_true_anomaly(co_long, ET):\n curly_w = FRING_W0_DEG + FRING_DW_DEGDAY*et/86400.\n return (co_long - f_ring_longitude_shift(ET) - curly_w) % 360.\n","repo_name":"rfrenchseti/f-ring","sub_path":"mosaics/ring/ring_util.py","file_name":"ring_util.py","file_ext":"py","file_size_in_byte":33259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"9404006684","text":"import boto3\nfrom botocore.exceptions import ClientError\n\ndef get_client(aws_access_key_id,aws_secret_access_key):\n client = boto3.client(\n 'ec2',\n aws_access_key_id=aws_access_key_id,\n aws_secret_access_key=aws_secret_access_key,\n region_name='ap-northeast-2'\n )\n\n return client\n\ndef get_all_security_group_rules(client):\n try:\n response = client.describe_security_group_rules()\n return response\n except ClientError as e:\n raise e\n\ndef find_sg_has_MZ_office_ip(security_group_rules):\n target_ip_list = [\"target_ip\"]\n has_mz_office_sg_list = []\n for security_group_rule in security_group_rules['SecurityGroupRules']:\n ret = {}\n cidr = security_group_rule.get(\"CidrIpv4\", None)\n if cidr and cidr in target_ip_list:\n ret['GroupId'] = security_group_rule['GroupId']\n ret['SecurityGroupRuleId'] = security_group_rule['SecurityGroupRuleId']\n ret['IpProtocol'] = security_group_rule['IpProtocol']\n ret['FromPort'] = security_group_rule['FromPort']\n ret['ToPort'] = security_group_rule['ToPort']\n ret['CidrIpv4'] = security_group_rule['CidrIpv4']\n has_mz_office_sg_list.append(ret)\n\n return has_mz_office_sg_list\n\ndef revoke_ingress_rule(client, group_id, rule_id):\n try:\n response = client.revoke_security_group_ingress(\n GroupId=group_id,\n SecurityGroupRuleIds=[rule_id]\n )\n print(response)\n except ClientError as e:\n raise e\n\nclient = get_client(\"api\", \"secret\")\n\nsecurity_group_rules = get_all_security_group_rules(client)\ndelete_list = find_sg_has_MZ_office_ip(security_group_rules)\n\nprint(delete_list)\n\n# for list in delete_list:\n# revoke_ingress_rule(client,list['GroupId'],list['SecurityGroupRuleId'])","repo_name":"GeunjeLEE/lee_infra_archive","sub_path":"scripts/python/update_sg/delete_ingress_rule.py","file_name":"delete_ingress_rule.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"12216035746","text":"import cv2 as cv\r\n\r\nimg1 = cv.imread('saw1.jpg', 0)\r\nsift = cv.SIFT_create()\r\nbf = cv.BFMatcher(cv.NORM_L2, crossCheck=True)\r\n\r\nkey_points1, descriptors1 = sift.detectAndCompute(img1, None)\r\n\r\n\r\ndef get_descriptors(img2):\r\n key_points2, descriptors2 = sift.detectAndCompute(img2, None)\r\n\r\n FLANN_INDEX_KDTREE = 1\r\n index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)\r\n search_params = dict(checks=50)\r\n flann = cv.FlannBasedMatcher(index_params, search_params)\r\n\r\n matches = flann.knnMatch(descriptors1, descriptors2, k=2)\r\n\r\n good = []\r\n for m, n in matches:\r\n if m.distance < 0.7 * n.distance:\r\n good.append(m)\r\n\r\n draw_params = dict(\r\n matchColor=(0, 255, 0),\r\n singlePointColor=None,\r\n matchesMask=None,\r\n flags=2\r\n )\r\n\r\n img3 = cv.drawMatches(img1, key_points1, img2, key_points2, good, None, **draw_params)\r\n scale_percent = 20\r\n width = int(img3.shape[1] * scale_percent / 100)\r\n height = int(img3.shape[0] * scale_percent / 100)\r\n dim = (width, height)\r\n img3 = cv.resize(img3, dim, interpolation=cv.INTER_AREA)\r\n return img3\r\n\r\n\r\nfor i in range(2, 5):\r\n img2 = cv.imread(f'saw{i}.jpg', 0)\r\n img3 = get_descriptors(img2)\r\n\r\n cv.imshow(f\"saw{i}\", img3)\r\n cv.waitKey(0)\r\n cv.destroyAllWindows()\r\n\r\nvideo = cv.VideoCapture('sawmovie.mp4')\r\nret, frame = video.read()\r\n\r\ni = 0\r\nwhile ret:\r\n i += 1\r\n if i < 50:\r\n ret, frame = video.read()\r\n continue\r\n key = cv.waitKey(1)\r\n frame = get_descriptors(frame)\r\n cv.imshow(\"sawmovie.mp4\", frame)\r\n if key == ord('q'):\r\n break\r\n ret, frame = video.read()\r\n\r\nvideo.release()\r\ncv.destroyAllWindows()","repo_name":"AndrieievDmytro/saw_detection","sub_path":"descriptors.py","file_name":"descriptors.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"10379198834","text":"class Solution:\n def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n # Solved using binary search and two-pointers\n \n left, right = 0, len(arr) - 1\n res = []\n \n while(left <= right):\n mid = left + (right - left) // 2\n if arr[mid] == x:\n break\n elif arr[mid] < x:\n left = mid + 1\n else:\n right = mid - 1\n \n # Setting up pointers to be close to the element\n if mid == 0: \n left = mid\n right = mid + 1\n else:\n left = mid - 1\n right = mid\n \n \n # Two pointers; Checks low and high doesn't exit bounds\n while k > 0 and left >= 0 and right < len(arr):\n if abs(arr[left] - x) <= abs(arr[right] - x):\n res.append(arr[left])\n left -= 1\n else:\n res.append(arr[right])\n right += 1\n\n k -= 1\n \n # When left side is left and right is exhausted\n while k > 0 and left >= 0:\n res.append(arr[left])\n left -= 1\n k -= 1\n \n # When right side is left and left is exhausted\n while k > 0 and right < len(arr):\n res.append(arr[right])\n right += 1\n k -= 1\n\n return sorted(res)\n","repo_name":"teltorob/leetcode","sub_path":"findKNearestElement.py","file_name":"findKNearestElement.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"24659001964","text":"\"\"\" find out the position of \">\" in a list map \"\"\"\r\ndef heropos(level,herotile=\">\"):\r\n selected = [-1,-1] #find hero\r\n for row in level:\r\n selected[0] += 1\r\n selected[1] = -1\r\n for subtile in row:\r\n selected[1] += 1\r\n if subtile == herotile:\r\n return selected[:]\r\n \r\n\"\"\" a quick tool to remove duplicate items in a list \"\"\"\r\ndef remdupli(x):\r\n output = list()\r\n for i in x:\r\n if i not in output:\r\n output.append(i)\r\n return output\r\n\r\n\r\n\"\"\" an algorith that searches all possible tiles reachable with the vision variable \r\n (expand variable is for higher precision) \"\"\"\r\ndef visible(level,position,vision,walls=[\"#\"]):\r\n import copy\r\n possible_spaces = []\r\n for ray in [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]]:\r\n cursor = position[:]\r\n hitwall = False\r\n for cycle in range(vision):\r\n if not hitwall:\r\n cursor[0] += ray[0]\r\n cursor[1] += ray[1]\r\n if level[cursor[0]][cursor[1]] not in walls:\r\n cursor_copy = copy.deepcopy(cursor)\r\n possible_spaces.append(cursor_copy)\r\n else:\r\n hitwall = True\r\n \r\n for rays in [[[-1,1 ],[-1,0 ]],[[-1,1 ],[0 ,1 ]],[[1 ,1 ],[0 ,1 ]],[[1 ,1 ],[1 ,0 ]],\r\n [[1 ,-1],[1 ,0 ]],[[1 ,-1],[0 ,-1]],[[-1,-1],[0 ,-1]],[[-1,-1],[-1,0 ]]]:\r\n cursor = position[:]\r\n hitwall = False\r\n for cycle in range(vision//2):\r\n if not hitwall:\r\n cursor[0] += rays[0][0]\r\n cursor[1] += rays[0][1]\r\n if level[cursor[0]][cursor[1]] not in walls and hitwall == False:\r\n cursor_copy = copy.deepcopy(cursor)\r\n possible_spaces.append(cursor_copy)\r\n cursor[0] += rays[1][0]\r\n cursor[1] += rays[1][1]\r\n if level[cursor[0]][cursor[1]] not in walls and hitwall == False:\r\n cursor_copy = copy.deepcopy(cursor)\r\n possible_spaces.append(cursor_copy)\r\n else:\r\n hitwall = True\r\n else:\r\n hitwall = True\r\n \r\n for i in range(2): #for higher precision, mostly unused | remove for 0.03s faster code\r\n for seeing in possible_spaces:\r\n for combine in [[1,1],[1,-1],[-1,1],[-1,-1]]:\r\n seeing\r\n if [seeing[0]+combine[0],seeing[1]+combine[1]] in possible_spaces:\r\n \r\n if level[seeing[0]+combine[0]][seeing[1]] not in walls and [seeing[0]+combine[0],seeing[1]] not in possible_spaces:\r\n possible_spaces.append([seeing[0]+combine[0],seeing[1]])\r\n if level[seeing[0]][seeing[1]+combine[1]] not in walls and [seeing[0],seeing[1]+combine[1]] not in possible_spaces:\r\n possible_spaces.append([seeing[0],seeing[1]+combine[1]])\r\n \r\n possible_spaces.remove(position)\r\n possible_spaces = remdupli(possible_spaces)\r\n \r\n return possible_spaces\r\n\r\n\"\"\" uses an algorith to find out where a player can step \"\"\"\r\ndef movingrange(level,position,steps):\r\n output = list()\r\n for i in [[position[0]-1,position[1]],[position[0]-1,position[1]+1],\r\n [position[0],position[1]+1],[position[0]+1,position[1]+1],\r\n [position[0]+1,position[1]],[position[0]+1,position[1]-1],\r\n [position[0],position[1]-1],[position[0]-1,position[1]-1]]:\r\n if level[i[0]][i[1]] != \"#\":\r\n output.append(i)\r\n movedto = output[:]\r\n \r\n for step in range(steps-1):\r\n movedto = output[:]\r\n for tile in movedto:\r\n output = remdupli(output)\r\n if tile[0]<0 or tile[1]<0 or tile[0]>15 or tile[1]>15:\r\n movedto.remove(tile)\r\n output.remove(tile)\r\n else:\r\n for direction in [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]]:\r\n if level[tile[0]+direction[0]][tile[1]+direction[1]] != \"#\" and []==[\r\n ]and level[tile[0]][tile[1]] != \"#\" and []==[\r\n ]and [tile[0]+direction[0],tile[1]+direction[1]] not in movedto:\r\n output.append([tile[0]+direction[0],tile[1]+direction[1]])\r\n \r\n \r\n output = remdupli(output)\r\n try:\r\n output.remove(position)\r\n except:\r\n pass\r\n \r\n return output","repo_name":"thesadru/gemcrawler","sub_path":"gc_tools.py","file_name":"gc_tools.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18107980405","text":"from PyQt5 import QtCore, QtGui, QtWidgets\r\nfrom OtherWindow import Ui_OtherWindow\r\nfrom acpx import Ui_OtherWind\r\nfrom PyQt5.QtWidgets import QWidget,QPushButton,QInputDialog,QLineEdit,QApplication\r\n\r\nclass Ui_MainWindow(object):\r\n def openWind(self):\r\n self.wind=QtWidgets.QMainWindow()\r\n self.ui= Ui_OtherWind()\r\n self.ui.setupUi(self.wind)\r\n self.wind.show()\r\n def openWindow(self):\r\n self.window=QtWidgets.QMainWindow()\r\n self.ui= Ui_OtherWindow()\r\n self.ui.setupUi(self.window)\r\n self.window.show()\r\n def setupUi(self, MainWindow):\r\n MainWindow.setObjectName(\"MainWindow\")\r\n MainWindow.setStyleSheet(\" background-color:rgb(0,85,127) ;\")\r\n MainWindow.resize(507, 405)\r\n MainWindow.setWindowOpacity(1.0)\r\n MainWindow.setAutoFillBackground(True)\r\n self.centralwidget = QtWidgets.QWidget(MainWindow)\r\n self.centralwidget.setObjectName(\"centralwidget\")\r\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton.setEnabled(True)\r\n self.pushButton.setGeometry(QtCore.QRect(10, 10, 221, 50))\r\n self.pushButton.setObjectName(\"pushButton\")\r\n self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton_2.setGeometry(QtCore.QRect(10, 70, 221, 50))\r\n self.pushButton_2.setObjectName(\"pushButton_2\")\r\n self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton_3.setGeometry(QtCore.QRect(10, 130, 221, 50))\r\n self.pushButton_3.setObjectName(\"pushButton_3\")\r\n self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton_4.setGeometry(QtCore.QRect(10, 190, 221, 50))\r\n self.pushButton_4.setObjectName(\"pushButton_4\")\r\n self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton_5.setGeometry(QtCore.QRect(10, 250, 221, 50))\r\n icon = QtGui.QIcon.fromTheme(\"\\\\\")\r\n self.pushButton_5.setIcon(icon)\r\n self.pushButton_5.setObjectName(\"pushButton_5\")\r\n self.openGLWidget = QtWidgets.QOpenGLWidget(self.centralwidget)\r\n self.openGLWidget.setGeometry(QtCore.QRect(-60, 470, 300, 200))\r\n self.openGLWidget.setObjectName(\"openGLWidget\")\r\n self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget)\r\n self.textBrowser.setGeometry(QtCore.QRect(240, 10, 256, 331))\r\n self.textBrowser.setObjectName(\"textBrowser\")\r\n self.pushButton_6 = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton_6.setGeometry(QtCore.QRect(10, 310, 221, 50))\r\n self.pushButton_6.setObjectName(\"pushButton_6\")\r\n MainWindow.setCentralWidget(self.centralwidget)\r\n self.menubar = QtWidgets.QMenuBar(MainWindow)\r\n self.menubar.setGeometry(QtCore.QRect(0, 0, 507, 21))\r\n self.menubar.setObjectName(\"menubar\")\r\n MainWindow.setMenuBar(self.menubar)\r\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\r\n self.statusbar.setObjectName(\"statusbar\")\r\n MainWindow.setStatusBar(self.statusbar)\r\n\r\n self.retranslateUi(MainWindow)\r\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\r\n\r\n def retranslateUi(self, MainWindow):\r\n _translate = QtCore.QCoreApplication.translate\r\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\r\n self.pushButton.setText(_translate(\"MainWindow\", \"Color Thresholding using OpenCV\"))\r\n self.pushButton_2.setText(_translate(\"MainWindow\", \"Shape detection using OpenCV\"))\r\n self.pushButton_3.setText(_translate(\"MainWindow\", \"Detection using haar-cascade\"))\r\n self.pushButton_4.setText(_translate(\"MainWindow\", \"Hough Lines detection\"))\r\n self.pushButton_5.setText(_translate(\"MainWindow\", \"Filters in OpenCV and their effect on images\"))\r\n self.textBrowser.setHtml(_translate(\"MainWindow\", \"\\n\"\r\n\"\\n\"\r\n\"

Course Project

\\n\"\r\n\"

This is our Course project for the subject Advanced Computer Programming it is based on the features of Computer Vision or OpenCV and how it makes our lives easier.

\\n\"\r\n\"


\"))\r\n self.pushButton_6.setText(_translate(\"MainWindow\", \"Tracking using OpenCV\"))\r\n self.pushButton.clicked.connect(self.on_click)\r\n self.pushButton_2.clicked.connect(self.on_click2)\r\n self.pushButton_3.clicked.connect(self.on_click3)\r\n self.pushButton_4.clicked.connect(self.on_click4)\r\n self.pushButton_5.clicked.connect(self.openWind)\r\n self.pushButton_6.clicked.connect(self.openWindow)\r\n self.pushButton.setStyleSheet(\" background-color: rgb(150, 170, 245);\")\r\n self.pushButton_3.setStyleSheet(\" background-color: rgb(150, 170, 245);\")\r\n self.pushButton_2.setStyleSheet(\" background-color: rgb(150, 170, 245);\")\r\n self.pushButton_4.setStyleSheet(\" background-color: rgb(150, 170, 245);\")\r\n self.pushButton_5.setStyleSheet(\" background-color: rgb(150, 170, 245);\")\r\n self.pushButton_6.setStyleSheet(\" background-color: rgb(150, 170, 245);\")\r\n\r\n def on_click(self):\r\n print(\"Starting Code for Color Thresholding\")\r\n exec (open(\"ct.py\").read())\r\n def on_click2(self):\r\n print(\"Starting Shape Detection for the given Input image\")\r\n exec (open(\"detect_shapes.py\").read())\r\n def on_click3(self):\r\n print(\"Starting Face Detection using Haar-Cascade\")\r\n exec (open(\"face.py\").read())\r\n def on_click4(self):\r\n print(\"Starting Striaght line Detection using Hough-Lines\")\r\n import cv2 as cv\r\n import numpy as np\r\n import matplotlib.pyplot as plt\r\n\r\n def do_canny(frame):\r\n gray = cv.cvtColor(frame, cv.COLOR_RGB2GRAY)\r\n blur = cv.GaussianBlur(gray, (5, 5), 0)\r\n canny = cv.Canny(blur, 50, 150)\r\n return canny\r\n\r\n def do_segment(frame):\r\n height = frame.shape[0]\r\n\r\n polygons = np.array([\r\n [(0, height), (800, height), (380, 290)]\r\n ])\r\n\r\n mask = np.zeros_like(frame)\r\n\r\n cv.fillPoly(mask, polygons, 255)\r\n\r\n segment = cv.bitwise_and(frame, mask)\r\n return segment\r\n\r\n def calculate_lines(frame, lines):\r\n left = []\r\n right = []\r\n\r\n for line in lines:\r\n # Reshapes line from 2D array to 1D array\r\n x1, y1, x2, y2 = line.reshape(4)\r\n # Fits a linear polynomial to the x and y coordinates and returns a vector of coefficients which describe the slope and y-intercept\r\n parameters = np.polyfit((x1, x2), (y1, y2), 1)\r\n slope = parameters[0]\r\n y_intercept = parameters[1]\r\n # If slope is negative, the line is to the left of the lane, and otherwise, the line is to the right of the lane\r\n if slope < 0:\r\n left.append((slope, y_intercept))\r\n else:\r\n right.append((slope, y_intercept))\r\n # Averages out all the values for left and right into a single slope and y-intercept value for each line\r\n left_avg = np.average(left, axis=0)\r\n right_avg = np.average(right, axis=0)\r\n # Calculates the x1, y1, x2, y2 coordinates for the left and right lines\r\n left_line = calculate_coordinates(frame, left_avg)\r\n right_line = calculate_coordinates(frame, right_avg)\r\n return np.array([left_line, right_line])\r\n\r\n def calculate_coordinates(frame, parameters):\r\n slope, intercept = parameters\r\n # Sets initial y-coordinate as height from top down (bottom of the frame)\r\n y1 = frame.shape[0]\r\n # Sets final y-coordinate as 150 above the bottom of the frame\r\n y2 = int(y1 - 150)\r\n # Sets initial x-coordinate as (y1 - b) / m since y1 = mx1 + b\r\n x1 = int((y1 - intercept) / slope)\r\n # Sets final x-coordinate as (y2 - b) / m since y2 = mx2 + b\r\n x2 = int((y2 - intercept) / slope)\r\n return np.array([x1, y1, x2, y2])\r\n\r\n def visualize_lines(frame, lines):\r\n # Creates an image filled with zero intensities with the same dimensions as the frame\r\n lines_visualize = np.zeros_like(frame)\r\n # Checks if any lines are detected\r\n if lines is not None:\r\n for x1, y1, x2, y2 in lines:\r\n # Draws lines between two coordinates with green color and 5 thickness\r\n cv.line(lines_visualize, (x1, y1), (x2, y2), (0, 255, 0), 5)\r\n return lines_visualize\r\n\r\n # The video feed is read in as a VideoCapture object\r\n cap = cv.VideoCapture(\"input.mp4\")\r\n while (cap.isOpened()):\r\n # ret = a boolean return value from getting the frame, frame = the current frame being projected in the video\r\n ret, frame = cap.read()\r\n canny = do_canny(frame)\r\n cv.imshow(\"canny\", canny)\r\n # plt.imshow(frame)\r\n # plt.show()\r\n segment = do_segment(canny)\r\n hough = cv.HoughLinesP(segment, 2, np.pi / 180, 100, np.array([]), minLineLength=100, maxLineGap=50)\r\n\r\n lines = calculate_lines(frame, hough)\r\n # Visualizes the lines\r\n lines_visualize = visualize_lines(frame, lines)\r\n cv.imshow(\"hough\", lines_visualize)\r\n\r\n output = cv.addWeighted(frame, 0.9, lines_visualize, 1, 1)\r\n\r\n cv.imshow(\"output\", output)\r\n\r\n if cv.waitKey(10) & 0xFF == ord('q'):\r\n break\r\n\r\n cap.release()\r\n cv.destroyAllWindows()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import sys\r\n app = QtWidgets.QApplication(sys.argv)\r\n MainWindow = QtWidgets.QMainWindow()\r\n ui = Ui_MainWindow()\r\n ui.setupUi(MainWindow)\r\n MainWindow.show()\r\n sys.exit(app.exec_())\r\n","repo_name":"battcheeks/CourseProject_ACP-CP-","sub_path":"acp.py","file_name":"acp.py","file_ext":"py","file_size_in_byte":10887,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"37270469702","text":"import abc\nfrom typing import Optional, Type, TypedDict\nimport sys\nfrom collections import defaultdict\nimport importlib\nfrom pathlib import Path\nimport logging\nfrom itertools import chain\n\n__all__ = ['ModuleInfo','KNCRModule','register_module']\n\nclass ModuleInfo(TypedDict):\n name:str\n scope:list[str]\n\n\nclass KNCRModule(abc.ABC):\n # @property\n @staticmethod\n def info()->ModuleInfo:\n ...\n \n def crawl(self,url:str)->str:\n ...\n\nclass Registry:\n def __init__(self) -> None:\n self._module_to_models = defaultdict(set) # dict of sets to check membership of model in module\n self._model_to_module = {} # mapping of model names to module names\n self._model_entrypoints = {} # mapping of model names to entrypoint fns\n self._hosts_to_models = {}\n\n \n @property\n def module_to_models(self):\n return self._module_to_models\n \n @property\n def hosts_to_models(self):\n return self._hosts_to_models\n\n @property\n def model_entrypoints(self):\n return self._model_entrypoints\n\n \n def register_module(self,fn):\n # lookup containing module\n mod = sys.modules[fn.__module__]\n module_name_split = fn.__module__.split('.')\n module_name = module_name_split[-1] if len(module_name_split) else ''\n\n # add model to __all__ in module\n model_name = fn.__name__\n if hasattr(mod, '__all__'):\n mod.__all__.append(model_name)\n else:\n mod.__all__ = [model_name]\n\n # add entries to registry dict/sets\n self._model_entrypoints[model_name] = fn\n self._model_to_module[model_name] = module_name\n self._module_to_models[module_name].add(model_name)\n for i in fn.info()[\"scope\"]:\n self._hosts_to_models[i]=fn\n\n return fn\n\nregistry=Registry()\nregister_module=registry.register_module\n\ndef import_modules(custom_module=None):\n modules_path = Path(__file__).parent/'modules'\n if not modules_path.exists() or not modules_path.is_dir():\n raise ImportError(\"No modules folder\")\n sys.path.insert(0, str(modules_path.absolute()))\n it=modules_path.glob(\"*\")\n if custom_module:\n custom_module=Path(custom_module)\n it=chain(it,custom_module.glob(\"*\"))\n sys.path.insert(0, str(custom_module.absolute()))\n \n # ensure that user modules are only imported once\n import_modules.memo = getattr(import_modules, \"memo\", set())\n for module_pth in it:\n if not module_pth.is_dir() and module_pth.suffix != \".zip\" and module_pth.suffix != \".py\":\n logging.warn(f\"Skip {module_pth} to load\")\n continue\n\n module_name = module_pth.stem\n module_parent = module_pth.parent.absolute()\n if module_name not in import_modules.memo:\n import_modules.memo.add(module_name)\n\n if module_name not in sys.modules:\n sys.path.insert(0, module_parent)\n importlib.import_module(module_name)\n elif str(module_pth) in sys.modules[module_name].__path__:\n logging.info(f\"{module_pth} has already been imported.\")\n else:\n raise ImportError(\n \"Failed to import {} because the corresponding module name \"\n \"({}) is not globally unique. Please rename the directory to \"\n \"something unique and try again.\".format(module_pth, module_name)\n )\n\nif __name__==\"__main__\":\n import_modules()\n print(\"called\",import_modules.memo)\n","repo_name":"Party4Bread/KoNaCrawler","sub_path":"src/konacrawler/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"30197889419","text":"from email.policy import default\nfrom sys import excepthook\nimport discord\n\nfrom data.data_grabbing import get_city\nimport utils\n\n\n# fields translations\n# the key is the raw field as it comes from the API\n# the value is the more beautiful way to show the field name\nui_fields_translations = {\n \"precipitaProb\": \"Probabilidade de precipitação\",\n \"tMin\": \"Temperatura mínima\",\n \"tMax\": \"Temperatura máxima\",\n \"predWindDir\": \"Direção do vento\",\n \"idWeatherType\": \"Estado do tempo\",\n \"classWindSpeed\": \"Classe de velocidade do vento\",\n \"forecastDate\": \"Data da previsão\"\n}\n\nfields_suffixes = {\n \"tMin\": \"º\",\n \"tMax\": \"º\",\n \"precipitaProb\": \"%\",\n}\n\n\n# Function that returns an embed discord response with the list of all the cities available at IPMA API\n# (prettifies the data to be shown)\ndef cities_list_prettify(cities_list, list_amount = 3, description=\"Lista de cidades\"):\n\n embed_response = discord.Embed(title=\"Cidades\",\n description=description,\n color=0x6FD9F8)\n\n cities_list_divided = utils.divide_big_list(cities_list, list_amount=list_amount)\n\n for i, element in enumerate(cities_list_divided):\n embed_response.add_field(name=\"Cidades\",\n value=cities_list_divided[i],\n inline=True)\n\n return embed_response\n\n\n# Function that returns an embed discord response with the weather of a city (prettifies the data to be shown)\ndef get_weather_prettify(weather_dict, city_code):\n\n embed_response = discord.Embed(title=get_city(city_code),\n description=\"Previsão do tempo\",\n color=0x6FD9F8)\n\n for key in weather_dict:\n field_translated = ui_fields_translations[key]\n embed_response.add_field(name=field_translated,\n value=handle_field_suffix(key, weather_dict[key]),\n inline=False)\n\n return embed_response\n\n\n# Function that returns an embed discord response with the help command (shows all the available commands)\ndef help_prettify(commands):\n\n embed_response = discord.Embed(title=\"Comandos disponíveis\",\n color=0x6FD9F8)\n\n commands_list = list(commands.keys())\n\n examples_list = []\n descriptions_list = []\n for command in commands_list:\n try:\n examples_list.append(commands[command][0])\n except IndexError:\n examples_list.append(\"Sem exemplo.\")\n except Exception as e:\n print(e)\n try:\n descriptions_list.append(commands[command][1])\n except IndexError:\n descriptions_list.append(\"Sem descrição\")\n except Exception as e:\n print(e)\n \n \n\n\n # values_list = list(commands.values()[0])\n\n embed_response.add_field(name=\"Comandos\",\n value=utils.list_to_string(commands_list, \"\\n\"),\n inline=True)\n\n embed_response.add_field(name=\"Exemplo\",\n value=utils.list_to_string(examples_list, \"\\n\"),\n inline=True)\n\n embed_response.add_field(name=\"Descrição\",\n value=utils.list_to_string(descriptions_list, \"\\n\"),\n inline=True)\n\n return embed_response\n\n\n# Function that returns an embed discord response with the error response (sends the error message)\ndef error_prettify(message):\n embed_response = discord.Embed(title=\"Erro\",\n color=0xFF0400)\n\n embed_response.add_field(name=\"Mensagem\",\n value=message,\n inline=False)\n\n return embed_response\n\n\n# Function that returns an embed discord response with the default message response (sends the message)\ndef default_message_prettify(message):\n embed_response = discord.Embed(title=\"Mensagem\",\n color=0x6FD9F8)\n\n embed_response.add_field(name=\"Mensagem\",\n value=message,\n inline=False)\n\n return embed_response\n\n\n# Function that returns the field with its suffix, example:\n# 20.0 to 20.0º\n# 0.0 to 0.0% (precipitaProb)\n# fields_suffixes dictionary has the keys with their suffixes\ndef handle_field_suffix(key, field_value):\n\n field_value_str = str(field_value)\n if key in fields_suffixes:\n field_value_str = field_value + fields_suffixes[key]\n\n return field_value_str\n","repo_name":"duartemelo/IPMADiscordBot","sub_path":"message/message_prettify.py","file_name":"message_prettify.py","file_ext":"py","file_size_in_byte":4701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"74894190792","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n# __author__:leezp\r\n# __date__:2019-07-04\r\n# Local: Win7 (python3)\r\n# pip install lxml\r\n# beautifulsoup教程 # https://www.jianshu.com/p/55fc16eebea4\r\n# fofa 提权高级会员\r\n\r\nimport requests\r\nfrom urllib import parse\r\nimport urllib\r\nimport base64\r\nfrom bs4 import BeautifulSoup\r\n\r\n'''\r\npython3 base64加密两种写法\r\n第一种写法:\r\nbyte_s = base64.b64encode(query_str.encode('utf-8'))\r\nquery_str_qbase64 =str(byte_s,'utf-8')\r\n第二种写法:\r\nbyte_s=base64.b64encode(query_str.encode('utf-8'))\r\n#b = str(byte_s)\r\n#print(b[2:-1])\r\n'''\r\n\r\n\r\nclass FofaSpider:\r\n def __init__(self, query_str, Cookie, Referer, X_CSRF_Token, If_None_Match):\r\n self.query_str_urlencode = urllib.parse.quote(query_str)\r\n query_str_qbase64 = str(base64.b64encode(query_str.encode('utf-8')), 'utf-8')\r\n self.query_str_qbase64_urlencode = urllib.parse.quote(query_str_qbase64)\r\n self.headers = {\r\n # 'Accept':'*/*', # OK\r\n # \"Accept\": \"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01\",# 直接复制网页的,导致网页格式出错\r\n 'Accept': 'application/ecmascript, application/x-ecmascript, */*,q=0.5',\r\n 'Accept-Encoding': 'gzip, deflate, br',\r\n 'Accept-Language': 'zh-CN,zh;q=0.9',\r\n 'Connection': 'keep-alive',\r\n 'Host': 'fofa.so',\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',\r\n 'X-Requested-With': 'XMLHttpRequest',\r\n 'If-None-Match': '%s' % (If_None_Match),\r\n 'Referer': '%s' % (Referer),\r\n 'Cookie': '%s' % (Cookie),\r\n 'X-CSRF-Token': '%s' % (X_CSRF_Token)\r\n }\r\n\r\n def file_put(self, str):\r\n with open(\"ip.txt\", \"a\", encoding='utf-8') as f:\r\n f.write(str)\r\n\r\n def spider_ip(self, url):\r\n '''\r\n 这里出了一个问题,思维阻塞了一天才发现原因。写了一个test脚本测试\r\n response = requests.get(url)\r\n soup=BeautifulSoup(response.text,'lxml')\r\n all_k = soup.find_all('div',class_=\"list_mod_t\")\r\n print (all_k)\r\n 发现不加 headers是可以打印出结果的,将headers中所有元素注释,发现可以跑出结果,\r\n 将headers中json字段逐条注释,发现 accept 字段出了问题,去掉accept字段可以打印,问题已定位\r\n 将accept 字段改为:'Accept':'*/*', 可以访问,将从目标页面复制的 accept 的value 值逐个注释,最终定位\r\n 出错的 value值:text/javascript, application/javascript, 去掉这两个value 可以打印,\r\n 经过调试,原来 'Accept':'*/*' requests.get 打印出 html 格式 数据,加上出错的value值将html数据转义,\" 变成了 \\\",\r\n 还有引起了 标签\r\n \r\n 结论 requests.get 打印出的网页 格式与 accept字段密切相关,默认打印html格式页面\r\n \r\n '''\r\n response = requests.get(url=url, headers=self.headers) \r\n soup = BeautifulSoup(response.content.decode('utf-8'), 'lxml')\r\n\r\n all_t = soup.find_all(\"div\", class_=\"list_mod_t\")\r\n all_c = soup.find_all(\"div\", class_=\"list_mod_c\")\r\n # 原理很简单,list_mod_t和list_mod_c都是10组标签,遍历,设置一个计数器,发现目标数据 记录list[count]\r\n # print(all_k)\r\n count = 0\r\n for k in all_t:\r\n num = k.find_all('a')\r\n if (\"http\" in num[0].get('href')) & (\"https\" not in num[0].get('href')):\r\n ip = num[0]['href']\r\n self.file_put(ip)\r\n text = all_c[count].find_all(\"ul\", class_=\"list_sx1\")\r\n text = text[0].find_all(\"li\")[0]\r\n title = text.text.strip() # 打印title 并去除空格\r\n self.file_put(\", \" + title + \"\\n\")\r\n count += 1\r\n\r\n # k.parent 定位会出错,用 num[0].parent\r\n # a标签父节点的下一个兄弟节点\r\n # print (num[0].parent.next_siblings) #list_iterator类型\r\n # 遍历\r\n # 通过 for迭代已知道 list_mod_c 在第二个元素,所以做个判断\r\n\r\n ''' q= 0\r\n for sibling in num[0].parent.next_siblings:\r\n if (q==1):\r\n print(sibling)\r\n soup2=BeautifulSoup(sibling.text,'lxml')\r\n all_c=soup2.findall(\"div\", class_=\"list_mod_c\")\r\n print (all_c)\r\n break\r\n q+=1'''\r\n\r\n '''\r\n for link in soup.find_all('a'):\r\n if (\"http:\" in link.get('href')):\r\n ip = link.get('href') # 等价于 ip=link[\"href\"] # '\\\"http://14.155.220.91:8443\\\"'\r\n # result = re.findall(r\"\\d+\\.\\d+\\.\\d+.\\d+(:\\d\\d\\d\\d|:\\d\\d\\d|:\\d\\d|)\", ip, re.I)\r\n self.file_put(ip + \"\\n\")\r\n '''\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # query_str 查询字符串\r\n query_str = 'app=\"用友-致远OA\"'\r\n If_None_Match = 'W/\"004099f9f8098bec5edc68de7d218055\"'\r\n X_CSRF_Token = ''\r\n Cookie = ''\r\n Referer = ''\r\n # referer_url加密:base64之后进行urlencode 再结合 result一起urlencode\r\n\r\n fofaSpider = FofaSpider(query_str, Cookie, Referer, X_CSRF_Token, If_None_Match)\r\n # 要爬取得页数,page=n+1,page = 2 则只爬取第一页\r\n page = 16\r\n for i in range(1, page):\r\n query_url = \"https://fofa.so/result?page=\" + str(\r\n i) + \"&q=\" + fofaSpider.query_str_urlencode + \"&qbase64=\" + fofaSpider.query_str_qbase64_urlencode\r\n fofaSpider.spider_ip(query_url)\r\n","repo_name":"leezp/fofaloved","sub_path":"Fofatqdemo.py","file_name":"Fofatqdemo.py","file_ext":"py","file_size_in_byte":5924,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"27"} +{"seq_id":"7909676720","text":"import re\nimport datetime\nimport parsedatetime\nimport ast\nimport copy\nimport random\nfrom dateutil.relativedelta import relativedelta\nimport json\nimport discord\nimport toml\nimport os.path\nfrom discord.ext import commands\nimport hashlib\nimport time\nimport math\nimport pytz\nimport collections\n\nconfig = {}\n\n# update in place for runtime config reload\ndef load_config():\n for k, v in toml.load(open(os.path.join(os.path.dirname(__file__), \"../config.toml\"), \"r\")).items(): config[k] = v\n\nload_config()\n\ndef timestamp(): return int(datetime.datetime.now(tz=datetime.timezone.utc).timestamp())\ndef timestamp_µs(): return int(datetime.datetime.now(tz=datetime.timezone.utc).timestamp() * 1e6)\n\nprefixes = {\n # big SI prefixes\n \"Y\": 24, \"Z\": 21, \"E\": 18, \"P\": 15, \"T\": 12, \"G\": 9, \"M\": 6, \"k\": 3, \"h\": 2, \"da\": 1,\n # small SI prefixes\n \"d\": -1, \"c\": -2, \"m\": -3, \"µ\": -6, \"μ\": -6, \"u\": -6, \"n\": -9, \"p\": -12, \"f\": -15, \"a\": -18, \"z\": -21, \"y\": -24,\n # highly dubiously useful unofficial prefixes\n \"R\": 27, \"r\": -27, \"Q\": 30, \"q\": -30, \"X\": 27, \"x\": -27, \"W\": 30, \"w\": -30\n}\nnumber = \"(-?[0-9]+(?:\\.[0-9]+)?)(\" + \"|\".join(prefixes.keys()) + \")?\"\n\ntime_units = (\n (\"galacticyears\", \"cosmicyears\", \"gy\", \"[Cc]y\"),\n (\"years\", \"y\"),\n (\"beelifespans\", \"🐝\", \"bees?\"),\n (\"months\", \"mo\"),\n (\"semesters\",),\n (\"fortnights\", \"ft?n?\"),\n (\"weeks\", \"w\"),\n (\"days\", \"d\"),\n (\"hours\", \"h\"),\n # Wikipedia tells me this is a traditional Chinese timekeeping unit\n (\"ke\",),\n (\"minutes\", \"m\"),\n (\"seconds\", \"s\"),\n (\"helloboiseconds\", \"hbseconds\", \"hbs\")\n)\n\ntu_mappings = {\n # dateutil dislikes fractional years, but this is 250My\n \"galacticyears\": (7.8892315e15, \"seconds\"),\n # apparently the average lifespan of a Western honey bee - I'm not very sure whether this is workers/drones/queens or what so TODO\n \"beelifespans\": lambda: (random.randint(122, 152), \"days\"),\n \"semesters\": (18, \"weeks\"),\n \"fortnights\": (2, \"weeks\"),\n \"ke\": (864, \"seconds\"),\n \"helloboiseconds\": (1800, \"seconds\")\n}\n\nfractional_tu_mappings = {\n \"years\": (365.25, \"days\"), # Julian year\n \"months\": (30.4375, \"days\") # average month length\n}\n\ndef rpartfor(u):\n if u[0][-1] == \"s\": \n l = [u[0] + \"?\"]\n l.extend(u[1:])\n else: l = u\n return f\"(?:(?P<{u[0]}>{number})(?:{'|'.join(l)}))?[\\t\\n\\r ]*\"\n\nshort_timedelta_regex = re.compile(\"\\n\".join(map(rpartfor, time_units)), re.VERBOSE)\n\ndef parse_prefixed(s):\n match = re.match(number, s)\n if not match: raise ValueError(\"does not match metric-prefixed integer format - ensure prefix is valid\")\n num = float(match.group(1))\n prefix = match.group(2)\n if prefix: num *= (10 ** prefixes[prefix])\n return num\n\ndef parse_short_timedelta(text):\n match = short_timedelta_regex.fullmatch(text)\n if match is None or not match.group(0): raise ValueError(\"parse failed\")\n data = { k: parse_prefixed(v) if v else 0 for k, v in match.groupdict().items() }\n for tu, mapping in tu_mappings.items():\n if callable(mapping): mapping = mapping()\n qty, resunit = mapping\n data[resunit] += qty * data[tu]\n del data[tu]\n for tu, (qty, unit) in fractional_tu_mappings.items():\n if tu in data and math.floor(data[tu]) != data[tu]:\n whole = math.floor(data[tu])\n fractional = data[tu] - whole\n data[tu] = whole\n data[unit] += fractional * qty\n return datetime.datetime.now(tz=datetime.timezone.utc) + relativedelta(**data)\n\ncal = parsedatetime.Calendar()\ndef parse_humantime(text, tz):\n dt_tuple = cal.parseDT(text, tzinfo=tz)\n if dt_tuple: return dt_tuple[0]\n else: raise ValueError(\"parse failed\")\n\ndef parse_time(text, tz):\n try: return datetime.datetime.strptime(text, \"%Y-%m-%d\")\n except: pass\n try: return parse_short_timedelta(text)\n except: pass\n try: return parse_humantime(text, tz)\n except: pass\n raise ValueError(\"time matches no available format\")\n\ndef format_time(dt):\n return dt.strftime(\"%Y-%m-%d %H:%M:%S\")\n\ntimeparts = (\n (\"y\", \"years\"),\n (\"mo\", \"months\"),\n (\"d\", \"days\"),\n (\"h\", \"hours\"),\n (\"m\", \"minutes\"),\n (\"s\", \"seconds\")\n)\n\ndef format_timedelta(from_, to):\n d = relativedelta(to, from_)\n out = \"\"\n for short, attr in timeparts:\n x = getattr(d, attr)\n if x != 0: out += str(x) + short\n return \"0s\" if out == \"\" else out\n\nCODEBLOCK_REGEX = \"^[^`]*```[a-zA-Z0-9_\\-+]*\\n(.+)```$\"\nCODELINE_REGEX = \"^[^`]*`(.*)`$\"\ndef extract_codeblock(s):\n match1 = re.match(CODEBLOCK_REGEX, s, flags=re.DOTALL)\n match2 = re.match(CODELINE_REGEX, s, flags=re.DOTALL)\n if match1: return match1.group(1)\n elif match2: return match2.group(1)\n else: return s.strip()\n\n# from https://github.com/Gorialis/jishaku/blob/master/jishaku/repl/compilation.py\nCORO_CODE = \"\"\"\nasync def repl_coroutine():\n import asyncio\n import aiohttp\n import discord\n from discord.ext import commands\n\"\"\"\nasync def async_exec(code, loc, glob):\n user_code = ast.parse(code, mode='exec')\n wrapper = ast.parse(CORO_CODE, mode='exec')\n funcdef = wrapper.body[-1]\n funcdef.body.extend(user_code.body)\n last_expr = funcdef.body[-1]\n\n if isinstance(last_expr, ast.Expr):\n funcdef.body.pop()\n funcdef.body.append(ast.Return(last_expr.value))\n ast.fix_missing_locations(wrapper)\n\n exec(compile(wrapper, \"\", \"exec\"), loc, glob)\n return await (loc.get(\"repl_coroutine\") or glob.get(\"repl_coroutine\"))()\n\ndef make_embed(*, fields=(), footer_text=None, **kwargs):\n embed = discord.Embed(**kwargs)\n for field in fields:\n if len(field) > 2:\n embed.add_field(name=field[0], value=field[1], inline=field[2])\n else:\n embed.add_field(name=field[0], value=field[1], inline=False)\n if footer_text:\n embed.set_footer(text=footer_text)\n return embed\n\ndef error_embed(msg, title=\"Error\"): return make_embed(color=config[\"colors\"][\"error\"], description=msg, title=title)\ndef info_embed(title, msg, fields=()): return make_embed(color=config[\"colors\"][\"info\"], description=msg, title=title, fields=fields)\n\n# https://github.com/LyricLy/Esobot/blob/bcc9e548c84ea9b23fc832d0b0aaa8288de64886/cogs/general.py\nlyrictable_raw = {\n \"a\": \"а\",\n \"c\": \"с\",\n \"e\": \"е\",\n \"s\": \"ѕ\",\n \"i\": \"і\",\n \"j\": \"ј\",\n \"o\": \"о\",\n \"p\": \"р\",\n \"y\": \"у\",\n \"x\": \"х\"\n }\nlyrictable = str.maketrans({v: k for k, v in lyrictable_raw.items()})\n\napioinfixes = [\"cryo\", \"pyro\", \"chrono\", \"meta\", \"anarcho\", \"arachno\", \"aqua\", \"accelero\", \"hydro\", \"radio\", \"xeno\", \"morto\", \"thanato\", \"memeto\", \n \"contra\", \"umbra\", \"macrono\", \"acantho\", \"acousto\", \"aceto\", \"acro\", \"aeolo\", \"hexa\", \"aero\", \"aesthio\", \"agro\", \"ferro\", \"alumino\",\n \"ammonio\", \"anti\", \"ankylo\", \"aniso\", \"annulo\", \"apo\", \"abio\", \"archeo\", \"argento\", \"arseno\", \"arithmo\", \"astro\", \"atlo\", \"auto\", \"axo\",\n \"azido\", \"bacillo\", \"bario\", \"balneo\", \"baryo\", \"basi\", \"benzo\", \"bismuto\", \"boreo\", \"biblio\", \"spatio\", \"boro\", \"bromo\", \"brachio\",\n \"bryo\", \"bronto\", \"calci\", \"caco\", \"carbo\", \"cardio\", \"cata\", \"iso\", \"centi\", \"ceno\", \"centro\", \"cero\", \"chalco\", \"chemo\", \"chloro\",\n \"chiono\", \"choano\", \"choro\", \"chromato\", \"chromo\", \"chryso\", \"chylo\", \"cine\", \"circum\", \"cirro\", \"climo\", \"cobalti\", \"coeno\", \"conico\",\n \"cono\", \"cortico\", \"cosmo\", \"crypto\", \"crano\", \"crystallo\", \"cyano\", \"cyber\", \"cyclo\", \"deca\", \"dendro\", \"cyno\", \"dactylo\", \"poly\", \"deutero\",\n \"dia\", \"digi\", \"diplo\", \"docosa\", \"disto\", \"dromo\", \"duo\", \"dynamo\", \"econo\", \"ecclesio\", \"echino\", \"eco\", \"ecto\", \"electro\", \"eigen\", \"eka\",\n \"elasto\", \"eicosa\", \"enviro\", \"enantio\", \"endo\", \"exo\", \"oeno\", \"femto\", \"ergato\", \"ergo\", \"etho\", \"euryo\", \"extro\", \"fluoro\", \"fructo\",\n \"galacto\", \"galvano\", \"glacio\", \"gibi\", \"glosso\", \"gluco\", \"glyco\", \"grammatico\", \"grapho\", \"gravi\", \"gyro\", \"hadro\", \"halo\", \"hapto\", \"hecto\",\n \"heli\", \"helio\", \"helico\", \"historio\", \"holo\", \"hella\", \"hemi\", \"hepta\", \"herpeto\", \"hiero\", \"hippo\", \"homo\", \"hoplo\", \"horo\", \"hyalo\", \"hyeto\",\n \"hygro\", \"hylo\", \"hypho\", \"hypno\", \"hypso\", \"iatro\", \"icthyo\", \"ichno\", \"icosa\", \"ideo\", \"idio\", \"imido\", \"info\", \"infra\", \"insta\", \"inter\",\n \"intro\", \"iodo\", \"iono\", \"irid\", \"iri\", \"iridio\", \"kilo\", \"diago\", \"juxta\", \"juridico\", \"bureaucrato\", \"entropo\", \"karyo\", \"kineto\", \"klepto\",\n \"konio\", \"kymo\", \"lamino\", \"leipdo\", \"lepto\", \"levo\", \"dextro\", \"lexico\", \"cognito\", \"ligno\", \"limno\", \"lipo\", \"litho\", \"logo\", \"magneto\",\n \"magnesio\", \"mega\", \"mento\", \"mercurio\", \"metallo\", \"mechano\", \"meco\", \"medio\", \"melo\", \"mero\", \"meso\", \"meteoro\", \"metro\", \"micto\",\n \"mono\", \"miso\", \"mnemo\", \"morpho\", \"myco\", \"myo\", \"myria\", \"mytho\", \"nano\", \"necro\", \"neo\", \"neutro\", \"neuro\", \"nitro\", \"nycto\", \"nucleo\",\n \"narco\", \"noto\", \"octo\", \"ochlo\", \"odonto\", \"oculo\", \"oligo\", \"opto\", \"organo\", \"ornitho\", \"osmio\", \"oneiro\", \"onto\", \"oxalo\", \"pachy\",\n \"paleo\", \"pali\", \"pallado\", \"pano\", \"para\", \"penta\", \"per\", \"patho\", \"pebi\", \"peloro\", \"pene\", \"petro\", \"pharma\", \"pheno\", \"philo\", \"pico\",\n \"piezo\", \"phono\", \"photo\", \"phospho\", \"physio\", \"physico\", \"phyto\", \"post\", \"pisci\", \"placo\", \"platy\", \"pleo\", \"plumbo\", \"pluto\",\n \"pneumato\", \"politico\", \"proto\", \"potassio\", \"proteo\", \"pseudo\", \"psycho\", \"ptero\", \"pykno\", \"quasi\", \"quadri\", \"recti\", \"retino\", \"retro\",\n \"rheo\", \"rhino\", \"rhizo\", \"rhodo\", \"roto\", \"rutheno\", \"saccharo\", \"sapo\", \"sauro\", \"seismo\", \"seleno\", \"septa\", \"silico\", \"scoto\", \"semanto\",\n \"sialo\", \"socio\", \"sodio\", \"skeleto\", \"somato\", \"somno\", \"sono\", \"spectro\", \"speleo\", \"sphero\", \"spino\", \"spiro\", \"sporo\", \"stanno\", \"stato\",\n \"steno\", \"stereo\", \"stegano\", \"strato\", \"hyper\", \"sulpho\", \"telluro\", \"stygo\", \"tachy\", \"tauto\", \"taxo\", \"techno\", \"tecto\", \"tele\", \"teleo\",\n \"temporo\", \"tera\", \"tetra\", \"thalasso\", \"thaumato\", \"thermo\", \"tephro\", \"tessera\", \"thio\", \"titano\", \"tomo\", \"topo\", \"tono\", \"tungsto\",\n \"turbo\", \"tyranno\", \"ultra\", \"undeca\", \"tribo\", \"trito\", \"tropho\", \"tropo\", \"uni\", \"urano\", \"video\", \"viro\", \"visuo\", \"xantho\", \"xenna\",\n \"xeri\", \"xipho\", \"xylo\", \"xyro\", \"yocto\", \"yttro\", \"zepto\", \"zetta\", \"zinco\", \"zirco\", \"zoo\", \"zono\", \"zygo\", \"templateo\", \"rustaceo\", \"mnesto\",\n \"amnesto\", \"cetaceo\", \"anthropo\", \"ioctlo\", \"crustaceo\", \"citrono\", \"apeiro\", \"Ægypto\", \"equi\", \"anglo\", \"atto\", \"ortho\", \"macro\", \"micro\", \"auro\", \n \"Australo\", \"dys\", \"eu\", \"giga\", \"Inver\", \"omni\", \"semi\", \"Scando\", \"sub\", \"super\", \"trans\", \"ur-\", \"un\", \"mid\", \"mis\", \"ante\", \"intra\"]\napiosuffixes = [\"hazard\", \"form\"]\n\ndef apioform():\n out = \"\"\n if random.randint(0, 3) == 0:\n out += random.choice(apioinfixes)\n out += \"apio\"\n i = 1\n while True:\n out += random.choice(apioinfixes)\n if random.randint(0, i) > 0: break\n i += 1\n out += random.choice(apiosuffixes)\n return out\n\ndef unlyric(text):\n return text.translate(lyrictable).replace(\"\\u200b\", \"\")\n\ndef gen_codeblock(content):\n return \"```\\n\" + content.replace(\"```\", \"\\\\`\\\\`\\\\`\")[:1900] + \"\\n```\"\n\ndef json_encode(x): return json.dumps(x, separators=(',', ':'))\n\nasync def server_mod_check(ctx):\n return ctx.channel.permissions_for(ctx.author).manage_channels or (await extpriv_check(ctx))\n\nasync def admin_check(ctx):\n return await ctx.bot.is_owner(ctx.author)\n\nasync def extpriv_check(ctx):\n return await ctx.bot.is_owner(ctx.author) or ctx.author.id in config[\"extpriv_users\"]\n\nasync def get_asset(bot: commands.Bot, identifier):\n safe_ident = re.sub(\"[^A-Za-z0-9_.-]\", \"_\", identifier)\n x = await bot.database.execute_fetchone(\"SELECT * FROM assets WHERE identifier = ?\", (safe_ident,))\n if x:\n return x[\"url\"]\n file = discord.File(os.path.join(\"./assets\", identifier), filename=safe_ident)\n message = await (bot.get_channel(config[\"image_upload_channel\"])).send(identifier, file=file)\n url = message.attachments[0].proxy_url\n await bot.database.execute(\"INSERT INTO assets VALUES (?, ?)\", (safe_ident, url))\n return url\n\ndef hashbow(thing):\n return int.from_bytes(hashlib.blake2b(thing.encode(\"utf-8\")).digest()[:3], \"little\")\n\nIDWrapper = collections.namedtuple(\"IDWrapper\", [\"id\"])\nAltCtx = collections.namedtuple(\"AltCtx\", [\"author\", \"guild\", \"bot\"])\n\nasync def user_config_lookup(ctx, cfg):\n userdata = ctx.bot.get_cog(\"Userdata\")\n if userdata is None: return\n row = await userdata.get_userdata(ctx.author.id, ctx.guild and ctx.guild.id, cfg)\n if row is None: return\n return row[\"value\"]\n\nasync def get_user_timezone(ctx):\n tzname = await user_config_lookup(ctx, \"tz\")\n if tzname:\n try:\n return pytz.timezone(tzname)\n except pytz.UnknownTimeZoneError:\n raise commands.UserInputError(f\"Invalid time zone {tzname}\")\n else:\n return pytz.utc\ndef in_timezone(dt, tz):\n # we already have an aware datetime, so return that and localized version\n if dt.tzinfo is not None: return dt, dt.astimezone(tz)\n else:\n aware = tz.localize(dt)\n return aware, aware.astimezone(pytz.utc)\n\nextensions = (\n \"reminders\",\n \"debug\",\n \"telephone\",\n \"achievement\",\n \"heavserver\",\n \"voice\",\n \"commands\",\n \"userdata\",\n \"irc_link\",\n \"search\",\n \"esoserver\"\n)\n\n# https://github.com/SawdustSoftware/simpleflake/blob/master/simpleflake/simpleflake.py\n\nSIMPLEFLAKE_EPOCH = 946702800\n#field lengths in bits\nSIMPLEFLAKE_TIMESTAMP_LENGTH = 43\nSIMPLEFLAKE_RANDOM_LENGTH = 21\n#left shift amounts\nSIMPLEFLAKE_RANDOM_SHIFT = 0\nSIMPLEFLAKE_TIMESTAMP_SHIFT = 21\n\ndef random_id():\n second_time = time.time()\n second_time -= SIMPLEFLAKE_EPOCH\n millisecond_time = int(second_time * 1000)\n randomness = random.getrandbits(SIMPLEFLAKE_RANDOM_LENGTH)\n return (millisecond_time << SIMPLEFLAKE_TIMESTAMP_SHIFT) + randomness\n\ndef chunks(source, length):\n for i in range(0, len(source), length):\n yield source[i : i+length]\n\n","repo_name":"osmarks/autobotrobot","sub_path":"src/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":13992,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"27"} +{"seq_id":"73608096073","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Dec 20 14:53:09 2019\r\n\r\n@author: Animesh\r\n\"\"\"\r\nimport cv2\r\n#import numpy as np\r\n\r\nfocal = 450.0 #focal length of camera\r\n\r\nwidth = 8.0 #width of object\r\n\r\nface_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\r\ncap = cv2.VideoCapture(0) #capture from webcam\r\n\r\ndef calculate_distance(width, focal, perWidth):\r\n return (width * focal) / perWidth\r\n\r\nwhile True:\r\n ret,img = cap.read()\r\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n faces = face_cascade.detectMultiScale(gray,1.3,5)\r\n for (x,y,w,h) in faces:\r\n new_distance = calculate_distance(width,focal,w)\r\n cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)\r\n print(new_distance /12 , \" ft\")\r\n \r\n img = cv2.resize(img,(int(img.shape[1]*2),int(img.shape[0]*2)))\r\n cv2.putText(img, \"%.2fft\"%(new_distance/12),\r\n\t(img.shape[1] - 210, img.shape[0] - 20), cv2.FONT_HERSHEY_SIMPLEX,\r\n\t\t1.5, (0, 255, 0), 3)\r\n cv2.imshow(\"img\",img)\r\n k = cv2.waitKey(30) & 0xff\r\n if k == 27:\r\n break\r\n\r\ncap.release()\r\ncv2.destroyAllWindows( )\r\n","repo_name":"asamaiya00/Real-time-distance-measurement-using-webcam","sub_path":"face_detect.py","file_name":"face_detect.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"22855158010","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import division\n\n__author__ = \"Olaf Merkert\"\n\nfrom errorrep import UnimplementedMethod\nfrom PyQt4 import QtCore, QtGui\nfrom math import log, ceil, floor\n\n\nclass MeterStack (QtGui.QWidget):\n\n types = {}\n\n def __init__(self, parent = None):\n QtGui.QWidget.__init__(self, parent = parent)\n self.layout = QtGui.QHBoxLayout()\n self.setLayout(self.layout)\n self.meters = []\n\n def create_display(self, name, type, interval=\"dynamic\", unit=\"\"):\n c = self.types[type]\n\n m = c(name=name, interval=interval, unit=unit)\n self.meters.append(m)\n self.layout.addWidget(m)\n return m\n\n @classmethod\n def register(cls, type, clss):\n cls.types[type] = clss\n return clss\n\n def show(self):\n QtGui.QWidget.show(self)\n\n\ndef downscale(x):\n \"\"\"Erniedrige x bis zur naechsten Groessenordnung\"\"\"\n if x == 0:\n return 0\n y = 10 ** floor( log(abs(x), 10) )\n return y * floor(x/y)\n\ndef upscale(x):\n \"\"\"Erhoehe x bis zur naechsten Groessenordnung\"\"\"\n if x == 0:\n return 0\n y = 10 ** floor( log(abs(x), 10) )\n return y * ceil(x/y)\n\n\nclass Display (object):\n\n def __init__(self, name, interval, unit):\n self._name = name\n # Verarbeiten der Bereichsgrenzen\n # Unterstuetzung fuer dynamische Skalierung\n if interval == \"dynamic\":\n self._dynamic = True\n self._lower, self._upper = 0, 0\n else:\n self._dynamic = False\n self._lower, self._upper = interval\n self._unit = unit\n\n def get_lower(self):\n return self._lower\n\n def get_upper(self):\n return self._upper\n\n def put(self, data):\n self._value = data\n if self._dynamic and not \\\n (self._lower <= data <= self._upper):\n self.recalc_bounds(data)\n\n def recalc_bounds(self, data):\n if self._lower > data:\n self._lower = downscale(data)\n if data > self._upper:\n self._upper = upscale(data)\n\n","repo_name":"OlafMerkert/ModellCockpit","sub_path":"displays/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"13871157691","text":"import socket\nfrom ast import literal_eval as make_tuple\nimport time\nimport random\nimport threading\nfrom threading import Thread\nfrom threading import Lock\n# import fcntl, os\nimport errno\n\n\nMCAST_GRP = '224.0.0.1'\nMCAST_PORT = 1000\nSERVICEID = 1\n\nPERIOD = 1\nMAX_ATTEMPTS = 10\n\n################################################################################\n# client sender thread code\nclass AtMostOnceSender(Thread):\n def run(self):\n global sock\n global end_lifetime\n while 1:\n # print(\"Going to sleep\")\n time.sleep(PERIOD)\n lock_lifetime.acquire()\n print ( \"end_lifetime\", end_lifetime)\n if end_lifetime == 1:\n lock_lifetime.release()\n print(\"Exiting from snder thread\")\n break\n lock_lifetime.release()\n\n lock.acquire()\n lock_received.acquire()\n # print(\"Printing list of requests to send\", requests2send)\n for request in list(requests2send.keys()):\n if (request not in requestsReceived.keys()):\n (message, attempts) = requests2send[request]\n # print(\"message \", message)\n # print(\"attempts \", attempts)\n if attempts > 0:\n # print(\"Going to send request\", request)\n # print(\"requests2send\")\n # print(requests2send)\n requests2send[request] = (message, attempts - 1)\n # requests2send[request][1] -= 1\n sock.sendto(str(message).encode(), (MCAST_GRP, MCAST_PORT))\n else:\n print(\"max attempts expired. going to reove it from sending list\")\n del requests2send[request]\n lock.release()\n lock_received.release()\n################################################################################\n\n# client sender thread code\nclass AtMostOnceReceiver(Thread):\n global sock\n def run(self):\n global end_lifetime\n while 1:\n print(\"\\tgoing to wait for an answer from server\")\n try:\n d = sock.recvfrom(1024)\n except KeyboardInterrupt:\n print(\"\\tEnding temp client\")\n break\n except OSError:\n print(\"\\tapp terminating this thread\")\n break\n\n print(\"\\tgoing to the the lock in receiver\")\n lock_lifetime.acquire()\n if end_lifetime == 1:\n lock_lifetime.release()\n print(\"\\tExiting from receiver thread\")\n break\n lock_lifetime.release()\n\n print(\"--------------------Message[\" + d[1][0] + \":\" + str(d[1][1]) + \"] : \" + d[0].decode().strip())\n (reqID, message) = make_tuple(d[0].decode())\n if message == \"There is no slave-server available\":\n print(\"There is no slave-server available\")\n continue\n lock_received.acquire()\n # print(\"Adding message that I received in requestsReceived\")\n requestsReceived[reqID] = message\n # print(\"requestsReceived:\", requestsReceived)\n # print(requestsReceived)\n lock_received.release()\n################################ APP FUNCTION ##################################\ndef app():\n global end_lifetime\n global sock\n\n block = 0\n req2wait4 = {}\n\n while 1:\n try:\n int2check = input(\"int2check: \")\n except KeyboardInterrupt:\n sock.close()\n lock_lifetime.acquire()\n print(end_lifetime)\n end_lifetime = 1\n lock_lifetime.release()\n print(\"wait for sender thread\")\n atMostOnceThread.join()\n print(\"wait for receiver thread\")\n sock.close()\n receiverThread.join()\n print(\"Ending communication...\")\n exit()\n if not int2check:\n sock.close()\n lock_lifetime.acquire()\n print(end_lifetime)\n end_lifetime = 1\n lock_lifetime.release()\n print(\"wait for sender thread\")\n atMostOnceThread.join()\n print(\"wait for receiver thread\")\n sock.close()\n\n receiverThread.join()\n print(\"Ending communication...\")\n exit()\n\n requestID = sendRequest(SERVICEID, int2check)\n req2wait4[requestID] = int2check\n\n # while req2wait4:\n for req in list(req2wait4.keys()):\n (getReplyError, answer) = getReply(req, block)\n if getReplyError == 0:\n print(\" @@@@@@@@@@@@@@ APPLICATION: \", req2wait4[req], \": \", answer)\n del req2wait4[req]\n else:\n print(\" \")\n\n\ndef sendRequest(svcid, int2check):\n # sendRequest.__dict__.setdefault('atMostOnceThread', -1)\n #\n # if sendRequest.atMostOnceThread == -1:\n # sendRequest.atMostOnceThread = AtMostOnceSender()\n # sendRequest.atMostOnceThread.start()\n\n sendRequest.__dict__.setdefault('requestID', -1)\n sendRequest.requestID += 1\n\n\n # probably won't be needed (99%)\n try:\n message2send = (svcid, sendRequest.requestID, int(int2check))\n except ValueError as verror:\n message2send = (svcid, sendRequest.requestID, int2check)\n\n lock.acquire()\n # print(\"Adding to requests2send: \", message2send)\n requests2send[sendRequest.requestID] = (message2send, MAX_ATTEMPTS)\n lock.release()\n # print(\"added \",message2send)\n return sendRequest.requestID\n\ndef getReply(requestID, block):\n if block:\n lock_received.acquire()\n while requestID not in requestsReceived:\n lock_received.release()\n # print(\"Request \", requestID , \" not found in incoming requests\")\n print(requestsReceived)\n # print()\n time.sleep(1)\n lock_received.acquire()\n\n print(\"Received \", requestID, \": \", requestsReceived[requestID])\n # print(requestID, \"has been received and will be removed from received packages\")\n returnValue = requestsReceived[requestID]\n requestsReceived.pop(requestID)\n # print(requestsReceived)\n lock_received.release()\n else:\n lock_received.acquire()\n if requestID in requestsReceived:\n returnValue = requestsReceived[requestID]\n print(\"Received \", requestID, \": \", requestsReceived[requestID])\n # print(requestID, \"has been received and will be removed from received packages\")\n requestsReceived.pop(requestID)\n # print(requestsReceived)\n lock_received.release()\n else:\n # print(\"Request \", requestID , \" not found in incoming requests\")\n # print(requestsReceived)\n lock_received.release()\n return (1, False)\n # telos diaxwrismou blocking - non blocking\n\n lock.acquire()\n if requestID in requests2send:\n # print(requestID, \"has been found in outgoing requests\")\n requests2send.pop(requestID)\n # else:\n # print(requestID, \"not found in outgoing requests\")\n print(requests2send)\n lock.release()\n return (0, returnValue)\n\n############################### SOCKET CREATION ################################\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\nsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)\n\n# fcntl.fcntl(sock, fcntl.F_SETFL, os.O_NONBLOCK)\n\nprint(\"Socket is ready\")\n\n################################################################################\n# atMostOnceThread = -1\natMostOnceThread = AtMostOnceSender()\natMostOnceThread.start()\n\nreceiverThread = AtMostOnceReceiver()\nreceiverThread.start()\n\nlock = Lock()\nlock_received = Lock()\nrequests2send = {}\nrequestsReceived = {}\nlock_lifetime = Lock()\n\nend_lifetime = 0\n\napp()\n# end_lifetime = 1\n","repo_name":"oaxelou/DistributedSystems","sub_path":"hw1/temp_client.py","file_name":"temp_client.py","file_ext":"py","file_size_in_byte":8021,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"12227791050","text":"\"\"\" Create Webex Room \"\"\"\nimport json\nimport requests\nimport pprint\n\nURL = \"https://webexapis.com/v1/rooms\"\nPAYLOAD = {\n \"title\": \"DevAsc Team Room\"\n}\nHEADERS = {\n \"Authorization\": \"Bearer OTkwODFmZjEtZDkzMS00ZGE5LWE4YWYtOWVjYTZjYWNjNmRiZmMzMmJiMDMtMzJh_PF84_1eb65fdf-9643-417f-9974-ad72cae0e10f\",\n \"Content-Type\": \"application/json\"\n}\nRESPONSE = requests.request(\"POST\", URL, data=json.dumps(PAYLOAD), headers=HEADERS)\npprint.pprint(json.loads(RESPONSE.text))\n\n","repo_name":"chrijack/devasc_crash_course","sub_path":"Cisco Infrastructure python demos/teams/create_new_room.py","file_name":"create_new_room.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"4625461099","text":"import os\nfrom yaml import load as yaml_load, FullLoader\nfrom time import sleep\nfrom pytz import timezone\nfrom redis import Redis\nfrom craigslist import CraigslistHousing\nfrom twilio.rest import Client as TwilioClient\nfrom attrdict import AttrDict\nfrom datetime import datetime, timedelta\n\nconfig = open(\"config.yml\", \"r\")\nconfig = yaml_load(config, Loader=FullLoader)\nconfig = AttrDict(config)\n\nredisClient = Redis(\n host=os.environ.get(\"REDIS_HOST\", config.redis.host),\n port=os.environ.get(\"REDIS_PORT\", config.redis.port),\n db=0,\n)\nclistClient = CraigslistHousing(\n site=config.craigslist.site,\n area=config.craigslist.area,\n filters=config.craigslist.filters,\n)\ntwilioClient = TwilioClient(config.twilio.sid, config.twilio.token)\n\n\ndef getApartmentOptions():\n results = []\n\n try:\n results = clistClient.get_results(\n sort_by=config.craigslist.search.sort_by,\n limit=config.craigslist.search.limit,\n )\n except:\n print(\"Failed to fetch posts from Craigslist.\")\n\n return results\n\n\ndef parseApartment(apartment):\n if redisClient.sismember(config.redis.key_names.seen, apartment[\"id\"]):\n return [None, None]\n\n post_id = apartment[\"id\"]\n post_name = apartment[\"name\"]\n post_cost = apartment[\"price\"]\n post_loc = apartment[\"where\"]\n post_time = apartment[\"datetime\"]\n post_url = apartment[\"url\"]\n\n message = \"-\"\n message += \"\\n\\n\" + post_name + \"\\n\\n\"\n message += \"price: %s\\n\\n\" % post_cost\n message += \"location: %s\\n\\n\" % post_loc\n message += \"posted: %s\\n\\n\" % post_time\n message += post_url\n\n return [post_id, message]\n\n\ndef sendSms(to_number, apartment_id, message_body):\n if not to_number or not apartment_id:\n return\n try:\n print(\"Sending SMS to %s for ID: %s\" % (to_number, apartment_id))\n twilioClient.messages.create(\n to=to_number, from_=config.twilio.from_number, body=message_body\n )\n\n redisClient.sadd(config.redis.key_names.seen, apartment_id)\n except:\n print(\"SMS delivery failed to %s for ID: %s\" % (to_number, apartment_id))\n\n\ndef getCurrentTime():\n tz = timezone(config.timing.timezone)\n return datetime.now(tz)\n\n\ndef getCurrentHour():\n return getCurrentTime().hour\n\n\ndef isBlackoutHours():\n blackout_start, blackout_end = (\n config.timing.blackout_start,\n config.timing.blackout_end,\n )\n currentHour = getCurrentHour()\n\n return currentHour >= blackout_start or currentHour < blackout_end\n\n\ndef hoursToSleep():\n HOURS_IN_DAY = 24\n\n currentHour = getCurrentHour()\n if currentHour >= config.timing.blackout_start:\n return HOURS_IN_DAY - currentHour + config.timing.blackout_end\n else:\n return config.timing.blackout_end - currentHour\n\n\ndef waitIntervalTime():\n sleep_time_in_seconds = config.timing.interval * 60 * 60\n sleeping_til = getCurrentTime() + timedelta(0, sleep_time_in_seconds)\n print(\"sleeping til %s...\" % sleeping_til.strftime(\"%H:%M:%S\"))\n sleep(sleep_time_in_seconds)\n\n\ndef main():\n while True:\n if isBlackoutHours():\n print(\"We are in a blackour hour!\")\n print(\"Sleeping for %d hours...\" % hoursToSleep())\n\n sleep(hoursToSleep() * 60 * 60) # seconds\n continue\n\n apartments = getApartmentOptions()\n for apartment in apartments:\n apartment_id, message_body = parseApartment(apartment)\n\n contacts = config.twilio.contacts\n for contact in config.twilio.contacts:\n number = config.twilio.contacts[contact]\n sendSms(number, apartment_id, message_body)\n\n waitIntervalTime()\n\n\nmain()\n","repo_name":"fbessez/house-hacker","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"24267805947","text":"import os\nimport openai\nimport uvicorn\nimport nltk\n\nfrom dotenv import load_dotenv\n\nfrom fastapi import FastAPI, HTTPException\n\nfrom typing import List\nfrom pydantic import BaseModel\n\nSERVER_PORT = 3001\n\nTOKEN_CHARACTER_COUNT = 4\nMAX_PROMPT_TOKENS = 1500\nMAX_SUMMARY_TOKENS = 250\n\nSUMMARY_MODEL = \"text-davinci-003\" # \"text-curie-001\"\nEMBEDDING_MODEL = \"text-embedding-ada-002\"\n\n\nclass Sentence(BaseModel):\n text: str\n embedding: List[float]\n\n\nclass Paragraph(BaseModel):\n text: str\n embedding: List[float]\n\n\nclass SummariserData(BaseModel):\n summary: List[Sentence]\n document: List[Paragraph]\n\n\nclass RequestBody(BaseModel):\n document: str\n\n\n# Download pre-trained tokeniser data (English)\nnltk.download(\"punkt\")\n\n# Load OpenAI API key from .env file\nload_dotenv()\nopenai.api_key = os.environ.get(\"OPENAI_API_KEY\")\n\n# Create FastAPI handle\nfast_api_app = FastAPI()\n\n# Approximates the number of tokens in a string\ndef approximate_tokens_count(text: str):\n return len(text) / TOKEN_CHARACTER_COUNT\n\n\n# Generates a prompt for OpenAI's completion API\ndef generate_prompt(text: str) -> str:\n return f\"Summarise the following text in 6 sentences:\\n\\nText: ###\\n{text}\\n###\"\n\n\n# Uses OpenAI's API to summarise a text\ndef summarise_text(text: str) -> str:\n summary_response = openai.Completion.create(\n model=SUMMARY_MODEL,\n prompt=generate_prompt(text),\n temperature=0.7,\n max_tokens=MAX_SUMMARY_TOKENS,\n top_p=1.0,\n frequency_penalty=0.0,\n presence_penalty=1,\n )\n\n if not summary_response.choices or not summary_response.choices[0].text:\n raise Exception(\"Request to OpenAI API returned no summary.\")\n\n return summary_response.choices[0].text.strip()\n\n\n# Uses OpenAI's API to generate embeddings for a list of strings\ndef generate_embeddings(input: List[str]) -> List[float]:\n return [\n data.embedding\n for data in openai.Embedding.create(input=input, model=EMBEDDING_MODEL).data\n ]\n\n\n# Splits a string into non-empty sentences\ndef generate_sentences(text: str) -> List[str]:\n sentences = [sentence for sentence in nltk.tokenize.sent_tokenize(text) if sentence]\n if not sentences:\n raise Exception(\"Insufficient sentence count.\")\n # If possible, remove last sentence which is likely to be incomplete\n return sentences[:-1] if (len(sentences) > 1) else sentences\n\n\n# Splits a string into non-empty paragraphs\ndef generate_paragraphs(text: str) -> List[str]:\n return [paragraph for paragraph in text.splitlines() if paragraph]\n\n\n@fast_api_app.post(\"/get-summarisation-data\")\nasync def get_summarisation_data(request_body: RequestBody):\n try:\n document = request_body.document\n\n if approximate_tokens_count(document) > MAX_PROMPT_TOKENS:\n raise ValueError(\"Document is too long.\")\n\n summary = summarise_text(document)\n summary_sentences = generate_sentences(summary)\n document_paragraphs = generate_paragraphs(document)\n\n summary_embeddings = generate_embeddings(summary_sentences)\n document_embeddings = generate_embeddings(document_paragraphs)\n\n summariser_data = SummariserData(\n summary=[\n Sentence(text=summary_sentences[i], embedding=summary_embeddings[i])\n for i in range(len(summary_sentences))\n ],\n document=[\n Paragraph(text=document_paragraphs[i], embedding=document_embeddings[i])\n for i in range(len(document_paragraphs))\n ],\n )\n\n return summariser_data\n except ValueError as e:\n raise HTTPException(status_code=422, detail=str(e))\n except Exception as e:\n raise HTTPException(status_code=500, detail=str(e))\n\n\nif __name__ == \"__main__\":\n uvicorn.run(\"main:fast_api_app\", port=SERVER_PORT, reload=True, log_level=\"info\")\n","repo_name":"Michael-JB/document-summariser","sub_path":"server/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"27856900870","text":"from collections import defaultdict\r\n\r\ndef stodict(x):\r\n\tdi = defaultdict(int)\r\n\tt = 0\r\n\twhile t < len(x):\r\n\t\tc = x[t]\r\n\t\tini = t\r\n\t\tt += 1\r\n\t\twhile t < len(x) and x[t].isdigit():\r\n\t\t\tt += 1\r\n\t\tdi[x[ini]] += int(x[ini+1:t] or '1')\r\n\treturn di\r\n\r\nx, y = input().split()\r\ndi = stodict(x)\r\ndu = stodict(input().strip())\r\nres = 10**20\r\nfor r, v in du.items():\r\n\tres = min(res, (di[r] * int(y)) // v)\r\nprint(res)\r\n","repo_name":"lmun/competitiveProgramingSolutions","sub_path":"kattis/htoo.py","file_name":"htoo.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"22304800149","text":"\r\nimport pandas as pd\r\n\r\nfrom . import DataUnit\r\n\r\n\r\nCATEGORICAL = 'categorical'\r\n\r\nclass Categorical(DataUnit):\r\n '''Discrete set of values\r\n\r\n Use for Boolean values as well\r\n - Not worth dealing with permutations\r\n - T/F\r\n - True/False\r\n - true/false\r\n - 0/1\r\n '''\r\n @staticmethod\r\n def _profile_categorical(data):\r\n # tested\r\n values = sorted(data.dropna().unique().tolist())\r\n profile = {\r\n 'values': values\r\n }\r\n return profile\r\n \r\n def profile(self, data):\r\n # wrapper to multi-inheritance exposed self._profile_categorical()\r\n return self._profile_categorical(data)\r\n\r\n \r\n @staticmethod\r\n def _verify_categorical(data, profile):\r\n # tested\r\n expected_values = profile['values']\r\n actual_values = data.unique().tolist()\r\n unexpected_values = []\r\n has_unexpected_na = False\r\n for value in actual_values:\r\n if pd.isna(value) and not profile['hasna']:\r\n has_unexpected_na = True\r\n\r\n if value not in expected_values:\r\n unexpected_values.append(value)\r\n\r\n unexpected_values = sorted([repr(i) for i in unexpected_values])\r\n\r\n error_reports = []\r\n\r\n if has_unexpected_na:\r\n msg = f'Found unexpected NaN value'\r\n error = {\r\n 'level': 'info',\r\n 'msg': msg\r\n }\r\n error_reports.append(error)\r\n\r\n if len(unexpected_values) > 0:\r\n list_values = ',\\n '.join(unexpected_values)\r\n list_msg = f'[\\n {list_values}\\n]'\r\n msg = f'Unexpected categorical values:\\n{list_msg}'\r\n error = {\r\n 'level': 'info',\r\n 'msg': msg\r\n }\r\n error_reports.append(error)\r\n \r\n return error_reports\r\n\r\n def verify(self, data, profile):\r\n # wrapper to multi-inheritance exposed self._verify_categorical()\r\n return self._verify_categorical(data, profile)\r\n","repo_name":"ltskinner/dftegridy","sub_path":"dftegridy/dunits/categorical.py","file_name":"categorical.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"3253789565","text":"#!/usr/bin/python\nimport thspace as ths\n\n\ndef _complex_concat(a, b):\n tmp = []\n for i in a:\n for j in b:\n tmp.append(i+j)\n return tmp\n\n\ndef _add_prefix(l, prefix=\"w_\"):\n return [prefix + elem for elem in l]\n\n\n# Pruning threshold setting (90 % off)\nth = ths.th90\n\n# CNN settings for pruned training\ntarget_layer = [\"fc1\", \"fc2\"]\n\n# Retrain iteration after pruning\nretrain_iterations = 10\n\n# Data settings\nshow_zero = False\n\n# Train directory\ntrain_dir = 'train'\n\n# Output data lists: do not change this\ntarget_all_layer = _add_prefix(target_layer)\n\ntarget_dat = _complex_concat(target_all_layer, [\".dat\"])\ntarget_p_dat = _complex_concat(target_all_layer, [\"_p.dat\"])\ntarget_tp_dat = _complex_concat(target_all_layer, [\"_tp.dat\"])\n\nweight_all = target_dat + target_p_dat + target_tp_dat\nsyn_all = [\"in_conv1.syn\", \"in_conv2.syn\", \"in_fc1.syn\", \"in_fc2.syn\"]\n\n# Graph settings\nalpha = 0.75\ncolor = \"green\"\npdf_prefix = \"\"\n\n","repo_name":"sh0416/pruning","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"27"} +{"seq_id":"70407090631","text":"import numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom scipy.stats import expon\n\n\n\ndef coagulation_cst(coag_proportion, N):\n prob_coag = np.zeros(2500)\n coag_cst = np.zeros(2500)\n for index in range(2500):\n index_maths = index + 1\n i = 1\n ticker = 99\n while ticker < index_maths:\n i += 1\n ticker += (101- 2*i)\n else:\n last_lower_i = i\n last_lower = ticker - (101 - 2*i)\n diff = index - last_lower\n j = diff + last_lower_i\n # print('Value check', last_lower_i, last_lower, diff, j)\n ## (i,j) now corresponds to the size of the 2 clusters to coagulate\n \n ## Diffusion based kernel\n D_i = 1/i\n D_j = 1/j\n prob_coag[index] = (D_i +D_j)\n\n ## Constant kernel\n # prob_coag[index] = 1\n\n ## Multiplicative kernel\n # prob_coag[index] = i*j\n \n sum_prob_coag = np.sum(prob_coag)\n coag_cst = coag_proportion * (prob_coag/sum_prob_coag)\n\n # plt.plot(coag_cst)\n # plt.show()\n print('Sum', np.sum(coag_cst))\n\n return coag_cst\n\n\n#\ndef shed_cst(shed_proportion, N, shed_type):\n shed_prop = np.zeros(99)\n shed_prob = np.zeros(99)\n shed_cst = np.zeros(99)\n if shed_type == 1: #Constant dependence\n for i in range(99):\n shed_prob[i] = 1/99\n if shed_type == 2: #Linear dependence\n for i in range(99):\n shed_prop[i] = i+1\n shed_sum = np.sum(shed_prop)\n for j in range(99):\n shed_prob[j] = shed_prop[j]/shed_sum\n if shed_type == 3: #Exponential dependence\n for i in range(99):\n shed_prop[i] = math.exp((i+1)/20)\n shed_sum = np.sum(shed_prop)\n for j in range(99):\n shed_prob[j] = shed_prop[j]/shed_sum\n if shed_type == 4: #Power 2/3\n for i in range(99):\n shed_prop[i] = i**(2/3)\n shed_sum = np.sum(shed_prop)\n for j in range(99):\n shed_prob[j] = shed_prop[j]/shed_sum\n\n shed_cst = shed_proportion*shed_prob\n\n return shed_cst\n\n\n\n\n#calculate probability that x is less than 50 when mean rate is 40\ndef death_cst(death_proportion, N):\n prob_an = np.zeros(N)\n prob_ap = np.zeros(N)\n prob_tot = np.zeros(N)\n death_cst = np.zeros(N)\n for i in range(1, N+1):\n prob_an[i-1] = expon.cdf(x=i, scale=40) - expon.cdf(x=i-1, scale=40)\n prob_ap[i-1] = expon.cdf(x= N - i + 1, scale=40) - expon.cdf(x= N - i + 1 - 1, scale=40)\n prob_tot[i-1] = prob_an[i-1] + prob_ap[i-1]\n sum = np.sum(prob_tot)\n\n for j in range(1, N+1):\n death_cst[j-1] = 0*(prob_tot[j-1]*death_proportion) * (1/sum)\n # Plot current death constant\n # plt.plot(death_cst)\n # plt.show()\n print('Sum death', np.sum(death_cst))\n return death_cst","repo_name":"njs59/clusters","sub_path":"gillespie/constant_functions.py","file_name":"constant_functions.py","file_ext":"py","file_size_in_byte":2836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"3692130444","text":"__version__ = \"v0.0.1\"\n\nimport logging\nfrom . import Command as C\nfrom .sumologic import SumoLogic\nfrom .Utils import merge_dicts\n\nlogger = logging.getLogger(__name__)\n\n\nclass Connection(object):\n name = None\n accessId = None\n accessKey = None\n endpoint = None\n settings = None\n encoding = None\n show_query = None\n history = None\n timeout = None\n sumo = None\n collectors = None\n\n def __init__(self, name, options, settings=None,\n commandClass='ThreadCommand'):\n self.name = name\n\n if settings is None:\n settings = {}\n\n self.settings = settings\n self.encoding = 'utf-8'\n self.accessId = options.get('accessId', None)\n self.accessKey = options.get('accessKey', None)\n self.endpoint = options.get('endpoint', None)\n self.show_query = settings.get('show_query', False)\n self.useStreams = settings.get('use_streams', False)\n\n sumo_endpoint = self.getSumoAPIEndPoint()\n\n self.sumo = SumoLogic(self.accessId, self.accessKey, sumo_endpoint)\n self.Command = getattr(C, commandClass)\n\n def __str__(self):\n return self.name\n\n def info(self):\n return 'Sumo Connection: {accessId} @ {name}'.format(\n accessId=self.accessId, name=self.name)\n\n def getSumoAPIEndPoint(self):\n protocol = 'http' if 'local' in self.endpoint else 'https'\n full_endpoint = '{protocol}://{endpoint}'.format(\n protocol=protocol, endpoint=self.endpoint)\n return full_endpoint\n\n def runInternalNamedQueryCommand(self, api_call, params, callback):\n def cb(result, params):\n callback(result, params)\n\n self.Command.createAndRun(callback=cb, sumo=self.sumo,\n api_call=api_call, params=params,\n encoding=self.encoding,\n options={'show_query': self.show_query},\n timeout=self.timeout, silenceErrors=False)\n\n def getCollectors(self, callback, params=None):\n local_params = {\"uri_name\": \"collectors\", \"json_root\": \"collectors\",\n \"results_format\": \"json\"}\n self.runInternalNamedQueryCommand(\n api_call=\"get_resources\", params= merge_dicts(master=params, slave=local_params),\n callback=callback)\n\n def getSources(self, collector_id, callback, params=None):\n local_params = {\"uri_name\": \"sources\", \"parent_uri_name\": \"collectors\",\n \"parent_uri_id\": collector_id, \"json_root\": \"sources\",\n \"results_format\": \"json\"}\n self.runInternalNamedQueryCommand(api_call=\"get_resources\",\n params= merge_dicts(slave=params, master=local_params),\n callback=callback)\n def getPartitions(self, callback, params=None):\n local_params = {\"uri_name\": \"partitions\",\n \"results_format\": \"json\", \"json_root\": \"data\"}\n\n self.runInternalNamedQueryCommand(api_call=\"get_resources\",\n params=local_params,\n callback=callback)\n\n def getUsers(self, callback, params=None):\n local_params = {\"uri_name\": \"users\",\n \"results_format\": \"json\", \"json_root\": \"data\"}\n\n self.runInternalNamedQueryCommand(api_call=\"get_resources\",\n params= merge_dicts(slave=params, master=local_params),\n callback=callback)\n\n def getRoles(self, callback, params=None):\n local_params = {\"uri_name\": \"roles\",\n \"results_format\": \"json\", \"json_root\": \"data\"}\n\n self.runInternalNamedQueryCommand(api_call=\"get_resources\",\n params=local_params,\n callback=callback)\n\n def getScheduledViews(self, callback, params=None):\n local_params = {\"uri_name\": \"scheduledViews\",\n \"results_format\": \"json\", \"json_root\": \"data\"}\n\n self.runInternalNamedQueryCommand(api_call=\"get_resources\",\n params=local_params,\n callback=callback)\n\n def getFolder(self, callback, params=None):\n local_params = {\"api_version\": \"v2\", \"uri_name\": \"content/folders\", \"uri_id\": params['request_params']['folder_type'], \"results_format\": \"json\", \"json_root\": None}\n\n self.runInternalNamedQueryCommand(api_call=\"get_resources\",\n params=merge_dicts(master=params, slave=local_params),\n callback=callback)\n\n def getContentExportJob(self, callback, params=None):\n local_params = {\"method\": \"get\", \"api_version\": \"v2\", \"parent_uri_name\": \"content\", \"results_format\": \"json\", \"json_root\": None}\n\n self.runInternalNamedQueryCommand(api_call=\"get_resources\",\n params=merge_dicts(master=params, slave=local_params),\n callback=callback)\n\n def startContentExportJob(self, callback, params=None):\n local_params = {\"method\": \"post\", \"api_version\": \"v2\", \"parent_uri_name\": \"content\",\"results_format\": \"json\", \"json_root\": None}\n\n self.runInternalNamedQueryCommand(api_call=\"get_resources\",\n params=merge_dicts(master=params, slave=local_params),\n callback=callback)\n\n\n def getFERs(self, callback, params=None):\n local_params = {\"uri_name\": \"extractionRules\",\n \"results_format\": \"json\", \"json_root\": \"data\"}\n\n self.runInternalNamedQueryCommand(api_call=\"get_resources\",\n params=local_params,\n callback=callback)\n\n def getRestValues(self, api_call=None, params=None, callback=None):\n\n self.Command.createAndRun(callback=callback, sumo=self.sumo,\n api_call=api_call, params=params,\n encoding=self.encoding,\n options={'show_query': self.show_query},\n timeout=self.timeout, silenceErrors=False)\n\n def execute(self, callback,\n params=None, stream=None):\n local_params = {\"uri_name\": \"search/jobs\", \"json_root\": None,\n \"method\": \"post\", \"results_format\": \"json\"}\n\n self.Command.createAndRun(callback=callback, sumo=self.sumo,\n api_call=\"get_resources\",\n params=merge_dicts(master=params, slave=local_params), encoding=self.encoding,\n options={'show_query': self.show_query},\n timeout=self.timeout, silenceErrors=False)\n\n def search_job_polling(self, callback, params=None):\n local_params = {\"uri_name\": \"search/jobs\",\n \"results_format\": \"json\", \"json_root\": None,\n \"method\": \"get\", \"request_params\": None}\n\n self.Command.createAndRun(callback=callback, sumo=self.sumo,\n api_call=\"get_resources\",\n params=merge_dicts(master=params, slave=local_params),\n encoding=self.encoding,\n options={'show_query': self.show_query},\n timeout=self.timeout, silenceErrors=False)\n\n def get_job_messages(self, callback, job_id, params=None):\n local_params = {\"parent_uri_name\": \"search/jobs\",\n \"parent_uri_id\": job_id, \"uri_name\": \"messages\",\n \"results_format\": \"grid\", \"json_root\": \"messages\",\n \"method\": \"get\", \"request_params\": None}\n\n self.Command.createAndRun(callback=callback, sumo=self.sumo,\n api_call=\"get_resources\",\n params=merge_dicts(master=params, slave=local_params),\n encoding=self.encoding,\n options={'show_query': self.show_query},\n timeout=self.timeout, silenceErrors=False)\n\n def get_job_records(self, callback, job_id, params=None):\n local_params = {\"parent_uri_name\": \"search/jobs\",\n \"parent_uri_id\": job_id, \"uri_name\": \"records\",\n \"results_format\": \"grid\", \"json_root\": \"records\",\n \"method\": \"get\", \"request_params\": None}\n\n self.Command.createAndRun(callback=callback, sumo=self.sumo,\n api_call=\"get_resources\",\n params=merge_dicts(master=params, slave=local_params),\n encoding=self.encoding,\n options={'show_query': self.show_query},\n timeout=self.timeout, silenceErrors=False)\n\n @staticmethod\n def setTimeout(timeout):\n Connection.timeout = timeout\n logger.info('Connection timeout set to {0} seconds'.format(timeout))\n\n @staticmethod\n def setHistoryManager(manager):\n Connection.history = manager\n size = manager.getMaxSize()\n logger.info('Connection history size is {0}'.format(size))\n","repo_name":"scrummastermind/SumoSwissKnife","sub_path":"SumoSwissKnifeAPI/Connection.py","file_name":"Connection.py","file_ext":"py","file_size_in_byte":9651,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"41387826925","text":"# -*- coding: utf-8 -*-\n\nfrom itest2.core.client import Client\nimport records\nimport logging\n\nCLIENT_TYPE = (records.Database, )\n\n\nclass DataBaseClientManage(Client):\n \"\"\"\n 数据库连接管理\n example:\n db_client_manage.create_clients(conf.databases)\n all = db_client_manage.client('moon').query('SELECT * FROM test_table LIMIT 10')\n db_client_manage.close_all()\n \"\"\"\n\n __instance = None\n clz = {}\n\n __default_headers = {}\n\n def __new__(cls, *args, **kwargs):\n if not cls.__instance:\n cls.__instance = super(DataBaseClientManage, cls).__new__(\n cls, *args, **kwargs)\n return cls.__instance\n\n def client(self, name: str) -> records.Database:\n \"\"\"\n \n :param name: \n :return:\n \"\"\"\n if name in self.__instance.__dict__.keys():\n return self.__instance.__getattribute__(name)\n else:\n logging.debug(f'database client {name} do not exist!')\n\n def create_clients(self, conn_config: list = None):\n \"\"\"\n 根据传入的配置创建records.Database\n :param conn_config: (\n {\n \"name\": \"pg\",\n \"uri\": \"postgresql://user:password@host:port/database\"\n }\n )\n :return:\n \"\"\"\n if conn_config is not None:\n for database in conn_config:\n self.create_client(database['name'], database['uri'])\n return self.__instance\n\n def create_client(self, name: str, uri: str):\n \"\"\"\n 指定名称和连接串创建records.Database\n :param name: records.Database对象名称\n :param uri: 数据库连接串\n :return:\n \"\"\"\n if name in self.__instance.__dict__.values():\n if self.__instance.__getattribute__(name).open:\n return self.__instance\n self.__instance.__setattr__(name, records.Database(uri))\n logging.debug(f'create db client: name: {name}, uri: {uri}')\n return self.__instance\n\n def close_all(self):\n for k, v in self.__instance.__dict__.items():\n if isinstance(v, CLIENT_TYPE):\n v.close()\n\n\n# 初始化一个实例\ndb_client_manage = DataBaseClientManage()\n","repo_name":"hzhang123/ITest2","sub_path":"itest2/core/database_client.py","file_name":"database_client.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"1917203964","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*- \n# filename: worklist.py\n# version: v2\n# description: sms.py\n\nfrom log import log\n\nimport nexmo\nimport time\n#from datetime import datetime\nfrom concurrent.futures import ThreadPoolExecutor\n\n\nclass sms():\n sleep = 2\n number = 16018666656\n key = 'd1258708'\n secret = 'No1secret'\n def __init__(self, phone):\n self.phone = phone\n self.list = []\n self._login()\n self.start()\n def _login(self):\n self._client = nexmo.Client(key=self.key, secret=self.secret)\n message = '登录短信客户端'\n #print(message)\n log.sms(message)\n def start(self):\n message = '开启发送短信'\n #print(message)\n log.sms(message)\n pool = ThreadPoolExecutor(max_workers=1)\n pool.submit(self.starter)\n def starter(self):\n self.status = True\n while self.status == True:\n if len(self.list) == 0:\n time.sleep(2)\n else:\n text = self.list[0]\n self._send_sms(text)\n self.list.remove(text)\n def stop(self):\n self.status = False\n message = '停止发送短信'\n #print(message)\n log.sms(message)\n def send(self, text):\n self.list.append(text)\n def _send_sms(self, text):\n c = 0\n result = None\n while result != '0':\n #print(c)\n if c == 5:\n status = '失败'\n break\n result = self._client.send_message({\n 'from': self.number,\n 'to': self.phone,\n 'text': text,\n 'type': 'unicode'\n })['messages'][0]['status']\n status = '成功'\n c += 1\n message = '发送%s:%s' % (status, text)\n #print(message)\n log.sms(message)\n def help(self):\n print('''sms.list\\nsms.send(number, text)\\n/log\n ''')\n\n\nsms = sms(16267318573)\n\nif __name__ != '__main__':\n #print('sms = sms(16267318573)')\n pass\n\n\n#sms = sms(16267318573)\n#sms.send('001')\n#sms.send('002')\n#sms.send('003')\n#sms.send('004')\n#sms.send('005')\n\n\n\n","repo_name":"tz1006/trade-temp","sub_path":"sms.py","file_name":"sms.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"406529661","text":"# Créer un programme qui parcourt le contenu du fichier “domains.xml” et qui compte le\n# nombre d’extension de domaines qui s’y trouvent (.com, .net, etc ...).\nimport re\n\nfile = open('domains.xml', 'r')\nfile2 = open('domains.xml', 'r') # triche ?\n\nnet = '.net'\ncom = '.com'\nx = re.findall(\".net\", file.read())\ny = re.findall(\".com\", file2.read())\nprint(len(x))\nprint('x')\nprint(len(y))\nprint('y')\nfile.close()\n","repo_name":"joris-verguldezoone/runtrack-python","sub_path":"jour03/job01/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19255935132","text":"from bark.util.logger import BarkLogger\nfrom pathlib import Path\n\nclass TestLoggerClass:\n\n def setup_method(self, method):\n if Path.exists(Path('test.log')):\n os.remove(\"test.log\")\n\n def teardown_method(self, method):\n if Path.exists(Path('test.log')):\n os.remove(\"test.log\")\n\n def test_debug(self, caplog):\n logger = BarkLogger(__file__)\n logger.debug('TEST DEBUG MESSAGE')\n for record in caplog.records:\n assert record.levelname == 'DEBUG'\n assert record.message == 'TEST DEBUG MESSAGE'\n\n def test_error(self, caplog):\n logger = BarkLogger(__file__)\n logger.error('TEST ERROR MESSAGE')\n for record in caplog.records:\n assert record.levelname == 'ERROR'\n assert record.message == 'TEST ERROR MESSAGE'\n\n def test_info(self, caplog):\n logger = BarkLogger(__file__)\n logger.info('TEST INFO MESSAGE')\n for record in caplog.records:\n assert record.levelname == 'INFO'\n assert record.message == 'TEST INFO MESSAGE'\n","repo_name":"jfm/bark","sub_path":"tests/logger_test.py","file_name":"logger_test.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"18298101636","text":"\"\"\"Unit tests for the ``architectures`` paths.\"\"\"\n\nfrom fauxfactory import gen_string\nfrom nailgun import entities\nfrom requests.exceptions import HTTPError\nfrom robottelo.test import APITestCase\n\n\nclass Architectures(APITestCase):\n \"\"\"Tests for the ``architectures`` path.\"\"\"\n\n def test_positive_create(self):\n \"\"\"@Test: Create an architecture providing the initial name.\n\n @Assert: Architecture is created and contains provided name.\n\n @Feature: Architecture\n\n \"\"\"\n name = gen_string('utf8', 30)\n arch = entities.Architecture(name=name).create()\n self.assertEqual(name, arch.name)\n\n def test_negative_create(self):\n \"\"\"@Test: Create architecture providing an invalid initial name.\n set.\n\n @Assert: Architecture is not created\n\n @Feature: Architecture\n\n \"\"\"\n with self.assertRaises(HTTPError):\n entities.Architecture(name=gen_string('utf8', 300)).create()\n\n def test_positive_update(self):\n \"\"\"@Test: Create architecture then update its name to another\n valid name.\n\n @Assert: Architecture is created, and its name can be updated.\n\n @Feature: Architecture\n\n \"\"\"\n arch = entities.Architecture().create()\n\n new_name = gen_string('utf8', 30)\n updated = entities.Architecture(\n id=arch.id, name=new_name).update(['name'])\n self.assertEqual(new_name, updated.name)\n self.assertNotEqual(arch.name, updated.name)\n\n def test_negative_update(self):\n \"\"\"@Test: Create architecture then update its name to an invalid name.\n\n @Assert: architecture is created, and its name is not updated.\n\n @Feature: Architecture\n\n \"\"\"\n arch = entities.Architecture().create()\n name = arch.name\n new_name = gen_string('utf8', 300)\n with self.assertRaises(HTTPError):\n entities.Architecture(\n id=arch.id, name=new_name).update(['name'])\n arch = entities.Architecture(id=arch.id).read()\n self.assertNotEqual(arch.name, new_name)\n self.assertEqual(name, arch.name)\n\n def test_positive_delete(self):\n \"\"\"@Test: Create architecture and then delete it.\n\n @Assert: architecture is successfully deleted.\n\n @Feature: Architecture\n\n \"\"\"\n arch = entities.Architecture().create()\n arch.delete()\n with self.assertRaises(HTTPError):\n entities.Architecture(id=arch.id).read()\n","repo_name":"omaciel/satellite-tests","sub_path":"tests/crud/api/test_architecture.py","file_name":"test_architecture.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"26717142407","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\ndef solve(x, y):\r\n global cnt\r\n while stack and y < stack[-1][1]:\r\n cnt += 1\r\n stack.pop()\r\n if not stack or stack[-1][1] != y:\r\n stack.append((x, y))\r\n\r\nN = int(input())\r\nstack = []\r\ncnt = 0\r\n\r\nfor _ in range(N):\r\n x, y = map(int, input().split())\r\n solve(x, y)\r\n\r\nwhile stack:\r\n if stack[-1][1] > 0:\r\n cnt += 1\r\n stack.pop()\r\n\r\nprint(cnt)","repo_name":"tnpfldyd/TIL","sub_path":"백준/Gold/1863. 스카이라인 쉬운거/스카이라인 쉬운거.py","file_name":"스카이라인 쉬운거.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"14198573737","text":"# Python 3 -- Decision Making\r\n# Consider one vaiable a = 50\r\n\r\n# if Statement\r\n\r\na = 50\r\nif (a >= 50):\r\n print(\"Student is Passed with Grade C\")\r\nelse:\r\n print(\"Student is failed\")\r\n\r\n# Example\r\n\r\namount = int (input (\"Enter the Amount:\"))\r\n\r\nif amount <= 1000:\r\n discount = amount * 0.05\r\n print (\"Discount is\",discount)\r\nelse:\r\n discount = amount * 0.10\r\n print(\"Discount is \", discount)\r\n\r\nprint(\"Total Amount to Pay is here:\", amount - discount)\r\n\r\n# Example if else \r\n\r\n# if the user ammount is > = 10000 provide 20 % discount else\r\n # 10 %\r\n\r\namt = int (input (\"Please enter the amount:\" ))\r\nif amt >= 10000:\r\n dcount = amt * 0.20\r\n print(\"Discount amount is:\", dcount)\r\nelse:\r\n dcount= amt * 0.10\r\n print(\"Discount amount is :\", dcount)\r\n\r\nprint(\"Total amount after Discount:\", amount-dcount)\r\n \r\n# Example if elif\r\n\r\namount=int(input(\"Enter amount: \"))\r\nif amount<1000:\r\n discount=amount*0.05\r\n print (\"Discount\",discount)\r\nelif amount<5000:\r\n discount=amount*0.10\r\n print (\"Discount\",discount)\r\nelse:\r\n discount=amount*0.15\r\n print (\"Discount\",discount)\r\n \r\nprint (\"Net payable:\",amount-discount)\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n","repo_name":"ergowherm/Python","sub_path":"If_Else Statements.py","file_name":"If_Else Statements.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"72411402632","text":"from dataset.SUBJ_2004.utils import *\r\n\r\nvocab_size = 23906\r\nembedding_dim = 300\r\nmax_len = 64\r\nmodel = position_attention(vocab_size=vocab_size, output_dim=1, embedding_dim=embedding_dim, max_len=max_len)\r\n\r\nvocab = get_vocab(dir1='plot.tok.gt9.5000', dir2='quote.tok.gt9.5000', dir3='vocab.txt')\r\n\r\ni = 9\r\ncheckpoint_filepath = 'errors_4/checkpoint/checkpoint'\r\nfilepath = checkpoint_filepath + '_' + str(i)\r\nmodel.load_weights(filepath)\r\nmodel.compile(optimizer=optimizers.Adam(), # 静态学习率没有动态学习率更适应模型\r\n loss=losses.BinaryCrossentropy(from_logits=True),\r\n metrics=['accuracy'])\r\n\r\nsentences = get_error_sentence(dir='errors_4/error_sample_' + str(i) + '.txt')\r\nsentences = pad_list_word(sentences, vocab, max_len)\r\nprobability = np.zeros([len(sentences), 1])\r\nfor id, sentence in enumerate(sentences):\r\n probability[id] = Evaluate_error(model, sentence, vocab, max_len)\r\n\r\n# modify_false_sample(i, probability)\r\nprint()\r\n\r\n\r\n\"\"\"\r\n 生成\"_extract.txt\"文件 \r\n\"\"\"\r\n# if __name__ == '__main__':\r\n# for i in range(10):\r\n# modify_false_sample(i)\r\n\r\n","repo_name":"yxq9710/dataProcessAndModelReproduction","sub_path":"dataset/SUBJ_2004/plot_error_sample.py","file_name":"plot_error_sample.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"42174423091","text":"import torch.nn as nn\n\n\nclass CRNN(nn.Module):\n\n def __init__(self, imgH, nc, nclass, nh):\n super(CRNN, self).__init__()\n assert imgH % 16 == 0, 'imgH has to be a multiple of 16'\n\n self.kernels = [3, 3, 3, 3, 3, 3, 2]\n self.paddings = [1, 1, 1, 1, 1, 1, 0]\n self.strides = [1, 1, 1, 1, 1, 1, 1]\n self.channels = [64, 128, 256, 256, 512, 512, 512, nc]\n\n conv0 = nn.Sequential(\n self._make_layer(0),\n nn.MaxPool2d((2, 2))\n )\n conv1 = nn.Sequential(\n self._make_layer(1),\n nn.MaxPool2d((2, 2))\n )\n conv2 = self._make_layer(2, True)\n conv3 = nn.Sequential(\n self._make_layer(3),\n nn.MaxPool2d((2, 2), (2, 1), (0, 1))\n )\n conv4 = self._make_layer(4, True)\n conv5 = nn.Sequential(\n self._make_layer(5),\n nn.MaxPool2d((2, 2), (2, 1), (0, 1))\n )\n conv6 = self._make_layer(6, True)\n\n self.cnn = nn.Sequential(\n conv0,\n conv1,\n conv2,\n conv3,\n conv4,\n conv5,\n conv6\n )\n\n\n def _make_layer(self, i, batch_normalization=False):\n in_channel = self.channels[i - 1]\n out_channel = self.channels[i]\n layer = list()\n layer.append(nn.Conv2d(in_channel, out_channel, self.kernels[i], self.strides[i], self.paddings[i]))\n if batch_normalization:\n layer.append(nn.BatchNorm2d(out_channel))\n else:\n layer.append(nn.ReLU())\n return nn.Sequential(*layer)\n\n def forward(self, input):\n # conv features\n return self.cnn(input)\n\n\ndef crnn_backbone(imgH=32, nc=3, nclass=37, nh=256):\n return CRNN(imgH, nc, nclass, nh)\n","repo_name":"Megvii-CSG/MegReader","sub_path":"backbones/crnn.py","file_name":"crnn.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","stars":344,"dataset":"github-code","pt":"27"} +{"seq_id":"17071808546","text":"from replicator import Replicator\nfrom notation import Notation, Func\n\n\nclass Replacer(Replicator):\n \"\"\"Replacer\"\"\"\n\n crosstab = (\n (Notation.P_LIST, Notation.S_LIST),\n (Notation.P_LIST, Notation.C_LIST),\n (Notation.S_LIST, Notation.C_LIST),\n (Notation.P_LIST, Notation.PLUS),\n (Notation.P_LIST, Notation.MINUS),\n (Notation.PLUS, Notation.PLUS),\n (Notation.PLUS, Notation.MINUS),\n (Notation.MINUS, Notation.PLUS),\n (Notation.MINUS, Notation.MINUS),\n (Notation.PLUS, Notation.S_LIST),\n (Notation.MINUS, Notation.S_LIST),\n )\n\n def escape(self, sym, br, linked_sym):\n return self.output_notation.repf(self.mapsym(sym), Func(Notation.GROUP, (linked_sym,), br=br))\n\n def subst(self, sym, new_sym, ctx):\n f = self.output_notation.get(new_sym)\n if f is not None:\n if ctx is not None:\n if ctx.name in Notation.oper:\n return self.escape(sym, '{}', new_sym)\n if ctx == Notation.INDEX or (ctx, f.sym) in self.crosstab:\n return self.escape(sym, '()', new_sym)\n return new_sym\n","repo_name":"semyonc/toymath","sub_path":"engine/replacer.py","file_name":"replacer.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"31587419686","text":"import pymysql\nimport config\n\n#--Подключение к БД--\ndb = pymysql.connect(host=config.host, user=config.user,password=config.password,\n db='stalker_db', charset='utf8mb4')\ncur = db.cursor() # формируем курсор для работы с sql-запросами\n#--\n#--Получаем список включенных каналов\ncur.execute(\"SELECT name,logo,cmd,tv_genre_id FROM itv where status='1' ORDER BY tv_genre_id ASC;\")\nresult=cur.fetchall()\ncur.execute(\"SELECT number,name,cmd from itv where status='1' ORDER BY number ASC;\")\nr_list=cur.fetchall()\ndb.close()\n#--\n#Локализируем жанр телеканала\ngroup={\n1:'Документальное',\n2:'Развлекательное',\n3:'Для Детей',\n4:'Видео',\n5:'Музыкальные',\n6:'Новостные',\n7:'Природа',\n8:'Спорт',\n19:'Для взрослых',\n20:'Религиозные',\n22:'Телемагазин',\n23:'Кулинарный',\n24:'Fashion'}\n#--\n#Пишем телеканалы групируя по жанру\nwith open(config.home+\"group.m3u\",\"w+\") as f:\n f.write('#EXTM3U\\n')\n for channel in result:\n f.write('\\n#EXTINF:-1 logo=\"/misc/logos/320/'+str(channel[1])+'\" group-title=\"'+str(group[channel[3]])+'\" on-demand=\"1\", '+str(channel[0])+'\\n'+str(channel[2])+'\\n')\n#--\n#Пишем телеканалы без групировки\nwith open(config.home+\"smart.m3u\",\"w+\") as f:\n f.write('#EXTM3U\\n')\n for channel in r_list:\n f.write('\\n#EXTINF:-1 on-demand=\"1\", '+str(channel[1])+'\\n'+str(channel[2]+'\\n'))\n#--\n#Пишем телеканалы одним списком в текстовик\nwith open(config.home+\"channels.txt\",\"w+\",encoding=\"cp1251\") as f:\n for channel in r_list:\n f.write(str(channel[0])+' '+str(channel[1])+'\\n')\n#--\n","repo_name":"Xerber/stalker","sub_path":"w_tv.py","file_name":"w_tv.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"41844093786","text":"from django import forms\nfrom .models import BOOLEAN_CHOICES\n\n\nclass UserQuizForm(forms.Form):\n name = forms.CharField(max_length=256)\n\n def __init__(self, quiz, *args, **kwargs):\n super(UserQuizForm, self).__init__(*args, **kwargs)\n for q in quiz.questions.all():\n label = \"qid_{}\".format(q.id)\n self.fields[label] = forms.ChoiceField(label=id, choices=BOOLEAN_CHOICES)\n\n def get_answers(self):\n for k, v in self.cleaned_data.items():\n if k.startswith('qid_'):\n qid = int(k.split('_')[1])\n yield qid, v\n","repo_name":"rcludwick/quiz","sub_path":"app/quiz/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"43411026853","text":"import tkinter\r\n\r\nroot = tkinter.Tk()\r\n\r\ncanvas = tkinter.Canvas(width = 400, height = 600, bg = \"skyblue\")\r\ncanvas.pack()\r\nplayer = tkinter.PhotoImage(file = \"player.png\")\r\ncanvas.create_image(200,300, image = player )\r\n\r\nroot.mainloop()\r\n","repo_name":"EastupGame/python_basic","sub_path":"0813/GUI5.py","file_name":"GUI5.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19017283798","text":"from django.shortcuts import render_to_response\r\nfrom django.template import RequestContext\r\n\r\nfrom isasuk.upload.models import Proposal, File\r\n\r\ndef proposal_view(request, proposal_id, file_id):\r\n proposal = Proposal.objects.get(id=proposal_id)\r\n files = File.objects.filter(proposal_id=proposal_id)\r\n main_file = File.objects.get(id=file_id)\r\n path = file_id + \"/\" + ('.').join(main_file.name.split('.')[:-1]) + \".html\"\r\n return render_to_response(\r\n 'viewer/main.html',\r\n {\r\n 'path': path,\r\n 'proposal': proposal,\r\n 'files': files,\r\n 'file': main_file,\r\n },\r\n context_instance=RequestContext(request)\r\n )\r\n\r\ndef document_view(request, id):\r\n file_instance = File.objects.get(id=id)\r\n print(file_instance.path + '/' + id + '/' + file_instance.name, file=sys.stderr) \r\n return render_to_response(\r\n 'viewer/dohoda123.html',\r\n context_instance=RequestContext(request)\r\n )\r\n\r\n\r\ndef path_view(request, path):\r\n return render_to_response(\r\n path,\r\n {'path': path},\r\n context_instance=RequestContext(request)\r\n )","repo_name":"andrejskok/isasuk","sub_path":"isasuk/viewer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"32625245973","text":"import time\nimport json\nfrom database import Database\nfrom graphql import GraphQLQuery\nfrom utils import get_column_names\nfrom psycopg2 import sql\nfrom psycopg2.errors import UniqueViolation, UndefinedTable\n\ngql = GraphQLQuery()\n\nwith open(\"stat_id_dictionary.json\") as stat_list:\n all_stats = json.load(stat_list)\n \n# with open(\"sg_tot_example.json\") as stat_example:\n# ex = json.load(stat_example)\n\nwith Database(db_type='prod') as (db, con, cur):\n select_query = \"\"\"\n SELECT id, pga_id, first_name || ' ' || last_name as player_name\n from players\n \"\"\"\n cur.execute(select_query)\n player_id_results = cur.fetchall()\n\n select_query = \"\"\"\n SELECT id, pga_tournament_id\n from tournaments\n \"\"\"\n cur.execute(select_query)\n tournament_id_results = cur.fetchall()\n\n thru_tourn_select = \"\"\"\n select\n id\n ,pga_tournament_id\n ,tournament_end_date\n \n from tournaments\n \n where tournament_end_date IS NOT NULL\n AND season_year = '2022 - 2023'\n AND lower(tournament_name) NOT LIKE 'corales%'\n AND lower(tournament_name) NOT LIKE 'puerto rico%'\n AND lower(tournament_name) NOT LIKE 'butterfield%'\n AND lower(tournament_name) NOT LIKE 'zurich classic%'\n order by tournament_end_date desc \n \"\"\"\n cur.execute(thru_tourn_select)\n thru_tourn_results = cur.fetchall()\n\nplayer_id_dict = {result.get(\"pga_id\"):int(result.get(\"id\")) for result in player_id_results }\ntournament_id_dict = {result.get(\"pga_tournament_id\"):int(result.get(\"id\")) for result in tournament_id_results }\nthru_tourn_list = [result.get(\"pga_tournament_id\") for result in thru_tourn_results]\n\nwith Database(db_type='prod') as (db, con, cur):\n for tournament in thru_tourn_list:\n print(tournament)\n for stat in list(all_stats.keys())[:10]: \n print(all_stats.get(stat))\n table_name = all_stats.get(stat)\n\n time.sleep(6)\n stats = gql.scrape_stats(stat_id=stat, schedule_year=2023, through_event_flag=\"THROUGH_EVENT\", pga_tournament_id=tournament)\n \n try:\n query = sql.SQL(\"\"\"SELECT 1 FROM {}\"\"\").format(\n sql.Identifier(table_name))\n cur.execute(query)\n\n except UndefinedTable: \n print(\"table undefined\")\n con.rollback() \n stat_headers = ['id', 'pga_stat_id', 'pga_stat_name', 'player_id', 'thru_tournament_id', 'rank']\n stat_types = ['SERIAL PRIMARY KEY', 'VARCHAR(255)', 'VARCHAR(255)', 'INT', 'INT', 'INT']\n\n for stat_header in stats['data']['statDetails']['statHeaders']:\n if stat_header.lower() in ('avg', 'average'):\n stat_header = 'avg_val'\n stat_headers.append(stat_header)\n stat_types.append(\"VARCHAR(255)\")\n\n \n\n db.create_table(table_name, stat_headers, stat_types, ['player_id', 'pga_stat_id', 'thru_tournament_id'])\n \n\n finally:\n \n cols = get_column_names('public', table_name, cur)[1:]\n req_num_stats = len(cols)\n vals = []\n\n for row in stats['data']['statDetails']['rows']:\n if row['__typename'] != 'StatDetailsPlayer':\n continue\n else:\n pga_stat_id = stat\n pga_stat_name = stats['data']['statDetails']['statTitle']\n try:\n player_id = player_id_dict.get(row['playerId'])\n except KeyError:\n player_id = None\n \n thru_tournament_id = tournament_id_dict.get(tournament)\n rank = row['rank']\n\n row_vals = [pga_stat_id, pga_stat_name, player_id, thru_tournament_id, rank]\n\n for val in row['stats']:\n row_vals.append(val['statValue'])\n\n if len(row_vals) < req_num_stats:\n i = 0\n for i in range(req_num_stats-len(row_vals)):\n row_vals.append(None)\n i += 1\n\n vals.append(tuple(row_vals))\n\n try:\n db.bulk_insert(table_name, cols, vals)\n except UniqueViolation:\n print(\"Already in Database\")\n con.rollback()\n continue","repo_name":"adrevezzo/pga-data","sub_path":"stats_scrape.py","file_name":"stats_scrape.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18191268182","text":"import numpy as np\nimport csv\nfrom torch.utils.data import Dataset\nfrom PIL import Image\nimport torchvision.transforms as transforms\nimport torch.nn.functional as F\nimport os\n\nclass BaseDataset(Dataset):\n def __init__(self, model_name, cfg_file_path, transform=None, img_size=256, imgpath=False):\n assert model_name == \"Triplet\" or \"Arcface\" or \"ImprovedTriplet\" or \"Quadruplet\" or \"UIR\",\\\n f\"\"\"model {model_name} is not supported. Choose model in [Triplet, Arcface, ImprovedTriplet, Quadruplet, UIR].\"\"\"\n\n with open(cfg_file_path, \"r\") as f:\n reader = csv.reader(f)\n # if \"MOT\" in cfg_file_path:\n # data = np.array([[os.path.normpath(os.path.join(cfg_file_path,\"../../../\",row[0])), row[1]]\\\n # for row in reader])\n # elif \"WLO\" in cfg_file_path:\n data = np.array([[os.path.normpath(row[0]), row[1]]\\\n for row in reader])\n self.images_path = data[:, 0]\n self.labels = np.array(list(map(int, data[:, 1])))\n # if model_name==\"Arcface\" or model_name==\"UIR\":#XXX\n # label_set = list(set(self.labels))\n # label_to_idx = {label: idx for idx, label in enumerate(label_set)}\n # self.labels = np.array([label_to_idx[label] for label in self.labels])\n\n self.img_size = img_size\n self.n_data = len(self.images_path)\n self.imgpath = imgpath\n\n self.transform = transform if transform else transforms.ToTensor()\n \n def pad_to_square(self, img, pad_value):\n c, h, w = img.shape\n dim_diff = np.abs(h - w)\n # (upper / left) padding and (lower / right) padding\n pad1, pad2 = dim_diff // 2, dim_diff - dim_diff // 2\n # Determine padding\n pad = (0, 0, pad1, pad2) if h <= w else (pad1, pad2, 0, 0)\n # Add padding\n img = F.pad(img, pad, \"constant\", value=pad_value)\n\n return img, pad\n\n def resize(self, image, size):\n image = F.interpolate(image.unsqueeze(0), size=size, mode=\"nearest\").squeeze(0)\n return image\n\n def __getitem__(self, index):\n # tolist = lambda x: [x] if type(x) is int else x\n tolist = lambda x: x if type(x) is list else [int(x)]\n\n imgs = list()\n img_paths = list()\n labels = list()\n\n for i in tolist(index):\n img_path = self.images_path[i]\n label = self.labels[i]\n # Extract image as PyTorch tensor\n img = self.transform(Image.open(img_path).convert('RGB'))\n\n # Handle images with less than three channels\n if len(img.shape) != 3:\n img = img.unsqueeze(0)\n img = img.expand((3, img.shape[1:]))\n\n # Pad to square resolution\n img, pad = self.pad_to_square(img, 0)\n # Resize\n img = self.resize(img, self.img_size)\n imgs.append(img)\n img_paths.append(img_path)\n labels.append(label)\n\n\n fromlist = lambda x: x[0] if len(x)==1 else x\n if self.imgpath:\n return fromlist(img_paths), fromlist(imgs), fromlist(labels)\n else:\n return fromlist(imgs), fromlist(labels)\n\n\n def __len__(self):\n return self.n_data","repo_name":"u-shiori/reid","sub_path":"src/datasets/_BaseDataset.py","file_name":"_BaseDataset.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70341725831","text":"import utils\nimport string\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom tqdm import tqdm\n\ndef loss_fn(o1, o2, t1, t2):\n l1 = nn.BCEWithLogitsLoss()(o1, t1)\n l2 = nn.BCEWithLogitsLoss()(o2, t1)\n return l1 + l2\n\ndef train_fn(data_loader, model, optimizer, device, scheduler):\n model.train()\n losses = utils.AverageMeter()\n tk0 = tqdm(data_loader, total=len(data_loader))\n for bi, d in enumerate(tk0):\n ids = d[\"ids\"]\n token_type_ids = d[\"token_type_ids\"]\n mask = d[\"mask\"]\n targets_start = d[\"targets_start\"]\n targets_end = d[\"targets_end\"]\n\n ids = ids.to(device, dtype=torch.long)\n token_type_ids = token_type_ids.to(device, dtype=torch.long)\n mask = mask.to(device, dtype=torch.long)\n targets_start = targets_start.to(device, dtype=torch.float)\n targets_end = targets_end.to(device, dtype=torch.float)\n\n optimizer.zero_grad()\n o1, o2 = model.forward(ids=ids, mask=mask, token_type_ids=token_type_ids)\n\n loss = loss_fn(o1, o2, targets_start, targets_end)\n loss.backward()\n optimizer.step()\n scheduler.step()\n losses.update(loss.item(), ids.size(0))\n tk0.set_postfix(loss=losses.avg)\n\ndef eval_fn(data_loader, model, optimizer, device, scheduler):\n model.eval()\n fin_output_start = []\n fin_output_end = []\n fin_padding_lens = []\n fin_context_tokens = []\n fin_orig_context = []\n fin_orig_question = []\n fin_orig_answer = []\n\n for bi, d in enumerate(data_loader):\n ids = d[\"ids\"]\n token_type_ids = d[\"token_type_ids\"]\n context_tokens = d[\"context_tokens\"]\n padding_len = d[\"padding_len\"]\n orig_context = d[\"orig_context\"]\n orig_quesion = d[\"orig_quesion\"]\n orig_answer = d[\"orig_answer\"]\n\n ids = ids.to(device, dtype=torch.long)\n token_type_ids = token_type_ids.to(device, dtype=torch.long)\n mask = mask.to(device, dtype=torch.long)\n\n optimizer.zero_grad()\n o1, o2 = model.forward(\n ids=ids, \n mask=mask, \n token_type_ids=token_type_ids\n )\n\n fin_output_start.append(torch.sigmoid(o1).cpu().detach().numpy())\n fin_output_end.append(torch.sigmoid(o1).cpu().detach().numpy())\n fin_padding_lens.append(padding_len.cpu().detach().numpy().tolist())\n\n fin_context_tokens.append(context_tokens)\n fin_orig_context.append(orig_context)\n fin_orig_question.append(orig_quesion)\n fin_orig_answer.append(orig_answer)\n\n fin_output_start = np.vstack(fin_output_start)\n fin_output_end = np.vstack(fin_output_end)\n\n threshold = 0.2\n jaccards = []\n for j in range(len(fin_context_tokens)):\n target_string = fin_orig_answer[j]\n context_tokens = fin_context_tokens[j]\n padding_len = fin_padding_lens[j]\n original_context = fin_orig_context[j]\n question = fin_orig_question[j]\n\n if padding_len > 0:\n mask_start = fin_output_start[j, :][:-padding_len] >= threshold\n mask_end = fin_output_end[j, :][:-padding_len] >= threshold\n\n else:\n mask_start = fin_output_start[j, :] >= threshold\n mask_end = fin_output_end[j, :] >= threshold\n\n mask = [0] * len(mask_start)\n idx_start = np.nonzero(mask_start)[0]\n idx_end = np.nonzero(mask_end)[0]\n\n if len(idx_start) > 0:\n idx_start = idx_start[0]\n if len(idx_end) > 0:\n idx_end = idx_end[0]\n else:\n idx_end = idx_start\n else:\n idx_start = 0\n idx_end = 0\n\n for mj in range(idx_start, idx_end + 1):\n mask[mj] = 1\n\n output_tokens = [x for p, x in enumerate(context_tokens.split()) if mask[p] == 1]\n output_tokens = [x for x in output_tokens if not x in (\"[CLS]\", \"[SEP]\")]\n\n final_output = \"\"\n for ot in output_tokens:\n if ot.startswith(\"##\"):\n final_output = final_output + ot[2:]\n elif len(ot) == 1 and ot in string.punctuation:\n final_output = final_output + ot\n else:\n final_output = final_output + \" \" + ot\n\n final_output = final_output.strip()\n\n jac = utils.jaccard(target_string.strip(), final_output.strip())\n jaccards.append(jac)\n \n mean_jac = np.mean(jaccards)\n return mean_jac\n","repo_name":"Claudio9701/spanish-squad-bert","sub_path":"src/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":4434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"25967958760","text":"import os\nimport subprocess\nimport logging\nimport hashlib\nimport time\nimport xml.etree.ElementTree as ET\n\nlogging.basicConfig(format='[%(asctime)s] %(levelname)8s [%(filename)16s:%(lineno)4d] %(message)s', level=logging.DEBUG)\nlogger = logging.getLogger('phonelab')\n\n\nDEVNULL = open(os.devnull, 'w')\n\ndef call(cmd, verbose=False, dryrun=False):\n if verbose:\n logger.debug(cmd)\n if not dryrun:\n subprocess.check_call(cmd, shell=True)\n else:\n if not dryrun:\n subprocess.check_call(cmd, stdout=DEVNULL, stderr=DEVNULL, shell=True)\n\n\ndef repo_forall(cmd, verbose=False, dryrun=False):\n \"\"\"Wrap of ``repo forall`` without output pager.\n \"\"\"\n call('GIT_PAGER= repo forall -j 4 -epv -c %s' % (cmd), verbose, dryrun)\n\n\ndef bump_version(ver):\n \"\"\"Bump up patch part of version.\n \"\"\"\n numbers = ver.split('.')\n assert all([len(i) == 1 for i in numbers]), \"Version number should be x.y.x, where x, y and z are one digit numbers.\"\n current = int(ver.replace('.', ''))\n return '.'.join(str(int(current+1)))\n\n\ndef md5_hash(path):\n \"\"\"Compute file's MD5 hash.\n\n Args:\n path (str): file's path.\n\n Returns:\n string: file's MD5 hash.\n \"\"\"\n hashlib.md5(open(path, 'rb').read()).hexdigest()\n\n\ndef find(dir, filename):\n \"\"\"Recursively find files under directory.\n\n Args:\n dir (str): directory to search\n filename: file name to search\n\n Returns:\n list: A list of file paths. Could be empty.\n \"\"\"\n hit = []\n for dirpath, dirname, filenames in os.walk(dir):\n if filename in filenames:\n hit.append(os.path.join(dirpath, filename))\n return hit\n\n\ndef time_it(func):\n\n def func_wrapper(*args, **kwargs):\n start = time.time()\n func(*args, **kwargs)\n duration_sec = time.time() - start\n logger.debug(\"%s finished, time elapesd: %d min %d sec\" % (func.__name__,\\\n int(duration_sec / 60), int(duration_sec % 60)))\n\n return func_wrapper\n\n\ndef get_repo_projs(aosp_root):\n projs = []\n for child in ET.parse(os.path.join(aosp_root, '.repo', 'manifests',\\\n 'default.xml')).getroot():\n if child.tag == 'project' and 'notdefault' not in child.attrib.get(\\\n 'groups', ''):\n projs.append(child.attrib['path'])\n\n return projs\n\n","repo_name":"blue-systems-group/project.phonelab.platform_checker","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"3300227032","text":"import os, glob\nfrom typing import Tuple\nimport pickle\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nimport socket\nimport random\nimport scipy.io as sio\n\nDEFAULT_DATA_ROOT = '/wdata/roironen/Data'\n\n\nALL_DATASETS = (\"BOMEX_CASS_10cams_20m\", \"CASS_10cams_20m\", \"CASS_10cams_50m\", \"BOMEX_10cams_20m\",\n \"BOMEX_10cams_50m\", \"BOMEX_32cams_20m\", \"BOMEX_32cams_50m\", \"BOMEX_10cameras_20m_varying_S\", \"BOMEX_10cameras_20m_varying_M\",\n \"BOMEX_10cameras_20m_varying_L\", \"BOMEX_10cameras_20m_varying_XL\",\n \"subset_of_seven_clouds\")\n\n\ndef trivial_collate(batch):\n \"\"\"\n A trivial collate function that merely returns the uncollated batch.\n \"\"\"\n batch = np.array(batch, dtype=object).transpose().tolist()\n return batch\n\n\ndef get_cloud_datasets(\n cfg,\n data_root: str = DEFAULT_DATA_ROOT,\n) -> Tuple[Dataset, Dataset]:\n \"\"\"\n Obtains the training and validation dataset object for a dataset specified\n with the `dataset_name` argument.\n\n Args:\n cfg: The config file with the name of the dataset to load.\n data_root: The root folder at which the data is stored.\n\n Returns:\n train_dataset: The training dataset object.\n val_dataset: The validation dataset object.\n \"\"\"\n dataset_name = cfg.data.dataset_name\n\n if dataset_name not in ALL_DATASETS:\n raise ValueError(f\"'{dataset_name}'' does not refer to a known dataset.\")\n\n if dataset_name == 'CASS_10cams':\n data_root = os.path.join(data_root, 'CASS_50m_256x256x139_600CCN/10cameras_50m')\n image_size = [236, 236]\n elif dataset_name == 'BOMEX_CASS_10cams_20m':\n data_root_cass = os.path.join(data_root, 'CASS_50m_256x256x139_600CCN/10cameras_20m')\n data_root_bomex = os.path.join(data_root, 'BOMEX_256x256x100_5000CCN_50m_micro_256', '10cameras_20m')\n elif dataset_name == 'CASS_10cams_50m':\n data_root = os.path.join(data_root, 'CASS_50m_256x256x139_600CCN/10cameras_50m')\n image_size = [96, 96]\n elif dataset_name == 'BOMEX_10cams_20m':\n data_root = os.path.join(data_root, 'BOMEX_256x256x100_5000CCN_50m_micro_256', '10cameras_20m')\n image_size = [116, 116]\n elif dataset_name == 'BOMEX_10cameras_20m_varying_S':\n data_root = os.path.join(data_root, 'BOMEX_256x256x100_5000CCN_50m_micro_256', '10cameras_20m_varying_S')\n image_size = [116, 116]\n elif dataset_name == 'BOMEX_10cameras_20m_varying_M':\n data_root = os.path.join(data_root, 'BOMEX_256x256x100_5000CCN_50m_micro_256', '10cameras_20m_varying_M')\n image_size = [116, 116]\n elif dataset_name == 'BOMEX_10cameras_20m_varying_L':\n data_root = os.path.join(data_root, 'BOMEX_256x256x100_5000CCN_50m_micro_256', '10cameras_20m_varying_L')\n image_size = [116, 116]\n elif dataset_name == 'BOMEX_10cameras_20m_varying_XL':\n data_root = os.path.join(data_root, 'BOMEX_256x256x100_5000CCN_50m_micro_256', '10cameras_20m_varying_XL')\n image_size = [116, 116]\n elif dataset_name == 'BOMEX_10cams_50m':\n data_root = os.path.join(data_root, 'BOMEX_256x256x100_5000CCN_50m_micro_256', '10cameras_50m')\n image_size = [48, 48]\n elif dataset_name == 'BOMEX_32cams_50m':\n data_root = os.path.join(data_root, 'BOMEX_256x256x100_5000CCN_50m_micro_256', '32cameras_50m')\n image_size = [48, 48]\n elif dataset_name == 'BOMEX_32cams':\n data_root = os.path.join(data_root, 'BOMEX_256x256x100_5000CCN_50m_micro_256', '32cameras_20m')\n image_size = [116, 116]\n elif dataset_name == 'subset_of_seven_clouds':\n data_root = os.path.join(data_root, 'BOMEX_256x256x100_5000CCN_50m_micro_256', '10cameras_50m')\n image_size = [48, 48]\n else:\n FileNotFoundError()\n\n if not dataset_name == 'BOMEX_CASS_10cams_20m':\n print(f\"Loading dataset {dataset_name}, image size={str(image_size)} ...\")\n data_train_paths = [f for f in glob.glob(os.path.join(data_root, \"train/cloud*.pkl\"))]\n else:\n print(f\"Loading dataset {dataset_name}...\")\n data_train_paths = [f for f in glob.glob(os.path.join(data_root_cass, \"train/cloud*.pkl\"))]\n data_train_paths += [f for f in glob.glob(os.path.join(data_root_bomex, \"train/cloud*.pkl\"))]\n random.shuffle(data_train_paths)\n train_len = cfg.data.n_training if cfg.data.n_training>0 else len(data_train_paths)\n data_train_paths = data_train_paths[:train_len]\n\n n_cam = cfg.data.n_cam\n mean = cfg.data.mean\n std = cfg.data.std\n rand_cam = cfg.data.rand_cam\n train_dataset = CloudDataset(\n data_train_paths,\n n_cam=n_cam,\n rand_cam = rand_cam,\n mask_type=cfg.ct_net.mask_type,\n mean=mean,\n std=std,\n dataset_name = dataset_name,\n\n )\n if not (dataset_name == 'BOMEX_CASS_10cams_20m' or dataset_name == 'subset_of_seven_clouds'):\n val_paths = [f for f in glob.glob(os.path.join(data_root, \"test/cloud*.pkl\"))]\n elif dataset_name == 'subset_of_seven_clouds':\n val_paths = [f for f in glob.glob(os.path.join(data_root, \"subset_of_seven_clouds/cloud*.pkl\"))]\n print(val_paths)\n else:\n val_paths = [f for f in glob.glob(os.path.join(data_root_cass, \"test/cloud*.pkl\"))]\n val_paths += [f for f in glob.glob(os.path.join(data_root_bomex, \"test/cloud*.pkl\"))]\n random.shuffle(val_paths)\n\n val_len = cfg.data.n_val if cfg.data.n_val>0 else len(val_paths)\n val_paths = val_paths[:val_len]\n val_dataset = CloudDataset(val_paths, n_cam=n_cam,\n rand_cam = rand_cam, mask_type=cfg.ct_net.val_mask_type, mean=mean, std=std, dataset_name = dataset_name\n)\n\n return train_dataset, val_dataset\n\n\nclass CloudDataset(Dataset):\n def __init__(self, cloud_dir, n_cam, rand_cam=False, transform=None, target_transform=None, mask_type=None, mean=0, std=1, dataset_name=''):\n self.cloud_dir = cloud_dir\n self.transform = transform\n self.target_transform = target_transform\n self.mask_type = mask_type\n self.n_cam = n_cam\n self.rand_cam = rand_cam\n self.mean = mean\n self.std = std\n self.dataset_name = dataset_name\n\n def __len__(self):\n return len(self.cloud_dir)\n\n def __getitem__(self, idx):\n cloud_path = self.cloud_dir[idx]\n\n with open(cloud_path, 'rb') as f:\n data = pickle.load(f)\n images = data['images']\n mask = None\n if self.mask_type == 'space_carving':\n mask = data['mask']\n elif self.mask_type == 'space_carving_morph':\n mask = data['mask_morph']\n elif self.mask_type == 'space_carving_0.9':\n mask = data['mask0.9']\n if 'varying' in self.dataset_name:\n # randomly sample a perturbation out of the tenth simulated data\n index = torch.randperm(10)[0]\n cam_i = torch.arange(index,100,10)\n mask = mask[index] if mask is not None else None\n else:\n cam_i = torch.arange(self.n_cam)\n images = images[cam_i]\n images -= self.mean\n images /= self.std\n\n if hasattr(data, 'image_sizes'):\n image_sizes = data['image_sizes'][cam_i]\n else:\n image_sizes = [image.shape for image in images]\n extinction = data['ext']\n grid = data['grid']\n camera_center = data['cameras_pos'][cam_i]\n projection_matrix = data['cameras_P'][cam_i]\n\n return images, extinction, grid, image_sizes, projection_matrix, camera_center, mask\n","repo_name":"ronenroi/VIPCT","sub_path":"VIPCT/VIPCT/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":7552,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"37444854335","text":"\"\"\"\ntests for openqa_review.\n\nCan't get isort to work on this file\n\nisort:skip_file\n\"\"\"\n\n# see http://python-future.org/compatible_idioms.html\nfrom future.standard_library import install_aliases # isort:skip to keep 'install_aliases()'\nfrom future.utils import iteritems\n\ninstall_aliases()\nimport contextlib\nimport os.path\nimport re\nimport shutil\nimport sys\nimport tempfile\nfrom argparse import Namespace\nfrom openqa_review.browser import filename_to_url\nfrom urllib.parse import urljoin, urlparse\nfrom configparser import ConfigParser # isort:skip can not make isort happy here\n\nimport pytest\n\nfrom openqa_review import openqa_review # SUT\n\n\ndef args_factory():\n args = Namespace()\n args.host = 'https://openqa.opensuse.org'\n args.job_group_urls = None\n args.job_groups = None\n args.exclude_job_groups = None\n args.no_progress = True\n args.verbose = 1\n args.output_state_results = False\n args.base_url = '/'\n args.verbose_test = 4\n args.arch = 'x86_64'\n args.save = False\n args.load = False\n args.load_dir = '.'\n args.builds = None\n args.against_reviewed = None\n args.running_threshold = 0\n args.show_empty = True\n args.bugrefs = False\n args.include_softfails = True\n args.query_issue_status = False\n args.query_issue_status_help = True\n args.report_links = False\n return args\n\n\ndef browser_factory(args=None):\n if not args:\n args = cache_test_args_factory()\n return openqa_review.Browser(args, urljoin(args.host, args.base_url))\n\n\n# similar to python3.2 TemporaryDirectory, not available on older versions\n# also see http://stackoverflow.com/a/13379969/5031322\n\n@contextlib.contextmanager\ndef TemporaryDirectory(): # noqa\n temp_dir = tempfile.mkdtemp()\n yield temp_dir\n shutil.rmtree(temp_dir)\n\n\ndef test_help():\n sys.argv += '--help'.split()\n with pytest.raises(SystemExit):\n openqa_review.main()\n\n\ndef test_missing_config():\n openqa_review.CONFIG_PATH = \"/dev/null/.missing_file\"\n sys.argv[1:] = ['--query-issue-status']\n with pytest.raises(SystemExit) as excinfo:\n openqa_review.main()\n assert excinfo.value.code == 1\n\n\ndef test_query_issue_status_help_shows_config_help():\n sys.argv[1:] = ['--query-issue-status-help']\n with pytest.raises(SystemExit):\n # we are not actually testing the content of help, just that it does not fail\n openqa_review.main()\n\n\ndef test_args_implicit():\n sys.argv[1:] = ['--reminder-comment-on-issues']\n args = openqa_review.parse_args()\n assert args.reminder_comment_on_issues\n assert args.query_issue_status\n assert args.bugrefs\n\n sys.argv[1:] = ['--report-links']\n args = openqa_review.parse_args()\n assert not args.bugrefs\n\n\ndef cache_test_args_factory():\n args = args_factory()\n args.job_group_urls = args.host + '/group_overview/25'\n args.load = True\n args.load_dir = os.path.dirname(os.path.realpath(__file__))\n return args\n\n\ndef compare_report(report, ref_report):\n # for simpler display of the diff in case of differences it helps to have\n # both reports in same encoding, i.e. casting to str\n lines = str(report).splitlines()\n ref = ref_report.splitlines()\n # report equals the reference except for the time tag so skip the\n # date/time line\n del lines[3], ref[3]\n assert lines == ref\n\n\ndef test_previously_loaded_cache_file_is_generated_into_valid_verbose_report_if_configured():\n args = cache_test_args_factory()\n report = str(openqa_review.generate_report(args))\n assert '**Common issues:**' in report\n # Missing architecture is reported\n assert re.search(\"Missing arch.*i586\", report)\n ref_report = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'report25_TTT.md')).read()\n compare_report(report, ref_report)\n\n\ndef test_previously_loaded_cache_file_is_generated_into_valid_terse_report_by_default():\n args = cache_test_args_factory()\n args.verbose_test = 1\n report = str(openqa_review.generate_report(args))\n assert '**Common issues:**' in report\n ref_report = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'report25_terse.md')).read()\n compare_report(report, ref_report)\n\n\ndef test_previously_loaded_cache_file_is_generated_into_ref_report_l2():\n args = cache_test_args_factory()\n args.verbose_test = 2\n report = str(openqa_review.generate_report(args))\n ref_report = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'report25_T.md')).read()\n compare_report(report, ref_report)\n\n\ndef test_previously_loaded_cache_file_is_generated_into_ref_report_l3():\n args = cache_test_args_factory()\n args.verbose_test = 3\n report = str(openqa_review.generate_report(args))\n ref_report = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'report25_TT.md')).read()\n compare_report(report, ref_report)\n\n\ndef test_builds_can_be_specified_and_appear_in_report():\n args = cache_test_args_factory()\n args.builds = '0313,0308'\n report = str(openqa_review.generate_report(args))\n assert '**Build:** {} (reference {})'.format(*args.builds.split(',')) in report\n\n\ndef test_too_high_verbosity_selection_yields_still_valid_selection():\n args = cache_test_args_factory()\n args.verbose_test = 5\n report = str(openqa_review.generate_report(args))\n assert report != ''\n\n\ndef test_ha_tests_yields_valid_report_with_valid_build_nr():\n args = cache_test_args_factory()\n args.arch = None # let this test check architectures by itself to reach good test coverage\n args.load_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'live')\n args.job_group_urls = args.host + '/group_overview/27'\n report = str(openqa_review.generate_report(args))\n assert '0104@0351' in report\n\n\ndef test_specified_job_group_yields_single_product_report():\n args = cache_test_args_factory()\n args.job_group_urls = None\n args.load_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'single_job_group')\n args.job_groups = 'openSUSE Argon'\n report = str(openqa_review.generate_report(args))\n assert args.job_groups in report\n # There must be only one job group tag\n assert len([l for l in report.splitlines() if l.startswith('#')]) == 1\n\n # Invalid name should yield assertion with helpful message\n args.job_groups = 'openSUSE Tumbleweed FOO'\n with pytest.raises(AssertionError) as e:\n report = openqa_review.generate_report(args)\n assert 'No job group' in str(e.value)\n\n # Multiple job groups can be specified\n args.job_groups = 'openSUSE Argon,openSUSE Leap 42.2 Updates'\n # we don't actually need to check the parsing just make sure\n # openqa_review tries to parse all and as there is no cache page\n # for 'openSUSE Tumbleweed 2.KDE' saved, we assume its corresponding\n # page can not be retrieved.\n # Unfortunately we can not easily be more specific about the\n # exception as python2 raises IOError, python3 FileNotFoundError\n # but we can check the content anyway.\n with pytest.raises(Exception) as e:\n report = str(openqa_review.generate_report(args))\n assert 'group_overview:26' in str(e.value)\n\n # job groups can also be used as an incomplete search tags or regex\n args.job_groups = '(42.2 Updates|Argon)'\n # To increase statement and branch coverage we enable progress report here.\n # It will be invisible but executed.\n args.no_progress = False\n # see above\n with pytest.raises(Exception) as e:\n report = str(openqa_review.generate_report(args))\n assert 'group_overview:26' in str(e.value)\n\n # job group with only a single recent build yields empty report\n args.job_groups = 'openSUSE Leap 42.2 AArch64'\n report = str(openqa_review.generate_report(args))\n assert args.job_groups in report\n # There must be only one job group tag\n assert 'Not enough finished builds' in report\n\n\ndef test_new_job_group_json_syntax_after_openqa_9b50b22():\n args = cache_test_args_factory()\n args.load_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'job_group_after_openqa_9b50b22')\n args.job_group_urls = 'http://openqa.opensuse.org/group_overview/70'\n report = str(openqa_review.generate_report(args))\n assert '0211' in report\n assert 'Green' in report\n\n\ndef test_get_build_urls_to_compare_finds_last_reviewed_if_selected():\n args = cache_test_args_factory()\n browser = browser_factory(args)\n current, reviewed = openqa_review.get_build_urls_to_compare(browser, args.job_group_urls, against_reviewed='0311')\n assert '=0311' in current\n assert '=0307' in reviewed\n\n # If '--against-reviewed' is 'last', search for the latest finished\n current, reviewed = openqa_review.get_build_urls_to_compare(browser, args.job_group_urls, against_reviewed='last')\n assert '=0313' in current\n assert '=0307' in reviewed\n\n # Also accept still running if threshold is increased\n current, reviewed = openqa_review.get_build_urls_to_compare(browser, args.job_group_urls, against_reviewed='last', running_threshold=45)\n assert '=0318' in current\n assert '=0307' in reviewed\n\n # Not accepted if slightly below threshold\n current, reviewed = openqa_review.get_build_urls_to_compare(browser, args.job_group_urls, against_reviewed='last', running_threshold=36)\n assert '=0313' in current\n assert '=0307' in reviewed\n\n\ndef test_non_number_build_nr_also_finds_valid_review_build_urls():\n args = cache_test_args_factory()\n args.load_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'live')\n args.job_group_urls = args.host + '/group_overview/27'\n browser = browser_factory(args)\n current, reviewed = openqa_review.get_build_urls_to_compare(browser, args.job_group_urls, against_reviewed='last')\n assert '=0104%400351' in current # i.e. escaped '0104@0351'\n assert '=0097%400305' in reviewed\n\n # if no review comments are found we revert to the last two finished\n args.load_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'live_no_review')\n browser = browser_factory(args)\n current, reviewed = openqa_review.get_build_urls_to_compare(browser, args.job_group_urls, against_reviewed='last')\n assert '=0104%400351' in current # i.e. escaped '0104@0351'\n assert '=0104%400350' in reviewed # no review comments found, reverting to last two finished\n\n # builds with no finished results are catched\n args.load_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'only_old_invalid_builds')\n args.job_group_urls = args.host + '/group_overview/28'\n browser = browser_factory(args)\n with pytest.raises(openqa_review.NotEnoughBuildsError):\n current, reviewed = openqa_review.get_build_urls_to_compare(browser, args.job_group_urls, against_reviewed='last')\n\n\ndef test_generate_report_with_progress_notification_does_not_fail():\n args = cache_test_args_factory()\n # Not easy to test automatically but at least we can call it and assume it also gives valid results\n args.no_progress = False\n args.job_groups_url = None\n report = str(openqa_review.generate_report(args))\n assert '**Common issues:**' in report\n\n\ndef test_state_report_does_not_break_generation():\n args = cache_test_args_factory()\n args.output_state_results = True\n report = openqa_review.generate_report(args)\n assert report\n\n\ndef test_get_job_groups_yields_job_groups_in_page():\n args = cache_test_args_factory()\n args.job_groups = None\n args.job_group_urls = None\n args.load_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'single_job_group')\n root_url = urljoin(args.host, args.base_url)\n browser = browser_factory(args)\n job_groups = openqa_review.get_job_groups(browser, root_url, args)\n assert len(job_groups.keys()) == 14\n args.load_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'openqa_4.4_dashboard')\n browser = browser_factory(args)\n job_groups = openqa_review.get_job_groups(browser, root_url, args)\n assert sorted(job_groups.keys()) == sorted([\n 'Staging Projects',\n 'Test Parent Group / openSUSE Argon',\n 'openSUSE Krypton',\n 'openSUSE Leap 42.1 JeOS',\n 'openSUSE Leap 42.1 Maintenance',\n 'openSUSE Leap 42.1 Updates',\n 'openSUSE Leap 42.2',\n 'openSUSE Leap 42.2 AArch64',\n 'openSUSE Leap 42.2 Maintenance',\n 'openSUSE Leap 42.2 Updates',\n 'openSUSE Leap Staging Projects',\n 'openSUSE Tumbleweed',\n 'openSUSE Tumbleweed AArch64',\n 'openSUSE Tumbleweed PowerPC'])\n args.exclude_job_groups = '(Krypton|Leap)'\n job_groups = openqa_review.get_job_groups(browser, root_url, args)\n assert sorted(job_groups.keys()) == sorted([\n 'Staging Projects',\n 'Test Parent Group / openSUSE Argon',\n 'openSUSE Tumbleweed',\n 'openSUSE Tumbleweed AArch64',\n 'openSUSE Tumbleweed PowerPC'])\n\n\n# TODO should be covered by doctest already but I can not get coverage analysis to work with doctests in py.test\ndef test_filename_to_url_encodes_valid_url():\n url_object = urlparse(filename_to_url('https%3A::openqa.opensuse.org:group_overview:25'))\n assert url_object.scheme == 'https'\n assert url_object.netloc == 'openqa.opensuse.org'\n\n\ndef test_single_job_group_pages_can_be_cached_from_cache():\n args = cache_test_args_factory()\n with TemporaryDirectory() as tmp_dir:\n args.save_dir = tmp_dir\n args.save = True\n report = str(openqa_review.generate_report(args))\n assert '**Common issues:**' in report\n\n\ndef test_new_tests_appearing_in_builds_are_supported():\n args = cache_test_args_factory()\n args.job_groups = None\n args.builds = '0405,0389'\n args.arch = 'i586'\n args.running_threshold = 10\n args.load_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'differing_tests')\n report = str(openqa_review.generate_report(args))\n # There should be one new test which is failing and has not been there in before\n assert '* [btrfs@zkvm](https://openqa.opensuse.org/tests/181148 \"Failed modules: livecdreboot\")' in report\n\n\ndef test_bugrefs_are_used_for_triaging():\n # python openqa_review/openqa_review.py --load-dir tests/tags_labels --host https://openqa.opensuse.org -J https://openqa.opensuse.org/group_overview/25 -b\n # 1507,1500 --load -n > tests/tags_labels/report25_bugrefs.md\n args = cache_test_args_factory()\n args.job_groups = None\n args.bugrefs = True\n args.builds = '1507,1500'\n args.arch = 'i586'\n args.load_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tags_labels')\n args.show_empty = False\n args.include_softfails = False\n args.verbose_test = 1\n openqa_review.config = ConfigParser()\n openqa_review.config.add_section('product_issues')\n openqa_review.config.set('product_issues', 'base_url', 'https://apibugzilla.suse.com')\n openqa_review.config.set('product_issues', 'username', 'user')\n openqa_review.config.set('product_issues', 'password', 'pass')\n openqa_review.config.set('product_issues', 'report_url', 'https://bugzilla.opensuse.org')\n openqa_review.config.add_section('product_issues:https://openqa.opensuse.org:product_mapping')\n openqa_review.config.set('product_issues:https://openqa.opensuse.org:product_mapping', '25', 'openSUSE Tumbleweed')\n openqa_review.config.add_section('product_issues:https://openqa.opensuse.org:component_mapping')\n openqa_review.config.set('product_issues:https://openqa.opensuse.org:component_mapping', 'installation-bootloader', 'Bootloader')\n openqa_review.config.add_section('test_issues')\n openqa_review.config.set('test_issues', 'api_key', '0123456789ABCDEF')\n openqa_review.config.set('test_issues', 'report_url', 'https://progress.opensuse.org/projects/openqatests/issues/new')\n report = str(openqa_review.generate_report(args))\n # report should feature bug references\n assert 'bsc#' in report\n # and references to 'test issues'\n assert 'poo#' in report\n ref_report = open(os.path.join(args.load_dir, 'report25_bugrefs.md')).read()\n compare_report(report, ref_report)\n\n args.verbose_test = 2\n args.report_links = True\n report = str(openqa_review.generate_report(args))\n ref_report = open(os.path.join(args.load_dir, 'report25_T_bugrefs.md')).read()\n compare_report(report, ref_report)\n\n # report bug link(s) with 'new issue'\n args.load_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tags_labels/report_link_new_issue')\n args.arch = 'arm'\n report = str(openqa_review.generate_report(args))\n ref_report = open(os.path.join(args.load_dir, 'report25_bugrefs_bug_link_new_issue.md')).read()\n compare_report(report, ref_report)\n\n # now, with query issues\n args.verbose_test = 1\n args.report_links = False\n args.query_issue_status = True\n args.load_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tags_labels')\n args.arch = 'i586'\n report = openqa_review.generate_report(args)\n ref_report = open(os.path.join(args.load_dir, 'report25_bugrefs_query_issues.md')).read()\n compare_report(report, ref_report)\n\n # reminder comments\n args.dry_run = True\n report = openqa_review.generate_report(args)\n\n # test double comment prevention code\n p, pr = list(iteritems(report.report))[0]\n report.report[p + 237] = pr\n\n openqa_review.reminder_comment_on_issues(report)\n args.dry_run = False\n\n # now, try filtering: unassigned\n report = openqa_review.generate_report(args)\n openqa_review.filter_report(report, openqa_review.ie_filters[\"unassigned\"])\n ref_report = open(os.path.join(args.load_dir, 'report25_bugrefs_query_issues_filter_unassigned.md')).read()\n compare_report(report, ref_report)\n\n # 2nd filter: closed\n report = openqa_review.generate_report(args)\n openqa_review.filter_report(report, openqa_review.ie_filters[\"closed\"])\n ref_report = open(os.path.join(args.load_dir, 'report25_bugrefs_query_issues_filter_closed.md')).read()\n compare_report(report, ref_report)\n\n # report generated when no todo items are left and some bugref is not accessible\n args.builds = '1508,1500'\n args.query_issue_status = True\n report = openqa_review.generate_report(args)\n ref_report = open(os.path.join(args.load_dir, 'report25_bugrefs_build1508.md')).read()\n compare_report(report, ref_report)\n\n\ndef test_arch_distinguish():\n args = cache_test_args_factory()\n args.arch = None\n args.job_group_urls = args.host + '/group_overview/4'\n\n report = str(openqa_review.generate_report(args))\n assert 'ppc64le' in report\n","repo_name":"Martchus/openqa_review","sub_path":"tests/test_openqa_review.py","file_name":"test_openqa_review.py","file_ext":"py","file_size_in_byte":18693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"22795827183","text":"import numpy as np\nfrom sklearn.base import BaseEstimator\nfrom copy import deepcopy\nfrom sklearn import linear_model\n\n\nclass MyRANSACRegressor(BaseEstimator):\n def __init__(self, base_estimator=None, min_samples=None,\n residual_threshold='Ploshkin', percentile=60,\n is_model_valid=None, max_trials=100, loss='absolute_loss'):\n\n self.base_estimator = base_estimator\n self.min_samples = min_samples\n self.residual_threshold = residual_threshold\n self.percentile = percentile\n self.is_model_valid = is_model_valid\n self.max_trials = max_trials\n self.loss = loss\n\n\n def _score(self, distances):\n eps = np.amax(np.abs(distances))\n return (distances.shape[0] - np.sum(np.abs(distances)) / eps) / eps ** 2\n \n\n def fit(self, X, y):\n if self.base_estimator is not None:\n base_estimator = deepcopy(self.base_estimator)\n else:\n base_estimator = linear_model.LinearRegression()\n\n if self.min_samples is None:\n # assume linear model by default\n min_samples = X.shape[1] + 1\n elif self.min_samples >= 1:\n if self.min_samples % 1 != 0:\n raise ValueError(\"Absolute number of samples must be an \"\n \"integer value.\")\n min_samples = self.min_samples\n else:\n raise ValueError(\"Value for `min_samples` must be scalar and \"\n \"positive integer value.\")\n if min_samples > X.shape[0]:\n min_samples = X.shape[0] / 2\n\n if 0 < self.percentile < 100:\n percentile = self.percentile\n else:\n raise ValueError(\"`percentile` must be float from (0, 100].\")\n\n # adaptive residual threshold\n if self.residual_threshold == 'Ploshkin':\n residual_threshold = lambda \\\n distances: np.maximum(0.05, np.abs(distances[distances < distances.std()]).mean())\n\n elif self.residual_threshold == 'percentile':\n residual_threshold = lambda \\\n distances: np.percentile(np.abs(distances), percentile)\n\n elif callable(self.residual_threshold):\n residual_threshold = self.residual_threshold\n\n else:\n raise ValueError(\n \"residual_threshold should be 'Ploshkin', 'percentile' or a callable.\"\n \"Got %s. \" % self.loss)\n\n\n if self.loss == \"absolute_loss\":\n if y.ndim == 1:\n loss_function = lambda y_true, y_pred: y_true - y_pred\n else:\n loss_function = lambda \\\n y_true, y_pred: np.sum(np.abs(y_true - y_pred), axis=1)\n\n elif self.loss == \"squared_loss\":\n if y.ndim == 1:\n loss_function = lambda y_true, y_pred: np.sign(y_true - y_pred) * (y_true - y_pred) ** 2\n else:\n loss_function = lambda \\\n y_true, y_pred: np.sum((y_true - y_pred) ** 2, axis=1)\n\n elif callable(self.loss):\n loss_function = self.loss\n\n else:\n raise ValueError(\n \"loss should be 'absolute_loss', 'squared_loss' or a callable.\"\n \"Got %s. \" % self.loss)\n\n n_inliers_best = 0\n score_best = 0\n inlier_mask_best = None\n X_inlier_best = None\n y_inlier_best = None\n\n # number of data samples\n n_samples = X.shape[0]\n sample_idxs = np.arange(n_samples)\n\n n_samples, _ = X.shape\n\n for self.n_trials_ in range(1, self.max_trials + 1):\n\n # choose random sample set\n subset_idxs = np.random.choice(n_samples, min_samples, replace=False)\n X_subset = X[subset_idxs]\n y_subset = y[subset_idxs]\n\n # fit model for current random sample set\n base_estimator.fit(X_subset, y_subset)\n\n # check if estimated model is valid\n if (self.is_model_valid is not None and not\n self.is_model_valid(base_estimator, X_subset, y_subset)):\n continue\n\n # residuals of all data for current random sample model\n y_pred = base_estimator.predict(X)\n residuals_subset = loss_function(y, y_pred)\n\n # classify data into inliers and outliers\n inlier_mask_subset = np.abs(residuals_subset) < residual_threshold(residuals_subset)\n n_inliers_subset = np.sum(inlier_mask_subset)\n\n # less inliers -> skip current random sample\n if n_inliers_subset < n_inliers_best:\n continue\n if n_inliers_subset == 0:\n raise ValueError(\"No inliers found, possible cause is \"\n \"setting residual_threshold too low.\")\n\n # extract inlier data set\n inlier_idxs_subset = sample_idxs[inlier_mask_subset]\n X_inlier_subset = X[inlier_idxs_subset]\n y_inlier_subset = y[inlier_idxs_subset]\n\n # score of inlier data set\n score_subset = self._score(residuals_subset[inlier_idxs_subset])\n\n # same number of inliers but worse score -> skip current random\n # sample\n if (n_inliers_subset == n_inliers_best\n and score_subset < score_best):\n continue\n\n # save current random sample as best sample\n n_inliers_best = n_inliers_subset\n score_best = score_subset\n inlier_mask_best = inlier_mask_subset\n X_inlier_best = X_inlier_subset\n y_inlier_best = y_inlier_subset\n\n # if none of the iterations met the required criteria\n if inlier_mask_best is None:\n raise ValueError(\n \"RANSAC could not find valid consensus set, because\"\n \" either the `residual_threshold` rejected all the samples or\"\n \" `is_model_valid` returned False for all\"\n \" `max_trials` randomly \"\"chosen sub-samples. Consider \"\n \"relaxing the \"\"constraints.\")\n\n # estimate final model using all inliers\n base_estimator.fit(X_inlier_best, y_inlier_best)\n\n self.estimator_ = base_estimator\n self.inlier_mask_ = inlier_mask_best\n return self\n\n def predict(X):\n return self.estimator_.predict(X)\n","repo_name":"ploshkin/videogroup","sub_path":"my_ransac_regressor.py","file_name":"my_ransac_regressor.py","file_ext":"py","file_size_in_byte":6379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"37830092007","text":"import sys\n\ninput= sys.stdin.readline\n\nN=int(input())\nns=list(map(int,input().split()))\nans=[0]\nfor i in range(1,N):\n l=ns[i]\n for j in range(i-1,-1,-1):\n if ns[j]>=l:\n ans.append(j+1)\n break\n else:\n ans.append(0)\nprint(' '.join(list(map(str,ans))))","repo_name":"SeungHunL/TIL","sub_path":"baekjun_220807/2493.py","file_name":"2493.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"73091507272","text":"#EXERCISE :15 \n#Reading Files\n\nfrom sys import argv\nscript, filename = argv\n\n\"\"\"\ntesting in file handling of read, write, append and create a new file \n\"\"\"\n# txt = open(\"readme2.txt\",\"x\")\n# txt = txt.write(\"hello this is a new file!\")\n# txt = open(\"readme2.txt\",\"r\")\n# print(txt.read())\n# txt.close()\n#txt = open(filename,\"a\")\n# txt = open(filename)\n# txt.write(\"\\nThis is something new!\")\n# txt = open(filename,\"r\")\n# print(txt.read())\n#----------------------------------\n\ntxt = open(filename)\n\nprint(f\"here is your file {filename} isn't it:\")\nresponse = input()\nif(response=='yes'):\n print(\"\\n\"+txt.read())\nelif(response=='no'):\n print(\"Please check the file name you've specified!\")\nprint(\"\\nDo you want one more file: \")\nresponse2 = input()\nif(response2=='yes'):\n print(\"type another filename to view\")\n file_again = input(\"--> \")\n txt_again = open(file_again)\n print(txt_again.read())\nelif(response2=='no'):\n print(\"Ok bie, come back later\")\nelse:\n print(\"Something went wrong!\")\n","repo_name":"coder0p/LP3THW","sub_path":"exercises/ex15.py","file_name":"ex15.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18159964575","text":"import random\nr1 = int(input(\"Enter row size of Matrix 1 : \"))\nc1 = int(input(\"Enter column size of Matrix 1 : \"))\n\nm1 = []\n\nprint(\"Enter Elements Row Wise\\n\")\nfor i in range(r1):\n a1 = []\n for j in range(c1):\n a1.append(int(input()))\n m1.append(a1)\nprint(\"Matrix 1 is : \\n\")\nfor i in range(r1):\n for j in range(c1):\n print(m1[i][j],end=\" \")\n print()\n\nr2 = int(input(\"Enter row size of Matrix 2 : \"))\nc2 = int(input(\"Enter column size of Matrix 2 : \"))\n\nm2 = []\nprint(\"Enter Elements Row Wise : \\n\")\nfor i in range(r2):\n a2 = []\n for j in range(c2):\n a2.append(int(input()))\n m2.append(a2)\nprint(\"Matrix 2 is : \\n\")\nfor i in range(r2):\n for j in range(c2):\n print(m2[i][j],end=\" \")\n print()\nif c1 == r2:\n m3 = [[random.random()for col in range(c2)]for row in range(r1)]\n for i in range(r1):\n for j in range(c2):\n m3[i][j] = 0\n for k in range(r2):\n m3[i][j] = m1[i][k] * m2[k][j]\n print(\"The Resultant Matrix is : \")\n for i in range(r1):\n for j in range(c2):\n print(m3[i][j],end=\" \")\n print()\nelse:\n print(\"Matrix Multiplication Can Not be Possible\")\nprint()\nif r1 == r2 and c1 == c2:\n m4 = [[random.random()for col in range(c1)]for row in range(r1)]\n\n for i in range(r1):\n for j in range(c2):\n m4[i][j] = m1[i][j] + m2[i][j]\n print(\"\\nThe Resultant Matrix is : \")\n for i in range(r1):\n for j in range(c2):\n print(m4[i][j],end=\" \")\n print()\nelse:\n print(\"Matrix Addition Can Not be Possible\")\n \n","repo_name":"nihar-ranjan-samantaray/python-beginner","sub_path":"matrix_addition_multiplication.py","file_name":"matrix_addition_multiplication.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"41612961098","text":"import json, boto3\n\nfrom django.views import View\nfrom django.http import JsonResponse\nfrom django.db.models import Q\nfrom django.db import transaction\nfrom django.conf import settings\n\nfrom recipes.models import Content, ContentImage, HashTag, Ingredient, Recipe, RecipeComment, RecipeProduct, RecipeLike, RecipeCommentLike\n\nfrom utils.fileuploader_api import FileUploader, FileHandler\nfrom utils.login_decorator import login_decorator\nfrom utils.word_extract import word_extract\nfrom utils.ip_get_modul import get_client_ip\n\nconfig = {\n \"bucket\" : settings.AWS_STORAGE_BUCKET_NAME\n}\n\nfile_uploader = FileUploader(boto3.client('s3'), config)\nfile_handler = FileHandler(file_uploader)\n\n\nclass RecipeListView(View):\n def get(self, request, menu_id):\n tag = int(request.GET.get('tag',1))\n main = int(request.GET.get('main', 1))\n sub = int(request.GET.get('sub', 1))\n sort = int(request.GET.get('sort', 1))\n search = request.GET.get('search')\n\n if sort > 4:\n sort_set = {\n 1 : \"-id\",\n 2 : \"-hit\",\n 3 : \"-recipelike__recipe_id\",\n }\n recipe_list = Recipe.objects.filter(menu_id = menu_id).select_related('user').order_by(sort_set[sort])\n else:\n recipe_list = Recipe.objects.filter(menu_id = menu_id).select_related('user').order_by(\"-hit\", \"-recipelike__recipe_id\")\n \n q = Q()\n \n if main == 1:\n q = Q()\n if sub > 1:\n q = Q(sub_category_id = sub)\n elif main > 1 :\n q = Q(main_category_id = main)\n if sub > 1:\n q = Q(main_category_id = main) & Q(sub_category_id = sub)\n\n recipe_list = recipe_list.filter(q) \n\n if search:\n q = Q()\n if tag == 1:\n q &= Q(title__icontains = search)\n elif tag == 2:\n q &= Q(content__content__icontains=search)|\\\n Q(hashtag__name__icontains=search)|\\\n Q(intro__country__icontains=search)\n elif tag == 3:\n q &= Q(title__icontains=search)|\\\n Q(content__content__icontains=search)|\\\n Q(hashtag__name__icontains=search)|\\\n Q(intro__country__icontains=search) \n elif tag == 4:\n q &= Q(user__name__icontains=search) \n \n recipe_list = recipe_list.filter(q)\n\n result = [{\n \"id\" : recipe.id,\n \"title\" : recipe.title,\n \"recipe_thumbnail\" : recipe.thumbnail,\n \"intro\" : recipe.intro,\n \"user_id\" : recipe.user.id,\n \"user_thumbnauil\" : recipe.user.thumbnail,\n \"user_name\" : recipe.user.name,\n \"rating_id\" : recipe.user.rating_id,\n \"rating_name\" : recipe.user.rating.name,\n \"rating_mark_image\": recipe.user.rating.mark_image,\n \"hit\" : recipe.hit,\n \"like_count\" : recipe.recipelike_set.all().count(),\n \"comment_count\" : recipe.recipecomment_set.all().count()\n }for recipe in recipe_list]\n\n return JsonResponse({\"result\": result}, status = 200)\n\nclass RecipeWrite(View):\n @login_decorator\n def post(self, request, menu_id):\n title = request.POST.get(\"title\")\n intro = request.POST.get(\"intro\")\n thumbnail = request.FILES.get(\"thumbnail\")\n user_id = request.user.id\n cooktime = request.POST.get(\"cooktime\")\n serving = request.POST.get(\"serving\")\n difficulty = request.POST.get(\"difficulty\")\n main_key = request.POST.get(\"main_category_id\")\n sub_key = request.POST.get(\"sub_category_id\")\n ingredients = request.POST[\"ingredient\"]\n products = request.POST[\"product\"]\n contents = request.POST[\"content\"]\n content_images = request.FILES.getlist(\"content_image\")\n hash_tag = request.POST.getlist(\"hash_tag\")\n\n ingredients = json.loads(ingredients)\n products = json.loads(products)\n contents = json.loads(contents)\n\n extension = ['PNG', 'png','jpg', 'JPG', 'GIF', 'gif', 'JPEG', 'jpeg']\n if not str(thumbnail).split('.')[-1] in extension:\n return JsonResponse({\"message\":\"INVALID EXTENSION\"}, status = 400)\n \n thumbnail_url = file_handler.upload(file=thumbnail) \n \n main_category_set = {\n \"전체보기\": 1,\n \"한식\" : 2,\n \"중식\" : 3,\n \"일식\" : 4,\n \"양식\" : 5,\n \"그외\" : 6\n } \n sub_category_set = {\n \"전체보기\": 1,\n \"메인요리\": 2,\n \"밑반찬\" : 3,\n \"간식\" : 4,\n \"안주\" : 5\n } \n\n with transaction.atomic():\n recipe = Recipe.objects.create(\n title = title,\n intro = intro,\n thumbnail = thumbnail_url,\n user_id = user_id,\n cooktime = cooktime,\n serving = serving,\n difficulty = difficulty,\n hit = 0,\n menu_id = menu_id,\n main_category_id= main_category_set[main_key],\n sub_category_id = sub_category_set[sub_key]\n )\n\n ingredient_list = [Ingredient(name = i[\"name\"], quantity = i[\"quantity\"], recipe_id = recipe.id)for i in ingredients]\n\n product_list = [RecipeProduct(product_id = i[\"id\"], recipe_id = recipe.id)for i in products ] \n \n hashtag_list = [HashTag(name=i) for i in hash_tag ]\n \n \n Ingredient.objects.bulk_create(ingredient_list)\n RecipeProduct.objects.bulk_create(product_list)\n HashTag.objects.bulk_create(hashtag_list)\n\n content_image_list = []\n for image in content_images:\n extension = ['PNG', 'png','jpg', 'JPG', 'GIF', 'gif', 'JPEG', 'jpeg']\n if not str(image).split('.')[-1] in extension:\n return JsonResponse({\"message\":\"INVALID EXTENSION\"}, status = 400)\n image_url = file_handler.upload(file=image) \n content_image_list.append(image_url)\n\n for i in range(len(content_image_list)):\n with transaction.atomic():\n content=Content.objects.create(\n step = contents[i][\"step\"],\n content = contents[i][\"content\"],\n recipe_id = recipe.id\n )\n ContentImage.objects.create(\n image = content_image_list[i],\n content_id = content.id\n ) \n\n return JsonResponse({\"message\": \"SUCCESS\"}, status = 200)\n\nclass RecipeDetailView(View):\n def get(self, request, id):\n recipe = Recipe.objects.get(id = id)\n\n result = {\n \"id\" : recipe.id,\n \"tilte\" : recipe.title,\n \"intro\" : recipe.intro,\n \"thumbnail\" : recipe.thumbnail,\n \"hit\" : recipe.hit,\n \"like_count\" : recipe.recipelike_set.all().count(),\n \"comment_count\" : recipe.recipecomment_set.all().count(),\n \"user_id\" : recipe.user_id,\n \"name\" : recipe.user.name,\n \"user_thumbnail\" : recipe.user.thumbnail,\n \"rating_id\" : recipe.user.rating_id,\n \"rating_name\" : recipe.user.rating.name,\n \"rating_mark_image\": recipe.user.rating.mark_image,\n \"cooktime\" : recipe.cooktime,\n \"serving\" : recipe.serving,\n \"difficulty\" : recipe.difficulty,\n \"ingredient\" : [{\n \"id\" : ingre.id,\n \"name\" : ingre.name,\n \"quantity\": ingre.quantity\n } for ingre in recipe.ingredient_set.all()],\n \"product\" : [{\n \"id\" : product.product.id,\n \"name\" : product.product.name,\n \"price\": product.product.price,\n \"image\": product.product.image\n } for product in recipe.recipeproduct_set.all()],\n \"content\" : [{\n \"id\" : content.id,\n \"step\" : content.step,\n \"content\": content.content,\n \"image\" : [i.image for i in content.contentimage_set.all()],\n }for content in recipe.content_set.all()],\n \"hash_tag\" : [{\n \"id\" : hash.hashtag.id,\n \"name\": hash.hashtag.name\n }for hash in recipe.recipehashtag_set.all()], \n }\n recipe.hit += 1\n recipe.save()\n return JsonResponse({\"result\": result}, status = 200)\n\n\nclass RecipeCommnetView(View):\n @login_decorator\n def post(self, request, recipe_id):\n data = json.loads(request.body)\n\n content = data.get('content')\n tag = data.get('tag')\n\n RecipeComment.objects.create(\n content = content,\n tag = tag,\n user_id = request.user.id,\n recipe_id = recipe_id,\n parent_comment_id = None\n )\n\n return JsonResponse({\"message\": \"SUCCESS\"}, status = 200)\n\n def get(self, request, recipe_id):\n \n recipe_comments = RecipeComment.objects.filter(recipe_id = recipe_id)\n recipe_comments = recipe_comments.filter(parent_comment_id = None)\n recipe_count = len(recipe_comments)\n result = [{ \n \"id\" : comment.id,\n \"user_id\" : comment.user_id,\n \"user_name\" : comment.user.name,\n \"tag\" : comment.tag,\n \"content\" : comment.content,\n \"created_at\" : comment.created_at,\n \"recipe_comment_like\": comment.recipecommentlike_set.all().count(),\n \"counter\" : comment.parent_comment_id\n }for comment in recipe_comments]\n \n return JsonResponse({\"result\": result}, status = 200)\n @login_decorator\n def delete(self, request, recipe_id, comment_id):\n RecipeComment.objects.get(recipe_id = recipe_id, id = comment_id).delete() \n\n return JsonResponse({\"message\": \"SUCCESS\"}, status = 200)\nclass ReCommentView(View):\n def get(self, request, recipe_id, comment_id):\n recomments = RecipeComment.objects.filter(parent_comment_id = comment_id, recipe_id = recipe_id)\n\n result = [{ \n \"id\" : comment.id,\n \"user_id\" : comment.user_id,\n \"user_name\" : comment.user.name,\n \"tag\" : comment.tag,\n \"content\" : comment.content,\n \"created_at\" : comment.created_at,\n }for comment in recomments]\n \n return JsonResponse({\"result\": result}, status = 200)\n\n @login_decorator\n def post(self,request, recipe_id):\n data = json.loads(request.body)\n\n content = data.get('content')\n recomment_id = data.get('recomment_id')\n\n RecipeComment.objects.create(\n content = content,\n tag = True,\n user_id = request.user.id,\n recipe_id = recipe_id,\n parent_comment_id = recomment_id\n )\n\n return JsonResponse({\"message\": \"SUCCESS\"}, status = 200)\n\n\nclass RecipeSimiltude(View):\n def get(self, request, recipe_id):\n recipe_content = Content.objects.filter(recipe_id = recipe_id)\n \n content = \"\"\n for i in recipe_content:\n content += i.content\n \n word_rank_list = word_extract(content)[:5]\n recipe_lists = []\n for i in word_rank_list:\n r = Recipe.objects.filter(content__content__icontains = i).first()\n recipe_lists.append(r)\n \n result = [{\n \"id\" : recipe.id,\n \"title\" : recipe.title,\n \"thumbnail\": recipe.thumbnail\n }for recipe in recipe_lists]\n\n return JsonResponse({\"result\": result}, status = 200) \n\nclass RecipeLikeView(View):\n @login_decorator\n def post(self, request, recipe_id):\n RecipeLike.objects.create(\n user_id = request.user.id,\n recipe_id = recipe_id\n )\n return JsonResponse({\"message\": \"SUCCESS\"}, status = 200)\n\n @login_decorator\n def delete(self, request, recipe_id):\n try:\n recipe_list = RecipeLike.objects.get(\n user_id = request.user.id,\n recipe_id = recipe_id\n )\n recipe_list.delete()\n\n return JsonResponse({\"message\": \"SUCCESS\"}, status = 205)\n except RecipeLike.DoesNotExist:\n return JsonResponse({\"message\" : \"DoesNotExist\"}, status = 401) \n \nclass RecipeCommentLikeView(View):\n @login_decorator\n def post(self, request, recipe_comment_id):\n RecipeCommentLike.objects.create(\n user_id = request.user.id,\n recipe_comment_id = recipe_comment_id\n )\n return JsonResponse({\"message\": \"SUCCESS\"}, status = 200)\n\n @login_decorator\n def delete(self, request, recipe_comment_id):\n try:\n recipe_list = RecipeCommentLike.objects.get(\n user_id = request.user.id,\n recipe_comment_id = recipe_comment_id\n )\n recipe_list.delete()\n\n return JsonResponse({\"message\": \"SUCCESS\"}, status = 205)\n except RecipeCommentLike.DoesNotExist:\n return JsonResponse({\"message\" : \"DoesNotExist\"}, status = 401) \n \n","repo_name":"nicholas019/kurly-borikkori-backend","sub_path":"recipes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"44491543447","text":"from django.conf.urls import patterns, url, include\nfrom django.views.generic.base import TemplateView\n\nurlpatterns = patterns(\n '',\n url(r'^$', TemplateView.as_view(template_name='layout.html'),\n name='layout'),\n url(r'^auth/', include('auth.urls')),\n url(r'^api/', include('api.urls')),\n)\n","repo_name":"pombredanne/snippit","sub_path":"snippit/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"26675393601","text":"\r\nimport random\r\nimport turtle\r\n\r\n\r\ndef shape(color,side,num,x,y):\r\n turtle.up()\r\n turtle.goto(x,y)\r\n turtle.down()\r\n turtle.color(color)\r\n turtle.begin_fill()\r\n a=180-(((num-2)*180)//num)\r\n for _ in range (num+1):\r\n turtle.left(a)\r\n turtle.forward(side)\r\n turtle.end_fill()\r\n\r\n\r\n\r\nslist=[\"yellow\",\"white\",\"green\",\"blue\",\"red\",\"orange\",\"purple\"]\r\n\r\n\r\n\r\n\r\nfor _ in range (11):\r\n color=random.choice(slist)\r\n x=random.randint(-200,200)\r\n y=random.randint(-200,200)\r\n side= random.randint(20,100)\r\n num= random.randint(3,10)\r\n\r\n shape(color,side,num,x,y)\r\nturtle.done()\r\n","repo_name":"dainpark525/dain","sub_path":"리스트 과제.py","file_name":"리스트 과제.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"754604896","text":"# Back (retro) Propagation\n# This python function shows how to implement back (retro) propagation\n# in a classification model.\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\nops.reset_default_graph()\n\n# Create graph and start a session\nsess = tf.Session()\n\n# This is a classification example.\n# There are 200 values of the corresponding output index\n# We will fit the binary classification model:\n# If sigmoid(x+b) < 0.5 -> 0 else 1\n# Theoretically, the constant bias b should be -(mean1 + mean2)/2\n\nops.reset_default_graph()\n\n# Create graph\nsess = tf.Session()\n\n# We first create 100 sample data which are random values from a normal = N(-1, 0.2)\n#np.concatenate((np.random.normal(-1, 0.2, 100), np.random.normal(4, 0.3, 110)))\n\nx_sample1=np.random.normal(-1, 0.2, 100)\nx_sample2=np.random.normal(4, 0.3, 110)\nx_num = np.concatenate((x_sample1, x_sample2))\n\n\n## we now create 100 values of 0\ny_target1=np.repeat(0., 100)\n\n##next we create 110 values of 1\ny_target2=np.repeat(1., 110)\n\n#y_vals1 = np.concatenate((np.repeat(0., 100), np.repeat(1., 110)))\ny_num=np.concatenate((y_target1, y_target2))\n\nprint(x_num)\nprint(y_num)\n\n##Now we create 2 placeholders\nx_data = tf.placeholder(shape=[1], dtype=tf.float32)\ny_target = tf.placeholder(shape=[1], dtype=tf.float32)\n\n# We now create a variable called bias (one model parameter = b)\nb = tf.Variable(tf.random_normal(mean=5, shape=[1]))\n\n#Next we create the activation operation using sigmoid function: sigmoid(x + b)\n# The sigmoid() is the non-linear, activation part of the final loss function\ny_out = tf.add(x_data, b)\n\n# Now we have to add another dimension to each (batch size of 1)\ny_out_expanded = tf.expand_dims(y_out, 0)\ny_target_expanded = tf.expand_dims(y_target, 0)\n\n# Initialize variables\ninit = tf.global_variables_initializer()\nsess.run(init)\n\n# Now calculate the classification loss which typically uses the cross entropy loss \ncrossentropyloss = tf.nn.sigmoid_cross_entropy_with_logits(logits=y_out_expanded, labels=y_target_expanded)\n\n# Next we define the Optimizer\ntheOptimizer = tf.train.GradientDescentOptimizer(0.04)\ntrain_step = theOptimizer.minimize(crossentropyloss)\n\n# USe for-loop to start the training...the following for-loop will run 1800 times.\nfor i in range(1800):\n rand_index = np.random.choice(210) ##0 to 209 \n rand_x = [x_num[rand_index]]\n rand_y = [y_num[rand_index]]\n \n sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})\n if (i+1)%100==0:\n print('Step#' + str(i+1) + ' b=' + str(sess.run(b)))\n print('Loss=' + str(sess.run(crossentropyloss, feed_dict={x_data: rand_x, y_target: rand_y})))\n\n# Now it is time to evaluate predictions\npredictions = [] ###empty list\nfor i in range(len(x_num)): ##len() function returns total data number for x_num.\n x_val = [x_num[i]]\n prediction = sess.run(tf.round(tf.sigmoid(y_out)), feed_dict={x_data: x_val})\n predictions.append(prediction[0])\n \naccuracy = sum(x==y for x,y in zip(predictions, y_num))/210.\nprint('Final Achieved Accuracy = ' + str(np.round(accuracy, 2)))","repo_name":"JunzuoWan/DeepLearning_MachineLearning","sub_path":"ClassificationLossMinimizeUsingBackProp.py","file_name":"ClassificationLossMinimizeUsingBackProp.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"3906728065","text":"\"\"\"Unique exchange\n\nRevision ID: e273ab9d6b4e\nRevises: 27a6cad86571\nCreate Date: 2022-08-24 15:58:32.689589\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e273ab9d6b4e'\ndown_revision = '27a6cad86571'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_unique_constraint('unique_exchange_rates', 'exchange_rates', ['bank_id', 'currency_id', 'date'])\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint('unique_exchange_rates', 'exchange_rates', type_='unique')\n # ### end Alembic commands ###\n","repo_name":"ZifeRRoT/currencyApi","sub_path":"alembic/versions/e273ab9d6b4e_unique_exchange.py","file_name":"e273ab9d6b4e_unique_exchange.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"33162718737","text":"# coding: utf-8\nimport datetime\n\nfrom flask import render_template, redirect, url_for, current_app, flash, request, abort\nfrom flask.ext.login import login_required\nfrom containers import app, db\nfrom containers.models import Container, Manufacturer, Investor, Renter, RentPeriod, RentPeriodItem\nfrom containers.forms import ContainerForm, ManufacturerForm, InvestorForm, RenterForm, RentContainerPeriodForm, RentPeriodItemForm\n\n\n@app.route('/')\ndef index():\n return redirect(url_for('containers'))\n\n\n@app.route('/periods/')\n@login_required\ndef periods():\n container_id = request.args.get('container_id')\n if container_id is None:\n abort(404)\n items = RentPeriod.query.filter(RentPeriod.container_id == int(container_id)).order_by(RentPeriod.begin_date).all()\n return render_template('periods.html', items=items)\n\n\n@app.route('/periods//', methods=['GET', 'POST'])\n@login_required\ndef period(period_id=None):\n if period_id is None:\n abort(404)\n period_inst = RentPeriod.query.get(period_id)\n form = RentContainerPeriodForm(obj=period_inst)\n if form.validate_on_submit():\n form.populate_obj(period_inst)\n db.session.add(period_inst)\n try:\n db.session.commit()\n except Exception as e:\n db.session.rollback()\n current_app.logger.exception(e)\n flash(u'Произошла ошибка при сохранении периода аренды', 'danger')\n else:\n flash(u'Период аренды контейнера был успешно обновлен', 'success')\n return redirect(url_for('periods', container_id=period_inst.container_id, period_id=period_inst.id))\n\n return render_template('period.html', form=form, period_id=period_inst.id)\n\n\n@app.route('/renters/')\n@login_required\ndef renters():\n section = 'renters'\n items = Renter.query.all()\n return render_template('renters.html', items=items, section=section)\n\n\n@app.route('/renters/add/', methods=['GET', 'POST'])\n@app.route('/renters//', methods=['GET', 'POST'])\n@login_required\ndef renter(renter_id=None):\n renter_inst = Renter.query.get(renter_id) if renter_id is not None else Renter()\n form = RenterForm(obj=renter_inst)\n if form.validate_on_submit():\n form.populate_obj(renter_inst)\n db.session.add(renter_inst)\n try:\n db.session.commit()\n except Exception as e:\n db.session.rollback()\n current_app.logger.exception(e)\n else:\n flash(u'Арендатор успешно добавлен' if renter_id is None else u'Арендатор успешно обновлен', 'success')\n return redirect(url_for('renters'))\n return render_template('renter.html', form=form, renter_id=renter_id)\n\n\n@app.route('/investors/')\n@login_required\ndef investors():\n section = 'investors'\n items = Investor.query.all()\n return render_template('investors.html', items=items, section=section)\n\n\n@app.route('/investors/add/', methods=['GET', 'POST'])\n@app.route('/investors//', methods=['GET', 'POST'])\n@login_required\ndef investor(investor_id=None):\n investor_inst = Investor.query.get(investor_id) if investor_id is not None else Investor()\n form = InvestorForm(obj=investor_inst)\n if form.validate_on_submit():\n form.populate_obj(investor_inst)\n db.session.add(investor_inst)\n try:\n db.session.commit()\n except Exception as e:\n db.session.rollback()\n current_app.logger.exception(e)\n else:\n flash(u'Инвестор успешно добавлен' if investor_id is None else u'Инвестор успешно обновлен', 'success')\n return redirect(url_for('investors'))\n return render_template('investor.html', form=form, investor_id_id=investor_id)\n\n\n@app.route('/manufacturers/')\n@login_required\ndef manufacturers():\n section = 'manufacturers'\n items = Manufacturer.query.all()\n return render_template('manufacturers.html', items=items, section=section)\n\n\n@app.route('/manufacturers/add/', methods=['GET', 'POST'])\n@app.route('/manufacturers//', methods=['GET', 'POST'])\n@login_required\ndef manufacturer(manufacturer_id=None):\n manufacturer_inst = Manufacturer.query.get(manufacturer_id) if manufacturer_id is not None else Manufacturer()\n form = ManufacturerForm(obj=manufacturer_inst)\n if form.validate_on_submit():\n form.populate_obj(manufacturer_inst)\n db.session.add(manufacturer_inst)\n try:\n db.session.commit()\n except Exception as e:\n db.session.rollback()\n current_app.logger.exception(e)\n else:\n flash(u'Производитель успешно добавлен' if manufacturer_id is None else u'Производитель успешно обновлен', 'success')\n return redirect(url_for('manufacturers'))\n return render_template('manufacturer.html', form=form, manufacturer_id=manufacturer_id)\n\n\n@app.route('/containers/')\n@login_required\ndef containers():\n section = 'containers'\n items = Container.query.order_by(Container.id).all()\n return render_template('containers.html', items=items, section=section)\n\n\n@app.route('/containers/add/', methods=['GET', 'POST'])\n@app.route('/containers//', methods=['GET', 'POST'])\n@login_required\ndef container(container_id=None):\n container_inst = Container.query.get(container_id) if container_id is not None else Container()\n form = ContainerForm(obj=container_inst)\n if form.validate_on_submit():\n form.populate_obj(container_inst)\n db.session.add(container_inst)\n try:\n db.session.commit()\n except Exception as e:\n db.session.rollback()\n current_app.logger.exception(e)\n else:\n flash(u'Блок контейнер успешно добавлен' if container_id is None else u'Блок контейнер успешно обновлен', 'success')\n return redirect(url_for('containers'))\n return render_template('container.html', form=form, container_id=container_id)\n\n\n@app.route('/period_form/', methods=['GET', 'POST'])\n@login_required\ndef period_form():\n def add_months(sourcedate, months):\n import calendar\n month = sourcedate.month - 1 + months\n year = sourcedate.year + month / 12\n month = month % 12 + 1\n day = min(sourcedate.day, calendar.monthrange(year, month)[1])\n return datetime.date(year, month, day)\n container_id = request.form.get('container_id') or request.args.get('container_id')\n if container_id is None or not container_id.isdigit():\n abort(404)\n period = RentPeriod()\n container = Container.query.get(int(container_id))\n\n period.begin_date = datetime.date.today()\n period.status = 'open'\n period_form = RentContainerPeriodForm(obj=period)\n if period_form.validate_on_submit():\n period_form.populate_obj(period)\n period.container = container\n period.status = 'open'\n container.status = 'arend'\n rent_period_item = RentPeriodItem()\n rent_period_item.rent_period = period\n rent_period_item.begin_date = period.begin_date\n rent_period_item.end_date = add_months(rent_period_item.begin_date, 1)\n rent_period_item.summ = period.summ\n db.session.add_all([period, container, rent_period_item])\n try:\n db.session.commit()\n except Exception as e:\n db.session.rollback()\n current_app.logger.exception(e)\n flash(u'Произошла ошибка сохранения состояния', 'danger')\n else:\n flash(u'Блок контейнер успешно поставлен в аренду', 'success')\n return 'OK'\n return render_template('ajax/container_period_form.html', form=period_form, container_id=container_id)\n\n\n@app.route('/edit_month//', methods=['GET', 'POST'])\n@login_required\ndef edit_month(month_id):\n month = RentPeriodItem.query.get(month_id)\n form = RentPeriodItemForm(obj=month)\n if form.validate_on_submit():\n form.populate_obj(month)\n db.session.add(month)\n try:\n db.session.commit()\n except Exception as e:\n db.session.rollback()\n current_app.logger.exception(e)\n flash(u'Произошла ошибка сохранения', 'danger')\n else:\n flash(u'Изменения успешно вступили в силу', 'success')\n return redirect(url_for('periods', container_id=month.rent_period.container_id))\n\n return render_template('month.html', form=form)\n\n\n@app.route('/end_arend//', methods=['GET'])\n@login_required\ndef end_arend(period_id):\n period = RentPeriod.query.get(period_id)\n period.status = 'closed'\n container = period.container\n container.status = 'sklad'\n db.session.add_all([period, container])\n try:\n db.session.commit()\n except Exception as e:\n db.session.rollback()\n current_app.logger.exception(e)\n flash(u'Произошла ошибка сохранения', 'danger')\n else:\n flash(u'Аренда успешно завершена', 'success')\n finally:\n return redirect(url_for('periods', container_id=container.id))\n\n\n@app.errorhandler(401)\ndef not_authorized(error):\n return render_template('401.html', error=error), 401\n\n\n@app.errorhandler(404)\ndef error_404(error):\n return render_template('404.html', error=error), 404\n\n\n@app.errorhandler(500)\ndef error_500(error):\n return render_template('500.html', error=error), 500\n\n\n@app.errorhandler(501)\ndef not_implemented(error):\n return render_template('501.html', error=error), 501\n","repo_name":"mkaplenko/containers","sub_path":"src/containers/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"27293636304","text":"import heapq as hq\n\n\ndef solution(jobs):\n answer = 0\n N = len(jobs)\n jobs.sort()\n waiting = []\n current = jobs[0][0]\n total = 0\n check = 0\n while check < N:\n while jobs and jobs[0][0] <= current:\n job = hq.heappop(jobs)\n hq.heappush(waiting, [job[1], job[0]])\n\n if waiting:\n wait = hq.heappop(waiting)\n current = current + wait[0]\n total += current - wait[1]\n check += 1\n else:\n current += 1\n\n answer = total / N\n\n return int(answer)\n","repo_name":"chamchiking/algorithm-python-study","sub_path":"week2/programmers/heap_problem2/mincheol.py","file_name":"mincheol.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"17004047546","text":"import gametools\nimport room\n\ndef load():\n roomPath = gametools.findGamePath(__file__)\n exists = room.check_loaded(roomPath)\n if exists: return exists\n \n trap = room.Room('gold room', roomPath)\n trap.indoor = True\n trap.set_description('room with gold in the center', 'You are in a large room. In the center of the room is a big pile of gold coins.')\n trap.add_exit('east', 'domains.school.dungeon.small_tunnel')\n trap.add_names('room', 'trap')\n trap.add_adjectives('gold')\n\n gold = gametools.clone('domains.school.dungeon.gold')\n trap.insert(gold)\n return trap\n","repo_name":"1Bayshore/old-skool-text-game","sub_path":"domains/school/dungeon/trap.py","file_name":"trap.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"1349412213","text":"import os\nimport sys\nfrom src.exception import CustomException\nfrom src.logger import logging\nfrom src.utils import save_object\nfrom dataclasses import dataclass\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import OneHotEncoder, FunctionTransformer, StandardScaler\nfrom sklearn.compose import ColumnTransformer\n\n@dataclass\nclass DataTransformationConfig:\n preprocessor_obj_file_path = os.path.join('artifacts',\"preprocessor.pkl\")\n\nclass DataTransformation:\n def __init__(self):\n self.data_transformation_config = DataTransformationConfig()\n\n def get_data_transformer_object(self):\n '''\n This function is responsible for data transformation\n \n '''\n \n\n try:\n\n numerical_columns = ['age', 'avg_glucose_level', 'bmi']\n\n categorical_columns = [\n 'gender', \n 'ever_married', \n 'work_type',\n 'Residence_type', \n 'smoking_status',\n 'hypertension', \n 'heart_disease'\n ]\n\n numerical_pipeline= Pipeline(\n steps=[\n (\"imputer\",SimpleImputer(missing_values=np.nan, strategy=\"mean\")),\n (\"scaler\",StandardScaler())\n\n ]\n )\n logging.info(f\"Numerical Columns: {numerical_columns}\")\n\n categorical_pipeline=Pipeline(\n\n steps=[\n (\"imputer\",SimpleImputer(strategy=\"most_frequent\")),\n (\"onehot-encoder\",OneHotEncoder(handle_unknown=\"ignore\",drop='first'))\n ]\n\n )\n\n logging.info(f\"Categorical Columns: {categorical_columns}\")\n\n preprocessor = ColumnTransformer(\n [\n (\"num_pipeline\",numerical_pipeline,numerical_columns),\n (\"cat_pipelines\",categorical_pipeline,categorical_columns)\n\n ]\n\n\n )\n\n return preprocessor\n \n except Exception as e:\n logging.exception(CustomException(e,sys))\n raise CustomException(e,sys)\n\n def initiate_data_transformation(self,train_path,test_path):\n\n try:\n train_df = pd.read_csv(train_path)\n test_df = pd.read_csv(test_path)\n\n logging.info(\"Read train and test data completed\")\n\n columns_to_convert = ['hypertension', 'heart_disease']\n train_df[columns_to_convert] = train_df[columns_to_convert].astype(str)\n test_df[columns_to_convert] = test_df[columns_to_convert].astype(str)\n logging.info(\"Converted Numerical Columns to Categorical Columns Successfully...\")\n\n logging.info(\"Obtaining preprocessing object\")\n\n preprocessing_obj = self.get_data_transformer_object()\n\n drop_feature = 'id'\n target_column_name=\"stroke\"\n\n input_feature_train_df = train_df.drop(columns=[drop_feature,target_column_name],axis=1)\n target_feature_train_df = train_df[target_column_name]\n\n input_feature_test_df = test_df.drop(columns=[drop_feature,target_column_name],axis=1)\n target_feature_test_df = test_df[target_column_name]\n\n logging.info(\n f\"Applying preprocessing object on training dataframe and testing dataframe.\"\n )\n\n input_feature_train_arr = preprocessing_obj.fit_transform(input_feature_train_df)\n input_feature_test_arr = preprocessing_obj.transform(input_feature_test_df)\n\n train_arr = np.c_[\n input_feature_train_arr, np.array(target_feature_train_df)\n ]\n test_arr = np.c_[input_feature_test_arr, np.array(target_feature_test_df)]\n\n logging.info(f\"Saved preprocessing object.\")\n\n save_object(\n\n file_path=self.data_transformation_config.preprocessor_obj_file_path,\n obj=preprocessing_obj\n\n )\n\n return (\n train_arr,\n test_arr,\n self.data_transformation_config.preprocessor_obj_file_path,\n )\n except Exception as e:\n logging.exception(CustomException(e,sys))\n raise CustomException(e,sys)","repo_name":"ni3choudhary/mlproject-end-to-end","sub_path":"src/components/data_transformation.py","file_name":"data_transformation.py","file_ext":"py","file_size_in_byte":4343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"244309026","text":"class Solution(object):\n def longestWord(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: str\n \"\"\"\n words.sort()\n words.sort(key = lambda word:len(word))\n start = [word for word in words if len(word)==1]\n candidates = []\n for word in words:\n if word in start:\n candidates.append(word)\n else:\n for idx,candidate in enumerate(candidates):\n if word[:-1]== candidate:\n candidates.append(word)\n candidates.sort(key=lambda word:(len(word),word))\n last = candidates[-1]\n print(candidates)\n for i in range(len(candidates)-1,-1,-1):\n if len(candidates[i]) < len(last):\n return last\n last = candidates[i]\nsol = Solution()\nwords = ['b',\"a\", \"banana\"]\nprint(sol.longestWord(words))\n","repo_name":"lizyang95/leetcode","sub_path":"leetcode7/longestWord.py","file_name":"longestWord.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"28774094124","text":"from ooo.oenv.env_const import UNO_NONE\nimport typing\n\n\nclass ChartDataValue(object):\n \"\"\"\n Struct Class\n\n describes a single data value, including the error\n \n This struct is currently used nowhere.\n \n .. deprecated::\n \n Class is deprecated.\n\n See Also:\n `API ChartDataValue `_\n \"\"\"\n __ooo_ns__: str = 'com.sun.star.chart'\n __ooo_full_ns__: str = 'com.sun.star.chart.ChartDataValue'\n __ooo_type_name__: str = 'struct'\n typeName: str = 'com.sun.star.chart.ChartDataValue'\n \"\"\"Literal Constant ``com.sun.star.chart.ChartDataValue``\"\"\"\n\n def __init__(self, Value: typing.Optional[float] = 0.0, HighError: typing.Optional[float] = 0.0, LowError: typing.Optional[float] = 0.0) -> None:\n \"\"\"\n Constructor\n\n Arguments:\n Value (float, optional): Value value.\n HighError (float, optional): HighError value.\n LowError (float, optional): LowError value.\n \"\"\"\n super().__init__()\n\n if isinstance(Value, ChartDataValue):\n oth: ChartDataValue = Value\n self.Value = oth.Value\n self.HighError = oth.HighError\n self.LowError = oth.LowError\n return\n\n kargs = {\n \"Value\": Value,\n \"HighError\": HighError,\n \"LowError\": LowError,\n }\n self._init(**kargs)\n\n def _init(self, **kwargs) -> None:\n self._value = kwargs[\"Value\"]\n self._high_error = kwargs[\"HighError\"]\n self._low_error = kwargs[\"LowError\"]\n\n\n @property\n def Value(self) -> float:\n \"\"\"\n value by itself.\n \"\"\"\n return self._value\n\n @Value.setter\n def Value(self, value: float) -> None:\n self._value = value\n\n @property\n def HighError(self) -> float:\n \"\"\"\n highest possible error value.\n \"\"\"\n return self._high_error\n\n @HighError.setter\n def HighError(self, value: float) -> None:\n self._high_error = value\n\n @property\n def LowError(self) -> float:\n \"\"\"\n lowest possible error value.\n \"\"\"\n return self._low_error\n\n @LowError.setter\n def LowError(self, value: float) -> None:\n self._low_error = value\n\n\n__all__ = ['ChartDataValue']\n","repo_name":"Amourspirit/python-ooouno","sub_path":"ooo/lo/chart/chart_data_value.py","file_name":"chart_data_value.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"30595648965","text":"'''\nCreated on 2015/6/16\n\n:author: hubo\n'''\nfrom __future__ import print_function, absolute_import, division\nimport sys\nfrom .core import QuitException, TimerEvent, SystemControlEvent\nfrom .event import Event, withIndices, M_, Diff_\nimport asyncio\n\n\nclass EventHandler(object):\n '''\n Runnable with an event handler model. \n '''\n def __init__(self, scheduler = None, daemon = False):\n self.handlers = dict()\n self.scheduler = scheduler\n self.daemon = daemon\n self.registered = False\n def bind(self, scheduler):\n self.scheduler = scheduler\n def __iter__(self):\n '''\n Keep it like a iterator. Not very useful.\n '''\n return self\n def next(self):\n '''\n Keep it like a iterator. Not very useful.\n '''\n self.send(None)\n def __next__(self):\n '''\n Python 3 next\n '''\n self.send(None)\n def send(self, etup):\n '''\n Handle events\n '''\n return self.handlers[etup[1]](etup[0], self.scheduler)\n def _setDaemon(self):\n if not self.registered:\n self.registered = True\n self.scheduler.setDaemon(self, self.daemon)\n def registerHandler(self, matcher, handler):\n '''\n Register self to scheduler\n '''\n self.handlers[matcher] = handler\n self.scheduler.register((matcher,), self)\n self._setDaemon()\n def unregisterHandler(self, matcher):\n self.scheduler.unregister((matcher,), self)\n del self.handlers[matcher]\n def unregisterAllHandlers(self):\n self.scheduler.unregister(tuple(self.handlers.keys()), self)\n self.handlers.clear()\n def registerAllHandlers(self, handlerDict):\n '''\n Register self to scheduler\n '''\n self.handlers.update(handlerDict)\n if hasattr(handlerDict, 'keys'):\n self.scheduler.register(handlerDict.keys(), self)\n else:\n self.scheduler.register(tuple(h[0] for h in handlerDict), self)\n self._setDaemon()\n def close(self):\n self.scheduler.unregisterall(self)\n self.registered = False\n def registerExceptionHandler(self, handler):\n self.exceptionHandler = handler\n def registerQuitHandler(self, handler):\n self.quitHandler = handler\n def throw(self, typ, val = None, tb = None):\n if val is None:\n if isinstance(typ, type):\n val = typ()\n else:\n val = typ\n typ = type(val)\n if isinstance(val, QuitException):\n self.quitHandler(self.scheduler)\n else:\n self.exceptionHandler(val, self.scheduler)\n def exceptionHandler(self, val, scheduler):\n raise val\n def quitHandler(self, scheduler):\n raise StopIteration\n\n\nclass GeneratorExit_(BaseException):\n \"\"\"\n Bypass PyPy3 bug\n \"\"\"\n pass\n\n\ndef _close_generator(g):\n \"\"\"\n PyPy 3 generator has a bug that calling `close` caused\n memory leak. Before it is fixed, use `throw` instead\n \"\"\"\n if isinstance(g, generatorwrapper):\n g.close()\n elif _get_frame(g) is not None:\n try:\n g.throw(GeneratorExit_)\n except (StopIteration, GeneratorExit_):\n return\n else:\n raise RuntimeError(\"coroutine ignored GeneratorExit\")\n\n\ndef _await(coroutine):\n \"\"\"\n Return a generator\n \"\"\"\n if hasattr(coroutine, '__await__'):\n return coroutine.__await__()\n else:\n return coroutine\n\n\n@withIndices('type', 'routine')\nclass RoutineControlEvent(Event):\n DELEGATE_FINISHED = 'delegatefinished'\n\nclass IllegalMatchersException(Exception):\n pass\n\n\ndef _get_frame(obj):\n if hasattr(obj, 'cr_frame'):\n return obj.cr_frame\n else:\n return obj.gi_frame\n\n\nclass generatorwrapper(object):\n '''\n Default __repr__ of a generator is not readable, use a wrapper to improve the readability\n '''\n __slots__ = ('run', 'name', 'classname', '_iter')\n def __init__(self, run, name = 'coroutine', classname = 'routine'):\n self.run = run\n self.name = name\n self.classname = classname\n if hasattr(run, '__await__'):\n self._iter = run.__await__()\n else:\n self._iter = run\n def __iter__(self):\n return self._iter\n __await__ = __iter__\n def next(self):\n try:\n return next(self._iter)\n except StopIteration:\n raise StopIteration\n def __next__(self):\n try:\n return next(self._iter)\n except StopIteration:\n raise StopIteration\n def send(self, arg):\n try:\n return self._iter.send(arg)\n except StopIteration:\n raise StopIteration\n def throw(self, typ, val = None, tb = None):\n try:\n return self._iter.throw(typ, val, tb)\n except StopIteration:\n raise StopIteration\n def __repr__(self, *args, **kwargs):\n try:\n iterator = _get_frame(self.run).f_locals[self.name]\n try:\n return '<%s %r of %r at 0x%016X>' % (self.classname, iterator,\n _get_frame(iterator).f_locals['self'],\n id(iterator))\n except Exception:\n return '<%s %r at 0x%016X>' % (self.classname, iterator, id(iterator))\n except Exception:\n return repr(self.run)\n def close(self):\n return _close_generator(self.run)\n\n\ndef Routine(coroutine, scheduler, asyncStart = True, container = None, manualStart = False, daemon = False):\n \"\"\"\n This wraps a normal coroutine to become a VLCP routine. Usually you do not need to call this yourself;\n `container.start` and `container.subroutine` calls this automatically.\n \"\"\"\n def run():\n iterator = _await(coroutine)\n iterself = yield\n if manualStart:\n yield\n try:\n if asyncStart:\n scheduler.yield_(iterself)\n yield\n if container is not None:\n container.currentroutine = iterself\n if daemon:\n scheduler.setDaemon(iterself, True)\n try:\n matchers = next(iterator)\n except StopIteration:\n return\n while matchers is None:\n scheduler.yield_(iterself)\n yield\n try:\n matchers = next(iterator)\n except StopIteration:\n return\n try:\n scheduler.register(matchers, iterself)\n except Exception:\n try:\n iterator.throw(IllegalMatchersException(matchers))\n except StopIteration:\n pass\n raise\n while True:\n try:\n etup = yield\n except GeneratorExit_:\n raise\n except:\n #scheduler.unregister(matchers, iterself)\n lmatchers = matchers\n t,v,tr = sys.exc_info() # @UnusedVariable\n if container is not None:\n container.currentroutine = iterself\n try:\n matchers = iterator.throw(t,v)\n except StopIteration:\n return\n else:\n #scheduler.unregister(matchers, iterself)\n lmatchers = matchers\n if container is not None:\n container.currentroutine = iterself\n try:\n matchers = iterator.send(etup)\n except StopIteration:\n return\n while matchers is None:\n scheduler.yield_(iterself)\n yield\n try:\n matchers = next(iterator)\n except StopIteration:\n return\n try:\n if hasattr(matchers, 'two_way_difference'):\n reg, unreg = matchers.two_way_difference(lmatchers)\n else:\n reg = set(matchers).difference(lmatchers)\n unreg = set(lmatchers).difference(matchers)\n scheduler.register(reg, iterself)\n scheduler.unregister(unreg, iterself)\n except Exception:\n try:\n iterator.throw(IllegalMatchersException(matchers))\n except StopIteration:\n pass\n raise\n finally:\n # iterator.close() can be called in other routines, we should restore the currentroutine variable\n if container is not None:\n lastcurrentroutine = getattr(container, 'currentroutine', None)\n container.currentroutine = iterself\n else:\n lastcurrentroutine = None\n _close_generator(coroutine)\n if container is not None:\n container.currentroutine = lastcurrentroutine\n scheduler.unregisterall(iterself)\n r = generatorwrapper(run())\n next(r)\n r.send(r)\n return r\n\nclass RoutineException(Exception):\n \"\"\"\n Special exception type raised from :py:method::`vlcp.event.runnable.RoutineContainer.withException`.\n e.matcher is set to the matcher and e.event is set to the matched event.\n \"\"\"\n def __init__(self, matcher, event):\n Exception.__init__(self, matcher, event)\n self.matcher = matcher\n self.event = event\n\nclass MultipleException(Exception):\n \"\"\"\n Special exception type raised from :py:method::`vlcp.event.runnable.RoutineContainer.executeAll`\n \"\"\"\n def __init__(self, exceptions):\n Exception.__init__(self, '%d exceptions occurs in parallel execution' % (len(exceptions),) \\\n + ': ' + repr(exceptions[0]) + ', ...')\n self.exceptions = exceptions\n\nclass RoutineContainer(object):\n \"\"\"\n A routine container groups several routines together and shares data among them. It is also\n used to pass important information like events, matchers and return values to the routine.\n \n Several attributes are commonly used:\n \n currentroutine\n Always set to the executing routine - which is the wrapped routine object of the routine itself\n \n mainroutine\n Set to the main routine `container.main` (started by `container.start`)\n \n \"\"\"\n \n _container_cache = {}\n \n def __init__(self, scheduler = None, daemon = False):\n \"\"\"\n Create the routine container.\n \n :param scheduler: The scheduler. This must be set; if None is used, it must be set with\n `container.bind(scheduler)` before using.\n \n :param daemon: If daemon = True, the main routine `container.main` is set to be a daemon routine.\n A daemon routine does not stop the scheduler from quitting; if all non-daemon routines\n are quit, the scheduler stops.\n \"\"\"\n self.scheduler = scheduler\n self.daemon = daemon\n def bind(self, scheduler):\n \"\"\"\n If scheduler is not specified, bind the scheduler\n \"\"\"\n self.scheduler = scheduler\n def main(self):\n \"\"\"\n The main routine method, should be rewritten to an async method\n \"\"\"\n raise NotImplementedError\n def start(self, asyncStart = False):\n \"\"\"\n Start `container.main` as the main routine.\n \n :param asyncStart: if True, start the routine in background. By default, the routine\n starts in foreground, which means it is executed to the first\n `yield` statement before returning. If the started routine raises\n an exception, the exception is re-raised to the caller of `start`\n \"\"\"\n r = Routine(self.main(), self.scheduler, asyncStart, self, True, self.daemon)\n self.mainroutine = r\n try:\n next(r)\n except StopIteration:\n pass\n return r\n def subroutine(self, iterator, asyncStart = True, name = None, daemon = False):\n \"\"\"\n Start extra routines in this container.\n \n :param iterator: A coroutine object i.e the return value of an async method `my_routine()`\n \n :param asyncStart: if False, start the routine in foreground. By default, the routine\n starts in background, which means it is not executed until the current caller\n reaches the next `yield` statement or quit.\n \n :param name: if not None, `container.` is set to the routine object. This is useful when\n you want to terminate the routine from outside.\n \n :param daemon: if True, this routine is set to be a daemon routine.\n A daemon routine does not stop the scheduler from quitting; if all non-daemon routines\n are quit, the scheduler stops. \n \"\"\"\n r = Routine(iterator, self.scheduler, asyncStart, self, True, daemon)\n if name is not None:\n setattr(self, name, r)\n # Call subroutine may change the currentroutine, we should restore it\n currentroutine = getattr(self, 'currentroutine', None)\n try:\n next(r)\n except StopIteration:\n pass\n self.currentroutine = currentroutine\n return r\n def terminate(self, routine = None):\n \"\"\"\n Stop a routine.\n \n :param routine: if None, stop the main routine. If not None, it should be a routine object. You\n can specify a name for a subroutine, and use `container.` to retrieve it.\n \"\"\"\n if routine is None:\n routine = self.mainroutine\n routine.close()\n def close(self):\n \"\"\"\n Same as `terminate()`\n \"\"\"\n self.terminate()\n \n async def wait_for_send(self, event, *, until=None):\n '''\n Send an event to the main event queue. Can call without delegate.\n \n :param until: if the callback returns True, stop sending and return\n \n :return: the last True value the callback returns, or None\n '''\n while True:\n if until:\n r = until()\n if r:\n return r\n waiter = self.scheduler.send(event)\n if waiter is None:\n break\n await waiter\n waitForSend = wait_for_send\n \n async def wait_with_timeout(self, timeout, *matchers):\n \"\"\"\n Wait for multiple event matchers, or until timeout.\n \n :param timeout: a timeout value\n \n :param \\*matchers: event matchers\n \n :return: (is_timeout, event, matcher). When is_timeout = True, event = matcher = None.\n \"\"\"\n if timeout is None:\n ev, m = await M_(*matchers)\n return False, ev, m\n else:\n th = self.scheduler.setTimer(timeout)\n try:\n tm = TimerEvent.createMatcher(th)\n ev, m = await M_(*(tuple(matchers) + (tm,)))\n if m is tm:\n return True, None, None\n else:\n return False, ev, m\n finally:\n self.scheduler.cancelTimer(th)\n \n waitWithTimeout = wait_with_timeout\n \n async def execute_with_timeout(self, timeout, subprocess):\n \"\"\"\n Execute a subprocess with timeout. If time limit exceeds, the subprocess is terminated,\n and `is_timeout` is set to True; otherwise the `is_timeout` is set to False.\n \n You can uses `execute_with_timeout` with other help functions to create time limit for them::\n \n timeout, result = await container.execute_with_timeout(10, container.execute_all([routine1(), routine2()]))\n \n :return: (is_timeout, result) When is_timeout = True, result = None\n \"\"\"\n if timeout is None:\n return (False, await subprocess)\n else:\n th = self.scheduler.setTimer(timeout)\n try:\n tm = TimerEvent.createMatcher(th)\n try:\n r = await self.with_exception(subprocess, tm)\n except RoutineException as exc:\n if exc.matcher is tm:\n return True, None\n else:\n raise\n else:\n return False, r\n finally:\n self.scheduler.cancelTimer(th)\n \n executeWithTimeout = execute_with_timeout\n \n async def do_events(self):\n '''\n Suspend this routine until the next polling. This can be used to give CPU time for other routines and\n socket processings in long calculating procedures. Can call without delegate.\n '''\n self.scheduler.wantContinue()\n await SystemControlEvent.createMatcher(SystemControlEvent.CONTINUE)\n \n doEvents = do_events\n \n async def with_exception(self, subprocess, *matchers):\n \"\"\"\n Monitoring event matchers while executing a subprocess. If events are matched before the subprocess ends,\n the subprocess is terminated and a RoutineException is raised.\n \"\"\"\n def _callback(event, matcher):\n raise RoutineException(matcher, event)\n return await self.with_callback(subprocess, _callback, *matchers)\n \n withException = with_exception \n \n @asyncio.coroutine\n def with_callback(self, subprocess, callback, *matchers, intercept_callback = None):\n \"\"\"\n Monitoring event matchers while executing a subprocess. `callback(event, matcher)` is called each time\n an event is matched by any event matchers. If the callback raises an exception, the subprocess is terminated.\n \n :param intercept_callback: a callback called before a event is delegated to the inner subprocess\n \"\"\"\n it_ = _await(subprocess)\n if not matchers and not intercept_callback:\n return (yield from it_)\n try:\n try:\n m = next(it_)\n except StopIteration as e:\n return e.value\n while True:\n if m is None:\n try:\n yield\n except GeneratorExit_:\n raise\n except:\n t,v,tr = sys.exc_info() # @UnusedVariable\n try:\n m = it_.throw(t,v)\n except StopIteration as e:\n return e.value\n else: \n try:\n m = next(it_)\n except StopIteration as e:\n return e.value\n else:\n while True:\n try:\n ev, matcher = yield m + tuple(matchers)\n except GeneratorExit_:\n # subprocess is closed in `finally` clause\n raise\n except:\n # delegate this exception inside\n t,v,tr = sys.exc_info() # @UnusedVariable\n try:\n m = it_.throw(t,v)\n except StopIteration as e:\n return e.value\n else:\n if matcher in matchers:\n callback(ev, matcher)\n else:\n if intercept_callback:\n intercept_callback(ev, matcher)\n break\n try:\n m = it_.send((ev, matcher))\n except StopIteration as e:\n return e.value\n finally:\n _close_generator(subprocess)\n \n withCallback = with_callback\n \n async def wait_for_empty(self, queue):\n '''\n Wait for a queue to be empty. Can call without delegate\n '''\n while True:\n m = queue.waitForEmpty()\n if m is None:\n break\n else:\n await m\n \n waitForEmpty = wait_for_empty \n \n async def wait_for_all(self, *matchers, eventlist = None, eventdict = None, callback = None):\n \"\"\"\n Wait until each matcher matches an event. When this coroutine method returns,\n `eventlist` is set to the list of events in the arriving order (may not\n be the same as the matchers); `eventdict` is set to a dictionary\n `{matcher1: event1, matcher2: event2, ...}`\n \n :param eventlist: use external event list, so when an exception occurs\n (e.g. routine close), you can retrieve the result\n from the passed-in list\n \n :param eventdict: use external event dict\n \n :param callback: if not None, the callback should be a callable callback(event, matcher)\n which is called each time an event is received\n \n :return: (eventlist, eventdict)\n \"\"\"\n if eventdict is None:\n eventdict = {}\n if eventlist is None:\n eventlist = []\n ms = len(matchers)\n last_matchers = Diff_(matchers)\n while ms:\n ev, m = await last_matchers\n ms -= 1\n if callback:\n callback(ev, m)\n eventlist.append(ev)\n eventdict[m] = ev\n last_matchers = Diff_(last_matchers, remove=(m,))\n return eventlist, eventdict\n \n waitForAll = wait_for_all\n \n async def wait_for_all_to_process(self, *matchers, eventlist = None, eventdict = None,\n callback = None):\n \"\"\"\n Similar to `waitForAll`, but set `canignore=True` for these events. This ensures\n blocking events are processed correctly.\n \"\"\"\n def _callback(event, matcher):\n event.canignore = True\n if callback:\n callback(event, matcher)\n return await self.wait_for_all(*matchers, eventlist=eventlist,\n eventdict=eventdict, callback=_callback)\n\n waitForAllToProcess = wait_for_all_to_process\n \n async def wait_for_all_empty(self, *queues):\n \"\"\"\n Wait for multiple queues to be empty at the same time.\n\n Require delegate when calling from coroutines running in other containers\n \"\"\"\n matchers = [m for m in (q.waitForEmpty() for q in queues) if m is not None]\n while matchers:\n await self.wait_for_all(*matchers)\n matchers = [m for m in (q.waitForEmpty() for q in queues) if m is not None]\n \n waitForAllEmpty = wait_for_all_empty\n \n @asyncio.coroutine\n def syscall_noreturn(self, func):\n '''\n Call a syscall method. A syscall method is executed outside of any routines, directly\n in the scheduler loop, which gives it chances to directly operate the event loop.\n See :py:method::`vlcp.event.core.Scheduler.syscall`.\n '''\n matcher = self.scheduler.syscall(func)\n while not matcher:\n yield\n matcher = self.scheduler.syscall(func)\n ev, _ = yield (matcher,)\n return ev\n \n async def syscall(self, func, ignoreException = False):\n \"\"\"\n Call a syscall method and retrieve its return value\n \"\"\"\n ev = await self.syscall_noreturn(func)\n if hasattr(ev, 'exception'):\n if ignoreException:\n return\n else:\n raise ev.exception[1]\n else:\n return ev.retvalue\n \n async def delegate(self, subprocess, forceclose = False):\n '''\n Run a subprocess without container support\n \n Many subprocess assume itself running in a specified container, it uses container reference\n like self.events. Calling the subprocess in other containers will fail.\n \n With delegate, you can call a subprocess in any container (or without a container)::\n \n r = await c.delegate(c.someprocess())\n \n :return: original return value\n '''\n finish, r = self.begin_delegate(subprocess)\n return await self.end_delegate(finish, r, forceclose)\n \n async def end_delegate(self, delegate_matcher, routine = None, forceclose = False):\n \"\"\"\n Retrieve a begin_delegate result. Must be called immediately after begin_delegate\n before any other `await`, or the result might be lost.\n \n Do not use this method without thinking. Always use `RoutineFuture` when possible.\n \"\"\"\n try:\n ev = await delegate_matcher\n if hasattr(ev, 'exception'):\n raise ev.exception\n else:\n return ev.result\n finally:\n if forceclose and routine:\n routine.close()\n\n def begin_delegate(self, subprocess):\n '''\n Start the delegate routine, but do not wait for result, instead returns a (matcher, routine) tuple.\n Useful for advanced delegates (e.g. delegate multiple subprocesses in the same time).\n This is NOT a coroutine method.\n \n WARNING: this is not a safe way for asynchronous executing and get the result. Use `RoutineFuture` instead.\n \n :param subprocess: a coroutine\n \n :returns: (matcher, routine) where matcher is a event matcher to get the delegate result, routine is the created routine\n '''\n async def delegateroutine():\n try:\n r = await subprocess\n except:\n _, val, _ = sys.exc_info()\n e = RoutineControlEvent(RoutineControlEvent.DELEGATE_FINISHED, self.currentroutine,\n exception=val)\n self.scheduler.emergesend(e)\n raise\n else:\n e = RoutineControlEvent(RoutineControlEvent.DELEGATE_FINISHED, self.currentroutine,\n result = r)\n await self.wait_for_send(e)\n r = self.subroutine(generatorwrapper(delegateroutine(), 'subprocess', 'delegate'), True)\n finish = RoutineControlEvent.createMatcher(RoutineControlEvent.DELEGATE_FINISHED, r)\n return finish, r\n \n def begin_delegate_other(self, subprocess, container, retnames = ('',)):\n '''\n DEPRECATED Start the delegate routine, but do not wait for result, instead returns a (matcher routine) tuple.\n Useful for advanced delegates (e.g. delegate multiple subprocesses in the same time).\n This is NOT a coroutine method.\n \n :param subprocess: a coroutine\n \n :param container: container in which to start the routine\n \n :param retnames: get return values from keys. '' for the return value (for compatibility with earlier versions)\n \n :returns: (matcher, routine) where matcher is a event matcher to get the delegate result, routine is the created routine\n '''\n async def delegateroutine():\n try:\n r = await subprocess\n except:\n _, val, _ = sys.exc_info()\n e = RoutineControlEvent(RoutineControlEvent.DELEGATE_FINISHED, container.currentroutine, exception = val)\n container.scheduler.emergesend(e)\n raise\n else:\n e = RoutineControlEvent(RoutineControlEvent.DELEGATE_FINISHED, container.currentroutine,\n result = tuple(r if n == '' else getattr(container, n, None)\n for n in retnames))\n await container.waitForSend(e)\n r = container.subroutine(generatorwrapper(delegateroutine(), 'subprocess', 'delegate'), True)\n return (RoutineControlEvent.createMatcher(RoutineControlEvent.DELEGATE_FINISHED, r), r)\n \n beginDelegateOther = begin_delegate_other\n \n async def delegate_other(self, subprocess, container, retnames = ('',), forceclose = False):\n '''\n DEPRECATED Another format of delegate allows delegate a subprocess in another container, and get some returning values\n the subprocess is actually running in 'container'. ::\n \n ret = await self.delegate_other(c.method(), c)\n \n :return: a tuple for retnames values\n \n '''\n finish, r = self.beginDelegateOther(subprocess, container, retnames)\n return await self.end_delegate(finish, r, forceclose)\n\n delegateOther = delegate_other\n \n async def execute_all_with_names(self, subprocesses, container = None, retnames = ('',), forceclose = True):\n '''\n DEPRECATED Execute all subprocesses and get the return values.\n \n :param subprocesses: sequence of subroutines (coroutines)\n \n :param container: if specified, run subprocesses in another container.\n \n :param retnames: DEPRECATED get return value from container.(name) for each name in retnames.\n '' for return value (to be compatible with earlier versions)\n \n :param forceclose: force close the routines on exit, so all the subprocesses are terminated\n on timeout if used with executeWithTimeout\n \n :returns: a list of tuples, one for each subprocess, with value of retnames inside:\n `[('retvalue1',),('retvalue2',),...]`\n '''\n if not subprocesses:\n return []\n subprocesses = list(subprocesses)\n if len(subprocesses) == 1 and (container is None or container is self) and forceclose:\n # Directly run the process to improve performance\n return [await subprocesses[0]]\n if container is None:\n container = self\n delegates = [self.begin_delegate_other(p, container, retnames) for p in subprocesses]\n matchers = [d[0] for d in delegates]\n try:\n _, eventdict = await self.wait_for_all(*matchers)\n events = [eventdict[m] for m in matchers]\n exceptions = [e.exception for e in events if hasattr(e, 'exception')]\n if exceptions:\n if len(exceptions) == 1:\n raise exceptions[0]\n else:\n raise MultipleException(exceptions)\n return [e.result for e in events]\n finally:\n if forceclose:\n for d in delegates:\n try:\n container.terminate(d[1])\n except Exception:\n pass\n \n executeAll = execute_all_with_names\n \n async def execute_all(self, subprocesses, forceclose=True):\n '''\n Execute all subprocesses and get the return values.\n \n :param subprocesses: sequence of subroutines (coroutines)\n \n :param forceclose: force close the routines on exit, so all the subprocesses are terminated\n on timeout if used with executeWithTimeout\n \n :returns: a list of return values for each subprocess\n '''\n if not subprocesses:\n return []\n subprocesses = list(subprocesses)\n if len(subprocesses) == 1 and forceclose:\n return [await subprocesses[0]]\n delegates = [self.begin_delegate(p) for p in subprocesses]\n matchers = [d[0] for d in delegates]\n try:\n _, eventdict = await self.wait_for_all(*matchers)\n events = [eventdict[m] for m in matchers]\n exceptions = [e.exception for e in events if hasattr(e, 'exception')]\n if exceptions:\n if len(exceptions) == 1:\n raise exceptions[0]\n else:\n raise MultipleException(exceptions)\n return [e.result for e in events]\n finally:\n if forceclose:\n for d in delegates:\n try:\n d[1].close()\n except Exception:\n pass\n \n @classmethod\n def get_container(cls, scheduler):\n \"\"\"\n Create temporary instance for helper functions\n \"\"\"\n if scheduler in cls._container_cache:\n return cls._container_cache[scheduler]\n else:\n c = cls(scheduler)\n cls._container_cache[scheduler] = c\n return c\n \n @classmethod\n def destroy_container_cache(cls, scheduler):\n \"\"\"\n Remove cached container\n \"\"\"\n if scheduler in cls._container_cache:\n del cls._container_cache[scheduler]\n","repo_name":"hubo1016/vlcp","sub_path":"vlcp/event/runnable.py","file_name":"runnable.py","file_ext":"py","file_size_in_byte":33558,"program_lang":"python","lang":"en","doc_type":"code","stars":223,"dataset":"github-code","pt":"27"} +{"seq_id":"13674653375","text":"from abc import ABC\nimport csv\nimport json\nimport xmltodict\nfrom inventory_report.reports.simple_report import SimpleReport\nfrom inventory_report.reports.complete_report import CompleteReport\n\nREPORT = {\"simples\": SimpleReport, \"completo\": CompleteReport}\n\n\nclass Inventory(ABC):\n @classmethod\n def import_data(self, path, report_type):\n product_list = Inventory.read_file(path)\n\n return REPORT[report_type].generate(product_list)\n\n @classmethod\n def read_csv_file(self, path):\n with open(path) as file:\n reader = csv.reader(file)\n header, *data = reader\n\n product_list = [dict(zip(header, row)) for row in data]\n\n return product_list\n\n @classmethod\n def read_json_file(self, path):\n with open(path) as file:\n product_list = json.load(file)\n\n return product_list\n\n @classmethod\n def read_xml_file(self, path):\n with open(path) as file:\n product_list = xmltodict.parse(file.read())['dataset']['record']\n\n return product_list\n\n @classmethod\n def read_file(self, path):\n file_type = path.split(\".\")[-1]\n\n readers = {\n \"csv\": Inventory.read_csv_file,\n \"json\": Inventory.read_json_file,\n \"xml\": Inventory.read_xml_file,\n }\n\n return readers[file_type](path)\n","repo_name":"Lucas-Almeida-SD/Trybe-Projeto_35-Inventory-Report","sub_path":"inventory_report/inventory/inventory.py","file_name":"inventory.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"32958265283","text":"import datetime\nimport json\nimport requests\nimport logging\nimport unittest\nfrom operator import itemgetter\nimport time\nimport ical_parser\nimport urllib.request\nfrom icalendar import Calendar\nfrom app import app\n\nlog = logging.getLogger(__name__)\n\n\nclass FlaskrTestCase(unittest.TestCase):\n\n def setUp(self):\n # creates a test client\n self.app = app.test_client()\n # propagate the exceptions to the test client\n # self.app.testing = True\n\n def test_self(self):\n result = self.app.get('/')\n self.assertEqual(result.status_code, 200)\n\n def test_app(self):\n url = 'http://p27-calendars.icloud.com/published/2/sAKB2qXoM7Kj0E4v8n2nzd3naihwmKKZqvpklvflY9V-xB0-vg5pkFqB2dAyd_84'\n ics = urllib.request.urlopen(url).read()\n cal = Calendar.from_ical(ics)\n entries = []\n entries = ical_parser.ical_parser(cal)\n sorted_events = sorted(entries, key=itemgetter('date'))\n filtered = [i for i in sorted_events if i['date'] >= time.strftime(\n \"%Y-%m-%d %H:%M:%S\")]\n self.assertIsNotNone(filtered)\n\n def test_cal(self):\n result = self.app.get('/get_calendar')\n self.assertEqual(result.status_code, 200)\n\n def test_news(self):\n result = self.app.get('/get_news_headlines')\n self.assertEqual(result.status_code, 200)\n\n def test_weather(self):\n result = self.app.get('/get_weather')\n self.assertEqual(result.status_code, 200)\n self.assertTrue(result.data)\n\n def test_compliment(self):\n result = self.app.get('/get_compliment')\n self.assertEqual(result.status_code, 200)\n self.assertTrue(result.data)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"rhino78/my_magic_mirror","sub_path":"test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"26241832858","text":"# -*- coding: utf-8 -*-\n\"\"\"\nProgram to plot time evolution of galaxy in snapshots. \nGiven a set of Gadget snapshots, plots 3D scatter of\ngalaxy gas and star particles, and saves figures as\nordered frames.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nplt.ion()\n\nfrom iccpy.gadget import load_snapshot\nfrom iccpy.gadget.labels import cecilia_labels\n\n\n\nnumber_of_snapshots = 200 # actually includes snap_000\n\nfile = '../outputs/snap_{:03d}'\n\n\nfig = plt.figure(figsize=(13.0, 6.0)) # in inches!\nax3 = Axes3D(fig)\n\nfor i in range(200, number_of_snapshots + 1):\n\n\tsnap = load_snapshot(file.format(i), label_table = cecilia_labels)\n\tgas_pos = snap['POS '][0]\n\tstars_pos = snap['POS '][4]\n\n\t# clears figure, plots, and saves ordered frame as .png\n\n\tax3.set_xlim3d(-300, 300)\n\tax3.set_ylim3d(-300, 300)\n\tax3.set_zlim3d(-300, 300)\n\n\tax3.scatter(gas_pos[:,0], gas_pos[:,1], gas_pos[:,2], color = 'b', s = 0.001)\n\tax3.scatter(stars_pos[:,0], stars_pos[:,1], stars_pos[:,2], color = 'r', s = 0.001)\n\n\tplt.title('Galaxy at snapshot {:03d}'.format(i), fontsize = 20)\n\t\n\t# to undo figure saving and preview time evolution, comment following\n\t# line and uncomment pause\n\n\t#plt.savefig('frames3d/frame_{:03d}.png'.format(i), dpi = 100, bbox_inches = 'tight')\n\t\n\tplt.pause(0.001)\n\n\n\t#ax3.clear()\n\n\n\n\n","repo_name":"martincss/thesis","sub_path":"snap_time_evol_3d.py","file_name":"snap_time_evol_3d.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"22353857496","text":"def check_email(e):\n\tflag=0\n\tx1,x2=e.index('@'),e.index('.')\n\tif(e.count('@')>1 or e.count('.')>1):\n\t\treturn 1\n\telif((e.index('@')-e.index('.'))>1):\n\t\treturn 1\n\telif (e[x1+1:x2] not in ['gmail','yahoo' ,'rediffmail','hotmail']):\n\t\treturn 404\n\telif(e.index('@')==0):\n\t\treturn 1\n\telse:\n\t\treturn 0\ndef main():\n\ts=input(\"Enter the email you want to check:\")\n\tprint(\"The Entered email is:\",s)\n\tresult=check_email(s)\n\tif(result==0):\n\t\tprint(\"Supported email\")\n\telif(result==404):\n\t\tprint(\"Unsupported email\")\n\telse:\n\t\tprint(\"Invalid email\")\nmain()\n","repo_name":"biswajit-SEA/Data-Visualizaton","sub_path":"Lab2 11-3-22/Lab q1.py","file_name":"Lab q1.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"14306534196","text":"## This script relates to everything that is used for handling the images on the display\n\nimport time\nimport sys\nimport threading\nfrom rgbmatrix import RGBMatrix, RGBMatrixOptions\nfrom PIL import Image, ImageEnhance \nThreadAlive = False;\n\n\nexit_event = threading.Event()\n\n#Called when a new image needs to be displayed\ndef imageviewer(image_file, matrix, brightness, rotation):\n\n print(\"Brightness Setting: \"+str(brightness))\n #Go through all threads running and if there is a display thread already running then kill it and create a new one.\n #This happens to try and reduce the flicker that can occur on the screen due to the PI processing. This is one\n #of the limiations of the RGB matrix lib we are using.\n for thread in threading.enumerate():\n print(thread.getName() +\",\")\n if(thread.getName() == \"DisplayImageThread\"):\n \n while(thread.is_alive()):\n if(thread.is_alive()):\n print(\"Deleteing thread\")\n #Sets the exit_event event to be true which will be triggered in any active display threads and\n #will ask them to close correctly\n exit_event.set()\n time.sleep(0.1)\n print(\"thread alive\")\n #Resets the event so that it doesn't keep triggering\n exit_event.clear()\n \n \n print(\"Create New Thread\")\n DisplayImage = True\n #Load the file that the user has requested from the images folder\n image = Image.open(\"Images/\"+ str(image_file) +\".png\")\n \n # Configuration for the matrix\n matrix.brightness = brightness\n # Make image fit our screen.\n image.thumbnail((matrix.width, matrix.height), Image.ANTIALIAS) \n #Creates a new display thread with all of the needed parameters\n displayThread = threading.Thread(target=ThreadDisplay, args=(1,image,matrix,brightness,rotation,))\n displayThread.setName(\"DisplayImageThread\")\n displayThread.start()\n\n \n \ndef ThreadDisplay(name, image, matrix, brightnessLevel, rotation):\n \n ThreadAlive = True;\n \n DisplayImage = True\n #Adjust the images rotation if needed and converts it to RGB values to be used on\n #the matrix.\n image = image.rotate(rotation)\n matrix.SetImage(image.convert('RGB'),0,0, False)\n matrix.brightness = brightnessLevel\n #Runs a while loop to constantly display the image. This is in a different thread from the \n #main program so it doesn't block any of the UDP listening. We also use a while loop to keep\n #this thread running, otherwise it would display an image for a second and then stop.\n while(DisplayImage):\n #If the exit_event is set then force the program to stop.\n if exit_event.is_set():\n DisplayImage = False\n image = None\n print(\"Display Thread End\")\n \ndef closeImageDisplay():\n exit_event.set() \n \n\n","repo_name":"Hantoo/Firefly","sub_path":"RaspberryPiSoftware/rpi-rgb-led-matrix-master/bindings/python/ImageDisplay.py","file_name":"ImageDisplay.py","file_ext":"py","file_size_in_byte":2900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"15385339863","text":"n1 = int(input('digite um numero: '))\nc = 0\n\nfor i in range(2, n1+1):\n if n1 % i == 0:\n c = c+1\nif c <= 2:\n print('O numero {} é divisivel {} vezes, é um numero primo'.format(n1, c+1))\nelse:\n print('O numero {} é divisivel {} vezes, ele não é um numero primo'.format(n1,c)) ","repo_name":"ThiagoDev00/python_avancado","sub_path":"Listas for e While/exercicio 10.py","file_name":"exercicio 10.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"74508084230","text":"#!/bin/python3\n'''\n tag_primes\n\n https://projecteuler.net/problem=35\n How many circular primes are there below one million?\n\n https://www.hackerrank.com/contests/projecteuler/challenges/euler035\n Score: 100.00\n\n pylint 1.5.5\n Your code has been rated at 8.41/10\n'''\n\nimport math\n\n####################################################\n\ndef get_primes(limit):\n # not rounded since we skip 1 & 2\n primes = [i*2+3 for i in range(limit//2-1)]\n limit_of_sieve = 1+math.floor(math.sqrt(limit))\n for i in range(3, limit_of_sieve, 2):\n if primes[i//2-1]:\n for j in range(i*i, limit, 2*i):\n primes[j//2-1] = 0\n return [2]+[i for i in primes if i != 0]\n\n####################################################\n\ndef no_digits(number, base=10):\n digits = 0\n while number >= 1:\n number //= base\n digits += 1\n return digits\n\ndef get_digits(number, base=10):\n digits = []\n while number >= 1:\n digits.append(number%base)\n number //= base\n return digits\n\ndef get_digits_r(number, base=10):\n digits = get_digits(number, base)\n return digits[::-1]\n\n####################################################\n\ndef get_rotation(digits, pos):\n number = 0\n for i in range(pos, len(digits)):\n number *= 10\n number += digits[i]\n for i in range(pos):\n number *= 10\n number += digits[i]\n return number\n\ndef solve_problem_primes(primes, limit):\n primes_set = set(primes)\n\n circular_primes = []\n for i in primes:\n if i >= limit:\n break\n digits = get_digits_r(i)\n is_circular_prime = True\n for j in range(1, len(digits)):\n rotation = get_rotation(digits, j)\n # print(i, rotation)\n if not rotation in primes_set:\n is_circular_prime = False\n break\n if is_circular_prime:\n circular_primes.append(i)\n\n return circular_primes\n\ndef solve_problem(limit):\n primes = get_primes(10**no_digits(limit-1))\n return solve_problem_primes(primes, limit)\n\n# https://www.hackerrank.com/contests/projecteuler/challenges/euler035\ndef parse_input():\n limit = int(input().strip())\n circular_primes = solve_problem(limit)\n print(sum(circular_primes))\n\ndef problem():\n circular_primes = solve_problem(1000000)\n print(len(circular_primes))\n\ndef debug_assertions():\n primes = get_primes(1000)\n assert len(solve_problem_primes(primes, 50)) == 9\n assert len(solve_problem_primes(primes, 100)) == 13\n assert sum(solve_problem_primes(primes, 100)) == 446\n assert len(solve_problem_primes(primes, 1000)) == 25\n\ndef main():\n debug_assertions()\n\n # parse_input()\n # problem()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"landron/Project-Euler","sub_path":"Python/easy/problem_35_circular_primes.py","file_name":"problem_35_circular_primes.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"30956439835","text":"\r\nmod = 10**9 + 7\r\n\r\ndef total_sum(l):\r\n total = 0\r\n factor = 2\r\n part = l.pop(0)<<1\r\n for v in l:\r\n total = (v*part + (total<<1))%mod\r\n part = (part + (v*factor))%mod\r\n factor = (factor<<1)%mod\r\n return total\r\n \r\ndef parse(val):\r\n return [int(value) for value in val.split(' ')]\r\n\r\nif __name__ == \"__main__\":\r\n T = int(input())\r\n for _ in range(T):\r\n N = int(input())\r\n A = parse(input())\r\n print(total_sum(A))\r\n","repo_name":"SeraphWedd/CodeChef_Codes-Python-3.x-","sub_path":"beginner/RGAME.py","file_name":"RGAME.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"12013685873","text":"import tensorflow as tf\r\nimport numpy as np\r\nimport tensorflow.contrib.slim as slim\r\nfrom model import Timer, DeepLab_v3\r\n\r\n\r\nclass Trainer():\r\n\tdef __init__(self):\r\n\t\tself._batch_size = 5\r\n\t\tself._shuffle_size = 15\r\n\t\tself._image_size = [513, 513]\r\n\t\tself._num_classes = 20\r\n\t\tself._learning_rate = 1e-4\r\n\t\tself._epochs = 50\r\n\t\tself._pixel_val = np.array([[123.68, 116.78, 103.94]])\r\n\t\tself._file_path = \"D:/program/deeplab_v3/data/city.tfrecord\"\r\n\t\tself._pre_trained = \"D:/program/deeplab_v3/pretrained_model/resnet_v2_101.ckpt\"\r\n\t\tself._save_path = \"D:/program/deeplab_v3/model_city/\"\r\n\t\tself._log_path = \"D:/program/deeplab_v3/log_city/\"\r\n\t\tself.network = DeepLab_v3(num_classes=self._num_classes)\r\n\t\tself.timer = Timer()\r\n\r\n\tdef parser(self, record):\r\n\t\tfeatures = tf.io.parse_single_example(record, features={\r\n\t\t\t\"image\": tf.io.FixedLenFeature([], tf.string),\r\n\t\t\t\"label\": tf.io.FixedLenFeature([], tf.string),\r\n\t\t\t\"high\": tf.io.FixedLenFeature([], tf.int64),\r\n\t\t\t\"width\": tf.io.FixedLenFeature([], tf.int64),\r\n\t\t\t\"depth\": tf.io.FixedLenFeature([], tf.int64)\r\n\t\t\t})\r\n\t\thigh, width = tf.cast(features[\"high\"], tf.int32), tf.cast(features[\"width\"], tf.int32)\r\n\t\tdepth = tf.cast(features[\"depth\"], tf.int32)\r\n\t\tdecode_image, decode_label = tf.decode_raw(features[\"image\"], tf.uint8), tf.decode_raw(features[\"label\"], tf.uint8)\r\n\t\tdecode_image = tf.reshape(decode_image, [high, width, depth])\r\n\t\tdecode_label = tf.reshape(decode_label, [high, width, 1])\r\n\t\treturn decode_image, decode_label\r\n\r\n\tdef preprocess(self, image, label):\r\n\t\timage = tf.image.convert_image_dtype(image, dtype=tf.float32)\r\n\t\timage_shape = tf.shape(image)\r\n\t\tscale = tf.random.uniform([1], minval=0.5, maxval=2.0)\r\n\t\tnew_high = tf.cast(tf.math.multiply(tf.cast(image_shape[0], tf.float32), scale), tf.int32)\r\n\t\tnew_width = tf.cast(tf.math.multiply(tf.cast(image_shape[1], tf.float32), scale), tf.int32)\r\n\t\tnew_shape = tf.squeeze(tf.stack([new_high, new_width]), axis=1)\r\n\t\timage = tf.image.resize_images(image, new_shape, method=0)\r\n\t\tlabel = tf.image.resize_images(label, new_shape, method=1)\r\n\t\tlabel = tf.cast(tf.cast(label, tf.int32) - 255, tf.float32)\r\n\t\timage_with_label = tf.concat([image, label], axis=-1)\r\n\t\timage_with_label = tf.image.pad_to_bounding_box(image_with_label, 0, 0, tf.math.maximum(new_shape[0], self._image_size[0]),\r\n\t\t\ttf.math.maximum(new_shape[1], self._image_size[1]))\r\n\t\timage_with_label = tf.image.random_crop(image_with_label, [self._image_size[0], self._image_size[1], 4])\r\n\t\timage, label = image_with_label[:, :, :image_shape[2]], image_with_label[:, :, image_shape[2]]\r\n\t\timage = tf.image.convert_image_dtype(image, dtype=tf.uint8)\r\n\t\timage = tf.cast(tf.cast(image, tf.int32), tf.float32) - tf.convert_to_tensor(self._pixel_val, dtype=tf.float32)\r\n\t\tlabel = tf.cast(label + 255., tf.int32)\r\n\t\timage.set_shape([self._image_size[0], self._image_size[1], 3])\r\n\t\tlabel.set_shape([self._image_size[0], self._image_size[1]])\r\n\t\treturn image, label\r\n\r\n\tdef get_dataset(self):\r\n\t\tdataset = tf.data.TFRecordDataset(self._file_path)\r\n\t\tdataset = dataset.map(self.parser)\r\n\t\tdataset = dataset.map(lambda image, label: self.preprocess(image, label))\r\n\t\tdataset = dataset.shuffle(self._shuffle_size).repeat(self._epochs).batch(self._batch_size)\r\n\t\tself.iterator = dataset.make_initializable_iterator()\r\n\t\timage_batch, label_batch = self.iterator.get_next()\r\n\t\treturn image_batch, label_batch\r\n\r\n\tdef get_load_variables(self):\r\n\t\tadded, exclusion = \"resnet_v2_101\", \"resnet_v2_101/logits\"\r\n\t\tvariables_to_restore = []\r\n\t\tfor var in slim.get_model_variables():\r\n\t\t\tif (added in var.op.name) and (exclusion not in var.op.name):\r\n\t\t\t\tvariables_to_restore.append(var)\r\n\t\treturn variables_to_restore\r\n\r\n\tdef train(self):\r\n\t\tconfig = tf.compat.v1.ConfigProto()\r\n\t\tconfig.allow_soft_placement = True\r\n\t\tconfig.gpu_options.allow_growth = True\r\n\t\twith tf.compat.v1.Session(config=config) as sess:\r\n\t\t\tglobal_step = tf.Variable(0, trainable=False)\r\n\t\t\tlearning_rate = tf.Variable(self._learning_rate, trainable=False)\r\n\t\t\ttf.compat.v1.summary.scalar(\"learning_rate\", learning_rate)\r\n\r\n\t\t\timage_batch, label_batch = self.get_dataset()\r\n\t\t\timage_batch = tf.reshape(image_batch, [self._batch_size, self._image_size[0], self._image_size[1], 3])\r\n\t\t\tlabel_batch = tf.reshape(label_batch, [self._batch_size, self._image_size[0], self._image_size[1]])\r\n\r\n\t\t\tself.network.build_network(image_batch, is_training=True)\r\n\t\t\tcross_entropy = self.network.add_loss(label_batch)\r\n\t\t\ttf.compat.v1.summary.scalar(\"cross_entropy\", cross_entropy)\r\n\r\n\t\t\tupdate_ops = tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.UPDATE_OPS)\r\n\t\t\twith tf.control_dependencies(update_ops):\r\n\t\t\t\ttrain_op = tf.compat.v1.train.AdamOptimizer(learning_rate).minimize(cross_entropy, global_step=global_step)\r\n\r\n\t\t\tself.saver = tf.compat.v1.train.Saver(var_list=tf.compat.v1.global_variables(), max_to_keep=5)\r\n\t\t\tload_fn = slim.assign_from_checkpoint_fn(self._pre_trained, self.get_load_variables(), ignore_missing_vars=True)\r\n\t\t\tmerged = tf.compat.v1.summary.merge_all()\r\n\t\t\tsummary_writer = tf.compat.v1.summary.FileWriter(self._log_path, sess.graph)\r\n\r\n\t\t\tsess.run([tf.compat.v1.global_variables_initializer(), tf.compat.v1.local_variables_initializer()])\r\n\t\t\tload_fn(sess)\r\n\t\t\tprint(\"Load network: \" + self._pre_trained)\r\n\t\t\tsess.run(self.iterator.initializer)\r\n\t\t\tsess.run([tf.compat.v1.assign(learning_rate, self._learning_rate), tf.compat.v1.assign(global_step, 0)])\r\n\r\n\t\t\twhile True:\r\n\t\t\t\ttry:\r\n\t\t\t\t\tself.timer.tic()\r\n\t\t\t\t\t_cross_entropy, steps, summary = self.network.train_step(sess, train_op, global_step, merged)\r\n\t\t\t\t\tsummary_writer.add_summary(summary, steps)\r\n\t\t\t\t\tself.timer.toc()\r\n\t\t\t\t\tif (steps + 1) % 24880:\r\n\t\t\t\t\t\tsess.run(tf.compat.v1.assign(learning_rate, self._learning_rate * 0.1))\r\n\t\t\t\t\tif (steps + 1) % 622 == 0:\r\n\t\t\t\t\t\tprint(\">>>Steps: %d\\n>>>Cross_entropy: %.6f\\n>>>Average_time: %.6fs\\n\" % (steps + 1, _cross_entropy, \r\n\t\t\t\t\t\t\tself.timer.average_time))\r\n\t\t\t\t\tif (steps + 1) % 6220 == 0:\r\n\t\t\t\t\t\tself.snap_shot(sess, steps + 1)\r\n\t\t\t\texcept tf.errors.OutOfRangeError:\r\n\t\t\t\t\tbreak\r\n\r\n\tdef snap_shot(self, sess, iter):\r\n\t\tnetwork = self.network\r\n\t\tfile_name = self._save_path + \"model\" + str(iter) + \".ckpt\"\r\n\t\tself.saver.save(sess, file_name)\r\n\t\tprint(\"Wrote snapshot to: \" + file_name + \"\\n\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\ttrainer = Trainer()\r\n\ttrainer.train()","repo_name":"hoodpy/deeplab_v3","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"13139690386","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 25 13:17:51 2017\n\n@author: mmenoret\n\"\"\"\n\nimport numpy as np\nfrom sklearn.covariance import LedoitWolf\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pylab as plt\n\n# Behavioral DATA\nfold_g = 'F:/IRM_Marche/'\nsmt='ss' \nnames='ap','as','boh','bh','bi','cmp','cas','cs','cb','gm','gn','gbn','mv','ms','pm','pc','ph','pa','pv','pom','rdc','ti','vs'\nlabel=np.loadtxt(fold_g+'label_main.txt','S12')\nblock=np.loadtxt(fold_g+'block_main.txt','int')\nmotor_region=np.fromfile('F:/IRM_Marche/masquesROI/reg_whole70_basc444asym.np','int')\n\n# Remove data not analysed\nmask_block=block==block\nfor x in range(label.shape[0]):\n if label[x,2]!=label[x-1,2]:\n mask_block[x]=False\n elif label[x,2]!=label[x-2,2]:\n mask_block[x]=False\nc_des_out=np.logical_not(label[:,2]== b'des')\ntmp_out= np.logical_and(c_des_out,mask_block)\nc_rest_out=np.logical_not(label[:,0]== b'rest')\ncond_out= np.logical_and(tmp_out,c_rest_out)\ny=label[cond_out,2]\nlabels=np.unique(y)\n# Prepare correlation\nestimator = LedoitWolf()\nscaler=StandardScaler()\n# Create np array\nresult_matrix = np.empty([len(names),motor_region.shape[0],labels.shape[0],labels.shape[0]])\n\n#Analysis for each subject\nfor i,n in enumerate(sorted(names)):\n roi_name=fold_g+'mni4060/asymroi_'+smt+'_'+n+'.npz' \n roi=np.load(roi_name)['roi'][cond_out]\n roi=roi[:,motor_region-1] \n for j in range(motor_region.shape[0]):\n roi_j=roi[:,j]\n roi_mat=np.zeros(((y==b'imp').sum(),len(labels)))\n for z,lab in enumerate(sorted(labels)):\n roi_mat[:,z]=roi_j[y==lab] \n roi_sc=scaler.fit_transform(roi_mat) \n estimator.fit(roi_sc)\n matrix=estimator.covariance_ \n result_matrix[i,j]=1-matrix\n\nnp.savez_compressed('F:/IRM_Marche/dismatrix.npz',result_matrix)\n\n\n","repo_name":"mmenoret/IRM_Marche_WIP","sub_path":"WIP/dissimilaritymatrix_all.py","file_name":"dissimilaritymatrix_all.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"28528607238","text":"def isSame(sub_str1, str2):\n\n for a, b in zip(sub_str1, str2):\n if a != b:\n return False\n\n return True\n\ndef main():\n\n str1 = list(input())\n str2 = list(input())\n\n dp = [0] * (len(list(str1)) + 1)\n\n for i in range(len(str2) - 1, len(str1)):\n\n if str1[i] == str2[-1] and isSame(str1[i + 1 - len(str2):i + 1], str2):\n dp[i] = dp[i - 1] + 1\n else:\n dp[i] = dp[i - 1]\n\n print(max(dp))\n\nif __name__ == \"__main__\":\n main()","repo_name":"su-ram/Problem-Solving","sub_path":"elice/부분문자열.py","file_name":"부분문자열.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"36172018960","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 7 09:39:39 2020\n\n@author: Zhuo\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport warnings\nwarnings.filterwarnings('ignore') #忽略warning信息\n\ndf = pd.DataFrame(columns=['身高','体重','肺活量'])\ndf['身高'] = [162,165,168,163,170,174,176,178,173,180,182,185]\ndf['体重'] = [600,45.2,50.2,60.3,59.6,62.4,64.5,72.7,70.0,75.4,76.1,74.8]\ndf['肺活量'] = [2500,3200,4240,4000,4400,3800,4120,4400,44111,3800,5200,6000] \ntarget = np.array([0,0,0,0,1,0,1,1,1,1,1,1])\n\n\n\"\"\"四分差法\"\"\"\ndef detect_outliers_1(df): #输入df\n for i in range(0,len(df.iloc[0,:])):\n x = df.iloc[:,i]\n q1,q3 = np.percentile(x, [25,75])\n iqr = q3 - q1\n upper = q3+iqr*1.5\n lower = q1-iqr*1.5\n x[(x[:]>upper)|(x[:]> 3) & 1\n state[1] = (bstate >> 2) & 1\n state[2] = (bstate >> 1) & 1\n state[3] = (bstate >> 0) & 1\n\n state[4] = self.board.turn * 1.0\n\n return state\n\n def edges(self):\n return list(self.board.turn * 1.0)\n\n\ndef get_dataset(num_samples=None):\n X, y = [], []\n gn = 0\n values = {\"1/2-1/2\": 0, \"0-1\": -1, \"1-0\": 1}\n for fn in os.listdir(\"data\"):\n pgn = open(os.path.join(\"data\", fn))\n while 1:\n game = chess.pgn.read_game(pgn)\n if game is None:\n break\n res = game.headers[\"Result\"]\n if res not in values:\n continue\n value = values[res]\n board = game.board()\n for i, move in enumerate(game.mainline_moves()):\n board.push(move)\n ser = State(board).serialize()\n X.append(ser)\n y.append(value)\n print(\"Parsing game %d, got %d examples\" % (gn, len(X)))\n if num_samples is not None and len(X) > num_samples:\n X = np.array(X)\n y = np.array(y)\n return X, y\n gn += 1\n X = np.array(X)\n y = np.array(y)\n\n return X, y\n\n\nif __name__ == \"__main__\":\n X, y = get_dataset(10000)\n print(type(X))\n np.savez(\"dataset_100.npz\", X, y)\n","repo_name":"HenryDashwood/chess-engine","sub_path":"chess/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70418173192","text":"import time\n\nfrom typing import Optional\n\n\nclass PIDController:\n def __init__(self,\n proportional_coef: float,\n integral_coef: float,\n derivative_coef: float,\n windup_guard: float,\n current_time: Optional[float] = None) -> None:\n \"\"\"PID Controller class for universal control purposes.\n\n u(t) = K_p e(t) + K_i \\int_{0}^{t} e(t)dt + K_d {de}/{dt}\n\n Args:\n proportional_coef (float): Proportional coefficient.\n integral_coef (float): Integral coefficient.\n derivative_coef (float): Derivative coefficient.\n windup_guard (float): Critical value of integral term in main equation.\n current_time (Optional[float]): First timestamp of control in seconds.\n \"\"\"\n self.__p_coef = proportional_coef\n self.__i_coef = integral_coef\n self.__d_coef = derivative_coef\n\n self.__windup_guard = windup_guard\n self.__current_time = current_time if current_time is not None else time.time()\n\n self.__set_point = None\n\n self.__last_time = self.__current_time\n self.__last_error = 0.0\n\n self.__p_term = 0.0\n self.__i_term = 0.0\n self.__d_term = 0.0\n\n def update(self,\n feedback_value: float,\n current_time: Optional[float]) -> float:\n \"\"\"Method for updating actuator value.\n\n Args:\n feedback_value (float): Real target value, measured in previous step.\n current_time (Optional[float]): Current timestamp in seconds.\n\n Returns:\n float: Actuator value.\n \"\"\"\n\n error = self.__set_point - feedback_value\n delta_error = error - self.__last_error\n\n self.__current_time = current_time if current_time is not None else time.time()\n delta_time = self.__current_time - self.__last_time\n\n self.__p_term = self.__p_coef * error\n self.__d_term = self.__d_coef * delta_error / delta_time\n self.__i_term += self.__i_term * error * delta_time\n self.__i_term = max(min(self.__windup_guard, self.__i_term), -self.__windup_guard)\n\n self.__last_time = self.__current_time\n self.__last_error = error\n\n return self.__p_term + self.__i_term + self.__d_term\n\n def reset(self) -> None:\n \"\"\"Method resets all equation terms.\n\n \"\"\"\n self.__p_term = 0.0\n self.__i_term = 0.0\n self.__d_term = 0.0\n self.__last_error = 0.0\n\n def set_set_point(self, set_point: float) -> None:\n \"\"\"Setter method for new set point.\n\n Args:\n set_point(float): Point of interest, eg. target velocity.\n\n Returns:\n\n \"\"\"\n self.__set_point = set_point\n","repo_name":"KolodziejczykWaldemar/AutonomousRobot","sub_path":"pid.py","file_name":"pid.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"28990908031","text":"import pygame\nimport application_constants as game\nimport game_images\nui_images = game_images.get_ui_images()\n\ndef button_default():\n print('this button is useless!')\n\nclass Element(pygame.sprite.Sprite):\n def __init__(self, text = None, pos = (0, 0),\n image = None, image_name = None, offset = None, text_color = None, centered = False):\n pygame.sprite.Sprite.__init__(self)\n \n if text:\n text_surface = game.FONT_STANDARD.render(text, False, game.WHITE)\n else:\n text_surface = pygame.Surface((0, 0))\n \n if image:\n self.image = image\n elif image_name:\n self.image = ui_images[image_name]\n else: \n self.image = pygame.Surface((\n (text_surface.get_width()+40),\n (text_surface.get_height()+10)))\n \n if not offset:\n offset = (\n (self.image.get_width()-text_surface.get_width())/2,\n (self.image.get_height()-text_surface.get_height())/2)\n self.image.blit(text_surface, offset)\n \n self.rect = self.image.get_rect()\n self.rect.x = pos[0]\n self.rect.y = pos[1]\n if centered:\n self.rect.x += (game.WIDTH-self.image.get_width())/2\n self.rect.y += (game.HEIGHT-self.image.get_height())/2\n\n def set_image(self, image = None, image_name = None):\n if image:\n self.image = image\n elif image_name:\n self.image = ui_images[image_name]\n else:\n return\n\nclass Popup(Element):\n def __init__(self, text = '!',\n pos = (0, 0), image = None, image_name = None, offset = None, text_color = game.YELLOW):\n Element.__init__(self, text, pos, image, image_name, offset, text_color, centered = True)\n \nclass Button(Element):\n def __init__(self, text = None,\n pos = (0, 0), image = None, image_name = None, offset = None, text_color = None, centered = False,\n onclick = button_default, arg = None):\n Element.__init__(self, text, pos, image, image_name, offset, text_color, centered)\n self.onclick = onclick\n self.arg = arg\n \n def clicked(self):\n if self.arg:\n self.onclick(self.arg)\n else:\n self.onclick()\n","repo_name":"s4rd0n1k/pygame_mariokart","sub_path":"game_ui.py","file_name":"game_ui.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"27"} +{"seq_id":"35415088114","text":"import unittest\nfrom typing import List, Optional\n\nfrom leetcode_data_structure import TreeNode\n\n\nclass Solution:\n def getLonelyNodes(self, root: Optional[TreeNode]) -> List[int]:\n ans: list = []\n if root is None:\n return []\n\n def dfs(node):\n if node.left is not None and node.right is None:\n ans.append(node.left.val)\n dfs(node.left)\n elif node.left is None and node.right is not None:\n ans.append(node.right.val)\n dfs(node.right)\n elif node.left is not None and node.right is not None:\n dfs(node.left)\n dfs(node.right)\n\n dfs(root)\n return ans\n\n\ndef test(testObj: unittest.TestCase, root_arr: List[int], expected: int) -> None:\n root = TreeNode.from_array(root_arr) # type: ignore\n so = Solution()\n actual = so.getLonelyNodes(root)\n testObj.assertEqual(actual, expected)\n\n\nclass TestClass(unittest.TestCase):\n def test_1(self):\n test(self, [1, 2, 3, None, 4], [4])\n\n def test_2(self):\n test(self, [7, 1, 4, 6, None, 5, 3, None, None, None, None, None, 2], [6, 2])\n\n def test_3(self):\n test(\n self,\n [11, 99, 88, 77, None, None, 66, 55, None, None, 44, 33, None, None, 22],\n [77, 55, 33, 66, 44, 22],\n )\n\n def test_4(self):\n test(self, [], [])\n\n def test_5(self):\n test(self, [1, 2, 3], [])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n\"\"\"\nRuntime: 60 ms, faster than 87.98%\nMemory Usage: 15.2 MB, less than 44.29%\n\"\"\"\n","repo_name":"EricWebsmith/leetcode_py","sub_path":"archive/lc_1469_find_all_the_lonely_nodes.py","file_name":"lc_1469_find_all_the_lonely_nodes.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"31662228664","text":"from django.urls import path, include\n\nfrom . import views\n\n\n\n#paths\n\nurlpatterns = [\n\n path('', include(([\n path('', views.workerpanel, name='workerpanel'),\n path('transactionfromworker/', views.transactionfromworker, name='transactionfromworker'),\n path('connectforworker/', views.connectforworker, name='connectforworker'),\n path('cntrltransaction/', views.cntrltransaction, name='ccntrltransaction'),\n path('Informationworker/', views.Informationworker, name='Informationworker'),\n path('dolar/', views.dolar, name='dolar'),\n ], 'staff'), namespace='staff')),\n\n\n\n]\n","repo_name":"ZahraDLBR/mobadelan","sub_path":"staff_fatemeh/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19492275930","text":"ATTR_MAPPING = {\n 'AS': 'networkSourceAsn',\n 'email-dst': 'emailRecipient',\n 'email-src-display-name': 'emailSenderName',\n 'email-subject': 'emailSubject',\n 'email-x-mailer': 'emailXMailer',\n 'filename': 'fileName',\n 'malware-type': 'malwareFamilyNames',\n 'mutex': 'fileMutexName',\n 'port': 'networkPort',\n 'published': 'isActive',\n 'size-in-bytes': 'fileSize',\n 'url': 'url',\n 'user-agent': 'userAgent',\n 'uuid': 'externalId'\n}\n\nMISP_HASH_TYPES = frozenset([\n \"filename|authentihash\",\n \"filename|impfuzzy\",\n \"filename|imphash\",\n \"filename|md5\",\n \"filename|pehash\",\n \"filename|sha1\",\n \"filename|sha224\",\n \"filename|sha256\",\n \"filename|sha384\",\n \"filename|sha512\",\n \"filename|sha512/224\",\n \"filename|sha512/256\",\n \"filename|ssdeep\",\n \"filename|tlsh\",\n \"authentihash\",\n \"impfuzzy\",\n \"imphash\",\n \"md5\",\n \"pehash\",\n \"sha1\",\n \"sha224\",\n \"sha256\",\n \"sha384\",\n \"sha512\",\n \"sha512/224\",\n \"sha512/256\",\n \"ssdeep\",\n \"tlsh\",\n])\n\nMISP_SPECIAL_CASE_TYPES = frozenset([\n *MISP_HASH_TYPES,\n 'ip-dst',\n 'ip-src',\n 'domain|ip',\n 'email-src',\n 'ip-dst|port',\n 'ip-src|port'\n])\n\nMISP_ACTIONABLE_TYPES = frozenset([\n *ATTR_MAPPING.keys(),\n *MISP_SPECIAL_CASE_TYPES\n])\n\nCLIENT_ID = 'client_id'\nCLIENT_SECRET = 'client_secret'\nTENANT = 'tenant'\nACCESS_TOKEN = 'access_token'\nGRAPH_TI_INDICATORS_URL = 'https://graph.microsoft.com/beta/security/tiindicators'\nGRAPH_BULK_POST_URL = f'{GRAPH_TI_INDICATORS_URL}/submitTiIndicators'\nGRAPH_BULK_DEL_URL = f'{GRAPH_TI_INDICATORS_URL}/deleteTiIndicators'\nLOG_DIRECTORY_NAME = 'logs'\nEXISTING_INDICATORS_HASH_FILE_NAME = 'existing_indicators_hash.json'\nEXPIRATION_DATE_TIME = 'expirationDateTime'\nEXPIRATION_DATE_FILE_NAME = 'expiration_date.txt'\nINDICATOR_REQUEST_HASH = 'indicatorRequestHash'\n# TARGET_PRODUCT_BULK_SUPPORT = ['Azure Sentinel']\n# TARGET_PRODUCT_NON_BULK_SUPPORT = ['Microsoft Defender ATP']\n\nEVENT_MAPPING = {\n 'date': 'firstReportedDateTime',\n 'timestamp': 'lastReportedDateTime',\n 'info': 'description',\n 'uuid': 'externalId'\n}\n\nREQUIRED_GRAPH_METADATA = frozenset([\n \"threatType\",\n \"tlpLevel\",\n \"description\",\n \"expirationDateTime\",\n \"targetProduct\",\n])\n\nOPTIONAL_GRAPH_METADATA = frozenset([\n \"activityGroupNames\",\n \"additionalInformation\",\n \"confidence\",\n \"diamondModel\",\n \"externalId\",\n \"isActive\",\n \"killChain\",\n \"knownFalsePositives\",\n \"lastReportedDateTime\",\n \"malwareFamilyNames\",\n \"passiveOnly\",\n \"severity\",\n \"tags\",\n])\n\nGRAPH_OBSERVABLES = frozenset([\n \"emailEncoding\",\n \"emailLanguage\",\n \"emailRecipient\",\n \"emailSenderAddress\",\n \"emailSenderName\",\n \"emailSourceDomain\",\n \"emailSourceIPAddress\",\n \"emailSubject\",\n \"emailXMailer\",\n \"fileCompileDateTime\",\n \"fileCreationDateTime\",\n \"fileHashType\",\n \"fileHashValue\",\n \"fileMutexName\",\n \"fileName\",\n \"filePacker\",\n \"filePath\",\n \"fileSize\",\n \"fileType\",\n \"domainName\",\n \"networkIPv4\",\n \"networkIPv6\",\n \"networkPort\",\n \"networkDestinationAsn\",\n \"networkDestinationCidrBlock\",\n \"networkDestinationIPv4\",\n \"networkDestinationIPv6\",\n \"networkDestinationPort\",\n \"networkProtocol\",\n \"networkSourceAsn\",\n \"networkSourceCidrBlock\",\n \"networkSourceIPv4\",\n \"networkSourceIPv6\",\n \"networkSourcePort\",\n \"url\",\n \"userAgent\",\n])","repo_name":"microsoftgraph/security-api-solutions","sub_path":"Samples/MISP/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":3437,"program_lang":"python","lang":"en","doc_type":"code","stars":205,"dataset":"github-code","pt":"27"} +{"seq_id":"8252102961","text":"n = int(input())\ndice = list(map(int, input().split()))\n\n# n=1이면 제일 큰 수 제외 나머지 합\n# n=2이면 3면 보이는 거 4개(1,2,3), 2면 보이는 거 4개(1,2)\n# n=3이면 2면 보이는 거 12개, 1면 보이는 거 9개, 3면 보이는 거 4개, 0면 보이는 거 2개\n# 3면 4개, 2면 4*(n-1)+4*(n-2), 1면 4*(n-1)(n-2)+(n-2)*(n-2)\n\n# 마주보는 면은 제외해야 함!!! -> 이거때매 틀림\ntemp = [min(dice[0], dice[5]), min(dice[1], dice[4]), min(dice[2], dice[3])]\ntemp.sort()\nanswer = 0\n\nif n == 1:\n print(sum(dice) - max(dice))\nelse:\n answer += sum(temp) * 4\n answer += (temp[0] + temp[1]) * (4 * (n - 1) + 4 * (n - 2))\n answer += temp[0] * ((n - 2) * 4 * (n - 1) + (n - 2) * (n - 2))\n print(answer)\n \n \n\n","repo_name":"M1nseoPark/CodingtestStudy","sub_path":"주사위.py","file_name":"주사위.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"14264607936","text":"from PyQt5.QtWidgets import *\r\nfrom PyQt5 import QtGui,QtCore\r\nfrom PyQt5.QtGui import QPixmap\r\n\r\n\r\nimport sys\r\nimport time\r\nfrom MobileWorld.mlogin import Mylogin\r\n\r\ndef main():\r\n\r\n\r\n\r\n\r\n\r\n app=QApplication(sys.argv)\r\n\r\n\r\n splash_pix=QPixmap(\"tulips.jpg\")\r\n splash=QSplashScreen(splash_pix)\r\n\r\n\r\n current_window_flags=splash.windowFlags()\r\n splash.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | current_window_flags)\r\n\r\n font = QtGui.QFont()\r\n font.setFamily(\"Arial\")\r\n font.setPointSize(80)\r\n splash.setFont(font)\r\n\r\n splash.showMessage('welcome...',QtCore.Qt.AlignLeft | QtCore.Qt.AlignBottom,QtGui.QColor.fromRgb(150,100,100))\r\n\r\n splash.show()\r\n\r\n\r\n\r\n import xlrd\r\n import pyttsx as p\r\n engine = p.init() # object creation\r\n\r\n voices = engine.getProperty('voices')\r\n engine.setProperty('voice', voices[0].id)\r\n engine.setProperty('volume',10)\r\n engine.say(\"welcome to the future\")\r\n engine.setProperty('rate', 100)\r\n engine.runAndWait()\r\n engine.stop()\r\n\r\n\r\n app.processEvents()\r\n import time\r\n time.sleep(4)\r\n login=Mylogin()\r\n login.show()\r\n splash.finish(login)\r\n app.exec_()\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':main()\r\n","repo_name":"atisheksingh/Mobile_world","sub_path":"MobileWorld/msplash.py","file_name":"msplash.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"29852463914","text":"import pytest as pytest\nimport requests\nimport json\nimport jsonpath\nfrom utility.file_utility import *\nfrom utility.numpyencoder import NumpyEncoder\n\nbaseUrl = \"https://url.com\"\nvehicle_size_endpoint = \"/vehicle_size\"\ndata_file = \"tests/data/input_vehicles.csv\"\nnegative_data_file = \"tests/data/input_vehicles_negative.csv\"\nrequirements_file = \"tests/data/requirements.csv\"\n\n\n# 1. Positive tests with Pandas\ndef test_size_of_vehicles_pandas():\n jsArray = []\n df = pd.read_csv(data_file)\n for i in df.index:\n jsArray.insert(i, create_one_item(df.loc[df.index[i], \"length\"], df.loc[df.index[i], \"width\"],\n df.loc[df.index[i], \"height\"], df.loc[df.index[i], \"weight\"],\n df.loc[df.index[i], \"quantity\"]))\n inputData = json.dumps(jsArray, indent=4, sort_keys=True, separators=(', ', ': '), ensure_ascii=False,\n cls=NumpyEncoder)\n print(inputData)\n response = requests.post(url=baseUrl + vehicle_size_endpoint, json=inputData)\n responseJson = json.loads(response.text)\n print(responseJson)\n assert response.status_code == 200\n actual_vehicle_size = jsonpath.jsonpath(responseJson, '$.calculated_vehicle_size')\n assert actual_vehicle_size is not None\n\n\n# 1. Positive tests without Pandas\ndef test_size_of_vehicles_positive():\n jsArray = []\n index_object = 0\n with open(data_file, newline=\"\") as csvfile:\n csv_dict_reader = csv.DictReader(csvfile, delimiter=',')\n for row in csv_dict_reader:\n index_object += 1\n jsArray.insert(index_object,\n create_one_item_convert(row['length'], row['width'], row['height'], row['weight'],\n row['quantity']))\n inputData = json.dumps(jsArray, sort_keys=True, indent=3)\n print(inputData)\n response = requests.post(url=baseUrl + vehicle_size_endpoint, json=inputData)\n responseJson = json.loads(response.text)\n print(responseJson)\n assert response.status_code == 200\n actual_vehicle_size = jsonpath.jsonpath(responseJson, '$.calculated_vehicle_size')\n assert actual_vehicle_size is not None\n\n\n# Negative tests\n# 1. Zero input length\n# 2. Zero input width\n# 3. Zero input height\n# 4. Zero input weight\n# 5. Zero input quantity\n# 6. Zero input all values\n# 7. Letters input length\n# 8. Letters input width\n# 9. Letters input height\n# 10. Letters input weight\n# 11. Letters input quantity\n# 12. Spec character input length\n# 13. Spec character width\n# 14. Spec character height\n# 15. Spec character weight\n# 16. Spec character quantity\n# 17. -1 in all values.\n\n\n@pytest.mark.parametrize(\"index,length,width,height,weight,quantity\", read_from_csv(negative_data_file))\ndef test_size_of_vehicles_spec_negative(index, length, width, height, weight, quantity):\n jsArray = []\n index_obj = int(index)\n jsArray.insert(index_obj, create_one_item(length, width, height, weight, quantity))\n inputData = json.dumps(jsArray, sort_keys=True, indent=3)\n print(inputData)\n response = requests.post(url=baseUrl + vehicle_size_endpoint, json=inputData)\n responseJson = json.loads(response.text)\n assert response.status_code == 400\n print(responseJson)\n\n\n# Generate random values.\ndef test_size_of_vehicles_negative_random():\n jsArray = []\n index_object = 3\n length = randomDigits(5, 100)\n width = randomDigits(2, 10)\n height = randomDigits(4, 1000)\n weight = randomDigits(1, 1000)\n quantity = randomDigits(1, 100)\n jsArray.insert(index_object, create_one_item(length, width, height, weight, quantity))\n inputData = json.dumps(jsArray, sort_keys=True, indent=3)\n print(inputData)\n response = requests.post(url=baseUrl + vehicle_size_endpoint, json=inputData)\n responseJson = json.loads(response.text)\n assert response.status_code == 400\n print(responseJson)\n","repo_name":"seniorQAautomationEngineer/vehicle_identifier","sub_path":"tests/identifier.py","file_name":"identifier.py","file_ext":"py","file_size_in_byte":3925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"9122592237","text":"class Scrabble(object):\r\n # Scrabble Class, input: file\r\n def __init__(self, scrabbleFileName):\r\n # Word List\r\n self.__wordList = []\r\n # Open the file and reading it\r\n fileIn = open(scrabbleFileName, \"r\")\r\n # For ever word in the file...\r\n for words in fileIn:\r\n # Separate by sentences\r\n words = words.strip()\r\n # Every word is added into the wordList\r\n self.__wordList.append(words)\r\n fileIn.close()\r\n # Word List's Value\r\n self.wordValue()\r\n # Q's and no U's\r\n def qAndU (self):\r\n for words in self.__wordList:\r\n # Letters\r\n # First Letter\r\n first_letter = words[0]\r\n # Second Letter\r\n second_letter = words[1]\r\n if first_letter == \"q\":\r\n if second_letter != \"u\":\r\n print(words, self.__newDictionary[words])\r\n # Shows every two letters\r\n def twoLetter (self):\r\n for words in self.__wordList:\r\n # Gets the length of each word\r\n (length) = int(len(words))\r\n if length == 2:\r\n print(words, self.__newDictionary[words])\r\n # Shows every three letters with the user input letter.\r\n def threeLetter (self):\r\n # User's input\r\n print(\"Please enter a letter:\")\r\n firstLetterChoice = input(\"< \")\r\n firstLetterChoice = firstLetterChoice.lower()\r\n for words in self.__wordList:\r\n first_letter = words[0]\r\n if first_letter == firstLetterChoice:\r\n length = int(len(words))\r\n # Obtains all the 3 length words\r\n if length == 3:\r\n print(words, self.__newDictionary[words])\r\n # Word checker\r\n def wordVerify (self):\r\n # User's input\r\n print(\"Please write a word to check:\")\r\n choice = input(\"< \")\r\n choice = choice.lower()\r\n # If it's in the list\r\n if choice in self.__wordList:\r\n print(choice, \"is in the word list!\")\r\n # If it's not in the list\r\n else:\r\n print(choice, \"is not in the word list!\")\r\n # The end checker\r\n def checkEnd (self):\r\n # User's input\r\n print(\"Please enter letters:\")\r\n choice = input(\"< \")\r\n choice = choice.lower()\r\n for words in self.__wordList:\r\n # Get's the length of the word and starts from the back\r\n if words[-len(choice):] == choice:\r\n print(words, self.__newDictionary[words])\r\n # The beginning checker\r\n def checkBeginning (self):\r\n # User input\r\n print(\"Please enter letters:\")\r\n choice = input(\"< \")\r\n choice = choice.lower()\r\n for words in self.__wordList:\r\n # Get's the length of the word and starts from the beginning\r\n if words[0:len(choice)] == choice:\r\n print(words, self.__newDictionary[words])\r\n # It has \"X\" or \"Z\"\r\n def xOrZ (self):\r\n # User's input\r\n print(\"Please enter letters:\")\r\n choice = input(\"< \")\r\n choice = choice.lower()\r\n for words in self.__wordList:\r\n # Obtains all words with x or z with user input\r\n if \"x\" in words or \"z\" in words:\r\n if choice in words:\r\n print(words, self.__newDictionary[words])\r\n # The word value\r\n def wordValue (self):\r\n # Values\r\n myDictionary = {\"a\": 1, \"b\": 3, \"c\": 3, \"d\": 2, \"e\": 1, \"f\": 4, \"g\": 2, \"h\": 4, \"i\": 1, \"j\": 8, \"k\": 5, \"l\": 1,\r\n \"m\": 3, \"n\": 1, \"o\": 1, \"p\": 3, \"q\": 10, \"r\": 1, \"s\": 1, \"t\": 1, \"u\": 1, \"v\": 4, \"w\": 4, \"x\": 8,\r\n \"y\": 4, \"z\": 10}\r\n self.__newDictionary = {}\r\n for words in self.__wordList:\r\n # Value\r\n total = 0\r\n for letters in words:\r\n value = myDictionary[letters]\r\n # Adds up the value\r\n total += int(value)\r\n # the value\r\n self.__newDictionary[words] = total","repo_name":"taehwany/ITP115","sub_path":"Scrabble Dictionary/Function.py","file_name":"Function.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"2071959581","text":"import numpy as np\nimport pygame\nimport os\nimport GLOBAL_VARS as G\nfrom neural_network import NeuralNetwork\n\n\nclass Bird(object):\n sprite = [\n pygame.image.load(os.path.join('assets/sprites', 'bluebird-downflap.png')),\n pygame.image.load(os.path.join('assets/sprites', 'bluebird-midflap.png')),\n pygame.image.load(os.path.join('assets/sprites', 'bluebird-upflap.png'))\n ]\n\n best_sprite = [\n pygame.image.load(os.path.join('assets/sprites', 'redbird-downflap.png')),\n pygame.image.load(os.path.join('assets/sprites', 'redbird-midflap.png')),\n pygame.image.load(os.path.join('assets/sprites', 'redbird-upflap.png'))\n ]\n\n def __init__(self):\n self.x = 0.2 * G.SCREEN_WIDTH\n self.y = 200\n self.width = 34\n self.height = 24\n self.move_count = 0 # to cycle among sprites\n self.acc = 0.0\n self.vel = 0.0\n self.hitbox = [self.x + 6, self.y + 5, self.width - 6, self.height - 5]\n self.dead = False\n self.tf_inputs = []\n self.score = 0\n self.fitness = 0.0\n self.nn = NeuralNetwork(5, 8, 2)\n self.baby = None\n self.is_best = False\n\n def show(self, window):\n self.hitbox = [self.x + 6, self.y + 5, self.width - 6, self.height - 5]\n # pygame.draw.rect(window, (255, 0, 0), self.hitbox, 2)\n\n if self.move_count > 8:\n self.move_count = 0\n if self.is_best:\n new_sprite = pygame.transform.rotate(self.best_sprite[self.move_count // 3], self.vel)\n else:\n new_sprite = pygame.transform.rotate(self.sprite[self.move_count // 3], self.vel)\n window.blit(new_sprite, (self.x, self.y))\n if not self.dead:\n self.move_count += 1\n\n def move(self):\n self.think()\n self.vel += G.Y_ACC\n self.vel = np.clip(self.vel, -40, 20)\n self.y -= self.vel\n self.y = np.clip(self.y, -10, 401 - self.height)\n\n def update(self):\n if not self.dead:\n self.move()\n self.collide()\n self.score = - G.X_POS\n elif self.x < - self.width - 5:\n pass\n else:\n self.x -= G.X_VEL\n\n def jump(self):\n self.vel = 10\n\n def collide(self):\n if self.hitbox[1] + self.hitbox[3] > 400:\n # print(\"COLLISION TERRAIN\")\n self.dead = True\n elif self.hitbox[1] < 0:\n # print(\"COLLISION SKY\")\n self.dead = True\n return False\n\n def gimme_baby(self):\n self.baby = Bird()\n self.baby.nn = self.nn.copy()\n self.baby.mutate()\n return self.baby\n\n def clone(self):\n self.baby = Bird()\n self.baby.nn = self.nn.copy()\n return self.baby\n\n def get_tf_inputs(self, _pipes_):\n next_obstacle = _pipes_.get_next_obstacle()\n self.tf_inputs = []\n self.tf_inputs.append(self.vel / 40.0)\n self.tf_inputs.append(self.y / G.SCREEN_HEIGHT)\n self.tf_inputs.append((next_obstacle[0] - self.x + 26) / G.SCREEN_WIDTH)\n self.tf_inputs.append((next_obstacle[1] - self.y) / G.SCREEN_WIDTH)\n self.tf_inputs.append((next_obstacle[1] - self.y + 120) / G.SCREEN_WIDTH)\n\n def think(self):\n output = self.nn.predict(self.tf_inputs)\n if output[0] > output[1]:\n self.jump()\n\n def mutate(self):\n self.nn.mutate(G.MUT_RATE)\n","repo_name":"annessi33/NeuralFlappy","sub_path":"bird.py","file_name":"bird.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"5349318394","text":"from __future__ import absolute_import\n\n# this is needed to get logging info in `py.test` when something fails\nimport logging\nlogging.basicConfig()\n\n# 3rd-party imports\nfrom mock import MagicMock, call, patch\nimport pytest\nfrom pytest import raises\n\n# ElastiCluster imports\nfrom elasticluster.exceptions import ClusterError\n\n# local test imports\nfrom _helpers.config import make_cluster\nfrom _helpers.environ import clean_os_environ_openstack\n\n\n__author__ = (', '.join([\n 'Nicolas Baer ',\n 'Riccardo Murri ',\n]))\n\n\n\ndef test_add_node(tmpdir):\n \"\"\"\n Add node and let ElastiCluster choose the name.\n \"\"\"\n clean_os_environ_openstack()\n cluster = make_cluster(tmpdir)\n size = len(cluster.nodes['compute'])\n cluster.add_node(\"compute\", 'image_id', 'image_user', 'flavor',\n 'security_group')\n assert (size + 1) == len(cluster.nodes['compute'])\n new_node = cluster.nodes['compute'][2]\n assert new_node.kind == 'compute'\n assert new_node.name == 'compute003'\n\n\ndef test_add_node_with_custom_name(tmpdir):\n \"\"\"\n Add node with a given name.\n \"\"\"\n cluster = make_cluster(tmpdir)\n name = \"test-node\"\n size = len(cluster.nodes['compute'])\n cluster.add_node(\"compute\", 'image_id', 'image_user', 'flavor',\n 'security_group', image_userdata=\"\", name=name)\n assert (size + 1) == len(cluster.nodes['compute'])\n assert (cluster.nodes['compute'][-1].name) == name\n\n\ndef test_remove_node(tmpdir):\n \"\"\"\n Remove node\n \"\"\"\n cluster = make_cluster(tmpdir)\n size = len(cluster.nodes['compute'])\n # Method `cluster.remove_node()` calls\n # `cluster._gather_node_ip_addresses()` which in turn tries to\n # connect to nodes over SSH, so we need to avoid that these\n # connections are really attempted during tests. This requires\n # two steps:\n #\n # (1) that each node is assigned a list of IP addresses (otherwise\n # connection is skipped); and\n # (2) that we substitute the actual connection function with a mock one\n for node in cluster.get_all_nodes():\n node.ips = ['1.2.3.4']\n with patch('paramiko.SSHClient'):\n cluster.remove_node(cluster.nodes['compute'][1])\n assert (size - 1) == len(cluster.nodes['compute'])\n\n\ndef test_start(tmpdir):\n \"\"\"\n Start cluster\n \"\"\"\n cloud_provider = MagicMock()\n cloud_provider.start_instance.return_value = {'instance_id': 'test-id'}\n cloud_provider.get_ips.return_value = ['127.0.0.1']\n cloud_provider.is_instance_running.return_value = True\n\n cluster = make_cluster(tmpdir, template='example_ec2', cloud=cloud_provider)\n cluster.repository = MagicMock()\n cluster.repository.storage_path = '/unused/path'\n\n with patch('paramiko.SSHClient'):\n cluster.start()\n\n cluster.repository.save_or_update.assert_called_with(cluster)\n\n for node in cluster.get_all_nodes():\n assert node.instance_id == u'test-id'\n assert node.ips == ['127.0.0.1']\n\n\ndef test_check_cluster_size_ok(tmpdir):\n cluster = make_cluster(tmpdir)\n\n assert len(cluster.nodes[\"frontend\"]) == 1\n assert len(cluster.nodes[\"compute\"]) == 2\n\n # pylint: disable=protected-access\n cluster._check_cluster_size({'frontend':1, 'compute':1})\n\n\ndef test_check_cluster_size_fail(tmpdir):\n cluster = make_cluster(tmpdir)\n\n assert len(cluster.nodes[\"frontend\"]) == 1\n assert len(cluster.nodes[\"compute\"]) == 2\n\n # pylint: disable=protected-access\n with raises(ClusterError):\n cluster._check_cluster_size({'frontend':1, 'compute':5})\n\n with raises(ClusterError):\n cluster._check_cluster_size({'frontend':3, 'compute':1})\n\n\ndef test_get_all_nodes(tmpdir):\n \"\"\"\n Check that `Cluster.get_all_nodes()` returns all nodes in the cluster.\n \"\"\"\n cluster = make_cluster(tmpdir)\n all_nodes = cluster.get_all_nodes()\n assert len(all_nodes) == 3\n assert len([node for node in all_nodes if node.name.startswith('frontend')]) == 1\n assert len([node for node in all_nodes if node.name.startswith('compute')]) == 2\n\n\ndef test_stop(tmpdir):\n \"\"\"\n Test `Cluster.stop()`\n \"\"\"\n cloud_provider = MagicMock()\n cloud_provider.start_instance.return_value = {'instance_id': 'test-id'}\n cloud_provider.get_ips.return_value = ('127.0.0.1', '127.0.0.1')\n states = [\n # pylint: disable=bad-whitespace\n True, True, True, True, True,\n False, False, False, False, False\n ]\n def is_running(instance_id): # pylint: disable=unused-argument,missing-docstring\n return states.pop()\n cloud_provider.is_instance_running.side_effect = is_running\n\n cluster = make_cluster(tmpdir, cloud=cloud_provider)\n nodes = cluster.get_all_nodes()\n for node in nodes:\n node.instance_id = 'test-id'\n\n cluster.repository = MagicMock()\n cluster.repository.storage_path = '/unused/path'\n expected_stop_calls = [call(node) for node in nodes]\n cluster.stop()\n\n cloud_provider.stop_instance.assert_has_calls(expected_stop_calls, any_order=True)\n cluster.repository.delete.assert_called_once_with(cluster)\n\n\ndef test_get_ssh_to_node_with_class(tmpdir):\n \"\"\"\n Get frontend node\n \"\"\"\n cluster = make_cluster(tmpdir)\n cluster.ssh_to = 'frontend'\n frontend = cluster.get_ssh_to_node()\n assert cluster.nodes['frontend'][0] == frontend\n\n\ndef test_get_ssh_to_node_with_nodename(tmpdir):\n \"\"\"\n Get frontend node\n \"\"\"\n cluster = make_cluster(tmpdir)\n cluster.ssh_to = 'frontend001'\n frontend = cluster.get_ssh_to_node()\n assert frontend.name == 'frontend001'\n\n\ndef test_get_ssh_to_node_with_defaults(tmpdir):\n \"\"\"\n Get frontend node\n \"\"\"\n cluster = make_cluster(tmpdir)\n cluster.ssh_to = None\n frontend = cluster.get_ssh_to_node()\n assert cluster.nodes['frontend'][0] == frontend\n\n\ndef test_setup(tmpdir):\n \"\"\"\n Setup the nodes of a cluster\n \"\"\"\n # pylint: disable=protected-access\n cluster = make_cluster(tmpdir)\n setup_provider = MagicMock()\n setup_provider.setup_cluster.return_value = True\n cluster._setup_provider = setup_provider\n\n cluster.setup()\n\n setup_provider.setup_cluster.assert_called_once_with(cluster, tuple())\n\n\ndef test_update(tmpdir):\n cloud_provider = MagicMock()\n ip_addr = '127.0.0.1'\n cloud_provider.get_ips.return_value = (ip_addr, ip_addr)\n\n storage = MagicMock()\n\n cluster = make_cluster(tmpdir, cloud=cloud_provider)\n cluster.repository = storage\n\n with patch('paramiko.SSHClient'):\n cluster.update()\n\n for node in cluster.get_all_nodes():\n assert ip_addr == node.ips[0]\n\n\ndef test_dict_mixin(tmpdir):\n \"\"\"Check that instances of the `Cluster` class can be recast as Python dictionary.\"\"\"\n cluster = make_cluster(tmpdir, template='example_ec2')\n\n # add an attribute and test later if it's exported\n cluster.ssh_to = \"misc\"\n\n cluster_as_dict = dict(cluster)\n assert cluster_as_dict['template'] == 'example_ec2'\n assert cluster_as_dict['template'] == cluster_as_dict['name']\n assert 'misc_nodes' in cluster_as_dict['extra']\n # FIXME: why on earth are node numbers converted to string?\n assert cluster_as_dict['extra']['misc_nodes'] == '10'\n assert cluster_as_dict['ssh_to'] == 'misc'\n assert list(cluster_as_dict['nodes'].keys()) == list(cluster.nodes.keys())\n\n # non-public attrs should not be exported\n with raises(KeyError):\n # pylint: disable=pointless-statement\n cluster_as_dict['_cloud_provider']\n # pylint: disable=protected-access\n assert cluster['_cloud_provider'] == cluster._cloud_provider\n\n\nif __name__ == \"__main__\":\n pytest.main(['-v', __file__])\n","repo_name":"elasticluster/elasticluster","sub_path":"tests/test_cluster.py","file_name":"test_cluster.py","file_ext":"py","file_size_in_byte":7712,"program_lang":"python","lang":"en","doc_type":"code","stars":332,"dataset":"github-code","pt":"27"} +{"seq_id":"40414579446","text":"from django.shortcuts import render\nfrom Event.models import Event\nfrom .models import EventRatingManager, ProfileRatingManager\nfrom Profile.models import Profile\nfrom django.core import serializers\nfrom django.http import HttpResponse\nfrom django.contrib.auth.decorators import login_required\nimport json\n\n# Create your views here.\n#http://stackoverflow.com/questions/32323683/why-ajax-success-not-called-when-json-passed-through-django\n@login_required\ndef add_event_review(request, event_pk,author_pk, rating):\n\t#print \"This is adding event review view!!!!!\"\n\t#print \"Event_pk: %s author: %s rating: %s\" % (event_pk,author_pk, rating)\n\te = Event.objects.get(pk=event_pk) #get reference to event with id passed to function as an argument\n\tp = Profile.objects.get(pk = author_pk)\n\term = EventRatingManager()\n\tsuccess = erm.add_event_rating(e,p,int(rating))\n\tresponse = {'message': success}\n\t#print response\n\treturn HttpResponse(json.dumps(response), content_type='application/json')#return JSON to AJAX query\n\n\"\"\"Returns HttpResponse with dict telling if target Profile has already been rated by given author Profile for a given Event. \"\"\"\n@login_required\ndef has_been_rated(request):\n\tif(request.method == 'POST'):\n\t\t#Gathering information from AJAX query\n\t\tevent_pk = request.POST['event_pk']\n\t\tauthor_pk = request.POST['author_pk']\n\t\ttarget_pk = request.POST['target_pk']\n\t\trating = request.POST['rating']\n\t\t#Get reference to objects\n\t\tevent_reference = Event.objects.get(pk=event_pk)\n\t\tauthor_reference = Profile.objects.get(pk = author_pk)\n\t\ttarget_profile_reference = Profile.objects.get(pk = target_pk)\n\t\t#Create ProfileRatingManager\n\t\tprm = ProfileRatingManager()\n\t\talready_rated = prm.check_if_already_rated(event_reference, author_reference, target_profile_reference)\n\t\tresponse = {'profile_was_rated': already_rated}\n\telse:\n\t\tresponse = {'error':'not a post request!'}\n\treturn HttpResponse(json.dumps(response), content_type='application/json')#return JSON to AJAX query\n\n\ndef rate_target_profile(request):\n\tif(request.method == 'POST'):\n\t\t#Gathering information from AJAX query\n\t\tevent_pk = request.POST['event_pk']\n\t\tauthor_pk = request.POST['author_pk']\n\t\ttarget_pk = request.POST['target_pk']\n\t\trating = int(request.POST['rating'])\n\t\t#Get reference to objects\n\t\tevent_reference = Event.objects.get(pk=event_pk)\n\t\tauthor_reference = Profile.objects.get(pk = author_pk)\n\t\ttarget_profile_reference = Profile.objects.get(pk = target_pk)\n\t\t#Create ProfileRatingManager\n\t\tprm = ProfileRatingManager()\n\t\tadding_successfull = prm.add_profile_rating(event_reference, author_reference, target_profile_reference, rating)\n\t\tresponse = {'rating_added': adding_successfull}\n\telse:\n\t\tresponse = {'error':'not a post request!'}\n\treturn HttpResponse(json.dumps(response), content_type='application/json')#return JSON to AJAX query","repo_name":"wald3k/SetAndMeet","sub_path":"Project/RatingSystem/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"6353705400","text":"#https://www.cs.miami.edu/home/burt/learning/Csc517.091/workbook/countingsort.html\n\nimport sys\ninput=sys.stdin.readline\n\na = int(input())\nx = [0]*10000\n\nfor i in range(a):\n b = int(input())\n x[b-1] += 1 #x 에 입력된 각 숫자의 횟수를 저장함. 5가 3번 입력되면 5번째에 3을 저장.\n \nfor i in range(10000):\n if x[i] != 0:\n for j in range(x[i]): #x에 저장된 수만큼 index+1 의 숫자를 출력(0부터 시작하는 리스트 특성)\n print(i+1)","repo_name":"Daramgineer/Python_study","sub_path":"Python_study/4th.Code-Test/10.Sorting/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"256511044","text":"import json\nimport os\nimport pandas as pd\nimport folium\n# map_osm = folium.Map(location=[45.5236, -122.6750])\n# map_osm.save('./img/choropleth_map.html')\n\nrootpath = os.path.abspath(os.path.dirname(__file__))\n\ndef setup_data():\n \"\"\"Import economic data for testing.\"\"\"\n with open(os.path.join(rootpath, 'iowa-counties.json')) as f:\n get_id = json.load(f)\n\n county_codes = [x['id'] for x in get_id['features']]\n county_df = pd.DataFrame({'FIPS_Code': county_codes}, dtype=str)\n\n # Read into Dataframe, cast to string for consistency.\n df = pd.read_csv(os.path.join(rootpath, 'county_data.csv'),\n na_values=[' '])\n df['FIPS_Code'] = df['FIPS_Code'].astype(str)\n\n # Perform an inner join, pad NA's with data from nearest county.\n merged = pd.merge(df, county_df, on='FIPS_Code', how='inner')\n return merged.fillna(method='pad')\n \nimport folium\nimport pandas as pd\n\niowa_counties_geo = os.path.join(rootpath, 'iowa_counties.json')\niowa_county_data = os.path.join(rootpath, 'iowa_county_data.csv')\n\nstate_data = pd.read_csv(iowa_county_data)\n\n#Let Folium determine the scale\nmap = folium.Map(location=[48, -102], zoom_start=3)\nmap.choropleth(geo_path=iowa_counties_geo, data=state_data,\n columns=['County', 'Consumption'],\n key_on='feature.id',\n fill_color='YlGn', fill_opacity=0.7, line_opacity=0.2,\n legend_name='Consumption (Liters)')\nmap.save('./img/choropleth_map.html')\n\n# m.choropleth(\n# geo_data=state_geo,\n# name='choropleth',\n# data=state_data,\n# columns=['State', 'Unemployment'],\n# key_on='feature.id',\n# fill_color='YlGn',\n# fill_opacity=0.7,\n# line_opacity=0.2,\n# legend_name='Unemployment Rate (%)'\n# )\n\n\n","repo_name":"nicholsonjohnc/promotion-optimization","sub_path":"src/choropleth_map.py","file_name":"choropleth_map.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"18253767566","text":"#!/usr/bin/python3\n\"\"\"\nPython script that takes in an argument and displays all values\nin the states table of hbtn_0e_0_usa where name matches the argument.\n\"\"\"\n\nfrom sys import argv\nimport MySQLdb\n\nif __name__ == '__main__':\n db = MySQLdb.connect(\n host=\"localhost\",\n port=3306,\n user=argv[1],\n passwd=argv[2],\n db=argv[3],\n charset=\"utf8\")\n state_arg = argv[4]\n cursor = db.cursor()\n sql_query = \"SELECT * FROM states WHERE name = '{}'\\\n ORDER BY states.id ASC\".format(state_arg)\n cursor.execute(sql_query)\n res_query_rows = cursor.fetchall()\n\n for row in res_query_rows:\n if row[1] == state_arg:\n print(row)\n cursor.close()\n db.close()\n","repo_name":"SFreire2022/holbertonschool-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/2-my_filter_states.py","file_name":"2-my_filter_states.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"28548007593","text":"from fastapi import APIRouter\nfrom .routes import flight_routes, user_routes\n\nrouter = APIRouter()\n\nrouter.include_router(\n flight_routes.router,\n prefix=\"/flights\",\n tags=[\"flights\"]\n)\nrouter.include_router(\n user_routes.router,\n prefix=\"/users\",\n tags=[\"users\"]\n)\n","repo_name":"MarkKirichev/Personal-Website-Mark-Kirichev","sub_path":"backend-python-fastapi/app/api/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"244104586","text":"class Solution(object):\n def minMoves(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n nums.sort()\n moves = 0\n for i in range(1,len(nums)):\n diff = moves + nums[i] - nums[i-1]\n nums[i] += moves\n moves += diff\n return moves\n\n\n\nsol = Solution()\nnums = [1,2,3]\nprint(sol.minMoves(nums))\n","repo_name":"lizyang95/leetcode","sub_path":"leetcode5/minMoves.py","file_name":"minMoves.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"22397244505","text":"from itertools import product\nimport numpy as np\n\n\ndef next_index_mapping():\n \"\"\"\n Args:\n - N/A\n\n Returns:\n - mapper: A dictionary of key-value pairs where each key corresponds\n to an index and its value is another dictionary. This dictionary contains\n key-value pairs, where the key is the added digit and value is the\n new index.\n \"\"\"\n # Get all binary strings in sorted manner\n binary_strings = [list(x) for x in list(product([0, 1], repeat=10))]\n\n # Define a helperfunction to find the \"next\" index\n def find_next(idx, i):\n \"\"\"Finds the index of the newly computed binary strings.\"\"\"\n s = binary_strings[idx].copy()\n s[i] = 1\n new_idx = binary_strings.index(s)\n return new_idx\n\n # Create a dictionary that maps each index to its next index (based on new digit)\n mapper = {}\n for idx in range(len(binary_strings)):\n mapper[idx] = {i: find_next(idx, i) for i in range(10)}\n\n return mapper\n\n\ndef p178(N):\n \"\"\"Calculates the number of step numbers up to (and including) N digits.\"\"\"\n # Use a pre-computed mapper dictionary to find next indices\n mapper = next_index_mapping()\n\n def f(idx, d):\n \"\"\"Finds the new index\"\"\"\n return mapper[idx][d]\n\n # Initialize cache\n D = np.zeros((N + 1, 10 + 1, 1024 + 1))\n\n # Dynamic programming scheme\n for n in range(1, N + 1):\n for l in range(10):\n for i in range(1024):\n if n == 1:\n # 1-digit numbers should correspond to their binary string\n # with the exception of 0\n if i == 0 and l != 0:\n D[n][l][f(i, l)] += 1\n else:\n pass\n else:\n if l == 0:\n D[n][l + 1][f(i, l + 1)] += D[n - 1][l][i]\n elif l == 9:\n D[n][l - 1][f(i, l - 1)] += D[n - 1][l][i]\n else:\n D[n][l + 1][f(i, l + 1)] += D[n - 1][l][i]\n D[n][l - 1][f(i, l - 1)] += D[n - 1][l][i]\n\n # Get the total count of numbers with idx 1023 (i.e. pandigital)\n total = 0\n for n in range(N + 1):\n for l in range(10):\n total += D[n][l][1023]\n return total\n\n\nif __name__ == \"__main__\":\n # assert(p178(10)==1)\n print(p178(40))\n","repo_name":"leonlan/projecteuler","sub_path":"python/p178.py","file_name":"p178.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"549207259","text":"import concurrent.futures\nimport os\nimport re\nimport sys\nfrom contextlib import contextmanager\nfrom typing import Iterable, Iterator, List, Optional, Set\n\nimport click\nfrom pygitguardian import GGClient\n\nfrom ggshield.core.cache import Cache\nfrom ggshield.core.config import Config\nfrom ggshield.core.constants import CPU_COUNT\nfrom ggshield.core.git_shell import get_list_commit_SHA, is_git_dir\nfrom ggshield.core.text_utils import STYLE, format_text\nfrom ggshield.core.types import IgnoredMatch\nfrom ggshield.core.utils import SupportedScanMode, handle_exception\nfrom ggshield.output import OutputHandler\nfrom ggshield.scan import Commit, ScanCollection\n\n\n@contextmanager\ndef cd(newdir: str) -> Iterator[None]:\n prevdir = os.getcwd()\n os.chdir(os.path.expanduser(newdir))\n try:\n yield\n finally:\n os.chdir(prevdir)\n\n\ndef scan_repo_path(\n client: GGClient,\n cache: Cache,\n output_handler: OutputHandler,\n config: Config,\n repo_path: str,\n scan_id: str,\n) -> int: # pragma: no cover\n try:\n with cd(repo_path):\n if not is_git_dir():\n raise click.ClickException(f\"{repo_path} is not a git repository\")\n\n return scan_commit_range(\n client=client,\n cache=cache,\n commit_list=get_list_commit_SHA(\"--all\"),\n output_handler=output_handler,\n verbose=config.verbose,\n exclusion_regexes=set(),\n matches_ignore=config.matches_ignore,\n all_policies=config.all_policies,\n scan_id=scan_id,\n banlisted_detectors=config.banlisted_detectors,\n )\n except Exception as error:\n return handle_exception(error, config.verbose)\n\n\ndef scan_commit(\n commit: Commit,\n client: GGClient,\n cache: Cache,\n verbose: bool,\n matches_ignore: Iterable[IgnoredMatch],\n all_policies: bool,\n banlisted_detectors: Optional[Set[str]] = None,\n) -> ScanCollection: # pragma: no cover\n results = commit.scan(\n client=client,\n cache=cache,\n matches_ignore=matches_ignore,\n all_policies=all_policies,\n mode_header=SupportedScanMode.REPO.value,\n banlisted_detectors=banlisted_detectors,\n )\n\n return ScanCollection(\n commit.sha or \"unknown\",\n type=\"commit\",\n results=results,\n optional_header=commit.optional_header,\n extra_info=commit.info._asdict(),\n )\n\n\ndef scan_commit_range(\n client: GGClient,\n cache: Cache,\n commit_list: List[str],\n output_handler: OutputHandler,\n verbose: bool,\n exclusion_regexes: Set[re.Pattern],\n matches_ignore: Iterable[IgnoredMatch],\n all_policies: bool,\n scan_id: str,\n banlisted_detectors: Optional[Set[str]] = None,\n) -> int: # pragma: no cover\n \"\"\"\n Scan every commit in a range.\n\n :param client: Public Scanning API client\n :param commit_list: List of commits sha to scan\n :param verbose: Display successfull scan's message\n \"\"\"\n return_code = 0\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=min(CPU_COUNT, 4)\n ) as executor:\n future_to_process = [\n executor.submit(\n scan_commit,\n Commit(sha, exclusion_regexes),\n client,\n cache,\n verbose,\n matches_ignore,\n all_policies,\n banlisted_detectors,\n )\n for sha in commit_list\n ]\n\n scans: List[ScanCollection] = []\n with click.progressbar(\n iterable=concurrent.futures.as_completed(future_to_process),\n length=len(future_to_process),\n label=format_text(\"Scanning Commits\", STYLE[\"progress\"]),\n file=sys.stderr,\n ) as completed_futures:\n for future in completed_futures:\n scans.append(future.result())\n\n return_code = output_handler.process_scan(\n ScanCollection(id=scan_id, type=\"commit-range\", scans=scans)\n )\n return return_code\n","repo_name":"pierrelalanne/ggshield","sub_path":"ggshield/scan/repo.py","file_name":"repo.py","file_ext":"py","file_size_in_byte":4100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"71641305992","text":"import numpy as np\nfrom heapq import heappop as pop\nfrom heapq import heappush as push\nfrom heapq import heapify\nimport random\n\n\ngraph = [\n [0, 3, 0, 3, 5],\n [3, 0, 5, 1, 0],\n [0, 5, 0, 2, 0],\n [3, 1, 2, 0, 1],\n [5, 0, 0, 1, 0],\n]\n\n# list of nodes in graph\nv = [1, 2, 3, 4, 5]\n\n# starting node\n# s = random.choice(v)\ns = 1\n\n# node keys\nk = [np.Inf for i in v]\nk[s - 1] = 0\n\n# previous nodes\npred = [0 for i in v]\n\n\n# adding nodes with corresponding keys to the priority queue\npq = []\nfor i in range(0, len(v)):\n push(pq, (k[i], v[i]))\n\n\n# list with nodes which are still in pq\nnodes_in_pq = v\n\n# as long as there are nodes in pq\nwhile nodes_in_pq:\n # pull the node with the lowest value from \"pq\"\n u_node = pop(pq)\n\n # remove an \"u_node\" element from the list of remaining elements\n nodes_in_pq.remove(u_node[1])\n\n # iteration for each element in the 'u_node' row in graph\n for i in range(0, len(graph[u_node[1] - 1])):\n # if there is a conection between 'u_node' and 'i'-node then\n if graph[u_node[1] - 1][i] > 0:\n #'v_node' is a node which has a conection with 'u_node'\n v_node = i + 1\n # if 'v_node' is still in pq then\n if v_node in nodes_in_pq:\n # assign the weight of the conection to the weight variable\n weight = graph[u_node[1] - 1][i]\n # if weight of the conection is lower than key of the node then\n if weight < k[v_node - 1]:\n # change the predecessor value and the key value\n pred[v_node - 1] = u_node[1]\n k[v_node - 1] = weight\n\n # modify value of the v_node key in pq\n # getting an index of the v_node by [nodes_in_pq.index(v_node)]\n pq[nodes_in_pq.index(v_node)] = (k[v_node - 1], v_node)\n heapify(pq)\n\nprint(f\"Start in node: {s}\")\nprint(f\"pred: {pred}\")\nprint(f\"k: {k}\")\n","repo_name":"kacpermoll/algorithms-and-data-structure","sub_path":"III/Prima/Prima.py","file_name":"Prima.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"39336214935","text":"import asyncio\nimport os\nimport re\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List\n\nfrom aio_pika import DeliveryMode, Message, connect\nfrom aio_pika.abc import AbstractIncomingMessage\nfrom dotenv import load_dotenv\nfrom sqlalchemy import Column, DateTime, Integer, String\nfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine\nfrom sqlalchemy.orm import declarative_base, sessionmaker\n\nload_dotenv()\nRABBITMQ_USERNAME = os.getenv(\"RABBITMQ_USERNAME\")\nRABBITMQ_PASSWORD = os.getenv(\"RABBITMQ_PASSWORD\")\nPOSTGRES_USER = os.getenv(\"POSTGRES_USER\")\nPOSTGRES_PASSWORD = os.getenv(\"POSTGRES_PASSWORD\")\n\nBase = declarative_base()\nengine = create_async_engine(\n f\"postgresql+asyncpg://{POSTGRES_USER}:{POSTGRES_PASSWORD}@0.0.0.0/twitch\",\n echo=False,\n)\nasync_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)\n\n\nasync def create_db():\n # async with engine.begin() as conn:\n # await conn.run_sync(Base.metadata.drop_all)\n async with engine.begin() as conn:\n await conn.run_sync(Base.metadata.create_all)\n\n\nclass PrivateMessage(Base):\n __tablename__ = \"chat\"\n\n id = Column(Integer, primary_key=True)\n message = Column(String)\n timestamp = Column(DateTime)\n channel = Column(String)\n nick = Column(String)\n\n # required in order to access columns with server defaults\n # or SQL expression defaults, subsequent to a flush, without\n # triggering an expired load\n __mapper_args__ = {\"eager_defaults\": True}\n\n\nasync def push_to_db(data):\n # print(data)\n # tweet = PrivateMessage(\n # timestamp=data[\"timestamp\"],\n # channel=data[\"channel\"],\n # nick=data[\"username\"],\n # message=data[\"message\"],\n # )\n list_private_messages = [PrivateMessage(**d) for d in data]\n print(\"pushing to db\")\n async with async_session() as session:\n async with session.begin():\n session.add_all(list_private_messages)\n await session.commit()\n\n\n@dataclass\nclass SubscriberInfo:\n msg_per_sec: int = 0\n channels: List = field(default_factory=list)\n\n\n@dataclass\nclass Orchestrator:\n subscribers: Dict[str, Dict] = field(default_factory=dict)\n channels_monitored: List = field(default_factory=list)\n channels_new: List = field(default_factory=list)\n last_message: Dict = field(default_factory=dict)\n buffer_data: List = field(default_factory=list)\n\n async def on_message(self, message: AbstractIncomingMessage) -> None:\n async with message.process():\n # print(f\" Message body is: {message.body!r}\")\n # print(f\" Message body is: {message.headers['x-id']}\")\n # print(f\" Message body is: {message.timestamp}\")\n messages = message.body.split(b\"\\r\\n\")\n for msg in messages:\n if msg.startswith(b\"SUBSCRIBE\"):\n print(\"got new subscriber\")\n id_subscribers = str(msg.split(b\" \")[1], \"utf-8\")\n self.subscribers[id_subscribers] = SubscriberInfo()\n msg_utf8 = msg.decode()\n is_privmsg = re.match(\n r\"^:[a-zA-Z0-9_]+\\![a-zA-Z0-9_]+@[a-zA-Z0-9_]+\"\n r\"\\.tmi\\.twitch\\.tv \"\n r\"PRIVMSG #[a-zA-Z0-9_]+ :.+$\",\n msg_utf8,\n )\n if is_privmsg:\n data = {\n \"channel\": re.findall(\n r\"^:.+![a-zA-Z0-9_]+\"\n r\"@[a-zA-Z0-9_]+\"\n r\".+ \"\n r\"PRIVMSG (.*?) :\",\n msg_utf8,\n )[0],\n \"timestamp\": message.timestamp,\n \"nick\": re.findall(r\"^:([a-zA-Z0-9_]+)!\", msg_utf8)[0],\n \"message\": re.findall(\n r\"PRIVMSG #[a-zA-Z0-9_]+ :(.+)$\", msg_utf8\n )[0],\n }\n self.buffer_data.append(data)\n if len(self.buffer_data) > 1500:\n await push_to_db(self.buffer_data)\n self.buffer_data = []\n\n async def consumer(self) -> None:\n connection = await connect(\n f\"amqp://{RABBITMQ_USERNAME}:{RABBITMQ_PASSWORD}@localhost\"\n )\n\n async with connection:\n # Creating a channel\n channel = await connection.channel()\n await channel.set_qos(prefetch_count=1)\n\n # Declaring queue\n queue = await channel.declare_queue(\n \"task_queue\",\n durable=False,\n # durable=True,\n )\n\n # Start listening the queue with name 'task_queue'\n await queue.consume(self.on_message)\n\n print(\" [*] Waiting for messages. To exit press CTRL+C\")\n await asyncio.Future()\n\n async def producer(self) -> None:\n # Perform connection\n connection = await connect(\n f\"amqp://{RABBITMQ_USERNAME}:{RABBITMQ_PASSWORD}@localhost\"\n )\n async with connection:\n # Creating a channel\n channel = await connection.channel()\n message = Message(\n b\"Hello World!\",\n delivery_mode=DeliveryMode.PERSISTENT,\n )\n\n # Sending the message\n for sub in self.subscribers:\n await channel.default_exchange.publish(\n message,\n routing_key=sub,\n )\n\n print(f\" [x] Sent {message!r}\")\n print(f\" [x] Sent {message.body!r}\")\n\n async def infinite_producer(self) -> None:\n while True:\n if self.subscribers:\n print(\"producing\")\n try:\n await self.producer()\n except Exception as exp:\n raise exp\n\n await asyncio.sleep(10)\n\n def run(self):\n loop = asyncio.get_event_loop()\n loop.run_until_complete(create_db())\n # await push_to_db({\"channel\": \"test\", \"username\": \"test\", \"message\": \"test\"})\n # loop.create_task(\n # push_to_db({\"channel\": \"test\", \"username\": \"test\", \"message\": \"test\"})\n # )\n # loop.create_task(self.consumer())\n # loop.create_task(self._push_to_db())\n # loop.create_task(self.infinite_producer())\n cors = asyncio.gather(self.consumer())\n loop.run_until_complete(cors)\n # loop.run_forever()\n print(\"done\")\n\n\nif __name__ == \"__main__\":\n orchestrator = Orchestrator()\n orchestrator.run()\n","repo_name":"adrz/twitch-chat-scrapper","sub_path":"orchestrator.py","file_name":"orchestrator.py","file_ext":"py","file_size_in_byte":6671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"2364427146","text":"import logging\n\nfrom django.dispatch import Signal, receiver\nfrom django.db import models\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes.fields import GenericForeignKey\n\nfrom django.conf import settings\n\nlogger = logging.getLogger(__name__)\n\nclass Event(models.Model):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)\n name = models.CharField(max_length=100)\n timestamp = models.DateTimeField(auto_now_add=True)\n note = models.CharField(max_length=255, default='')\n related_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True)\n related_object_id = models.PositiveIntegerField(null=True, blank=True)\n related_object = GenericForeignKey('related_content_type', 'related_object_id')\n\n class Meta:\n ordering = ('-timestamp',)\n get_latest_by = 'timestamp'\n app_label = 'tracking'\n\n def __str__(self):\n return \"%s at %s\" % ( self.name, self.timestamp )\n\n @classmethod\n def events_related_to(cls, related_object):\n related_ct = ContentType.objects.get_for_model(related_object)\n related_pk = related_object.id\n\n return Event.objects.filter(related_content_type=related_ct,\n related_object_id=related_pk)\n\n\nevent_logged = Signal(providing_args=[\"event\"])\n\n@receiver(models.signals.post_save, sender=Event)\ndef event_handler(sender, instance, created=False, **kwargs):\n if instance is not None and created:\n event_logged.send_robust(sender=sender, event=instance)\n\n# logging callback\n@receiver(event_logged)\ndef event_logger(sender, event=None, **kwargs):\n if event is not None:\n extra = dict(note=event.note, timestamp=event.timestamp,\n user=None, related_object=None, request=None)\n msg = ['%s event created' % event.name]\n if event.user is not None:\n extra['user'] = event.user.username\n msg.append('for user %s' % event.user.username)\n if event.related_object is not None:\n extra['related_object'] = event.related_object\n msg.append('connected to %r' % event.related_object)\n if hasattr(event, 'request') and event.request is not None:\n extra['request'] = event.request\n msg.append('@ %s' % event.request.path)\n logger.info(' '.join(msg), extra=extra)\n","repo_name":"tl-its-umich-edu/student_explorer","sub_path":"tracking/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"27"} +{"seq_id":"23290558535","text":"# -*- coding: utf-8 -*-\nimport json\n\nfrom django.core.mail import send_mail\nfrom django.conf import settings\n\nfrom utils.redis_func import Client as RedisClient\n\n\n# Custom SMS Provider\nfrom tencentcloud.common import credential\nfrom tencentcloud.common.exception.tencent_cloud_sdk_exception import (\n TencentCloudSDKException,\n)\nfrom tencentcloud.common.profile.client_profile import ClientProfile\nfrom tencentcloud.common.profile.http_profile import HttpProfile\nfrom tencentcloud.sms.v20190711 import models, sms_client\n\n\ndef send_sms(phone_number, code, type):\n \"\"\"Since Django does not currently have a good SMS sending plugin,\n if you need to use the SMS authentication function,\n you need to use the SMS provider's SDK to rewrite the send_sms function to achieve related functions\n\n Args:\n phone_number (str): phone number\n code (str): verify code (could be random string or number)\n type (str): sms template type [register, update, reset]\n\n Returns:\n bool: True if send success, False if send failed\n \"\"\"\n\n cred = credential.Credential(settings.SMS_SECRET_ID, settings.SMS_SECRET_KEY)\n httpProfile = HttpProfile()\n httpProfile.reqMethod = \"POST\"\n httpProfile.reqTimeout = 30\n httpProfile.endpoint = settings.SMS_ENDPOINT\n clientProfile = ClientProfile()\n clientProfile.signMethod = \"TC3-HMAC-SHA256\"\n clientProfile.language = \"en-US\"\n clientProfile.httpProfile = httpProfile\n client = sms_client.SmsClient(cred, \"ap-guangzhou\", clientProfile)\n req = models.SendSmsRequest()\n req.SmsSdkAppid = settings.SMS_SDK_APPID\n req.Sign = settings.SMS_SIGN\n req.ExtendCode = \"\"\n req.SessionContext = \"\"\n req.SenderId = \"\"\n req.PhoneNumberSet = [\"+86\" + phone_number]\n req.TemplateID = settings.SMS_TEMPLATES[type]\n req.TemplateParamSet = [code]\n resp = client.SendSms(req)\n ret = json.loads(resp.to_json_string(indent=2))\n return ret\n\n\ndef send_email(email, code, type):\n TYPES = {\n \"register\": \"{{cookiecutter.project_name_cn}}注册\",\n \"update\": \"{{cookiecutter.project_name_cn}}邮箱绑定\",\n \"reset\": \"{{cookiecutter.project_name_cn}}密码重置\",\n }\n title = TYPES[type]\n content = f\"您的验证码为{code}。有效期为10分钟,请尽快输入!\"\n ret = send_mail(title, content, settings.EMAIL_FROM, [email], fail_silently=True)\n return ret\n\n\ndef set_verification_code(type, verification, code):\n \"\"\"Set verify code to redis\n\n Args:\n type (str): verify code type [register, update, reset]\n verification (str): verification\n code (str): verify code (could be random string or number)\n \"\"\"\n r = RedisClient()\n r.set(f\"{type}_{verification}\", code)\n","repo_name":"jokerwho/cookiecutter-drf","sub_path":"{{cookiecutter.project_name}}/utils/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"7300197858","text":"import os\n\nfrom multiprocessing import Process\n\ndef doubler(number):\n\n result = number * 2\n proc = os.getpid()\n\n print(f\"{number} doubled to {result} by prrcess id: {proc}\")\n\n\nif __name__ == '__main__':\n numbers = [5,10,15,20,25]\n procs = []\n\n for index, number in enumerate(numbers):\n\n proc = Process(target=doubler, args=(number,))\n procs.append(proc)\n proc.start()\n\n for proc in procs:\n proc.join()","repo_name":"DONGYEONKANG/Python","sub_path":"multiprocessing/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"32776434736","text":"from ds.vortex.core import baseNode\nfrom ds.vortex.core import plug as plugs\n\n\nclass IfNode(baseNode.BaseNode):\n def __init__(self, name):\n \"\"\"\n :param name: str, the name of the node\n \"\"\"\n baseNode.BaseNode.__init__(self, name)\n\n def initialize(self):\n baseNode.BaseNode.initialize(self)\n self.outputPlug_ = self.addPlug(self.outputPlug_, clean=True)\n self.conditionPlug_ = plugs.InputPlug(\"condition\", self, value=True)\n self.ifTruePlug_ = plugs.InputPlug(\"ifTrue\", self, value=0)\n self.ifFalsePlug = plugs.InputPlug(\"ifFalse\", self, value=0)\n\n self.addPlug(self.conditionPlug_, clean=True)\n self.addPlug(self.ifTruePlug_, clean=True)\n self.addPlug(self.ifFalsePlug, clean=True)\n\n self.plugAffects(self.conditionPlug_, self.outputPlug_)\n self.plugAffects(self.ifTruePlug_, self.outputPlug_)\n self.plugAffects(self.ifFalsePlug, self.outputPlug_)\n\n def compute(self, requestPlug):\n baseNode.BaseNode.compute(self, requestPlug=requestPlug)\n if self.conditionPlug_.value:\n result = self.ifTruePlug_.value\n else:\n result = self.ifFalsePlug.value\n\n requestPlug.value = result\n requestPlug.dirty = False\n return result\n\n\ndef getNode():\n \"\"\"General function that returns our node, used to get create our node via Ui etc\n :return: Node instance\n \"\"\"\n return IfNode\n","repo_name":"dsparrow27/vortex","sub_path":"src/ds/vortex/nodes/comparison/ifCondition.py","file_name":"ifCondition.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"37555410729","text":"\r\n\r\n\r\nstr = 'The quick Brow Fox'\r\n\r\nupper = 0\r\nlower = 0\r\nfor i in str:\r\n if i.isupper():\r\n upper = upper+1\r\n else:\r\n lower = lower+1\r\n \r\nprint(\"No.of upper case character:\",upper)\r\nprint(\"No.of lower case character:\",lower)\r\n","repo_name":"J077969n/assignment-3_upper","sub_path":"no. of upper.py","file_name":"no. of upper.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"1089415751","text":"from gtts import gTTS\nfrom pydub import AudioSegment\nfrom pydub.playback import play\nimport time, os\n\ncharlist = ['活潑', '搞怪', '沉穩', '傲嬌', '溫柔', '欠揍']\nfolderlist = ['active', 'funny', 'mature', 'tsundere', 'gentle', 'naughty']\ndef contentToAudio(resp, target, name):\n try:\n start = time.time()\n tts = gTTS(resp, lang='zh-TW', slow=False)\n tts.save(\"/home/pi/Music/resp.mp3\")\n end = time.time()\n print('tts: ', end-start)\n \n start = time.time()\n sound = AudioSegment.from_mp3(\"/home/pi/Music/resp.mp3\")\n targetFile = \"/home/pi/Music/common_resp/\" + target + \"/\" + name + \".wav\"\n sound.export(targetFile, format=\"wav\")\n end = time.time()\n print('export: ', end-start)\n except Exception as ex:\n print(ex)\n \ndef combine(char, content, pattern):\n if pattern.find('f') != -1:\n if char == '活潑':\n content = '好滴,' + content\n elif char == '搞怪':\n content = '好喔,' + content\n elif char == '沉穩':\n content = '/' + content\n elif char == '傲嬌':\n content = '恨/,' + content\n elif char == '溫柔':\n content = '豪/,' + content\n elif char == '欠揍':\n content = '好哇,' + content\n if pattern.find('q') != -1:\n if char == '活潑':\n content += '鴨'\n elif char == '搞怪':\n content += '捏'\n elif char == '沉穩':\n content += '/'\n elif char == '傲嬌':\n content += '軋'\n elif char == '溫柔':\n content += 'ㄋ'\n elif char == '欠揍':\n content += '/'\n elif pattern.find('r') != -1:\n if char == '活潑':\n content += '優'\n elif char == '搞怪':\n content += '撸'\n elif char == '沉穩':\n content += '/'\n elif char == '傲嬌':\n content += 'ho'\n elif char == '溫柔':\n content += '/'\n elif char == '欠揍':\n content += '呵'\n return content\n\ndef playAudio(filename):\n cmd = 'omxplayer -o local /home/pi/Music/common_resp/active/' + filename + '.wav &'\n os.system(cmd)\n \nif __name__ == '__main__':\n content = '我沒聽懂你想要我推薦什麼,但我覺得多喝水挺好'\n pattern = 'r'\n name = 'nofood'\n for i in range(6):\n resp = combine(charlist[i], content, pattern)\n contentToAudio(resp, folderlist[i], name)\n \n playAudio(name)","repo_name":"D0610960/Nemo","sub_path":"Main/Project/tmp/common_resp.py","file_name":"common_resp.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"20946024322","text":"_base_ = ['../_base_/models/retinanet_r50_fpn.py', '../common/ms_3x_coco.py']\n# optimizer\nmodel = dict(\n backbone=dict(\n type='ResNeXt',\n depth=101,\n groups=64,\n base_width=4,\n init_cfg=dict(\n type='Pretrained', checkpoint='open-mmlab://resnext101_64x4d')))\noptim_wrapper = dict(optimizer=dict(type='SGD', lr=0.01))\n","repo_name":"open-mmlab/mmdetection","sub_path":"configs/retinanet/retinanet_x101-64x4d_fpn_ms-640-800-3x_coco.py","file_name":"retinanet_x101-64x4d_fpn_ms-640-800-3x_coco.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":26167,"dataset":"github-code","pt":"20"} +{"seq_id":"4198361312","text":"import nibabel as nib\nimport scipy as sp\nimport glob\nimport numpy as np\nimport h5py\nimport os\nfrom neurosynth.base.dataset import Dataset\n\nclass AutoExpandingArray:\n\tdef __init__(self):\n\t\tself.data = np.zeros((2,100))\n\t\tself.capacity = 100\n\t\tself.size = 0\n\n\tdef update(self, row):\n\t\tfor r in row:\n\t\t\tself.add(r)\n\n\tdef add(self, x, rowidx):\n\t\tif (self.size + x.shape[0]) >= self.capacity:\n\t\t\tself.capacity = max((self.size + x.shape[0]), self.capacity*4)\n\t\t\tnewdata = np.zeros((2,self.capacity,))\n\t\t\tnewdata[:,:self.size] = self.data[:,:self.size]\n\t\t\tself.data = newdata\n\t\ttempdata = sp.append(sp.vstack(x).T,sp.ones((1,x.shape[0]))*rowidx,axis=0)\n\t\tself.data[:,self.size:self.size+x.shape[0]] = tempdata\n\t\tself.size += x.shape[0]\n\n\tdef finalize(self):\n\t\tdata = self.data[:,:self.size]\n\t\treturn data\n\ndef numpy_voxel_feature_matrix(dataset, image_folder):\n\tfeature_list = dataset.get_feature_names()\n\tnum_voxel = dataset.volume.full.shape[0]\n\tnum_features = len(feature_list)\n\tvoxel_by_features = sp.zeros((num_voxel, num_features), dtype=sp.int16)\n\tfor (i,feature) in enumerate(feature_list):\n\t\timage_path = image_folder + feature + '_pFgA_z.nii.gz'\n\t\timage = nib.load(image_path)\n\t\tvoxel_by_features[:,i] = image.get_data().ravel()\n\treturn voxel_by_features\n\ndef numpy_voxel_activity_matrix(dataset, image_folder):\n\timage_list = sorted(glob.glob(image_folder + 'rr_*.nii'))\n\tnum_voxel = dataset.volume.full.shape[0]\n\tnum_scans = len(image_list)\n\tvoxel_activity_mat = sp.zeros((num_voxel, num_scans), dtype=sp.int16)\n\tfor (i,image_path) in enumerate(image_list):\n\t\timage = nib.load(image_path)\n\t\tvoxel_activity_mat[:,i] = image.get_data().ravel()\n\treturn voxel_activity_mat\n\ndef add_h5py_voxel_activity_matrix(h5py_file, dataset, image_folder, dset_name):\n\timage_list = sorted(glob.glob(image_folder + 'rr_*.nii'))\n\tnum_voxel = dataset.volume.full.shape[0]\n\tnum_scans = len(image_list)\n\tdset = h5py_file.create_dataset(dset_name, (num_voxel, num_scans), dtype=np.int16)\n\tfor (i,image_path) in enumerate(image_list):\n\t\timage = nib.load(image_path)\n\t\tdset[:,i] = image.get_data().ravel()\n\t\t\ndef add_h5py_voxel_feature_matrix(h5py_file, dataset, image_folder, dset_name):\n\tfeature_list = sorted(dataset.get_feature_names())\n\tnum_voxel = dataset.volume.full.shape[0]\n\tnum_features = len(feature_list)\n\tdset = h5py_file.create_dataset(dset_name, (num_voxel, num_features), dtype=np.int16)\n\tfor (i,feature) in enumerate(feature_list):\n\t\timage_path = image_folder + feature + '_pFgA_z.nii.gz'\n\t\timage = nib.load(image_path)\n\t\tdset[:,i] = image.get_data().ravel()\n\t\ndataset_loc = 'data/old/neurosynth-dataset.pkl'\nneurosynth_image_loc = 'data/old/results/'\nfMRI_base_dir = '/home/achim/masterprojekt/data/functional_realigned/'\ndataset = Dataset.load(dataset_loc)\n\n# load matrices in hdf5 database\nwith h5py.File('neurodata.hdf5') as f:\n\t# add voxel feature matrix (from neurosynth)\n\tadd_h5py_voxel_feature_matrix(f, dataset, neurosynth_image_loc, 'nsynth_mat')\n\tprint('neurosynth data added.')\n\n\t# add voxel activity matrices (from fMRI scans)\n\tsubject_folders = sorted(os.listdir(fMRI_base_dir))\n\tfor (i,folder) in enumerate(subject_folders):\n\t\timage_folder_path = fMRI_base_dir + folder + '/'\n\t\tadd_h5py_voxel_activity_matrix(f, dataset, image_folder_path, 's_' + str(i+1))\n\t\tprint(folder + ' added.')\n\n#with h5py.File('neurodata.hdf5', 'a') as f:\n#\tkeys = sorted(os.listdir(fMRI_base_dir))\n#\tfor (i,key) in enumerate(keys):\n#\t\tdset = f[key]\n#\t\tnonzero_entries = AutoExpandingArray()\n\t\t\n#a = AutoExpandingArray()\n#b = sp.rand(80)\n#a.add(b,1)\n#b = sp.rand(80)\n#a.add(b,2)\t\n\n\n","repo_name":"acley/neuro-data-matrix-factorization","sub_path":"neuromatrices.py","file_name":"neuromatrices.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"18179197844","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 12 23:49:18 2023\n\n@author: cesaralba\n\"\"\"\n\nfrom textPreprocessor import TextPreprocessor\nfrom collections import Counter\nimport pandas as pd\n\nclass InvertedIndex:\n def __init__(self):\n self.index = dict()\n self.textPreprocessor = TextPreprocessor(meaning_method = 'stemming')\n self.document_count = 0\n self.average_document_length=0\n self.word_count = 0\n self.term_freq = dict()\n \n def generateIndex(self, documents):\n # THe expected oobject is a list of tuples that (doc-id , text). Each tuple contains the document id and the text\n self.document_count = len(documents)\n for doc in documents:\n id = doc[0]\n # Prepare the text and return the list of tokens\n tokens =self.textPreprocessor.prepocess(doc[1])\n # Update the word count\n self.word_count += len(tokens)\n # Count the frequency of each term in the document\n token_freq = Counter(tokens)\n #Add terms to the index. If it's a new term it will the term to the dictionary and the document.\n #If term already exist it will add the document to the posting list\n #Posting list contains id of document, freq onf the term and document length\n for token in token_freq:\n if token in self.index:\n self.index[token][id] = (token_freq[token], len(tokens))\n # Count the total freq of the indext term in the corpus\n self.term_freq[token] += token_freq[token]\n else:\n posting = dict()\n posting[id]= (token_freq[token], len(tokens))\n self.index[token] = posting\n self.term_freq[token] = token_freq[token]\n \n #Calculates the average document length\n self.average_document_length = self.word_count / self.document_count\n \n #After the index is genereated the elements and the posting list need to be sorted\n self.index = dict(sorted(self.index.items()))\n \n def documentMatrixForQuery(self, query):\n query_terms = self.textPreprocessor.prepocess(query) # Tokenize the query\n query_terms = self.textPreprocessor.uniqueTerms(query_terms)\n\n df = pd.DataFrame(columns = query_terms) #Creates an empty dataframe with the terms as columns\n\n for term in query_terms:\n if term in self.index: # If its an index term get the posting list\n documents = self.index.get(term)\n documents = documents.keys()\n for d in documents:\n if not d in df.index: # If document doesn't in matrix add the document with 0 for all terms\n df.loc[d] = [0] * len(query_terms)\n df.at[d,term] = 1 # Set 1 for the document/term\n \n return df\n \n \n\n \n \n \n \n \n","repo_name":"cesar-arturo/search-engine","sub_path":"src/invertedIndex.py","file_name":"invertedIndex.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31551588824","text":"import numpy\nimport matplotlib.pylab as plt\nimport math\n\n\ndef f(x):\n return 3.0 * x[0] ** 2 + 2.0 * x[0] * x[1] + x[1] ** 2 - 4.0 * x[0] + 5.0 * x[1]\n\n\ndef grad(x):\n return numpy.array([6.0 * x[0] + 2.0 * x[1] - 4.0,\n 2.0 * x[0] + 2.0 * x[1] + 5.0])\n\n\nx1 = numpy.linspace(-25, 25, 400)\nx2 = numpy.linspace(-25, 25, 400)\nX, Y = numpy.meshgrid(x1, x2)\nz = f([X, Y])\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nplt.pcolormesh(X, Y, z, cmap='Blues')\nplt.colorbar()\nplt.contour(X, Y, z, colors=\"black\", alpha=0.5, linestyles=\"dotted\", linewidth=0.5)\n\n\ndef line_search_interpolation(g, h, a0, p):\n deriv = numpy.dot(g, h)\n\n e0 = f(p)\n print(\"%12.8f %12.8f %12.8f\" % (e0, p[0], p[1]))\n\n e1 = f(p + a0 * h)\n p1 = p + a0 * h\n print(\"%12.8f %12.8f %12.8f %12.8f\" % (e1, p1[0], p1[1], a0))\n\n if e1 < e0 + 1e-4 * a0 * deriv:\n return a0\n\n a1 = -deriv * a0 * a0 / (2.0 * (e1 - e0 - deriv * a0))\n e2 = f(p + a1 * h)\n p2 = p + a1 * h\n print(\"%12.8f %12.8f %12.8f %12.8f\" % (e2, p2[0], p2[1], a1))\n\n if e2 < e0 + 1e-4 * a1 * deriv:\n return a1\n\n a = 1.0 / (a0 * a0 * a1 * a1 * (a1 - a0)) * (a0 * a0 * (e2 - e0 - deriv * a1) - a1 * a1 * (e1 - e0 - deriv * a0))\n b = 1.0 / (a0 * a0 * a1 * a1 * (a1 - a0)) * (\n -a0 * a0 * a0 * (e2 - e0 - deriv * a1) + a1 * a1 * a1 * (e1 - e0 - deriv * a0))\n a2 = -b + math.sqrt(b * b - 3.0 * a * deriv) / (3.0 * a)\n if a2 < 0:\n a2 = a1 / 2.0\n e3 = f(p + a2 * h)\n p3 = p + a2 * h\n\n print(\"%12.8f %12.8f %12.8f %12.8f\" % (e3, p3[0], p3[1], a2))\n\n if e3 < e0 + 1e-4 * a2 * deriv:\n return a2\n\n return 0.0\n\n\ndef conjugate_gradient(p, color):\n iter = 0\n g = grad(p)\n h = -g / numpy.linalg.norm(g)\n eold = f(p)\n pold = numpy.copy(p)\n maxlinesearch = 2.0\n\n while (iter < 100):\n a = line_search_interpolation(g, h, maxlinesearch, p)\n mp = p + maxlinesearch * h\n\n g1 = grad(p + a * h)\n angle = math.acos(numpy.dot(-g1, h) / (numpy.linalg.norm(g1) * numpy.linalg.norm(h)))\n print(\"%12.8f\" % angle)\n\n p += a * h\n\n enew = f(p)\n dif = math.fabs(enew - eold)\n if dif < 1e-4:\n print(\"Done\")\n break\n\n eold = enew\n\n if angle > (math.pi / 4):\n print(\"Angle larger than 45 deg, perform conjugate gradient step\")\n\n oldg = numpy.copy(g)\n g = grad(p)\n beta = numpy.dot(g, g - oldg) / numpy.dot(oldg, oldg)\n h = -g + beta * h\n\n plt.plot([pold[0], p[0]], [pold[1], p[1]], linestyle=\"dashed\", linewidth=2, color=color)\n\n pold = numpy.copy(p)\n\n iter += 1\n\n\nconjugate_gradient([20, 20], 'red')\nconjugate_gradient([-20, 20], 'green')\nconjugate_gradient([-20, -20], 'blue')\nconjugate_gradient([20, -20], 'black')\n\nplt.show()\n","repo_name":"rkhomenko/maga","sub_path":"sem01/data-proc/optimization/minimize.py","file_name":"minimize.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"31393658923","text":"import airsim\nimport sys\nimport math\nimport numpy as np\n\n\nclass lidar:\n def __init__(self):\n self.client = airsim.MultirotorClient()\n self.client.confirmConnection()\n self.client.enableApiControl(True)\n\n def checkData(self):\n data = self.client.getLidarData()\n measurements = data.point_cloud\n return measurements\n\n\nif __name__ == '__main__':\n sensor = lidar()\n while True:\n m = sensor.checkData()\n region = len(m)/4\n\n print(np.max(m))\n if np.max(m) < 4:\n print(\"---STOP---\")\n sensor.client.hoverAsync()\n #if measurements.x_val > 3:\n #sensor.client.hoverAsync()\n","repo_name":"Sabrin0/DroneRescueNav","sub_path":"PythonAPI/ObstacleAvoidance/lidar.py","file_name":"lidar.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"9054018438","text":"## \n# @file equation.py\n# @brief the Equation class for the printingCalc project\n# @details This file contains the Equation class, which is used to store the equation its result and create the equation in the GUI\n# @author Jack Duignan (JackpDuignan@gmail.com)\n\nimport tkinter as tk\nfrom tkinter import ttk\nfrom typing import Any\n\n## @class Equation\n# @brief Stores the equation and its result and contains modules to create the equation in the GUI\nclass Equation():\n ## @brief The constructor for the Equation class\n # @param self The object pointer\n # @param equation The equation string to store\n def __init__(self, equation: str):\n self.equation_str = equation\n self.result = self.__find_result()\n\n ## @brief Print the equation and its result in a readable format\n # @param self The object pointer\n def __str__(self):\n return self.equation_str + \" = \" + str(self.result)\n \n ## @brief Find the result of the equation\n # @param self The object pointer\n # @return The result of the equation None if the equation is invalid\n def __find_result(self):\n try:\n result = eval(self.equation_str)\n except:\n result = None\n \n return result\n \n ## @brief Update the equation in the class\n # @param self The object pointer\n # @param equation The new equation string\n def update_equation(self, equation: str):\n self.equation_str = equation\n self.result = self.__find_result()\n \n ## @brief Delete the equation from the list\n # @param self The object pointer\n # @param event The event that called the function\n def delete_equation(self, event: tk.Event = None):\n self.frm_equation.destroy() # Remove the equation from the GUI\n \n if self.deleteFunction != None:\n self.deleteFunction(self) # Remove the equation from the list\n\n ## @brief Creates the equation in the GUI\n # @param self The object pointer\n # @param master The master widget to place the equation in\n # @param row The row to place the equation in\n # @param deleteFunction The function to call when an equation is deleted (To remove the equation from the list)\n # @param column The column to place the equation in default=0\n # @param sticky The sticky value for the equation default=\"sew\" (bottom)\n def create_equation(self, master: tk.Widget, row: int, deleteFunction = None, column: int = 0, sticky: str = \"sew\"):\n # Create the equation frame\n self.frm_equation = tk.Frame(master)\n self.frm_equation.columnconfigure(0, weight=1)\n self.frm_equation.grid(row=row, column=column, sticky=sticky)\n\n self.lbl_equation = ttk.Label(self.frm_equation, text=self.equation_str, anchor=\"w\")\n self.lbl_equation.grid(row=0, column=0, sticky=\"new\")\n self.lbl_answer = ttk.Label(self.frm_equation, text=\"=\"+str(self.result), anchor=\"w\")\n self.lbl_answer.grid(row=1, column=0, sticky=\"new\")\n \n self.btn_delete = ttk.Button(self.frm_equation, text=\"x\", width=2, command=self.delete_equation)\n self.btn_delete.grid(row=0, column=1, rowspan=2, padx=10)\n\n # Set the delete function\n self.deleteFunction = deleteFunction\n\n\nif __name__ == \"__main__\":\n equation1 = Equation(\"2+2\")\n print(equation1)\n equation1.update_equation(\"2+3\")\n print(equation1)\n\n equation1.create_equation(tk.Tk(), 0)\n tk.mainloop() # 2+3 \\n =5\n","repo_name":"jaxsonpd/PrintingCalc","sub_path":"equation.py","file_name":"equation.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"14139261777","text":"from Data_Class import T_data, DataSet, loadData\nfrom pythonds import Stack\nclass Node:\n def __init__(self, dataset , attrset, basis = None, name = None, leaf=False, label=None):\n self.dataset = dataset\n self.attrset = attrset\n self.leaf = leaf\n self.basis = basis\n self.name = name\n self.label = label\n self.child = dict()\n def set_as_leaf(self,label):\n self.leaf = True\n self.label = label\n def recovery(self):\n self.leaf = False\n self.label = None\n def set_name(self, name):\n self.name = name\n def set_basis(self, basis):\n self.basis = basis \n def set_child(self, node, feature):\n self.child[feature] = node\n\nclass TestDataError(ValueError):\n pass\n\n#类:决策树分类器\nclass DesicionTreeClassifier:\n def __init__(self, dataset, attrset, critertion=\"entropy\"):\n \"\"\"criterion代表分类准则,有entropy和gini两个选项\"\"\"\n self.critertion = critertion\n self.root = Node(dataset, attrset, name='task')\n \n @staticmethod\n def best_label(node):\n dataset = node.dataset\n n = 0\n b_label = None\n for x in dataset.labels:\n if dataset.labels[x] > n:\n b_label = x\n n = dataset.labels[x]\n return b_label\n\n def best_split(self, node):\n dataset = node.dataset\n attrset = node.attrset\n if self.critertion == \"entropy\":\n entropy = 0\n av, division = None, None\n for attr in attrset:\n infor_gain, Dv = dataset.info_gain(attr)\n if infor_gain > entropy:\n entropy = infor_gain\n av = attr\n division = Dv\n return av, entropy, division\n elif self.critertion == \"gini\":\n gini_index = 1\n av, division = None, None\n for attr in attrset:\n gini, Dv = dataset.gini_index(attr)\n if gini < gini_index:\n gini_index = gini\n av = attr\n division = Dv\n return av, gini_index, division\n \n def generateTree(self, pruning='un', testData=None):\n \"\"\"pruning 有 un pre post 三个选项,若需要剪枝,需有testData\"\"\" \n def same_in_A(dataset,attrset):\n d = dataset.datas[0]\n for x in dataset.datas:\n for attr in attrset:\n if d.data[attr] != x.data[attr]:\n return False\n return True\n\n def gen_iter(node, pru, tD=testData):\n if_pruning = pru\n dataset = node.dataset\n attrset = node.attrset\n if if_pruning =='pre':#若需预剪枝,记录初始验证率\n node.set_as_leaf(label=self.best_label(node))\n ori_rate = self.clarrify_rate(tD)\n node.recovery()\n if len(dataset.labels) == 1: #样本全属一类\n label = list(dataset.labels.keys())[0]\n node.set_as_leaf(label)\n return\n elif not attrset or same_in_A(dataset, attrset):\n label = self.best_label(node)\n node.set_as_leaf(label)\n return\n attr, value, Dv = self.best_split(node)\n node.set_basis(attr)\n new_attrset = attrset.copy()\n new_attrset.remove(attr)\n if if_pruning == \"un\" or if_pruning == \"post\":\n for av in Dv:\n ds = Dv[av]\n av_node = Node(ds, new_attrset, name=av)\n node.set_child(av_node, av)\n gen_iter(av_node, pru=if_pruning,tD=testData)\n elif if_pruning == 'pre':\n for av in Dv:\n ds = Dv[av]\n av_node = Node(ds, new_attrset, name=av)\n av_node.set_as_leaf(self.best_label(av_node))\n node.set_child(av_node, av)\n new_rate = self.clarrify_rate(tD)\n if ori_rate > new_rate:\n node.set_as_leaf(self.best_label(node))\n node.child = dict()\n return\n else:\n for av in node.child:\n av_node = node.child[av]\n av_node.recovery()\n gen_iter(av_node, pru = if_pruning, tD=testData)\n\n if (pruning == 'pre' or pruning == 'post') and testData is None:\n raise TestDataError\n gen_iter(self.root,pru=pruning,tD=testData)\n if pruning == 'post':\n ori_rate = self.clarrify_rate(testData)\n dfs = [] \n def postorder(node):\n if node.leaf:#叶节点不进入dfs序列\n return\n nonlocal dfs\n for x in node.child:\n ch_node = node.child[x]\n postorder(ch_node)\n dfs.append(node)\n postorder(self.root)\n for post_node in dfs:\n post_node.set_as_leaf(self.best_label(post_node))\n new_rate = self.clarrify_rate(testData)\n if new_rate > ori_rate:\n post_node.child = dict()\n ori_rate = new_rate\n else:\n post_node.recovery()\n \n \n def clarrify(self, data):\n st = Stack()\n st.push(self.root)\n while st is not None:\n node = st.pop()\n if node.leaf:\n return data.label == node.label\n basis = node.basis\n feature = data.data[basis]\n st.push(node.child[feature])\n\n def clarrify_rate(self, dataset):\n n = 0\n N = len(dataset.datas)\n for data in dataset.datas:\n if self.clarrify(data):\n n += 1\n return n/N\n\n def export_tree(self, filename):\n f = open(filename, 'w')\n f.write('digraph Tree { \\n node [shape=box] ;\\n')\n st = Stack()\n st.push(self.root)\n while not st.isEmpty():\n node = st.pop()\n name, label = node.name, node.label\n if node.leaf:\n content = '[label=\"{}\",name=\"{}\"];\\n'.format(label, name)\n f.write(name+content)\n continue\n else:\n content = '[name=\"{}\",basis=\"{}\"];\\n'.format(name,node.basis)\n f.write(name+content)\n for x in node.child:\n child_node = node.child[x]\n st.push(child_node)#保证栈内总是Node类型\n f.write('{} -> {} ;\\n'.format(name, child_node.name))\n continue\n f.write('}')\n f.close()\n\n\nif __name__ == \"__main__\":\n dataset, attrset = loadData(\"4.2_data.csv\")\n testdataset, testattrset = loadData('4.2_test.csv')\n clf = DesicionTreeClassifier(dataset, attrset,critertion='gini')\n clf.generateTree(pruning='un')\n clf.export_tree('4.2_un.dot')\n clf2 = DesicionTreeClassifier(dataset, attrset)\n clf2.generateTree(pruning='pre',testData=testdataset)\n clf2.export_tree('4.2_pre.dot')\n clf3 = DesicionTreeClassifier(dataset, attrset)\n clf3.generateTree(pruning='post',testData= testdataset)\n clf3.export_tree('4.2_post.dot')","repo_name":"YuanzhaoLin1999/MachineLearning_Coursework","sub_path":"DecisionTree/pruningID3.py","file_name":"pruningID3.py","file_ext":"py","file_size_in_byte":7440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"27266612417","text":"import numpy as np\nimport scipy.sparse as sp\nimport numpy as np\n\ndef createDws(w, f, dL, N):\n '''\n s = 'x' or 'y': x derivative or y derivative\n f = 'b' or 'f'\n catches exceptions if s and f are misspecified\n '''\n M = np.prod(N);\n \n\n sign = 1 if f == 'f' else -1;\n dw = None; #just an initialization\n indices = np.reshape(np.arange(M), N, order = 'F');\n if(w == 'x'):\n ind_adj = np.roll(indices, -sign, axis = 0)\n dw = dL[0]\n elif(w == 'y'):\n ind_adj = np.roll(indices, -sign, axis = 1)\n dw = dL[1];\n elif(w == 'z'):\n ind_adj = np.roll(indices, -sign, axis = 2)\n dw = dL[-1]\n \n # we could use flatten here since the indices are already in 'F' order\n indices_flatten = np.reshape(indices, (M, ), order = 'F')\n indices_adj_flatten = np.reshape(ind_adj, (M, ), order = 'F')\n # on_inds = np.hstack((indices.flatten(), indices.flatten()))\n # off_inds = np.concatenate((indices.flatten(), ind_adj.flatten()), axis = 0);\n on_inds = np.hstack((indices_flatten, indices_flatten));\n off_inds = np.concatenate((indices_flatten, indices_adj_flatten), axis = 0);\n\n all_inds = np.concatenate((np.expand_dims(on_inds, axis =1 ), np.expand_dims(off_inds, axis = 1)), axis = 1)\n\n data = np.concatenate((-sign*np.ones((M)), sign*np.ones((M))), axis = 0)\n Dws = sp.csc_matrix((data, (all_inds[:,0], all_inds[:,1])), shape = (M,M));\n\n return (1/dw)*Dws;","repo_name":"zhaonat/py-maxwell-fd3d","sub_path":"pyfd3d/derivatives.py","file_name":"derivatives.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"20"} +{"seq_id":"9224559142","text":"import pandas as pd\nfrom prophet import Prophet\n\ndf = pd.read_csv(r'Finall Project\\foreign exchange DATA\\EUR\\EUR_GBP.csv')\npd.set_option('display.max_rows', None)\n\nm = Prophet()\nm.fit(df)\nfuture = m.make_future_dataframe(periods=365)\nfuture.tail()\nforecast = m.predict(future)\nforecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()\nx=forecast[forecast['ds'] >= pd.to_datetime('2023-01-01')]\npd.DataFrame(x, columns=['ds','yhat']).to_csv('XXX.csv')\n\nprint(x)\n","repo_name":"nofariof12/Project","sub_path":"Prophet.py","file_name":"Prophet.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"38277855643","text":"\"\"\"\nEXercício: TODOS\nAluno: Arthur Denarchi\nnUSP: 7992894\n\n\"Biblioteca\" desenvolvida pelo aluno com objetivo de ser utilizada nos EPCs da Matéria Fuzzy\no desenvolvimento deste arquivo tem como objetivo colocar sob a óptica da programação orientada\nobjetos as regiões Fuzzy de um sistema.\n\nPara seu funcionamento é necessário determinar o tamanho do universo, parte-se do pressusposto\nde universos que se iniciam em zero, tipo de região Fuzzy, sua descritização e alguns\npontos de interesse da função (dependendo do tipo de função).\n\"\"\"\n\n\nimport math\nclass Region:\n\tdef __init__(self, name, npoints, universe_size, region_min, region_max, region_type, trap_init=None, trap_end=None, alfa_cut_fuzzy=None, universe_init=0, centered='None'):\n\t\t\"\"\"Constructor\n\n\t\tArguments:\n\t\t\tnpoints {integer} -- Número de pontos na discretização da região fuzzy\n\t\t\tuniverse_size {integer} -- Tamanho máximo do universo, considera-se que todo universo se inicia em 0(zero)\n\t\t\tregion_min {float} -- Ponto de intersecção inicial entre a região e a absissa\n\t\t\tregion_max {float} -- Ponto de intersecção final entre a região e a absissa\n\t\t\tregion_type {string} -- Tipo da Região\n\n\t\tKeyword Arguments:\n\t\t\ttrap_init {float} -- Ponto inicial do teto do trapézio (default: {None})\n\t\t\ttrap_end {float} -- Ponto final do teto do trapézio (default: {None})\n\t\t\"\"\"\n\n\t\tself.name = name\n\t\tself.npoints = npoints\n\t\tself.universe_size = universe_size\n\t\tself.universe_init = universe_init\n\t\tself.fuzzy = []\n\t\tself.region_min = region_min\n\t\tself.region_max = region_max\n\t\tself.region_type = region_type\n\t\tself.region_size = region_max - region_min\n\t\tif centered == None:\n\t\t\tself.region_center = self.region_min + self.region_size/2\n\t\telse:\n\t\t\tself.region_center = centered\n\n\t\tif self.region_type == 'trapezoid':\n\t\t\tself.trap_init = trap_init\n\t\t\tself.trap_end = trap_end\n\n\t\tif self.region_type == 'blank':\n\t\t\tfor x in range (0, self.npoints):\n\t\t\t\tx = self.__get_x(x)\n\t\t\t\tu = 0\n\t\t\t\tregion_item = {'x': x, 'u': u}\n\t\t\t\tself.fuzzy.append(region_item)\n\n\t\telif self.region_type == 'blank_filled':\n\t\t\tfor x in range (0, self.npoints):\n\t\t\t\tx = self.__get_x(x)\n\t\t\t\tu = 1\n\t\t\t\tregion_item = {'x': x, 'u': u}\n\t\t\t\tself.fuzzy.append(region_item)\n\n\t\telif self.region_type == 'alfa_cut':\n\t\t\tfor x in range(0, self.npoints):\n\t\t\t\tx = self.__get_x(x)\n\t\t\t\tfor item in alfa_cut_fuzzy:\n\t\t\t\t\tif x == item['x']:\n\t\t\t\t\t\tu = item['u']\n\t\t\t\t\t\tregion_item = {'x': x, 'u': u}\n\t\t\t\t\t\tself.fuzzy.append(region_item)\n\t\t\t\tu = 0\n\t\t\t\tregion_item = {'x': x, 'u': u}\n\t\t\t\tself.fuzzy.append(region_item)\n\t\t\tself.update()\n\n\t\telse:\n\t\t\tfor x in range (0, self.npoints):\n\t\t\t\tx = self.__get_x(x)\n\t\t\t\tu = self.__get_u(x)\n\t\t\t\tregion_item = {'x': x, 'u': u}\n\t\t\t\tself.fuzzy.append(region_item)\n\n\t\tself.update_active()\n\n\tdef __close__(self):\n\t\t\"\"\"Destructor\n\t\t\"\"\"\n\t\tself.npoints = None\n\t\tself.universe_size = None\n\t\tself.fuzzy = None\n\t\tself.region_min = None\n\t\tself.region_max = None\n\t\tself.region_type = None\n\t\tself.region_size = None\n\t\tself.region_center = None\n\n\t\tif self.region_type == 'trapezoid':\n\t\t\tself.trap_init = None\n\t\t\tself.trap_end = None\n\n\tdef __get_x(self, x):\n\t\t\"\"\"get_x - Função para o construtor - Acha um elemento do universo discretizado\n\n\t\tArguments:\n\t\t\tx {integer} -- Índice entre 0 e npoints\n\n\t\tReturns:\n\t\t\tfloat -- elemento do universo relativo ao índice de discretização de entrada\n\n\t\t\"\"\"\n\t\treturn round((x/self.npoints)*self.universe_size, int(math.log(self.npoints, 10)+1))+self.universe_init\n\n\tdef __get_u(self, x):\n\t\t\"\"\"get_u - Função para o construtor - acha o grau de pertinência de um elemento do universo\n\n\t\tArguments:\n\t\t\tx {float} -- elemento do universo da região fuzzy\n\n\t\tReturns:\n\t\t\tfloat -- pertinencia do elemento de entrada na região fuzzy\n\t\t\"\"\"\n\t\tif x < self.region_min or x > self.region_max:\n\t\t\treturn 0\n\n\t\tif self.region_type == 'trapezoid':\n\t\t\tif self.trap_init == None or self.trap_end == None:\n\t\t\t\tprint('Error: please specify trapezoid characteristics.')\n\t\t\tif x <= self.trap_init and self.trap_init != self.region_min:\n\t\t\t\tdelta_y = 1\n\t\t\t\tdelta_x = self.trap_init - self.region_min\n\t\t\t\tslope = delta_y/delta_x\n\t\t\t\tu = slope*(x-self.region_min)\n\t\t\tif x >= self.trap_init <= self.trap_end:\n\t\t\t\tu = 1\n\t\t\tif x > self.trap_end:\n\t\t\t\tdelta_y = -1\n\t\t\t\tdelta_x = self.region_max - self.trap_end\n\t\t\t\tslope = delta_y/delta_x\n\t\t\t\tu = 1 + slope*(x-self.trap_end)\n\n\t\tif self.region_type == 'triangular':\n\t\t\tif x <= self.region_center:\n\t\t\t\tdelta_y = 1\n\t\t\t\tdelta_x = self.region_center - self.region_min\n\t\t\t\tslope = delta_y/delta_x\n\t\t\t\tu = slope*(x-self.region_min)\n\t\t\tif x > self.region_center:\n\t\t\t\tdelta_y = -1\n\t\t\t\tdelta_x = self.region_max - self.region_center\n\t\t\t\tslope = delta_y/delta_x\n\t\t\t\tu = 1+slope*(x-self.region_center)\n\t\treturn u\n\n\tdef get_u(self, x):\n\t\t\"\"\"get_u - Funçao para o usuário encontrar pertinência de um elemento qualquer\n\n\t\tArguments:\n\t\t\tx {float} -- elemento do universo da região fuzzy\n\n\t\tReturns:\n\t\t\tfloat -- grau de pertinencia do elemento escolhido do universo\n\t\t\"\"\"\n\t\tfor i, item in enumerate(self.fuzzy):\n\t\t\tif x == item['x']:\n\t\t\t\treturn item['u']\n\t\t\tif x < item['x']:\n\t\t\t\treturn self.fuzzy[i-1]['u']\n\n\tdef update_active(self):\n\t\tactive = []\n\t\tfor item in self.fuzzy:\n\t\t\tif self.get_u(item['x']) > 0:\n\t\t\t\tactive.append(item)\n\t\tself.active = active\n\n\n\tdef is_active(self, x):\n\t\tfor i, item in enumerate(self.fuzzy):\n\t\t\tif x == item['x']:\n\t\t\t\tif item['u'] > 0:\n\t\t\t\t\treturn True\n\t\t\t\telse:\n\t\t\t\t\treturn False\n\t\t\tif x < item['x']:\n\t\t\t\tif self.fuzzy[i-1]['u'] > 0:\n\t\t\t\t\treturn True\n\t\t\t\telse:\n\t\t\t\t\treturn False\n\t\treturn False\n\n\tdef get_alfa_cut(self, alfa):\n\t\talfa_cut = []\n\t\tfor item in self.fuzzy:\n\t\t\tif item['u'] >= alfa:\n\t\t\t\talfa_cut.append(item)\n\t\treturn alfa_cut\n\n\tdef mandani(self, treshold):\n\t\tfor item in self.fuzzy:\n\t\t\titem['u'] = min(item['u'], treshold)\n\t\tself.update()\n\n\tdef zadeh(self, treshold):\n\t\tfor item in self.fuzzy:\n\t\t\titem['u'] = max(1-treshold, min(item['u'], treshold))\n\t\tself.update()\n\n\tdef larsen(self, treshold):\n\t\tfor item in self.fuzzy:\n\t\t\titem['u'] = item['u']*treshold\n\t\tself.update()\n\n\tdef cda(self):\n\t\tu_times_x = 0\n\t\tu = 0\n\t\tfor item in self.fuzzy:\n\t\t\tu_times_x = u_times_x + item['u']*item['x']\n\t\t\tu = u + item['u']\n\t\treturn round(u_times_x/u, 2)\n\n\tdef mdm(self):\n\t\tmax_u = 0\n\t\tfor item in self.fuzzy:\n\t\t\tmax_u = max(item['u'], max_u)\n\n\t\tsum_x = 0\n\t\tnumber_of_x = 0\n\t\tfor item in self.fuzzy:\n\t\t\tif item['u'] == max_u:\n\t\t\t\tsum_x = sum_x + item['x']\n\t\t\t\tnumber_of_x = number_of_x + 1\n\n\t\treturn round(sum_x/number_of_x, 2)\n\n\tdef mpm(self):\n\t\tmax_u = 0\n\t\tfor item in self.fuzzy:\n\t\t\tmax_u = max(item['u'], max_u)\n\n\t\tfor item in self.fuzzy:\n\t\t\tif item['u'] == max_u:\n\t\t\t\treturn round(item['x'], 2)\n\n\tdef update(self):\n\t\t\"\"\"update\n\t\t\tFunção que atualiza alguns atributos da região, deve ser utilizada após alterar-se diretamente os elementos\n\t\t\tdo atributo fuzzy.\n\t\t\"\"\"\n\t\tfor item in self.fuzzy:\n\t\t\tif item['u'] == 0:\n\t\t\t\tself.region_min = item['x']\n\t\t\telse:\n\t\t\t\tbreak\n\n\t\tfor item in reversed(self.fuzzy):\n\t\t\tif item['u'] == 0:\n\t\t\t\tself.region_max = item['x']\n\t\t\telse:\n\t\t\t\tbreak\n\n\t\tself.region_size = self.region_max - self.region_min\n\t\tself.region_center = self.region_min + self.region_size/2\n\t\tself.update_active()","repo_name":"arthurdemarchi/FuzzyEPCs","sub_path":"MyLibs/region.py","file_name":"region.py","file_ext":"py","file_size_in_byte":7158,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"14587265226","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nco2 = pd.read_excel('Graph Data/CO2-comparison-final.xlsx', skiprows = 3, nrows = 4, usecols = 'D:AI')\n\ndef divide(ds):\n\tscen = []\n\tfor i in range(0,4):\n\t\tscen.append(ds.loc[i].to_numpy().reshape(-1))\n\treturn scen\n\nscen = divide(co2)\nyear = np.arange(2019, 2051)\ncol = ['#c1d4b7', '#99b880', '#769e4f','#5d8541']\nfor i in range (0,4):\n\tplt.plot(year, scen[i], color = col[i], linewidth = 3)\nplt.xlabel('Year', fontsize = 14)\nplt.ylabel(r'Total Annual Emissions (MMt $CO_2e)$', fontsize = 14)\nplt.legend(['Scenario 1', 'Scenario 2', 'Scenario 3', 'Scenario 4'])\nplt.show()","repo_name":"SayYoungMan/2050-Energy-Estimate","sub_path":"Legacy/co2_comparison.py","file_name":"co2_comparison.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"10850034777","text":"# link :: https://school.programmers.co.kr/learn/courses/30/lessons/134240\n\n# blogged link :: https://medium.com/@va1afar.biz/programmers-coding-test-lv-1-a-food-fight-competition-b998915a250b\n\ndef solution(food):\n # variable\n answer = ''\n i = 1\n \n # calc.\n food.pop(0)\n for each_food in food:\n answer += (str(i) * (each_food//2))\n i += 1\n answer = answer + '0' + answer[::-1]\n \n return answer\n","repo_name":"va1afar/code_test","sub_path":"Programmers/lv.1/[Blogged] 푸드 파이트 대회 (A food fight competition).py","file_name":"[Blogged] 푸드 파이트 대회 (A food fight competition).py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"29923412524","text":"# author: victorisimo\n# description: hackaton\nfrom typing import List\n\ndef justify_method(words, max_lenght):\n lines = []\n curr = []\n width = 0\n i = 0\n\n while i < len(words):\n word = words[i]\n new_width = width + len(word) + bool(curr)\n if new_width <= max_lenght:\n i += 1\n curr.append(word)\n width = new_width\n elif curr:\n lines.append(add_spaces(curr, max_lenght, format_text=True))\n curr = []\n width = 0\n if curr:\n lines.append(add_spaces(curr, max_lenght, format_text=False))\n return lines\n\n\ndef add_spaces(words, max_size, format_text):\n if format_text:\n wid, remainder = divmod(max_size - sum(len(w) for w in words), len(words) - 1)\n text_wi = [wid + int(i < remainder) for i in range(len(words) - 1)]\n text_wi.append(0)\n else:\n text_wi = [1 for _ in range(len(words) - 1)]\n text_wi.append(max_size - sum(len(w) for w in words) - len(words) - 1)\n\n return ''.join(\n w + (' ' * wid)\n for w, wid in zip(words, text_wi)\n )\n\n# main methodxw\nif __name__ == '__main__':\n print(justify_method(['This is an', 'example of text', 'justification.'], 26))","repo_name":"victorisimoo/hackathon_url","sub_path":"second.py","file_name":"second.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17357655697","text":"from __future__ import absolute_import\nfrom __future__ import print_function\nimport argparse\nimport glob\nimport json\nimport os\nimport os.path\nimport random\nimport subprocess\nimport sys\nimport time\nimport uuid\nimport zipfile\n\n# Backwards-compatibility with Python 2.7\ntry:\n input = raw_input\nexcept NameError:\n pass\n\nimport requests\n\n# inline:\n# websocket if `mpm logskill`\n\nfrom .__init__ import __version__\nfrom . import config\n\n\ndef _get_logs(addr):\n try:\n logs_resp = requests.get(addr + '/api/logs')\n except requests.exceptions.ConnectionError:\n print('failed to connect to the Misty robot!')\n print('check connection with `mpm config --ping`')\n return None\n if not logs_resp.ok:\n print('failed to connect to the Misty robot!')\n print('check connection with `mpm config --ping`')\n return None\n logs_resp = logs_resp.json()\n if logs_resp['status'] != 'Success':\n print('Misty returned failure status: {}'.format(logs_resp['status']))\n return None\n raw_logdump = logs_resp['result']\n return [l for l in raw_logdump.split('\\r\\n') if l]\n\n\ndef main(argv=None):\n if argv is None:\n argv = sys.argv[1:]\n\n argparser = argparse.ArgumentParser(description='package (skill) manager for Misty', add_help=False)\n argparser.add_argument('-h', '--help', dest='print_help',\n action='store_true', default=False,\n help='print this help message and exit')\n argparser.add_argument('-V', '--version', dest='print_version',\n action='store_true', default=False,\n help='print version number and exit.')\n\n subparsers = argparser.add_subparsers(dest='command')\n\n init_help = 'create a new (empty) skill'\n init_parser = subparsers.add_parser('init', description=init_help, help=init_help, add_help=False)\n init_parser.add_argument('NAME', help='name of the skill')\n init_parser.add_argument('-h', '--help', dest='print_init_help',\n action='store_true', default=False,\n help='print this help message and exit')\n\n build_help = 'create bundle ready for upload to Misty robot'\n build_parser = subparsers.add_parser('build', description=build_help, help=build_help, add_help=False)\n build_parser.add_argument('--compress', dest='compress_source',\n action='store_true', default=False,\n help=('compress source code using uglify-js '\n '(https://github.com/mishoo/UglifyJS2)'))\n build_parser.add_argument('-h', '--help', dest='print_build_help',\n action='store_true', default=False,\n help='print this help message and exit')\n\n clean_help = 'clean distribution files generated by `mpm build`'\n clean_parser = subparsers.add_parser('clean', description=clean_help, help=clean_help, add_help=False)\n clean_parser.add_argument('-h', '--help', dest='print_clean_help',\n action='store_true', default=False,\n help='print this help message and exit')\n\n config_help = 'manage local configuration'\n config_parser = subparsers.add_parser('config', description=config_help, help=config_help, add_help=False)\n config_parser.add_argument('-h', '--help', dest='print_config_help',\n action='store_true', default=False,\n help='print this help message and exit')\n config_parser.add_argument('--addr', dest='config_addr',\n default=None, metavar='ADDRESS',\n help='declare address of Misty robot')\n config_parser.add_argument('--ping', dest='config_ping',\n action='store_true', default=False,\n help='check that Misty robot can be reached')\n config_parser.add_argument('--rm', dest='delete_config',\n action='store_true', default=False,\n help='delete local configuration data')\n\n list_help = 'list skills currently on Misty robot'\n list_parser = subparsers.add_parser('list', description=list_help, help=list_help, add_help=False)\n list_parser.add_argument('-h', '--help', dest='print_list_help',\n action='store_true', default=False,\n help='print this help message and exit')\n\n upload_help = 'upload skill to Misty robot'\n upload_parser = subparsers.add_parser('upload', description=upload_help, help=upload_help, add_help=False)\n upload_parser.add_argument('-h', '--help', dest='print_upload_help',\n action='store_true', default=False,\n help='print this help message and exit')\n\n remove_help = 'remove skill from Misty robot'\n remove_parser = subparsers.add_parser('remove', description=remove_help, help=remove_help, add_help=False)\n remove_parser.add_argument('remove_ID', metavar='ID', default=None, nargs='?',\n help=('uniqueId of skill to remove from robot; '\n 'if none given, and only 1 skill is on robot, '\n 'then remove it.'))\n remove_parser.add_argument('-h', '--help', dest='print_remove_help',\n action='store_true', default=False,\n help='print this help message and exit')\n\n start_help = 'start execution of skill on Misty robot'\n start_parser = subparsers.add_parser('skillstart', description=start_help, help=start_help, add_help=False)\n start_parser.add_argument('start_ID', metavar='ID', default=None, nargs='?',\n help=('uniqueId of skill to start on robot; '\n 'if none given, and only 1 skill is on robot, '\n 'then start it.'))\n start_parser.add_argument('-h', '--help', dest='print_start_help',\n action='store_true', default=False,\n help='print this help message and exit')\n\n log_help = 'print logs from Misty robot'\n log_parser = subparsers.add_parser('log', description=log_help, help=log_help, add_help=False)\n log_parser.add_argument('-h', '--help', dest='print_log_help',\n action='store_true', default=False,\n help='print this help message and exit')\n log_parser.add_argument('-f', dest='config_logfollow',\n action='store_true', default=False,\n help='follow logs, print changes incrementally')\n\n logskill_help = 'stream logs from skill via SkillData WebSocket'\n logskill_parser = subparsers.add_parser('logskill', description=logskill_help, help=logskill_help, add_help=False)\n logskill_parser.add_argument('-h', '--help', dest='print_logskill_help',\n action='store_true', default=False,\n help='print this help message and exit')\n\n mversion_help = 'print (YAML format) identifiers and version numbers of Misty robot and exit.'\n mversion_parser = subparsers.add_parser('mistyversion', description=mversion_help, help=mversion_help, add_help=False)\n mversion_parser.add_argument('-h', '--help', dest='print_mversion_help',\n action='store_true', default=False,\n help='print this help message and exit')\n\n subparsers.add_parser('version', help='print version number and exit.', add_help=False)\n help_parser = subparsers.add_parser('help', help='print this help message and exit', add_help=False)\n help_parser.add_argument('help_target_command', metavar='COMMAND', type=str, nargs='?')\n\n # Workaround for Python 2.7 argparse, which does not accept empty COMMAND:\n # If `--help` or `-h` present and every argument before it begins with `-`,\n # then convert it to `help`.\n # If `-V` or `--version` present and every argument before it begins with `-`,\n # then convert it to `version.\n if sys.version_info.major < 3:\n try:\n ind = argv.index('--help')\n except ValueError:\n try:\n ind = argv.index('-h')\n except ValueError:\n ind = None\n if ind is not None:\n for k in range(ind):\n if argv[k][0] != '-':\n ind = None\n break\n if ind is not None:\n argv[ind] = 'help'\n try:\n ind = argv.index('--version')\n except ValueError:\n try:\n ind = argv.index('-V')\n except ValueError:\n ind = None\n if ind is not None:\n for k in range(ind):\n if argv[k][0] != '-':\n ind = None\n break\n if ind is not None:\n argv[ind] = 'version'\n\n args = argparser.parse_args(argv)\n if args.print_version or args.command == 'version':\n print(__version__)\n return 0\n\n if args.print_help or args.command is None or args.command == 'help':\n if hasattr(args, 'help_target_command') and args.help_target_command is not None:\n if args.help_target_command == 'init':\n init_parser.print_help()\n elif args.help_target_command == 'build':\n build_parser.print_help()\n elif args.help_target_command == 'clean':\n clean_parser.print_help()\n elif args.help_target_command == 'config':\n config_parser.print_help()\n elif args.help_target_command == 'list':\n list_parser.print_help()\n elif args.help_target_command == 'upload':\n upload_parser.print_help()\n elif args.help_target_command == 'remove':\n remove_parser.print_help()\n elif args.help_target_command == 'skillstart':\n start_parser.print_help()\n elif args.help_target_command == 'log':\n log_parser.print_help()\n elif args.help_target_command == 'logskill':\n logskill_parser.print_help()\n elif args.help_target_command == 'mistyversion':\n mversion_parser.print_help()\n else:\n print('Unrecognized command. Try `--help`.')\n return 1\n else:\n argparser.print_help()\n return 0\n\n if args.command == 'init':\n if args.print_init_help:\n init_parser.print_help()\n return 0\n\n # Preconditions\n skillmeta_path = os.path.join('src', '{}.json'.format(args.NAME))\n if os.path.exists(skillmeta_path):\n print('ERROR: cannot initialize '\n 'because path already exists: {}'.format(skillmeta_path))\n return 1\n mainjs_path = os.path.join('src', '{}.js'.format(args.NAME))\n if os.path.exists(mainjs_path):\n print('ERROR: cannot initialize '\n 'because path already exists: {}'.format(mainjs_path))\n return 1\n\n skillmeta = {\n 'Name': args.NAME,\n 'UniqueId': str(uuid.uuid4()),\n 'Description': '',\n 'StartupRules': ['Manual', 'Robot'],\n 'Language': 'javascript',\n 'BroadcastMode': 'verbose',\n 'TimeoutInSeconds': 60,\n 'CleanupOnCancel': True,\n 'WriteToLog': False,\n }\n\n # Write results\n if not os.path.exists('src'):\n os.mkdir('src')\n with open(skillmeta_path, 'wt') as fp:\n json.dump(skillmeta, fp, indent=2)\n with open(mainjs_path, 'wt') as fp:\n pass\n\n elif args.command == 'build':\n if args.print_build_help:\n build_parser.print_help()\n return 0\n\n # Preconditions\n candidate_metafiles = glob.glob(os.path.join('src', '*.json'))\n candidate_metafiles += glob.glob(os.path.join('src', '*.JSON'))\n\n skillname = None\n for candidate_metafile in candidate_metafiles:\n candidate_skillname = os.path.basename(candidate_metafile)\n if candidate_skillname.endswith('.json') or candidate_skillname.endswith('.JSON'):\n candidate_skillname = candidate_skillname[:-len('.json')]\n else:\n continue\n candidate_mainjsfile = os.path.join('src', '{}.js'.format(candidate_skillname))\n if not os.path.exists(candidate_mainjsfile):\n candidate_mainjsfile = os.path.join('src', '{}.JS'.format(candidate_skillname))\n if not os.path.exists(candidate_mainjsfile):\n continue\n skillname = candidate_skillname\n skillmeta_path = candidate_metafile\n mainjs_path = candidate_mainjsfile\n break\n if skillname is None:\n print('ERROR: no meta file found in src/')\n return 1\n\n if args.compress_source:\n newpath = mainjs_path[:-2] + 'min.js'\n try:\n rc = subprocess.call(['uglifyjs', '-o', newpath, mainjs_path])\n except OSError:\n print('ERROR: error calling uglifyjs. Is it installed?')\n return 1\n if rc != 0:\n print('ERROR: failed to compress source file: {}'.format(mainjs_path))\n return rc\n mainjs_path = newpath\n\n # Write results\n if not os.path.exists('dist'):\n os.mkdir('dist')\n zipout_path = os.path.join('dist', '{}.zip'.format(skillname))\n if os.path.exists(zipout_path):\n print('WARNING: destination file {} already exists. overwriting...'.format(zipout_path))\n zp = zipfile.ZipFile(zipout_path, mode='w')\n zp.write(skillmeta_path, arcname='{}.json'.format(skillname))\n zp.write(mainjs_path, arcname='{}.js'.format(skillname))\n zp.close()\n\n elif args.command == 'clean':\n if args.print_clean_help:\n clean_parser.print_help()\n return 0\n for fname in glob.glob(os.path.join('dist', '*')):\n os.unlink(fname)\n os.rmdir('dist')\n\n elif args.command == 'config':\n if args.print_config_help:\n config_parser.print_help()\n return 0\n if args.delete_config:\n print('Do you want to delete all local configuration data? [y/N]')\n decision = input()\n if decision.lower() not in ['y', 'yes']:\n return 1\n try:\n config.delete()\n except Exception as e:\n print('Failed to remove configuration: {}'.format(e))\n return 1\n return 0\n\n cfg = config.load(init_if_missing=True)\n if args.config_addr:\n cfg['addr'] = args.config_addr\n config.save(cfg)\n if args.config_ping:\n addr = cfg.get('addr')\n if addr is None:\n print('ERROR: Misty address is not known!')\n print('add it using `mpm config --addr`')\n return 1\n if not addr.startswith('http'):\n addr = 'http://' + addr\n try:\n pong = requests.get(addr + '/api/battery').ok\n except requests.exceptions.ConnectionError:\n pong = False\n if pong:\n print('success!')\n return 0\n else:\n print('failed to ping the Misty robot!')\n return 1\n\n else:\n out = config.pprint(cfg)\n if len(out) == 0:\n print('(empty)')\n else:\n print(out)\n\n elif args.command == 'list':\n if args.print_list_help:\n list_parser.print_help()\n return 0\n cfg = config.load()\n addr = cfg.get('addr')\n if not addr.startswith('http'):\n addr = 'http://' + addr\n try:\n slist = requests.get(addr + '/api/skills').json()\n except requests.exceptions.ConnectionError:\n print('failed to connect to the Misty robot!')\n print('check connection with `mpm config --ping`')\n return 1\n if slist['status'] != 'Success':\n print('Misty returned failure status: {}'.format(slist['status']))\n return 1\n slist = slist['result']\n for skilldata in slist:\n print('{} {}'.format(skilldata['uniqueId'], skilldata['name']))\n\n elif args.command == 'upload':\n if args.print_upload_help:\n upload_parser.print_help()\n return 0\n dist_files = glob.glob(os.path.join('dist', '*'))\n if len(dist_files) > 1:\n print('ERROR: more than one file under dist/')\n print('perhaps `mpm clean`, then `mpm build` again')\n return 1\n fp = open(dist_files[0], 'rb')\n cfg = config.load()\n addr = cfg.get('addr')\n if not addr.startswith('http'):\n addr = 'http://' + addr\n try:\n res = requests.request(method='POST', url=addr + '/api/skills', files={\n 'File': (dist_files[0], fp, 'application/zip'),\n 'ImmediatelyApply': (None, 'false'),\n 'OverwriteExisting': (None, 'true'),\n })\n except requests.exceptions.ConnectionError:\n print('failed to connect to the Misty robot!')\n print('check connection with `mpm config --ping`')\n return 1\n fp.close()\n if not res.ok:\n print('failed to upload skill to robot')\n return 1\n print(res.text)\n\n elif args.command == 'remove':\n if args.print_remove_help:\n remove_parser.print_help()\n return 0\n cfg = config.load()\n addr = cfg.get('addr')\n if not addr.startswith('http'):\n addr = 'http://' + addr\n if args.remove_ID is None:\n try:\n slist = requests.get(addr + '/api/skills').json()\n except requests.exceptions.ConnectionError:\n print('failed to connect to the Misty robot!')\n print('check connection with `mpm config --ping`')\n return 1\n if slist['status'] != 'Success':\n print('Misty returned failure status: {}'.format(slist['status']))\n return 1\n slist = slist['result']\n if len(slist) == 0:\n print('no skills on the robot; nothing to remove.')\n return 1\n if len(slist) > 1:\n print('more than 1 skill on the robot!')\n print('specify which skill to remove explicitly in `mpm remove ID`')\n return 1\n remove_ID = slist[0]['uniqueId']\n else:\n remove_ID = args.remove_ID\n\n try:\n res = requests.delete(addr + '/api/skills?Skill={}'.format(remove_ID))\n except requests.exceptions.ConnectionError:\n print('failed to connect to the Misty robot!')\n print('check connection with `mpm config --ping`')\n return 1\n if not res.ok:\n print('failed to remove skill {} from robot'.format(remove_ID))\n return 1\n\n elif args.command == 'skillstart':\n if args.print_start_help:\n start_parser.print_help()\n return 0\n cfg = config.load()\n addr = cfg.get('addr')\n if not addr.startswith('http'):\n addr = 'http://' + addr\n if args.start_ID is None:\n try:\n slist = requests.get(addr + '/api/skills').json()\n except requests.exceptions.ConnectionError:\n print('failed to connect to the Misty robot!')\n print('check connection with `mpm config --ping`')\n return 1\n if slist['status'] != 'Success':\n print('Misty returned failure status: {}'.format(slist['status']))\n return 1\n slist = slist['result']\n if len(slist) == 0:\n print('no skills on the robot; nothing to start.')\n print('try uploading a skill using `mpm upload`')\n return 1\n if len(slist) > 1:\n print('more than 1 skill on the robot!')\n print('specify which skill to start explicitly in `mpm start ID`')\n return 1\n start_ID = slist[0]['uniqueId']\n else:\n start_ID = args.start_ID\n\n try:\n res = requests.post(addr + '/api/skills/start', json={\n 'Skill': start_ID,\n })\n except requests.exceptions.ConnectionError:\n print('failed to connect to the Misty robot!')\n print('check connection with `mpm config --ping`')\n return 1\n if not res.ok:\n print('failed to start skill {} on robot'.format(start_ID))\n return 1\n\n elif args.command == 'log':\n if args.print_log_help:\n log_parser.print_help()\n return 0\n cfg = config.load()\n addr = cfg.get('addr')\n if not addr.startswith('http'):\n addr = 'http://' + addr\n logs = _get_logs(addr)\n if logs is None:\n return 1\n print('\\n'.join(logs))\n if args.config_logfollow:\n try:\n while True:\n time.sleep(1)\n nlogs = _get_logs(addr)\n diff = nlogs.index(logs[-1]) + 1\n nlogs = nlogs[diff:]\n print('\\n'.join(nlogs))\n logs = nlogs\n except KeyboardInterrupt:\n pass\n\n\n elif args.command == 'logskill':\n if args.print_logskill_help:\n logskill_parser.print_help()\n return 0\n\n import websocket\n\n cfg = config.load()\n addr = cfg.get('addr')\n if addr.startswith('http:'):\n addr = 'ws:' + addr[5:]\n elif addr.startswith('https:'):\n addr = 'wss:' + addr[6:]\n elif not addr.startswith('http'):\n addr = 'ws://' + addr\n\n def on_open(ws):\n ws.send(json.dumps({\n 'Operation': 'subscribe',\n 'Type': 'SkillData',\n 'DebounceMS': None,\n 'EventName': 'SkillData{}'.format(random.randint(0,1000)),\n 'Message': '',\n 'ReturnProperty': None,\n }))\n\n def on_error(ws, err):\n print('error:', msg)\n\n def on_message(ws, msg):\n x = json.loads(msg)\n print(x['message'])\n\n ws = websocket.WebSocketApp(addr + '/pubsub', on_open=on_open, on_message=on_message, on_error=on_error)\n ws.run_forever(ping_interval=15)\n\n\n elif args.command == 'mistyversion':\n if args.print_mversion_help:\n mversion_parser.print_help()\n return 0\n cfg = config.load()\n addr = cfg.get('addr')\n if not addr.startswith('http'):\n addr = 'http://' + addr\n try:\n res = requests.get(addr + '/api/device')\n if not res.ok:\n print('failed to connect to the Misty robot!')\n return 1\n devinfo = res.json()\n except requests.exceptions.ConnectionError:\n print('failed to connect to the Misty robot!')\n print('check connection with `mpm config --ping`')\n return 1\n if devinfo['status'] != 'Success':\n print('Misty returned failure status: {}'.format(devinfo['status']))\n return 1\n devinfo = devinfo['result']\n print('sku:', devinfo['sku'])\n print('serial number:', devinfo['serialNumber'])\n print('robotId:', devinfo['robotId'])\n for k in ['robotVersion', 'sensoryServiceAppVersion', 'androidOSVersion', 'windowsOSVersion']:\n print('{}: {}'.format(k, devinfo[k]))\n hardware_info = devinfo['hardwareInfo']\n for k in hardware_info:\n print('{}:'.format(k))\n for subk in hardware_info[k]:\n print(' {}: {}'.format(subk, hardware_info[k][subk]))\n\n else:\n print('Unrecognized command. Try `--help`.')\n return 1\n\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:]))\n","repo_name":"rerobots/MistyPackageManager","sub_path":"mpm/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":24688,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"28765410475","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\npd.options.display.max_columns = None\n\nseaborn.set()\n\n\ndef loaddatasets(filepath):\n wine_dataset = pd.read_csv(f'{filepath}/DataSet.csv')\n return wine_dataset\n\n\ndef printbarplot(wine_df):\n grouped_countries_points = wine_df.groupby(\n [\"country\"], as_index=False)['points'].mean()\n grouped_countries_price = wine_df.groupby(\n [\"country\"], as_index=False)['price'].mean()\n\n plt.barh(grouped_countries_points.points,\n grouped_countries_points.country, color=(0.2, 0.4, 0.6, 0.6))\n plt.xlabel('Country', fontsize=5)\n plt.ylabel('Points(from 100)', fontsize=5)\n plt.title('Country VS Points')\n plt.savefig('BarPlotPoints/points.png')\n plt.clf()\n\n plt.barh(grouped_countries_price.price,\n grouped_countries_price.country, color=(0.2, 0.4, 0.6, 0.6))\n plt.xlabel('Country', fontsize=5)\n plt.ylabel('Price', fontsize=5)\n plt.title('Country VS Price')\n plt.savefig('BarPlotPrice/price.png')\n plt.clf()\n\n\ndef DecisionTree(wine_df):\n y = wine_df['points_'].values\n wine_df = wine_df.drop(columns=['points_'])\n X = wine_df.values\n\n X_train, X_valid, y_train, y_valid = train_test_split(X, y)\n\n model = DecisionTreeClassifier(max_depth=30)\n model.fit(X_train, y_train)\n print(\"Score with Decision Tree Classifier \" +\n str(model.score(X_valid, y_valid)))\n\n\ndef GB(wine_df):\n y = wine_df['points_'].values\n wine_df = wine_df.drop(columns=['points_'])\n X = wine_df.values\n\n X_train, X_valid, y_train, y_valid = train_test_split(X, y)\n\n modelGB = GradientBoostingClassifier(n_estimators=50,\n max_depth=50, min_samples_leaf=0.1)\n modelGB.fit(X_train, y_train)\n print(\"Score with Gradient Boosting \"+str(modelGB.score(X_valid, y_valid)))\n\n\ndef KNN(wine_df):\n y = wine_df['points_'].values\n wine_df = wine_df.drop(columns=['points_'])\n X = wine_df.values\n\n X_train, X_valid, y_train, y_valid = train_test_split(X, y)\n\n modelKNN = KNeighborsClassifier(n_neighbors=1)\n modelKNN.fit(X_train, y_train)\n print(\"Score with K-Nearest Neighbours \" +\n str(modelKNN.score(X_valid, y_valid)))\n\n\ndef GNB(wine_df):\n y = wine_df['points_'].values\n wine_df = wine_df.drop(columns=['points_'])\n X = wine_df.values\n\n X_train, X_valid, y_train, y_valid = train_test_split(X, y)\n modelGNB = GaussianNB()\n modelGNB.fit(X_train, y_train)\n print(\"Score with Gaussian Naive Bayes Neighbours \" +\n str(modelGNB.score(X_valid, y_valid)))\n\n\ndef WithoutRegion2Analysis(wine_df):\n # Since there are limited number of countries, let's look at avg of each country's points and plot a graph for visualization\n printbarplot(wine_df)\n\n country_, country_unique_values = pd.factorize(wine_df.loc[:, 'country'])\n designation_, country_unique_values = pd.factorize(\n wine_df.loc[:, 'designation'])\n price_, price_unique_values = pd.factorize(wine_df.loc[:, 'price'])\n province_, province_unique_values = pd.factorize(\n wine_df.loc[:, 'province'])\n region_1_, region_unique_values = pd.factorize(wine_df.loc[:, 'region_1'])\n winery_, winery_unique_values = pd.factorize(\n wine_df.loc[:, 'winery'])\n points_, points_unique_values = pd.factorize(\n wine_df.loc[:, 'points'])\n\n wine_df['country_'] = country_\n wine_df['designation_'] = designation_\n wine_df['price_'] = price_\n wine_df['province_'] = province_\n wine_df['winery_'] = winery_\n wine_df['region_'] = region_1_\n wine_df['points_'] = points_\n\n wine_df = wine_df.drop(columns=['Unnamed: 0', 'country', 'designation', 'price',\n 'province', 'winery', 'region_1', 'points', 'variety'])\n\n DecisionTree(wine_df)\n GB(wine_df)\n KNN(wine_df)\n GNB(wine_df)\n\n\ndef WithRegionAnalysis(wine_df):\n country_, country_unique_values = pd.factorize(wine_df.loc[:, 'country'])\n designation_, country_unique_values = pd.factorize(\n wine_df.loc[:, 'designation'])\n price_, price_unique_values = pd.factorize(wine_df.loc[:, 'price'])\n province_, province_unique_values = pd.factorize(\n wine_df.loc[:, 'province'])\n region_1_, region_unique_values = pd.factorize(wine_df.loc[:, 'region_1'])\n region_2_, region_unique_values = pd.factorize(wine_df.loc[:, 'region_2'])\n winery_, winery_unique_values = pd.factorize(\n wine_df.loc[:, 'winery'])\n points_, points_unique_values = pd.factorize(wine_df.loc[:, 'points'])\n\n wine_df['country_'] = country_\n wine_df['designation_'] = designation_\n wine_df['price_'] = price_\n wine_df['province_'] = province_\n wine_df['winery_'] = winery_\n wine_df['region1_'] = region_1_\n wine_df['region2_'] = region_2_\n wine_df['points_'] = points_\n\n wine_df = wine_df.drop(columns=['Unnamed: 0', 'country', 'designation', 'price',\n 'province', 'winery', 'region_1', 'region_2', 'points', 'variety'])\n\n DecisionTree(wine_df)\n GB(wine_df)\n KNN(wine_df)\n GNB(wine_df)\n\n\ndef main():\n print(\"****** Welcome to Location Analysis of Wine ****** \\n\")\n wine_dataset_without_region = loaddatasets(\"DataWithoutRegion2\")\n wine_dataset_with_region = loaddatasets(\"DatawithRegion2\")\n\n Analyze_withoutRegion = WithoutRegion2Analysis(wine_dataset_without_region)\n # Score with Decision Tree Classifier 0.23341313269493844\n # Score with Gradient Boosting 0.1629046967624259\n # Score with K-Nearest Neighbours 0.25216598267213863\n Analyze_withRegion = WithRegionAnalysis(wine_dataset_with_region)\n\n # Score with Decision Tree Classifier 0.2199272385870203\n # Score with Gradient Boosting 0.16289167938035443\n # Score with K-Nearest Neighbours 0.2242694519422603\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"rsehmbi/WineAnalysis","sub_path":"data_comparison/LocationReviews/Transform_Load_Analysis.py","file_name":"Transform_Load_Analysis.py","file_ext":"py","file_size_in_byte":6361,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"39374582171","text":"# requests 모듈 사용하기\r\n\r\nimport requests\r\n\r\n# sess = requests.Session()\r\n\r\n# res = sess.get(\"https://www.naver.com\")\r\n\r\n# print('1 : ', res.text)\r\n\r\n# print(f'Status Code : {res.status_code}')\r\n\r\n# # 상태코드를 이용해서 조건문에 활용할 경우\r\n# print(f'상태코드 확인 : {res.ok}')\r\n\r\n# sess.close()\r\n\r\n# with requests.Session() as sess:\r\n# res = sess.get(\"http://daum.net\")\r\n# print(res.text)\r\n# print(res.ok)\r\n\r\n\r\n# httpbin.org 사이트는 HTTP Methods, Auth(인증), Status codes를 테스트\r\n# 할 수 있는 사이트 중의 하나\r\n\r\nsess = requests.Session()\r\n\r\nres1 = sess.get('http://httpbin.org/cookies', cookies={\"name\": 'jhkim'})\r\nprint(res1.text)\r\n\r\n\r\nres2 = sess.get('http://httpbin.org/cookies/set', cookies={\"name\": 'jhkim'})\r\nprint(res2)\r\n\r\n\r\n# 가상의 User-Agent \r\nurl = 'http://httpbin.org/get'\r\nheaders = {'user-agent': 'jhkim_app_v1.000_home_chrome'}\r\n\r\nres3 = sess.get(url, headers=headers)\r\n\r\nprint(res3.text)\r\n\r\nsess.close()\r\n\r\n\r\n\r\n","repo_name":"codingq007/python","sub_path":"10_28_python_crawl/13_crawl_requests_rev.py","file_name":"13_crawl_requests_rev.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"21109127097","text":"from utils.DataProcessors import *\nfrom utils.gaze_utils import GazeData, GazeType\nfrom utils.general_utils import init_fifo_buffer_with_duration_sampling_rate, calculate_angular_dispersion, \\\n edge_ignore_linear_interpolation, angular_velocity_between_vectors_degrees\nfrom collections import deque\n\n\nclass GazeDataGapFilling(DataProcessor):\n\n def __init__(self, sampling_frequency=250,\n max_gap_duration=75,\n sampling_frequency_unit_duration_unit_scaling_factor=1000,\n invalid_flag=0):\n super().__init__()\n self.sampling_frequency = sampling_frequency\n self.max_gap_duration = max_gap_duration\n self.sampling_frequency_unit_duration_unit_scaling_factor = sampling_frequency_unit_duration_unit_scaling_factor\n self.max_gap_duration_in_seconds = max_gap_duration / sampling_frequency_unit_duration_unit_scaling_factor\n self.buffer_size = int(sampling_frequency * (\n self.max_gap_duration / self.sampling_frequency_unit_duration_unit_scaling_factor))\n self.invalid_flag = invalid_flag\n\n self._gaze_data_buffer = deque(maxlen=int(self.buffer_size))\n\n # self.gap_holding = False\n self.gap_head = 0\n self.gap_holding = False\n self.gap_buffer_full = False\n self.a = 0\n\n def process_sample(self, gaze_data: GazeData):\n '''\n\n :param gaze_data:\n :return: gaze data\n '''\n # self.a+=1\n # print(self.a)\n # if self.a == 13869:\n # pass\n # this is not filter with buffer, but just a gap filling # [ ->x x x x x] #\n self._gaze_data_buffer.appendleft(gaze_data)\n print(gaze_data.combined_eye_gaze_data.gaze_point_valid)\n\n if gaze_data.combined_eye_gaze_data.gaze_point_valid == 0:\n if self.gap_holding is False and self.gap_buffer_full is False: # no gap in the buffer\n self.gap_holding = True\n self.gap_head += 1\n elif self.gap_buffer_full is True: # if the gap buffer is full\n self.gap_head += 1\n elif self.gap_head + 1 == self.buffer_size: # if the gap is already full which means the last\n self.gap_buffer_full = True\n self.gap_holding = False\n self.gap_head += 1\n else:\n self.gap_head += 1\n else:\n if self.gap_holding is True and self.gap_buffer_full is False:\n if self._gaze_data_buffer[self.gap_head + 1].combined_eye_gaze_data.gaze_point_valid == 1:\n print('pad_gap' + str(self.gap_head + 1))\n self.gap_holding = False\n self.gap_head = 0\n elif self.gap_buffer_full is True:\n self.gap_buffer_full = False # reset the gap buffer the new available valid data becomes the head\n self.gap_head = 0\n\n return self._gaze_data_buffer[-1]\n\n\nclass GazeFilterFixationDetectionIDTAngular(DataProcessor):\n def __init__(self,\n sampling_frequency=250, duration=100,\n sampling_frequency_unit_duration_unit_scaling_factor=1000,\n angular_threshold_degree=1.2, dtype=np.float64):\n super().__init__()\n\n self.sampling_frequency = sampling_frequency\n self.duration = duration\n self.sampling_frequency_unit_duration_unit_scaling_factor = sampling_frequency_unit_duration_unit_scaling_factor\n self.angular_threshold_degree = angular_threshold_degree\n self.dtype = dtype\n\n self._gaze_data_buffer = None\n self.buffer_size = None\n self._gaze_vector_buffer = None\n\n def evoke_function(self):\n self.buffer_size = int(self.sampling_frequency * (\n self.duration / self.sampling_frequency_unit_duration_unit_scaling_factor))\n\n self._gaze_data_buffer = deque(maxlen=int(self.buffer_size))\n self._gaze_vector_buffer = deque(maxlen=int(self.buffer_size))\n\n def set_data_processor_params(self, sampling_frequency=250, duration=150,\n sampling_frequency_unit_duration_unit_scaling_factor=1000,\n angular_threshold_degree=1.5, dtype=np.float64):\n self.sampling_frequency = sampling_frequency\n self.duration = duration\n self.sampling_frequency_unit_duration_unit_scaling_factor = sampling_frequency_unit_duration_unit_scaling_factor\n self.angular_threshold_degree = angular_threshold_degree\n self.dtype = dtype\n\n def process_sample(self, gaze_data: GazeData):\n # centroid of the gaze data will be assigned\n self._gaze_data_buffer.appendleft(gaze_data)\n # self._gaze_vector_buffer.appendleft(gaze_data.combined_eye_gaze_data.gaze_direction)\n\n if gaze_data.combined_eye_gaze_data.gaze_point_valid:\n self._gaze_vector_buffer.appendleft(gaze_data.combined_eye_gaze_data.gaze_direction)\n else:\n # empty the buffer\n self._gaze_vector_buffer.clear()\n self._gaze_data_buffer.appendleft(gaze_data)\n\n if len(self._gaze_vector_buffer) == self.buffer_size:\n angular_dispersion = calculate_angular_dispersion(self._gaze_vector_buffer, self.dtype)\n if angular_dispersion <= self.angular_threshold_degree:\n gaze_data.gaze_type = GazeType.FIXATION\n else:\n gaze_data.gaze_type = GazeType.SACCADE\n else:\n gaze_data.gaze_type = GazeType.UNDETERMINED\n\n return gaze_data\n\n\nclass GazeFilterFixationDetectionIVT(DataProcessor):\n def __init__(self, angular_speed_threshold_degree=100):\n super().__init__()\n self.last_gaze_data = GazeData()\n self.angular_threshold_degree = angular_speed_threshold_degree\n\n def process_sample(self, gaze_data: GazeData):\n if self.last_gaze_data.combined_eye_gaze_data.gaze_point_valid:\n\n speed = angular_velocity_between_vectors_degrees(\n self.last_gaze_data.combined_eye_gaze_data.gaze_direction,\n gaze_data.combined_eye_gaze_data.gaze_direction,\n time_delta=gaze_data.timestamp - self.last_gaze_data.timestamp)\n # print(speed)\n if speed <= self.angular_threshold_degree:\n gaze_data.gaze_type = GazeType.FIXATION\n else:\n gaze_data.gaze_type = GazeType.SACCADE\n else:\n print('invalid gaze data')\n self.last_gaze_data = gaze_data\n\n return gaze_data\n","repo_name":"HaowenWeiJohn/illumiRead","sub_path":"utils/GazeFilter.py","file_name":"GazeFilter.py","file_ext":"py","file_size_in_byte":6557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"23629756718","text":"import xmltodict\nimport json\n\ndef get_image_locations(jsonfile):\n\t# get krystal images spritesheet coordinates\n\tlist = []\n\twith open(jsonfile, 'r') as f:\n\t\tj = json.load(f)\n\t\tfor i in range(len(j['frames'])):\n\t\t\tx = j['frames'][i]['frame']['x']\n\t\t\ty = j['frames'][i]['frame']['y']\n\t\t\tw = j['frames'][i]['frame']['w']\n\t\t\th = j['frames'][i]['frame']['h']\n\t\t\tlist.append((x, y, w, h))\n\treturn list\n\n\ndef get_krystal_offsets():\n\t# get krystal images spritesheet coordinates\n\tlist = []\n\twith open('assets/krystal_images/image_locations.json', 'r') as f:\n\t\tj = json.load(f)\n\t\tfor i in range(len(j['frames'])):\n\t\t\tx_off = j['frames'][i]['offset']['x_off']\n\t\t\ty_off = j['frames'][i]['offset']['y_off']\n\t\t\tlist.append((x_off))\n\treturn list\n\n","repo_name":"biglukefish/krystallion","sub_path":"imaging.py","file_name":"imaging.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"12185124812","text":"import pandas as pd\nfrom flask import Flask, jsonify, render_template\n\ndf = pd.read_excel(\"data_best_sells.xlsx\")\n\n\ndef get_articles():\n articles = df[['Article Name', 'Nr of Orders']].to_dict('records')\n print(articles)\n\nget_articles()","repo_name":"testingpurposesite/fyndiq-app","sub_path":"test_one.py","file_name":"test_one.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"36262222587","text":"\n# -*- coding: utf-8 -*-\nimport os\nimport requests\nfrom lxml import html\n\nheards = {\n 'Host': 'www.zhihu.com',\n 'Accept-Languge': 'zh-CN,zh;q=0.8,en;q=0.6',\n 'Connection': 'keep-alive',\n 'Pragma': 'no-cache',\n 'Cach-Control': 'no-cache',\n 'Upgrade-Insecure-Resquests': '1',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4)'\n 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',\n}\n\ndef save(text, filename='temp', path='download'):\n fpath = os.path.join(path,filename)\n with open(fpath,'w') as f:\n print('output',fpath)\n f.write(text)\n\ndef save_image(image_url):\n resp = requests.get(image_url)\n page = resp.content\n filename = image_url.split('zhimg.com/')[-1]\n save(page, filename)\n\ndef crawl(url):\n resp = requests.get(url, headers=headers)\n page = resp.content\n root = html.fromstring(page)\n print (root)\n image_urls = root.xpath('//img[@data-original]/@data-original')\n for image_url in image_urls:\n save_image(image_url)\n\n url = 'http://www.zhihu.com/question/27364360'\n crawl(url)\n","repo_name":"tangmengbo/python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"15711338038","text":"from collections import defaultdict\n\na = [0, 0, 0, 1, 2, 5, 0, 0, 2]\n\n# build a hash map to store this data structure, but avoid storing 0\n# and you will need to able to access the value inside the data structure\n# like a[0] = 0, a[3] = 1\n\nDICT_SIZE = 4\n\n\ndef convert_list_into_dict(array):\n hash = defaultdict(dict)\n for index, value in enumerate(array):\n if value: # ignore zero\n global_index = index % DICT_SIZE\n hash[global_index][index] = value\n return hash\n\n\ndef get_value_from_hash(hash, position):\n global_index = position % DICT_SIZE\n if global_index in hash.keys() and position in hash[global_index].keys():\n return hash[global_index][position]\n return 0\n\n\nhash = convert_list_into_dict(a)\nprint(hash)\nfor i in range(len(a)):\n assert a[i] == get_value_from_hash(\n hash, i\n ), f\"position={i}, a[{i}]={a[i]}, hash[{i}]={get_value_from_hash(a, i)}\"\n","repo_name":"neong83/algorithm_practices","sub_path":"ex04 - best data structure for array with many zeros.py","file_name":"ex04 - best data structure for array with many zeros.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"21327383029","text":"from django.urls import path, include\nfrom .views import *\nfrom django.contrib.auth.views import LogoutView\n\nurlpatterns = [\n path('', home, name=\"home\" ),\n path('servicios/', ServicioList.as_view(), name=\"servicios\" ),\n path('create_servicio/', ServicioCreate.as_view(), name=\"create_servicio\" ),\n path('update_servicio//', ServicioUpdate.as_view(), name=\"update_servicio\" ),\n path('delete_servicio//', ServicioDelete.as_view(), name=\"delete_servicio\" ),\n path('vehiculos/', VehiculoList.as_view(), name=\"vehiculos\" ),\n path('create_vehiculo/', VehiculoCreate.as_view(), name=\"create_vehiculo\" ),\n path('update_vehiculo//', VehiculoUpdate.as_view(), name=\"update_vehiculo\" ),\n path('delete_vehiculo//', VehiculoDelete.as_view(), name=\"delete_vehiculo\" ),\n path('productos/', ProductoList.as_view(), name=\"productos\" ),\n path('create_producto/', ProductoCreate.as_view(), name=\"create_producto\" ),\n path('update_producto//', ProductoUpdate.as_view(), name=\"update_producto\" ),\n path('delete_producto//', ProductoDelete.as_view(), name=\"delete_producto\" ),\n path('login/', loguearse, name=\"login\" ),\n path('registro/', registrarse, name=\"registro\" ),\n path('logout/', LogoutView.as_view(template_name=\"aplicacion/logout.html\"), name=\"logout\" ),\n path('editar_usuario/', editarUsuario, name=\"editar_usuario\" ),\n path('agregar_avatar/', agregarAvatar, name=\"agregar_avatar\" ),\n path('acerca_de', acercaDe, name=\"acerca_de\" ),\n]","repo_name":"WaldoGaspari/Gaspari_Waldo_55630","sub_path":"aplicacion/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"69816827570","text":"# 设计师:Pan YuDong\n# 编写者:God's hand\n# 时间:2022/6/28 20:00\nimport os\nimport pandas as pd\nimport math\nimport xxhash\nfrom operator import itemgetter\nfrom collections import defaultdict\n\nclass UserbasedCF():\n '''TopN recommendation - User Based Collaborative Filtering'''\n def __init__(self):\n self.train_dataset = {}\n self.test_dataset = {}\n\n self.n_sim_user = 20 # number of similar users\n self.n_rec_item = 10 # number of recommend items\n\n self.user_sim_mat = {}\n self.item_popular = {}\n self.item_count = 0\n\n print(f\"similar user number {self.n_sim_user}\")\n print(f\"recommended item number {self.n_rec_item}\")\n\n @staticmethod\n def loadfile(filename):\n '''load a file, return a generator'''\n fp = open(filename, 'r')\n for i, line in enumerate(fp):\n yield line.strip('\\r\\n')\n if i % 100000 == 0:\n print(f\"loading {filename}, {i}\")\n fp.close()\n print(f'load{filename} success')\n\n def generate_dataset(self, filename, pivot=0.7):\n '''load data and split it to training dataset and test dataset'''\n train_dataset_len = 0\n test_dataset_len = 0\n\n raw_dataset = self.loadfile(filename)\n for line in raw_dataset:\n user, item, has_star = line.split(',')\n unique_id = user + item\n encoder_id = xxhash.xxh32(unique_id).intdigest()\n # split the data by pivot\n if encoder_id % 100 < int(pivot * 100):\n self.train_dataset.setdefault(user, {})\n self.train_dataset[user][item] = has_star\n train_dataset_len += 1\n else:\n self.test_dataset.setdefault(user, {})\n self.test_dataset[user][item] = has_star\n test_dataset_len += 1\n\n print('split training dataset and test dataset success')\n print(f'length of training dataset: {train_dataset_len}')\n print(f'length of test dataset: {test_dataset_len}')\n\n\n def calc_user_sim(self):\n '''calculate user similarity matrix'''\n # build inverse table for item-users\n # key = itemID, value = list of userIDs who have seen this item\n print('building item-users inverse table...')\n item2users = dict()\n\n for user, items in self.train_dataset.items():\n for item in items:\n # inverse table for item-users\n if item not in item2users:\n item2users[item] = set() # make sure no repeated users\n item2users[item].add(user)\n # count item popularity at the same time\n if item not in self.item_popular:\n self.item_popular[item] = 0\n self.item_popular[item] += 1\n print('build item-users inverse table success')\n\n # save the total item number, which will be used in evaluation phase\n self.item_count = len(item2users)\n print(f'total item number {self.item_count}')\n\n # count co-related matrix between users\n user_sim_mat = self.user_sim_mat\n print('building user co-related item matrix')\n\n for item, users in item2users.items():\n for u in users:\n user_sim_mat.setdefault(u, defaultdict(int))\n for v in users:\n if u == v:\n continue\n user_sim_mat[u][v] += 1\n print('build user co-related item matrix success')\n\n # calculate similarity matrix\n print('calculating user similarity matrix...')\n sim_factor_count = 0\n PRINT_STEP = 200000\n\n for u, related_users in user_sim_mat.items():\n for v, count in related_users.items():\n user_sim_mat[u][v] = count / math.sqrt(len(self.train_dataset[u]) * len(self.train_dataset[v]))\n sim_factor_count += 1\n if sim_factor_count % PRINT_STEP == 0:\n print(f'calculating user similarity factor {sim_factor_count}')\n\n print('calculate user similarity matrix success')\n print(f'Total similarity factor number {sim_factor_count}')\n\n\n def recommend(self, user):\n '''Find K similar users and recommend N items'''\n K = self.n_sim_user\n N = self.n_rec_item\n rank = dict()\n watched_items = self.train_dataset[user]\n # print(\"watched_items:\", watched_items)\n # print(\"similar_user:\", sorted(self.user_sim_mat[user].items(), key=itemgetter(1), reverse=True)[0:K])\n\n for similar_user, similar_factor in sorted(self.user_sim_mat[user].items(), key=itemgetter(1), reverse=True)[0:K]:\n for item in self.train_dataset[similar_user]:\n if item in watched_items:\n continue\n # predict the user's interest for each item\n rank.setdefault(item, 0)\n rank[item] += similar_factor\n\n # print(\"rank:\", rank)\n\n # return N best items\n return sorted(rank.items(), key=itemgetter(1), reverse=True)[0:N]\n\n\n def evaluate(self, root):\n '''print evaluation measurement:precision, recall, coverage and popularity'''\n print('Evaluation Start...')\n df_user = pd.read_csv(os.path.join(root, 'users.csv'))\n df_project = pd.read_csv(os.path.join(root, 'projects.csv'))\n user_dict = df_user['name'].to_dict()\n project_dict = df_project['name'].to_dict()\n # print(\"item_popular:\", self.item_popular)\n\n N = self.n_rec_item\n # variable for precision and recall\n hit = 0\n rec_count = 0\n test_count = 0\n # variable for coverage\n all_rec_items = set()\n # variables for popularity\n popular_sum = 0\n\n empty_user = []\n for i, user in enumerate(self.train_dataset):\n if i % 500 == 0:\n print(f'recommend for {i} users')\n test_items = self.test_dataset.get(user, {}) # if user doesn't exist in test dataset, return {}\n rec_items = self.recommend(user)\n\n if i % 100 == 0:\n rec_projects = [project_dict[int(j[0])] for j in rec_items]\n print(f\"recommended projects for user {user_dict[i]}: {rec_projects}\")\n\n if len(rec_items) == 0:\n empty_user.append(user)\n\n for item, _ in rec_items:\n if item in test_items:\n hit += 1\n all_rec_items.add(item)\n popular_sum += math.log(1 + self.item_popular[item])\n rec_count += N\n test_count += len(test_items)\n\n # The ratio of the user's favorite products to all recommended products in the system's recommended list\n precision = 1.0 * hit / rec_count\n # The ratio of products that users like in the recommendation list to all products that users like in the system\n recall = 1.0 * hit / test_count\n # Describe the ability of a recommendation system to mine the long tail of an item\n coverage = 1.0 * len(all_rec_items) / self.item_count\n # Popularity bias\n popularity = 1.0 * popular_sum / rec_count\n\n print(f'precision={precision:.4f}, recall={recall:.4f}, coverage={coverage:.4f}, '\n f'popularity={popularity:.4f}')\n\n print(\"empty_user:\", empty_user)\n\n\n\n\n","repo_name":"YuDongPan/Github_Recommendation","sub_path":"Model/UbCF.py","file_name":"UbCF.py","file_ext":"py","file_size_in_byte":7417,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"20"} +{"seq_id":"26714947216","text":"import sys\nfrom itertools import permutations\n\nsys.stdin = open('input.txt', 'r')\n\nglobal shortest\n\n# 아직 연결 안된것들 중 선택지가 가장 적은것 부터 해버려야할것 같은데?\n# 이걸 매 반복마다 검색해야겠다\n# def route_num(pm:int):\n# # 아직 연결 안된 core1, core2, core3, core4... 이런 순서대로 cores에 저장되어있음\n# core_dict = {}\n# for i in range(len(cores)):\n# core_dict[i] = []\n#\n# # 각 코어마다 방향 찾기\n# for i in range(len(cores)):\n# cur_r, cur_c = cores[i]\n# direction_cnt = 0\n# way = []\n# # 4방으로 봄\n# for j in range(4):\n# # 해당 방향이 뚫려있는지 확인\n# length = 1\n# while length < N+2:\n# nr = cur_r + dr[j]*length\n# nc = cur_c + dc[j]*length\n# # 만약 다른 코어를 만남\n# if matrix[nr][nc] == 1:\n# break\n# # 연결 가능\n# if matrix[nr][nc] == 2:\n# way.append(j)\n# direction_cnt += 1\n# break\n# # 아직 모름\n# if matrix[nr][nc] == 0:\n# length += 1\n# # 몇가지로 연결 가능한지랑 어디로 가야하는지도 넣자\n# # 연결 가능성이 0이면 안넣음\n# if direction_cnt == 0:\n# continue\n# core_dict[i].append([direction_cnt,way])\n# return core_dict\n\n\n\n# 그냥 순열조합으로 하자\ndef connect_cores(cores:list):\n total = 0\n while cores:\n cur_core = cores.pop()\n cur_shortest = N+2\n for i in range(4):\n ans = shortest_connected(cur_core[0], cur_core[1],i)\n if ans:\n if ans < cur_shortest:\n cur_shortest = ans\n\n total += cur_shortest\n return total\n\n\ndef shortest_connected(r, c, i):\n length = 1\n trail = []\n while length < N+2:\n nr = r + dr[i] * length\n nc = r + dc[i] * length\n\n # 전선 안겹침\n if matrix[nr][nc] == 0:\n matrix[nr][nc] = 1\n trail.append([nr,nc])\n length += 1\n # 길에 다른 코어 존재\n elif matrix[nr][nc] == 1:\n # 왔던 길을 다시 0으로 칠해줘야함\n while trail:\n fix_r, fix_c = trail.pop()\n matrix[fix_r][fix_c] = 0\n return 0\n elif matrix[nr][nc] == 2:\n return length\n\n\n\n# 순열 조합중에 가장 연결 많이 되는것 구하고 그것의 최소 거리를 구하면 되는거 아님?\n \nfor tc in range(1, int(input())+1):\n N = int(input())\n matrix = []\n matrix.append([2 for _ in range(N+2)])\n for _ in range(N):\n matrix.append([2]+list(map(int, input().split()))+[2])\n matrix.append([2 for _ in range(N+2)])\n shortest = N*N\n \n #print(matrix)\n\n # 최대한 많은 core를 전원에 연결하였을 경우\n # 전원이 연결되지 않는 core가 있을 수 있다.\n # 전선은 직선만 가능\n # 전선 길이의 최소\n # N-queens?\n\n # visited = [[0 for _ in range(N + 2)] for _ in range(N + 2)]\n\n # 전체 코어 찾기 + 이미 연결된 코어는 표시-> 아직 연결 안된 코어들만 찾기\n cores = []\n for i in range(N+2):\n for j in range(N+2):\n if matrix[i][j]==1:\n if j == 1 or j == N: # 가장 왼쪽 혹은 오른쪽의 코어들\n # visited[i][j] = 1\n continue\n if i == 1 or i == N: # 가장 윗줄에 있는 코어들\n # visited[i][j] = 1\n continue\n\n # 가장자리가 아닌 코어들\n cores.append([i,j])\n\n # delta 상하좌우\n dr = [-1, 1, 0, 0]\n dc = [0, 0, -1, 1]\n\n # 순열\n pm = list(permutations(cores, len(cores)))\n\n for i in range(len(pm)):\n ans = connect_cores(list(pm[i]))\n if ans < shortest:\n shortest = ans\n\n print(shortest)\n\n\n\n","repo_name":"alpaka99/algorithm","sub_path":"A형_test/전원연결/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":4139,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"28743209820","text":"import numpy as np\nimport cv2\nimport collections\nfrom PIL import Image\n\n\ndef replace_color(img, dst_clr):\n '''\n 通过矩阵操作颜色替换程序\n @param\timg:\t图像矩阵\n @param\tsrc_clr:\t需要替换的颜色(r,g,b)\n @param\tdst_clr:\t目标颜色\t\t(r,g,b)\n @return\t\t\t\t替换后的图像矩阵\n '''\n\n img_arr = np.asarray(img, dtype=np.double)\n r_img = img_arr[:, :, 0].copy()\n g_img = img_arr[:, :, 1].copy()\n b_img = img_arr[:, :, 2].copy()\n\n r_img[0 == 0] = dst_clr[0]\n g_img[0 == 0] = dst_clr[1]\n b_img[0 == 0] = dst_clr[2]\n dst_img = np.array([r_img, g_img, b_img], dtype=np.uint8)\n dst_img = dst_img.transpose(1, 2, 0)\n\n return dst_img\n\n\ndef color_dict():\n color_dict = collections.defaultdict(list)\n color_dict['orange'] = [0, 102, 255]\n color_dict['red'] = [102, 0, 255]\n color_dict['red2'] = [102, 0, 255]\n color_dict['yellow'] = [0, 255, 204]\n color_dict['green'] = [0, 255, 51]\n color_dict['cyan'] = [255, 204, 0]\n color_dict['blue'] = [255, 0, 0]\n return color_dict\n\n\ndef image_compose(color_arr):\n '''\n :param color_arr:\n :return:\n '''\n img = np.zeros([16, 16, 3], np.uint8)\n colors_dict = color_dict()\n image_column = len(color_arr) # 行数\n image_row = len(color_arr[0]) # 列数\n n_image1 = []\n n_image2 = []\n for x in range(image_column):\n for y in range(image_row):\n if color_arr[x][y] in colors_dict:\n small_img = replace_color(img, colors_dict.get(color_arr[x][y]))\n else:\n small_img = replace_color(img, colors_dict.get('green'))\n n_image1.append(small_img)\n im1_ = np.concatenate(n_image1, axis=1) # 横向拼接\n n_image1 = []\n n_image2.append(im1_)\n new_img = np.concatenate(n_image2, axis=0) # 纵向拼接\n return new_img\n\n\nif __name__ == '__main__':\n color_arr = [['blue', 'green','green'],\n ['red', 'blue','green'],\n ['blue', 'green', 'green']]\n im2 = image_compose(color_arr)\n cv2.imshow('', im2)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n im2 = Image.fromarray(im2)\n # im2.save('../output/im.jpg')\n colors_dict = color_dict()\n if 'res' in colors_dict:\n print(colors_dict)","repo_name":"LuWei091997/Project_for_BHF","sub_path":"tools_for_image/creat_similar_image.py","file_name":"creat_similar_image.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"22033545592","text":"'''\nHMAC scheme consists of an inner and outer hash.\n\nMD5 example from RFC 2104.\n\nhttps://datatracker.ietf.org/doc/html/rfc2104\n\nHMACk(x) = h[ (k+ XOR opad) || h[(k+ XORed ipad) || x] ]\n'''\nfrom hashlib import md5\n\ndef hmac_md5(key, text):\n '''\n hmac_md5(key=\"Jefe\", text=\"what do ya want for nothing?\")\n\n key = \"Jefe\"\n data = \"what do ya want for nothing?\"\n data_len = 28 bytes\n digest = 0x750c783e6ab0b503eaa86e310a5db738\n\n returns 750c783e6ab0b503eaa86e310a5db738\n '''\n B = 64 # Block byte length\n ipad = b'\\x36' * B # ipad = the byte 0x36 repeated B times\n opad = b'\\x5c' * B # opad = the byte 0x5C repeated B times\n # 1. Append zeros to the end of the key to create a B=64 byte string\n key_bytes = key.encode().ljust(B, b'\\0')\n # 2. XOR (bitwise exclusive-OR) the B=64 byte string computed in step (1) with ipad\n bitwise_ipad_bytes = bytes([a ^ b for (a, b) in zip(ipad, key_bytes)])\n # 3. Append the stream of data 'text' to the B=64 byte string resulting from step (2)\n inner_data = bitwise_ipad_bytes + text.encode()\n # 4. Apply hashing to the stream generated in step (3)\n inner_hash = md5(inner_data).digest()\n # 5. XOR (bitwise exclusive-OR) the B=64 byte string computed in step (1) with opad\n bitwise_opad_bytes = bytes([a ^ b for (a, b) in zip(opad, key_bytes)])\n # 6. Append the hashing result from step (4) to the B=64 byte string resulting from step (5)\n outer_data = bitwise_opad_bytes + inner_hash\n # 7. Apply hashing to the stream generated in step (6) and output the result\n outer_hash = md5(outer_data).digest()\n # Finally, return the hex value of the HMAC hash\n return outer_hash.hex()\n\ndef main():\n ''' Testing HMAC '''\n # Use the example from the RFC 2104\n message = \"what do ya want for nothing?\"\n key = \"Jefe\"\n print('Message: ' + message)\n print('Secret shared key: ' + key)\n # Calculate the hmac md5 value\n hmac_value = hmac_md5(key, message)\n print('HMAC: ' + hmac_value)\n # Test that the function returns the correct value\n expected_result = '750c783e6ab0b503eaa86e310a5db738'\n assert hmac_value == expected_result\n\nif __name__ == '__main__':\n main()\n","repo_name":"juhanurmi/cryptography","sub_path":"hmac/hmac.py","file_name":"hmac.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"20"} +{"seq_id":"5636430107","text":"#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nimport sys\nimport math\nimport matplotlib\n\nargs = sys.argv[1]\nnum_args = len(args)\n\nmatplotlib.rcParams['axes.linewidth'] = 3\n\ndf = pd.read_csv(args,sep='\\t',header=None)\ndfsorted = df[::-1]\n\nlength_of_complex = len(df[0])\n\nfig, ax = plt.subplots(figsize=(15,15), dpi=300)\n\nfont = {'weight' : 'bold',\n\t'size' : 28}\nmatplotlib.rc('font', **font)\n\nN=256\nvals = np.ones((N,4))\nvals[0:26, 2] = np.linspace(0.5,1,26)\nvals[27:132, 2] = 1\nvals[132:178, 2] = np.linspace(0.89,0,46)\nvals[178:256, 2] = 0\n\nvals[0:26, 1] = 0\nvals[26:108, 1] = np.linspace(0,1,82)\nvals[108:148, 1] = 1\nvals[148:230, 1] = np.linspace(1,0,82)\nvals[229:256, 1] = 0\n\nvals[0:78, 0] = 0\nvals[78:124, 0] = np.linspace(0,1,46)\nvals[124:229, 0] = 1\nvals[229:256, 0] = np.linspace(1,0.5,27)\nnewcmp = matplotlib.colors.ListedColormap(vals)\n\nhm = sns.heatmap(dfsorted, cmap=newcmp,center=0,square=True, cbar_kws={\"shrink\": 0.5})\ncbar = ax.collections[0].colorbar\ncbar.ax.tick_params(labelsize=15)\ncbar.set_ticks([-0.99, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1])\ncbar.set_ticklabels([\"-1.00\",\"-0.75\",\"-0.50\",\"-0.25\",\"0\", \"0.25\", \"0.50\", \"0.75\", \"1.00\"])\nif length_of_complex==1248:\n\tdom = [227,489,624,(624+227),(624+489)]\n\tdomainname = [r'NTD$_{(GA)}$', r'MD$_{(GA)}$', r'CTD$_{(GA)}$', r'NTD$_{(GB)}$', r'MD$_{(GB)}$', r'CTD$_{(GB)}$']\n\tdomaincolor = ['gold', 'forestgreen', 'blue', 'gold', 'forestgreen', 'blue']\n\tplt.yticks([48,248,448,648,848,1048,1248],[1200,1000,800,600,400,200,0], fontsize = 25, weight='bold')\n\tplt.xticks([0,200,400,600,800,1000,1200],np.arange(0,1201,step=200),rotation=45, fontsize = 25, weight='bold')\nelif length_of_complex==1357:\n\tdom = [390,510,605,(605+110),(605+254),(376+605),(376+605+110),(376+605+254)]\n\tdomainname = [r'NBD$_{(K)}$', r'SBD$\\beta_{(K)}$', r'SBD$\\alpha_{(K)}$', r'JD$_{(JA)}$', r'CTDI$_{(JA)}$', r'CTDII$_{(JA)}$ ', r'JD$_{(JB)}$', r'CTDI$_{(JB)}$', r'CTDII$_{(JB)}$']\n\tdomaincolor = ['grey','red','salmon','cyan','violet','purple','cyan','violet','purple']\n\tplt.xticks([0,200,400,600,800,1000,1200],np.arange(0,1301,step=200),rotation=45, fontsize = 25, weight='bold')\n\tplt.yticks([57,257,457,657,857,1057,1257],[1200,1000,800,600,400,200,0], fontsize = 25, weight='bold')\nelif length_of_complex==923:\n\tdom = [390,510,605,605+159]\n\tdomainname = [r'NBD$_{(K)}$', r'SBD$\\beta_{(K)}$', r'SBD$\\alpha_{(K)}$', r'GrpE$_{(A)}$', r'GrpE$_{(B)}$']\n\tdomaincolor = ['grey','red','salmon','orange','orange']\n\tplt.xticks([0,200,400,600,800],np.arange(0,901,step=200),rotation=45, fontsize = 25, weight='bold')\n\tplt.yticks([23,223,423,623,823],[800,600,400,200,0], fontsize = 25, weight='bold')\nelif length_of_complex==1853 and \"dnakatend\" not in args:\n\tdom = [227,489,624,(624+227),(624+489),1248,(1248+390),(1248+510)]\n\tdomainname = [r'NTD$_{(GA)}$', r'MD$_{(GA)}$', r'CTD$_{(GA)}$', r'NTD$_{(GB)}$', r'MD$_{(GB)}$', r'CTD$_{(GB)}$', r'NBD$_{(K)}$', r'SBD$\\beta_{(K)}$', r'SBD$\\alpha_{(K)}$']\n\tdomaincolor = ['gold', 'forestgreen', 'blue', 'gold', 'forestgreen', 'blue', 'grey', 'red', 'salmon']\n\tplt.xticks(np.arange(0,1853,step=200),np.arange(0,1853,step=200),rotation=45, fontsize = 25, weight='bold')\n\tplt.yticks([53,253,453,653,853,1053,1253,1453,1653,1853],[1800,1600,1400,1200,1000,800,600,400,200,0], fontsize = 25, weight='bold')\nelif length_of_complex==1853 and \"dnakatend\" in args:\n\tdom = [227,489,624,(624+227),(624+489),1248,(1248+390),(1248+510)]\n\tdomainname = [r'NTD$_{(GA)}$', r'MD$_{(GA)}$', r'CTD$_{(GA)}$', r'NTD$_{(GB)}$', r'MD$_{(GB)}$', r'CTD$_{(GB)}$', r'NBD$_{(K)}$', r'SBD$\\beta_{(K)}$', r'SBD$\\alpha_{(K)}$']\n\tdomaincolor = ['gold', 'forestgreen', 'blue', 'gold', 'forestgreen', 'blue', 'grey', 'red', 'salmon']\n\tplt.xticks(np.arange(0,1853,step=200),np.arange(0,1853,step=200),rotation=45, fontsize = 25, weight='bold')\n\tplt.yticks([53,253,453,653,853,1053,1253,1453,1653,1853],[1800,1600,1400,1200,1000,800,600,400,200,0], fontsize = 25, weight='bold')\nelif length_of_complex==2458:\n\tdom = [227,489,624,(624+227),(624+489),1248,(1248+390),(1248+510),1853,(1853+390),(1853+510)]\n\tdomainname = [r'NTD$_{(GA)}$', r'MD$_{(GA)}$', r'CTD$_{(GA)}$', r'NTD$_{(GB)}$', r'MD$_{(GB)}$', r'CTD$_{(GB)}$', r'NBD$_{(KA)}$', r'SBD$\\beta_{(KA)}$', r'SBD$\\alpha_{(KA)}$', r'NBD$_{(KB)}$', r'SBD$\\beta_{(KB)}$', r'SBD$\\alpha_{(KB)}$']\n\tdomaincolor = ['gold', 'forestgreen', 'blue', 'gold', 'forestgreen', 'blue', 'grey', 'red', 'salmon', 'grey', 'red', 'salmon']\n\tplt.xticks(np.arange(0,2458,step=200),np.arange(0,2458,step=200),rotation=45, fontsize =25, weight = 'bold')\n\tplt.yticks([58,258,458,658,858,1058,1258,1458,1658,1858,2058,2258,2458],[2400,2200,2000,1800,1600,1400,1200,1000,800,600,400,200,0], fontsize = 25, weight = 'bold')\nelif length_of_complex==605:\n\tdom = [390,510]\n\tdomainname = [r'NBD$_{(K)}$', r'SBD$\\beta_{(K)}$', r'SBD$\\alpha_{(K)}$']\n\tdomaincolor = ['grey', 'red', 'salmon']\n\tplt.xticks(np.arange(0,601,step=100),np.arange(0,601,step=100),rotation=45, fontsize = 25, weight='bold')\n\tplt.yticks([5,205,405,605],[600,400,200,0], fontsize = 25, weight='bold')\nelif length_of_complex==604:\n\tdom = [390,510]\n\tdomainname = [r'NBD$_{(K)}$', r'SBD$\\beta_{(K)}$', r'SBD$\\alpha_{(K)}$']\n\tdomaincolor = ['grey', 'red', 'salmon']\n\tplt.xticks(np.arange(0,601,step=100),np.arange(0,601,step=100),rotation=45, fontsize = 25, weight='bold')\n\tplt.yticks([4,204,404,604],[600,400,200,0], fontsize = 25, weight='bold')\nelif length_of_complex==624:\n\tdom = [227,489]\n\tdomainname = ['NTD', 'MD', 'CTD', 'NTD', 'MD', 'CTD']\n\tdomaincolor = ['gold', 'forestgreen', 'blue']\nelse:\n\tdom = []\n\tprint(length_of_complex, \"is not an expected number of residues\")\n\ndominv=[]\nif len(dom)>0:\n\tax.text(length_of_complex,(-0.002*length_of_complex),f\"{length_of_complex-dom[-3]}\",ha='center', fontsize = 12)\n\tfor i in range(len(dom)):\n\t\tif i == 0:\n\t\t\tax.text(dom[i]/2,(-0.03*length_of_complex), \"{}\".format(domainname[i]),ha='left', rotation=45, color=f\"{domaincolor[i]}\")\n\t\t\tprint(\"first domain --> {} {} {}\".format(dom[i], domainname[i], domaincolor[i]))\n\t\telif dom[i] == dom[-1]:\n\t\t\tax.text((dom[i]+dom[i-1])/2, (-0.03*length_of_complex), \"{}\".format(domainname[i]),ha='left',rotation=45, color=f\"{domaincolor[i]}\")\n\t\t\tax.text((dom[i]+length_of_complex)/2, (-0.03*length_of_complex), \"{}\".format(domainname[i+1]), rotation=45, color=f\"{domaincolor[i+1]}\")\n\t\t\tprint(\"This is the {} domain --> {} {} {}\".format(i, dom[i], domainname[i], domaincolor[i]))\n\t\t\tprint(\"{} domain --> {} {} {}\".format(i+1, dom[i], domainname[i+1], domaincolor[i+1]))\n\t\telse:\n\t\t\thac = 'left'\n\t\t\tax.text((dom[i]+dom[i-1])/2, (-0.03*length_of_complex), \"{}\".format(domainname[i]),ha=hac, color=f\"{domaincolor[i]}\", rotation=45)\n\t\t\tprint(\"{} domain --> {} {} {}\".format(i, dom[i], domainname[i], domaincolor[i]))\n\t\tif dom[i] < 624:\n\t\t\tax.text(dom[i],(-0.002*length_of_complex),f\"{dom[i]}\", ha='center', fontsize = 12)\n\t\telif 624 <= dom[i] < 1248:\n\t\t\tax.text(dom[i], (-0.002*length_of_complex),f\"{dom[i] - 624}\", ha='center', fontsize = 12)\n\t\telif 1248 <= dom[i] < 1853:\n\t\t\tax.text(dom[i], (-0.002*length_of_complex),f\"{dom[i] - 1248}\", ha='center', fontsize = 12)\n\t\telif 1853 <= dom[i] < 2458:\n\t\t\tax.text(dom[i], (-0.002*length_of_complex),f\"{dom[i] - 1853}\", ha='center', fontsize = 12)\n\t\tdominv.append(abs(dom[i]-length_of_complex))\n\t\tdominv.sort()\n\tax.vlines(dom, 0, length_of_complex, linewidth=5, color='k')\n\tax.hlines(dominv, 0, length_of_complex, linewidth=5,color='k')\n\nplt.xlabel('Residue Number', fontsize=24, weight = 'bold')\nplt.ylabel('Residue Number', fontsize=24, weight = 'bold')\nax.tick_params(direction='out', length=8, width=4)\nprint(dom, dominv, length_of_complex)\n\nplt.savefig(f\"{args[:-4]}.png\")\n","repo_name":"grindlm/basicprograms","sub_path":"corrcov.py","file_name":"corrcov.py","file_ext":"py","file_size_in_byte":7706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"27023729626","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Project\nfrom .forms import ProjectForm\n\n\n@login_required\ndef index(request):\n\tcontext = {}\n\treturn render(request, 'base.html', context)\n\n\ndef add_project(request):\n\tcontext = {}\n\tif request.method == 'POST':\n\t\tproject_form = ProjectForm(request.POST)\n\t\tif project_form.is_valid():\n\t\t\tproject_form.save()\n\t\t\treturn redirect('/')\n\telse:\n\t\tproject_form = ProjectForm()\n\tcontext.update({'project_form': project_form})\n\treturn render(request,'projects/add_project.html', context)\n\n\n","repo_name":"jelukas/greekey_crm","sub_path":"greekey/projects/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"37059430897","text":"import torch\nfrom diffusers import StableDiffusionPipeline\n\n# pip install diffusers\n\nmodel_ckpt = \"CompVis/stable-diffusion-v1-4\"\ndevice = \"mps\" # cuda, cpu, mps\nweight_dtype = torch.float16\n\npipe = StableDiffusionPipeline.from_pretrained(model_ckpt, torch_dtype=weight_dtype)\npipe = pipe.to(device)\n\nprompt = \"a photograph of an astronaut riding a horse\"\nimage = pipe(prompt).images[0]\nimage.save(\"simple_results.png\")","repo_name":"taki0112/diffusion-pytorch","sub_path":"src/stable_diffusion/sd_simple_main.py","file_name":"sd_simple_main.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"20"} +{"seq_id":"72633564528","text":"from __future__ import division # holy crap, python\nimport collections\nimport sys\nimport re\nimport urllib2\nimport json\nimport hive\nimport operator\nimport os\nfrom lifter import Lifter\nfrom settings import *\n\nclass AddonBangForBuck(Lifter):\n \"\"\"This lifter determines which add-ons to target for a particular purpose\n in order to get to 80% of Firefox users.\"\"\"\n \n def lift(self):\n # Make output directory and index\n self.make_dir()\n # Get data\n hive_file = self.hive_data()\n # Get Firefox ADU\n adu = self.get_adu()\n # Get add-on names\n self.addon_names = self.cache_addon_names()\n # Filter add-on combinations from HIVE\n combos = self.filter_combos(hive_file)\n # Calculate and output results\n data = self.calculate_bfb(combos, adu)\n \n self.hive_cleanup(hive_file)\n \n def make_dir(self):\n self.data_path = FILES + '/bfb/' + self.date\n os.mkdir(self.data_path)\n \n f = open(self.data_path + '/index.html', 'w')\n \n f.write(\"\"\"\n

High Value Add-on Targets Report - {date}

\n

In certain situations, we want to know which add-ons to target in \n order to cover the highest number of Firefox users. In order for a user \n to be covered, all of the add-ons they have installed must be targeted. \n This report looks at what add-ons, if targeted, would account for 80% \n of Firefox users.

\n \n

To obtain this data, we look at the add-ons a user has installed and \n group together combinations, e.g. 10000 people have Skype Toolbar and \n Adblock Plus installed. When have a list of the top combinations, we go \n down it, pulling out the add-ons until we reach 80% of Firefox's ADU for \n that day.

\n \n

We then have a list of the unique add-on GUIDs that, if targeted, \n would cover 80% of Firefox users in the most effective way.

\n \n

These reports are CONFIDENTIAL.

\n \n
\n \"\"\".format(date=self.date))\n \n f.close()\n \n def hive_data(self):\n \"\"\"Performs a HIVE query and writes it to a text file.\"\"\"\n \n if HIVE_ALTERNATE is not None:\n self.log('Hive alternate file used')\n return HIVE_ALTERNATE\n \n self.log('Starting HIVE query...')\n hive_file = hive.query(\"\"\"SELECT guid, COUNT(1) as num \n FROM addons_pings WHERE ds = '{date}' AND src='firefox' AND \n guid LIKE '%972ce4c6-7e08-4474-a285-3208198ce6fd%' \n GROUP BY guid HAVING num > 1 ORDER BY num DESC;\"\"\".format(date=self.date))\n \n self.time_event('hive_data')\n self.log('HIVE data obtained')\n \n return hive_file\n\n def filter_combos(self, hive_file):\n \"\"\"This function reads a file of add-on GUID combinations and filters\n out undesirable GUIDs, combines duplicates, and sorts them.\"\"\"\n \n self.log('Filtering combinations...')\n \n # These GUIDs aren't stored in the DB\n not_stored = [\n '\\d+$',\n '.+%40greasespot.net',\n '\\d+%40personas\\.mozilla\\.org',\n ]\n \n not_stored = re.compile('(%s)' % '|'.join(not_stored))\n \n combos = collections.defaultdict(int)\n\n with open(hive_file) as f:\n for line in f:\n _guids, _count = line.split()\n _count = int(_count)\n filtered = []\n \n if _guids == '%7B972ce4c6-7e08-4474-a285-3208198ce6fd%7D':\n filtered.append('No add-ons installed')\n else:\n for guid in _guids.split(','):\n if guid[-1:] == '?':\n guid = guid[:-1]\n if not not_stored.match(guid):\n filtered.append(urllib2.unquote(guid).lower())\n \n combos[','.join(sorted(filtered))] += _count\n \n combos = sorted(combos.iteritems(), key=operator.itemgetter(1), reverse=True)\n \n self.log('Combinations from file processed')\n \n self.time_event('filter_combos')\n \n return combos\n \n def calculate_bfb(self, combos, adu):\n \"\"\"Takes a sorted list of add-on combinations and retains those that\n make up the top 80% of Firefox users and ouputs them. Then selects\n unique add-ons from that list and outputs them.\"\"\"\n \n f = open(self.data_path + '/combos.html', 'w')\n f.write('

Add-on combinations accounting for the most users - {date}

'.format(date=self.date))\n \n target_adu = adu * 0.8\n users = 0\n combos_counted = 0\n unique_guids = collections.defaultdict(int)\n \n for _guids, _count in combos:\n if users >= target_adu:\n break\n \n users += _count\n combos_counted += 1\n pretty_names = []\n \n for guid in _guids.split(','):\n unique_guids[guid] += _count\n pretty_names.append(self.get_addon_name(guid))\n \n \n f.write('[%.2f%%] %s
\\n' % (users / adu * 100, ', '.join(pretty_names)))\n \n f.close()\n self.log(\"\"\"{counted} out of {total} combinations counted representing {users} \n users ({percentage}%)\"\"\".format(counted=combos_counted, total=len(combos), \n users=users, percentage=round(users / adu * 100, 2)))\n self.time_event('calculate_bfb-combos')\n \n f = open(self.data_path + '/addons.html', 'w')\n f.write(\"\"\"

{count} Unique Add-ons making up {percentage}% of Firefox users \n - {date}

\"\"\".format(count=len(unique_guids), \n percentage=round(users / adu * 100, 2), date=self.date))\n f.write('
    ')\n unique_guids = sorted(unique_guids.iteritems(), key=operator.itemgetter(1), reverse=True)\n \n for guid, count in unique_guids:\n f.write('
  • {name} - {users} users\\n
  • '.format(name=self.get_addon_name(guid), users=count))\n \n f.write('
')\n f.close()\n self.time_event('calculate_bfb-addons')\n \n \n def get_adu(self):\n \"\"\"Gets application ADUs for the date from metrics.\"\"\"\n \n db = self.get_database('metrics').cursor()\n db.execute(\"\"\"SELECT SUM(adu_count) FROM raw_adu WHERE date = '%s' AND \n product_name = 'Firefox' AND product_version >= '4.0'\"\"\" % self.date)\n adu = int(db.fetchall()[0][0])\n \n self.log('%d active daily users' % adu)\n \n return adu\n \n def get_addon_name(self, guid):\n \"\"\"Return the name of an add-on in HTML if we know it\"\"\"\n \n if guid in self.addon_names:\n name = ''\n if self.addon_names[guid][1] is not None:\n name += \"\"\"\"\"\".format(id=self.addon_names[guid][1], guid=guid)\n name += self.addon_names[guid][0]\n if self.addon_names[guid][1] is not None:\n name += ''\n else:\n name = guid\n \n return name\n \n def cache_addon_names(self):\n \"\"\"Pull all add-on names from AMO and unhosted sources\"\"\"\n \n # Get AMO names\n addon_names = {}\n db = self.get_database('amo').cursor()\n db.execute(\"\"\"SELECT guid, localized_string as name, addons.id \n FROM addons INNER JOIN translations ON translations.id = addons.name AND \n translations.locale = addons.defaultlocale WHERE guid IS NOT NULL AND \n guid != '' AND addontype_id != 9\"\"\")\n \n self.log('%d GUIDs pulled from AMO' % db.rowcount)\n for r in db.fetchall():\n if r[1] is not None:\n addon_names[r[0].lower()] = (r[1], r[2])\n db.close()\n \n # Get non-hosted names\n db = self.get_database('panorama').cursor()\n db.execute(\"SELECT guid, name FROM _unhosted_guids\")\n self.log('%d GUIDs pulled from unhosted' % db.rowcount)\n for r in db.fetchall():\n addon_names[r[0].lower()] = (r[1], None)\n db.close()\n \n return addon_names\n\nif __name__ == '__main__':\n AddonBangForBuck()","repo_name":"fligtar/panorama","sub_path":"heavylifting/lifter_bangforbuck.py","file_name":"lifter_bangforbuck.py","file_ext":"py","file_size_in_byte":8810,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"18501008007","text":"from grpc.beta import implementations\nimport numpy as np\nfrom PIL import Image\n\nimport tensorflow as tf\nfrom tensorflow_serving.apis import predict_pb2\nfrom tensorflow_serving.apis import prediction_service_pb2\n\nserver = 'localhost:8500'\nmodel_name = 'deeplab'\nsignature_name = 'predict_image'\n\nhost, port = server.split(':')\n_channel = implementations.insecure_channel(host, int(port))\n_TFstub = prediction_service_pb2.beta_create_PredictionService_stub(_channel)\n\n_TFrequest = predict_pb2.PredictRequest()\n_TFrequest.model_spec.name = model_name\n_TFrequest.model_spec.signature_name = signature_name\n\n\ndef tf_predict(image_path, mask_path, request=_TFrequest, stub=_TFstub):\n \"\"\"Predict image segmentation using TF Server\n Args:\n image_name: str\n Return:\n res: dict {'status': int, 'mask_path': str, 'height': int, 'width': int}.\n status: 0 is SUCCESS, 1 is FileNotFound, 2 is TFServerError, 3 is MaskSaveError, 4 is OtherErroe\n \"\"\"\n res = {'status': 104, 'mask_path': 'null', 'height': 0, 'width': 0}\n\n try:\n im = np.array(Image.open(image_path))\n except IOError:\n res['status'] = 101\n return res\n\n height, width, _ = im.shape\n res['height'] = height\n res['width'] = width\n\n try:\n request.inputs[\"image\"].CopyFrom(\n tf.contrib.util.make_tensor_proto(im.astype(dtype=np.float32), shape=[1, height, width, 3]))\n response = stub.Predict(request, 10.0)\n output = np.array(response.outputs['seg'].int64_val)\n except:\n res['status'] = 102\n return res\n\n try:\n output = np.reshape(output, (height, width)).astype(np.uint8)\n mask = Image.fromarray(output)\n mask.save(mask_path)\n except:\n res['status'] = 103\n return res\n else:\n res['status'] = 0\n res['mask_path'] = mask_path.split('/')[-1]\n return res\n\n","repo_name":"neuleaf/tensorflow_serving_demo","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"4018677465","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\n文件/文件路径操作及查询\n\"\"\"\nimport os\n\n\ndef search(path, word, __path_list):\n \"\"\"\n 查询path目录下word相同文件夹名的目录绝对路径\n :param path: 查询的目录\n :param word: 目录名\n :return: 绝对路径list\n \"\"\"\n for x in os.listdir(path):\n fp = os.path.join(path, x)\n if x == word:\n __path_list.append(os.path.abspath(fp))\n if os.path.isdir(fp):\n search(fp, word, __path_list)\n return __path_list\n\n\ndef search_package(project_path, package, module=None, filter='src' + os.sep + 'main' + os.sep + 'java'):\n \"\"\"\n 查询包路径\n :param project_path:项目路径\n :param package:使用模板生成的类文件需要存放的包名\n :param module:使用模板生成的类文件的模块名, 模块名默认为None,若没有制定,则采用项目名作为模块名\n :param filter:过滤条件(需过滤掉测试目录下,target目录下的同名package目录,默认为'src\\\\main\\\\java')\n :return:\n \"\"\"\n if module is None:\n module = os.path.basename(project_path)\n # 将包名转化为目录\n package_dir = package.replace('.', os.sep)\n\n # 截取表名的最后目录名\n basename = os.path.basename(package_dir)\n\n # 查询项目目录下包含basename目录名的所有的目录路径\n # 过滤出包含有package的所有目录路径,并且包含module\n __path_list = []\n search(project_path, basename, __path_list)\n filterpath = []\n for e in __path_list:\n\n if package_dir in e \\\n and module in e \\\n and filter in e:\n filterpath.append(e)\n if filterpath.__len__() < 1:\n raise Exception('查询不到文件需生成的路径')\n if filterpath.__len__() > 1:\n raise Exception('查询到生成文件的路径不唯一,请检查提供的参数是否有误')\n return filterpath[0]\n\n\nif __name__ == '__main__':\n path_list = search(r'C:\\Apps\\sinnis\\project\\entity', 'entity')\n print('---------------------------')\n print(path_list)\n\n path = search_package('C:\\\\Apps\\\\sinnis', 'com.miz.sinnis.service.atom', 'service-atom')\n print(path)\n\n resource_path = search_package('C:\\\\Apps\\\\sinnis', 'com.miz.sinnis.dao.mapper', 'dao',\n filter='src\\\\main\\\\resources')\n print(resource_path)\n","repo_name":"MasonChi/Jtemplate.py","sub_path":"generator/pos.py","file_name":"pos.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"8408348589","text":"# ===========================================================================\n# Project: How I Learned to Stop Worrying and Love Retraining - IOL Lab @ ZIB\n# File: strategies/pretrainedStrategies.py\n# Description: Sparsification strategies for pretrained models\n# ===========================================================================\nimport torch.nn.utils.prune as prune\n\nfrom strategies import scratchStrategies\n\n\n#### Base Class\nclass IMP(scratchStrategies.Dense):\n \"\"\"Iterative Magnitude Pruning Base Class\"\"\"\n\n def __init__(self, **kwargs) -> None:\n super().__init__(**kwargs)\n\n self.n_phases = self.run_config['n_phases']\n self.n_epochs_per_phase = self.run_config['n_epochs_per_phase']\n self.n_epochs_to_split = self.run_config['n_epochs_to_split']\n\n if self.n_epochs_to_split is not None:\n assert self.n_epochs_per_phase in [None, 0]\n if self.n_epochs_to_split % self.n_phases == 0:\n self.n_epochs_per_phase = {p: self.n_epochs_to_split // self.n_phases for p in\n range(1, self.n_phases + 1, 1)}\n else:\n self.n_epochs_per_phase = {p: self.n_epochs_to_split // self.n_phases for p in\n range(1, self.n_phases, 1)}\n self.n_epochs_per_phase[self.n_phases] = self.n_epochs_to_split - (self.n_phases - 1) * (\n self.n_epochs_to_split // self.n_phases)\n else:\n self.n_epochs_per_phase = {p: self.n_epochs_per_phase for p in range(1, self.n_phases + 1, 1)}\n\n def at_train_end(self, **kwargs):\n # Sparsity factor on remaining weights after each round, yields desired_sparsity after all rounds\n prune_per_phase = 1 - (1 - self.goal_sparsity) ** (1. / self.n_phases)\n for phase in range(1, self.n_phases + 1, 1):\n self.pruning_step(pruning_sparsity=prune_per_phase)\n self.current_sparsity = 1 - (1 - prune_per_phase) ** phase\n self.callbacks['after_pruning_callback']()\n self.finetuning_step(pruning_sparsity=prune_per_phase, phase=phase)\n\n def finetuning_step(self, pruning_sparsity, phase):\n self.callbacks['finetuning_callback'](pruning_sparsity=pruning_sparsity,\n n_epochs_finetune=self.n_epochs_per_phase[phase],\n phase=phase)\n\n def get_pruning_method(self):\n return prune.L1Unstructured\n\n def final(self):\n super().final()\n self.callbacks['final_log_callback']()\n","repo_name":"jiujiuwei/BIMP","sub_path":"strategies/pretrainedStrategies.py","file_name":"pretrainedStrategies.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"43629691424","text":"import logging\nimport os\nimport time\nfrom os.path import abspath\n\n\ntimestamp = int(time.time())\nlogs_dir = abspath('./logs')\n\nif not os.path.exists(logs_dir):\n os.mkdir(logs_dir)\n\nLOG_FILE_PATH = './logs/' + str(timestamp) + \".log\"\nconsole_out = logging.StreamHandler()\nfile_log = logging.FileHandler(LOG_FILE_PATH, encoding='utf-8')\n\nlogging.basicConfig(handlers=(file_log, console_out),\n format='[%(asctime)s | %(levelname)s]: %(message)s',\n datefmt='%m.%d.%Y %H:%M:%S',\n level=logging.INFO)\n\nlogger = logging.getLogger()\n\nlog = logging","repo_name":"egorDan89/playlist_task","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25822082414","text":"import urllib.request\nfrom bs4 import BeautifulSoup\nfrom slpp import slpp as lua\nimport os\nimport platform\n\n\nhdr = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',\n 'Accept-Encoding': 'none',\n 'Accept-Language': 'en-US,en;q=0.8',\n 'Connection': 'keep-alive',\n}\n\nsphere = None\n\ndef get_recipe(row):\n crystals = [\n 'Dark Crystal',\n 'Light Crystal',\n 'Earth Crystal',\n 'Water Crystal',\n 'Fire Crystal',\n 'Wind Crystal',\n 'Lightning Crystal',\n 'Ice Crystal',\n 'Pyre Crystal',\n 'Frost Crystal',\n 'Vortex Crystal',\n 'Geo Crystal',\n 'Terra II Crystal',\n 'Bolt Crystal',\n 'Fluid Crystal',\n 'Glimmer Crystal',\n 'Shadow Crystal',\n ]\n result, _, recipe = [\n td for td in row.findAll('td')\n ]\n name = str(result.findAll('a')[0]['title'])\n crystal = None\n ingredients = []\n for li in recipe.findAll('li'):\n english = str(li.findAll('a')[0]['title'])\n if english in crystals:\n crystal = english\n continue\n try:\n if li.text is None:\n ingredients.append(\"unknown\") # ingredient is \"Question Mark\", e.g. for Pagodite\n elif li.text[-1].isdigit() and not \"Kit\" in english:\n for n in range(int(li.text[-1])):\n ingredients.append(english)\n else:\n ingredients.append(english)\n except IndexError:\n return None\n return [(name, crystal, ingredients)]\n\ndef get_sphere_recipe(row):\n spheres = [\n 'Liquefaction Sphere',\n 'Transfixion Sphere',\n 'Detonation Sphere',\n 'Impaction Sphere',\n 'Induration Sphere',\n 'Reverberation Sphere',\n 'Scission Sphere',\n 'Compression Sphere',\n ]\n global sphere\n cells = [td for td in row.findAll('td')]\n if len(cells) > 4:\n rare_ex, rare, ex, c, s = cells[:5]\n if str(s.findAll('a')[0]['title']) in spheres:\n sphere = str(s.findAll('a')[0]['title'])\n else:\n rare_ex, rare, ex, c = cells[:4]\n recipes = []\n crystal = str(c.findAll('img')[0]['alt']).rstrip(' icon.png')\n ingredients = []\n for cell in cells[:3]:\n for a in cell.findAll('a'):\n recipes.append((sphere, crystal, [str(a['title'])]))\n return recipes\n\ndef get_recipes_from_rows(rows, spheres=False):\n recipes = {}\n for row in rows:\n if spheres:\n subrecipes = get_sphere_recipe(row)\n else:\n subrecipes = get_recipe(row)\n for (name, crystal, ingredients) in subrecipes:\n while name in recipes.keys():\n if name[-1].isdigit():\n name = name[:-2] + (\" %d\" % (int(name[-1]) + 1))\n else:\n name = name + \" 2\"\n recipes[name] = [crystal, ingredients]\n return recipes\n\ndef get_recipes_from_soup(soup, spheres=False):\n string = \"Sphere Obtained\" if spheres else \"Synthesis Information\"\n lengths = [4, 5, 6, 7] if spheres else [3]\n subtables = [\n descendant.parent.parent.parent\n for descendant in soup.descendants\n if string in descendant\n ]\n rows = []\n for subtable in subtables:\n children = [\n row\n for row in subtable.children\n if (hasattr(row, 'findAll') and\n len(row.findAll('td')) in lengths)\n ]\n rows.extend(children)\n return get_recipes_from_rows(rows, spheres)\n\ndef get_items_dictionary():\n if platform.system() == 'Windows':\n path = 'C:\\\\Program Files (x86)\\\\Windower4\\\\res\\\\items.lua'\n else:\n path = os.path.join(os.path.expanduser(\"~\"), 'Resources/lua/items.lua')\n with open(path) as fd:\n data = fd.read().replace('return', '', 1)\n return lua.decode(data)\n\ndef get_items():\n exceptions = {\n 'geo crystal' : 6509,\n 'terra ii crystal' : 6509,\n 'broken single-hook fishing rod' : 472,\n 'broken hume rod' : 1832,\n 'broken bamboo rod' : 487,\n 'dark adaman sheet' : 2001,\n 'black chocobo fletchings' : 1254,\n 'broken willow rod' : 485,\n 'four-leaf korringan bud' : 1265,\n 'broken fastwater rod' : 488,\n 'h. q. coeurl hide' : 1591,\n 'broken yew rod' : 486,\n 'broken mithran rod' : 483,\n 'broken tarutaru rod' : 484,\n \"broken lu shang's rod\" : 489,\n 'fire emblem card' : 9764,\n 'ice emblem card' : 9765,\n 'wind emblem card' : 9766,\n 'earth emblem card' : 9767,\n 'lightning emblem card': 9768,\n 'water emblem card' : 9769,\n 'light emblem card': 9770,\n 'dark emblem card': 9771,\n }\n items = get_items_dictionary()\n inverted = {}\n for k, v in items.items():\n if not v['en'].lower() in inverted:\n inverted[v['en'].lower()] = k\n if not v['enl'].lower() in inverted:\n inverted[v['enl'].lower()] = k\n inverted.update(exceptions)\n return items, inverted\n\ndef get_item(ingredient, inverted):\n results = []\n exceptions = {\n 'behemoth leather' : 'square of behemoth leather',\n 'puk fletchings' : 'bag of puk fletchings',\n 'phrygian gold' : 'phrygian gold ingot',\n 'smilodon leather' : 'square of smilodon leather',\n 'chocobo fletchings' : 'bag of chocobo fletchings',\n 'vermilion lacquer' : 'pot of vermilion lacquer',\n }\n if ingredient in exceptions:\n return inverted[exceptions[ingredient]]\n for name, iid in inverted.items():\n if ingredient in name:\n return iid\n\ndef fix_recipes(recipes):\n items, inverted = get_items()\n for name, (crystal, ingredients) in recipes.items():\n crystal = items[inverted[crystal.lower()]]['en']\n sorted = []\n for ingredient in ingredients:\n ingredient = ingredient.lower()\n if ingredient in inverted:\n sorted.append(inverted[ingredient])\n else:\n sorted.append(get_item(ingredient, inverted))\n sorted = list(filter(lambda item: item is not None, sorted))\n sorted.sort()\n ingredients = [\n items[ingredient]['en']\n for ingredient in sorted\n ]\n recipes[name] = [crystal, ingredients]\n\ndef build_recipe_string(name, crystal, ingredients):\n recipe = \" [\\\"%s\\\"] = {\\n [\\\"crystal\\\"] = \\\"%s\\\",\\n [\\\"ingredients\\\"] = {\\n\" % (name, crystal)\n for ingredient in ingredients:\n recipe += \" \\\"%s\\\",\\n\" % ingredient\n recipe += \" },\\n },\\n\"\n return recipe\n\ndef save_recipes(recipes):\n with open('recipes.lua', 'w') as fd:\n fd.write(\"return {\\n\")\n for key in sorted(recipes.keys()):\n fd.write(build_recipe_string(key, *recipes[key]))\n fd.write(\"}\\n\")\n\ndef get_recipes(craft, spheres=False):\n base = \"https://www.bg-wiki.com/bg/\"\n name = \"%s.html\" % craft\n if not os.path.exists(name):\n req = urllib.request.Request(base + craft, headers=hdr)\n try:\n page = urllib.request.urlopen(req).read()\n except urllib.request.HTTPError:\n return\n with open(name, 'wb') as fd:\n fd.write(page)\n with open(name, 'r') as fd:\n page = fd.read()\n soup = BeautifulSoup(page, 'lxml')\n return get_recipes_from_soup(soup, spheres)\n\nif __name__ == \"__main__\":\n crafts = [\n 'Alchemy',\n 'Bonecraft',\n 'Clothcraft',\n 'Cooking',\n 'Goldsmithing',\n 'Leathercraft',\n 'Smithing',\n 'Woodworking',\n ]\n recipes = {}\n for craft in crafts:\n recipes.update(get_recipes(craft))\n recipes.update(get_recipes('Category:Escutcheons', True))\n fix_recipes(recipes)\n save_recipes(recipes)\n","repo_name":"Windower/Lua","sub_path":"addons/craft/create_recipes.py","file_name":"create_recipes.py","file_ext":"py","file_size_in_byte":8081,"program_lang":"python","lang":"en","doc_type":"code","stars":217,"dataset":"github-code","pt":"20"} +{"seq_id":"73032723570","text":"import unittest\n\nimport sys\nsys.path.append(\"../../../\")\n\nfrom sudoku.grupos.herramientas.numerosFaltantes import NumerosFaltantesImp\nfrom sudoku.grupos.herramientas.matriz import MatrizImp\n\nclass Test_NumerosFaltantes(unittest.TestCase):\n \n def test_numerosFaltantes(self):\n self.numerosFaltantes = NumerosFaltantesImp()\n self.crear()\n self.get()\n self.set()\n self.remove()\n\n def crear(self):\n matriz = MatrizImp()\n matriz = [\n [0, 0, 0], \n [0, 0, 0], \n [0, 0, 0]\n ]\n esperado = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n self.verificarMatrizCreada(matriz, esperado)\n \n matriz= [\n [1, 2, 3], \n [4, 5, 6], \n [7, 8, 9]\n ]\n esperado = list()\n\n self.verificarMatrizCreada(matriz, esperado)\n \n matriz = [\n [1, 0, 0], \n [8, 5, 0], \n [0, 0, 3]\n ]\n esperado = [2, 4, 6, 7, 9]\n self.verificarMatrizCreada(matriz, esperado)\n\n def verificarMatrizCreada(self, matriz: list, esperado: list):\n self.numerosFaltantes.crear(matriz)\n matrizComparativa = esperado\n self.assertEqual(self.numerosFaltantes.get(), matrizComparativa)\n\n def get(self):\n numeros = self.numerosFaltantes.get()\n esperado = [2, 4, 6, 7, 9]\n self.assertEqual(numeros, esperado)\n\n def set(self):\n self.numerosFaltantes.set([1,2,3])\n esperado = [1, 2, 3]\n numeros = self.numerosFaltantes.get()\n self.assertEqual(numeros, esperado)\n\n def remove(self):\n self.numerosFaltantes.remove(2)\n esperado = [1, 3]\n numeros = self.numerosFaltantes.get()\n self.assertEqual(numeros, esperado)","repo_name":"baydex/sudoku","sub_path":"tests/grupos/herramientas/test_numerosFaltantes.py","file_name":"test_numerosFaltantes.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"24293707897","text":"from PySide2.QtWidgets import QMainWindow\nfrom sos.gui.main_window_ui import Ui_MainWindow\n\nclass MainWindow(QMainWindow, Ui_MainWindow):\n def __init__(self, db_model):\n super().__init__()\n self.setupUi(self)\n self.db_model = db_model\n self.loginScreen.db_model = db_model\n self.loginScreen.loginSuccessful.connect(self.navigate_to_admin_screen)\n self.adminScreen.db_model = db_model\n self.adminScreen.signoutRequested.connect(self.navigate_to_login_screen)\n self.admin_session_id = None\n\n def navigate_to_login_screen(self):\n self.admin_session_id = None\n self.stackedWidget.setCurrentWidget(self.loginScreen)\n\n def navigate_to_admin_screen(self, session_id):\n self.admin_session_id = session_id\n self.stackedWidget.setCurrentWidget(self.adminScreen)\n self.adminScreen.refresh_form()","repo_name":"tornado80/sos-game-server","sub_path":"sos/gui/main_window.py","file_name":"main_window.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"14296417048","text":"import torch\nimport torch.nn as nn\nimport gym\nimport numpy as np\nfrom torch.optim import Adam\nfrom NeuralNet import Network\nfrom ReplayMemory import ReplayMemory\nfrom EpsilonDecay import EpsilonDecay\nfrom dqn_wrapper import SkipFrame\nfrom gym.wrappers import GrayScaleObservation, ResizeObservation, FrameStack\n\n\ndef preprocess(env_, stack_frame_no, resize_size, skip_number):\n env_new = SkipFrame(env_, skip_number)\n env_new = GrayScaleObservation(env_new)\n env_new = ResizeObservation(env_new, shape=resize_size)\n env_new = FrameStack(env_new, stack_frame_no)\n return env_new\n\n\ndef state_process(state_):\n state_new = state_.__array__()\n state_new = state_new.squeeze(axis=None)\n state_new = torch.Tensor(state_new / 255)\n return state_new\n\n\ndef optimize_step(batch_size_, gamma_, loss_fn_, optimizer_):\n if len(memory.replay_memory) < batch_size_:\n return\n memory_batch = memory.sample(batch_size_)\n state_list = [memory_element[0] for memory_element in memory_batch]\n states = torch.stack(state_list)\n new_state_list = [memory_element[3] for memory_element in memory_batch]\n new_states = torch.stack(new_state_list)\n actions_list = [memory_element[1] for memory_element in memory_batch]\n actions = torch.stack(actions_list)\n reward_list = [memory_element[2] for memory_element in memory_batch]\n rewards = torch.stack(reward_list)\n target = target_net(new_states).max(dim=1)[0]\n q_val = q_net(states)[np.arange(0, batch_size_), actions]\n target = rewards + gamma_ * target\n loss = loss_fn_(q_val, target)\n loss.backward()\n optimizer_.step()\n optimizer_.zero_grad()\n\n\nif __name__ == '__main__':\n env_name = \"SpaceInvaders-v0\"\n env = gym.make(env_name)\n env= preprocess(env, 4, 84, 4)\n action_number = env.action_space.n\n input_image_channel_number = 4\n lr = .001\n epsilon_start = 0.9\n epsilon_end = 0.05\n decay = 0.1\n memory_limit = 1000\n batch_size = 32\n gamma = 0.999\n target_update = 20\n q_net = Network(in_size=input_image_channel_number, out_size=action_number)\n target_net = Network(in_size=input_image_channel_number, out_size=action_number)\n target_net.load_state_dict(q_net.state_dict())\n optimizer = Adam(q_net.parameters(), lr)\n loss_fn = nn.SmoothL1Loss()\n memory = ReplayMemory(memory_size=memory_limit)\n epsilon_decay = EpsilonDecay(e_start=epsilon_start, e_end=epsilon_end, decay=decay)\n episodes = 100\n for i in range(episodes):\n state = env.reset()\n state = state_process(state)\n ep_rew = 0\n time_step = 0\n while True:\n time_step += 1\n if time_step % 20 == 0:\n env.render()\n action = epsilon_decay.select_action(state, action_number, q_net)\n new_state, reward, done, _ = env.step(action)\n ep_rew += reward\n new_state = state_process(new_state)\n temp = (state, action, torch.as_tensor(reward), new_state)\n memory.insert_transition(temp)\n state = new_state\n optimize_step(batch_size, gamma, loss_fn,optimizer)\n\n if done:\n print(\"Episode no {0:f} , reward \".format(i))\n print(ep_rew)\n break\n if i % 20 == 0:\n target_net.load_state_dict(q_net.state_dict())\n","repo_name":"akshay-antony/DQN","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"32022298300","text":"from neo4j import GraphDatabase, ServerInfo, Session\n\nURI = \"neo4j://localhost:7687\"\nAUTH = (\"neo4j\", \"password\")\n\n\ndef print_connection_details(info: ServerInfo) -> None:\n print(f\"Connection info: agent={info.agent} address={info.address} protocol_version={info.protocol_version}\")\n\n\ndef print_all_nodes(session: Session) -> None:\n count = session.run(\"\"\"\n MATCH ()\n RETURN COUNT(*) as count\n \"\"\").single()\n result = session.run(\"\"\"\n MATCH (s)\n RETURN s\n \"\"\").fetch(10)\n print(f\"Nodes count: {count.data()['count']}\")\n for item in result:\n print(item.data())\n\n\ndef add_new_nodes(session: Session) -> None:\n test = session.run(\"\"\"\n CREATE (s1:Student {fullname: \"Kacper Czajkowski\", birthdate: \"1999-11-19\"}),\n (s2:Student {fullname: \"Dominik Daniłowski\", birthdate: \"1998-04-17\"}),\n (s3:Student {fullname: \"Marcin Zadrożny\", birthdate: \"2000-08-21\"}),\n (w:Wydzial {name: \"Wydział Matematyki i Informatyki\", abbreviation: \"WMII\"}),\n (s2) -[r1:STUDIUJE_NA]-> (w),\n (s3) -[r2:STUDIUJE_NA]-> (w)\n RETURN s1, s2, s3, w\n \"\"\").single()\n print(test.data())\n\n\ndef add_relationship_between_existing_nodes(session: Session) -> None:\n result = session.run(\"\"\"\n MATCH (s:Student {fullname: \"Kacper Czajkowski\"}), (w:Wydzial {abberviation: \"WMII\"})\n CREATE (s) -[:STUDIUJE_NA]-> (w)\n \"\"\").single()\n\n\ndef add_or_update_property_in_node(session: Session) -> None:\n result = session.run(\"\"\"\n MATCH (s:Student {fullname: \"Kacper Czajkowski\"})\n SET s.fullname = \"Kacper Zedytowany Czajkowski\"\n \"\"\").single()\n\n\ndef override_all_properties_of_node(session: Session) -> None:\n result = session.run(\"\"\"\n MATCH (s:Student {fullname: \"Dominik Daniłowski\"})\n SET s = {full_name: \"Henryk Daniłowski\", age: 24}\n \"\"\").single()\n\n\ndef update_multiple_properties(session: Session) -> None:\n result = session.run(\"\"\"\n MATCH (s:Student {fullname: \"Marcin Zadrożny\"})\n SET s += {fullname: \"Marcin Odświeżony Zadrożny\", age: 23}\n \"\"\").single()\n\n\n# usuwanie\n# usuwanie node'a\n# usuwanie property\n# usuwanie labela ze wszystkich node'ów\n# usuwanie wszystkiego\ndef remove_all_nodes_and_relationships(session: Session) -> None:\n session.run(\"\"\"\n MATCH (n)\n DETACH DELETE n;\n \"\"\").single()\n\n\nif __name__ == '__main__':\n with GraphDatabase.driver(URI, auth=AUTH) as driver:\n print_connection_details(driver.get_server_info())\n with driver.session() as session:\n remove_all_nodes_and_relationships(session)\n print_all_nodes(session)\n add_new_nodes(session)\n print_all_nodes(session)\n add_relationship_between_existing_nodes(session)\n print_all_nodes(session)\n update_multiple_properties(session)\n print_all_nodes(session)\n override_all_properties_of_node(session)\n print_all_nodes(session)\n","repo_name":"CzaplaPL/neo4j","sub_path":"neo4j_example/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72090500211","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 8 13:31:55 2019\n\n@author: ben\n\"\"\"\n\n#!/usr/bin/env python\n\n#CREDIT: Deep-Reinforcement-Learning-Hands-On PacktPublishing\n\nimport random\nimport argparse\nimport cv2\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom tensorboardX import SummaryWriter\n\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\n\n\nimport gym\nimport gym.spaces\n\nimport numpy as np\n\nfrom PIL import Image\n\nlog = gym.logger\nlog.set_level(gym.logger.INFO)\n\nLATENT_VECTOR_SIZE = 40\nFILTERS = 64\nBATCH_SIZE = 16\n\n# dimension input image will be rescaled\nIMAGE_SIZE = 64\n\nLEARNING_RATE = 0.0001\nREPORT_EVERY_ITER = 100\nSAVE_IMAGE_EVERY_ITER = 100\n\n\nclass InputWrapper(gym.ObservationWrapper):\n \"\"\"\n Preprocessing of input numpy array:\n 1. resize image into predefined size\n 2. move color channel axis to a first place\n \"\"\"\n def __init__(self, *args):\n super(InputWrapper, self).__init__(*args)\n assert isinstance(self.observation_space, gym.spaces.Box)\n old_space = self.observation_space\n self.observation_space = gym.spaces.Box(self.observation(old_space.low), self.observation(old_space.high),\n dtype=np.float32)\n\n def observation(self, observation):\n # resize image\n new_obs = cv2.resize(observation, (IMAGE_SIZE, IMAGE_SIZE))\n # transform (210, 160, 3) -> (3, 210, 160)\n new_obs = np.moveaxis(new_obs, 2, 0)\n return new_obs.astype(np.float32)\n\n\nclass VAE(nn.Module):\n def __init__(self, input_shape, output_shape):\n super(VAE, self).__init__()\n # this pipe converges image into the single number\n self.conv_pipe = nn.Sequential(\n nn.Conv2d(in_channels=input_shape[0], out_channels=FILTERS,\n kernel_size=4, stride=2, padding=1),\n nn.ReLU(),\n nn.Conv2d(in_channels=FILTERS, out_channels=FILTERS*2,\n kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(FILTERS*2),\n nn.ReLU(),\n nn.Conv2d(in_channels=FILTERS * 2, out_channels=FILTERS * 4,\n kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(FILTERS * 4),\n nn.ReLU(),\n nn.Conv2d(in_channels=FILTERS * 4, out_channels=FILTERS * 8,\n kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(FILTERS * 8),\n nn.ReLU(),\n nn.Conv2d(in_channels=FILTERS * 8, out_channels=LATENT_VECTOR_SIZE,\n kernel_size=4, stride=1, padding=0),\n nn.Sigmoid()\n )\n self.mu_layer = nn.Linear(LATENT_VECTOR_SIZE, LATENT_VECTOR_SIZE)\n self.sig_layer = nn.Linear(LATENT_VECTOR_SIZE, LATENT_VECTOR_SIZE)\n self.deconv_pipe = nn.Sequential(\n nn.ConvTranspose2d(in_channels=LATENT_VECTOR_SIZE, out_channels=FILTERS * 8,\n kernel_size=4, stride=1, padding=0),\n nn.BatchNorm2d(FILTERS * 8),\n nn.ReLU(),\n nn.ConvTranspose2d(in_channels=FILTERS * 8, out_channels=FILTERS * 4,\n kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(FILTERS * 4),\n nn.ReLU(),\n nn.ConvTranspose2d(in_channels=FILTERS * 4, out_channels=FILTERS * 2,\n kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(FILTERS * 2),\n nn.ReLU(),\n nn.ConvTranspose2d(in_channels=FILTERS * 2, out_channels=FILTERS,\n kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(FILTERS),\n nn.ReLU(),\n nn.ConvTranspose2d(in_channels=FILTERS, out_channels=output_shape[0],\n kernel_size=4, stride=2, padding=1),\n nn.Tanh())\n \n \n def encoder(self, x):\n en = self.conv_pipe(x).view(-1, LATENT_VECTOR_SIZE)\n return self.mu_layer(en), self.sig_layer(en)\n \n \n def decoder(self, z):\n z = z.view(-1, LATENT_VECTOR_SIZE, 1, 1)\n return self.deconv_pipe(z) #deconv pipe expects 4d input\n \n def reparam(self, mu, logsig):\n std = 0.5 * torch.exp(logsig) #to avoid numerical problems the network learns log variance\n gaus = torch.randn(LATENT_VECTOR_SIZE) #normal distribution with mean 0 variance 1\n return mu + gaus * std\n\n def forward(self, x):\n mu, logsig = self.encoder(x)\n z = self.reparam(mu, logsig)\n y = self.decoder(z)\n return y, mu, logsig\n \n def gaussian_reg_loss(self, y, x, mu, logsig):\n xyl = nn.MSELoss()\n # solution to kl divergence with a standard gaussian prior |integral N(z;mu,sig) log N(z;0,I)\n kld = -0.5 * torch.sum(1 + logsig - mu.pow(2) - logsig.exp()) \n return xyl(y, x) + kld\n \nwriter = SummaryWriter()\n\ndef iterate_batches(envs, batch_size=BATCH_SIZE):\n batch = [e.reset() for e in envs]\n env_gen = iter(lambda: random.choice(envs), None)\n\n while True:\n e = next(env_gen)\n obs, reward, is_done, _ = e.step(e.action_space.sample())\n if np.mean(obs) > 0.01:\n batch.append(obs)\n if len(batch) == batch_size:\n # Normalising input between -1 to 1\n batch_np = np.array(batch, dtype=np.float32) * 2.0 / 255.0 - 1.0\n yield torch.tensor(batch_np)\n batch.clear()\n if is_done:\n e.reset()\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--cuda\", default=False, action='store_true', help=\"Enable cuda computation\")\n args = parser.parse_args()\n\n device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n envs = [InputWrapper(gym.make(name)) for name in ['FishingDerby-v0', 'MsPacman-v0']]\n input_shape = envs[0].observation_space.shape\n\n vae = VAE(input_shape=input_shape,output_shape=input_shape).to(device)\n\n objective = vae.gaussian_reg_loss\n optimizer = optim.Adam(params=vae.parameters(), lr=LEARNING_RATE, betas=(0.5, 0.999))\n \n writer = SummaryWriter()\n\n losses = []\n iter_no = 0\n \n batch_v = next(iterate_batches(envs))\n writer.add_graph(vae, batch_v)\n\n for batch_v in iterate_batches(envs):\n \n batch_v = batch_v.to(device)\n \n # train\n optimizer.zero_grad()\n output_v, mu, logsig = vae(batch_v)\n loss = objective(output_v, batch_v, mu, logsig)\n loss.backward()\n optimizer.step()\n losses.append(loss.item())\n \n if iter_no % REPORT_EVERY_ITER == 0:\n log.info(\"Iter %d: loss=%.3e\", iter_no, np.mean(losses))\n writer.add_scalar(\"loss\", np.mean(losses), iter_no)\n losses = []\n if iter_no % SAVE_IMAGE_EVERY_ITER == 0: \n\n gen_img = vutils.make_grid(output_v.data[:64], normalize=True)\n real_img = vutils.make_grid(batch_v.data[:64], normalize=True)\n gen_img = transforms.ToTensor()(transforms.Resize(256 + 128, Image.NEAREST)(transforms.ToPILImage()(gen_img)))\n real_img = transforms.ToTensor()(transforms.Resize(256 + 128, Image.NEAREST)(transforms.ToPILImage()(real_img)))\n \n writer.add_image(\"fake\", gen_img, iter_no)\n writer.add_image(\"real\", real_img, iter_no)\n \n iter_no += 1\n \n \n\n ","repo_name":"BenedictWilkins/pyworld-rl","sub_path":"pyworld/algorithms/Other/Atari_VAE.py","file_name":"Atari_VAE.py","file_ext":"py","file_size_in_byte":7455,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"16577918846","text":"import numpy as np\r\nimport flask\r\nfrom flask import Flask, render_template,request\r\nimport pickle#Initialize the flask App\r\napp = Flask(__name__)\r\nmodel = pickle.load(open('model.pkl', 'rb'))\r\n@app.route('/')\r\ndef home():\r\n return render_template('dummy.html')\r\n@app.route('/predict',methods=['POST'])\r\ndef predict():\r\n #For rendering results on HTML GUI\r\n int_features = [x for x in request.form.values()]\r\n print(int_features)\r\n newencoder = pickle.load(open(\"soilencoder.pkl\", \"rb\"))\r\n int_features[2] = newencoder.transform([int_features[2]])\r\n newencoder = pickle.load(open(\"stateencoder.pkl\", \"rb\"))\r\n int_features[3] = newencoder.transform([int_features[3]])\r\n newencoder = pickle.load(open(\"watersupplyencoder.pkl\", \"rb\"))\r\n int_features[4] = newencoder.transform([int_features[4]])\r\n newencoder = pickle.load(open(\"humidityencoder.pkl\", \"rb\"))\r\n int_features[5] = newencoder.transform([int_features[5]])\r\n final_features = [np.array(int_features)]\r\n prediction = model.predict(final_features)\r\n output = prediction\r\n return render_template('dummy.html', prediction_text='The crop suitable for your environment is: ' + output)\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n","repo_name":"PMalvikaReddy/Quamtum_Hacks_Farmer-s-Friend","sub_path":"ML_crop_recommendation_system/page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"5957788177","text":"'''\r\nCreated on 2018年6月14日\r\n\r\n@author: Administrator\r\n'''\r\n\r\nimport requests\r\nimport time\r\n\r\nif __name__ == '__main__':\r\n payload = dict(a=2, b=3)\r\n for i in range(100):\r\n t = time.clock()\r\n r = requests.post('http://127.0.0.1:8006/add', data = payload)\r\n t1 = time.clock()\r\n print('add [%.4d] [%f] %s' % (i, t1-t, r.text))\r\n \r\n for i in range(100):\r\n r = requests.post('http://127.0.0.1:8006/sub', data = payload)\r\n print('sub [%.4d] [%f] %s' % (i, t1-t, r.text))\r\n \r\n for i in range(100):\r\n r = requests.post('http://127.0.0.1:8006/mul', data = payload)\r\n print('mul [%.4d] [%f] %s' % (i, t1-t, r.text))\r\n \r\n data = input('[press any key to exit]')","repo_name":"lw000/new_python_demo","sub_path":"python/tornado_wb_demo/src/bench_test.py","file_name":"bench_test.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"28456340235","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 21 23:19:22 2023\n\n@author: rober\n\"\"\"\n\ndef soma1(n):\n print(\"Aqui eu somo 1 a inteiros :D\")\n if type(n) == int:\n n +=1\n return n\n else:\n print(\"epa, epa! bota um inteiro na próxima!\")\n ","repo_name":"jr-homelidasilva/git-testando","sub_path":"grosseria.py","file_name":"grosseria.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"21193375207","text":"import random\n\ncomputer = random.randint(-1, 1)\nhuman = int(input(\"玩家请出拳\\n-1\\t=>\\t剪刀\\n 0\\t=>\\t石头\\n 1\\t=>\\t布\\n:\"))\nif computer == -1:\n print(\"电脑出拳:剪刀\")\nelif computer == 0:\n print(\"电脑出拳:石头\")\nelse:\n print(\"电脑出拳:布\")\n\nif human == -1:\n print(\"你的出拳:剪刀\")\nelif human == 0:\n print(\"你的出拳:石头\")\nelse:\n print(\"你的出拳:布\")\n\nif ((human == -1 and computer == 1)\n or (human == 0 and computer == -1)\n or (human == 1 and computer == 0)):\n print(\"玩家胜利了\")\nelif human == computer:\n print(\"平局\")\nelse:\n print(\"电脑赢了哦\")\n","repo_name":"gaga2455066166/gaga_python3","sub_path":"Practice_2020/py_random.py","file_name":"py_random.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"154726412","text":"\ndef m1():\n r'''\n 一、readline\n '''\n with open('Animal.py', 'rt', encoding='utf-8') as f:\n line = f.readline()\n while line:\n print(line)\ndef m2():\n r'''\n 二、readlines\n '''\n # 一次读取所有行\n # with open('Animal.py', 'rt', encoding='utf-8') as f:\n # for line in f.readlines():\n # print(line)\n\n # 一次读取批定行数\n with open('Animal.py', 'rt', encoding='utf-8') as f:\n while True:\n for line in f.readlines(1000):\n print(line)\n\n\ndef m3():\n '''\n 三、直接for循环\n :return:\n '''\n # 逐行读取\n for line in open(\"Animal.py\"):\n print(line)\n\n\ndef m4():\n r'''\n 四、fileinput模块\n :return:\n '''\n import fileinput\n for line in fileinput.input('Animal.py'):\n print(line)\n\ndef m5():\n '''\n linecache\n :return:\n '''\n # 指定范围读取(行数)\n import linecache\n text = linecache.getline('Animal.py', 4)\n print(text)\n\n\nm4()","repo_name":"dantefung/Python-Codebase","sub_path":"study_sample/file_read.py","file_name":"file_read.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72045066290","text":"#For Tech Challenge\n\ndef unite(p, q, links):\n pid = links[p[0]][p[1]]\n for i in range(0, len(links)):\n for j in range(0, len(links[i])):\n if links[i][j] == pid:\n links[i][j] = links[q[0]][q[1]]\n return links\n\ninputString = input()\ncities = []\nrow = []\ncity = ''\nfor value in inputString:\n if value == '#':\n row.append(int(city))\n cities.append(row)\n row = []\n city = ''\n else:\n if value == '@':\n row.append(int(city))\n city = ''\n else:\n city = city + value\nif city != '':\n row.append(int(city))\n cities.append(row)\n\nprint(cities)\n\ndef least_cost_path(blocks):\n for i in range(len(blocks)):\n for j in range(len(blocks[i])):\n cost = blocks[i][j]\n costs = []\n if i == 0 and j == 0:\n costs.append(cost)\n if i > 0:\n costs.append(cost + blocks[i-1][j])\n if j > 0:\n costs.append(cost + blocks[i-1][j-1])\n if j < (len(blocks[i]) - 1):\n costs.append(cost + blocks[i-1][j+1])\n if j > 0:\n costs.append(cost + blocks[i][j-1])\n if j < (len(blocks[i]) - 1):\n costs.append(cost + blocks[i][j+1])\n if i < (len(blocks) - 1):\n costs.append(cost + blocks[i+1][j])\n if j > 0:\n costs.append(cost + blocks[i+1][j-1])\n if j < (len(blocks[i]) - 1):\n costs.append(cost + blocks[i+1][j+1])\n blocks[i][j] = min(costs)\n return blocks\n\nprint('*********************')\nprint(least_cost_path(cities))\n\n# links = []\n# row = []\n\n# for i in range(0, len(cities)):\n# for j in range(0, len(cities[i])):\n# row.append((i, j))\n# links.append(row)\n# row = []\n\n# red_zone_count = 0\n# green_zone_count = 0\n\n# for i in range(len(cities)):\n# for j in range(len(cities[i])):\n# if cities[i][j] == -1:\n# green_zone_count += 1\n# if i > 0 and j > 0 and cities[i-1][j-1] == -1:\n# links = unite((i-1, j-1), (i, j), links)\n# if i > 0 and cities[i-1][j] == -1:\n# links = unite((i-1, j), (i, j), links)\n# if i > 0 and j < (len(cities[i]) - 1) and cities[i-1][j+1] == -1:\n# unite((i-1, j+1), (i, j), links)\n# if j > 0 and cities[i][j-1] == -1:\n# links = unite((i, j-1), (i, j), links)\n# else:\n# red_zone_count += 1\n\n# print(\"***links***\")\n# print(links)\n \n","repo_name":"bhuvankaruturi/Python-Programs","sub_path":"grid-links.py","file_name":"grid-links.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"24474736651","text":"# I'm DengHwee or you can call me Chimmey\n\nclass Gamer :\n thoiGian = 0\n def __init__(self, ma, ten, gioVao, gioRa) :\n self.ma = ma\n self.ten = ten\n self.thoiGian = gioRa[0] * 60 + gioRa[1] - gioVao[0] * 60 - gioVao[1]\n\n def output(self) :\n print(self.ma, self.ten, int(self.thoiGian / 60), 'gio', self.thoiGian % 60, 'phut')\n\nn = int(input())\na = []\nfor i in range(n) :\n ma = input()\n ten = input()\n gioVao = [int(x) for x in input().split(':')]\n gioRa = [int(x) for x in input().split(':')]\n a.append(Gamer(ma, ten, gioVao, gioRa))\n\na = sorted(a, key= lambda x : (- x.thoiGian))\nfor i in a :\n i.output()\n","repo_name":"denghwee/Python_PTIT","sub_path":"PY04021 - TÍNH TOÁN THỜI GIAN.py","file_name":"PY04021 - TÍNH TOÁN THỜI GIAN.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"30547661995","text":"# -*- coding:utf-8 -*-\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\n\ndef createTraj(a, b, revel, resolution, rotationDeg):\n arr = []\n rotationRad = float(rotationDeg) / 180.0 * math.pi\n maxloop = int(revel*resolution)\n for i in xrange(0,maxloop):\n x = a*math.cos(float(i)/resolution)\n y = b*math.sin(float(i)/resolution)\n\n x = x*math.cos(rotationRad) - y*math.sin(rotationRad)\n y = x*math.sin(rotationRad) + y*math.cos(rotationRad)\n arr.append([x,y])\n return arr\n\ndef main():\n f = open('test.csv','w')\n circle1 = createTraj(2, 2, 2* math.pi, 10, 0)\n circle2 = createTraj(2, 1.8, 0.5* math.pi, 10, 20)\n circle = np.vstack((circle1, circle2))\n circleTrans = circle.transpose()\n\n\n for x in circle:\n text = str(x[0]) + \",\" + str(x[1]) + \"\\n\"\n f.write(text)\n f.close()\n\n plt.plot(circleTrans[0], circleTrans[1] ,\"o\")\n plt.show()\n\nif __name__ == '__main__':\n main()","repo_name":"Ry0/convexHull","sub_path":"build/daen.py","file_name":"daen.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"33437687531","text":"import argparse\n\nfrom pathlib import Path\n\nfrom .core import NexeDecompiler\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"source\", help=\"source file path\", type=str)\nparser.add_argument(\n \"--dest\", help=\"destination directory, default is cwd\", type=str, default=None\n)\n\n\ndef path_sub(path: str) -> str:\n return path.replace(\"\\\\\", \"/\").replace(\"../\", \"\")\n\n\ndef cli():\n args = parser.parse_args()\n\n source = Path(args.source)\n\n if args.dest:\n dest = Path(args.dest).resolve()\n else:\n dest = Path.cwd().joinpath(f\"{source.name}_decompiled\")\n\n if not source.exists():\n print(f'\"{source}\" does not exist')\n return\n\n if not source.is_file():\n print(f\"Source must be a file\")\n return\n\n with source.open(\"rb\") as fp:\n decomp = NexeDecompiler.from_file(fp).decompile()\n\n dest.mkdir(parents=True, exist_ok=True)\n\n print(f\"Writing {len(decomp.files)} files to {dest}\")\n\n for path, data in decomp.files.items():\n path = path_sub(path)\n\n filepath = dest.joinpath(path)\n filepath.parent.mkdir(parents=True, exist_ok=True)\n filepath.write_bytes(data)\n\n entrypoint = dest.joinpath(path_sub(decomp.entrypoint))\n\n print(f\"Entrypoint located at {entrypoint}\")\n","repo_name":"unex/nexeDecompiler","sub_path":"nexedecompiler/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"20"} +{"seq_id":"29671114564","text":"#This is the code for AOC day 4--->contains both the parts\nfile1 = open(\"day4.txt\",\"r\")\ndata = file1.read().split('\\n') #reading the file\ncount = count2 =0\nfor i in range(len(data)):\n word = data[i]\n range1 = (word.split(','))[0]\n range2 = (word.split(','))[1]\n lower1 = int((range1.split('-')[0]))\n upper1 = int((range1.split('-')[1]))\n lower2 = int((range2.split('-')[0]))\n upper2 = int((range2.split('-')[1])) \n set1 = set()\n set2 = set()\n while(lower1<=upper1):\n set1.add(lower1)\n lower1+=1\n while(lower2<=upper2):\n set2.add(lower2)\n lower2+=1\n set3 = set1&set2\n if(set3 == set1 or set3 == set2):count+=1\n if(len(set3)!=0):count2+=1\nprint(count) #soln for the first problem\nprint(count2) #soln for the second problem","repo_name":"Aryaman-13/AOC_22","sub_path":"day4.py","file_name":"day4.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"39736357582","text":"# By Anders Gorm Pedersen, agpe@dtu.dk\n\nimport phylotreelib as pt\nimport argparse, os, sys, time, math, copy, psutil, statistics, configparser\nfrom itertools import (takewhile,repeat)\nfrom operator import itemgetter\nfrom pathlib import Path\nimport gc\n\ngc.disable() # Faster. Assume no cyclic references will ever be created\n\ndef main(commandlist=None):\n # Python note: \"commandlist\" is to enable unit testing of argparse code\n # https://jugmac00.github.io/blog/testing-argparse-applications-the-better-way/\n start=time.time()\n args = parse_commandline(commandlist)\n\n try:\n pid = psutil.Process(os.getpid())\n args.outbase.parent.mkdir(parents=True, exist_ok=True) # Create intermediate dirs\n if args.quiet:\n sys.stdout = open(os.devnull, 'w')\n\n wt_file_list = parse_infilelist(args)\n\n n_trees_analyzed, wt_count_burnin_filename_list = count_trees(wt_file_list, args)\n\n memory1 = pid.memory_full_info().rss\n\n treesummarylist = process_trees(wt_count_burnin_filename_list, args)\n\n if args.std:\n ave_std = compute_converge_stats(treesummarylist, args)\n\n treesummary = merge_treesummaries(treesummarylist)\n treesummary.add_branchid()\n\n contree, logcred = compute_and_print_contree(treesummary, args, wt_count_burnin_filename_list)\n\n compute_and_print_biparts(treesummary, args)\n\n if args.treeprobs:\n compute_and_print_trprobs(treesummary, args)\n if args.trackclades:\n n_topo_seen = len(treesummary.cladetoposummary)\n elif args.trackbips:\n n_topo_seen = len(treesummary.biptoposummary)\n\n stop=time.time()\n\n memory2 = pid.memory_full_info().rss\n memorymax = max(memory1, memory2)\n\n nrootkids = len(contree.children(contree.root))\n if nrootkids == 2:\n rootdegree = \"bifurcation\"\n elif nrootkids == 3:\n rootdegree = \"trifurcation\"\n else:\n rootdegree = \"multifurcation\"\n\n n_leaves = len(treesummary.leaves)\n if args.mcc:\n n_uniq_groupings = len(treesummary.cladesummary) - n_leaves\n else:\n n_uniq_groupings = len(treesummary.bipartsummary) - n_leaves\n\n theo_max_clades = n_leaves - 1\n theo_max_bips = n_leaves - 3\n if args.mcc:\n theo_max_groups = theo_max_clades\n else:\n theo_max_groups = theo_max_bips\n n_internal_biparts = contree.n_bipartitions()\n\n if args.mcc:\n treetype = \"MCC\"\n branchtype = \"clade\"\n space = \" \" * 7\n elif args.mbc:\n treetype = \"MBC\"\n branchtype = \"bipartition\"\n space = \" \" * 1\n else:\n treetype = \"Consensus\"\n branchtype = \"bipartition\"\n space = \" \" * 1\n\n # Information about bipartitions, clades and topologies\n print(f\"\\n Number of leaves on input trees: {n_leaves:>7,d}\")\n if args.treeprobs:\n print(\" Different topologies seen: {:>13,d}\".format(n_topo_seen))\n print(f\" Different {branchtype}s seen:{space}{n_uniq_groupings:>11,d} (theoretical maximum: {theo_max_groups * n_topo_seen:,d})\")\n else:\n print(f\" Different {branchtype}s seen:{space}{n_uniq_groupings:>11,d} (theoretical maximum: {theo_max_groups * n_trees_analyzed:,d})\")\n print(\" {:<34}\".format(f\"Bipartitions in {treetype} tree:\"), end=\"\")\n print(f\"{n_internal_biparts:>6,d} (theoretical maximum: {theo_max_bips:,d})\")\n\n if n_internal_biparts < theo_max_bips:\n print(\" (tree contains polytomies)\")\n else:\n print(\" (tree is fully resolved - no polytomies)\")\n\n\n # Information about rooting\n if not (args.actively_rooted or args.mcc):\n print(f\"\\n {treetype} tree has not been explicitly rooted\")\n print(f\" Tree has been rooted at random internal node; root is at {rootdegree}\")\n else:\n if args.outgroup:\n print(f\"\\n {treetype} tree has been rooted based on outgroup\")\n elif args.rootmid:\n print(f\"\\n {treetype} tree has been midpoint-rooted\")\n elif args.rootminvar:\n print(f\"\\n {treetype} tree has been rooted using minimum variance-rooting\")\n elif args.rootmaxfreq:\n print(f\"\\n {treetype} tree has been rooted at location most frequently observed in input trees\")\n elif args.mcc:\n print(f\"\\n MCC tree rooted at original root of tree sample having highest clade credibility\")\n\n if args.rootmaxfreq or args.mcc:\n print(f\" Root credibility (frequency of root location in input trees): {contree.rootcred * 100:.1f}%\")\n\n # Information about branch lengths\n if args.meandepth:\n print(f\"\\n Branch lengths set based on mean node depths in input trees\")\n else:\n print(f\"\\n Branch lengths set based on mean branch lengths for corresponding bipartitions\")\n\n # Information about log credibility\n if args.mbc or (args.mcc and not args.actively_rooted):\n print(f\"\\n Highest log {branchtype} credibility: {logcred:.6g}\")\n else:\n print(f\"\\n Log {branchtype} credibility: {logcred:.6g}\")\n\n if args.std:\n print((\" Average standard deviation of split frequencies: {:.6f}\".format(ave_std)))\n\n time_spent=stop-start\n h = int(time_spent/3600)\n m = int((time_spent % 3600)/60)\n s = int(time_spent % 60)\n print(\"\\n Done. {:,d} trees analyzed.\\n Time spent: {:d}:{:02d}:{:02d} (h:m:s)\".format(n_trees_analyzed, h, m, s))\n\n if memorymax > 1E9:\n print(\" Max memory used: {:,.2f} GB.\".format( memorymax / (1024**3) ))\n else:\n print(\" Max memory used: {:,.2f} MB.\".format( memorymax / (1024**2) ))\n\n\n except Exception as error:\n print(\"\\n\\nExecution failed:\\n\")\n if args.verbose:\n import traceback\n traceback.print_exc(file=sys.stdout)\n else:\n print(error)\n\n sys.exit()\n\n####################################################################################\n####################################################################################\n\ndef parse_commandline(commandlist):\n # Python note: \"commandlist\" is to enable unit testing of argparse code\n # Will be \"None\" when run in script mode, and argparse will then automatically take values from sys.argv[1:]\n\n parser = build_parser()\n args = parser.parse_args(commandlist)\n\n if args.version:\n config = configparser.ConfigParser()\n config.read('setup.cfg')\n try:\n print(config['metadata']['version'])\n exit()\n except KeyError:\n print(\"Unknown\")\n exit()\n\n if not (args.con or args.all or args.mcc or args.mbc):\n parser.error(\"One of --con, --all, --mcc, or --mbc must be specified.\")\n\n if not args.infilelist and not args.fileweights:\n parser.error(\"Please list one or more tree files.\")\n\n # If output basename is not set: use stem of infilenames minus all suffixes\n if not args.outbase:\n if args.infilelist:\n infilepath = args.infilelist[0]\n else:\n wt, infilepath = args.fileweights[0]\n args.outbase = Path(infilepath.stem.split('.')[0])\n\n if args.burninfrac > 1 or args.burninfrac < 0:\n parser.error(\"option -b: NUM must be between 0.0 and 1.0\")\n\n if args.treeprobs and (args.treeprobs > 1 or args.treeprobs < 0):\n parser.error(f\"option -t: NUM must be between 0.0 and 1.0 (provided value: -t {args.treeprobs})\")\n\n if args.infilelist:\n nfiles = len(args.infilelist)\n else:\n nfiles = len(args.fileweights)\n if args.std and nfiles==1:\n parser.error(\"cannot compute standard deviation (option -s) from one tree file\")\n\n if args.quiet:\n args.nowarn = True\n\n if args.mcc and (args.rootfile or args.outgroup or args.rootmid or args.rootminvar):\n parser.error(\"MCC tree is not compatible with any of these rooting methods: --rootmid, --rootminvar, --rootout, --rootfile\")\n\n if args.mcc:\n args.meandepth = True # Python note: will not be true by default when I implement CA heights\n\n # Bipartitions need to be tracked in these situations\n if args.con or args.all or args.mbc:\n args.trackbips = True\n else:\n args.trackbips = False\n\n # Clades need to be tracked in these situations:\n if args.mcc or args.meandepth:\n args.trackclades = True\n else:\n args.trackclades = False\n\n # Root needs to be tracked in these situations:\n if args.mcc or args.meandepth or args.rootmaxfreq:\n args.trackroot = True\n else:\n args.trackroot = False\n\n if args.rootfile:\n args.outgroup = read_outgroup(args.rootfile)\n\n if (args.outgroup or args.rootmid or args.rootminvar or args.rootmaxfreq):\n args.actively_rooted = True\n else:\n args.actively_rooted = False\n\n return args\n\n####################################################################################\n####################################################################################\n\ndef build_parser():\n\n parser = argparse.ArgumentParser(description = \"Computes summary tree and statistics from set of phylogenetic trees\")\n\n parser.add_argument('--version', action='store_true', dest=\"version\",\n help=\"show the program's version number and exit\")\n\n ####################################################################################\n\n sumtype_grp = parser.add_argument_group(\"Type of summary tree (pick one option)\")\n sumtype_excl = sumtype_grp.add_mutually_exclusive_group()\n\n sumtype_excl.add_argument(\"--con\", action=\"store_true\",\n help=\"majority rule consensus tree\")\n\n sumtype_excl.add_argument(\"--all\", action=\"store_true\",\n help=\"majority rule consensus tree with all compatible bipartitions added\")\n\n sumtype_excl.add_argument(\"--mcc\", action=\"store_true\",\n help=\"Maximum Clade Credibility (MCC) tree. \"\n + \"The MCC tree is determined by inspecting tree samples and selecting the \"\n + \"tree that has the highest product of clade frequencies (= highest sum of \"\n + \"log of clade frequencies). The MCC tree is therefore a tree that has been \"\n + \"observed in the pool of tree samples, differing from the consensus tree \"\n + \"which typically does not match any individual sample. \"\n + \"NOTE 1: only meaningful if input trees are estimated using clock model. \"\n + \"NOTE 2: by default, the MCC tree uses the rooting of the specific tree sample. \"\n + \"This will often (but not always) correspond to the \"\n + \"bipartition where the root is most commonly found in the input trees.\")\n\n sumtype_excl.add_argument(\"--mbc\", action=\"store_true\",\n help=\"Maximum Bipartition Credibility (MBC) tree. \"\n + \"The MBC tree is similar to the MCC tree \"\n + \"but counting bipartitions instead of clades, i.e. ignoring rooting \"\n + \"(two input trees can have the same set of bipartitions, but be rooted \"\n + \"in different locations).\")\n\n ####################################################################################\n\n root_grp = parser.add_argument_group(\"Rooting of summary tree\")\n root_excl = root_grp.add_mutually_exclusive_group()\n root_excl.add_argument(\"--rootmid\", action=\"store_true\",\n help=\"perform midpoint rooting of summary tree\")\n root_excl.add_argument(\"--rootminvar\", action=\"store_true\",\n help=\"perform minimum variance rooting of summary tree\")\n\n root_excl.add_argument(\"-r\", dest=\"outgroup\", metavar=\"TAXON\", nargs=\"+\", default=None,\n help=\"root summary tree on specified outgroup taxon/taxa\")\n\n root_excl.add_argument(\"--rootfile\", action=\"store\", metavar=\"FILE\", default=None,\n help=\"root summary tree on outgroup taxa listed in file (one name per line)\")\n\n root_excl.add_argument(\"--rootmaxfreq\", action=\"store_true\",\n help=\"root summary tree on bipartition where root is located most frequently in input trees. \" +\n \"NOTE: only meaningful if input trees are estimated using clock model\")\n\n ####################################################################################\n\n bayes_grp = parser.add_argument_group(\"Bayesian phylogeny options\")\n\n bayes_grp.add_argument(\"-b\", type=float, dest=\"burninfrac\", metavar=\"NUM\", default=0.0,\n help=\"burnin: fraction of trees to discard [0 - 1; default: %(default)s]\")\n\n bayes_grp.add_argument(\"-t\", type=float, dest=\"treeprobs\", metavar=\"NUM\",\n help=\"compute tree probabilities, report NUM percent credible interval [0 - 1]\")\n\n bayes_grp.add_argument(\"-s\", action=\"store_true\", dest=\"std\",\n help=\"compute average standard deviation of split frequencies (ASDSF)\")\n\n bayes_grp.add_argument(\"-f\", type=float, dest=\"minfreq\", metavar=\"NUM\", default=0.1,\n help=\"Minimum frequency for including bipartitions in report and in computation of ASDSF [default: %(default)s]\")\n\n ####################################################################################\n\n outformat_grp = parser.add_argument_group(\"Output to terminal and files\")\n\n outformat_grp.add_argument(\"-n\", action=\"store_true\", dest=\"nowarn\",\n help=\"no warning when overwriting files\")\n\n outformat_grp.add_argument(\"-v\", action=\"store_true\", dest=\"verbose\",\n help=\"verbose: show full traceback in the event of failed python execution\")\n\n outformat_grp.add_argument(\"-q\", action=\"store_true\", dest=\"quiet\",\n help=\"quiet: don't print progress indication to terminal window. NOTE: also turns on the -n option\")\n\n outformat_grp.add_argument(\"--basename\", action=\"store\", type=Path, dest=\"outbase\", metavar=\"NAME\",\n help=\"base name of output files (default: derived from input file)\")\n\n ####################################################################################\n\n depth_grp = parser.add_argument_group(\"Estimation of node depths for clock trees\")\n depth_excl = depth_grp.add_mutually_exclusive_group()\n depth_excl.add_argument(\"--meandepth\", action=\"store_true\",\n help=\"set node depth for each clade to mean node depth observed for that clade \"\n + \"among input trees \"\n + \"(and branch lengths are then based on these depths). \"\n + \"NOTE 1: only meaningful if input trees are estimated using clock model. \"\n + \"NOTE 2: will only work if all clades in tree have been observed at least \"\n + \"once among input trees - the option will therefore fail for some rootings.\")\n\n ####################################################################################\n\n other_grp = parser.add_argument_group(\"Other options\")\n\n other_grp.add_argument(\"--autow\", action=\"store_true\", dest=\"autoweight\",\n help=\"automatically assign file weights based on tree counts, so all files have equal impact \"\n + \"(default is for all trees, not files, to be equally important)\")\n\n other_grp.add_argument(\"--informat\", action=\"store\", dest=\"informat\", metavar=\"FORMAT\",\n choices=[\"nexus\", \"newick\"], default=\"nexus\",\n help=\"format of input files: %(choices)s [default: %(default)s]\")\n\n\n ####################################################################################\n\n infile_grp = parser.add_argument_group(\"Input tree files\")\n infile_excl = infile_grp.add_mutually_exclusive_group()\n\n infile_excl.add_argument(\"-i\", action=\"append\", dest='infilelist', metavar='FILE', type=Path,\n help=\"input FILE(s) containing phylogenetic trees (repeat -i FILE option for each input file)\")\n\n infile_excl.add_argument(\"-w\", action=\"append\", dest=\"fileweights\",\n nargs=2, metavar=(\"WEIGHT\", \"FILE\"),\n help=\"input FILEs with specified weights (repeat -w WEIGHT FILE option for each input file)\")\n\n ####################################################################################\n\n return parser\n\n####################################################################################\n####################################################################################\n\ndef parse_infilelist(args):\n\n # If only unweighted filenames are given:\n # Reformat list of filenames into (weight, filename) tuple format expected by program\n # Set all weights to 1\n if args.infilelist:\n wt_file_list = [(1, filename) for filename in args.infilelist]\n\n # If only weighted filenames are listed:\n # Reformat list of tuples such that weight is in float (not string).\n # Normalize weights so their average is one.\n else:\n wt_file_list = []\n\n # Attempt to convert weight string to float. Print sensible error message if this fails\n for (wt_string, filename) in args.fileweights:\n try:\n wt = float(wt_string)\n except ValueError:\n msg = f'Invalid file weight: \"{wt_string}\" - value has to be a real number.'\n raise Exception(msg)\n wt_file_list.append((wt, filename))\n\n # Normalize weights, build final weight/file list:\n wtsum = 0.0\n n_files = len(wt_file_list)\n for (wt, filename) in wt_file_list:\n wtsum += wt\n wt_avg = wtsum / n_files\n wt_file_list = [(wt / wt_avg, filename) for (wt, filename) in wt_file_list]\n\n return wt_file_list\n\n####################################################################################\n####################################################################################\n\ndef read_outgroup(rootfile):\n infile = open(rootfile, \"r\")\n outgroup = []\n for line in infile:\n leaf = line.strip()\n outgroup.append(leaf)\n infile.close()\n return outgroup\n\n####################################################################################\n####################################################################################\n\ndef count_trees_by_parsing(filename, args):\n # Open treefile. Discard (i.e., silently pass by) the requested number of trees\n if args.informat == \"nexus\":\n treefile = pt.Nexustreefile(filename)\n else:\n treefile = pt.Newicktreefile(filename)\n treecount = 0\n for tree in treefile:\n treecount += 1\n return treecount\n\n####################################################################################\n#\n# def count_bytestring(filename, bytestring):\n# \"\"\"Fast counting of specific pattern. Bytestring argument must be given\n# with b modifier (e.g., b');')\"\"\"\n#\n# # from: https://stackoverflow.com/a/27517681/7836730\n# f = open(filename, 'rb')\n# bufsize = 1024*1024\n# bufgen = takewhile(lambda x: x, (f.raw.read(bufsize) for _ in repeat(None)))\n# return sum( buf.count(bytestring) for buf in bufgen)\n#\n####################################################################################\n\ndef count_bytestring(filename, bytestring):\n \"\"\"Fast counting of specific pattern. Bytestring argument must be given\n with b modifier (e.g., b');')\"\"\"\n\n # Modified from: https://stackoverflow.com/a/27517681/7836730\n with open(filename, 'rb') as f:\n bufsize = 1024*1024\n bufgen = takewhile(lambda x: x, (f.raw.read(bufsize) for _ in repeat(None)))\n\n prev_buf = b\"\"\n count = 0\n\n for buf in bufgen:\n count += buf.count(bytestring)\n\n # For multi-byte patterns, consider overlaps between buffers\n if len(bytestring) > 1 and len(prev_buf) > 0:\n merged = prev_buf[-len(bytestring)+1:] + buf[:len(bytestring)-1]\n count += merged.count(bytestring)\n\n prev_buf = buf\n\n return count\n\n####################################################################################\n\ndef fast_treecount(filename, args):\n \"\"\"Heuristic: count patterns ([;=\\n] etc) to infer number of trees\"\"\"\n\n # Empirically: if ); is in file, then this == number of trees\n n_terminators = count_bytestring(filename, b\");\")\n if n_terminators > 0:\n return n_terminators\n\n # Count semicolon: if == 1 (possibly after nexus correction): 1 tree\n n_semicolons = count_bytestring(filename, b\";\")\n if n_semicolons == 1:\n return 1\n if args.informat == \"nexus\":\n n_other_semicolon_patterns = count_bytestring(filename, b\"egin taxa;\")\n n_other_semicolon_patterns += count_bytestring(filename, b\"egin trees;\")\n n_other_semicolon_patterns += count_bytestring(filename, b\"nd;\")\n n_other_semicolon_patterns += count_bytestring(filename, b\"imensions ntax\")\n n_other_semicolon_patterns += count_bytestring(filename, b\"axlabels\")\n n_other_semicolon_patterns += count_bytestring(filename, b\"ranslate\")\n n_semicolons -= n_other_semicolon_patterns\n if n_semicolons == 1:\n return 1\n\n # If we got this far, and filetype is newick then bail out and use precise counting\n if args.informat == \"newick\":\n return count_trees_by_parsing(filename, args)\n\n # Final attempt to infer ntrees for nexus files:\n # count \"= (\", \"= and \"tree \"\n # Add the values that are not 0 to list, choose minimum as count\n # Should be robust to most variations, but should check at end of sumt...\n n_eqparen = count_bytestring(filename, b\"= (\")\n n_treestr = count_bytestring(filename, b\"tree \")\n countlist = [n_semicolons, n_eqparen, n_treestr]\n notzero = [val for val in countlist if val>0]\n return min(countlist)\n\n####################################################################################\n\ndef count_trees(wt_file_list, args):\n\n count_list = []\n burnin_list = []\n for (wt, filename) in wt_file_list:\n treelist = []\n sys.stdout.write(f\" Counting trees in file {str(filename):<40}\")\n sys.stdout.flush()\n n_tot = fast_treecount(filename, args)\n sys.stdout.write(f\"{n_tot:>15,d}\\n\")\n sys.stdout.flush()\n burnin = int(args.burninfrac * n_tot)\n count_list.append(n_tot)\n burnin_list.append(burnin)\n\n # If automatic weighting requested: Compute new weights\n if args.autoweight:\n countsum = sum(count_list)\n countavg = countsum / len(count_list)\n new_wt_list = [count / countavg for count in count_list] # Normalized so avg=1\n\n # Construct final combined wt + count + burnin + filename list\n wt_count_burnin_filename_list = []\n for i in range(len(wt_file_list)):\n filename = wt_file_list[i][1]\n count = count_list[i]\n burnin = burnin_list[i]\n if args.autoweight:\n wt = new_wt_list[i]\n else:\n wt = wt_file_list[i][0]\n\n wt_count_burnin_filename_list.append((wt, count, burnin, filename))\n\n n_trees_analyzed = sum(count_list) - sum (burnin_list)\n return (n_trees_analyzed, wt_count_burnin_filename_list)\n\n####################################################################################\n####################################################################################\n\ndef process_trees(wt_count_burnin_filename_list, args):\n\n treesummarylist = []\n interner = pt.Interner()\n for i, (weight, count, burnin, filename) in enumerate(wt_count_burnin_filename_list):\n\n sys.stdout.write(\"\\n Analyzing file: {} (Weight: {:5.3f})\".format(filename, weight))\n sys.stdout.flush()\n\n # Open treefile. Discard (i.e., silently pass by) the requested number of trees\n if args.informat == \"nexus\":\n treefile = pt.Nexustreefile(filename, interner=interner)\n else:\n treefile = pt.Newicktreefile(filename, interner=interner)\n for j in range(burnin):\n treefile.readtree(returntree=False)\n sys.stdout.write(f\"\\n Discarded {burnin:,} of {count:,} trees (burnin fraction={args.burninfrac:.2f})\")\n\n # Instantiate Treesummary.\n trackbips = args.trackbips\n trackclades = args.trackclades\n trackroot = args.trackroot\n if args.mcc or args.mbc or args.treeprobs:\n treesummary = pt.BigTreeSummary(store_trees=args.treeprobs,\n trackbips=trackbips, trackclades=trackclades, trackroot=trackroot)\n else:\n treesummary = pt.TreeSummary(trackbips=trackbips, trackclades=trackclades, trackroot=trackroot)\n\n # Read remaining trees from file, add to treesummary\n sys.stdout.write(\"\\n\\n Processing trees:\")\n sys.stdout.flush()\n sys.stdout.write(\"\\n \")\n\n # Progress indicator (bar going to 100%)\n progscale = \"0 10 20 30 40 50 60 70 80 90 100\"\n progticks = \"v-------v-------v-------v-------v-------v-------v-------v-------v-------v-------v\"\n ndots = len(progticks)\n n_tot = count - burnin\n trees_per_dot = n_tot / ndots\n sys.stdout.write(f\"\\n {progscale}\\n\")\n sys.stdout.write(f\" {progticks}\\n \")\n\n n_trees = 0\n n_dotsprinted = 0\n for tree in treefile:\n treesummary.add_tree(tree, weight)\n n_trees += 1\n n_dots_expected = math.floor(n_trees / trees_per_dot)\n if n_dotsprinted < n_dots_expected:\n n_missing = n_dots_expected - n_dotsprinted\n sys.stdout.write(\"*\" * n_missing)\n sys.stdout.flush()\n n_dotsprinted += n_missing\n del tree\n\n # Ensure all dots are printed at the end if they haven't been already\n if n_dotsprinted < ndots:\n n_missing = ndots - n_dotsprinted\n sys.stdout.write(\"*\" * n_missing)\n sys.stdout.flush()\n\n treesummarylist.append(treesummary)\n print(\"\\n\")\n\n return treesummarylist\n\n##########################################################################################\n##########################################################################################\n\ndef compute_converge_stats(treesummarylist, args):\n \"\"\"Compute average bipartition/clade frequency standard deviation between treesummaries\"\"\"\n\n # NOTES ON COMPUTATION:\n # (1) all bipartitions/clades are included in computation, regardless of whether they are present\n # in only one of the treesummaries (their freq is set to zero in those treesummaries\n # where they are not present)\n # (2) external branches (leading to leafs) are not included in computation since they\n # will allways be present in all trees (=> p=1, std=0)\n # (3) N-1 is used in the denominator when computing std. This has to do with sample vs.\n # population estimates of std, and is in accordance with what MrBayes does. One could\n # argue that N should be used instead of N-1 (to get the Max Likelihood estimate of std).\n\n if args.mcc:\n ave_std = compute_converge_clades(treesummarylist, args)\n else:\n ave_std = compute_converge_biparts(treesummarylist, args)\n return ave_std\n\n##########################################################################################\n##########################################################################################\n\ndef compute_converge_biparts(treesummarylist, args):\n sum_std = 0\n N = float(len(treesummarylist))\n\n # Find combined set of bipartitions (excluding external branches)\n # Only biparts that have freq >= minfreq are kept\n bipset = set()\n for treesummary in treesummarylist:\n for bipart,branch in treesummary.bipartsummary.items():\n (bip1, bip2) = bipart\n if len(bip1)>1 and len(bip2)>1 and branch.freq >= args.minfreq:\n bipset.add(bipart)\n\n # For each internal bipart: compute std of freq of this bipart across all treesummaries\n for bipart in bipset:\n freqlist = []\n for treesummary in treesummarylist:\n # If current bipartition not in current treesummary: set freq=0.0\n if bipart in treesummary.bipartsummary:\n freqlist.append(treesummary.bipartsummary[bipart].freq)\n else:\n freqlist.append(0.0)\n sum_std += statistics.stdev(freqlist)\n\n ave_std = sum_std / len(bipset)\n return ave_std\n\n##########################################################################################\n##########################################################################################\n\ndef compute_converge_clades(treesummarylist, args):\n sum_std = 0\n N = float(len(treesummarylist))\n\n # Find combined set of clades (excluding leaves)\n # Only clades that have freq >= minfreq are kept\n cladeset = set()\n for treesummary in treesummarylist:\n for clade,node in treesummary.cladesummary.items():\n leafset = clade.get_clade()\n if len(leafset)>1 and node.freq >= args.minfreq:\n cladeset.add(clade)\n\n # For each internal bipart: compute std of freq of this bipart across all treesummaries\n for clade in cladeset:\n freqlist = []\n for treesummary in treesummarylist:\n # If current clade not in current treesummary: set freq=0.0\n if clade in treesummary.cladesummary:\n freqlist.append(treesummary.cladesummary[clade].freq)\n else:\n freqlist.append(0.0)\n sum_std += statistics.stdev(freqlist)\n\n ave_std = sum_std / len(cladeset)\n return ave_std\n\n##########################################################################################\n##########################################################################################\n\ndef merge_treesummaries(treesummarylist):\n\n treesummary = treesummarylist[0]\n for treesummary2 in treesummarylist[1:]:\n treesummary.update(treesummary2)\n del treesummary2\n return treesummary\n\n##########################################################################################\n##########################################################################################\n\ndef compute_and_print_biparts(treesummary, args):\n\n # Compute and retrieve results\n (leaflist, bipreslist) = bipart_report(treesummary, args)\n\n # Before printing results: check whether files already exist\n partsfilename = args.outbase.parent / (args.outbase.name + \".parts\")\n if args.nowarn:\n partsfile = open(partsfilename, \"w\")\n elif partsfilename.is_file():\n overwrite = input(f\" File {partsfilename} already exists.\\n Overwrite (y/n): \")\n if overwrite== \"y\":\n partsfile = open(partsfilename, \"w\") # Overwrite\n print(f\" Overwriting file {partsfilename}\\n\")\n else:\n partsfile = open(partsfilename, \"a\") # Append\n print(f\" Appending to file {partsfilename}\\n\")\n else:\n partsfile = open(partsfilename, \"w\")\n\n # Print bipartitions\n partsfile.write(\"List of bipartitions:\\n\\n\"\n \"PART = Description of partition in .* format\\n\"\n \"PROB = Posterior probability of the partition\\n\"\n \"BLEN = Mean branch length\\n\"\n \"VAR = Branch length variance\\n\"\n \"SEM = Standard error of the mean for branch length\\n\"\n \"ID = Leaf name or internal branch label, for those bipartitions that are included in consensus tree\\n\\n\")\n stringwidth = len(leaflist)\n partsfile.write(\"PART\" + (stringwidth-1)*\" \" + \"PROB \" + \"BLEN \" + \"VAR \" + \"SEM \" + \"ID\\n\")\n\n for (_, _, bipstring, freq, mean, var, sem, branchID) in bipreslist:\n if var == \"NA\":\n partsfile.write(f\"{bipstring} {freq:<8.6f} {mean:<9.4g} ({var:<9}) ({sem:<9}) {branchID}\\n\")\n else:\n partsfile.write(f\"{bipstring} {freq:<8.6f} {mean:<9.4g} ({var:<9.4g}) ({sem:<9.4g}) {branchID}\\n\")\n partsfile.close()\n print(f\" Bipartition list written to {partsfilename}\")\n\n##########################################################################################\n##########################################################################################\n\ndef bipart_report(treesummary, args):\n \"\"\"Return processed, almost directly printable, summary of all observed bipartitions\"\"\"\n\n leaflist = sorted(treesummary.leaves)\n position_dict = {}\n for position, leaf in enumerate(leaflist):\n position_dict[leaf] = position\n bipreport = []\n for _,bipart in treesummary.sorted_biplist:\n branch = treesummary.bipartsummary[bipart]\n freq = branch.freq\n if freq > args.minfreq:\n bipstring = bipart_to_string(bipart, position_dict, leaflist)\n bipsize = bipstring.count(\"*\") # Size of smaller set\n bipreport.append([1-freq, bipsize, bipstring,\n freq, branch.length, branch.var, branch.sem, branch.branchID])\n bipreport = sorted(bipreport, key=itemgetter(0,1,2))\n # Return tuple of (leaflist, bipreport)\n return (leaflist, bipreport)\n\n##########################################################################################\n\ndef bipart_to_string(bipartition, position_dict, leaflist):\n \"\"\"Takes bipartition (set of two leaf sets) and returns string representation\"\"\"\n\n bipart1, bipart2 = bipartition\n\n # Bipartstring will be built as a list of chars first. Initialize with all \".\"\n stringwidth = len(leaflist)\n bipart_list = stringwidth * [\".\"]\n\n # Smaller set is represented by \"*\" characters. Larger set by \".\" characters (already set)\n if len(bipart1) < len(bipart2):\n smallset = bipart1\n else:\n smallset = bipart2\n\n for leaf in smallset:\n pos = position_dict[leaf]\n bipart_list[pos] = \"*\"\n\n return \"\".join(bipart_list) # Concatenate into one string\n\n##########################################################################################\n##########################################################################################\n\ndef compute_and_print_contree(treesummary, args, wt_count_burnin_filename_list):\n\n if args.mcc:\n sys.stdout.write(\"\\n Finding Maximum Clade Credibility tree...\")\n sys.stdout.flush()\n contree, logcred = treesummary.max_clade_cred_tree()\n contree.rootcred = treesummary.compute_rootcred(contree)\n elif args.mbc:\n sys.stdout.write(\"\\n Finding Maximum Bipartition Credibility tree...\")\n sys.stdout.flush()\n contree, logcred = treesummary.max_bipart_cred_tree()\n else:\n sys.stdout.write(\"\\n Computing consensus tree...\")\n sys.stdout.flush()\n contree = treesummary.contree(allcompat=args.all)\n logcred = treesummary.log_bipart_credibility(contree.topology())\n sys.stdout.write(\"done.\\n\")\n sys.stdout.flush()\n\n if args.outgroup:\n contree.rootout(args.outgroup)\n elif args.rootmid:\n contree.rootmid()\n elif args.rootminvar:\n contree.rootminvar()\n elif args.rootmaxfreq:\n treesummary.root_maxfreq(contree)\n\n # If MCC tree was re-rooted, then we need to recompute log clade credibility\n if args.mcc and args.actively_rooted:\n clade_topology = contree.topology_clade\n logcred = treesummary.log_clade_credibility(clade_topology)\n\n # meandepth can be requested for all contree types (but will only make sense if they are based on clock trees)\n if args.meandepth:\n contree = treesummary.set_mean_node_depths(contree)\n\n # If root is bifurcation and one child is leaf: Remove branchID (=leafname) and label from other child-branch\n # (In this case both branches from root are the same bipartition, so not useful to label internal branch part)\n # Python note: not sure this generalizes to all tree types. think...\n rootkids = contree.children(contree.root)\n if (len(rootkids) == 2) and (rootkids & contree.leaves):\n rootkids = list(rootkids)\n if rootkids[0] in contree.leaves:\n node2 = rootkids[1]\n else:\n node2 = rootkids[0]\n contree.set_branch_attribute(contree.root, node2, \"branchID\", \"\")\n contree.set_branch_attribute(contree.root, node2, \"label\", \"\")\n\n newick_prob_tree = contree.newick(labelfield=\"label\")\n if not args.mcc:\n newick_branchID_tree = contree.newick(labelfield=\"branchID\")\n\n if args.mbc:\n confilename = args.outbase.parent / (args.outbase.name + \".mbc\")\n elif args.mcc:\n confilename = args.outbase.parent / (args.outbase.name + \".mcc\")\n elif args.all:\n confilename = args.outbase.parent / (args.outbase.name + \".all\")\n else:\n confilename = args.outbase.parent / (args.outbase.name + \".con\")\n if args.nowarn:\n confile = open(confilename, \"w\")\n elif confilename.is_file():\n overwrite = input(f\"\\n File {confilename} already exists.\\n Overwrite (y/n): \")\n if overwrite== \"y\":\n confile = open(confilename, \"w\") # Overwrite\n print(\" Overwriting file {}\\n\".format(confilename))\n else:\n confile = open(confilename, \"a\") # Append\n print(\" Appending to file {}\\n\".format(confilename))\n else:\n confile = open(confilename, \"w\")\n\n confile.write(\"#NEXUS\\n\")\n confile.write(\"\\n\")\n confile.write(\"begin trees;\\n\")\n confile.write(\" [In this tree branch labels indicate the posterior probability of the bipartition corresponding to the branch.]\\n\")\n confile.write(\" tree prob = \")\n confile.write(newick_prob_tree)\n if not args.mcc:\n confile.write(\"\\n\\n [In this tree branch labels indicate the bipartition ID listed in the file {}.\\n\".format(args.outbase.name + \".parts\"))\n confile.write(\" These branch labels can be used for interpreting the table of branch lenght info in that file]\\n\")\n confile.write(\" tree partID = \")\n confile.write(newick_branchID_tree)\n confile.write(\"\\nend;\\n\")\n confile.close()\n\n if args.mbc:\n print(f\" Maximum bipartition credibility tree written to {confilename}\")\n elif args.mcc:\n print(f\" Maximum clade credibility tree written to {confilename}\")\n else:\n print(f\" Consensus tree written to {confilename}\")\n\n return contree, logcred\n\n##########################################################################################\n##########################################################################################\n\ndef compute_and_print_trprobs(treesummary, args):\n topolist = topo_report(treesummary, args)\n\n # Before printing results: check whether file already exist\n topofilename = args.outbase.parent / (args.outbase.name + \".trprobs\")\n if args.nowarn:\n topofile = open(topofilename, \"w\")\n elif topofilename.is_file():\n overwrite = input(f\"\\n File {topofilename} already exists.\\n Overwrite (y/n): \")\n if overwrite== \"y\":\n topofile = open(topofilename, \"w\") # Overwrite\n print(f\" Overwriting file {topofilename}\\n\")\n else:\n topofile = open(topofilename, \"a\") # Append\n print(f\" Appending to file {topofilename}\\n\")\n else:\n topofile = open(topofilename, \"w\")\n\n topofile.write(\"#NEXUS\\n\")\n topofile.write(\"\\n\")\n if args.treeprobs < 1:\n topofile.write(f\"[This file contains the {round(args.treeprobs*100)}% most probable trees found during the\\n\")\n topofile.write(f\"MCMC search, sorted by posterior probability (the {round(args.treeprobs*100)}% HPD interval).\\n\")\n else:\n topofile.write(\"[This file contains all trees that were found during the MCMC\\n\")\n topofile.write(\"search, sorted by posterior probability. \\n\")\n topofile.write(\"Lower case 'p' indicates the posterior probability of a tree.\\n\")\n topofile.write(\"Upper case 'P' indicates the cumulative posterior probability.]\\n\")\n topofile.write(\"\\n\")\n topofile.write(\"begin trees;\\n\")\n topofile.write(treesummary.translateblock)\n n=1\n cum = 0.0\n for (freq, tree) in topolist:\n cum += freq\n treestring = tree.newick(printdist=False, printlabels=False, transdict=treesummary.transdict)\n topofile.write(f\" tree tree_{n} [p = {freq:.6f}] [P = {cum:.6f}] = {treestring}\\n\")\n n += 1\n if cum > args.treeprobs:\n break\n\n topofile.write(\"end;\\n\")\n topofile.close()\n print(f\" Tree probabilities written to {topofilename}\")\n\n##########################################################################################\n##########################################################################################\n\ndef topo_report(treesummary, args):\n \"\"\"Returns list of [freq, treestring] lists\"\"\"\n\n # Python note: root trees in trprobs?\n if treesummary.trackclades:\n toposummary = treesummary.cladetoposummary\n elif treesummary.trackbips:\n toposummary = treesummary.biptoposummary\n toporeport = []\n for topology, topostruct in toposummary.items():\n toporeport.append((topostruct.freq, topostruct.tree))\n\n # Sort report according to frequency (higher values first) and return\n toporeport = sorted(toporeport, key=itemgetter(0), reverse=True)\n\n return toporeport\n\n##########################################################################################\n##########################################################################################\n\nif __name__ == \"__main__\":\n main()\n # import cProfile\n # cProfile.run('main()', 'tmp/profile.pstats')\n","repo_name":"agormp/sumt","sub_path":"sumt.py","file_name":"sumt.py","file_ext":"py","file_size_in_byte":42579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17529834611","text":"import pandas as pd\nimport logging\nimport snakemake\n\n# The hierarchy of the enrich2 config file elements is as follows:\n# experiment\n# conditions\n# tiles (if applicable: implemented as individual conditions)\n# replicates\n# timepoints/bins (individual samples)\n\n\ndef tiled_config(conditions, experiments, tsv_path, output_directory):\n \"\"\"Generate the Enrich2 config file for tiled experiments.\"\"\"\n enrich2_config = [\"{\", '\\t\"conditions\": [']\n\n for condition in conditions:\n tiles = experiments.loc[(experiments[\"condition\"] == condition)][\n \"tile\"\n ].unique()\n\n for tile in tiles:\n # open condition\n enrich2_config.extend([\"\\t{\"])\n # condition name\n enrich2_config.extend(\n ['\\t\\t\"name\": \"' + condition + \"_tile\" + str(tile) + '\",']\n )\n # start selections (a.k.a. set of replicates)\n enrich2_config.extend(['\\t\\t\"selections\": ['])\n\n replicates = experiments.loc[\n (experiments[\"condition\"] == condition) & (experiments[\"tile\"] == tile)\n ][\"replicate\"].unique()\n\n for replicate in replicates:\n timepoints = experiments.loc[\n (experiments[\"condition\"] == condition)\n & (experiments[\"replicate\"] == replicate)\n & (experiments[\"tile\"] == tile)\n ][\"time\"].unique()\n\n # open library (a.k.a. single replicate)\n enrich2_config.extend([\"\\t\\t{\"])\n # start libraries\n enrich2_config.extend(['\\t\\t\\t\"libraries\": ['])\n for time in timepoints:\n sample_name = experiments.loc[\n (experiments[\"condition\"] == condition)\n & (experiments[\"replicate\"] == replicate)\n & (experiments[\"time\"] == time)\n & (experiments[\"tile\"] == tile)\n ][\"sample\"].iloc[0]\n\n # open file definition\n name = \"{}_rep{}_T{}_tile{}\".format(\n condition, str(replicate), str(time), str(tile)\n )\n\n enrich2_config.extend([\"\\t\\t\\t\\t{\"])\n\n # close file definition\n enrich2_config.extend(\n [\n '\\t\\t\\t\\t\\t\"counts file\": \"'\n + tsv_path\n + sample_name\n + '.tsv\",',\n '\\t\\t\\t\\t\\t\"identifiers\": {},',\n '\\t\\t\\t\\t\\t\"name\": \"' + name + '\",',\n '\\t\\t\\t\\t\\t\"report filtered reads\": false,',\n '\\t\\t\\t\\t\\t\"timepoint\": ' + str(time),\n ]\n )\n if time == timepoints[-1]:\n enrich2_config.extend([\"\\t\\t\\t\\t}\"])\n else:\n enrich2_config.extend([\"\\t\\t\\t\\t},\"])\n\n # closes and completes library definition\n enrich2_config.extend([\"\\t\\t\\t],\"])\n enrich2_config.extend(\n [\n '\\t\\t\\t\"name\": \"'\n + condition\n + \"_R\"\n + str(replicate)\n + \"_tile\"\n + str(tile)\n + '\"'\n ]\n )\n if replicate == replicates[-1]:\n enrich2_config.extend([\"\\t\\t}\"])\n else:\n enrich2_config.extend([\"\\t\\t},\"])\n\n # closes replicate\n enrich2_config.extend([\"\\t\\t]\"])\n\n # closes condition. Checks for this being the last\n # condition in the file, as well.\n if condition == conditions[-1] and tile == tiles[-1]:\n enrich2_config.extend([\"\\t}\"])\n else:\n enrich2_config.extend([\"\\t},\"])\n\n enrich2_config.extend([\"\\t],\"])\n enrich2_config.extend(['\"name\": \"' + experiment_name + '\",'])\n enrich2_config.extend(['\"output directory\": \"' + output_directory + '\"'])\n enrich2_config.extend([\"}\"])\n\n return enrich2_config\n\n\ndef untiled_config(conditions, experiments, tsv_path, output_directory):\n \"\"\"Generate the Enrich2 config file for untiled experiments.\"\"\"\n enrich2_config = [\"{\", '\\t\"conditions\": [']\n\n for condition in conditions:\n # open condition\n enrich2_config.extend([\"\\t{\"])\n # condition name\n enrich2_config.extend(['\\t\\t\"name\": \"' + condition + '\",'])\n # start selections (a.k.a. set of replicates)\n enrich2_config.extend(['\\t\\t\"selections\": ['])\n\n replicates = experiments.loc[(experiments[\"condition\"] == condition)][\n \"replicate\"\n ].unique()\n\n for replicate in replicates:\n timepoints = experiments.loc[\n (experiments[\"condition\"] == condition)\n & (experiments[\"replicate\"] == replicate)\n ][\"time\"].unique()\n\n # open library (a.k.a. single replicate)\n enrich2_config.extend([\"\\t\\t{\"])\n # start libraries\n enrich2_config.extend(['\\t\\t\\t\"libraries\": ['])\n for time in timepoints:\n sample_name = experiments.loc[\n (experiments[\"condition\"] == condition)\n & (experiments[\"replicate\"] == replicate)\n & (experiments[\"time\"] == time)\n ][\"sample\"].iloc[0]\n\n # open file definition\n name = \"{}_rep{}_T{}\".format(condition, str(replicate), str(time))\n\n enrich2_config.extend([\"\\t\\t\\t\\t{\"])\n\n # close file definition\n enrich2_config.extend(\n [\n '\\t\\t\\t\\t\\t\"counts file\": \"'\n + tsv_path\n + sample_name\n + '.tsv\",',\n '\\t\\t\\t\\t\\t\"identifiers\": {},',\n '\\t\\t\\t\\t\\t\"name\": \"' + name + '\",',\n '\\t\\t\\t\\t\\t\"report filtered reads\": false,',\n '\\t\\t\\t\\t\\t\"timepoint\": ' + str(time),\n ]\n )\n if time == timepoints[-1]:\n enrich2_config.extend([\"\\t\\t\\t\\t}\"])\n else:\n enrich2_config.extend([\"\\t\\t\\t\\t},\"])\n\n # closes and completes library definition\n enrich2_config.extend([\"\\t\\t\\t],\"])\n enrich2_config.extend(\n ['\\t\\t\\t\"name\": \"' + condition + \"_R\" + str(replicate) + '\"']\n )\n if replicate == replicates[-1]:\n enrich2_config.extend([\"\\t\\t}\"])\n else:\n enrich2_config.extend([\"\\t\\t},\"])\n\n # closes replicate\n enrich2_config.extend([\"\\t\\t]\"])\n\n # closes condition\n if condition == conditions[-1]:\n enrich2_config.extend([\"\\t}\"])\n else:\n enrich2_config.extend([\"\\t},\"])\n\n enrich2_config.extend([\"\\t],\"])\n enrich2_config.extend(['\"name\": \"' + experiment_name + '\",'])\n enrich2_config.extend(['\"output directory\": \"' + output_directory + '\"'])\n enrich2_config.extend([\"}\"])\n\n return enrich2_config\n\n\noutput_file = snakemake.output[0]\nlog_file = snakemake.log[0]\n\n# Set up logging\nif log_file:\n logging.basicConfig(filename=log_file, filemode=\"w\", level=logging.DEBUG)\nelse:\n logging.basicConfig(level=logging.DEBUG)\n\nexperiment_name = snakemake.config[\"experiment\"]\ntsv_path = \"results\" + \"/\" + experiment_name + \"/processed_counts/\"\n\nbaseline_condition = snakemake.config[\"baseline_condition\"]\n\noutput_directory = \"results\" + \"/\" + experiment_name + \"/enrich/\"\n\nexperiments = (\n pd.read_csv(snakemake.config[\"experiment_file\"], header=0)\n .dropna(how=\"all\")\n .set_index(\"sample\", drop=False, verify_integrity=True)\n)\n\nconditions = experiments[\"condition\"].unique().tolist()\n\n# Do not generate scores for the baseline condition, if it exists.\nif baseline_condition:\n try:\n conditions.remove(baseline_condition)\n except ValueError:\n logging.warning(\n \"Baseline condition %s not found in experiment file.\", baseline_condition\n )\n\n# Generate the Enrich2 config file\nif snakemake.config[\"tiled\"]:\n enrich2_config_lines = tiled_config(conditions, experiments, tsv_path, output_directory)\nelse:\n enrich2_config_lines = untiled_config(conditions, experiments, tsv_path, output_directory)\n\nwith open(output_file, \"w+\") as f:\n for line in enrich2_config_lines:\n f.write(line + \"\\n\")\n","repo_name":"odcambc/dumpling","sub_path":"workflow/rules/scripts/generate_enrich_configs.py","file_name":"generate_enrich_configs.py","file_ext":"py","file_size_in_byte":8773,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"72899660849","text":"import argparse\nimport json\nfrom pathlib import Path\nimport threading\nfrom datetime import datetime\n\nfrom google.oauth2 import service_account\nfrom apiclient.discovery import build_from_document\nfrom googleapiclient import discovery\nfrom google.cloud import storage\nfrom google.cloud import bigquery\n\n#SERVICE_ACCOUNT_FILE = str(Path.home()) + '/achintapatla-project-df6e964e0b56.json'\nSERVICE_ACCOUNT_FILE = 'achintapatla-project-df6e964e0b56.json'\nRECOMMENDER_DISCOVERY_DOC = 'recommender_discovery.json'\nSCOPE = 'https://www.googleapis.com/auth/cloud-platform'\n\n\"\"\"\nRECOMMENDER = 'google.compute.instance.MachineTypeRecommender'\nbq_table_id = 'MachineTypeRecommender'\ngcs_bucket = 'achintapatla-co-machine-type-recommender'\n\"\"\"\n\nRECOMMENDER = 'google.compute.instance.IdleResourceRecommender'\nbq_table_id = 'IdleResourceRecommender'\ngcs_bucket = 'achintapatla-co-idle-resource-recommender'\n\nRECOMMENDATION_FILE_PREFIX = 'rec_output-'\n\nbq_dataset_id = 'cost_optimization'\n\ngcs_project = 'achintapatla-project'\ndate_time = datetime.now()\nbucket_prefix = date_time.strftime(\"%Y-%m-%d\")\n\n\ndef get_credentials():\n credentials = service_account.Credentials.from_service_account_file(\n SERVICE_ACCOUNT_FILE, scopes=[SCOPE])\n return credentials\n\n\ndef get_zones_list(credentials, project):\n service = discovery.build('compute', 'v1', credentials=credentials)\n zones = []\n response = service.zones().list(project=project).execute()\n for r in response['items']:\n zones.append(r['name'])\n return zones\n\n\ndef get_projects_list(credentials):\n service = discovery.build('cloudresourcemanager', 'v1', credentials=credentials)\n projects = []\n request = service.projects().list()\n response = request.execute()\n for p in response['projects']:\n if (p['lifecycleState'] == 'ACTIVE'):\n projects.append(p['projectId'])\n print(\"projectId {}\".format(p['projectId']))\n return projects\n\n\ndef get_recommendation_service(credentials):\n with open(RECOMMENDER_DISCOVERY_DOC, 'r') as f:\n doc = f.read()\n return build_from_document(doc, credentials=credentials)\n\ndef get_recommendation_service_ga(credentials):\n service = discovery.build('recommender', 'v1', credentials=credentials)\n return service\n\ndef upload_to_gcs(project, bucket, target, data):\n print(\"BEFORE upload_to_gcs bucket {0} file {1}\", bucket, target)\n gcs = storage.Client(gcs_project)\n print(\"AFTER gcs\")\n\n try:\n #output_bucket = gcs.get_bucket(bucket)\n output_bucket = gcs.bucket(bucket)\n print(\"AFTER output_bucket\")\n blob=output_bucket.blob(target)\n print(\"AFTER blob\")\n ret_val = blob.upload_from_string(data)\n print(\"AFTER upload_to_gcs bucket {0} file {1} ret {2}\", bucket, target, ret_val)\n #except google.cloud.exceptions.NotFound:\n # print(\"Sorry, that bucket does not exist! {0}\", bucket)\n except Exception as ex:\n template = \"upload_to_gcs:: exception of type {0} occurred. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print (message)\n\n\ndef bulk_load_bq(dataset, table, gcs_uri):\n client = bigquery.Client()\n dataset_ref = client.dataset(dataset)\n job_config = bigquery.LoadJobConfig()\n job_config.autodetect = True\n job_config.source_format = bigquery.SourceFormat.NEWLINE_DELIMITED_JSON\n\n load_job = client.load_table_from_uri(\n gcs_uri,\n dataset_ref.table(table),\n job_config=job_config,\n )\n print(\"Starting BigQuery bulk load job {}\".format(load_job.job_id))\n\n load_job.result() # Waits for table load to complete.\n print(\"BigQuery Job finished.\")\n\n\ndef collect_recommendations_data(credentials, service, p):\n zones = get_zones_list(credentials, p)\n for z in zones:\n parent = str.format('projects/{0}/locations/{1}/recommenders/{2}', p,\n z, RECOMMENDER)\n\n request = service.projects().locations().recommenders().recommendations().list(\n parent=parent)\n\n try:\n response = request.execute()\n print(\"===========================================================\")\n print(\"collect_recommendations_data {} : {}\".format(p,z))\n if response:\n json_string = \"\\n\".join(json.dumps(x) for x in response['recommendations'])\n\n #print(json_string[])\n #print(\"Response json {}\".format(json_string))\n gcs_json_file = bucket_prefix + '/' + \\\n RECOMMENDATION_FILE_PREFIX + \\\n p + \"-\" + z + \".json\"\n print(\"gcs_json_file {}\".format(gcs_json_file))\n upload_to_gcs(p, gcs_bucket, gcs_json_file, json_string)\n print(\"===========================================================\")\n\n #except:\n # print(\"===========================================================\")\n # print(\"API Error in Project {}, Zone {}\".format(p, z))\n except Exception as ex:\n template = \"collect_recommendations_data:: exception of type {0} occurred. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print (message)\n\ncredentials = get_credentials()\nservice = get_recommendation_service_ga(credentials)\nprojects = get_projects_list(credentials)\n\n#projects =['psosapproj']\nprint(\"Execute\")\n\n\"\"\"\napi_threads = []\nfor p in projects:\n api_thread = threading.Thread(target=collect_recommendations_data,\n args=(credentials, service, p), name=p)\n api_threads.append(api_thread)\n api_thread.start()\n\n# Wait for all threads to complete\nfor i in api_threads:\n i.join()\n\"\"\"\nfor p in projects:\n try:\n collect_recommendations_data(credentials, service, p)\n except Exception as ex:\n template = \"for loop:: exception of type {0} occurred. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print (message)\n\ngcs_uri = \"gs://\" + gcs_bucket + \"/\" + bucket_prefix + \"/*.json\"\nbulk_load_bq(bq_dataset_id, bq_table_id, gcs_uri)","repo_name":"zhongchen/gcp-billing","sub_path":"scripts/recommend_api.py","file_name":"recommend_api.py","file_ext":"py","file_size_in_byte":6153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"42487980103","text":"import nltk\nfrom nltk.corpus import gutenberg\nfrom nltk import pos_tag\nfrom nltk.probability import FreqDist\n\nwords = gutenberg.words('melville-moby_dick.txt')\ntaggeds = pos_tag(words)\n\ntags = [tagged[1].lower() for tagged in taggeds]\nprint('Adliklar')\nprint(tags)\n\ndistribution = FreqDist(tags)\ndistribution.plot(title='Adlik Sirtliklari')\n\nbins = distribution.B()\nprint('Kovalar')\nprint(bins)\n\nnumbers = distribution.N()\nprint('Sayilar')\nprint(numbers)\n\nnoun_count = distribution['nn']\nprint('Ad sayisi: ', noun_count)\n\nnoun_frequency = distribution.freq('nn')\nprint('Ad sikligi: ', noun_frequency)","repo_name":"thealper2/NaturalLanguageProcessing-Basics","sub_path":"NLTK_Siklik.py","file_name":"NLTK_Siklik.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"36019154182","text":"from shopcart import views\r\nfrom django.urls import path\r\nfrom goods.urls import router\r\n\r\n\r\nurlpatterns = [\r\n path('shoppingCart/clear', views.shop_cart_clear_view.as_view()),\r\n path('alipay/return/', views.alipay_return_view.as_view()),\r\n]\r\n\r\n# 商品购物车的路由\r\nrouter.register('shopcarts', views.shop_cart_view, basename='shopcarts')\r\nrouter.register('orders', views.order_view, basename='orders')\r\nurlpatterns += router.urls\r\n","repo_name":"wgc17331109301/study","sub_path":"BookStore/apps/shopcart/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"29873074554","text":"\"\"\"This module contains code retrieving prayer times from the API and transferring them onto a google calendar\"\"\"\nfrom quickstart import *\nfrom tqdm import tqdm\nimport requests\nimport json\nimport os\nimport sys\nfrom datetime import datetime, timedelta\n\n\ndef find_file_path() -> str:\n \"\"\"Finds the path to the folder when run and returns it\"\"\"\n if getattr(sys, 'frozen', False):\n application_path = os.path.dirname(sys.executable)\n elif __file__:\n application_path = os.path.dirname(__file__)\n return application_path\n\n\ndef get_monthly_prayer_time_data_from_api(year_input: str, month_input: str) -> str:\n \"\"\"Sends request to API to get a response with all prayer times as json\"\"\"\n response = requests.get(f'https://www.londonprayertimes.com/api/times/?format=json&key=3d07d979-1145-4d4e-81d0-8fac6e634a2d&year={year_input}&month={month_input}&24hours=true')\n data = json.loads(response.text)\n return data[\"times\"]\n \n\ndef create_calendar_event(date: str, time: str, prayer: str, credential) -> None:\n \"\"\"Creates the calendar events using google api\"\"\"\n time = str(datetime.strptime(time, \"%H:%M\")-timedelta(minutes=1))[11:16]\n event = {\n 'start': {\n 'dateTime': f'{date}T{time}:00',\n 'timeZone': 'Europe/London'\n },\n 'end': {\n 'dateTime': f'{date}T{time}:59',\n 'timeZone': 'Europe/London'\n },\n 'summary': prayer,\n 'description': prayer\n }\n\n service = build('calendar', 'v3', credentials=credential)\n\n event = service.events().insert(calendarId='1a4a4046ea518584fe2a3a0dc2dcffc889427489a999182a13214a1c2c5d830c@group.calendar.google.com', body=event).execute()\n\n\nif __name__ == '__main__':\n\n path = find_file_path()\n\n year = input('Please input the year that you want the times for (in digits [e.g.2023]): ')\n month = input('Please input the month that you want the times for (in lowercase [e.g. november]): ')\n\n prayer_times_json = get_monthly_prayer_time_data_from_api(year, month)\n\n creds = Credentials.from_authorized_user_file(f'{path}/token.json', SCOPES)\n\n prayers = ['fajr', 'dhuhr', 'asr_2', 'magrib', 'isha']\n for day in tqdm(prayer_times_json):\n for prayer in prayer_times_json[day]:\n if prayer in prayers:\n prayer_time = prayer_times_json[day][prayer]\n create_calendar_event(day, prayer_time, prayer, creds)\n\n print(\"Check your calendar at the month and year you inputted. You will find Hornchurch prayer times there.\")\n","repo_name":"IADesai/prayer-times-to-google-calendar","sub_path":"uploader.py","file_name":"uploader.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"36783993727","text":"import math\nimport random\nfrom codequest22.server.events import *\nfrom codequest22.server.requests import *\nfrom codequest22 import stats\nfrom heapq import heappop, heappush\n\nfrom codequest22.stats.ants import Fighter\n\n# TODO\n# Similar idea to defended for settlers - or something more fast evolving\n# That being said, in a 4 person game you can't dominate. So maybe do streaks? (Test this)\n# Move to current closest settle spot\n# Fighter ants go to patrol mode once at point.\n\nDEBUG = True\n\ndef get_team_name():\n return f\"Jackson\"\n\nmy_index = None\ndef read_index(player_index, num_players):\n global my_index, defeated\n my_index = player_index\n for x in range(num_players, 4):\n defeated[x] = True\n\nmap_data = {}\nspawns = {}\nproduction = []\nproduction_info = {}\ndefended = {}\noccupied = {}\nlast_occupied = {}\ndistance = {}\ninteresting_path_map = {}\ndefeated = [False]*4\ninteresting_points = []\nreset_points = []\nallocated = []\nmy_energy = stats.general.STARTING_ENERGY\ncur_tick = 0\n\ndef read_map(md, energy_info):\n global map_data, spawn, production, distance, defended, occupied, production_info, interesting_path_map, interesting_points, reset_points\n map_data = md\n for y in range(len(map_data)):\n for x in range(len(map_data[0])):\n if map_data[y][x] == \"F\":\n production.append((x, y))\n allocated.append(0)\n interesting_points.append((x, y))\n if map_data[y][x] in \"RBYG\":\n spawns[\"RBYG\".index(map_data[y][x])] = (x, y)\n occupied[\"RBYG\".index(map_data[y][x])] = []\n reset_points.append((x, y))\n if map_data[y][x] == \"Z\":\n # TODO: This can probably be made better\n interesting_points.append((x, y))\n for key in occupied:\n occupied[key] = {key2: False for key2 in production}\n last_occupied[key] = {key2: -10000 for key2 in production}\n interesting_path_map[key] = {}\n production_info = {\n key2: {\n \"base\": energy_info[key2],\n \"mult\": 1\n }\n for key2 in production\n }\n defended = {\n key: {\n key2: 0\n for key2 in production\n }\n for key in occupied \n }\n # Dijkstra's for every start point.\n # Generate edges\n adj = {}\n h, w = len(map_data), len(map_data[0])\n points = []\n for y in range(h):\n for x in range(w):\n distance[(x, y)] = {}\n adj[(x, y)] = []\n if map_data[y][x] == \"W\": continue\n points.append((x, y))\n for x, y in points:\n for a, b in [(y+1, x), (y-1, x), (y, x+1), (y, x-1)]:\n if 0 <= a < h and 0 <= b < w and map_data[a][b] != \"W\":\n adj[(x, y)].append((b, a, 1))\n for a, b in [(y+1, x+1), (y+1, x-1), (y-1, x+1), (y-1, x-1)]:\n if (\n 0 <= a < h and 0 <= b < w and \n map_data[a][b] != \"W\" and\n map_data[a][x] != \"W\" and\n map_data[y][b] != \"W\"\n ):\n adj[(x, y)].append((b, a, math.sqrt(2)))\n idx = {p: i for i, p in enumerate(points)}\n for x, y in points:\n # Dijkstra run\n expanded = [False] * len(points)\n queue = []\n heappush(queue, (0, (x, y)))\n while queue:\n d, (a, b) = heappop(queue)\n if expanded[idx[(a, b)]]: continue\n expanded[idx[(a, b)]] = True\n distance[(x, y)][(a, b)] = d\n # Look at all neighbours\n for j, k, d2 in adj[(a, b)]:\n if not expanded[idx[(j, k)]]:\n heappush(queue, (\n d + d2,\n (j, k)\n ))\n\nclass Ant:\n def __init__(self, type, ticks, hp, position, energy) -> None:\n self.ant_type = type\n self.ticks = ticks\n self.hp = hp\n self.position = position\n self.energy = energy\n self.previous_positions = []\n self.dead = False\n\nants = [{} for _ in range(4)]\nant_ids = 0\ntotal_ants = 0\ncurrent_workers = 0\ncurrent_settlers = 0\n\ndef calculate_defended():\n # Calculates whether certain production zones are defended, or at least safe for me to move to.\n for player_index in occupied:\n for prod in production:\n defended[player_index][prod] = 0\n for player_index in occupied:\n for key in ants[player_index]:\n if player_index == my_index:\n if ants[player_index][key].cur_allocation in production:\n if ants[player_index][key].ant_type == AntTypes.FIGHTER:\n defended[player_index][ants[player_index][key].cur_allocation] += 1\n else:\n # My own workers don't mean shit for defence, or taking away my enemies energy.\n defended[player_index][ants[player_index][key].cur_allocation] += 0\n continue\n # Are we close enough to the particular production site?\n pos = ants[player_index][key].position\n ipos = (round(pos[0]), round(pos[1]))\n for prod in production:\n d = abs(pos[0] - prod[0]) + abs(pos[1] - prod[1])\n if d < 3:\n if ants[player_index][key].ant_type == AntTypes.FIGHTER:\n defended[player_index][prod] += 1\n else:\n defended[player_index][prod] += 0.2\n break\n else:\n options = interesting_path_map[player_index].get(ipos, {})\n options = list(sorted([(v, k) for k, v in options.items()]))[-3::]\n for _, option in options:\n if option in production:\n if ants[player_index][key].ant_type == AntTypes.FIGHTER:\n defended[player_index][option] += 1 / len(options)\n else:\n defended[player_index][option] += 0.2 / len(options)\n\ndef calculate_production_benefit():\n global production_info\n for prod in production:\n loop_cost = stats.ants.Worker.COST / stats.ants.Worker.TRIPS\n loop_return = production_info[prod][\"base\"] * production_info[prod][\"mult\"]\n d = distance[prod][spawns[my_index]]\n enemy_d = 1000000\n for other in occupied:\n if other == my_index or defeated[other]: continue\n enemy_d = min(enemy_d, distance[prod][spawns[other]])\n loop_time = d / stats.ants.Worker.SPEED + d / (stats.ants.Worker.SPEED * stats.ants.Worker.ENCUMBERED_RATE)\n rpt = (loop_return - loop_cost) / loop_time\n total_allocation = loop_time * (stats.energy.PER_TICK / stats.energy.DELAY)\n production_info[prod][\"rpt\"] = rpt\n production_info[prod][\"allocation\"] = math.floor(total_allocation)\n score_diff = 0\n if d < enemy_d:\n score_diff = pow(enemy_d / d, 3)\n elif d > enemy_d:\n score_diff = -pow(d / enemy_d, 3)\n production_info[prod][\"score\"] = rpt + score_diff\n\ndef allocate_production_zone(ant):\n global allocated\n choices = []\n for i, p in enumerate(production):\n bad = False\n # TODO\n for index in defended:\n if index != my_index and defended[index][p]:\n bad = True\n if bad and not defended[my_index][p]:\n # Don't go somewhere being actively defended by others.\n continue\n rpt = production_info[p][\"rpt\"]\n allocation_max = production_info[p][\"allocation\"]\n score = production_info[p][\"score\"]\n choices.append((allocation_max <= allocated[i], -score, p, i))\n choices.sort()\n if len(choices) == 0:\n return spawns[my_index]\n allocated[choices[0][3]] += 1\n ant.cur_allocation = choices[0][2]\n return choices[0][2]\n\ndef handle_failed_requests(requests):\n global my_energy\n for req in requests:\n if req.player_index == my_index:\n print(f\"Request {req.__class__.__name__} failed. Reason: {req.reason}.\")\n if DEBUG:\n # Raise an error immediately. Something went wrong!\n raise ValueError()\n if isinstance(req, SpawnRequest):\n my_energy += req.cost\n\ncurrent_settled = []\nsettle_timer = 0\n\ndef spawn_excluding_settler_action(max_amount=stats.general.MAX_SPAWNS_PER_TICK):\n global current_workers, total_ants, ant_ids, my_energy\n spawn_requests = []\n # Only production is worthwhile. So just decide if I need to defend anything\n options = []\n for prod in production:\n options.append((production_info[prod][\"score\"], production_info[prod][\"allocation\"], prod))\n options.sort()\n options = options[::-1]\n remaining_workers = current_workers\n remaining_cost = my_energy\n remaining_spawns = max_amount\n # First option is best for return and has the highest allocation.\n for score, allocate, prod in options:\n if remaining_workers <= 0 and remaining_cost <= 0:\n break\n if remaining_spawns <= 0:\n break\n n_defending = defended[my_index][prod]\n for index in defended:\n if index == my_index: continue\n n_defending -= defended[index][prod]\n if n_defending < 0 and (remaining_cost > stats.ants.Worker.COST * 5 or remaining_workers >= 5):\n # We need to spawn a fighter to secure this production area - We'll have multiple ants coming soon.\n if remaining_cost >= stats.ants.Fighter.COST and total_ants < stats.general.MAX_ANTS_PER_PLAYER - 5 and remaining_workers + remaining_spawns >= 5:\n key = f\"Fighter-{ant_ids}\"\n ant = Ant(AntTypes.FIGHTER, stats.ants.Fighter.LIFESPAN, stats.ants.Fighter.HP, spawns[my_index], stats.ants.Fighter.COST)\n ant.cur_allocation = prod\n ants[my_index][key] = ant\n spawn_requests.append(SpawnRequest(AntTypes.FIGHTER, id=f\"Fighter-{ant_ids}\", goal=prod))\n ant_ids += 1\n total_ants += 1\n remaining_cost -= stats.ants.Fighter.COST\n remaining_spawns -= 1\n defended[my_index][prod] += 1\n # Now we should allocate as many workers as possible\n if remaining_workers < allocate:\n max_spawn = min(allocate - remaining_workers, remaining_spawns)\n max_spawn = min(max_spawn, remaining_cost // stats.ants.Worker.COST)\n max_spawn = max(0, max_spawn)\n max_spawn = min(max_spawn, stats.general.MAX_ANTS_PER_PLAYER - total_ants)\n for i in range(max_spawn):\n key = f\"Worker-{ant_ids}\"\n ant = Ant(AntTypes.WORKER, 100000, stats.ants.Worker.HP, spawns[my_index], stats.ants.Worker.COST)\n ant.cur_allocation = prod\n allocated[production.index(prod)] += 1\n ants[my_index][key] = ant\n spawn_requests.append(SpawnRequest(AntTypes.WORKER, id=key, goal=prod))\n ant_ids += 1\n total_ants += 1\n remaining_cost -= stats.ants.Worker.COST\n remaining_spawns -= 1\n remaining_workers += max_spawn\n current_workers += max_spawn\n remaining_workers -= allocate\n my_energy = remaining_cost\n return spawn_requests\n\ndef handle_events(events):\n global ants, ant_ids, my_energy, current_settled, settle_timer, total_ants, cur_tick, current_workers, current_settlers, defended, defeated\n cur_tick += 1\n settle_timer -= 1\n for l in ants:\n for k in l:\n l[k].ticks -= 1\n req = []\n glob_to_remove = []\n for ev in events:\n if isinstance(ev, DieEvent):\n if ev.player_index == my_index:\n total_ants -= 1\n ant = ants[my_index][ev.ant_id]\n ant.dead = True\n if ant.cur_allocation in production and ant.ant_type == AntTypes.WORKER:\n allocated[production.index(ant.cur_allocation)] -= 1\n ant.cur_allocation = None\n if ant.ant_type == AntTypes.WORKER:\n current_workers -= 1\n if ant.ant_type == AntTypes.FIGHTER:\n pass\n if ant.ant_type == AntTypes.SETTLER:\n current_settlers -= 1\n glob_to_remove.append((ev.player_index, ev.ant_id))\n for ev in events:\n if isinstance(ev, SpawnEvent):\n # Create the relavent object.\n if ev.player_index != my_index:\n # Otherwise, we do this on request.\n ants[ev.player_index][ev.ant_id] = Ant(ev.ant_type, getattr(ev, \"ticks_left\", 1000000), ev.hp, ev.position, ev.cost)\n elif isinstance(ev, MoveEvent):\n pindex, key, pos = ev.player_index, ev.ant_id, ev.position\n if ev.ant_id not in ants[ev.player_index]: continue\n ipos = (round(ants[pindex][key].position[0]), round(ants[pindex][key].position[1]))\n ants[pindex][key].previous_positions.append(ipos)\n ants[pindex][key].position = pos\n for x, y in reset_points:\n d = abs(x - pos[0]) + abs(y - pos[1])\n if d < 1:\n ants[pindex][key].previous_positions = []\n for x, y in interesting_points:\n d = abs(x - pos[0]) + abs(y - pos[1])\n if d < 1.5:\n # We passed by interesting point.\n for (a, b), (e, f) in zip(ants[pindex][key].previous_positions, ants[pindex][key].previous_positions[1:] + [(x, y)]):\n # Get all points between a,b and e,f.\n d = abs(a-e) + abs(b-f)\n max_d = 2 * math.ceil(d)\n for z in range(0, max_d):\n point0 = a + z / max_d * (e-a) / abs(e-a) if e != a else a\n point1 = b + z / max_d * (f-b) / abs(f-b) if f != b else b\n point = (round(point0), round(point1))\n if point not in interesting_path_map[pindex]:\n interesting_path_map[pindex][point] = {}\n interesting_path_map[pindex][point][(x, y)] = cur_tick\n if ants[pindex][key].ant_type == AntTypes.FIGHTER:\n # Check if last_occupied needs to be updated\n for prod in production:\n d = abs(prod[0] - pos[0]) + abs(prod[1] - pos[1])\n if d < 5:\n last_occupied[pindex][prod] = cur_tick\n elif isinstance(ev, ProductionEvent):\n if ev.player_index == my_index:\n if ev.ant_id not in ants[ev.player_index]: continue\n req.append(GoalRequest(ev.ant_id, spawns[my_index]))\n ant = ants[my_index][ev.ant_id]\n if ant.cur_allocation in production:\n allocated[production.index(ant.cur_allocation)] -= 1\n ant.cur_allocation = None\n elif isinstance(ev, DepositEvent):\n if ev.player_index == my_index:\n if ev.ant_id not in ants[ev.player_index]: continue\n if ants[ev.player_index][ev.ant_id].dead: continue\n req.append(GoalRequest(ev.ant_id, allocate_production_zone(ants[ev.player_index][ev.ant_id])))\n my_energy += ev.energy_amount\n elif isinstance(ev, ZoneActiveEvent):\n current_settled = ev.points\n settle_timer = ev.num_ticks\n for ant in ants[my_index].values():\n if ant.dead: continue\n if ant.ant_type == AntTypes.SETTLER:\n req.append(GoalRequest(ant.ant_id, current_settled[0]))\n elif isinstance(ev, ZoneDeactivateEvent):\n current_settled = []\n elif isinstance(ev, FoodTileActiveEvent):\n production_info[ev.pos][\"mult\"] = ev.multiplier\n elif isinstance(ev, FoodTileDeactivateEvent):\n production_info[ev.pos][\"mult\"] = 1\n elif isinstance(ev, TeamDefeatedEvent):\n defeated[ev.defeated_index] = True\n for pi, ai in glob_to_remove:\n del ants[pi][ai]\n for pindex in occupied:\n if pindex == my_index: continue\n for key in ants[pindex]:\n a, b = round(ants[pindex][key].position[0]), round(ants[pindex][key].position[1])\n # print(\"NEW TICK\")\n # for key in defended:\n # for pos in defended[key]:\n # if defended[key][pos] > 0:\n # print(f\"Defense {key} {pos} = {defended[key][pos]}\")\n # Start responding with spawns and fighter movement.\n calculate_defended()\n calculate_production_benefit()\n # Tug of war between 4 options:\n # * Worker spawns\n # * Settler spawns\n # * Fighter spawns\n # * Holding onto energy\n # For now, holding onto energy is useless provided you funnel enough into worker production.\n # Fighter spawns and worker/settler disputes boils down to deciding which parts of the map you want under control.\n # As a rule, at least 20 workers should be alive, otherwise let's just spam workers.\n if current_settled == [] or current_workers < 30:\n req.extend(spawn_excluding_settler_action())\n else:\n # 1. Evaluate distance to settle zone, and how many current fighters.\n my_d = distance[spawns[my_index]][tuple(current_settled[0])]\n # TODO: Evaluate if we'll have enough time to get score.\n other_info = []\n for idx in occupied:\n if idx == my_index or defeated[idx]: continue\n their_d = distance[spawns[idx]][tuple(current_settled[0])]\n fighters_on_zone = 0\n for key in ants[idx]:\n if ants[idx][key].ant_type != AntTypes.FIGHTER: continue\n ipos = (round(ants[idx][key].position[0]), round(ants[idx][key].position[1]))\n options = interesting_path_map[idx].get(ipos, {})\n options = list(sorted([(v, k) for k, v in options.items()]))[-3::]\n for _, option in options:\n if option in current_settled:\n fighters_on_zone += 1/len(options)\n other_info.append((their_d/my_d, fighters_on_zone))\n my_fighters = 0\n for key in ants[my_index]:\n if ants[my_index][key].ant_type == AntTypes.FIGHTER:\n if ants[my_index][key].cur_allocation in current_settled:\n my_fighters += 1\n # I know how far away each player is, and how many fighters they are sending.\n # Is it worth fighting for?\n other_info.sort(key=lambda i: (i[1], i[0]))\n other_info = other_info[::-1]\n # If there are less than 8 fighters at zone then automatically go for it.\n good = False\n if other_info[0][1] < 8:\n good = True\n # If we have more than a 1/3 of all current fighters moving towards then also go.\n elif sum(map(lambda x: x[1], other_info)) < 3 * my_fighters:\n good = True\n if good:\n # Allocate max 80% fighters/settlers to hit the ratio, then do the worker stuff for rest.\n maximum_spawns = round(stats.general.MAX_SPAWNS_PER_TICK*0.8)\n total_spawns = 0\n while total_spawns < maximum_spawns:\n if total_ants >= stats.general.MAX_ANTS_PER_PLAYER: break\n if my_energy < max(stats.ants.Settler.COST, stats.ants.Fighter.COST): break\n if my_fighters > 0 and current_settlers / my_fighters < 0.3:\n key = f\"Settler-{ant_ids}\"\n ant = Ant(AntTypes.SETTLER, stats.ants.Settler.LIFESPAN, stats.ants.Settler.HP, spawns[my_index], stats.ants.Settler.COST)\n ant.ant_id = key\n ant.cur_allocation = current_settled[0]\n ants[my_index][key] = ant\n req.append(SpawnRequest(AntTypes.SETTLER, id=key, goal=current_settled[0]))\n current_settlers += 1\n ant_ids += 1\n total_ants += 1\n total_spawns += 1\n my_energy -= stats.ants.Settler.COST\n else:\n key = f\"Fighter-{ant_ids}\"\n ant = Ant(AntTypes.FIGHTER, stats.ants.Fighter.LIFESPAN, stats.ants.Fighter.HP, spawns[my_index], stats.ants.Fighter.COST)\n ant.ant_id = key\n ant.cur_allocation = current_settled[0]\n ants[my_index][key] = ant\n req.append(SpawnRequest(AntTypes.FIGHTER, id=key, goal=current_settled[0]))\n my_fighters += 1\n ant_ids += 1\n total_ants += 1\n total_spawns += 1\n my_energy -= stats.ants.Fighter.COST\n # Only spawn more workers if we don't want to spawn more settlers/fighters.\n if current_workers < 40:\n req.extend(spawn_excluding_settler_action(max_amount=stats.general.MAX_SPAWNS_PER_TICK - total_spawns))\n else:\n req.extend(spawn_excluding_settler_action())\n\n return req\n","repo_name":"MonashAPS/cq22-game","sub_path":"test_bots/new_jackson_bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"14351134248","text":"try:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nconfig = {\n 'description': 'Learn Python The Hard Way ex48',\n 'author': 'Alexander Bozhkov',\n 'url': 'URL to get it at.',\n 'download_url': 'Where to download it.',\n 'author_email': 'test@mail.com',\n 'version': '0.1',\n 'install_requires': ['nose'],\n 'packages': ['ex48'],\n 'scripts': [],\n 'name': 'Learn Python The Hard Way ex48'\n}\n\nsetup(**config)\n","repo_name":"alexbozhkov/Learn-Python-The-Hard-Way-ex48","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"28390107052","text":"\n# Library import.\nfrom flask import Flask, request\nimport firebase_admin\nfrom firebase_admin import credentials, firestore\nfrom flask import jsonify\nimport pygeohash as pgh\nfrom geopy import distance\n\n\napp = Flask(__name__)\n\n# Your Firebase credentials here.\ncred = credentials.Certificate('./bright-pro-firebase-adminsdk-1ao7r-920e09b64c.json')\nfirebase_admin.initialize_app(cred)\ndb = firestore.client()\ndoc_ref = db.collection(u'venues')\n\n\n# Homepage.\n@app.route(\"/\")\ndef hello():\n return \"Please type your query in URL\"\n\n# Search endpoints.\n@app.route(\"/search\", methods=['GET'])\ndef index():\n args = request.args\n\n # /search?name -- Returns a single document.\n if 'name' in args:\n name = args.get('name')\n\n # Firebase query.\n ml = doc_ref.where(u'restaurant_name', u'==', name)\n docs = ml.stream()\n out_li = []\n for doc in docs:\n out_li.append(doc.to_dict())\n\n # /search?rating -- Returns list of documents.\n elif 'rating' in args:\n rating = args.get('rating')\n\n # Firebase query.\n ml = doc_ref.where(u'restaurant_rating', u'>=', float(rating))\n docs = ml.stream()\n dummy = []\n\n for doc in docs:\n dummy.append(doc.to_dict())\n\n # Sorting the list by rating in descending order.\n out_li = sorted(dummy, key=lambda y: y['restaurant_rating'], reverse=True)\n\n # /search?price_type -- Returns list of documents.\n elif 'price_type' in args:\n price = args.get('price_type')\n\n # Firebase query.\n ml = doc_ref.where(u'price_type', u'==', price)\n docs = ml.stream()\n dummy = []\n\n for doc in docs:\n dummy.append(doc.to_dict())\n\n # Sorting the list by name in ascending order.\n out_li = sorted(dummy, key=lambda y: y['restaurant_name'], reverse=False)\n\n # /search?latitude & longitude -- Returns nearest restaurants within 5km radius.\n elif ('latitude' in args) and ('longitude' in args):\n lat = args.get('latitude')\n lon = args.get('longitude')\n\n # Use precision=5 to locate restaurants within 5km radius.\n search_geo = pgh.encode(float(lat), float(lon), precision=5)\n\n # Firebase query.\n ml = doc_ref.where(u'geohash', u'==', search_geo)\n docs = ml.stream()\n\n dummy = []\n ind = {}\n out_li = []\n\n for doc in docs:\n dummy.append(doc.to_dict())\n\n # Dictionary having distance in key and id in value.\n for idx, dummy_item in enumerate(dummy):\n key = distance.distance((lat,lon), (dummy_item['lat'], dummy_item['lon']))\n value = idx\n ind[key] = value\n\n # sorting the dictionary on keys (Distance).\n ind_sorted = sorted(ind.items())\n\n for z in ind_sorted:\n out_li.append(dummy[z[1]])\n\n else:\n return \"Invalid Input\"\n\n\n return jsonify(results = out_li)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=True, port=8080)\n","repo_name":"arjunsanchala/yelp-scraper","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"4275432582","text":"from contextlib import ExitStack\nfrom pathlib import Path\nfrom typing import ContextManager\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport streamlit as st\n\nfrom stable_diffusion import StableDiffusion\n\noutput_path = Path(\"output\")\n\nplt_rc_params = {\n \"font.family\": \"monospace\",\n \"font.size\": 20,\n \"savefig.facecolor\": (14 / 255, 17 / 255, 22 / 255),\n}\nplt_style = \"dark_background\"\n\n\nclass FigureManager(ContextManager):\n def __init__(self, figure: plt.Figure):\n self._figure = figure\n\n def __enter__(self):\n return self._figure\n\n def __exit__(self, type, value, traceback): # noqa\n plt.close(self._figure)\n\n\n@st.experimental_singleton\ndef load_model():\n return StableDiffusion()\n\n\ndef get_streamlit_controls():\n form = st.sidebar.form(key=\"input\")\n submit_button = form.form_submit_button(label=\"Generate\")\n fill_black_flag = form.checkbox(\"Just fill black\")\n text_input = form.text_input(\n \"Prompt for stable diffusion\",\n value=\"Fox like creature steals candies in the fields cartoon style, detailed image background\",\n )\n return submit_button, fill_black_flag, text_input\n\n\ndef save_output(file_name, generated_image):\n try:\n last_index = max(int(file.name.split(\"__\")[0]) for file in output_path.glob(\"*\"))\n except ValueError:\n last_index = -1\n last_index = last_index + 1\n\n generated_image_path = output_path / f\"{last_index:04d}__{Path(file_name).stem}_gen.png\"\n plt.imsave(generated_image_path, generated_image)\n\n return generated_image_path\n\n\ndef run_streamlit():\n (\n submit_button,\n fill_black_flag,\n text_input,\n ) = get_streamlit_controls()\n\n if not submit_button:\n st.markdown(\"### Use left panel to start generation\")\n return\n\n st.markdown(\"### Stable diffusion image output\")\n\n if fill_black_flag:\n generated_image = np.zeros((200, 200, 3), dtype=np.uint8)\n else:\n model = load_model()\n with st.spinner(\"Inferring stable diffusion (~15 sec)\"):\n generated_image = model.generate(text_input)\n\n with st.spinner(\"Saving...\"):\n image_file_path = save_output(\"image\", generated_image)\n\n st.download_button(\n label=\"Download generated image\",\n data=image_file_path.read_bytes(),\n file_name=image_file_path.name,\n mime=\"application/octet-stream\",\n )\n with st.spinner(\"Visualizing...\"):\n fig = plt.figure(figsize=(15, 15))\n with ExitStack() as context:\n context.enter_context(FigureManager(fig))\n context.enter_context(plt.style.context(plt_style))\n context.enter_context(plt.rc_context(plt_rc_params))\n plt.imshow(generated_image)\n plt.xticks(list(range(0, generated_image.shape[1], 100)))\n plt.yticks(list(range(0, generated_image.shape[0], 100)))\n plt.tight_layout(pad=0.0)\n plt.grid()\n st.pyplot(fig)\n\n\nif __name__ == \"__main__\":\n st.set_page_config(layout=\"centered\")\n output_path.mkdir(exist_ok=True, parents=True)\n run_streamlit()\n","repo_name":"dmitrii-listvin/neuroginarium","sub_path":"image_generator/streamlit_app.py","file_name":"streamlit_app.py","file_ext":"py","file_size_in_byte":3117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"71024544051","text":"import spacy\nfrom spacy import displacy\n\n\ndef getDependecyPaths(sentence):\n doc = nlp(sentence)\n list1 = []\n\n for token in doc:\n list2 = []\n while(token.head != token):\n list2.append(token.text)\n list2.append('--' + token.dep_ + '->')\n token = token.head\n list2.append(token.text)\n list2.append('--' + token.dep_ + '->')\n list2.append('ROOT')\n list1.append(list2[::-1])\n\n return list1\n\n\ndef getSubtrees(sentence):\n doc = nlp(sentence)\n list1 = []\n\n for token in doc:\n list2 = []\n for descendant in token.subtree:\n if(descendant != token):\n list2.append(descendant.text)\n list1.append((token.text, list2))\n\n return list1\n\n\ndef formsASubtree(sentence, tokenList):\n doc = nlp(sentence)\n tokenSet = set(tokenList)\n\n subtrees = []\n\n for token in doc:\n list2 = []\n for descendant in token.subtree:\n list2.append(descendant.text)\n subtrees.append(list2)\n\n for subtree in subtrees:\n subtreeSet = set(subtree)\n if(tokenSet == subtreeSet):\n return True\n\n return False\n\n\ndef getSpanHead(span):\n doc = nlp(span)\n\n root = [token for token in doc if token.head == token][0]\n\n return root.text\n\n\ndef getSpans(sentence):\n doc = nlp(sentence)\n\n nsubj = []\n for token in doc:\n lista = []\n if(token.dep_ == 'nsubj'):\n for descendant in token.subtree:\n lista.append(descendant.text)\n nsubj.append(' '.join(lista))\n\n dobj = []\n for token in doc:\n lista = []\n if(token.dep_ == 'dobj'):\n for descendant in token.subtree:\n lista.append(descendant.text)\n dobj.append(' '.join(lista))\n\n iobj = []\n for token in doc:\n lista = []\n if(token.dep_ == 'iobj'):\n for descendant in token.subtree:\n lista.append(descendant.text)\n iobj.append(' '.join(lista))\n\n return {'nsubj': nsubj, 'dobj': dobj, 'iobj': iobj}\n\n\nsentence = 'I saw the man with a telescope.'\nspan = 'I saw the man'\n\nnlp = spacy.load(\"en_core_web_sm\")\n\nprint(\"Question 1:\")\ndependencyPaths = getDependecyPaths(sentence)\nfor dependencyPath in dependencyPaths:\n print(dependencyPath)\nprint(\"\")\n\nprint(\"Question 2:\")\nsubtrees = getSubtrees(sentence)\nfor subtree in subtrees:\n print(subtree)\nprint(\"\")\n\nprint(\"Question 3:\")\nprint(formsASubtree(sentence, ['man', 'telescope']))\nprint(formsASubtree(sentence, ['a', 'telescope', 'with']))\nprint(\"\")\n\nprint(\"Question 4:\")\nspanHead = getSpanHead(span)\nprint(spanHead)\nprint(\"\")\n\nprint(\"Question 5:\")\nspans = getSpans(sentence)\nprint(spans)\nprint(\"\")\n","repo_name":"lorenzinigiovanni/nlu-1","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"33145634409","text":"from __future__ import annotations\n\nimport logging\nfrom typing import Any, Callable, Dict, List, Optional\n\nfrom tenacity import (\n before_sleep_log,\n retry,\n retry_if_exception_type,\n stop_after_attempt,\n wait_exponential,\n)\n\nfrom langchain.callbacks.manager import CallbackManagerForLLMRun\nfrom langchain.llms import BaseLLM\nfrom langchain.pydantic_v1 import BaseModel, root_validator\nfrom langchain.schema import Generation, LLMResult\nfrom langchain.utils import get_from_dict_or_env\n\nlogger = logging.getLogger(__name__)\n\n\ndef _create_retry_decorator() -> Callable[[Any], Any]:\n \"\"\"Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions\"\"\"\n try:\n import google.api_core.exceptions\n except ImportError:\n raise ImportError(\n \"Could not import google-api-core python package. \"\n \"Please install it with `pip install google-api-core`.\"\n )\n\n multiplier = 2\n min_seconds = 1\n max_seconds = 60\n max_retries = 10\n\n return retry(\n reraise=True,\n stop=stop_after_attempt(max_retries),\n wait=wait_exponential(multiplier=multiplier, min=min_seconds, max=max_seconds),\n retry=(\n retry_if_exception_type(google.api_core.exceptions.ResourceExhausted)\n | retry_if_exception_type(google.api_core.exceptions.ServiceUnavailable)\n | retry_if_exception_type(google.api_core.exceptions.GoogleAPIError)\n ),\n before_sleep=before_sleep_log(logger, logging.WARNING),\n )\n\n\ndef generate_with_retry(llm: GooglePalm, **kwargs: Any) -> Any:\n \"\"\"Use tenacity to retry the completion call.\"\"\"\n retry_decorator = _create_retry_decorator()\n\n @retry_decorator\n def _generate_with_retry(**kwargs: Any) -> Any:\n return llm.client.generate_text(**kwargs)\n\n return _generate_with_retry(**kwargs)\n\n\ndef _strip_erroneous_leading_spaces(text: str) -> str:\n \"\"\"Strip erroneous leading spaces from text.\n\n The PaLM API will sometimes erroneously return a single leading space in all\n lines > 1. This function strips that space.\n \"\"\"\n has_leading_space = all(not line or line[0] == \" \" for line in text.split(\"\\n\")[1:])\n if has_leading_space:\n return text.replace(\"\\n \", \"\\n\")\n else:\n return text\n\n\nclass GooglePalm(BaseLLM, BaseModel):\n \"\"\"Google PaLM models.\"\"\"\n\n client: Any #: :meta private:\n google_api_key: Optional[str]\n model_name: str = \"models/text-bison-001\"\n \"\"\"Model name to use.\"\"\"\n temperature: float = 0.7\n \"\"\"Run inference with this temperature. Must by in the closed interval\n [0.0, 1.0].\"\"\"\n top_p: Optional[float] = None\n \"\"\"Decode using nucleus sampling: consider the smallest set of tokens whose\n probability sum is at least top_p. Must be in the closed interval [0.0, 1.0].\"\"\"\n top_k: Optional[int] = None\n \"\"\"Decode using top-k sampling: consider the set of top_k most probable tokens.\n Must be positive.\"\"\"\n max_output_tokens: Optional[int] = None\n \"\"\"Maximum number of tokens to include in a candidate. Must be greater than zero.\n If unset, will default to 64.\"\"\"\n n: int = 1\n \"\"\"Number of chat completions to generate for each prompt. Note that the API may\n not return the full n completions if duplicates are generated.\"\"\"\n\n @property\n def lc_secrets(self) -> Dict[str, str]:\n return {\"google_api_key\": \"GOOGLE_API_KEY\"}\n\n @classmethod\n def is_lc_serializable(self) -> bool:\n return True\n\n @root_validator()\n def validate_environment(cls, values: Dict) -> Dict:\n \"\"\"Validate api key, python package exists.\"\"\"\n google_api_key = get_from_dict_or_env(\n values, \"google_api_key\", \"GOOGLE_API_KEY\"\n )\n try:\n import google.generativeai as genai\n\n genai.configure(api_key=google_api_key)\n except ImportError:\n raise ImportError(\n \"Could not import google-generativeai python package. \"\n \"Please install it with `pip install google-generativeai`.\"\n )\n\n values[\"client\"] = genai\n\n if values[\"temperature\"] is not None and not 0 <= values[\"temperature\"] <= 1:\n raise ValueError(\"temperature must be in the range [0.0, 1.0]\")\n\n if values[\"top_p\"] is not None and not 0 <= values[\"top_p\"] <= 1:\n raise ValueError(\"top_p must be in the range [0.0, 1.0]\")\n\n if values[\"top_k\"] is not None and values[\"top_k\"] <= 0:\n raise ValueError(\"top_k must be positive\")\n\n if values[\"max_output_tokens\"] is not None and values[\"max_output_tokens\"] <= 0:\n raise ValueError(\"max_output_tokens must be greater than zero\")\n\n return values\n\n def _generate(\n self,\n prompts: List[str],\n stop: Optional[List[str]] = None,\n run_manager: Optional[CallbackManagerForLLMRun] = None,\n **kwargs: Any,\n ) -> LLMResult:\n generations = []\n for prompt in prompts:\n completion = generate_with_retry(\n self,\n model=self.model_name,\n prompt=prompt,\n stop_sequences=stop,\n temperature=self.temperature,\n top_p=self.top_p,\n top_k=self.top_k,\n max_output_tokens=self.max_output_tokens,\n candidate_count=self.n,\n **kwargs,\n )\n\n prompt_generations = []\n for candidate in completion.candidates:\n raw_text = candidate[\"output\"]\n stripped_text = _strip_erroneous_leading_spaces(raw_text)\n prompt_generations.append(Generation(text=stripped_text))\n generations.append(prompt_generations)\n\n return LLMResult(generations=generations)\n\n @property\n def _llm_type(self) -> str:\n \"\"\"Return type of llm.\"\"\"\n return \"google_palm\"\n","repo_name":"hwchase17/langchain","sub_path":"libs/langchain/langchain/llms/google_palm.py","file_name":"google_palm.py","file_ext":"py","file_size_in_byte":5937,"program_lang":"python","lang":"en","doc_type":"code","stars":46200,"dataset":"github-code","pt":"20"} +{"seq_id":"25568466444","text":"from collections import deque\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\nclass Solution:\n def connect(self, root: 'Node') -> 'Node':\n if not root:\n return None\n \n q = deque([root])\n while q:\n level_size = len(q)\n prev_node = None\n for i in range(level_size):\n curr_node = q.popleft()\n if prev_node:\n prev_node.next = curr_node\n prev_node = curr_node\n if curr_node.left:\n q.append(curr_node.left)\n if curr_node.right:\n q.append(curr_node.right)\n \n prev_node.next = None\n \n return root","repo_name":"shri-ram-29/LeetCode-Solutions","sub_path":"Populating_Next_Right_Pointers_in_Each_Node_II.py","file_name":"Populating_Next_Right_Pointers_in_Each_Node_II.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"14853026468","text":"import numpy as np\nimport gym\nimport gym_slide\nenv = gym.make(\"slide-v0\")\nobservation = env.reset()\nfor _ in range(1000):\n env.render()\n # action = env.action_space.sample() # your agent here (this takes random actions)\n action = np.array([100,0])\n observation, reward, done, info = env.step(action)\n\n if done:\n observation = env.reset()\nenv.close()","repo_name":"mayank0926/physics-informed-learners","sub_path":"Burgers-PINN/customGym.py","file_name":"customGym.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"72139510129","text":"import numpy as np\nimport pandas as pd\nimport pickle\nimport matplotlib.pyplot as plt\nfrom Dense import Dense\nfrom Layer import Layer\nfrom Activations import ReLU, Tanh, Sine, Sigmoid\nimport argparse\n\nnp.random.seed(42)\nPIK = \"weights.dat\"\n\n\ndef softmax(x):\n \"\"\"Compute softmax values for each sets of scores in x.\"\"\"\n return np.exp(x) / np.sum(np.exp(x), axis=0)\n\n\ndef compute_sigmoid_loss(logits, reference_answers):\n\ty_hat = []\n\tpr = []\n\tloss = []\n\tfor i in range(0, len(logits)):\n\t\tpr.append( softmax(logits[i, :]))\n\t\tif reference_answers[i] == 1:\n\t\t\ty_hat.append(pr[-1][1])\n\t\telse:\n\t\t\ty_hat.append(pr[-1][0])\n\tfor i in range(0, len(logits)):\n\t\tlfa = logits[np.arange(len(logits)), reference_answers][i]\n\t\tloss.append(- lfa + np.log(np.sum(np.exp(logits[i]))))\n\treturn loss\n\n\ndef grad_compute_sigmoid_loss(logits, reference_answers):\n\tlogits_comp = np.zeros(logits.shape)\n\tlogits_comp[np.arange(len(logits)), reference_answers] = 1\n\tsoftmaxes = []\n\n\tfor i in range(len(logits)):\n\t\tsoftmaxes.append(softmax(logits[i, :]))\n\tret = - logits_comp + softmaxes\n\treturn ret / logits.shape[0]\n\n\n\n\ndef data_preparation(df, test_size=0.8):\n y = df[1]\n X = df.drop([1],axis='columns')\n for col in X.columns:\n X[col] = (X[col] - X[col].mean()) / X[col].std()\n\n msk = np.random.rand(len(X)) < test_size\n X_train = X[msk]\n X_val = X[~msk]\n y_train = y[msk]\n y_val = y[~msk]\n\n\n X_train = X_train.values #pd.DataFrame(X_train.values)\n y_train = y_train.values.reshape(y_train.shape[0],)# pd.DataFrame(y_train.values)\n X_val = X_val.values # pd.DataFrame(X_val.values)\n y_val = y_val.values.reshape(y_val.shape[0],) # pd.DataFrame(y_val.values)\n\n return X_train, y_train, X_val, y_val\n\n\ndef forward(network, X):\n\tactivations = []\n\tinpu = X\n\tfor layer in network:\n\t\tactivations.append(layer.forward(inpu))\n\t\tinpu = activations[-1]\n\n\treturn activations\n\n\ndef predict(network, X):\n\tlogits = forward(network, X)[-1]\n\treturn logits.argmax(axis=-1)\n\n\ndef train(network, X, y, X_val, y_val):\n\n\tlayer_activations = forward(network, X)\n\tlayer_inputs = [X] + layer_activations # layer_input[i] is an input for network[i]\n\tlogits = layer_activations[-1]\n\tloss = compute_sigmoid_loss(logits, y)\n\n\tnetw2 = network\n\tlayer_activations_val = forward(netw2, X_val)\n\tlogits_val = layer_activations_val[-1]\n\tloss_val = compute_sigmoid_loss(logits_val, y_val)\n\n\n\tloss_grad = grad_compute_sigmoid_loss(logits, y)\n\tfor layer_index in range(len(network))[::-1]:\n\t\tloss_grad = network[layer_index].backward(layer_inputs[layer_index], loss_grad)\n\n\treturn np.mean(loss), np.mean(loss_val)\n\n\ndef get_minibatches(inputs, targets, batchsize):\n indices = np.random.permutation(len(inputs))\n for start_idx in range(0, len(inputs) - batchsize + 1, batchsize):\n excerpt = indices[start_idx:start_idx + batchsize]\n yield inputs[excerpt], targets[excerpt]\n\n\ndef construct_model_default(input_shape, learning_rate=0.1):\n\tnetwork = []\n\tnetwork.append(Dense(input_shape, 100, learning_rate=learning_rate))\n\tnetwork.append(ReLU())\n\tnetwork.append(Dense(100, 200, learning_rate=learning_rate))\n\tnetwork.append(Sine())\n\tnetwork.append(Dense(200, 2, learning_rate=learning_rate))\n\treturn network\n\n\ndef custom_model(input_shape, learning_rate):\n\tnetwork = []\n\ttry:\n\t\tprint(\"Enter the number of layers: \")\n\t\tn_layers = int(input())\n\t\tprev_input = input_shape\n\t\tfor i in range(n_layers - 1):\n\t\t\tprint(\"Now, enter the number of neurons for Layer #\", i+1)\n\t\t\tneurons = int(input())\n\t\t\tnetwork.append(Dense(prev_input, neurons, learning_rate=learning_rate))\n\t\t\tprint(\"Its time to choose an activation function.\")\n\t\t\tprint(\"1 for ReLu, 2 for Tanh, 3 for Sine, 4 for Sigmoid: \")\n\t\t\tactiv = int(input())\n\t\t\tif activ == 1:\n\t\t\t\tnetwork.append(ReLU())\n\t\t\telif activ == 2:\n\t\t\t\tnetwork.append(Tanh())\n\t\t\telif activ == 3:\n\t\t\t\tnetwork.append(Sine())\n\t\t\telif activ == 4:\n\t\t\t\tnetwork.append(Sigmoid())\n\t\t\telse:\n\t\t\t\traise Exception\n\n\t\t\tprev_input = neurons\n\t\tnetwork.append(Dense(prev_input, 2, learning_rate=learning_rate))\n\t\treturn network\n\n\texcept:\n\t\tprint(\"You are doing it wrong! Initializing default model...\")\n\t\treturn construct_model_default(input_shape, learning_rate)\n\n\n\ndef process_args():\n\tap = argparse.ArgumentParser()\n\tap.add_argument(\"-e\", \"--epochs\", required = False, help = \"Number of epochs\")\n\tap.add_argument(\"-a\", \"--alpha\", required = False, help = \"Training speed\")\n\tap.add_argument(\"-c\", \"--custom\", action=\"store_true\", required=False, help=\"Create custom neural net\")\n\tap.add_argument(\"-stop\", \"--early_stop\", required=False, help=\"Early stopping\")\n\tap.add_argument(\"-f\", \"--file\", required = True, help = \"Path to dataset\")\n\tap.add_argument(\"-b\", \"--batch_size\", required = False, help = \"Batch size\")\n\targs = vars(ap.parse_args())\n\treturn args\n\n\ndef plot_loss(train_loss, val_loss):\n\tplt.plot(train_loss, label='train loss')\n\tplt.plot(val_loss, label='val loss')\n\tplt.legend(loc='best')\n\tplt.grid()\n\tplt.show()\n\n\ndef plot_acc(train_acc, val_acc):\n\tplt.plot(train_acc, label='train accuracy')\n\tplt.plot(val_acc, label='val accuracy')\n\tplt.legend(loc='best')\n\tplt.grid()\n\tplt.show()\n\n\ndef main(args):\n\tdf = pd.read_csv(args['file'], header=None)\n\tX_train, y_train, X_val, y_val = data_preparation(df, 0.7)\n\ty_train = (y_train == 'M').astype(int)\n\ty_val = (y_val == 'M').astype(int)\n\n\ttrain_log, val_log = [], []\n\ttrain_loss, val_loss = [], []\n\tnetworks = []\n\tearly_stopping_rounds = 20 if not args['early_stop'] else int(args['early_stop'])\n\tlearning_rate = 0.1 if not args['alpha'] else float(args['alpha'])\n\tn_epochs = 500 if not args['epochs'] else int(args['epochs'])\n\tbatch_size = 200 if not args['batch_size'] else int(args['batch_size'])\n\tnetwork = construct_model_default(X_train.shape[1], learning_rate) if not args['custom']\\\n\t\telse custom_model(X_train.shape[1], learning_rate)\n\n\n\tfor epoch in range(n_epochs):\n\t\tlos = []\n\t\tval_los = []\n\t\tfor x_batch, y_batch in get_minibatches(X_train, y_train, batchsize=batch_size):\n\t\t\tl, l1 = train(network, x_batch, y_batch, X_val, y_val)\n\t\t\tlos.append(l)\n\t\t\tval_los.append(l1)\n\t\ttrain_loss.append(np.mean(los))\n\t\tval_loss.append(np.mean(val_los))\n\n\t\ttrain_log.append(np.mean(predict(network, X_train) == y_train))\n\t\tval_log.append(np.mean(predict(network, X_val) == y_val))\n\t\tnetworks.append(network)\n\t\tif early_stopping_rounds <= epoch and early_stopping_rounds != 0:\n\t\t\tif val_loss[epoch] >= val_loss[epoch - early_stopping_rounds]:\n\t\t\t\tnetwork = networks[epoch - early_stopping_rounds]\n\t\t\t\tbreak\n\n\t\tprint(\"Epoch\", epoch, \" - \", \"Train acc:\", train_log[-1], \" - \", \"Val acc:\", val_log[-1])\n\t\tprint(\"Train loss:\", train_loss[-1], \" - \", \"Val loss:\", val_loss[-1])\n\n\tplot_acc(train_log, val_log)\n\tplot_loss(train_loss, val_loss)\n\tdata = network\n\twith open(PIK, \"wb\") as f:\n\t\tpickle.dump(data, f)\n\tprint(\"Weights are saved to \" + PIK)\n\n\nif __name__ == \"__main__\":\n\targs = process_args()\n\ttry:\n\t\tmain(args)\n\texcept Exception as e:\n\t\tprint(\"You did something wrong! Details:\")\n\t\tprint(e)\n","repo_name":"FedunAnton/numpy-nn","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"70259787889","text":"\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import random_correlation\n\n\ndef multivariate_df(n_samples, mean, var, corr, seed=False, name = 'c'):\n if seed:\n np.random.seed(seed)\n \n cov = corr_var_to_cov(corr, var)\n if (len(mean) == 1): \n data = np.random.normal(mean, cov[0]**2, n_samples)\n else:\n data = np.random.multivariate_normal(mean, cov, n_samples)\n\n cols = col_name_gen(len(mean), name)\n df = pd.DataFrame(data, columns=cols)\n info = {\n 'type': 'mvn',\n 'mean': mean,\n 'correlation' : corr,\n 'variance': var,\n 'dim' : len(mean)\n }\n return df, info\n\n\ndef log_normal_df(n_samples, mean, var, corr, seed=False):\n df, info = multivariate_df(n_samples, mean, var, corr, seed)\n\n df = df.applymap(lambda x: np.exp(x))\n info['type'] = 'log-normal'\n return df, info\n\n\ndef mixture_gauss(n_samples, proportions, means, varis, corrs, seed=False):\n # Note that means and var, corr are lists of means, variances and Correlation matrices\n \n info = {}\n if seed:\n np.random.seed(seed)\n \n k = len(means)\n cols = col_name_gen(len(means[0]), 'c')\n df = pd.DataFrame(columns=cols)\n n_samples_li = np.random.multinomial(n_samples, proportions)\n\n for i in range(k):\n temp_df, temp_info = multivariate_df(n_samples_li[i],\n means[i], varis[i], corrs[i], seed)\n df = pd.concat((df, temp_df))\n temp_info['Proportion of total'] = proportions[i]\n info['dist ' + str(i)] = temp_info\n \n \n info['dim'] = len(means[0])\n return df, info\n\n\ndef mixture_log_normal(n_samples, proportions, means, varis, corrs, seed=False):\n # Note that means and covs are lists of means and Covariance matrices\n info = {}\n if seed:\n np.random.seed(seed)\n\n k = len(means)\n cols = col_name_gen(len(means[0]), 'c')\n df = pd.DataFrame(columns=cols)\n n_samples_li = np.random.multinomial(n_samples, proportions)\n\n for i in range(k):\n temp_df, temp_info = log_normal_df(n_samples_li[i],\n means[i], varis[i], corrs[i], seed)\n df = pd.concat((df, temp_df))\n temp_info['Proportion of total'] = proportions[i]\n info['dist ' + str(i)] = temp_info\n \n info['dim'] = len(means[0])\n return df, info\n\n\ndef cat_mixture_gauss(cond_df, cond_info, means, varis, corrs, seed = False):\n # Note label in feature vectors need have names in the same order \n # as means/covs\n # \n info = {'Conditional info' : cond_info,\n 'mixture info': {} }\n if seed:\n np.random.seed(seed)\n dim_count = cond_info['dim']\n \n \n unique = []\n n_samples = []\n for i in range(len(cond_df.columns)): #For each categorical features\n \n temp_li = cond_df[cond_df.columns[i]].unique() #Find unique labels of features\n temp_li.sort()\n unique.append(temp_li)\n \n temp_li = []\n for j in range(len(unique[i])): #Find number of samples with i,j label\n temp_li.append(\n sum(cond_df[cond_df.columns[i]]==unique[i][j])\n )\n n_samples.append(temp_li)\n \n for i in range(len(unique)): #For every categorical feature\n df = pd.DataFrame()\n dim_count += len(means[i][0])\n \n for j in range(len(unique[i])): #for each unique label\n\n temp_df, temp_info = multivariate_df(n_samples[i][j], means[i][j],\n varis[i][j], corrs[i][j], name = (cond_df.columns[i]+ '_c'))\n df = pd.concat((df, temp_df))\n df = df.reset_index(drop = True)\n info['mixture info']['Cat_feature_{0} label_{1}'.format(str(i),str(j))] = temp_info\n \n cond_df = cond_df.sort_values(cond_df.columns[i]).reset_index(drop=True) \n cond_df = pd.concat((cond_df, df), axis = 1)\n \n info['dim'] = dim_count\n \n return cond_df, info\n \n \n\ndef multinomial(n_samples, probabilities, seed=False, name='f_'):\n # n_samples: int , probabilites = nested list of probabilities\n info = {}\n if seed:\n np.random.seed(seed)\n\n column_names = col_name_gen(len(probabilities), name)\n df = pd.DataFrame(columns=column_names)\n\n count = 0\n for prob in probabilities:\n temp_label_names = col_name_gen(len(prob), name+str(count)+'_l_')\n temp_data = np.random.choice(temp_label_names, size=n_samples, p=prob)\n\n df[column_names[count]] = temp_data\n info[column_names[count]] = prob\n count += 1\n info['dim'] = sum(map(lambda prob: len(prob), probabilities))\n return df, info\n\n\ndef multinomial_cond(n_samples, ind_probabilities, cond_probabilities, seed=False):\n # n_samples: int,\n # ind_probabilities : nested list of probabilities one per feature,\n # cond_probabilities : double nested list of probabilities with [0][0] representing p(cond_feature_1|ind_feature_1=label_1)\n \n # Example Use:\n # multinomial_cond(20, [[0.5, 0.5],[0.5, 0.5]], [\n # [\n # [\n # [0.8, 0.2],[0, 1]\n # ], [\n # [0, 1],[1, 0]\n # ]\n \n # ], [\n # [\n # [1, 0, 0], [0, 1]\n # ], [\n # [0, 0, 1], [1, 0]\n # ], [\n # [0.1, 0.4, 0.5], [1, 0]\n # ]\n \n # ]\n # ]\n \n \n info = {}\n if seed:\n np.random.seed()\n\n ind_df, ind_info = multinomial(\n n_samples, ind_probabilities, seed, 'indf_')\n cond_df = pd.DataFrame()\n \n dim_count = ind_info['dim']\n info['source distributions'] = ind_info\n\n for i in range(len(ind_probabilities)):\n cond_df = pd.DataFrame()\n\n unique_labels = ind_df[ind_df.columns[i]].unique()\n unique_labels.sort()\n ind_df = ind_df.sort_values(ind_df.columns[i])\n ind_df = ind_df.reset_index(drop=True)\n\n temp_li1 = []\n temp_li2 = []\n \n for j in range(len(unique_labels)):\n temp_n = len(ind_df[ind_df[ind_df.columns[i]] == unique_labels[j]])\n temp_df, temp_info = multinomial(\n temp_n, cond_probabilities[i][j], seed, 'cf_'+str(i))\n \n temp_li1.append(temp_df)\n temp_info['conditional on'] = unique_labels[j]\n temp_li2.append(temp_info)\n \n dim_count += temp_info['dim']\n \n temp = pd.concat(temp_li1)\n cond_df = pd.concat((cond_df, temp), axis=0)\n cond_df = cond_df.reset_index(drop=True)\n ind_df = pd.concat([ind_df, cond_df], axis=1)\n\n \n info['conditional on ' +str(i)] = temp_li2\n info['dim'] = dim_count\n\n return ind_df, info\n\n\ndef multinomial_cond_extension(n_samples, true_ind_prob, ind_prob, cond_prob, seed = False):\n ##Used to add truly independent multinomials to a conditional set\n info = {}\n if seed:\n np.random.seed()\n \n true_ind_df, true_ind_info = multinomial(n_samples, true_ind_prob, seed, 'tif_') \n cond_df, cond_info = multinomial_cond(n_samples, ind_prob, cond_prob, seed)\n \n df = pd.concat((true_ind_df, cond_df), axis=1)\n info['true independent'] = true_ind_info\n info['conditionals'] = cond_info\n info['dim'] = cond_info['dim'] + true_ind_info['dim']\n return df, info\n \n \n \n ### Helper functions\n \ndef corr_var_to_cov(corr, var):\n corr = np.array(corr)\n var = np.array(np.sqrt(var))\n \n res = corr*var\n var = var.reshape(len(var),1)\n \n res = res*var\n return res\n \n \ndef r_corr(size):\n r_arr = np.random.uniform(0,5, size = size)\n r_arr = size*r_arr/sum(r_arr)\n return random_correlation.rvs(r_arr) \n \ndef normalize(vec):\n return vec/sum(vec)\n\ndef rand_prop(size):\n return(normalize(np.random.uniform(0,1,size = size)))\n \n\ndef col_name_gen(num_cols, common_name):\n common_name_list = [common_name]*num_cols\n num_string_list = [num_string for num_string in map(\n lambda num: str(num), [num for num in range(num_cols)]\n )]\n res_list = [a + b for a, b in zip(common_name_list, num_string_list)]\n return res_list\n\n\n\n","repo_name":"TVSjoberg/gan-thesis","sub_path":"gan_thesis/data/datagen.py","file_name":"datagen.py","file_ext":"py","file_size_in_byte":8253,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"20944905282","text":"_base_ = [\n '../_base_/datasets/coco_detection.py',\n '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'\n]\n\nlang_model_name = 'bert-base-uncased'\n\nmodel = dict(\n type='GLIP',\n data_preprocessor=dict(\n type='DetDataPreprocessor',\n mean=[103.53, 116.28, 123.675],\n std=[57.375, 57.12, 58.395],\n bgr_to_rgb=False,\n pad_size_divisor=32),\n backbone=dict(\n type='SwinTransformer',\n embed_dims=96,\n depths=[2, 2, 6, 2],\n num_heads=[3, 6, 12, 24],\n window_size=7,\n mlp_ratio=4,\n qkv_bias=True,\n qk_scale=None,\n drop_rate=0.,\n attn_drop_rate=0.,\n drop_path_rate=0.2,\n patch_norm=True,\n out_indices=(1, 2, 3),\n with_cp=False,\n convert_weights=False),\n neck=dict(\n type='FPN',\n in_channels=[192, 384, 768],\n out_channels=256,\n start_level=0,\n relu_before_extra_convs=True,\n add_extra_convs='on_output',\n num_outs=5),\n bbox_head=dict(\n type='ATSSVLFusionHead',\n lang_model_name=lang_model_name,\n num_classes=80,\n in_channels=256,\n feat_channels=256,\n anchor_generator=dict(\n type='AnchorGenerator',\n ratios=[1.0],\n octave_base_scale=8,\n scales_per_octave=1,\n strides=[8, 16, 32, 64, 128],\n center_offset=0.5),\n bbox_coder=dict(\n type='DeltaXYWHBBoxCoderForGLIP',\n target_means=[.0, .0, .0, .0],\n target_stds=[0.1, 0.1, 0.2, 0.2]),\n ),\n language_model=dict(type='BertModel', name=lang_model_name),\n train_cfg=dict(\n assigner=dict(type='ATSSAssigner', topk=9),\n allowed_border=-1,\n pos_weight=-1,\n debug=False),\n test_cfg=dict(\n nms_pre=1000,\n min_bbox_size=0,\n score_thr=0.05,\n nms=dict(type='nms', iou_threshold=0.6),\n max_per_img=100))\n\ntest_pipeline = [\n dict(\n type='LoadImageFromFile',\n backend_args=_base_.backend_args,\n imdecode_backend='pillow'),\n dict(\n type='FixScaleResize',\n scale=(800, 1333),\n keep_ratio=True,\n backend='pillow'),\n dict(type='LoadAnnotations', with_bbox=True),\n dict(\n type='PackDetInputs',\n meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',\n 'scale_factor', 'text', 'custom_entities'))\n]\n\nval_dataloader = dict(\n dataset=dict(pipeline=test_pipeline, return_classes=True))\ntest_dataloader = val_dataloader\n","repo_name":"open-mmlab/mmdetection","sub_path":"configs/glip/glip_atss_swin-t_a_fpn_dyhead_pretrain_obj365.py","file_name":"glip_atss_swin-t_a_fpn_dyhead_pretrain_obj365.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","stars":26167,"dataset":"github-code","pt":"20"} +{"seq_id":"1712933208","text":"import cv2, imutils, socket\nimport numpy as np\nimport time\nimport base64\nimport threading\n\nBUFF_SIZE = 65536\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.setsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF,BUFF_SIZE)\n\nip =\"192.168.43.222\"\nport = 1234\n\n#binding ip and port number\ns.bind((ip,port))\n\n#receives packet from sender and show using cv2\ndef recv():\n while True:\n packet,_ = s.recvfrom(BUFF_SIZE)\n data = base64.b64decode(packet,' /')\n npdata = np.fromstring(data,dtype=np.uint8)\n frame = cv2.imdecode(npdata,1)\n cv2.imshow(\"sender\",frame)\n key = cv2.waitKey(1) & 0xFF\n if key == ord('q'):\n s.close()\n break\n\n \n#function to send image stream to sender program \ndef send():\n #opens webcam\n vid = cv2.VideoCapture(0)\n #set the width t osend image in a single shot of datagram\n WIDTH=400\n #receives datagram on its socket address\n while(vid.isOpened()):\n #starts capturing images\n _,frame = vid.read()\n #resize the image\n frame = imutils.resize(frame,width=WIDTH)\n #encode the image with a jpeg with a quality of 80%\n encoded,buffer = cv2.imencode('.jpg',frame,[cv2.IMWRITE_JPEG_QUALITY,80])\n #base64 encoding \n message = base64.b64encode(buffer)\n s.sendto(message,(\"192.168.43.148\",1235))\n\n \n\n#multithreading\nx1 = threading.Thread( target=recv )\nx2 = threading.Thread( target=send )\n\nx1.start()\nx2.start()\n\n","repo_name":"gt9802/summer_task3","sub_path":"server1.py","file_name":"server1.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7360736155","text":"import sys\n\nfrom django.core.urlresolvers import reverse\nfrom django.core.exceptions import MiddlewareNotUsed\nfrom django.db import connection\nfrom django.conf import settings\nfrom django.http import HttpResponseRedirect, HttpResponse\n\nfrom core.util import set_current_user, clear_current_user, \\\n set_current_organization\nfrom core.util import set_current_campaign\nfrom core.models import ShortURL\nfrom profile.models import Profile\nfrom organization.models import Organization\nfrom campaign.models import Campaign, UserMustSelectCampaign\n\n\nclass UserMiddleware:\n 'Get the user from the request and records it on a threadlocal'\n \n def __init__(self):\n pass\n \n def process_request(self, request):\n 'Runs before views.py'\n \n if settings.MEDIA_URL in request.path:\n return\n \n if request.user.is_anonymous():\n clear_current_user()\n return\n \n try:\n user = Profile.objects.get_cached_by_auth_userid(request.user.id)\n set_current_user(user)\n # Monkey patch to save a database query\n request.user.get_profile = lambda: user\n except Profile.DoesNotExist:\n # Super-users, for example, don't need a profile\n return\n\n\nclass OrganizationMiddleware:\n \"\"\"\n - Redirect any shortened urls\n - Get the organisation off the url and record it on a threadlocal\n - Get the campaign off the url and record it on a threadlocal\n \"\"\"\n \n def __init__(self):\n pass\n \n def process_request(self, request):\n \"\"\"Runs before views.py\"\"\"\n\n if settings.MEDIA_URL in request.path or '/admin' in request.path:\n return\n\n absolute = 'http://%s/' % request.get_host()\n if absolute == settings.SHORT_URL_DOMAIN:\n try:\n short = ShortURL.objects.resolve(request.path)\n return HttpResponseRedirect(short)\n except ShortURL.DoesNotExist:\n pass\n\n domain = request.get_host()\n if ':' in domain:\n domain = domain.split(':')[0]\n\n try:\n org = Organization.objects.get_cached(domain)\n except Organization.DoesNotExist:\n\n try:\n org = Organization.objects.all()[0]\n except Organization.DoesNotExist:\n return HttpResponse('No organizations found. ' +\n 'Create one via /admin/',\n mimetype='text/plain')\n \n set_current_organization(org)\n\n try:\n campaign_name = request.path.split('/')[1]\n except IndexError:\n campaign_name = ''\n\n if campaign_name != 'select': # select is url to select a campaign\n try:\n campaign = Campaign.objects.default(campaign_name, org)\n set_current_campaign(campaign)\n except UserMustSelectCampaign:\n return HttpResponseRedirect(reverse('select_campaign'))\n\n\nclass RefererMiddleware:\n \"\"\"Records in a cookie which user referer this user.\n That cookie is checked when a user registers.\n Register can't just check the url, beause there could be some redirects\n between first arrival and actual registration.\"\"\"\n\n def __init__(self):\n pass\n\n def process_response(self, request, response):\n \"\"\"Runs after views.py\"\"\"\n if settings.MEDIA_URL in request.path:\n return response\n\n if 'f' in request.GET:\n response.set_cookie('f', request.GET['f'])\n return response\n\n\nclass SqlStatementCountMiddleware:\n 'Prints out a count of the number of SQL statements that were run'\n\n def __init__(self):\n if not settings.DEBUG:\n raise MiddlewareNotUsed()\n\n def process_response(self, request, response):\n 'Runs once the work is done, prints out sql statement count'\n\n if settings.MEDIA_URL in request.path:\n return response\n\n num_queries = len(connection.queries)\n if num_queries:\n # No using 'print', it appends a \\n\n sys.stdout.write('SQL %d\\t' % num_queries)\n sys.stdout.flush()\n\n return response\n","repo_name":"grahamking/goodenergy","sub_path":"core/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"5677974379","text":"'''\nCreated on Sep 5, 2017\n\n@author: theo\n'''\nfrom django.core.management.base import BaseCommand\nimport logging\n \nfrom acacia.meetnet.models import Well\nfrom acacia.data.util import get_address\nfrom acacia.meetnet.util import set_well_address\n\nlogger = logging.getLogger(__name__)\n\nclass Command(BaseCommand):\n help = 'Adres gegevens ophalen bij Google'\n \n def add_arguments(self, parser):\n parser.add_argument('-w','--well',\n action='store',\n type=int,\n dest='pk')\n\n def handle(self, *args, **options):\n pk = options.get('pk',None)\n if pk:\n query = Well.objects.filter(pk=pk)\n else:\n query = Well.objects.all()\n for well in query:\n logger.info('Checking well {}'.format(well))\n if well.straat:\n # already has address\n continue\n if set_well_address(well):\n well.save()\n\n","repo_name":"acaciawater/delft","sub_path":"delft/management/commands/address.py","file_name":"address.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72862212849","text":"# \r\nfrom __future__ import annotations\r\nfrom abc import ABC, abstractmethod\r\nfrom typing import Optional\r\n\r\n\r\nclass IHandler(ABC):\r\n @abstractmethod\r\n def next(self, handler: IHandler) -> IHandler:\r\n raise NotImplementedError\r\n @abstractmethod\r\n def handle(self, request: str) -> Optional[str]:\r\n raise NotImplementedError\r\n \r\nclass Handler(IHandler):\r\n _handler: IHandler = None\r\n \r\n def next(self, handler: IHandler) -> IHandler:\r\n self._handler = handler\r\n return handler\r\n \r\n @abstractmethod\r\n def handle(self, request: str) -> Optional[str]:\r\n if not self._handler:\r\n return\r\n return self._handler.handle(request)\r\n \r\nclass MonkeyHandler(Handler):\r\n def handle(self, request: str) -> Optional[str]:\r\n if request == 'banana':\r\n return f\"{self.__class__} handle {request}\"\r\n return super().handle(request)\r\n \r\nclass SquirrelHandler(Handler):\r\n def handle(self, request: str) -> Optional[str]:\r\n if request == 'nut':\r\n return f\"{self.__class__} handle {request}\"\r\n return super().handle(request)\r\n \r\nclass DogHandler(Handler):\r\n def handle(self, request: str) -> Optional[str]:\r\n if request == 'meatball':\r\n return f\"{self.__class__} handle {request}\"\r\n return super().handle(request)\r\n\r\ndef client_code(h: IHandler) -> None:\r\n for food in [\r\n 'coffee',\r\n 'meatball',\r\n 'banana'\r\n ]:\r\n print(f\"who wanna {food}\")\r\n res = h.handle(food)\r\n if not res:\r\n print(f' {food} was left untouched')\r\n else:\r\n print(f' {res}')\r\n\r\ndef main() -> None:\r\n m = MonkeyHandler()\r\n d = DogHandler()\r\n s = SquirrelHandler()\r\n m.next(d).next(s)\r\n client_code(m)\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"AuroraBoreas/python_reviews","sub_path":"20211003PracticalPythonDesignPatterns/20230227Review/03_behavioral/01_chain.py","file_name":"01_chain.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"22546332222","text":"# 4435번_중간계 전쟁\n\n## 간달프점수 : 호빗1, 인간2, 엘프3, 드워프3, 독수리4, 마법사10\n## 사우론점수 : 오크1, 인간2, 워그2, 고블린2, 우럭하이3, 트롤5, 법사10\n## 전투에 참여한 각 종족의 점수 합한 뒤, 어느 쪽이 이기나\n## 첫째 줄 전투 개수 T, 각 전투는 두 줄로 이루어짐\n## 첫째 줄에 간달프팀 종족 수, 순서 위와 동일\n## 둘째 줄 사우론팀 종족 수, 순서 위와 동일\n## 각 전투에 대해 \"Battle\"과 전투 번호 출력\n## 간달프 승 : \"Good triumphs over Evil\"\n## 사우론 승 : \"Evil eradicates all trace of Good\"\n## 무승부 : \"No victor on this battle field\" 출력\n\n\nimport sys\n\nt = int(input()) # 전투 개수 t\ngan = [1, 2, 3, 3, 4, 10] # 간달프팀의 각 종족별 점수\nsau = [1, 2, 2, 2, 3, 5, 10] # 사우론팀의 각 종족별 점수\n\nbattle = 0\nfor i in range(t) : # 전투 개수만큼 간달프팀과 사우론팀의 참여자 수가 주어짐\n gnum = list(map(int, sys.stdin.readline().split())) #간달프팀 종족별 참여자 수\n snum = list(map(int, sys.stdin.readline().split())) #사우론팀 종족별 참여자 수\n\n gscore = 0\n sscore = 0\n\n for j in range(len(gnum)) :\n gscore += gan[j] * gnum[j] #간달프 종족별 점수 * 종족별 참여자 수\n \n for k in range(len(snum)) :\n sscore += sau[k] * snum[k] #사우론 종족별 점수 * 종족별 참여자 수\n\n battle += 1 # 전투 번호\n\n if gscore > sscore : #간달프팀 승리 시\n print(f'Battle {battle}: Good triumphs over Evil')\n\n elif gscore < sscore : #사우론팀 승리시\n print(f'Battle {battle}: Evil eradicates all trace of Good')\n\n else : #무승부\n print(f'Battle {battle}: No victor on this battle field')\n\n\n ","repo_name":"MeaninGood/Studying_CT","sub_path":"baekjoon/Bronze/2_4435.py","file_name":"2_4435.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"36866482581","text":"\r\n\r\ndef arry1(N):\r\n for i in range(1,100):\r\n for j in range(i+1,100):\r\n if N-i-j > 0:\r\n yield [i,j,N-i-j]\r\n\r\n\r\n\r\ndef arry2(N,i):\r\n for m in range(1,100):\r\n if m in i:\r\n continue\r\n for n in range(m+1,100):\r\n if n in i or N-m-n in i or N-m-n < 0:\r\n continue\r\n yield [m,n,N-m-n]\r\n# for i in arry1(N=50):\r\n# print(i)\r\n# for j in arry2(50,i):\r\n# print(j)\r\n# break\r\n\r\ndef arry3(N,i,j):\r\n q = N - i[0] - j[0]\r\n w = N - i[1] - j[1]\r\n e = N - i[2] - j[2]\r\n\r\n a3 = [q,w,e]\r\n for z in a3:\r\n if z <= 0 or z in i or z in j:\r\n return None\r\n\r\n as1 = [i[0],j[1],a3[2]]\r\n as2 = [i[2],j[1],a3[0]]\r\n\r\n\r\n if sum(a3) == N and sum(as1) == N and sum(as2) == N:\r\n return a3\r\n\r\n return None\r\n\r\ndef gene(N):\r\n res = []\r\n for i in arry1(N):\r\n # print(i)\r\n for j in arry2(N,i):\r\n # print(j)\r\n k = arry3(N,i,j)\r\n # print(k)\r\n if k:\r\n # print(k)\r\n res.append([i,j,k])\r\n\r\n else:\r\n continue\r\n\r\n return res\r\n\r\n\r\ndef main():\r\n n = int(input('>>>'))\r\n res = gene(n)\r\n if res:\r\n print(res)\r\n return res\r\n else:\r\n print('not found')\r\nwhile 1:\r\n main()\r\n","repo_name":"zx576/Crossin-practices","sub_path":"python_weekly_question/nine-gong-ge.py","file_name":"nine-gong-ge.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"20"} +{"seq_id":"74390617330","text":"import json\nfrom django.core.exceptions import SuspiciousOperation\nfrom django.http import JsonResponse, HttpResponseNotAllowed\nfrom django.http.response import Http404\nfrom django.shortcuts import get_object_or_404\n\nfrom survey.models import SurveyResult, OperatingSystem\nfrom survey.serializers import serialize_survey_result, serialize_os\n\n\ndef get_survey_results(request):\n if request.method == 'GET':\n params = request.GET.get('os')\n if params == None: # no query paramters\n survey_results = list(map(lambda result: serialize_survey_result(result), SurveyResult.objects.all()))\n else: # query parameter 'os' exists\n if params not in ('Windows', 'MacOS', 'Ubuntu (Linux)'):\n raise SuspiciousOperation # 400 Bad Request\n else:\n survey_results = list(map(lambda result: serialize_survey_result(result), SurveyResult.objects.filter(os__name=params)))\n return JsonResponse({\"surveys\": survey_results}, status=200)\n else:\n return HttpResponseNotAllowed(['GET', ])\n\n\ndef get_survey(request, survey_id):\n if request.method == 'GET':\n survey = get_object_or_404(SurveyResult, id=survey_id)\n return JsonResponse(serialize_survey_result(survey))\n else:\n return HttpResponseNotAllowed(['GET', ])\n\ndef get_os_results(request):\n if request.method == 'GET':\n os_results = list(map(lambda result: serialize_os(result), OperatingSystem.objects.all()))\n return JsonResponse({\"os\" : os_results}, status=200) \n else:\n return HttpResponseNotAllowed(['GET', ])\n\ndef get_os(request, operatingsystem_id):\n if request.method == 'GET':\n try:\n os = OperatingSystem.objects.get(id=operatingsystem_id)\n return JsonResponse(serialize_os(os))\n except OperatingSystem.DoesNotExist:\n raise Http404\n else:\n return HttpResponseNotAllowed(['GET', ])","repo_name":"footprinthere/waffle-rookies-19.5-backend-0","sub_path":"assignment0/survey/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"29828689463","text":"import pickle\n\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom os import listdir\nfrom os.path import isfile, join\n\nfrom src.utils.Read_Database import Read_Database\nfrom src.Global_Locks import Image_Clusters_Model_Lock\n\nclass Image_Based_Recommendation:\n def __init__(self) -> None:\n self.image_embeddings_datastore = \"database/images\"\n self.doc_embeddings_map = {}\n\n\n\n async def find_similar_images(self, test_image_id, top_n=5):\n onlyfiles = [f for f in listdir(self.image_embeddings_datastore) if isfile(join(self.image_embeddings_datastore, f))]\n main_file = \"\"\n staged_files = []\n\n for file_name in onlyfiles:\n if file_name[0:2] == \"st\":\n staged_files.append(file_name)\n else:\n main_file = file_name\n\n pickle_files = [main_file] + staged_files\n\n for file in pickle_files:\n with open(f\"{self.image_embeddings_datastore}/{file}\", \"rb\",) as pkl:\n doc_embeddings = pickle.load(pkl)\n self.doc_embeddings_map.update(doc_embeddings)\n\n test_embedding = self.doc_embeddings_map[test_image_id]\n # find similarity\n similarities_dict = {}\n for image_id, embedding in self.doc_embeddings_map.items():\n similarity = cosine_similarity([test_embedding], [embedding])[0][0]\n similarities_dict[image_id] = similarity\n\n # sorted and get the top n similar items\n sorted_similarities = sorted(similarities_dict.items(), key=lambda x: x[1], reverse=True)\n top_n_similarities = sorted_similarities[1:top_n+1]\n\n database_handler = Read_Database()\n product_id_to_photos_map = await database_handler.get_product_id_to_photos_map()\n image_id_to_product_id_map = {}\n\n for product_id, photos_ids in product_id_to_photos_map.items():\n for photo_id in photos_ids:\n image_id_to_product_id_map[photo_id] = product_id\n products = []\n for image_id, similarity in top_n_similarities:\n if image_id in image_id_to_product_id_map.keys():\n products.append(image_id_to_product_id_map[image_id])\n\n\n return products","repo_name":"Mahyar-Ali/recommendation-system","sub_path":"src/controllers/Image_Based_Recommendation.py","file_name":"Image_Based_Recommendation.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73922860209","text":"\"\"\"\r\nAuthor: Kajal Gupta\r\nDate: 11/23/2019\r\n\"\"\"\r\nimport random\r\nfrom math import inf\r\n\r\nfrom sklearn import model_selection\r\nfrom sklearn.svm import LinearSVC\r\nimport sys\r\n\r\ndata = open(sys.argv[1])\r\nlabels = open(sys.argv[2])\r\ntestData = open(sys.argv[3])\r\n\r\ndataMatrix = []\r\nfor line in data.readlines():\r\n line = [float(i) for i in line.split()]\r\n dataMatrix.append(line)\r\n\r\nlabelsInfo = {}\r\nfor line in labels.readlines():\r\n val, key = line.split()\r\n labelsInfo.update({int(key): int(val)})\r\n\r\ntestDataMatrix = []\r\nfor line in testData.readlines():\r\n line = [int(i) for i in line.split()]\r\n testDataMatrix.append(line)\r\n\r\nprint(\"Data Loaded: train, labels, test \", len(labelsInfo), len(testDataMatrix), len(dataMatrix))\r\n\r\n\r\ndef getbest(train, labels):\r\n c = [.001, .01, .1, 1, 10, 100]\r\n error = {}\r\n for i in c:\r\n error[i] = 0\r\n\r\n for i in c:\r\n model = LinearSVC(max_iter=100000, C=i)\r\n scoreNew = model_selection.cross_val_score(model, train, list(labels.values()), cv=10)\r\n error[i] = 1 - max(scoreNew)\r\n\r\n minError = float(inf)\r\n bestC = 0\r\n for key in error.keys():\r\n if error[key] < minError:\r\n minError = error[key]\r\n bestC = key\r\n\r\n return bestC, minError*100\r\n\r\n\r\ndef trainModel(trainData, labels):\r\n \"\"\"\r\n Accepts train dataset and its label files for initiating training.\r\n :return: trained weights\r\n \"\"\"\r\n c, _ = getbest(trainData, labels)\r\n print(c)\r\n svm = LinearSVC(max_iter=100000, C=c)\r\n model = svm.fit(trainData, list(labels.values()))\r\n return model\r\n\r\n\r\ndef testModel(model, testData):\r\n \"\"\"\r\n Performs testing using the trained model\r\n :param model: trained weights\r\n :param testData: test data to perform testing on\r\n :return: returns predictions of test dataset. Its a python dictionary\r\n \"\"\"\r\n predictions = model.predict(testData)\r\n return predictions\r\n\r\n\r\ndef calculateAccuracy(testPredictions, actualPredictions):\r\n \"\"\"\r\n Checks accuracy of the trained models\r\n :param testPredictions: output predictions\r\n :param actualPredictions: actual predictions\r\n :return: accuracy, precision, recall\r\n \"\"\"\r\n confusionMatrix = [[0, 0], [0, 0]]\r\n for i in range(len(testPredictions)):\r\n if actualPredictions[i] == 0 and testPredictions[i] == 0:\r\n confusionMatrix[0][0] += 1\r\n elif actualPredictions[i] == 1 and testPredictions[i] == 1:\r\n confusionMatrix[1][1] += 1\r\n elif actualPredictions[i] == 0 and testPredictions[i] == 1:\r\n confusionMatrix[0][1] += 1\r\n elif actualPredictions[i] == 1 and testPredictions[i] == 0:\r\n confusionMatrix[1][0] += 1\r\n\r\n print(confusionMatrix)\r\n accuracy = (confusionMatrix[0][0] + confusionMatrix[1][1])/(sum(confusionMatrix[0]) + sum(confusionMatrix[1]))\r\n error = 1 - accuracy\r\n return accuracy*100, error*100\r\n\r\n\r\ndef calculateCorrelation(colI, colJ):\r\n \"\"\"\r\n Calculates correlation for two columns.\r\n :param colI: first col\r\n :param colJ: second col\r\n :return: returns correlation cofficient\r\n \"\"\"\r\n uniqColI = set(colI)\r\n uniqColJ = set(colJ)\r\n contigencyMatrix = [[0 for i in range((len(uniqColJ)+1))] for j in range((len(uniqColI)+1))]\r\n\r\n for i, valI in enumerate(uniqColI):\r\n for j, valJ in enumerate(uniqColJ):\r\n for colVal in range(0, len(colI)):\r\n if colI[colVal] == valI and colJ[colVal] == valJ:\r\n contigencyMatrix[i][j] += 1\r\n contigencyMatrix[len(uniqColI)][j] += 1\r\n contigencyMatrix[i][len(uniqColJ)] = sum(contigencyMatrix[i])\r\n\r\n contigencyMatrix[len(uniqColI)][len(uniqColJ)] = sum(contigencyMatrix[len(uniqColI)])\r\n\r\n observedMatrxix = [[0 for i in range(len(uniqColJ))] for j in range(len(uniqColI))]\r\n\r\n for i, valI in enumerate(uniqColI):\r\n for j, valJ in enumerate(uniqColJ):\r\n observedMatrxix[i][j] = (contigencyMatrix[i][len(uniqColJ)]*contigencyMatrix[len(uniqColI)][j])/contigencyMatrix[len(uniqColI)][len(uniqColJ)]\r\n\r\n chiSq = 0\r\n for i in range(0, len(uniqColI)):\r\n for j in range(0, len(uniqColJ)):\r\n try:\r\n chiSq += (contigencyMatrix[i][j] - observedMatrxix[i][j])**2/observedMatrxix[i][j]\r\n except Exception as e:\r\n pass\r\n\r\n significanceFromTable = 18.465 # at significance of 0.001 and dof 4\r\n if chiSq > significanceFromTable:\r\n return 1, chiSq\r\n else:\r\n return -1, chiSq\r\n\r\n\r\ndef performFeatureSelection(dataMatrix, testDataMatrix, trainingLabels):\r\n print(\"Performing feature selection, it might take some time!\")\r\n columns = len(dataMatrix[0])\r\n chiValues = []\r\n for col in range(0, columns):\r\n colI = [dataMatrix[row][col] for row in range(0, len(dataMatrix))]\r\n correlation, chiSq = calculateCorrelation(colI, list(trainingLabels.values()))\r\n chiValues.append((col, correlation, chiSq))\r\n\r\n features = 25\r\n print(\"No. of features selected = \", features)\r\n chiValues = sorted(chiValues, reverse=True, key=lambda x: x[2])[:features]\r\n columnsToPick = [j[0] for j in chiValues]\r\n\r\n dataMatrixNew = [[] for i in range(0, len(dataMatrix))]\r\n for i, row in enumerate(dataMatrix):\r\n for j, col in enumerate(row):\r\n if j in columnsToPick:\r\n dataMatrixNew[i].append(col)\r\n\r\n testDataMatrixNew = [[] for i in range(0, len(testDataMatrix))]\r\n for i, row in enumerate(testDataMatrix):\r\n for j, col in enumerate(row):\r\n if j in columnsToPick:\r\n testDataMatrixNew[i].append(col)\r\n\r\n return dataMatrixNew, testDataMatrixNew\r\n\r\n\r\ndef startProject(dataMatrix, labelsInfo, testDataMatrix):\r\n \"\"\"\r\n Actual function that takes whole dataset,\r\n does feature selection and then trains the model on reduced features,\r\n performs testing on testData and returns final predictions\r\n :param dataMatrix: train dataset\r\n :param labelsInfo: data labels\r\n :param testDataMatrix: test dataset\r\n :return: predictions of test dataset\r\n \"\"\"\r\n trainData, testData = performFeatureSelection(dataMatrix, testDataMatrix, labelsInfo)\r\n model = trainModel(trainData, labelsInfo)\r\n predictions = testModel(model, testData)\r\n return predictions\r\n\r\n\r\ndef printPredictions(predictions, noLabels=True):\r\n \"\"\"\r\n Outputs predictions on console\r\n :param predictions: predictions dictionary\r\n :return: None\r\n \"\"\"\r\n if noLabels:\r\n for i, val in enumerate(predictions):\r\n print(val, i)\r\n else:\r\n for key in predictions:\r\n print(predictions[key], key)\r\n\r\n\r\ndef testTraining(dataMatrix, labelsInfo, k):\r\n \"\"\"\r\n This function is used to perform validations to be assured whether the algorithm is\r\n working correctly or not. This is test function used by me to validate my model and algorithm\r\n and should not be used by TAs. The actual function for project output is startProject\r\n :param dataMatrix: training data\r\n :param labelsInfo: training labels\r\n :param k: training:testing ratio\r\n :return: None\r\n \"\"\"\r\n # splitting the data in test and train and then starting feature selection\r\n dataIndexes = [i for i in range(0, len(dataMatrix)) if labelsInfo.get(i) != None]\r\n trainingDataIndexes = random.sample(dataIndexes, int(len(dataMatrix) * k / 100))\r\n\r\n trainingData, trainingLabels, trainI = [], {}, 0\r\n testData, testLabels, testI = [], {}, 0\r\n for i, row in enumerate(dataMatrix):\r\n if labelsInfo.get(i) != None:\r\n if i in trainingDataIndexes:\r\n trainingData.append(row)\r\n trainingLabels.update({trainI: labelsInfo.get(i)})\r\n trainI += 1\r\n else:\r\n testData.append(row)\r\n testLabels.update({testI: labelsInfo.get(i)})\r\n testI += 1\r\n\r\n print(len(trainingLabels), len(trainingData), trainI)\r\n print(len(testLabels), len(testData), testI)\r\n testPredictions = startProject(trainingData, trainingLabels, testData)\r\n accuracy, error = calculateAccuracy(testPredictions, list(testLabels.values()))\r\n print(\"accuracy= {}, error= {}\".format(accuracy, error))\r\n # printPredictions(testPredictions, False)\r\n return accuracy, error\r\n\r\n\r\nif __name__ == '__main__':\r\n \"\"\"\r\n Use testTraining to do in house training and validation while project development\r\n Use startProject to do predictions on actual test set by TAs\r\n \"\"\"\r\n\r\n #cross validation for my testing and training\r\n acc, err = [], []\r\n for i in range(0, 5):\r\n _acc, _err = testTraining(dataMatrix, labelsInfo, 70)\r\n acc.append(_acc)\r\n err.append(_err)\r\n\r\n print(\"avg accuracy = {}, avg error = {}\".format(sum(acc)/5, sum(err)/5))\r\n\r\n predictions = startProject(dataMatrix, labelsInfo, testDataMatrix)\r\n for i, val in enumerate(predictions):\r\n print(val, i)\r\n\r\n","repo_name":"shriyanka/ML-Project","sub_path":"ML-Project.py","file_name":"ML-Project.py","file_ext":"py","file_size_in_byte":9000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"28191762513","text":"# -*- coding: utf-8 -*-\nimport json\n\nimport torch\nfrom torch import nn\nfrom torch.utils.data import Dataset\nfrom torchcrf import CRF\nfrom transformers import BertModel, BertTokenizer\n\nMAX_LEN = 100\nlabel2id = {\"O\": 0, \"B-PER\": 1, \"I-PER\": 2, \"B-ORG\": 3, \"I-ORG\": 4, \"B-LOC\": 5, \"I-LOC\": 6}\ntokenizer = BertTokenizer.from_pretrained(\"pytorch_bert\")\n\n\nclass BertCRFModel(nn.Module):\n def __init__(self, bert_model_path, hidden_size, nun_labels, dropout_rate, is_biLSTM=False, LSTM_hidden_size=128,\n LSTM_input_size=128):\n super(BertCRFModel, self).__init__()\n self.num_labels = nun_labels\n self.bert = BertModel.from_pretrained(bert_model_path)\n for name, param in self.bert.named_parameters():\n param.requires_grad = True\n self.tokenizer = BertTokenizer.from_pretrained(bert_model_path)\n output_size = hidden_size\n self.dropout_layer = nn.Dropout(dropout_rate)\n self.crf = CRF(num_tags=nun_labels, batch_first=True)\n self.criterion = nn.CrossEntropyLoss()\n self.is_biLSTM = is_biLSTM\n if self.is_biLSTM:\n self.biLSTM = nn.LSTM(LSTM_hidden_size, LSTM_input_size, num_layers=1, bidirectional=True, batch_first=True)\n output_size = LSTM_input_size * 2\n self.linear = nn.Linear(output_size, nun_labels)\n\n def forward(self, input_ids, labels, token_type_ids=None, input_mask=None):\n emissions = self.get_outputs(input_ids, token_type_ids, input_mask)\n loss = -1 * self.crf(emissions, labels, mask=input_mask)\n return loss\n\n def get_outputs(self, input_ids, token_type_ids=None, input_mask=None):\n outputs = self.bert(input_ids, token_type_ids=token_type_ids, attention_mask=input_mask, return_dict=True)\n outputs = outputs[\"last_hidden_state\"]\n if self.is_biLSTM:\n outputs, _ = self.biLSTM(outputs)\n outputs = self.dropout_layer(outputs)\n emissions = self.linear(outputs)\n return emissions\n\n def predict(self, input_ids, token_type_ids=None, input_mask=None):\n emissions = self.get_outputs(input_ids, token_type_ids, input_mask)\n return self.crf.decode(emissions, input_mask)\n\n\nclass MSRAData(Dataset):\n def __init__(self, path):\n self.data = self.load_data(path)\n\n def load_data(self, path):\n with open(path, \"r\", encoding=\"utf-8\") as f:\n d = json.loads(f.read())\n d = [self.trans_data(_) for _ in d]\n return d\n\n def trans_data(self, data):\n \"\"\"\n 将data数据格式转换成比较方便处理的格式,减少训练时准备batch的时间\n :param data:\n :return:\n \"\"\"\n text = data[\"text\"]\n # labels = torch.zeros(len(text), len(text), dtype=torch.int64)\n labels = [0] * len(text)\n for ent in data[\"entities\"]:\n labels[ent[\"start\"]] = label2id[\"B-\" + ent[\"type\"]]\n for i in range(ent[\"start\"] + 1, ent[\"end\"]):\n labels[i] = label2id[\"I-\" + ent[\"type\"]]\n if len(labels) >= MAX_LEN:\n labels = labels[:MAX_LEN]\n else:\n labels += [0] * (MAX_LEN - len(labels))\n labels = [0] + labels + [0]\n return text, labels\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, index):\n return self.data[index]\n\n\ndef collate_fn(batch):\n texts = [_[0] for _ in batch]\n labels = [_[1] for _ in batch]\n labels = torch.LongTensor(labels)\n tokens = tokenizer.batch_encode_plus(texts, return_tensors=\"pt\", truncation=True, max_length=MAX_LEN + 2,\n padding='max_length')\n return (tokens[\"input_ids\"], tokens[\"token_type_ids\"], tokens[\"attention_mask\"], labels)\n","repo_name":"pzydzh/sangNER","sub_path":"models/BertCRF.py","file_name":"BertCRF.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"37762715258","text":"import json\nfrom decorest import GET, POST, DELETE\nfrom decorest import HttpStatus, RestClient\nfrom decorest import accept, body, content, endpoint, form\nfrom decorest import header, multipart, on, query, stream, timeout\n\n\nclass Index(RestClient):\n\n @DELETE(\"/index\")\n @body(\"payload\", lambda p: json.dumps(p))\n @on(200, lambda r: r.json())\n def drop_index(self, payload):\n \"\"\"Drop an index\"\"\"\n\n @GET(\"/index\")\n @body(\"payload\", lambda p: json.dumps(p))\n @on(200, lambda r: r.json())\n def describe_index(self, payload):\n \"\"\"Describe an index\"\"\"\n\n @POST(\"index\")\n @body(\"payload\", lambda p: json.dumps(p))\n @on(200, lambda r: r.json())\n def create_index(self, payload):\n \"\"\"create index\"\"\"\n\n @GET(\"index/progress\")\n @body(\"payload\", lambda p: json.dumps(p))\n @on(200, lambda r: r.json())\n def get_index_build_progress(self, payload):\n \"\"\"get index build progress\"\"\"\n\n @GET(\"index/state\")\n @body(\"payload\", lambda p: json.dumps(p))\n @on(200, lambda r: r.json())\n def get_index_state(self, payload):\n \"\"\"get index state\"\"\"\n","repo_name":"merlinepedra/MILVUS-IA","sub_path":"tests/restful_client/api/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"12645819597","text":"import os\nimport json\nimport logging\nimport resource\n\nfrom django.conf import settings\nfrom rest_framework.exceptions import ValidationError\n\nfrom exceptions import WebMeVException, \\\n ExecutedOperationInputOutputException\n\nfrom api.utilities.basic_utils import read_local_file\nfrom api.utilities.resource_utilities import get_resource_by_pk, \\\n check_resource_request_validity, \\\n get_operation_resources_for_field\n\nfrom data_structures.operation import Operation\n\nlogger = logging.getLogger(__name__)\n\n\ndef read_operation_json(filepath):\n '''\n Performs ingestion of a JSON-format file defining an `Operation`\n\n Accepts a local filepath for the JSON file, returns a dict\n '''\n try:\n logger.info('Parse Operation definition file at {path}'.format(\n path=filepath\n ))\n fp = read_local_file(filepath)\n j = json.load(fp)\n fp.close()\n logger.info('Done reading file.')\n return j\n except Exception as ex:\n logger.error('Could not read the operation JSON-format file at {path}.'\n ' Exception was {ex}'.format(\n path=filepath,\n ex=ex\n )\n )\n\n\ndef resource_operations_file_is_valid(operation_resource_dict, necessary_keys):\n '''\n Some Operations have \"static\" resources that are user-independent. The \n repository can contain a file which provides paths to these OperationDataResources\n and here we check that the data structure is formatted correctly and that\n it has the proper keys\n '''\n # require strict equality-- don't want to have extra keys in the\n # operation_resource_dict. Don't allow sloppy specs.\n if not (operation_resource_dict.keys() == necessary_keys):\n return False\n\n for k in necessary_keys:\n l = operation_resource_dict[k]\n if not type(l) is list:\n return False\n namelist, pathlist = [], []\n for item in l:\n if not type(item) is dict:\n return False\n if not (item.keys() == set(['name', 'path', 'resource_type'])):\n return False\n namelist.append(item['name'])\n pathlist.append(item['path'])\n\n # ensure the names and paths are unique for the \"options\"\n # corresponding to this input\n if len(set(namelist)) < len(namelist):\n return False\n if len(set(pathlist)) < len(pathlist):\n return False\n return True\n\n\ndef validate_operation(operation_dict):\n '''\n Takes a dictionary and validates it against the definition\n of an `Operation`. Returns an instance of \n data_structures.operation.Operation\n '''\n logger.info('Validate the dictionary against the definition'\n f' of an Operation...: {operation_dict}')\n\n try:\n return Operation(operation_dict)\n except WebMeVException as ex:\n logger.info('Failed to validate the operation dict.'\n f' The exception was: {ex}\\n'\n f' The data was: {operation_dict}')\n raise ex\n except Exception as ex:\n logger.info('Unexpected exception when validating the operation dict.'\n f' The exception was: {ex}\\n'\n f' The data was: {operation_dict}')\n raise ex\n\n\ndef get_operation_data_list(uuid_list):\n '''\n Return a list of Operation instances (in serialized json format)\n given a list of UUIDs. Does not check the existence of those UUIDs\n for addressing Operation instances. That should be done prior.\n '''\n pass\n\ndef get_operation_instance(operation_db_model):\n '''\n Using an Operation (database model) instance, return an\n instance of data_structures.operation.Operation\n '''\n f = os.path.join(\n settings.OPERATION_LIBRARY_DIR,\n str(operation_db_model.id),\n settings.OPERATION_SPEC_FILENAME\n )\n if os.path.exists(f):\n j = read_operation_json(f)\n return validate_operation(j)\n else:\n logger.error('Integrity error: the queried Operation with'\n f' id={operation_db_model.id} did not have a'\n ' corresponding folder.')\n raise Exception('Missing operation files.')\n\n\ndef get_operation_instance_data(operation_db_model):\n '''\n Using an Operation (database model) instance, return the\n dict representation of data_structures.operation.Operation\n '''\n op = get_operation_instance(operation_db_model)\n return op.to_dict()\n\n\ndef validate_operation_inputs(\n user, user_inputs, operation_db_instance, workspace):\n '''\n This function validates the inputs to check that they are compatible\n with the Operation that a user wishes to run.\n\n `user` is the user (database object) requesting the executed Operation\n `user_inputs` is a dictionary of input parameters for the Operation\n as submitted by a user\n `operation_db_instance` is an instance of Operation (the database model)\n `workspace` is an instance of Workspace (database model)\n\n Note that `workspace` is not required, as some operations can be run\n outside the context of a workspace. In that instance, `workspace`\n should be explicitly set to None\n '''\n # get the Operation data structure given the operation database instance:\n operation = get_operation_instance(operation_db_instance)\n\n final_inputs = {}\n op_inputs = operation.inputs\n for key in op_inputs.keys():\n op_input = op_inputs[key]\n required = op_input.required\n spec = op_input.spec\n key_is_present = key in user_inputs.keys()\n\n if key_is_present:\n supplied_input = user_inputs[key]\n elif required: # key not there, but it is required\n logger.info('The key ({key}) was not among the inputs, but it'\n ' is required.'.format(key=key)\n )\n raise ValidationError({key: 'This is a required input field.'})\n else: # key not there, but NOT required\n logger.info('key was not there, but also NOT required.')\n if spec.default is not None: # is there a default to use?\n logger.info(\n 'There was a default value in the operation spec.' \n ' Since no value was given, use that.')\n supplied_input = spec.default\n else:\n supplied_input = None\n\n # validate the input. Note that for simple inputs\n # this is all we need. However, for inputs like \n # data resources, we need to perform additional checks (below)\n # We pass the `ignore_extra_keys` so that any requests containing\n # extra info are ignored. Otherwise, it's too strict. The strictness\n # is good for validating operation specs, but is less desirable\n # when another application (e.g. the frontend) interacts with it.\n op_input.check_value(supplied_input, ignore_extra_keys=True)\n\n if op_input.is_data_resource_input() and (supplied_input is not None):\n\n # this gets the instance, e.g. an instance of\n # data_structures.data_resource_attributes.DataResourceAttribute\n # (or one of the sibling classes)\n data_resource_attr = op_input.spec.value\n\n # whether we are dealing with an input that can accept\n # a single or multiple inputs, we collect in a list\n # so that we can handle in the same manner\n resource_list = []\n\n # if the input resource is user-associated:\n if op_input.is_user_data_resource_input():\n\n logger.info('Input corresponds to a data resource. Perform'\n ' additional checks.')\n # if we are dealing with a file-type, we need\n # to ensure that:\n # - the file is owned by the requesting user\n # - the file is in the workspace\n # - the file has the proper resource type\n\n # if we are dealing with a single resource\n # (spec dictates many=False), then put in a list.\n # This allows us to handle both situations in the\n # same way:\n if not data_resource_attr.many:\n uuid_list = [supplied_input]\n else:\n uuid_list = supplied_input\n\n for u in uuid_list:\n # if this doens't raise an exception, then the user does own\n # the file.\n resource_instance = check_resource_request_validity(\n user, u)\n\n if not workspace in resource_instance.workspaces.all():\n raise ExecutedOperationInputOutputException(\n f'The resource ({supplied_input}) was not'\n f' part of the workspace where the'\n ' analysis operation was requested.')\n\n resource_list.append(resource_instance)\n\n else:\n # if we are here, then we have a resource that is NOT\n # user-associated. Need to check that the supplied input\n # UUID corresponds to an OperationResource (database model)\n # AND that it's meant for this input field. Recall that\n # the OperationResource model has a field called `input_field`\n # such that files are associated with specific inputs.\n # Otherwise, tools with multiple fields using OperationResource\n # inputs could have a confusing mess of files.\n\n resources_for_field = get_operation_resources_for_field(\n operation_db_instance, op_input.name)\n matching_resource_found = False\n idx = 0\n while (not matching_resource_found) \\\n and (idx < len(resources_for_field)):\n r = resources_for_field[idx]\n if str(r.pk) == supplied_input:\n resource_list.append(r)\n matching_resource_found = True\n idx += 1\n if not matching_resource_found:\n raise ExecutedOperationInputOutputException('The'\n f' provided input ({supplied_input}) was not'\n ' associated with the input field for this'\n ' operation.')\n\n # this method will raise an exception if the resource_type\n # of the requested resource does not match the requirements\n # of the specification\n for resource_instance in resource_list:\n data_resource_attr.verify_resource_type(\n resource_instance.resource_type)\n\n final_inputs[key] = supplied_input\n\n return final_inputs\n","repo_name":"web-mev/mev-backend","sub_path":"mev/api/utilities/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":10976,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"28122059230","text":"import os\n\nfrom hashlib import blake2b\nfrom hmac import compare_digest\n\n# e.g. base64.encodebytes(os.urandom(34)).strip()\n# blake2b needs 64 bytes; 16 from the uuid and remaining 48 from the secret key\nSECRET_KEY = os.getenv(\"ECHODELETES_SIGNINGKEY\").encode('utf8')\nassert SECRET_KEY is not None\nAUTH_SIZE = 16\n\ndef sign(message_asbytes, uuid_asbytes):\n \"\"\"Sign a message using the uuid and secret key\"\"\"\n key = uuid_asbytes+SECRET_KEY\n assert len(key) == 64, len(key) \n h = blake2b(digest_size=AUTH_SIZE, key=uuid_asbytes+SECRET_KEY)\n h.update(message_asbytes)\n return h.hexdigest().encode('utf-8')\n\ndef verify(message_asbytes, uuid_asbytes, sig):\n \"\"\"Verify a signature (in bytes), from the original messge, uuid and secret key\"\"\"\n good_sig = sign(message_asbytes, uuid_asbytes)\n return compare_digest(good_sig, sig)\n","repo_name":"snafus/echodeletes","sub_path":"echodeletes/signing.py","file_name":"signing.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"37952688442","text":"import psycopg2\nimport os\nimport sys\nimport pandas as pd\n\n\ndef log(*args):\n arr = [x for x in args]\n for obj in arr:\n print('-' * 150, '\\n', obj)\n\n\ndef connect():\n \"\"\"Connect to database\"\"\"\n conn = None\n try:\n print('Connecting....')\n conn = psycopg2.connect(host=os.environ['DB_PATH'], database=os.environ['DB_NAME'],\n user=os.environ['DB_USERNAME'], password=os.environ['DB_PASSWORD'])\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n sys.exit(1)\n print('All good, Connection successful!')\n return conn\n\n\n# def sql_to_dataframe(conn, query, column_names):\n# \"\"\"Import data from a PostgreSQL database using a SELECT query\"\"\"\n# cursor = conn.cursor()\n# try:\n# cursor.execute(query)\n# except (Exception, psycopg2.DatabaseError) as error:\n# print('Error: %s' % error)\n# cursor.close()\n# return 1\n# # To execute returns a list of tuples:\n# tuples_list = cursor.fetchall()\n# cursor.close()\n# # Now we need to transform the list into a pandas DataFrame:\n# df = pd.DataFrame(tuples_list, columns=column_names)\n# return df\n\n\ndef sql_to_dataframe(conn, query):\n \"\"\"Import data from a PostgreSQL database using a SELECT query\"\"\"\n cursor = conn.cursor()\n try:\n cursor.execute(query)\n except (Exception, psycopg2.DatabaseError) as error:\n print('Error: %s' % error)\n cursor.close()\n return 1\n # To execute returns a list of tuples:\n tuples_list = cursor.fetchall()\n # Now we need to transform the list into a pandas DataFrame:\n df = pd.DataFrame(tuples_list, columns=[elt[0] for elt in cursor.description])\n cursor.close()\n return df\n","repo_name":"connorbai/Python","sub_path":"pandons/Common_Method.py","file_name":"Common_Method.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"69820137970","text":"import random\nimport string\nimport urllib.request\n\nimport time\nfrom urllib import parse\n\nimport requests\n\nfrom com import utils\n\n\ndef get_data(params, ip=None):\n count = 0\n url = parse.quote(utils.host + params, string.printable, 'gbk')\n while 1:\n if count > 6:\n page = ''\n break\n count = count + 1\n response = requests.get(url, timeout=100)\n print(response.status_code)\n if response.status_code == 200:\n page = response.text\n page = page.encode('utf-8')\n print(page)\n break\n else:\n print(params + '----connect failed status_code:' + response.status_code)\n time.sleep(random.randint(20, 40))\n # try:\n # if ip:\n # proxies = {'http': ip}\n # opener = urllib.request.FancyURLopener(proxies)\n # response = opener.open(url)\n # else:\n # response = requests.get(url, timeout=100)\n # print(response.status_code)\n # if response.status_code == 200:\n # page = response.text\n # page = page.encode('utf-8')\n # print(page)\n # break\n # else:\n # print(params + '----connect failed status_code:' + response.status_code)\n # time.sleep(random.randint(20, 40))\n # # response = urllib.request.urlopen(utils.host + params, timeout=100)\n # # if response.getcode() == 200:\n # # page = response.read()\n # # page = page.decode('gbk').encode('utf-8')\n # # break\n # except Exception as e:\n # print(params + '----connect failed:' + str(e))\n # time.sleep(random.randint(20, 40))\n return page\n\n\ndef post_data(name):\n while 1:\n data = {\n 'domain': '',\n 'blname': name.encode('gbk'),\n 'bladdr': '',\n 'prname': '',\n 'Submit2222': '提交查询'.encode('gbk')\n }\n data = parse.urlencode(data).encode('gbk')\n try:\n response = urllib.request.urlopen(utils.host + 'xmqk.asp', data, 100)\n if response.getcode() == 200:\n page = response.read()\n page = page.decode('gbk').encode('utf-8')\n break\n except Exception as e:\n print('post_data connect failed:' + str(e))\n time.sleep(random.randint(20, 60))\n return page\n\n\ndef test_data(file_path):\n file_object = open(file_path, 'r', encoding='utf-8')\n page = ''\n try:\n page = file_object.read()\n except Exception as e:\n print('Exception:' + str(e))\n finally:\n file_object.close()\n return page\n\n","repo_name":"huchyi/spiderInfo","sub_path":"com/net_work.py","file_name":"net_work.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"34810389324","text":"from selenium import webdriver\nimport time\n\ndriver = webdriver.Chrome()\nurl =\"https://www.github.com\"\ndriver.get(url) # sayfayı açar\n\ntime.sleep(1)\ndriver.maximize_window() # pencereyi tam ekran yapar\ndriver.save_screenshot(\"github.com - homepage.png\") # sayfanın ekran görüntüsü alır\n\nurl_1 = \"https://www.github.com/sadikturan\"\ndriver.get(url_1)\nprint(driver.title) # sayfanın başlıgını yazar\n\nif \"sadikturan\" in driver.title:\n driver.save_screenshot(\"github - sadikturan.png\")\n\ntime.sleep(1)\ndriver.back() # bir önceki sayfaya döner\n# driver.forward() bir sonraki sayfaya geçer\ntime.sleep(1)\ndriver.close() # tarayyıcıyı kapatır","repo_name":"barisyazilimnet/pythonBTK","sub_path":"bot yazılımı/ders80.py","file_name":"ders80.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"tr","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"8711648771","text":"# -*- coding: utf-8 -*- \n\nimport sys\nimport os\nimport xmlrpclib\nimport unicodedata\nimport struct\nfrom xml.dom import minidom\nimport urllib\nimport xbmc, xbmcvfs\n\ntry:\n # Python 2.6 +\n from hashlib import md5 as md5\n from hashlib import sha256\nexcept ImportError:\n # Python 2.5 and earlier\n from md5 import md5\n from sha256 import sha256\n \n__addon__ = sys.modules[ \"__main__\" ].__addon__\n__scriptname__ = sys.modules[ \"__main__\" ].__scriptname__\n__version__ = sys.modules[ \"__main__\" ].__version__\n\nUSER_AGENT = \"%s_v%s\" % (__scriptname__.replace(\" \",\"_\"),__version__ )\n\nLANGUAGES = (\n\n # Full Language name[0] podnapisi[1] ISO 639-1[2] ISO 639-1 Code[3] Script Setting Language[4] localized name id number[5]\n\n (\"Albanian\" , \"29\", \"sq\", \"alb\", \"0\", 30201 ),\n (\"Arabic\" , \"12\", \"ar\", \"ara\", \"1\", 30202 ),\n (\"Belarusian\" , \"0\" , \"hy\", \"arm\", \"2\", 30203 ),\n (\"Bosnian\" , \"10\", \"bs\", \"bos\", \"3\", 30204 ),\n (\"Bulgarian\" , \"33\", \"bg\", \"bul\", \"4\", 30205 ),\n (\"Catalan\" , \"53\", \"ca\", \"cat\", \"5\", 30206 ),\n (\"Chinese\" , \"17\", \"zh\", \"chi\", \"6\", 30207 ),\n (\"Croatian\" , \"38\", \"hr\", \"hrv\", \"7\", 30208 ),\n (\"Czech\" , \"7\", \"cs\", \"cze\", \"8\", 30209 ),\n (\"Danish\" , \"24\", \"da\", \"dan\", \"9\", 30210 ),\n (\"Dutch\" , \"23\", \"nl\", \"dut\", \"10\", 30211 ),\n (\"English\" , \"2\", \"en\", \"eng\", \"11\", 30212 ),\n (\"Estonian\" , \"20\", \"et\", \"est\", \"12\", 30213 ),\n (\"Persian\" , \"52\", \"fa\", \"per\", \"13\", 30247 ),\n (\"Finnish\" , \"31\", \"fi\", \"fin\", \"14\", 30214 ),\n (\"French\" , \"8\", \"fr\", \"fre\", \"15\", 30215 ),\n (\"German\" , \"5\", \"de\", \"ger\", \"16\", 30216 ),\n (\"Greek\" , \"16\", \"el\", \"ell\", \"17\", 30217 ),\n (\"Hebrew\" , \"22\", \"he\", \"heb\", \"18\", 30218 ),\n (\"Hindi\" , \"42\", \"hi\", \"hin\", \"19\", 30219 ),\n (\"Hungarian\" , \"15\", \"hu\", \"hun\", \"20\", 30220 ),\n (\"Icelandic\" , \"6\", \"is\", \"ice\", \"21\", 30221 ),\n (\"Indonesian\" , \"0\", \"id\", \"ind\", \"22\", 30222 ),\n (\"Italian\" , \"9\", \"it\", \"ita\", \"23\", 30224 ),\n (\"Japanese\" , \"11\", \"ja\", \"jpn\", \"24\", 30225 ),\n (\"Korean\" , \"4\", \"ko\", \"kor\", \"25\", 30226 ),\n (\"Latvian\" , \"21\", \"lv\", \"lav\", \"26\", 30227 ),\n (\"Lithuanian\" , \"0\", \"lt\", \"lit\", \"27\", 30228 ),\n (\"Macedonian\" , \"35\", \"mk\", \"mac\", \"28\", 30229 ),\n (\"Malay\" , \"0\", \"ms\", \"may\", \"29\", 30248 ), \n (\"Norwegian\" , \"3\", \"no\", \"nor\", \"30\", 30230 ),\n (\"Polish\" , \"26\", \"pl\", \"pol\", \"31\", 30232 ),\n (\"Portuguese\" , \"32\", \"pt\", \"por\", \"32\", 30233 ),\n (\"PortugueseBrazil\" , \"48\", \"pb\", \"pob\", \"33\", 30234 ),\n (\"Romanian\" , \"13\", \"ro\", \"rum\", \"34\", 30235 ),\n (\"Russian\" , \"27\", \"ru\", \"rus\", \"35\", 30236 ),\n (\"Serbian\" , \"36\", \"sr\", \"scc\", \"36\", 30237 ),\n (\"Slovak\" , \"37\", \"sk\", \"slo\", \"37\", 30238 ),\n (\"Slovenian\" , \"1\", \"sl\", \"slv\", \"38\", 30239 ),\n (\"Spanish\" , \"28\", \"es\", \"spa\", \"39\", 30240 ),\n (\"Swedish\" , \"25\", \"sv\", \"swe\", \"40\", 30242 ),\n (\"Thai\" , \"0\", \"th\", \"tha\", \"41\", 30243 ),\n (\"Turkish\" , \"30\", \"tr\", \"tur\", \"42\", 30244 ),\n (\"Ukrainian\" , \"46\", \"uk\", \"ukr\", \"43\", 30245 ),\n (\"Vietnamese\" , \"51\", \"vi\", \"vie\", \"44\", 30246 ),\n (\"BosnianLatin\" , \"10\", \"bs\", \"bos\", \"100\", 30204 ),\n (\"Farsi\" , \"52\", \"fa\", \"per\", \"13\", 30247 ),\n (\"English (US)\" , \"2\", \"en\", \"eng\", \"100\", 30212 ),\n (\"English (UK)\" , \"2\", \"en\", \"eng\", \"100\", 30212 ),\n (\"Portuguese (Brazilian)\" , \"48\", \"pt-br\", \"pob\", \"100\", 30234 ),\n (\"Portuguese (Brazil)\" , \"48\", \"pb\", \"pob\", \"33\", 30234 ),\n (\"Portuguese-BR\" , \"48\", \"pb\", \"pob\", \"33\", 30234 ),\n (\"Brazilian\" , \"48\", \"pb\", \"pob\", \"33\", 30234 ),\n (\"Español (Latinoamérica)\" , \"28\", \"es\", \"spa\", \"100\", 30240 ),\n (\"Español (España)\" , \"28\", \"es\", \"spa\", \"100\", 30240 ),\n (\"Spanish (Latin America)\" , \"28\", \"es\", \"spa\", \"100\", 30240 ),\n (\"Español\" , \"28\", \"es\", \"spa\", \"100\", 30240 ),\n (\"SerbianLatin\" , \"36\", \"sr\", \"scc\", \"100\", 30237 ),\n (\"Spanish (Spain)\" , \"28\", \"es\", \"spa\", \"100\", 30240 ),\n (\"Chinese (Traditional)\" , \"17\", \"zh\", \"chi\", \"100\", 30207 ),\n (\"Chinese (Simplified)\" , \"17\", \"zh\", \"chi\", \"100\", 30207 ) )\n\n\ndef languageTranslate(lang, lang_from, lang_to):\n for x in LANGUAGES:\n if lang == x[lang_from] :\n return x[lang_to]\n\ndef log(module, msg):\n xbmc.log((u\"### [%s] - %s\" % (module,msg,)).encode('utf-8'),level=xbmc.LOGDEBUG ) \n\ndef compare_columns(b,a):\n return cmp( b[\"language_name\"], a[\"language_name\"] ) or cmp( a[\"sync\"], b[\"sync\"] ) \n\ndef normalizeString(str):\n return unicodedata.normalize(\n 'NFKD', unicode(unicode(str, 'utf-8'))\n ).encode('ascii','ignore')\n\ndef hashFile(file_path, rar=False):\n if rar:\n return OpensubtitlesHashRar(file_path)\n \n log( __name__,\"Hash Standard file\") \n longlongformat = 'q' # long long\n bytesize = struct.calcsize(longlongformat)\n f = xbmcvfs.File(file_path)\n \n filesize = f.size()\n hash = filesize\n \n if filesize < 65536 * 2:\n return \"SizeError\"\n \n buffer = f.read(65536)\n f.seek(max(0,filesize-65536),0)\n buffer += f.read(65536)\n f.close()\n for x in range((65536/bytesize)*2):\n size = x*bytesize\n (l_value,)= struct.unpack(longlongformat, buffer[size:size+bytesize])\n hash += l_value\n hash = hash & 0xFFFFFFFFFFFFFFFF\n \n returnHash = \"%016x\" % hash\n return filesize,returnHash\n\nclass OSDBServer:\n def create(self):\n self.subtitles_hash_list = []\n self.subtitles_list = []\n self.subtitles_name_list = []\n \n def mergesubtitles( self, stack ):\n if( len ( self.subtitles_hash_list ) > 0 ):\n for item in self.subtitles_hash_list:\n if item[\"format\"].find( \"srt\" ) == 0 or item[\"format\"].find( \"sub\" ) == 0:\n self.subtitles_list.append( item )\n\n if( len ( self.subtitles_name_list ) > 0 ):\n for item in self.subtitles_name_list:\n if item[\"format\"].find( \"srt\" ) == 0 or item[\"format\"].find( \"sub\" ) == 0:\n self.subtitles_list.append( item ) \n\n if( len ( self.subtitles_list ) > 0 ):\n self.subtitles_list = sorted(self.subtitles_list, compare_columns)\n\n def searchsubtitles_pod( self, movie_hash, lang , stack):\n# movie_hash = \"e1b45885346cfa0b\" # Matrix Hash, Debug only\n podserver = xmlrpclib.Server('http://ssp.podnapisi.net:8000') \n pod_session = \"\"\n hash_pod =[str(movie_hash)]\n try:\n init = podserver.initiate(USER_AGENT)\n hash = md5()\n hash.update(__addon__.getSetting( \"PNpass\" ))\n password256 = sha256(str(hash.hexdigest()) + str(init['nonce'])).hexdigest()\n if str(init['status']) == \"200\":\n pod_session = init['session']\n podserver.authenticate(pod_session, __addon__.getSetting( \"PNuser\" ), password256)\n podserver.setFilters(pod_session, True, lang , False)\n search = podserver.search(pod_session , hash_pod)\n if str(search['status']) == \"200\" and len(search['results']) > 0 :\n search_item = search[\"results\"][movie_hash]\n for item in search_item[\"subtitles\"]:\n if item[\"lang\"]:\n flag_image = item[\"lang\"]\n else: \n flag_image = \"-\"\n link = str(item[\"id\"])\n if item['release'] == \"\":\n episode = search_item[\"tvEpisode\"]\n if str(episode) == \"0\":\n name = \"%s (%s)\" % (str(search_item[\"movieTitle\"]),str(search_item[\"movieYear\"]),)\n else:\n name = \"%s S(%s)E(%s)\" % (str(search_item[\"movieTitle\"]),str(search_item[\"tvSeason\"]), str(episode), )\n else:\n name = item['release']\n if item[\"inexact\"]:\n sync1 = False\n else:\n sync1 = True\n \n self.subtitles_hash_list.append({'filename' : name,\n 'link' : link,\n \"language_name\" : languageTranslate((item[\"lang\"]),2,0),\n \"language_flag\" : flag_image,\n \"language_id\" : item[\"lang\"],\n \"ID\" : item[\"id\"],\n \"sync\" : sync1,\n \"format\" : \"srt\",\n \"rating\" : str(int(item['rating'])*2),\n \"hearing_imp\" : \"n\" in item['flags']\n })\n self.mergesubtitles(stack)\n return self.subtitles_list,pod_session\n except :\n return self.subtitles_list,pod_session\n\n def searchsubtitlesbyname_pod( self, name, tvshow, season, episode, lang, year, stack ):\n if len(tvshow) > 1:\n name = tvshow\n search_url=[] \n search_url_base = \"http://www.podnapisi.net/ppodnapisi/search?tbsl=1&sK=%s&sJ=%s&sY=%s&sTS=%s&sTE=%s&sXML=1&lang=0\" % (name.replace(\" \",\"+\"), \"%s\", str(year), str(season), str(episode))\n \n subtitles = None\n \n for i in range(len(lang)):\n url = search_url_base % str(lang[i])\n log( __name__ ,\"%s - Language %i\" % (url,i))\n temp_subs = self.fetch(url)\n if temp_subs:\n if subtitles:\n subtitles = subtitles + temp_subs\n else:\n subtitles = temp_subs \n try:\n if subtitles:\n url_base = \"http://www.podnapisi.net/ppodnapisi/download/i/\"\n for subtitle in subtitles:\n subtitle_id = 0\n rating = 0\n filename = \"\"\n movie = \"\"\n lang_name = \"\"\n lang_id = \"\"\n flag_image = \"\"\n link = \"\"\n format = \"srt\"\n hearing_imp = False\n if subtitle.getElementsByTagName(\"title\")[0].firstChild:\n movie = subtitle.getElementsByTagName(\"title\")[0].firstChild.data\n if subtitle.getElementsByTagName(\"release\")[0].firstChild:\n filename = subtitle.getElementsByTagName(\"release\")[0].firstChild.data\n if len(filename) < 2 :\n filename = \"%s (%s).srt\" % (movie,year,)\n else:\n filename = \"%s (%s).srt\" % (movie,year,) \n if subtitle.getElementsByTagName(\"rating\")[0].firstChild:\n rating = int(subtitle.getElementsByTagName(\"rating\")[0].firstChild.data)*2\n if subtitle.getElementsByTagName(\"languageId\")[0].firstChild:\n lang_name = languageTranslate(subtitle.getElementsByTagName(\"languageId\")[0].firstChild.data, 1,2)\n if subtitle.getElementsByTagName(\"id\")[0].firstChild:\n subtitle_id = subtitle.getElementsByTagName(\"id\")[0].firstChild.data\n if subtitle.getElementsByTagName(\"flags\")[0].firstChild:\n hearing_imp = \"n\" in subtitle.getElementsByTagName(\"flags\")[0].firstChild.data\n flag_image = lang_name\n link = str(subtitle_id)\n self.subtitles_name_list.append({'filename':filename,\n 'link':link,\n 'language_name' : languageTranslate((lang_name),2,0),\n 'language_id' : lang_id,\n 'language_flag' : flag_image,\n 'movie' : movie,\n \"ID\" : subtitle_id,\n \"rating\" : str(rating),\n \"format\" : format,\n \"sync\" : False,\n \"hearing_imp\" : hearing_imp\n })\n self.mergesubtitles(stack)\n return self.subtitles_list\n except :\n return self.subtitles_list\n \n def download(self,pod_session, id):\n podserver = xmlrpclib.Server('http://ssp.podnapisi.net:8000') \n init = podserver.initiate(USER_AGENT)\n hash = md5()\n hash.update(__addon__.getSetting( \"PNpass\" ))\n id_pod =[]\n id_pod.append(str(id))\n password256 = sha256(str(hash.hexdigest()) + str(init['nonce'])).hexdigest()\n if str(init['status']) == \"200\":\n pod_session = init['session']\n auth = podserver.authenticate(pod_session, __addon__.getSetting( \"PNuser\" ), password256)\n if auth['status'] == 300: \n log( __name__ ,\"Authenticate [%s]\" % \"InvalidCredentials\")\n download = podserver.download(pod_session , id_pod)\n if str(download['status']) == \"200\" and len(download['names']) > 0 :\n download_item = download[\"names\"][0]\n if str(download[\"names\"][0]['id']) == str(id):\n return \"http://www.podnapisi.net/static/podnapisi/%s\" % download[\"names\"][0]['filename']\n \n return None \n \n def fetch(self,url):\n socket = urllib.urlopen( url )\n result = socket.read()\n socket.close()\n xmldoc = minidom.parseString(result)\n return xmldoc.getElementsByTagName(\"subtitle\") \n","repo_name":"be4i/service.subtitles.addic7ed","sub_path":"resources/lib/pn_utilities.py","file_name":"pn_utilities.py","file_ext":"py","file_size_in_byte":17275,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"20"} +{"seq_id":"24710534068","text":"import os, arcpy, datetime, ast, sys, importlib\nfrom multiprocessing import Process, set_executable, Pool\n\narcpy.env.overwriteOutput = True\nset_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))\n\n\nsys.path.append(os.path.split(os.path.realpath(__file__))[0])\nimport timer_class as tc\nimport Module_Generate_OD_Pro_single\nimportlib.reload(Module_Generate_OD_Pro_single)\nfrom Module_Generate_OD_Pro_single import *\n\n\nif __name__ == '__main__':\n\ttry:\n\t\t\n\t\tdefault_workspace = arcpy.env.workspace\n\n\t\t##### ZCTA or other geoid slice folder usually don't need to change\n\t\t#inputfolder = r\"C:\\Users\\rl53\\Desktop\\Chiro_Active\\ZCTS_slice\" #Testing Default\n\t\tinputfolder = arcpy.GetParameterAsText(0)\n\n\n\t\t##### Table ID Need to change!!!!\n\t\t#orgID = 'ZCTA5CE10' #Testing Default\n\t\t#desID = 'NPI' #Testing Default\n\t\torgID = arcpy.GetParameterAsText(1)\n\t\tdesID = arcpy.GetParameterAsText(3)\n\n\t\t##### Provider file Need to specify every time\n\t\t#provider_file = r\"R:\\Projects\\Davis_NIH\\NPPES_2010_2015\\Active_2014_geocoded.gdb\\OTHERPCP_14_active_match\" #Testing Default\n\t\tprovider_file = arcpy.GetParameterAsText(2)\n\t\t\t\t\n\t\t##### Outpt folder Need to change every time\n\t\t#ODfolder = r\"C:\\Users\\rl53\\Desktop\\Active_provider_2014\\OTHERPCP_OD_14\"\n\t\tODfolder = arcpy.GetParameterAsText(4)\n\n\t\tmax_time_limit = int(arcpy.GetParameterAsText(5))\n\t\tif max_time_limit == '#' or max_time_limit =='':\n\t\t\tmax_time_limit = 60\n\n\t\tNTsetting = os.path.split(os.path.realpath(__file__))[0]+'\\\\Default_NetworkData_Setting.txt'\n\t\tntf = open(NTsetting, 'r')\n\t\tdefault_nt = ast.literal_eval(remove_leading_space(ntf.readline().split('=')[1].replace('\\n', '')))\n\t\tdefault_cost = ast.literal_eval(remove_leading_space(ntf.readline().split('=')[1].replace('\\n', '')))\n\t\tdefault_accost = ast.literal_eval(remove_leading_space(ntf.readline().split('=')[1].replace('\\n', '')))\n\t\tdefault_restrict = ast.literal_eval(remove_leading_space(ntf.readline().split('=')[1].replace('\\n', '')))\n\t\tdefault_hierarchy = ast.literal_eval(remove_leading_space(ntf.readline().split('=')[1].replace('\\n', '')))\n\t\tntf.close()\n\n\n\t\t##### street map premium path usually don't need to change\n\t\t#smp = r\"C:\\Users\\rl53\\Desktop\\StreetMapPremium2017_Release1\\StreetMap_Data\\NorthAmerica.gdb\\Routing\\Routing_ND\" \n\t\tsmp = arcpy.GetParameterAsText(6)\n\t\tif smp == '#' or smp =='':\n\t\t\tsmp = default_nt\n\n\t\t#cost = \"TravelTime\"\n\t\tcost = arcpy.GetParameterAsText(7)\n\t\tif cost == '#' or cost =='':\n\t\t\tcost = default_cost\n\n\t\t#accost = [\"TravelTime\", \"Miles\"]\n\t\taccost = arcpy.GetParameterAsText(8).split(';')\n\t\tif accost ==['#'] or accost == '' or accost == ['']:\n\t\t\taccost = default_accost\n\n\t\t#restrict = [\"Driving an Automobile\"]\n\t\trestrict = arcpy.GetParameterAsText(9).split(';')\n\t\tif restrict == ['#'] or restrict == '' or restrict == ['']:\n\t\t\trestrict = default_restrict\n\n\t\t#hierarchy='TRUE'\n\t\thierarchy = arcpy.GetParameterAsText(10).upper()\n\t\tif hierarchy == '#' or hierarchy == '':\n\t\t\thierarchy = default_hierarchy\n\t\tif hierarchy=='TRUE':\n\t\t\thier = \"USE_HIERARCHY\"\n\t\telse:\n\t\t\thier = \"NO_HIERARCHY\"\n\t\t\t\n\t\ti = 0\t\n\t\twhile i < len(restrict):\n\t\t\trestrict[i] = restrict[i].replace('\\'', '').replace('\\\"','')\n\t\t\ti += 1\n\t\t\t\n\t\ti = 0\t\n\t\twhile i < len(accost):\n\t\t\taccost[i] = accost[i].replace('\\'', '').replace('\\\"','')\n\t\t\ti += 1\n\n\n\t\t##### Temp folder and log file\n\t\ttempfolder = ODfolder + \"\\\\temp\"\n\t\tlog_file = ODfolder + \"\\\\log.txt\"\n\n\t\tna_layer = \"OD Cost Matrix\"\n\n\t\tif not os.path.exists(tempfolder):\n\t\t\tos.mkdir(tempfolder)\n\n\t\tarcpy.env.workspace = inputfolder\n\t\tallshps = arcpy.ListFeatureClasses()\n\t\tusable_shp = []\n\t\tfor each_shp in allshps:\n\t\t\tusable_shp.append(inputfolder + '\\\\' + each_shp)\n\t\t\n\t\tif not os.path.exists(ODfolder + '\\\\error_shp.gdb'):\n\t\t\terror_gdb = arcpy.CreateFileGDB_management(ODfolder, '\\\\error_shp.gdb')\n\t\t\t\n\t\tif not os.path.exists(ODfolder + '\\\\OD_cost_out.gdb'):\n\t\t\tarcpy.CreateFileGDB_management(ODfolder, 'OD_cost_out.gdb')\n\t\t\t\n\t\tarcpy.SetProgressor(\"step\", \"Generating OD cost matrix...\")\n\n\t\ttotaln = int(len(usable_shp))\n\t\twatch=tc.timer()\n\t\t\n\t\t\n\t\tn = 0\n\t\twhile n < totaln:\n\t\t\tu_shp = usable_shp[n]\n\t\t\t# for i in range(0,6):\n\t\t\t\t# if n < len(shps_list_list[i]):\n\t\t\t\t\t# u_shp.append(shps_list_list[i][n])\n\t\t\tarcpy.AddMessage(\"Working on \"+str(u_shp)+\"...\")\n\t\t\tprogress = int(float(n)/totaln * 100)\n\t\t\tarcpy.SetProgressorPosition (progress)\n\n\t\t\t#arcpy.AddMessage(str(argv))\n\t\t\t\n\t\t\t#get_ODCost(provider_file, u_shp, n, na_layer, ODfolder, smp, tempfolder, log_file, orgID, desID, cost, accost, restrict, hier, max_time_limit)\n\t\t\tp = Process(target = get_ODCost, args = (provider_file, u_shp, n, na_layer, ODfolder, smp, tempfolder, log_file, orgID, desID, cost, accost, restrict, hier, max_time_limit))\n\t\t\tp.start()\n\t\t\tp.join()\n\t\t\t#with Pool(processes=6) as p:\n\t\t\t#\tresults = p.starmap(get_ODCost, argv)\n\t\t\t\n\t\t\twatch.lap()\n\t\t\ttogo = watch.format_time(watch.avg_sec*(totaln-n-1))\n\t\t\tarcpy.AddMessage('Each batch take about {0}secs. {1} hours {2} mins {3} secs to go...'.format(str(watch.avg_sec)[0:5], togo[0], togo[1], togo[2]))\n\t\t\t\n\t\t\tn += 1\n\t\t#p.join()\n\t\t\t\n\t\t\n\texcept Exception as e:\n\t\tarcpy.AddError(str(e))\n","repo_name":"everknight/LargeODcost","sub_path":"03Generate_OD_Pro_single.py","file_name":"03Generate_OD_Pro_single.py","file_ext":"py","file_size_in_byte":5077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73733067568","text":"# -*- coding: utf-8 -*-\nfrom torch import nn\n\n\ndef weights_init(m: nn.Module) -> None:\n if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d, nn.Linear)):\n nn.init.xavier_normal_(m.weight, gain=1e-3)\n if m.bias is not None:\n nn.init.normal_(m.bias, std=1e-3)\n elif isinstance(\n m, (nn.BatchNorm1d, nn.BatchNorm2d, nn.LayerNorm, nn.GroupNorm)\n ):\n if m.weight is not None:\n nn.init.ones_(m.weight)\n if m.bias is not None:\n nn.init.zeros_(m.bias)\n","repo_name":"Ipsedo/MusicDiffusion","sub_path":"music_diffusion/networks/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"73733068848","text":"# -*- coding: utf-8 -*-\nfrom typing import List, NamedTuple, Optional, Tuple\n\nfrom .networks import Denoiser, Noiser\n\n\nclass ModelOptions(NamedTuple):\n steps: int\n unet_channels: List[Tuple[int, int]]\n time_size: int\n cuda: bool\n\n def new_denoiser(self) -> Denoiser:\n return Denoiser(\n self.steps,\n self.time_size,\n self.unet_channels,\n )\n\n def new_noiser(self) -> Noiser:\n return Noiser(self.steps)\n\n\nclass TrainOptions(NamedTuple):\n run_name: str\n dataset_path: str\n batch_size: int\n step_batch_size: int\n epochs: int\n learning_rate: float\n metric_window: int\n save_every: int\n output_directory: str\n nb_samples: int\n noiser_state_dict: Optional[str]\n denoiser_state_dict: Optional[str]\n ema_state_dict: Optional[str]\n optim_state_dict: Optional[str]\n\n\nclass GenerateOptions(NamedTuple):\n fast_sample: Optional[int]\n denoiser_dict_state: str\n ema_denoiser: bool\n output_dir: str\n frames: int\n musics: int\n magn_scale: float\n","repo_name":"Ipsedo/MusicDiffusion","sub_path":"music_diffusion/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"4631672069","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\nimport numpy as np\nimport utils\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, in_planes, planes, stride=1):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,\n stride=stride, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, self.expansion *\n planes, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(self.expansion*planes)\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion*planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion*planes,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(self.expansion*planes)\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = F.relu(self.bn2(self.conv2(out)))\n out = self.bn3(self.conv3(out))\n out += self.shortcut(x)\n out = F.relu(out)\n return out\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, in_channels, channels, stride=1):\n super(BasicBlock, self).__init__()\n \n layers = nn.ModuleList()\n\n conv_layer = []\n conv_layer.append(nn.Conv2d(in_channels, channels, kernel_size=3, stride=stride, padding=1, bias=False))\n conv_layer.append(nn.BatchNorm2d(channels))\n conv_layer.append(nn.ReLU(inplace=True))\n conv_layer.append(nn.Conv2d(channels, channels, kernel_size=3, stride=1, padding=1, bias=False))\n conv_layer.append(nn.BatchNorm2d(channels))\n\n layers.append(nn.Sequential(*conv_layer))\n\n shortcut = nn.Sequential()\n\n if stride != 1 or in_channels != self.expansion*channels:\n shortcut = nn.Sequential(\n nn.Conv2d(in_channels, self.expansion*channels, kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(self.expansion*channels)\n )\n\n layers.append(shortcut)\n layers.append(nn.ReLU(inplace=True))\n\n self.layers = layers\n \n def forward(self, x):\n fwd = self.layers[0](x) \n fwd += self.layers[1](x) \n fwd = self.layers[2](fwd) \n return fwd\n\nclass ResNet(nn.Module):\n def __init__(self, args, params):\n super(ResNet, self).__init__()\n self.num_blocks = params['num_blocks']\n self.num_classes = int(params['num_classes'])\n self.augment_training = params['augment_training']\n self.input_size = int(params['input_size'])\n self.block_type = params['block_type']\n self.train_func = utils.cnn_train\n self.test_func = utils.cnn_test\n self.in_channels = 16\n self.num_output = 1\n\n if self.block_type == 'basic':\n self.block = BasicBlock\n\n init_conv = []\n\n init_conv.append(nn.Conv2d(3, self.in_channels, kernel_size=3, stride=1, padding=1, bias=False))\n \n init_conv.append(nn.BatchNorm2d(self.in_channels))\n init_conv.append(nn.ReLU(inplace=True))\n\n self.init_conv = nn.Sequential(*init_conv)\n\n self.layers = nn.ModuleList()\n self.layers.extend(self._make_layer(self.in_channels, block_id=0, stride=1))\n self.layers.extend(self._make_layer(32, block_id=1, stride=2))\n self.layers.extend(self._make_layer(64, block_id=2, stride=2))\n \n end_layers = []\n\n end_layers.append(nn.AvgPool2d(kernel_size=8))\n end_layers.append(utils.Flatten())\n end_layers.append(nn.Linear(64*self.block.expansion, self.num_classes))\n self.end_layers = nn.Sequential(*end_layers)\n\n self.initialize_weights()\n\n self.augment_training = params['augment_training']\n if 'distill' in args.mode:\n self.train_func = utils.cnn_train_dis\n else:\n self.train_func = utils.cnn_train\n self.test_func = utils.cnn_test\n\n def _make_layer(self, channels, block_id, stride):\n num_blocks = int(self.num_blocks[block_id])\n strides = [stride] + [1]*(num_blocks-1)\n layers = []\n for stride in strides:\n layers.append(self.block(self.in_channels, channels, stride))\n self.in_channels = channels * self.block.expansion\n return layers\n\n def forward(self, x):\n out = self.init_conv(x)\n \n for layer in self.layers:\n out = layer(out)\n\n out = self.end_layers(out)\n\n return out\n\n def initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\nclass wide_basic(nn.Module):\n def __init__(self, in_channels, channels, dropout_rate, stride=1):\n super(wide_basic, self).__init__()\n self.layers = nn.ModuleList()\n conv_layer = []\n conv_layer.append(nn.BatchNorm2d(in_channels))\n conv_layer.append(nn.ReLU(inplace=True))\n conv_layer.append(nn.Conv2d(in_channels, channels, kernel_size=3, padding=1, bias=True))\n conv_layer.append(nn.Dropout(p=dropout_rate))\n conv_layer.append(nn.BatchNorm2d(channels))\n conv_layer.append(nn.ReLU(inplace=True))\n conv_layer.append(nn.Conv2d(channels, channels, kernel_size=3, stride=stride, padding=1, bias=True))\n\n self.layers.append(nn.Sequential(*conv_layer))\n\n shortcut = nn.Sequential()\n if stride != 1 or in_channels != channels:\n shortcut = nn.Sequential(\n nn.Conv2d(in_channels, channels, kernel_size=1, stride=stride, bias=True),\n )\n\n self.layers.append(shortcut)\n\n def forward(self, x):\n out = self.layers[0](x)\n out += self.layers[1](x)\n return out\n\nclass WideResNet(nn.Module):\n def __init__(self, args, params):\n super(WideResNet, self).__init__()\n self.num_blocks = params['num_blocks']\n self.widen_factor = params['widen_factor']\n self.num_classes = int(params['num_classes'])\n self.dropout_rate = params['dropout_rate']\n self.augment_training = params['augment_training']\n self.input_size = int(params['input_size'])\n self.augment_training = params['augment_training']\n if 'distill' in args.mode:\n self.train_func = utils.cnn_train_dis\n else:\n self.train_func = utils.cnn_train\n self.test_func = utils.cnn_test\n self.in_channels = 16\n self.num_output = 1\n\n self.init_conv = nn.Conv2d(3, self.in_channels, kernel_size=3, stride=1, padding=1, bias=True)\n \n self.layers = nn.ModuleList()\n self.layers.extend(self._wide_layer(wide_basic, self.in_channels*self.widen_factor, block_id=0, stride=1))\n self.layers.extend(self._wide_layer(wide_basic, 32*self.widen_factor, block_id=1, stride=2))\n self.layers.extend(self._wide_layer(wide_basic, 64*self.widen_factor, block_id=2, stride=2))\n\n end_layers = []\n\n end_layers.append(nn.BatchNorm2d(64*self.widen_factor, momentum=0.9))\n end_layers.append(nn.ReLU(inplace=True))\n end_layers.append(nn.AvgPool2d(kernel_size=8))\n end_layers.append(utils.Flatten())\n end_layers.append(nn.Linear(64*self.widen_factor, self.num_classes))\n self.end_layers = nn.Sequential(*end_layers)\n\n\n self.initialize_weights()\n\n def _wide_layer(self, block, channels, block_id, stride):\n num_blocks = int(self.num_blocks[block_id])\n strides = [stride] + [1]*(num_blocks-1)\n layers = []\n for stride in strides:\n layers.append(block(self.in_channels, channels, self.dropout_rate, stride))\n self.in_channels = channels\n return layers\n\n def forward(self, x):\n out = self.init_conv(x)\n\n for layer in self.layers:\n out = layer(out)\n\n out = self.end_layers(out)\n\n return out\n\n def initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.xavier_uniform_(m.weight, gain=np.sqrt(2))\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.Linear):\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\nclass ConvBlock(nn.Module):\n def __init__(self, conv_params):\n super(ConvBlock, self).__init__()\n input_channels = conv_params[0]\n output_channels = conv_params[1]\n avg_pool_size = conv_params[2]\n batch_norm = conv_params[3]\n\n conv_layers = []\n conv_layers.append(nn.Conv2d(in_channels=input_channels, out_channels=output_channels, kernel_size=3,padding=1))\n\n if batch_norm:\n conv_layers.append(nn.BatchNorm2d(output_channels))\n \n conv_layers.append(nn.ReLU())\n \n if avg_pool_size > 1:\n conv_layers.append(nn.AvgPool2d(kernel_size=avg_pool_size))\n \n self.layers = nn.Sequential(*conv_layers)\n\n def forward(self, x):\n fwd = self.layers(x)\n return fwd\n\nclass FcBlock(nn.Module):\n def __init__(self, fc_params, flatten):\n super(FcBlock, self).__init__()\n input_size = int(fc_params[0])\n output_size = int(fc_params[1])\n\n fc_layers = []\n if flatten:\n fc_layers.append(utils.Flatten())\n fc_layers.append(nn.Linear(input_size, output_size))\n fc_layers.append(nn.ReLU())\n fc_layers.append(nn.Dropout(0.5)) \n self.layers = nn.Sequential(*fc_layers)\n\n def forward(self, x):\n fwd = self.layers(x)\n return fwd\n\nclass VGG(nn.Module):\n def __init__(self, args, params):\n super(VGG, self).__init__()\n\n self.input_size = int(params['input_size'])\n self.num_classes = int(params['num_classes'])\n self.conv_channels = params['conv_channels'] \n self.fc_layer_sizes = params['fc_layers']\n\n self.max_pool_sizes = params['max_pool_sizes']\n self.conv_batch_norm = params['conv_batch_norm']\n self.init_weights = params['init_weights']\n self.augment_training = params['augment_training']\n if 'distill' in args.mode:\n self.train_func = utils.cnn_train_dis\n else:\n self.train_func = utils.cnn_train\n self.test_func = utils.cnn_test\n self.num_output = 1\n\n self.init_conv = nn.Sequential()\n\n self.layers = nn.ModuleList()\n input_channel = 3\n cur_input_size = self.input_size\n for layer_id, channel in enumerate(self.conv_channels):\n if self.max_pool_sizes[layer_id] == 2:\n cur_input_size = int(cur_input_size/2)\n conv_params = (input_channel, channel, self.max_pool_sizes[layer_id], self.conv_batch_norm)\n self.layers.append(ConvBlock(conv_params))\n input_channel = channel\n \n fc_input_size = cur_input_size*cur_input_size*self.conv_channels[-1]\n\n for layer_id, width in enumerate(self.fc_layer_sizes[:-1]):\n fc_params = (fc_input_size, width)\n flatten = False\n if layer_id == 0:\n flatten = True\n \n self.layers.append(FcBlock(fc_params, flatten=flatten))\n fc_input_size = width\n \n end_layers = []\n end_layers.append(nn.Linear(fc_input_size, self.fc_layer_sizes[-1]))\n end_layers.append(nn.Dropout(0.5))\n end_layers.append(nn.Linear(self.fc_layer_sizes[-1], self.num_classes))\n self.end_layers = nn.Sequential(*end_layers)\n\n if self.init_weights:\n self.initialize_weights()\n\n def forward(self, x):\n fwd = self.init_conv(x)\n\n for layer in self.layers:\n fwd = layer(fwd)\n\n fwd = self.end_layers(fwd)\n return fwd\n\n def initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\nclass Block(nn.Module):\n '''Depthwise conv + Pointwise conv'''\n def __init__(self, in_channels, out_channels, stride=1):\n super(Block, self).__init__()\n conv_layers = []\n conv_layers.append(nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=stride, padding=1, groups=in_channels, bias=False))\n conv_layers.append(nn.BatchNorm2d(in_channels))\n conv_layers.append(nn.ReLU())\n conv_layers.append(nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False))\n conv_layers.append(nn.BatchNorm2d(out_channels))\n conv_layers.append(nn.ReLU())\n\n self.layers = nn.Sequential(*conv_layers)\n\n def forward(self, x):\n fwd = self.layers(x)\n return fwd\n\nclass MobileNet(nn.Module):\n def __init__(self, args,params):\n super(MobileNet, self).__init__()\n self.cfg = params['cfg']\n self.num_classes = int(params['num_classes'])\n self.augment_training = params['augment_training']\n self.input_size = int(params['input_size'])\n if 'distill' in args.mode:\n self.train_func = utils.cnn_train_dis\n else:\n self.train_func = utils.cnn_train\n self.test_func = utils.cnn_test\n self.num_output = 1\n self.in_channels = 32\n init_conv = []\n \n init_conv.append(nn.Conv2d(3, self.in_channels, kernel_size=3, stride=1, padding=1, bias=False))\n init_conv.append(nn.BatchNorm2d(self.in_channels))\n init_conv.append(nn.ReLU(inplace=True))\n self.init_conv = nn.Sequential(*init_conv)\n\n self.layers = nn.ModuleList()\n self.layers.extend(self._make_layers(in_channels=self.in_channels))\n\n end_layers = []\n\n end_layers.append(nn.AvgPool2d(2))\n\n end_layers.append(utils.Flatten())\n end_layers.append(nn.Linear(1024, self.num_classes))\n self.end_layers = nn.Sequential(*end_layers)\n\n def _make_layers(self, in_channels):\n layers = []\n for x in self.cfg:\n out_channels = x if isinstance(x, int) else x[0]\n stride = 1 if isinstance(x, int) else x[1]\n layers.append(Block(in_channels, out_channels, stride))\n in_channels = out_channels\n return layers\n\n def forward(self, x):\n fwd = self.init_conv(x)\n for layer in self.layers:\n fwd = layer(fwd)\n\n fwd = self.end_layers(fwd)\n return fwd\n\n\n","repo_name":"DennisLiu2022/Membership-Inference-Attacks-by-Exploiting-Loss-Trajectory","sub_path":"architectures.py","file_name":"architectures.py","file_ext":"py","file_size_in_byte":15554,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"20"} +{"seq_id":"33938041065","text":"import fire\nimport torch\n\nfrom .model import GPT\nfrom .utils import get_device, get_tokenizer, set_seed\n\n\ndef from_openai(model_name):\n model = GPT.from_pretrained(model_name)\n tokenizer = get_tokenizer(\"gpt2\")\n return model, tokenizer\n\n\ndef from_ckpt_path(ckpt_path):\n ckpt = torch.load(ckpt_path)\n hparams = ckpt[\"hyper_parameters\"]\n tokenizer = get_tokenizer(hparams[\"tokenizer_name\"])\n model = GPT(**hparams[\"model\"])\n state_dict = {k.removeprefix(\"gpt.\"): v for k, v in ckpt[\"state_dict\"].items()}\n model.load_state_dict(state_dict)\n return model, tokenizer\n\n\ndef main(\n prompt,\n n_tokens_to_generate=30,\n batch_size=4,\n temperature=0.25,\n model_name_or_ckpt_path=\"gpt2\",\n seed=1234,\n):\n set_seed(seed)\n device = get_device()\n\n if model_name_or_ckpt_path in [\"gpt2\", \"gpt2-medium\", \"gpt2-large\", \"gpt2-xl\"]:\n model, tokenizer = from_openai(model_name_or_ckpt_path)\n else:\n model, tokenizer = from_ckpt_path(model_name_or_ckpt_path)\n model = model.to(device)\n model.eval()\n\n input_ids = torch.tensor(tokenizer.encode(prompt)).repeat(batch_size, 1).to(device)\n\n output_ids = model.generate(input_ids, n_tokens_to_generate, temperature)\n for i, ids in enumerate(output_ids):\n print(f\"==== Result {i + 1} ====\")\n print(tokenizer.decode(list(ids)))\n print()\n\n\nif __name__ == \"__main__\":\n fire.Fire(main)\n","repo_name":"jaymody/simpleGPT","sub_path":"src/simplegpt/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"20"} +{"seq_id":"6332007441","text":"import os\nimport numpy as np\nimport pandas as pd\ndef zdt1(x):\n g = 1 + 9 * np.sum(x[1:]) / (len(x) - 1)\n return (x[0], g * (1 - np.sqrt(x[0] / g))),[]\n\ndef helper(func):\n pdf = pd.read_csv(\"dv.dat\",delim_whitespace=True,index_col=0, header=None, names=[\"parnme\",\"parval1\"])\n #obj1,obj2 = func(pdf.values)\n objs,constrs = func(pdf.values)\n \n if os.path.exists(\"additive_par.dat\"):\n obj1,obj2 = objs[0],objs[1]\n cdf = pd.read_csv(\"additive_par.dat\", delim_whitespace=True, index_col=0,header=None, names=[\"parnme\",\"parval1\"])\n obj1[0] += cdf.parval1.values[0]\n obj2[0] += cdf.parval1.values[1]\n for i in range(len(constrs)):\n constrs[i] += cdf.parval1.values[i+2]\n\n with open(\"obj.dat\",'w') as f:\n for i,obj in enumerate(objs):\n f.write(\"obj_{0} {1}\\n\".format(i+1,float(obj)))\n #f.write(\"obj_2 {0}\\n\".format(float(obj2)))\n for i,constr in enumerate(constrs):\n f.write(\"constr_{0} {1}\\n\".format(i+1,float(constr)))\n\nif __name__ == '__main__':\n helper(zdt1)\n","repo_name":"pestpp/pestpp-ies_benchmarks","sub_path":"zdt1/zdt1_template/forward_run.py","file_name":"forward_run.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"20363835607","text":"import pandas as pd\nimport operator\nimport numpy as np\n\n\n\ndef read_csv(filename):\n\t'''\n\tLee el csv y devuelve un diccionario con los valores medios o moda, max, min de las variables numericas y categoricas \n\t'''\n\tdf = pd.read_csv(filename)\n\tcategorical = ['v3','v22','v24', 'v30', 'v31', 'v47', 'v52', 'v56', 'v66', 'v71', 'v74', 'v75', 'v79', 'v91', 'v107' , 'v110', 'v112', 'v113', 'v125']\n\tresult_values = dict()\n\tfor i in categorical:\n\t\tdicc = dict()\n\t\tcolumn = df[i]\n\t\tfor j in column:\n\t\t\tif not dicc.has_key(j) and not pd.isnull(j):\n\t\t\t\tdicc[j] = 1\n\t\t\telif dicc.has_key(j) and not pd.isnull(j):\n\t\t\t\tvalue = dicc.get(j)+1\n\t\t\t\tdicc[j] = value\n\t\tvalue = (max(dicc.iteritems(), key=operator.itemgetter(1))[0] , min(dicc.iteritems(), key=operator.itemgetter(1))[0]) \n\t\tresult_values[i] = value\n\n\n\tremove = categorical\n\tremove.extend(['ID','target'])\n\tnumerical = df.drop(remove,axis=1)\n\n\tfor i in numerical:\n\t\tcolumn = df[i]\n\t\tvector = []\n\t\tfor j in column:\n\t\t\tif not pd.isnull(j):\n\t\t\t\tvector.append(j)\n\t\tvalue = (np.mean(vector) , max(vector), min(vector))\n\t\tresult_values[i] = value\t\t\n\n\treturn result_values\n\n\ndef complete_data(filenameInput, filenameOutput, categorical=\"max\" , numerical=\"media\"):\n\t'''\n\tRecibe el archivo de entrada y el nombre del nuevo archivo\n\tEl parametro categorical por defecto \"max\" llena los nulos con la moda. \"min\" los llena con el valor minimo\n\tEl parametro numerical por defecto \"media\" los llena con el promedio. \n\n\tcategorical: max - min \n\tnumerical: media , max , min \n\t'''\n\n\tcategorical_values = ['v3','v22','v24', 'v30', 'v31', 'v47', 'v52', 'v56', 'v66', 'v71', 'v74', 'v75', 'v79', 'v91', 'v107' , 'v110', 'v112', 'v113', 'v125']\n\n\n\tresult_values = read_csv(filenameInput)\n\tnew_data = dict()\t\n\n\t\n\tdf = pd.read_csv(filenameInput)\n\tcolumns = [x for x in df] \n\n\tindex_categorical = 0\n\tindex_numerical = 0\n\n\tif categorical==\"max\":\n\t\tindex_categorical = 0\n\telse:\n\t\tindex_categorical = 1\n\n\n\tif numerical == \"media\":\n\t\tindex_numerical = 0\n\telif numerical == \"max\":\n\t\tindex_numerical = 1\n\telse: \n\t\tindex_numerical = 2\n\n\n\tfor i in df:\n\t\tvector = []\n\t\tcolumn = df[i]\n\n\t\tif result_values.has_key(i):\n\t\t\t\n\t\t\tfor j in column:\n\t\t\t\tif pd.isnull(j):\n\t\t\t\t\tvalue=0\n\t\t\t\t\tif i in categorical_values:\n\t\t\t\t\t\tvalue = result_values.get(i)[index_categorical]\n\t\t\t\t\telse:\n\t\t\t\t\t\tvalue = result_values.get(i)[index_numerical]\n\t\t\t\t\tvector.append(value)\n\t\t\t\telse:\n\t\t\t\t\tvector.append(j)\n\t\t\tnew_data[i] = vector\n\t\telse:\n\t\t\tvector = [x for x in column]\n\t\t\tnew_data[i] = vector\n\t\n\tdata = pd.DataFrame(new_data, columns=columns)\n\tdata.to_csv(filenameOutput) \n\treturn data\n\ndef complete_train_and_test(trainInput, trainOutput, testInput ,testOutput):\n\tcategorical_values = ['v3','v22','v24', 'v30', 'v31', 'v47', 'v52', 'v56', 'v66', 'v71', 'v74', 'v75', 'v79', 'v91', 'v107' , 'v110', 'v112', 'v113', 'v125']\n\n\n\tresult_values = read_csv(trainInput)\n\n\tindex_categorical = 0 # moda\n\tindex_numerical = 0 # media\n\n\n\tnew_data = dict()\t\n\tnew_data_test = dict()\n\tdf = pd.read_csv(trainInput)\n\tcolumns = [x for x in df] \n\t\n\tfor i in df:\n\t\tvector = []\n\t\tcolumn = df[i]\n\n\t\tif result_values.has_key(i):\n\t\t\t\n\t\t\tfor j in column:\n\t\t\t\tif pd.isnull(j):\n\t\t\t\t\tvalue=0\n\t\t\t\t\tif i in categorical_values:\n\t\t\t\t\t\tvalue = result_values.get(i)[index_categorical]\n\t\t\t\t\telse:\n\t\t\t\t\t\tvalue = result_values.get(i)[index_numerical]\n\t\t\t\t\tvector.append(value)\n\t\t\t\telse:\n\t\t\t\t\tvector.append(j)\n\t\t\tnew_data[i] = vector\n\t\telse:\n\t\t\tvector = [x for x in column]\n\t\t\tnew_data[i] = vector\n\n\n\n\tdf2 = pd.read_csv(testInput)\n\tfor i in df2:\n\t\tvector = []\n\t\tcolumn = df2[i]\n\n\t\tif result_values.has_key(i):\n\t\t\tfor j in column:\n\t\t\t\tif pd.isnull(j):\n\t\t\t\t\tvalue = 0\n\t\t\t\t\tif i in categorical_values:\n\t\t\t\t\t\tvalue = result_values.get(i)[index_categorical]\n\t\t\t\t\telse:\n\t\t\t\t\t\tvalue = result_values.get(i)[index_numerical]\n\t\t\t\t\tvector.append(value)\n\t\t\t\telse:\n\t\t\t\t\tvector.append(j)\n\t\t\tnew_data_test[i] = vector \n\t\telse:\n\t\t\tvector = [x for x in column]\n\t\t\tnew_data_test[i] = vector\n\t\n\n\n\n\n\tdata = pd.DataFrame(new_data, columns=columns)\n\tdata.to_csv(trainOutput)\n\n\n\tcolumns.remove('target')\n\tdata2 = pd.DataFrame(new_data_test, columns=columns)\t\n\tdata2.to_csv(testOutput)\n\n \n\nif __name__ == '__main__':\n\n\tdata_train = \"data/train.csv\"\n\tdata_test = \"data/test.csv\"\n\n\n\tmuestra = \"data/muestra.csv\"\n\tmuestra_test = \"data/muestra_test.csv\"\n\t\n\t#data = complete_data(muestra , \"output3.csv\", categorical=\"min\", numerical=\"min\")\n\t#data = complete_data(data_train , \"outputTrain.csv\")\n\n\n\tcomplete_train_and_test(muestra, \"outputMuestraTrain.csv\", muestra_test, \"outputMuestraTest.csv\")\n","repo_name":"raynerhmc/KaggleParibasTeam","sub_path":"KaggleParibas/Jorge/reading.py","file_name":"reading.py","file_ext":"py","file_size_in_byte":4522,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"73355909489","text":"#!/usr/local/bin/python3\n# fibonacce -- sequencia de numeros somados ao seu antecessor.\n# exemplo\n# 0, 1, 1, 2, 3, 5, 8, 13, 21 ...\n\n# vou determinar a quantidade de repetições que quero\ndef fibonacci(quantidade):\n resultado = [0, 1]\n while True:\n resultado.append(sum(resultado[-2:]))\n if len(resultado) == quantidade:\n break\n return resultado\n\n\nif __name__ == '__main__':\n # listar os 20 primeiros números da sequência.\n for fib in fibonacci(int(input('Defina a quantidade de repetições do loop: '))):\n print(fib)\n","repo_name":"Dipeoliver/python_class","sub_path":"estrutura_controle_projetos/Class_92_Fibo.py","file_name":"Class_92_Fibo.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"10419470510","text":"# coding=utf-8\nimport time\nimport random\nimport requests\nimport pandas as pd\nfrom requests.exceptions import RequestException\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import WebDriverException\n\ndef get_one_page(url):\n try:\n response = requests.get(url)\n response.encoding = 'gbk'\n if response.status_code == 200:\n return response.text\n print('requests error')\n return None\n except RequestException:\n return None\n\n\nclass spider_TB:\n def __init__(self, start_page, end_page):\n self.login_url = 'https://login.taobao.com/member/login.jhtml'\n self.user = ''\n self.pwd = ''\n self.search_key = '手机'\n self.result_path = '../data/tb.csv'\n self.start_page = start_page\n self.end_page = end_page\n\n options = webdriver.ChromeOptions()\n # options.add_argument('headless')\n options.add_experimental_option('excludeSwitches', ['enable-automation'])\n # options.add_experimental_option('prefs', {'profile.managed_default_content_settings.images': 2}) \n \n self.driver = webdriver.Chrome(options=options)\n self.wait = WebDriverWait(self.driver, 60)\n\n self.login()\n self.search()\n self.parse()\n \n self.driver.quit()\n\n def wait_css(self, css):\n return self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, css)))\n\n def clean(self, s):\n return s.replace(' ', '')\n\n def update_detail(self, detail, left, right):\n if '型号' in left:\n detail['型号'] = self.clean(right)\n elif '品牌' in left and 'CPU' not in left:\n detail['品牌'] = self.clean(right)\n elif '内存' in left:\n detail['运行内存'] = self.clean(right)\n elif '容量' in left:\n detail['机身存储'] = self.clean(right)\n\n def get_detail(self, html):\n is_taobao = 1 if 'taobao' in self.driver.current_url else 0\n detail = {}\n if is_taobao:\n flag = True\n try:\n ps = self.driver.find_elements_by_css_selector('.tb-attributes-list > li > p')\n for p in ps:\n lst = str(p.text).split(':')\n if len(lst) != 2:\n continue\n left, right = lst\n self.update_detail(detail, left, right.strip())\n except NoSuchElementException:\n flag = False\n \n if not flag:\n try:\n lis = self.driver.find_element_by_css_selector('.attributes-list > li')\n for li in lis:\n lst = str(li.text).split(':')\n if len(lst) != 2:\n continue\n left, right = lst\n self.update_detail(detail, left, right.strip())\n except NoSuchElementException:\n pass\n else:\n self.wait_css('#J_Detail > .J_DetailSection tr')\n trs = self.driver.find_elements_by_css_selector('#J_Detail > .J_DetailSection tr')\n for tr in trs:\n try:\n ths = tr.find_elements_by_css_selector('th')\n tds = tr.find_elements_by_css_selector('td')\n for td in tds:\n right = td.get_attribute('innerHTML')\n for th in ths:\n left = th.get_attribute('innerHTML')\n self.update_detail(detail, left, right)\n except NoSuchElementException:\n continue\n return detail\n\n def login(self):\n self.driver.get(self.login_url)\n \n pwd_login = self.wait_css('.qrcode-login > .login-links > .forget-pwd')\n pwd_login.click()\n time.sleep(random.randint(3, 7))\n\n weibo_login = self.wait_css('.weibo-login')\n weibo_login.click()\n time.sleep(random.randint(3, 7))\n\n user = self.wait_css('.username > .W_input')\n user.send_keys(self.user)\n time.sleep(random.randint(3, 7))\n\n pwd = self.wait_css('.password > .W_input')\n pwd.send_keys(self.pwd)\n time.sleep(random.randint(3, 7))\n\n submit = self.wait_css('.btn_tip > a > span')\n submit.click()\n time.sleep(random.randint(3, 7))\n\n self.wait_css('.site-nav-bd > ul.site-nav-bd-l > li#J_SiteNavLogin > div.site-nav-menu-hd > div.site-nav-user > a.site-nav-login-info-nick ')\n print('login successfully!')\n \n def search(self):\n input = self.wait_css('.search-combobox-input')\n input.send_keys(self.search_key)\n time.sleep(random.randint(3, 7))\n\n search = self.wait_css('.btn-search')\n search.click()\n time.sleep(random.randint(3, 7))\n\n sorts = self.driver.find_elements_by_css_selector('.sorts > .sort > .J_Ajax')\n for sort in sorts:\n if '销量' in sort.get_attribute('innerHTML'):\n sort.click()\n time.sleep(random.randint(3, 7))\n self.driver.refresh()\n break\n\n def save_checkpoint(self, index, result):\n df_cur = pd.DataFrame(result)\n if df_cur.shape[1] != 6:\n return False\n if index > 1:\n df_old = pd.read_csv(self.result_path, usecols=[1,2,3,4,5,6])\n df = pd.concat([df_old, df_cur])\n df.to_csv(self.result_path)\n else:\n df = df_cur\n df.to_csv(self.result_path)\n print('page', index, 'has been finished.')\n return True\n\n def parse(self):\n cnt = 0\n handle = self.driver.current_window_handle\n if self.start_page != 1:\n self.driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')\n time.sleep(random.randint(3, 7))\n self.driver.execute_script('window.scrollTo(0, 0)')\n for page in range(self.start_page, self.end_page + 1):\n result = []\n if page > 1:\n input = self.wait_css('.J_Input')\n input.clear()\n input.send_keys(page)\n time.sleep(random.randint(3, 7))\n submit = self.wait_css('.J_Submit')\n submit.click()\n # self.driver.refresh()\n time.sleep(random.randint(5, 10))\n\n self.wait_css('.J_MouserOnverReq')\n items = self.driver.find_elements_by_css_selector('.J_MouserOnverReq')\n for item in items:\n price = item.find_element_by_css_selector('.price > strong').text\n deal = item.find_element_by_css_selector('.deal-cnt').text\n url = item.find_element_by_css_selector('.row-2 > .J_ClickStat')\n url.click()\n\n handles = self.driver.window_handles\n for i in handles:\n if i != handle:\n self.driver.switch_to.window(i)\n try:\n detail = self.get_detail(self.driver.page_source)\n except WebDriverException:\n detail = {}\n self.driver.close()\n self.driver.switch_to.window(handle)\n\n info = {\n '价格': price,\n '销量': deal\n }\n info.update(detail)\n\n cnt = cnt + 1\n print(page, cnt, info)\n result.append(info)\n time.sleep(random.randint(3, 7))\n\n if not self.save_checkpoint(page, result):\n print('failed on page', page)\n break \n\n\nclass spider_JD:\n def __init__(self, start_page, end_page):\n self.start_page = start_page\n self.end_page = end_page\n self.url = 'https://www.jd.com/'\n self.result_path = '../data/jd.csv'\n\n options = webdriver.ChromeOptions()\n options.add_argument('headless')\n options.add_experimental_option('excludeSwitches', ['enable-automation'])\n options.add_experimental_option('prefs', {'profile.managed_default_content_settings.images': 2}) \n \n self.driver = webdriver.Chrome(options=options)\n self.driver.implicitly_wait(60)\n self.wait = WebDriverWait(self.driver, 60)\n\n self.driver.get(self.url)\n self.search()\n self.parse()\n \n self.driver.quit()\n\n def wait_css(self, css):\n return self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, css)))\n\n def search(self):\n input = self.wait_css('input.text')\n input.send_keys('手机')\n\n submit = self.wait_css('button.button')\n submit.click()\n\n self.wait_css('.f-sort .fs-tit')\n sorts = self.driver.find_elements_by_css_selector('.f-sort .fs-tit')\n for sort in sorts:\n if '评论数' in sort.get_attribute('innerHTML'):\n sort.click() \n self.driver.refresh()\n break\n\n def get_detail(self, url):\n html = get_one_page(url)\n detail = {}\n if html is None:\n return detail\n soup = BeautifulSoup(html, 'html.parser')\n infos = soup.select('#detail .clearfix')\n for info in infos:\n try:\n dt = info.select('dt')[0].string\n dd = info.select('dd')[0].string\n if '产品名称' in dt:\n detail['产品名称'] = dd\n elif '品牌' in dt and 'CPU' not in dt:\n detail['品牌'] = dd\n elif '机身存储' in dt:\n detail['机身存储'] = dd\n elif '运行内存' in dt:\n detail['运行内存'] = dd\n except IndexError:\n continue\n return detail\n \n def save_checkpoint(self, index, result):\n df_cur = pd.DataFrame(result)\n if df_cur.shape[1] != 6:\n return False\n if index > 1:\n df_old = pd.read_csv(self.result_path, usecols=[1,2,3,4,5,6])\n df = pd.concat([df_old, df_cur])\n df.to_csv(self.result_path)\n else:\n df = df_cur\n df.to_csv(self.result_path)\n print('page', index, 'has been finished.')\n return True\n\n def parse(self):\n cnt = 0\n for page in range(self.start_page, self.end_page + 1):\n result = []\n if page > 1:\n input = self.wait_css('.p-skip > .input-txt')\n input.clear()\n input.send_keys(page)\n submit = self.wait_css('.p-skip > .btn')\n submit.click()\n self.driver.refresh()\n time.sleep(random.randint(3, 7))\n\n self.driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')\n time.sleep(3)\n self.driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')\n time.sleep(3)\n self.driver.execute_script('window.scrollTo(0, 0)')\n\n soup = BeautifulSoup(self.driver.page_source, 'html.parser')\n items = soup.select('.gl-item')\n for item in items:\n price = item.select('.p-price > strong > i')[0].string\n deal = item.select('.p-commit > strong > a')[0].string\n url = item.select('.p-name > a')[0]['href']\n if 'https:' not in url:\n url = 'https:' + url\n detail = self.get_detail(url)\n\n info = {\n '价格': price,\n '销量': deal\n }\n info.update(detail)\n\n cnt = cnt + 1\n print(page, cnt, info)\n result.append(info) \n time.sleep(1) \n\n if not self.save_checkpoint(page, result):\n print('failed on page', page)\n break\n\n\nif __name__ == '__main__':\n spider_tb = spider_TB(1, 2)\n # spider_jd = spider_JD(1, 59)","repo_name":"Poeroz/TaobaoCrawler","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":12513,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"71582245170","text":"import os\nimport shutil\nimport subprocess\nimport click\nfrom PIL import Image\n\nTEMPLATEPROJECTNAME = \"TemplateProject\"\nGRADLE_LAUNCH = \"gradlew.bat\"\nGRADLE_OPTION = \":app:assembleDebug\"\n\nLOGO_RES = {\"h\": 72, \"m\": 48, \"xh\": 96, \"xxh\": 144, \"xxxh\": 192}\n\n\ndef replace_str_in_file(fileinout, oldstr, newstr):\n # Read in the file\n with open(fileinout, 'r') as file:\n filedata = file.read()\n filedata = filedata.replace(oldstr, newstr)\n\n # Write the file out again\n with open(fileinout, 'w') as file:\n file.write(filedata)\n\n\n@click.command()\n@click.argument(\"projectname\", required=True)\n@click.option(\n \"--html_folder\",\n required=False,\n help=\"HTML folder for new project\",\n)\n@click.option(\n \"--logo_folder\",\n required=False,\n help=\"HTML folder for new project\",\n)\ndef launch(projectname=\"\", html_folder=None, logo_folder=None):\n \"\"\"\n Create new Android project from Template Project\n\n :param projectname: name of new project\n :param html_folder: the name of html_folder\n \"\"\"\n\n # copy folder\n shutil.copytree(TEMPLATEPROJECTNAME, projectname)\n\n # copy html to asset if html_folder is given\n if html_folder is not None and os.path.isdir(html_folder):\n assert(os.path.exists(os.path.join(html_folder, \"index.html\"))), \\\n \"no index.html found. Please verify your html folder, it must contains main html page called \\\"index.html\\\"\"\n dst_asset = os.path.join(projectname, \"app\", \"src\", \"main\", \"assets\")\n shutil.copytree(html_folder, dst_asset)\n\n # Copy and rescale logo\n if logo_folder is not None and os.path.isdir(logo_folder):\n # verify if ic_launcher and ic_launcher_round exist\n img_list = [\n os.path.join(logo_folder, \"ic_launcher.png\"),\n os.path.join(logo_folder, \"ic_launcher_round.png\")\n ]\n for img in img_list:\n assert (os.path.exists(img)), \"no {} found.\".format(os.path.basename(img))\n for prefix, size in LOGO_RES.items():\n dst = os.path.join(projectname, \"app\", \"src\", \"main\", \"res\", \"mipmap-\"+prefix+\"dpi\", os.path.basename(img))\n im = Image.open(img)\n im.thumbnail((size,size), Image.LANCZOS)\n im.save(dst, \"PNG\")\n\n\n # Rename files\n shutil.move(os.path.join(projectname, TEMPLATEPROJECTNAME+\".iml\"), os.path.join(projectname, projectname+\".iml\"))\n src_java = os.path.join(projectname, \"app\",\"src\",\"main\",\"java\",\"com\",TEMPLATEPROJECTNAME.lower())\n dest_java = os.path.join(projectname, \"app\", \"src\", \"main\", \"java\", \"com\", projectname.lower())\n shutil.move(src_java, dest_java)\n\n # replace string in file\n fileinout_list = [\n os.path.join(projectname, projectname + \".iml\"),\n os.path.join(projectname, \"app\", \"src\", \"main\", \"res\", \"values\", \"strings.xml\")\n ]\n for fileinout in fileinout_list:\n replace_str_in_file(fileinout, TEMPLATEPROJECTNAME, projectname)\n\n # replace lower string in file\n fileinout_list_lower = [\n os.path.join(projectname, \"app\", \"build.gradle\"),\n os.path.join(projectname, \"app\", \"src\", \"main\", \"AndroidManifest.xml\"),\n os.path.join(projectname, \"app\", \"src\", \"main\", \"java\", \"com\", projectname.lower(), \"MainActivity.java\"),\n os.path.join(projectname, \"app\", \"src\", \"main\", \"res\", \"layout\", \"activity_main.xml\")\n ]\n for fileinout in fileinout_list_lower:\n replace_str_in_file(fileinout, TEMPLATEPROJECTNAME.lower(), projectname.lower())\n\n # launch compilation\n return_code = subprocess.run([GRADLE_LAUNCH, GRADLE_OPTION], shell=True, cwd=os.path.join(os.getcwd(), projectname))\n\n if return_code:\n apk_folder = os.path.join(projectname, \"app\", \"build\", \"outputs\", \"apk\", \"debug\")\n assert(os.path.exists(os.path.join(apk_folder, \"app-debug.apk\")))\n os.startfile(apk_folder)\n\n\nif __name__ == \"__main__\":\n launch()\n","repo_name":"haliminds/AndroidProject","sub_path":"androidProject.py","file_name":"androidProject.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"69927289330","text":"\"\"\"\nLongest Sequence with two Unique Numbers\nGiven an array we need to find the longest Longest Sequence with exactly two Unique Numbers.\n\neg: array: [1,3,5,3,1,3,1,5]\n Longest Sequence with two Unique Numbers: [3,1,3,1]\n\"\"\"\n\n\ndef findSequence(seq):\n if len(seq)<2:\n return len(seq)\n\n a,b=seq[0],seq[1]\n\n last_num=b\n last_num_count=(a==b)\n length=1\n max_length=1\n\n for n in seq[1:]:\n if n in (a,b):\n length+=1\n if b==n:\n last_num_count+=1\n else:\n last_num=a\n last_num_count=1\n else:\n a=last_num\n b=n\n last_num=b\n length=last_num_count+1\n max_length=max(length,max_length)\n return max_length\n\n\n\nprint(findSequence([1,3,5,3,1,3,1,5]))","repo_name":"kkgarai/Algo-Expert","sub_path":"Tch Coding Questions/17 Longest Sequence with two Unique Numbers.py","file_name":"17 Longest Sequence with two Unique Numbers.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17156078037","text":"import itertools\n\n\nclass ZigzagIterator:\n def __init__(self, v1, v2):\n def vals():\n for i in itertools.count():\n for v in v1, v2:\n if i < len(v):\n yield v[i]\n self.vals = vals()\n self.n = len(v1) + len(v2)\n\n def hasNext(self):\n return self.n > 0\n\n def next(self):\n self.n = self.n - 1\n return next(self.vals)\n\n\nif __name__ == \"__main__\":\n v1 = [1, 2, 3]\n v2 = [4, 5, 6, 8, 10]\n i, v = ZigzagIterator(v1, v2), []\n while i.hasNext():\n v.append(i.next())\n print(v)\n\n\n\n\n","repo_name":"DariaMinina/leetcode_solve_problems","sub_path":"zigzag_iterator.py","file_name":"zigzag_iterator.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31905377447","text":"import numpy as np\nfrom tqdm import tqdm\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n#We define the training as a function so we can easily re-use it.\ndef train(dataset, model, optimizer, num_epochs=10):\n def loss_fun(output, target):\n loss = nn.CrossEntropyLoss()\n return loss(output, target)\n #return F.nll_loss(output, target)\n out_dict = {'train_acc': [],\n 'test_acc': [],\n 'train_loss': [],\n 'test_loss': []}\n \n for epoch in tqdm(range(num_epochs), unit='epoch'):\n model.train()\n #For each epoch\n train_correct = 0\n train_loss = []\n for minibatch_no, (data, target) in tqdm(enumerate(dataset.train_loader), total=len(dataset.train_loader)):\n data, target = data.to(device), target.to(device)\n #Zero the gradients computed for each weight\n optimizer.zero_grad()\n #Forward pass your image through the network\n output = model(data)\n #Compute the loss\n loss = loss_fun(output, target)\n #Backward pass through the network\n loss.backward()\n #Update the weights\n optimizer.step()\n\n train_loss.append(loss.item())\n #Compute how many were correctly classified\n predicted = output.argmax(1)\n train_correct += (target==predicted).sum().cpu().item()\n #Comput the test accuracy\n test_loss = []\n test_correct = 0\n model.eval()\n for data, target in dataset.test_loader:\n data, target = data.to(device), target.to(device)\n with torch.no_grad():\n output = model(data)\n test_loss.append(loss_fun(output, target).cpu().item())\n predicted = output.argmax(1)\n test_correct += (target==predicted).sum().cpu().item()\n out_dict['train_acc'].append(train_correct/len(dataset.trainset))\n out_dict['test_acc'].append(test_correct/len(dataset.testset))\n out_dict['train_loss'].append(np.mean(train_loss))\n out_dict['test_loss'].append(np.mean(test_loss))\n print(f\"\\nLoss train: {np.mean(train_loss):.3f}\\t test: {np.mean(test_loss):.3f}\\t Accuracy train: {out_dict['train_acc'][-1]*100:.1f}%\\t test: {out_dict['test_acc'][-1]*100:.1f}%\")\n return out_dict","repo_name":"emilkris33/P1_1","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7916527731","text":"#encoding=utf-8\n\nimport os\nimport sys\nimport argparse\n\nparser = argparse.ArgumentParser(description=\"Normalize the phoneme on TIMIT\")\nparser.add_argument(\"--map\", default=\"./decode_map_48-39/phones.60-48-39.map\", help=\"The map file\")\nparser.add_argument(\"--to\", default=48, help=\"Determine how many phonemes to map\")\nparser.add_argument(\"--src\", default='./data_prepare/train/phn_text', help=\"The source file to mapping\")\nparser.add_argument(\"--tgt\", default='./data_prepare/train/48_text' ,help=\"The target file after mapping\")\n\ndef main():\n args = parser.parse_args()\n if not os.path.exists(args.map) or not os.path.exists(args.src):\n print(\"Map file or source file not exist !\")\n sys.exit(1)\n \n map_dict = {}\n with open(args.map) as f:\n for line in f.readlines():\n line = line.strip().split('\\t')\n if args.to == \"60-48\":\n if len(line) == 1:\n map_dict[line[0]] = \"\"\n else:\n map_dict[line[0]] = line[1]\n elif args.to == \"60-39\": \n if len(line) == 1:\n map_dict[line[0]] = \"\"\n else:\n map_dict[line[0]] = line[2]\n elif args.to == \"48-39\":\n if len(line) == 3:\n map_dict[line[1]] = line[2]\n else:\n print(\"%s phonemes are not supported\" % args.to)\n sys.exit(1)\n \n with open(args.src, 'r') as rf, open(args.tgt, 'w') as wf:\n for line in rf.readlines():\n line = line.strip().split(' ')\n uttid, utt = line[0], line[1:]\n map_utt = [ map_dict[phone] for phone in utt if map_dict[phone] != \"\" ]\n wf.writelines(uttid + ' ' + ' '.join(map_utt) + '\\n')\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Diamondfan/CTC_pytorch","sub_path":"timit/local/normalize_phone.py","file_name":"normalize_phone.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","stars":212,"dataset":"github-code","pt":"20"} +{"seq_id":"39559258744","text":"import functools\nfrom databricks.koalas.dask.compatibility import get_named_args\n\n\ndef derived_from(original_klass, version=None, ua_args=[]):\n \"\"\"Decorator to attach original class's docstring to the wrapped method.\n\n Parameters\n ----------\n original_klass: type\n Original class which the method is derived from\n version : str\n Original package version which supports the wrapped method\n ua_args : list\n List of keywords which Dask doesn't support. Keywords existing in\n original but not in Dask will automatically be added.\n \"\"\"\n def wrapper(method):\n method_name = method.__name__\n\n try:\n # do not use wraps here, as it hides keyword arguments displayed\n # in the doc\n original_method = getattr(original_klass, method_name)\n doc = original_method.__doc__\n if doc is None:\n doc = ''\n\n try:\n method_args = get_named_args(method)\n original_args = get_named_args(original_method)\n not_supported = [m for m in original_args if m not in method_args]\n except ValueError:\n not_supported = []\n\n if len(ua_args) > 0:\n not_supported.extend(ua_args)\n\n if len(not_supported) > 0:\n note = (\"\\n Notes\\n -----\\n\"\n \" Koalas doesn't support the following argument(s).\\n\\n\")\n args = ''.join([' * {0}\\n'.format(a) for a in not_supported])\n doc = doc + note + args\n doc = skip_doctest(doc)\n doc = extra_titles(doc)\n\n method.__doc__ = doc\n return method\n\n except AttributeError:\n module_name = original_klass.__module__.split('.')[0]\n\n @functools.wraps(method)\n def wrapped(*args, **kwargs):\n msg = \"Base package doesn't support '{0}'.\".format(method_name)\n if version is not None:\n msg2 = \" Use {0} {1} or later to use this method.\"\n msg += msg2.format(module_name, version)\n raise NotImplementedError(msg)\n return wrapped\n return wrapper\n\n\ndef _skip_doctest(line):\n # NumPy docstring contains cursor and comment only example\n stripped = line.strip()\n if stripped == '>>>' or stripped.startswith('>>> #'):\n return stripped\n elif '>>>' in stripped and '+SKIP' not in stripped:\n return line + ' # doctest: +SKIP'\n else:\n return line\n\n\ndef _pandas_to_koalas_in_doctest(line):\n return line.replace(\"pd\", \"ks\")\n\n\ndef skip_doctest(doc):\n if doc is None:\n return ''\n return '\\n'.join(\n [_pandas_to_koalas_in_doctest(_skip_doctest(line)) for line in doc.split('\\n')])\n\n\ndef extra_titles(doc):\n lines = doc.split('\\n')\n titles = {i: lines[i].strip() for i in range(len(lines) - 1)\n if lines[i + 1] and all(c == '-' for c in lines[i + 1].strip())}\n\n seen = set()\n for i, title in sorted(titles.items()):\n if title in seen:\n new_title = 'Extra ' + title\n lines[i] = lines[i].replace(title, new_title)\n lines[i + 1] = lines[i + 1].replace('-' * len(title),\n '-' * len(new_title))\n else:\n seen.add(title)\n\n return '\\n'.join(lines)\n","repo_name":"maingi254/customer360","sub_path":"transform/Lib/site-packages/databricks/koalas/dask/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"11699902523","text":"from .flight_comp import CompState, Action\nfrom .stage import Stage\nfrom .state import VehicleState\nfrom typing import Optional, List, Tuple\n\n\nclass Vehicle:\n \"\"\"\n Stores data about vehicle and interprets actions from flight computer.\n \"\"\"\n computer_state: CompState\n\n stage: Optional[Stage]\n remaining_engine_stages: List[Stage]\n parachute_stage: Optional[Stage]\n\n state: VehicleState\n\n def __init__(self,\n computer_state: CompState,\n stage: Optional[Stage],\n remaining_engine_stages: List[Stage],\n parachute_stage: Optional[Stage],\n state: VehicleState):\n \"\"\"\n :param computer_state: initial state of the computer.\n :param stage: current stage, e.g. engine being fired.\n :param remaining_engine_stages: list of stages which to be fired after current stage, in order which they\n should be fired.\n :param parachute_stage: stage to transition to to release parachute.\n :param state: current state of the vehicle.\n \"\"\"\n self.computer_state = computer_state\n self.stage = stage\n self.remaining_engine_stages = remaining_engine_stages\n self.parachute_stage = parachute_stage\n self.state = state\n\n def step(self, dt: float) -> 'Vehicle':\n \"\"\"\n :param dt: delta time, i.e. resolution.\n :return: next state of the vehicle.\n \"\"\"\n new_total_time = self.state.time_s + dt\n next_state = self.state.step(dt, new_total_time, self.stage)\n action, next_comp_state = self.computer_state.transition(self.state, next_state)\n next_stage, next_engine_stages = self._interpret(action)\n next_state.set_event_name(Vehicle._interpret_event_name(action))\n\n return Vehicle(next_comp_state, next_stage.step(dt), next_engine_stages, self.parachute_stage, next_state)\n\n def _interpret(self, action: Optional[Action]) -> Tuple[Stage, List[Stage]]:\n \"\"\"\n :param action: from flight computer to perform.\n :return: next stage to perform, as well as any remaining engine stages.\n \"\"\"\n if action is None:\n return self.stage, self.remaining_engine_stages\n\n elif action == Action.NEXT_STAGE:\n return self.remaining_engine_stages[0], self.remaining_engine_stages[1:]\n\n elif action == Action.PARACHUTE:\n if self.parachute_stage is None:\n raise RuntimeError('No parachute to eject')\n\n return self.parachute_stage, self.remaining_engine_stages\n\n raise RuntimeError('Unknown action')\n\n @staticmethod\n def _interpret_event_name(action: Optional[Action]) -> Optional[str]:\n if action is None:\n return None\n\n elif action == Action.NEXT_STAGE:\n return 'Stage'\n\n elif action == Action.PARACHUTE:\n return 'Parachute'\n\n raise RuntimeError('Unknown action')\n\n","repo_name":"BakerSmithA/rocket_sim","sub_path":"rocket_sim/vehicle.py","file_name":"vehicle.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"43470236294","text":"\n\n\nif __name__ == \"__main__\":\n PATH1 = r\"D:\\Speciale\\Code\\output\\Performance Trainings\\C48\\C48_Run1\\series.txt\"\n PATH2 = r\"D:\\Speciale\\Code\\output\\Performance Trainings\\C48\\2020-10-21--18-53-25_Training_7793\\series.txt\"\n\n f1 = open(PATH1, 'r')\n f2 = open(PATH2, 'r')\n\n for i in range(10):\n l1 = f1.readline()\n l2 = f2.readline()\n if(l1 != l2):\n print(\"NO\")\n exit(0)\n \n print(\"YES\")","repo_name":"Torehilbert/MasterThesis","sub_path":"wfutils/scripts/is_same_training.py","file_name":"is_same_training.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"35341903734","text":"from .. import models\n\n\ndef get_accounts(account_ids=[], fetch_user=False):\n datas = []\n for account_id in account_ids:\n account = models.Account.from_cache_by_id(account_id)\n if account:\n data = {}\n data['account'] = account\n if fetch_user:\n user = account.user\n data['user'] = user\n\n datas.append(data)\n return datas\n\n","repo_name":"zhongzhenyang/sz_sports_test","sub_path":"sz_webapp/helpers/model_helper.py","file_name":"model_helper.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"42568427332","text":"from django.db import models\nfrom django.db.models import Q\n\nfrom Collection.models import CardIDList\n\nfrom Models import CardFace\n\nclass DeckCardManager(models.Manager):\n def deck_card_by_deck_side(self, deck_id, side, commander):\n filter = Q(deck=deck_id) & Q(sideboard=side) & Q(commander=commander)\n return self.run_query(filter)\n\n def empty_deck(self, deck_id, side, commander):\n filter = Q(deck=deck_id) & Q(sideboard=side) & Q(commander=commander)\n return self.select_related().filter(\n filter\n ).delete()\n\n def deck_card_by_deck(self, deck_id):\n filter = Q(deck=deck_id)\n return self.run_query(filter)\n\n def deck_card_create(self, deck_id, card_oracle, quantity, side, commander):\n self.create(\n deck=deck_id,\n card_oracle=card_oracle,\n quantity=quantity,\n sideboard=side,\n commander=commander\n )\n\n def deck_card_update(self, deck_id, card_oracle, quantity, side, commander):\n return self.filter(deck=deck_id, card_oracle=card_oracle).update(\n quantity=quantity,\n sideboard=side,\n commander=commander\n )\n\n def deck_card_delete(self, deck_id, card_oracle, side, commander):\n self.filter(deck=deck_id,\n card_oracle=card_oracle,\n sideboard=side,\n commander=commander\n ).delete()\n\n def run_query(self, filter):\n return self.build_json(self.select_related().filter(\n filter\n ))\n\n def build_json(self, card_list):\n card_json_list = \"\"\n i = 0\n for card in card_list:\n card_json_list = card_json_list + card.__str__()\n if len(card_list) > 1 and i + 1 < len(card_list):\n card_json_list = card_json_list + '},'\n i += 1\n return card_json_list.__str__()\n\nclass DeckCard(models.Model):\n deck = models.IntegerField()\n card_oracle = models.CharField(max_length=200)\n quantity = models.IntegerField(default=0)\n sideboard = models.BooleanField(default=False)\n commander = models.BooleanField(default=False)\n\n objects = DeckCardManager()\n\n class Meta:\n app_label = \"Management\"\n\n def __str__(self):\n card_id_obj = CardIDList.get_card_face_by_oracle(self.card_oracle)\n card = CardFace.objects.select_related().filter(\n Q(legal__card_obj__card_id=card_id_obj.card_id)\n )[0]\n\n return '{' \\\n '\"deck_id\": \"' + str(self.deck) + \\\n '\", \"oracle_id\": \"' + str(self.card_oracle) + \\\n '\", \"quantity\": \"' + str(self.quantity) + \\\n '\", \"sideboard\": \"' + str(self.sideboard) + \\\n '\", \"commander\": \"' + str(self.commander) + \\\n '\", \"card_name\": \"' + str(card.name) + \\\n '\", \"card_image\": \"' + str(card.image_url) + \\\n '\", \"color_id\": \"' + str(card.color_id) + \\\n '\"}'","repo_name":"DustinWPernell/AppStateCapstone","sub_path":"content/Nenniltoz/Models/DeckCard.py","file_name":"DeckCard.py","file_ext":"py","file_size_in_byte":3026,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"24387497259","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport sys, os, warnings\ngpu = sys.argv[ sys.argv.index('-gpu') + 1 ] if '-gpu' in sys.argv else '0'\nos.environ['PYTHONHASHSEED'] = '0'\nos.environ['CUDA_VISIBLE_DEVICES']=gpu\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Disable Tensorflow CUDA load statements\nwarnings.filterwarnings('ignore')\n\nimport numpy as np\nimport argparse\nimport gc\nimport matplotlib\nmatplotlib.use('Agg')\nimport util\nimport utilDANN\nimport utilNNModel\nimport utilDANNModel\nimport utilGetData\nfrom keras import backend as K\n\nutil.init()\nK.set_image_data_format('channels_last')\n\nif K.backend() == 'tensorflow':\n import tensorflow as tf # Memory control with Tensorflow\n #config = tf.compat.v1.ConfigProto()\n config = tf.ConfigProto()\n config.gpu_options.allow_growth=True\n #sess = tf.compat.v1.Session(config=config)\n sess = tf.Session(config=config)\n K.set_session(sess)\n\n# -----------------------------------------------------------------------------\ndef train_dann(input_shape, num_labels, config, experiment):\n \n print('Getting data...')\n X_scalars_test, GT, fshots, shots = utilGetData.get_data()\n print('Done')\n machines = ['TCV', 'JET'] # source and target machines\n params_lstm_random = {\n 'batch_size': config.batch_size,\n 'lstm_time_spread': config.lstm_time_spread,\n 'epoch_size': config.epoch_size,\n 'no_input_channels' : config.no_input_channels,\n 'conv_w_size': config.conv_w_size,\n 'gaussian_hinterval': config.gaussian_hinterval,\n 'stride': config.stride,\n 'labelers': [config.labelers],\n 'shuffle': config.shuffle,\n 'conv_w_offset': config.conv_w_offset,\n 'normalization': config.normalization,\n 'no_classes': config.num_classes}\n\n if config.type=='adv':\n print('Getting adv model ...')\n config.batch_size = config.batch_size*2\n dann = utilDANNModel.DANNModel(config.model, input_shape, num_labels, config.batch_size)\n else:\n print('Getting std model ...')\n dann = utilNNModel.NNModel(config.model, input_shape, num_labels, config.batch_size)\n\n # I leave this comment since it will help in the future\n #dann_model = dann.build_tsne_model()\n #dann_vis = dann.build_dann_model()\n\n # Create dir with the id name of the experiment\n train_dir = './experiments/' + experiment\n if not os.path.isdir(train_dir):\n os.makedirs(train_dir)\n print('Will save this model in', train_dir)\n \n if config.load == False:\n utilDANN.train_dann(dann, None, None, config, experiment, params_lstm_random, machines, target_x_test=X_scalars_test, target_y_test=GT, test_shots=shots, fshots=fshots)\n else:\n print(' Load pre-trained model')\n dann.dann_model.load_weights(train_dir + '/model_checkpoints/' + 'weights.64.h5') # Load the save weights for a given epoch\n print('Start fine-tuning')\n utilDANN.train_dann(dann, None, None, config, experiment, weights_filename, params_lstm_random, machines, target_x_test=X_scalars_test, target_y_test=GT, test_shots=shots, fshots=fshots)\n\n gc.collect()\n\n\n\n# ----------------------------------------------------------------------------\n# ----------------------------------------------------------------------------\n# ----------------------------------------------------------------------------\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='DANN')\n\n group0 = parser.add_argument_group('Training type')\n group0.add_argument('-type', default='adv', type=str, help='Training type: adversarial (adv) or normal (std)')\n group0.add_argument('-model', default=99, type=int, help='Model number (1,2,3,4)')\n \n group1 = parser.add_argument_group('Input data parameters')\n group1.add_argument('-e',default=100,type=int,dest='epochs',help='Number of epochs')\n group1.add_argument('-stride',default=10,type=int, help='CNN-LSTM stride')\n group1.add_argument('-conv_w_size', default=40,type=int, help='CNN window size')\n group1.add_argument('-lstm_time_spread',default=2000, type=int, help='input seq length')\n group1.add_argument('-conv_w_offset',default=10,type=int, help='input seq offset')\n group1.add_argument('-gaussian_hinterval',default=5,type=int, help='smooth window size for labels')\n group1.add_argument('-normalization',default='z_GCS',type=str, help='smooth window size for labels')\n group1.add_argument('-shuffle',default=True,type=bool, help='shuffle data generator')\n group1.add_argument('-num_classes',default=2,type=int, help='number of confinement modes')\n group1.add_argument('-labelers',default='marceca',type=str, help='labeler name/type')\n group1.add_argument('-batch_size',default=64,type=int, help='batch size')\n group1.add_argument('-epoch_size',default=64,type=int, help='epoch size')\n group1.add_argument('-no_input_channels',default=3,type=int, help='number of input signals')\n\n parser.add_argument('-lda', default=0.03, type=float, help='Reversal gradient lambda')\n parser.add_argument('-lda_inc', default=0.001, type=float, help='Reversal gradient lambda increment')\n parser.add_argument('-lr', default=1.0, type=float, help='Learning rate')\n \n parser.add_argument('-set', default=1, type=int, help='Set of shots used for adv')\n\n parser.add_argument('--tsne', action='store_true', help='Activate TSNE')\n parser.add_argument('--aug', action='store_true', help='Use data augmentation')\n parser.add_argument('--load', action='store_true', help='Load weights.')\n parser.add_argument('--v', action='store_true', help='Activate verbose.')\n parser.add_argument('-gpu', default='0', type=str, help='GPU')\n args = parser.parse_args()\n\n input_shape = (None, 40, 3)\n num_labels = 3\n \n if args.type == 'std':\n args.lda = 0.0\n args.lda_inc = 0.0\n\n experiment = 'l_{}_inc_{}_{}_set{}_wodet'.format(str(args.lda), str(args.lda_inc), str(args.type), str(args.set))\n\n train_dann(input_shape, num_labels, args, experiment)\n","repo_name":"gmarceca/Adversarial-Conv-LSTM","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"42709741109","text":"def remove_nodes_from_graph(G,avg):\r\n G=G.copy()\r\n# total=0\r\n# counter=0\r\n print(len(G.edges()))\r\n print('It is getting the avergage')\r\n# for n in G.edges(data=True):\r\n# total+=n[2]['weight']\r\n# counter+=1\r\n# print(counter)\r\n# avg=total//counter\r\n# print(avg)\r\n# loop_counter=0\r\n for n in G.copy().edges(data=True):\r\n if n[2]['weight'] 2, T-SNE is used\n for the visualization (reducing the dimension of the data)\n \"\"\"\n if dataset is None:\n return\n\n z_array = np.zeros((\n len(dataset.dataset),\n network.get_z_dim()))\n labels = np.zeros(len(dataset.dataset))\n batch_id = 0\n for x, label in dataset:\n x = x.to(device)\n z1 = network.get_latent_space(x)\n np_z = z1.cpu().detach().numpy()\n np_label = label.detach().numpy()\n batch_size = np_z.shape[0]\n z_array[batch_id:batch_id + batch_size] = np_z[:, :]\n labels[batch_id:batch_id + batch_size] = np_label\n batch_id += batch_size\n\n if dark_background:\n plt.style.use('dark_background')\n\n fig = plt.figure(figsize=(12, 10))\n\n if network.get_z_dim() > dimensions:\n z_array = TSNE(n_components=dimensions).fit_transform(z_array)\n\n if dimensions == 2:\n plt.scatter(z_array[:, 0], z_array[:, 1], c=labels)\n plt.xlabel(\"z[0]\")\n plt.ylabel(\"z[1]\")\n plt.colorbar()\n\n elif dimensions == 3:\n ax = fig.add_subplot(111, projection='3d')\n cloud = ax.scatter(\n z_array[:, 0],\n z_array[:, 1],\n z_array[:, 2],\n c=labels)\n\n ax.set_xlabel(\"z[0]\")\n ax.set_ylabel(\"z[1]\")\n ax.set_zlabel(\"z[2]\")\n fig.colorbar(cloud)\n\n else:\n print(\"The dimensions param should be set to 2 or 3\")\n return\n\n plt.title(\"Latent space\")\n\n if not os.path.exists(\"../results\"):\n os.mkdir(\"../results\")\n\n plt.savefig(\"../results/latent_space.png\")\n plt.show()","repo_name":"mcaniot/simclr-pytorch","sub_path":"script/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"18572400522","text":"# Given a string s, reverse only all the vowels in the string and return it.\n\n# The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.\n\n \n\n# Example 1:\n\n# Input: s = \"hello\"\n# Output: \"holle\"\n# Example 2:\n\n# Input: s = \"leetcode\"\n# Output: \"leotcede\"\n \n\n# Constraints:\n\n# 1 <= s.length <= 3 * 105\n# s consist of printable ASCII characters.\n\n\ndef reverseVowels(s: str) -> str:\n vowles = 'aeiouAEIOU'\n stri = ''\n\n for i in s:\n if i in vowles:\n stri+=i\n\n ptr = 0\n newstr = ''\n\n for i in range(len(s)-1,-1,-1):\n if s[i] in vowles:\n newstr += stri[ptr]\n ptr +=1\n else:\n newstr += s[i]\n\n newstr = newstr[::-1]\n\n\nreverseVowels('hello')\nreverseVowels('leetcode')\n","repo_name":"VignanThota/leetcode-75","sub_path":"Reverse_Vowels_of_a_String.py","file_name":"Reverse_Vowels_of_a_String.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"31745691155","text":"# -*- coding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\n\n\nwith open('README.md') as f:\n readme = f.read()\n\nsetup(\n name='Practica 2 TDD',\n version='1.0.0',\n description='Practica para contar el numero de palabras que aparecen en un texto',\n long_description=readme,\n author='Alfonso Cuesta y Arturo Lara',\n packages=find_packages(exclude=('tests', 'docs'))\n)","repo_name":"ArturoLara/Proyecto-2-TDD","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25575078463","text":"import time\nimport datetime\nimport numpy as np\nimport struct\nimport casperfpga\nimport sys\n\nfrom astropy.time import Time\nfrom astropy import units as u\nfrom astropy.coordinates import EarthLocation, SkyCoord, AltAz\n\n#################################################################################################################\n# INITIALIZE RED PITAYA (USEFUL FOR CASE OF POWER CYCLE)\n#################################################################################################################\ndef init_rp(bof = 'firmware/loberotator_final_2022-07-14_1419.fpg'):\n \"\"\"\n Initialize BRAM and required registers for Red Pitaya - need to do this every time board is power cycled\n :param bof: firmware file used to program FPGA - should be either .bof or .fpg\n \"\"\"\n # connect to board\n rp = casperfpga.CasperFpga('rp-f07179.ovro.pvt')\n\n # program board with bof file\n rp.upload_to_ram_and_program(bof)\n\n # check that board is running\n print(rp.is_running())\n print(rp.is_connected())\n\n # program bram with values of sin and cos\n N = 2 ** 11\n n = np.arange(N) / float(N - 1)\n\n bram_dict = {'sin': np.sin(2 * np.pi * n), 'cos': np.cos(2 * np.pi * n)}\n bram_32b = {}\n\n for key in bram_dict.keys():\n\n scaled_sig_32b = np.empty(N)\n\n sig = bram_dict[key]\n for i in range(len(sig)):\n scaled_sig_32b[i] = sig[i] * (2 ** 31) - 1\n\n vals_32b = scaled_sig_32b.astype(int)\n\n # iterate through all values, pack them as hex data and write each word to correct bram address\n bram_name = 'bram_%s_phi' % key\n\n for j in range(2048):\n buf_val = struct.pack('>1i', vals_32b[j])\n rp.write(bram_name, buf_val, 4 * j)\n\n # read back from bram to ensure this worked properly\n bram_32b[key] = np.array(struct.unpack('>2048i', rp.read(bram_name, 2048 * 4, 0)))\n\n rp.write_int('phi_init', 0 * (2 ** 32))\n rp.write_int('phi_step', int(4e-9 * (2 ** 31)))\n\n delay = 0.46 # rad\n c1 = -1 / np.sin(delay)\n c2 = np.cos(delay) / np.sin(delay)\n\n rp.write_int('c1', int(c1 * (2 ** 14)))\n rp.write_int('c2', int(c2 * (2 ** 14)))\n\n rp.write_int('reg_cntrl', 1)\n rp.write_int('reg_cntrl', 0)\n\n\n#################################################################################################################\n# CALCULATE LOBE ROTATION RATE FOR ADJUSTING VALUES IN RED PITAYA\n#################################################################################################################\nC = 3e10 # speed of light\nB = 24e2 # baseline length\nB_VEC = [0, B, 0] # baseline vector\nNU = 90e9 # observing frequency\nRP_CLK_T = 1 / (125.22e6) # clock rate\nOVRO = EarthLocation.of_site('ovro')\n\n\ndef s_hat(alt_list, az_list):\n \"\"\"\n Calculate source direction vectors given an altitude and azimuth list\n :param alt_list: list of altitudes in degrees\n :param az_list: list of azimuths in degrees\n :return: list of direction unit vectors\n :rtype: numpy array\n \"\"\"\n\n alt_list = np.deg2rad(alt_list)\n az_list = np.deg2rad(az_list)\n\n s_hat_list = []\n for i in range(len(alt_list)):\n alt = alt_list[i]\n az = az_list[i]\n s_hat_list.append([np.cos(alt) * np.cos(az), np.cos(alt) * np.sin(az), np.sin(alt)])\n\n return (np.array(s_hat_list))\n\ndef calc_phi_step(ra, dec, start_UTC, t_obs, t_update):\n \"\"\"\n Calculate phase rate updates in units of fringe cycles per clock cycle to be sent to Red Pitaya for each time \\\n interval requested\n :param ra: string of RA of source in HMS\n :param dec: string of Dec of source in DM\n :param start_UTC: string in isot format for beginning of observation\n :param t_obs: length of observation in minutes\n :param t_update: update interval in minutes\n :return: list of phase rates\n :rtype: numpy array\n \"\"\"\n # create an astropy time object with all times to calculate dphi/dt at\n t_start = Time(start_UTC, format='fits', scale='utc')\n t_intervals = np.arange(0, t_obs, t_update) * u.min\n t_steps = t_start + t_intervals\n\n # create a sky coordinates object given source RA and Dec and\n # convert to altaz frame\n src = SkyCoord(ra, dec, unit=(u.hourangle, u.deg))\n altaz_frame = AltAz(obstime=t_steps, location=OVRO)\n altaz = src.transform_to(altaz_frame)\n\n # using the altaz info, generate source direction vectors and use that to\n # calculate the phase rate in rad/s\n s = s_hat(altaz.alt, altaz.az)\n theta = np.arccos(np.dot(B_VEC, s.T) / float(B))\n dtau_dt = B * np.gradient(theta, t_intervals.to(u.s).value) * np.sin(theta) / float(C)\n dphi_dt = 2 * np.pi * NU * dtau_dt\n\n # convert dphi_dt from rad/s to fringe cycles/red pitaya clock cycle\n phi_step_list = dphi_dt * RP_CLK_T / float((2 * np.pi))\n\n phi_step_list = np.array(phi_step_list)\n\n return phi_step_list\n\ndef calc_rp_error(phi_step_list):\n \"\"\"\n Calculate both actual phase rate and phase rate loaded into Red Pitaya in Hz\n :param phi_step_list: list of phase rates in units of fringe cycle per clock cycle\n :return: list of actual phase rates and list of loaded phase rates\n :rtype: numpy array, numpy array\n \"\"\"\n\n actual_phi_rate = phi_step_list / RP_CLK_T\n\n phi_step_list_32b = np.round(phi_step_list * (2 ** 31))\n rp_phi_rate = ( phi_step_list_32b / (2**31) ) / RP_CLK_T\n\n return actual_phi_rate, rp_phi_rate","repo_name":"nitikayad96/SPRITE","sub_path":"red_pitaya_utils.py","file_name":"red_pitaya_utils.py","file_ext":"py","file_size_in_byte":5403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"3527077367","text":"\"\"\"\n This file contains the tests for the API\n\"\"\"\nfrom django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom googletopterms.models import queries, comment\nfrom django.contrib.auth.models import User\n\n\"\"\"\n This class contains the tests for the User API\n Test doesn't work because of the json data format\n\"\"\"\nclass UserTests(APITestCase):\n\n def setUp(self):\n \"\"\"\n Create a user for the tests\n \"\"\"\n url = reverse('register')\n data = {'body':{'username': 'JulianGomez',\n 'password': 'secretPassword'}}\n self.client.post(url, data)\n\n def test_create_user(self):\n \"\"\"\n Ensure we can create a new user object\n \"\"\"\n url = reverse('register')\n data = {'body': {\n 'username': 'johndoe',\n 'password': 'secretPassword'\n }}\n response = self.client.post(url, data)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertTrue(User.objects.filter(username='johndoe').exists())\n \"\"\"\n Ensure we can't create a new user object with\n existing username\n \"\"\"\n data = {'body': {'username': 'JulianGomez',\n 'password': 'secretPassword'}}\n response = self.client.post(url, data)\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n self.assertEqual(response.data['username'][0],\n 'A user with that username already exists.')\n\n def test_login_user(self):\n \"\"\"\n Ensure we can log in with a valid user\n \"\"\"\n url = reverse('login')\n data = {'body': {'username': 'JulianGomez',\n 'password': 'secretPassword'}}\n response = self.client.post(url, data)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data['user'], 'JulianGomez')\n \"\"\"\n Ensure we cannot login with a non-existing user\n \"\"\"\n url = reverse('login')\n data = {\n 'body': {\n 'username': 'johndoe',\n 'password': 'secretPassword'\n }\n }\n response = self.client.post(url, data)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n self.assertEqual(response.data['message'], 'invalid Credentials')\n\n\nclass QueryTest(APITestCase):\n def setUp(self):\n \"\"\"\n Create a user for the tests\n \"\"\"\n url = reverse('register')\n data = {'body': {'username': 'JulianGomez',\n 'password': 'secretPassword'}}\n self.client.post(url, data)\n\n def test_create_query(self):\n \"\"\"\n Ensure we can create a new query object\n \"\"\"\n data = {\n 'body':{\n 'name': 'query1',\n 'description': 'query description',\n 'rawQuery': 'SELECT id, name FROM table_name',\n 'relatedTo': 'table_name',\n 'public': True,\n 'comments': []\n }\n\n }\n url = reverse('query_create', kwargs={\n 'username': 'JulianGomez'})\n response = self.client.post(url, data)\n\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertTrue(queries.objects.filter(name='query1').exists())\n self.assertEqual(response.data['name'], 'query1')\n self.assertEqual(response.data['username'], 'JulianGomez')\n\n def test_get_queries_community(self):\n \"\"\"\n Ensure we can't get a list of queries if database is empty\n \"\"\"\n url = reverse('community_queries')\n response = self.client.get(url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data, [])\n\n data_public = {\n 'body':{\n 'name': 'query1',\n 'description': 'query description',\n 'rawQuery': 'SELECT id, name FROM table_name',\n 'relatedTo': 'table_name',\n 'public': True,\n 'comments': []\n }\n }\n url = reverse('query_create', kwargs={'username': 'JulianGomez'})\n self.client.post(url, data_public)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n data_private = {\n 'body':{\n 'name': 'query2',\n 'description': 'query description2',\n 'rawQuery': 'SELECT id, name FROM table_name',\n 'relatedTo': 'table_name',\n 'public': False,\n 'comments': []\n }\n }\n self.client.post(url, data_private)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n url = reverse('community_queries')\n response = self.client.get(url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(len(response.data), 1)\n self.assertEqual(response.data[0]['name'], 'query1')\n\n data_public_2 = {\n 'body':{\n 'name': 'query3',\n 'description': 'query description3',\n 'rawQuery': 'SELECT id, name FROM table_name',\n 'relatedTo': 'table_name',\n 'public': True,\n 'comments': []\n }\n }\n url = reverse('query_create', kwargs={'username': 'JulianGomez'})\n self.client.post(url, data_public_2)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n url = reverse('community_queries')\n response = self.client.get(url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(len(response.data), 2)\n self.assertEqual(response.data[0]['name'], 'query3')\n\n\nclass CommentsTest(APITestCase):\n def setUp(self):\n \"\"\"\n Create a user for the tests\n \"\"\"\n url = reverse('register')\n data = {'body': {'username': 'JulianGomez',\n 'password': 'secretPassword'}}\n self.client.post(url, data)\n query_data = {\n 'body':{\n 'name': 'query1',\n 'description': 'query description',\n 'rawQuery': 'SELECT id, name FROM table_name',\n 'relatedTo': 'table_name',\n 'public': True,\n 'comments': []\n }\n }\n url = reverse('query_create', kwargs={\n 'username': 'JulianGomez'})\n self.client.post(url, query_data)\n\n def test_create_comment(self):\n \"\"\"\n Ensure we can create a new comment object\n \"\"\"\n comment_data = {\n 'body':{\n 'comment': 'This is a comment',\n 'user': 'JulianGomez'\n }\n }\n url = reverse('query_comment', kwargs={'pk': 1})\n response = self.client.post(url, comment_data)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertTrue(comment.objects.filter(query_id=1).exists())\n data = {\n 'body':{\n \"username\": \"JulianGomez\",\n }\n }\n url = reverse('my_queries', kwargs={'username': 'JulianGomez'})\n response = self.client.get(url, format='json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(len(response.data[0]['comments']), 1)\n self.assertEqual(response.data[0]['comments'][0]['comment'],\n 'This is a comment')\n\n\nclass GoogleApiTest(APITestCase):\n\n def test_top_25_terms_and_rising(self):\n \"\"\"\n Ensure we can get the top 25 terms\n \"\"\"\n url = reverse('top_25_terms')\n data = {'interval': 2, 'table_name': 'top_terms'}\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(len(response.data), 25)\n\n data = {'interval':3, 'table_name': 'top_rising_terms'}\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data[0]['term'], \"duane martin\")\n\n def test_top_25_international_terms(self):\n \"\"\"\n Ensure we can get the top 25 international terms\n \"\"\"\n url = reverse('top_25_international_terms')\n data = {'interval': 2, 'table_name': 'international_top_terms',\n 'country_name': 'Colombia'}\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(len(response.data), 25)\n","repo_name":"JuanEstebanR/veles_reyez","sub_path":"back_end/googletopterms/test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":8760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"3153113390","text":"import pickle\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\n\r\nmax_seq_length = 20\r\n\r\n\r\ndef PreprocessTextsAndHypotheses(tokenizer, texts, hypotheses):\r\n # Convert our list-of-strings data to NumPy padded arrays of integer indices.\r\n text_word_sequences = tokenizer.texts_to_sequences([texts])\r\n hypotheses_word_sequences = tokenizer.texts_to_sequences([hypotheses])\r\n x_text = tf.keras.preprocessing.sequence.pad_sequences(text_word_sequences, maxlen=max_seq_length)\r\n x_hypo = tf.keras.preprocessing.sequence.pad_sequences(hypotheses_word_sequences, maxlen=max_seq_length)\r\n return x_text, x_hypo\r\n\r\n\r\ndef LoadModelAndTokenizer(modelName):\r\n model = keras.models.load_model(modelName)\r\n with open(modelName + ' tokenizer.pickle', 'rb') as handle:\r\n tokenizer = pickle.load(handle)\r\n\r\n return model, tokenizer\r\n","repo_name":"juadHamdan/Recognizing-Textual-Entailment","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"27803845676","text":"#!/usr/bin/env python-sirius\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport matplotlib.gridspec as mpl_gs\nimport matplotlib.cm as cm\n\nimport pyaccel\nfrom pymodels import si\nfrom pymodels.middlelayer.devices import SOFB\nfrom siriuspy.clientconfigdb import ConfigDBClient\nfrom apsuite.commissioning_scripts.calc_orbcorr_mat import OrbRespmat\n\n\ndef get_correctors_strength():\n clt_gbl = ConfigDBClient(config_type='global_config')\n conf = clt_gbl.get_config_value('energy2p963gev_delta_quads_bo_config_A')\n conf = {n: v for n, v, d in conf['pvs']}\n\n vals = []\n for name in sofb.data.CH_NAMES:\n vals.append(conf[name + ':Current-SP'])\n return np.array(vals) * 39.0969 *1e-6\n\n\ndef correct_orbit(mod, irm, bpm, ch, cv, rf):\n respmcalc = OrbRespmat(model, 'SI', dim='6d')\n respmcalc.bpms = bpm\n for i in range(5):\n respmcalc.model = mod\n respmat = respmcalc.get_respm()\n u, s, vh = np.linalg.svd(respmat, full_matrices=False)\n invs = 1/s\n invs[-20:] = 0\n irespmat = vh.T @ np.diag(invs) @ u.T\n\n orb = pyaccel.tracking.find_orbit6(mod, indices=bpm)\n orbx, orby = orb[0], orb[2]\n print(i, np.std(orbx), np.mean(orbx))\n corrs = -irespmat @ np.hstack([orbx, orby])\n chkick = pyaccel.lattice.get_attribute(mod, 'hkick_polynom', ch)\n cvkick = pyaccel.lattice.get_attribute(mod, 'vkick_polynom', cv)\n freq = pyaccel.lattice.get_attribute(mod, 'frequency', rf)\n chkick += corrs[:120]\n cvkick += corrs[120:280]\n freq += corrs[280]\n pyaccel.lattice.set_attribute(mod, 'hkick_polynom', ch, chkick)\n pyaccel.lattice.set_attribute(mod, 'vkick_polynom', cv, cvkick)\n pyaccel.lattice.set_attribute(mod, 'frequency', rf, freq)\n print('')\n\n\ndef add_girder_errorx(mod, girds, girtyp, err):\n for gird, idx in girds.items():\n if not gird.endswith(girtyp):\n continue\n pyaccel.lattice.set_error_misalignment_x(mod, idx, err)\n\n\nsofb = SOFB('SI')\nmodel = si.create_accelerator()\nmodel.cavity_on = True\n# model.radiation_on = True\nrespmcalc = OrbRespmat(model, 'SI', dim='6d')\nbpms = respmcalc.bpms\nchs = respmcalc.ch\ncvs = respmcalc.cv\nrf = pyaccel.lattice.find_indices(model, 'pass_method', 'cavity_pass')\nfreq0 = pyaccel.lattice.get_attribute(model, 'frequency', rf)\n\nrespmat = respmcalc.get_respm()\nu, s, vh = np.linalg.svd(respmat, full_matrices=False)\nirespmat = vh.T @ np.diag(1/s) @ u.T\n\ngirders = respmcalc.fam_data['girder']\ngirs = dict()\nfor i, sub in enumerate(girders['subsection']):\n name = sub + girders['instance'][i]\n girs[name] = girders['index'][i]\ngirders = girs\n\ngird_tp = sorted(set([g[2:] for g in girders.keys()]))\n# gird_tp = ['C12', 'M2', 'C21', 'C41']\n\nconvgird_tp = {\n 'C11': 'B11', 'C12': 'C1', 'C21': 'B21', 'C22': 'C2', 'C31': 'C3',\n 'C32': 'B22', 'C41': 'C4', 'C42': 'B12', 'M1': 'M1', 'M2': 'M2',\n 'BC': 'BC', 'B1B2': 'B1B2', 'B1C': 'B1C', 'B2C': 'B2C'}\n\nresults = dict()\nerrx = 40e-6\nmat = []\nfor gtp in gird_tp:\n res = dict()\n\n add_girder_errorx(model, girders, gtp, errx)\n correct_orbit(model, irespmat, bpms, chs, cvs, rf)\n res['ch'] = np.array(\n pyaccel.lattice.get_attribute(model, 'hkick_polynom', chs))\n res['cv'] = np.array(\n pyaccel.lattice.get_attribute(model, 'vkick_polynom', cvs))\n results[gtp] = res\n mat.append(res['ch'])\n\n add_girder_errorx(model, girders, gtp, 0)\n pyaccel.lattice.set_attribute(model, 'hkick_polynom', chs, 0)\n pyaccel.lattice.set_attribute(model, 'vkick_polynom', cvs, 0)\n pyaccel.lattice.set_attribute(model, 'frequency', rf, freq0)\n\nmat = np.array(mat).T / errx\nu, s, vh = np.linalg.svd(mat, full_matrices=False)\ninvs = 1/s\ninvs[7:] = 0\nimat = vh.T @ np.diag(invs) @ u.T\n\nconfv = get_correctors_strength()\nconfv = sofb.kickch * 1e-6\n\nerrors = imat @ confv\n\ncorrs = []\nrelation = []\nc2 = np.dot(confv, confv)\nfor i in range(mat.shape[1]):\n m = mat[:, i]\n corrs.append(np.dot(confv, m) / np.dot(m, m))\n relation.append(np.dot(confv, m)**2 / np.dot(m, m) / c2)\nfor gtp, err, corr, rel in zip(gird_tp, errors, corrs, relation):\n print('{:5s}: {:-6.1f} {:6.1f} {:4.1f}'.format(\n convgird_tp[gtp], err*1e6, corr*1e6, rel*100))\n\nfit = mat @ errors\n\nf = plt.figure(figsize=(15, 10))\ngs = mpl_gs.GridSpec(1, 1)\ngs.update(\n left=0.10, right=0.97, top=0.97, bottom=0.05, hspace=0.4, wspace=0.25)\nax = plt.subplot(gs[0, 0])\nax.grid(True)\n\n# for gtp, res in results.items():\n# ax.plot(-2*res['ch']*1e6, label=convgird_tp[gtp])\n\nprint('std real', np.std(confv)*1e6)\nprint('std diff', np.std(confv - fit)*1e6)\n\nax.plot(confv*1e6, '-k', label='Before Correction')\nax.plot(fit*1e6, 'o--', label='Correction')\nax.plot((confv - fit)*1e6, label='Predicted After Correction')\nax.legend()\n\n# ##### FFT #####\n# f = plt.figure(figsize=(15, 10))\n# gs = mpl_gs.GridSpec(1, 1)\n# gs.update(\n# left=0.10, right=0.97, top=0.97, bottom=0.05, hspace=0.4, wspace=0.25)\n# ax = plt.subplot(gs[0, 0])\n# ax.grid(True)\n\n# fft = np.fft.rfft(confv)\n# freq = np.fft.rfftfreq(confv.size, d=1/120)\n# ax.plot(freq, np.abs(fft), '-k', label='CH Strength')\n# ax.plot(freq, np.abs(np.fft.rfft(confv - fit)), label='diff')\n# ax.legend()\n\ncorrmat = mat.T @ mat\ndiag = np.diag(corrmat)\ncorrmat = corrmat*corrmat / (diag[:, None] @ diag[None, :])\n\nf = plt.figure(figsize=(15, 10))\ngs = mpl_gs.GridSpec(1, 1)\ngs.update(\n left=0.10, right=0.97, top=0.97, bottom=0.05, hspace=0.4, wspace=0.25)\nax = plt.subplot(gs[0, 0])\nax.grid(True)\ntri = np.tri(corrmat.shape[0], k=0)\nax.plot(tri*corrmat)\nax.legend(gird_tp)\n\nplt.show()\n","repo_name":"fernandohds564/testing-scripts","sub_path":"girders_study.py","file_name":"girders_study.py","file_ext":"py","file_size_in_byte":5618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73336608370","text":"\"\"\" mmServer.shared.lib.messageHandler\n\n This module define various functions which work with messages.\n\"\"\"\nimport datetime\nimport logging\n\nfrom django.utils import timezone\n\nfrom mmServer.shared.lib import rippleInterface\nfrom mmServer.shared.models import *\n\n#############################################################################\n\nlogger = logging.getLogger(\"mmServer\")\n\n#############################################################################\n\ndef check_pending_messages():\n \"\"\" Check any messages with a status of \"pending\".\n\n We ask the Ripple network for the current status of each of \"pending\"\n message, and update the status for any message that has either failed\n or been accepted into the Ripple ledger.\n\n If a message was accepted, the associated conversation will also be\n updated to reflect the current unread message count and the details of\n the latest message.\n \"\"\"\n conversations_to_update = set()\n\n for msg in Message.objects.filter(status=Message.STATUS_PENDING):\n response = rippleInterface.request(\"tx\", transaction=msg.hash,\n binary=False)\n if response == None:\n continue\n\n if response['status'] == \"error\":\n # The Ripple server returned an error. If the error was\n # \"txnNotFound\" and the message is more than 60 seconds old, mark\n # it as failed so we don't continue to check for failed messages.\n cutoff = timezone.now() - datetime.timedelta(seconds=60)\n if response['error'] == \"txnNotFound\" and msg.timestamp < cutoff:\n msg.status = Message.STATUS_FAILED\n msg.error = response['error']\n msg.save()\n continue\n else:\n # Any other error -> try again later.\n continue\n\n if response.get(\"result\", {}).get(\"validated\", False):\n # This message has been validated -> update the status.\n\n trans_result = response['result']['meta']['TransactionResult']\n if trans_result == \"tesSUCCESS\":\n msg.status = Message.STATUS_SENT\n msg.error = None\n else:\n msg.status = Message.STATUS_FAILED\n msg.error = trans_result\n msg.save()\n\n # If the message was sent, update the conversation this message is\n # part of. This updates the unread message count, etc, for the\n # conversation.\n\n if msg.status == Message.STATUS_SENT:\n conversations_to_update.add(msg.conversation)\n\n for conversation in conversations_to_update:\n update_conversation(conversation)\n\n#############################################################################\n\ndef update_conversation(conversation):\n \"\"\" Update a conversation to reflect the current state of its messages.\n\n We update the following fields in the Conversation record to reflect\n the current set of messages associated with that conversation:\n\n last_message\n last_timestamp\n num_unread_1\n num_unread_2\n \"\"\"\n conversation.num_unread_1 = 0\n conversation.num_unread_2 = 0\n\n for message in Message.objects.filter(conversation=conversation):\n if ((conversation.last_timestamp == None) or\n (message.timestamp > conversation.last_timestamp)):\n if conversation.global_id_1 == message.sender_global_id:\n conversation.last_message_1 = message.sender_text\n conversation.last_message_2 = message.recipient_text\n else:\n conversation.last_message_1 = message.recipient_text\n conversation.last_message_2 = message.sender_text\n conversation.last_timestamp = message.timestamp\n\n if message.status == Message.STATUS_SENT:\n if message.sender_global_id == conversation.global_id_1:\n conversation.num_unread_2 = conversation.num_unread_2 + 1\n else:\n conversation.num_unread_1 = conversation.num_unread_1 + 1\n\n conversation.save()\n\n","repo_name":"erikwestra/mm-server","sub_path":"mmServer/shared/lib/messageHandler.py","file_name":"messageHandler.py","file_ext":"py","file_size_in_byte":4200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31233894444","text":"# çizgi bulma algoritması saptama\nimport cv2\nimport numpy as np\n\nimg = cv2.imread(\"3.2 h_line.png\")\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n# kenny kenar yöntemi köşeleri bulmaya yarar\n\nedges = cv2.Canny(gray, 75, 150)\n\n# cv2.HoughLines() çok işlemci yiyor o yüzden tercih edilmiyor\nlines = cv2.HoughLinesP(edges, 1, np.pi / 180, 50,\n maxLineGap=200) # tercih edilen bu ve çizgileri tespit ediyor ve maxlineGap ise çizgi aralıklarını dolduruyor\n# print(lines)\n\nfor i in lines:\n x1, y1, x2, y2 = i[0]\n cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), thickness=2)\n\ncv2.imshow(\"img\", img)\ncv2.imshow(\"Gray\", gray)\ncv2.imshow(\"Edges\", edges)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"malidrsn/OpenCV-Tutorial-w-Basic-Examples","sub_path":"hough_donusum_yontemleri/hough_line_transform.py","file_name":"hough_line_transform.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17273897349","text":"import pandas as pd\n# import matplotlib.pyplot as pl\n# import csv\nimport plotly.graph_objects as g\nimport plotly.express as pe\nimport pickle\n\ncases = 'https://raw.github.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv'\ndeaths = 'https://raw.github.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv'\n# recovered = 'https://raw.github.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Recovered.csv'\n\n\nRENAMED_COLUMNS = {\n 'Province/State': 'province_state',\n 'Country/Region': 'country',\n 'Lat': 'lat',\n 'Long': 'long',\n}\n\n\"\"\" function to read the values from the urls \"\"\"\n\n\ndef df_from_csv(file_name):\n \"\"\" Perform ETL on a Johns Hopkins COVID-19 CSV file, Returning a dataframe \"\"\"\n df = pd.read_csv(file_name)\n df = df.rename(columns=RENAMED_COLUMNS)\n date_cols = df.filter(regex='^\\d+/\\d+/\\d+$').columns\n df = pd.melt(df, id_vars=['province_state', 'country', 'lat', 'long'], value_vars=date_cols, var_name='date',\n value_name='cases')\n # df.to_csv('output.csv', index=False)\n # df.date = pd.to_datetime(df.date, format='%m/%d/%y')\n # df['day'] = (df.date - pd.to_datetime(df.date.iloc[0])).astype('timedelta64[D]')\n # df.day = df.day.apply(lambda day: int(round(day)))\n # print(df[['date', 'cases', 'province_state', 'country', 'lat', 'long']])\n return df[['date', 'cases', 'province_state', 'country', 'lat', 'long']]\n\n\n\"\"\" df_cases is the main dataframe which has all the values \"\"\"\ndf_cases = df_from_csv(cases)\ndf_deaths = df_from_csv(deaths)\ndf_cases['deaths'] = df_deaths['cases']\n# df_final = df_cases.append(df_deaths['cases'])\ndf_cases.to_csv('output.csv', index=False)\n# print(df_final)\n\n\n''' reading the data from output.csv '''\ndata = pd.read_csv('output.csv', parse_dates=['date'])\n# print(data.head())\n\n\n''' recent data '''\nrecent_data = data[data['date'] == data['date'].max()]\n# print(recent_data)\n\n''' max death'''\nmax_death = data[data['deaths'] == data['deaths'].max()].reset_index(drop=True).drop(['lat', 'long'], axis=1)\n# print(max_death)\n\n\n''' total cases and deaths group by counties'''\naffected_countries = recent_data.groupby('country').sum().reset_index()\nfinal = affected_countries.drop(['lat', 'long'], axis=1)\n# print(final)\n\n\n''' with the help of plotly we are showing max cases of each country and provinces '''\nfigure = g.Figure(data=g.Choropleth(\n locations=affected_countries['country'],\n locationmode='country names',\n z=affected_countries['cases'],\n colorscale='reds',\n autocolorscale=True,\n reversescale=False,\n marker_line_color='black',\n marker_line_width=0.5,\n colorbar_title='Confirmed Cases',\n))\n\nfigure.update_layout(\n title_text='Countries affected by Coronavirus (COVID-19)',\n geo=dict(\n showframe=False,\n showcoastlines=True,\n projection_type='equirectangular'\n\n ),\n annotations=[dict(\n x=0.50,\n y=0.2,\n )]\n)\n\nfigure.show()\n\n''' '''\ndata_spreading = data.groupby(['date', 'country', 'deaths']).max().drop(['lat', 'long'], axis=1).reset_index()\ndata_spreading['count'] = data_spreading['cases'].pow(0.1)\ndata_spreading['date'] = pd.to_datetime(data_spreading['date']).dt.strftime('%m/%d/%Y')\n\nfigure_world = pe.scatter_geo(data_spreading,\n locations=data_spreading['country'],\n locationmode='country names',\n color='cases',\n hover_name=\"country\",\n size='count',\n animation_frame=\"date\",\n projection=\"natural earth\",\n title='Spreading of Coronavirus disease (COVID-19) date wise')\n\nfigure_world.show()\n\n\n","repo_name":"mudittripathi/corona_plotly","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3915,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"72575886449","text":"import argparse\nimport pathlib\n\nimport utils_requirements\n\n\"\"\"\nUtilities to manage requirements files.\nNOTE: this should use ONLY the standard library and not import anything else\nbecause this is used for boostrapping with no requirements installed.\n\"\"\"\n\n\ndef gen_dev_requirements():\n description = \"\"\"\n Create or overwrite the `--dev-requirements-file` pip requirements FILE with\n all Python packages found installed in `--site-packages-dir`. Exclude\n package names also listed in the --main-requirements-file pip requirements\n FILE (that are assume to the production requirements and therefore to always\n be present in addition to the development requirements).\n \"\"\"\n parser = argparse.ArgumentParser(description=description)\n\n parser.add_argument(\n \"-s\",\n \"--site-packages-dir\",\n type=pathlib.Path,\n required=True,\n metavar=\"DIR\",\n help='Path to the \"site-packages\" directory where wheels are installed such as lib/python3.6/site-packages',\n )\n parser.add_argument(\n \"-d\",\n \"--dev-requirements-file\",\n type=pathlib.Path,\n metavar=\"FILE\",\n default=\"requirements-dev.txt\",\n help=\"Path to the dev requirements file to update or create.\",\n )\n parser.add_argument(\n \"-r\",\n \"--main-requirements-file\",\n type=pathlib.Path,\n default=\"requirements.txt\",\n metavar=\"FILE\",\n help=\"Path to the main requirements file. Its requirements will be excluded \"\n \"from the generated dev requirements.\",\n )\n args = parser.parse_args()\n\n utils_requirements.lock_dev_requirements(\n dev_requirements_file=args.dev_requirements_file,\n main_requirements_file=args.main_requirements_file,\n site_packages_dir=args.site_packages_dir,\n )\n\n\nif __name__ == \"__main__\":\n gen_dev_requirements()\n","repo_name":"nexB/scancode-toolkit","sub_path":"etc/scripts/gen_requirements_dev.py","file_name":"gen_requirements_dev.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","stars":1846,"dataset":"github-code","pt":"20"} +{"seq_id":"7339595533","text":"import pandas as pd\nimport os\n\npath_data = \"..\" + os.sep + \"static\" + os.sep + \"data\" + os.sep\n\n\ndef get_df_summary():\n total_py_pkgs = 0\n total_npm_pkgs = 0\n total_go_pkgs = 0\n total_rb_pkgs = 0\n graph1_data = []\n\n for root, directories, files in os.walk('..'):\n for nm in files:\n if not nm.startswith('.'):\n df = pd.read_json(os.path.join(root, nm))\n if 'python' in root:\n total_py_pkgs += len(df.columns)\n\n if 'npm' in root:\n total_npm_pkgs += len(df.columns)\n\n if 'go' in root:\n total_go_pkgs += len(df.columns)\n\n if 'ruby' in root:\n total_rb_pkgs += len(df.columns)\n\n if total_py_pkgs > 0:\n graph1_data.append({\"repo\": \"PyPi\", \"totalpkgs\": total_py_pkgs})\n if total_npm_pkgs > 0:\n graph1_data.append({\"repo\": \"NPM\", \"totalpkgs\": total_npm_pkgs})\n if total_rb_pkgs > 0:\n graph1_data.append({\"repo\": \"Gems\", \"totalpkgs\": total_rb_pkgs})\n if total_go_pkgs > 0:\n graph1_data.append({\"repo\": \"GoLang\", \"totalpkgs\": total_go_pkgs})\n\n print(graph1_data)\n\n return graph1_data\n\n\ndef get_df_graph2():\n total_py_files = 0\n total_py_typos = 0\n total_py_urls = 0\n total_py_ips = 0\n total_py_emails = 0\n total_py_vulns = 0\n total_py_vt = 0\n\n total_npm_files = 0\n total_npm_typos = 0\n total_npm_urls = 0\n total_npm_ips = 0\n total_npm_emails = 0\n total_npm_vulns = 0\n total_npm_vt = 0\n\n total_go_files = 0\n total_go_typos = 0\n total_go_urls = 0\n total_go_ips = 0\n total_go_emails = 0\n total_go_vulns = 0\n total_go_vt = 0\n\n total_rb_files = 0\n total_rb_typos = 0\n total_rb_urls = 0\n total_rb_ips = 0\n total_rb_emails = 0\n total_rb_vulns = 0\n total_rb_vt = 0\n\n graph2_data = []\n\n for root, directories, files in os.walk('..'):\n for nm in files:\n if not nm.startswith('.'):\n df = pd.read_json(os.path.join(root, nm), orient='index')\n if 'python' in root:\n if \"hash_files\" in df.columns:\n total_py_files += df[\"hash_files\"][0].\\\n values().__len__() - 1\n if \"typo_urls\" in df.columns:\n total_py_typos += df[\"typo_urls\"][0].values().__len__()\n if \"data_collected\" in df.columns:\n total_py_urls += df[\"data_collected\"][0][\n \"urls\"].__len__()\n total_py_ips += df[\"data_collected\"][0][\n \"ips\"].__len__()\n total_py_emails += df[\"data_collected\"][0][\n \"emails\"].__len__()\n if \"appinspector\" in df.columns and (\n df[\"appinspector\"][0].values() ==\n \"Called Process Error\" or df[\n \"appinspector\"][0].__len__() > 0):\n total_py_vulns += df[\"appinspector\"][0].\\\n values().__len__()\n if \"bandit\" in df.columns and (df[\"bandit\"][0] != \"\"):\n total_py_vulns += df[\"bandit\"][0][\"results\"].\\\n values().__len__()\n if \"virustotal\" in df.columns and \\\n df[\"virustotal\"][0] != \"\":\n total_py_vt += df[\"virustotal\"].__len__()\n\n if 'npm' in root:\n if \"hash_files\" in df.columns:\n total_npm_files += df[\"hash_files\"][0].\\\n values().__len__() - 1\n if \"typo_urls\" in df.columns:\n total_npm_typos += df[\"typo_urls\"][0].\\\n values().__len__()\n if \"data_collected\" in df.columns:\n total_npm_urls += df[\"data_collected\"][0][\n \"urls\"].__len__()\n total_npm_ips += df[\"data_collected\"][0][\n \"ips\"].__len__()\n total_npm_emails += df[\"data_collected\"][0][\n \"emails\"].__len__()\n if \"appinspector\" in df.columns and \\\n (df[\"appinspector\"][0].values() ==\n \"Called Process Error\" or df[\n \"appinspector\"][0].__len__() > 0):\n total_npm_vulns += df[\"appinspector\"][0].values()\\\n .__len__()\n if \"virustotal\" in df.columns and \\\n df[\"virustotal\"][0] != \"\":\n total_npm_vt += df[\"virustotal\"].__len__()\n\n if 'go' in root:\n if \"hash_files\" in df.columns:\n total_go_files += df[\"hash_files\"][0].\\\n values().__len__() - 1\n if \"typo_urls\" in df.columns:\n total_go_typos += df[\"typo_urls\"][0].\\\n values().__len__()\n if \"data_collected\" in df.columns:\n total_go_urls += df[\"data_collected\"][0][\n \"urls\"].__len__()\n total_go_ips += df[\"data_collected\"][0][\n \"ips\"].__len__()\n total_go_emails += df[\"data_collected\"][0][\n \"emails\"].__len__()\n if \"appinspector\" in df.columns and \\\n (df[\"appinspector\"][0].values() ==\n \"Called Process Error\" or df[\n \"appinspector\"][0].__len__() > 0):\n total_go_vulns += df[\"appinspector\"][0].\\\n values().__len__()\n if \"virustotal\" in df.columns and \\\n df[\"virustotal\"][0] != \"\":\n total_go_vt += df[\"virustotal\"].__len__()\n\n if 'ruby' in root:\n if \"hash_files\" in df.columns:\n total_rb_files += df[\"hash_files\"][0].values().__len__() - 1\n if \"typo_urls\" in df.columns:\n total_rb_typos += df[\"typo_urls\"][0].values().__len__()\n if \"data_collected\" in df.columns:\n total_rb_urls += df[\"data_collected\"][0][\n \"urls\"].__len__()\n total_rb_ips += df[\"data_collected\"][0][\n \"ips\"].__len__()\n total_rb_emails += df[\"data_collected\"][0][\n \"emails\"].__len__()\n if \"appinspector\" in df.columns and \\\n (df[\"appinspector\"][0].values() ==\n \"Called Process Error\" or\n df[\"appinspector\"][0].__len__() > 0):\n total_rb_vulns += df[\"appinspector\"][0].\\\n values().__len__()\n if \"virustotal\" in df.columns and \\\n df[\"virustotal\"][0] != \"\":\n total_rb_vt += df[\"virustotal\"].__len__()\n\n graph2_data.append({\"Repo\": \"PyPi\", \"Typos\": total_py_typos,\n \"#Files\": total_py_files, \"IPs\": total_py_urls,\n \"URLs\": total_py_urls, \"Emails\": total_py_emails,\n \"Issues\": total_py_vulns, \"VirusTotal\": total_py_vt})\n graph2_data.append({\"Repo\": \"NPM\", \"Typos\": total_npm_typos,\n \"#Files\": total_npm_files, \"IPs\": total_npm_urls,\n \"URLs\": total_npm_urls, \"Emails\": total_npm_emails,\n \"Issues\": total_npm_vulns, \"VirusTotal\": total_npm_vt})\n graph2_data.append({\"Repo\": \"Ruby\", \"Typos\": total_rb_typos,\n \"#Files\": total_rb_files, \"IPs\": total_rb_urls,\n \"URLs\": total_rb_urls, \"Emails\": total_rb_emails,\n \"Issues\": total_rb_vulns, \"VirusTotal\": total_rb_vt})\n graph2_data.append({\"Repo\": \"Go\", \"Typos\": total_go_typos,\n \"#Files\": total_go_files, \"IPs\": total_go_urls,\n \"URLs\": total_go_urls, \"Emails\": total_go_emails,\n \"Issues\": total_go_vulns, \"VirusTotal\": total_go_vt})\n\n print(graph2_data)\n\n return graph2_data\n","repo_name":"TelefonicaTC2Tech/packagedna","sub_path":"flask_server/main/data_graphs.py","file_name":"data_graphs.py","file_ext":"py","file_size_in_byte":8616,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"20"} +{"seq_id":"4657781119","text":"import time\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass PIDController:\n def __init__(self, kp, ki, kd, dt, setpoint):\n self.kp = kp\n self.ki = ki\n self.kd = kd\n self.dt = dt\n self.setpoint = setpoint\n self.clear()\n\n def clear(self):\n self.last_error = 0\n self.derivative = 0\n self.last_time = None\n self.integral = 0\n self.errors = []\n self.times = []\n self.outputs = []\n\n def update(self, process_variable):\n # Calculate time since last update\n now = time.time()\n if self.last_time is None:\n self.last_time = now\n return 0.0\n dt = now - self.last_time\n\n # Calculate error\n error = self.setpoint - process_variable\n\n # Calculate derivative term\n self.derivative = (error - self.last_error) / dt if dt > 0 else 0.0\n\n # Calculate integral term\n self.integral += error * dt\n\n\n # Calculate output\n output = self.kp * error + self.ki * self.integral + self.kd * self.derivative\n\n # Save error, time, and output for plotting\n self.errors.append(error)\n self.times.append(now)\n self.outputs.append(output)\n\n # Update last error and time\n self.last_error = error\n self.last_time = now\n\n return output\n\n def plot(self):\n plt.subplot(2, 1, 1)\n plt.plot(self.times, self.setpoint * np.ones_like(self.times), 'k--', label='Setpoint')\n plt.plot(self.times, self.outputs, label='Output')\n plt.ylabel('Output')\n plt.legend(loc='best')\n\n plt.subplot(2, 1, 2)\n plt.plot(self.times, self.errors, label='Error')\n plt.ylabel('Error')\n plt.legend(loc='best')\n plt.xlabel('Time (sec)')\n plt.show()\n\n\npid = PIDController(kp=0.003, ki=0.5, kd=0.01, dt=0.01, setpoint=0.0)\nprocess_variable = 10.0\n\nfor i in range(10000):\n output = pid.update(process_variable)\n process_variable += output\n time.sleep(pid.dt)\n\npid.plot()\n","repo_name":"PyroSage/Trainee","sub_path":"PPC/Checkpoint_3/PID.py","file_name":"PID.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"41466285829","text":"\"\"\"flow 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\nfrom app import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n #auth\n path('', views.home,name='home'),\n path('signup/', views.signupuser,name='signupuser'),\n path('login/', views.loginuser,name='loginuser'),\n path('logout/', views.logoutuser,name='logoutuser'),\n #post\n path('post/', views.post,name='post'),\n path('/', views.expandpost,name='expandpost'),\n #own\n path('profile/', views.userprofile,name='userprofile'),\n path('save/', views.savepost,name='savedpost'),\n path('post/',views.viewpost,name='viewpost'),\n path('post//unpost',views.unpost,name='unpost'),\n path('post//makepost',views.makepost,name='makepost'),\n path('post//deletepost',views.deletepost,name='deletepost'),\n path('mypost//',views.mypost,name='mypost'),\n\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)","repo_name":"utkarsh-777/Flow","sub_path":"flow/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"27691567770","text":"# -*- encoding: utf-8 -*-\r\n# @Time: 2022/03/31 11:19\r\n# @Author: librah\r\n# @Description: L2A ABR algorithm(Online learning for low-latency adaptive streaming)\r\n# @File: l2a.py\r\n# @Version: 1.0\r\n\r\nimport numpy as np\r\nimport math\r\n\r\nfrom config import Env_Config\r\nfrom algorithms.abr import ABR_Solver\r\n\r\nclass L2A_Solver(ABR_Solver):\r\n def __init__(self):\r\n # General\r\n super(L2A_Solver, self).__init__()\r\n \r\n # L2A\r\n self.lastQuality = 0\r\n self.currentPlaybakcRate = 1.0\r\n self.prev_w = [0] * len(self.bitrates)\r\n self.w = [0] * len(self.bitrates)\r\n self.horizon = 4\r\n self.v1 = math.pow(self.horizon, 0.99)\r\n self.alpha = max(math.pow(self.horizon, 1), self.v1 * math.sqrt(self.horizon))\r\n self.Q = self.v1\r\n self.react = 2\r\n\r\n # For Dash playback rate\r\n self.LIVE_DELAY = 1.\r\n self.MIN_PLAYBACK_RATE_CHANGE = 0.02\r\n self.LIVE_CATCHUP_PLAYBACK_RATE = 0.1\r\n \r\n def reset(self):\r\n \"\"\"\r\n Description: Reset the L2A Solver\r\n Args: None\r\n Return: None\r\n \"\"\"\r\n self.tp_history = []\r\n self.latency_history = []\r\n self.prev_w = [0] * len(self.bitrates)\r\n self.w = [0] * len(self.bitrates)\r\n self.currentPlaybakcRate = 1.0\r\n self.v1 = math.pow(self.horizon, 0.99)\r\n self.alpha = max(math.pow(self.horizon, 1), self.v1 * math.sqrt(self.horizon))\r\n self.Q = self.v1\r\n \r\n def adjust_rate(self):\r\n \"\"\"\r\n Description: Adjust the quality value and set prev_w\r\n Args: None\r\n Return: None\r\n \"\"\"\r\n lastThroughput = self.harmonic_prediction()\r\n self.lastQuality = self.choose_rate(lastThroughput)\r\n self.prev_w[self.lastQuality] = 1\r\n \r\n def solve(self, buffer_length, curr_latency, player_state):\r\n # First of all, get speed\r\n ## DASH default playbac rate adaption\r\n speed, speed_idx = self.dash_playback_rate(curr_latency, buffer_length, player_state, self.currentPlaybakcRate)\r\n\r\n self.currentPlaybakcRate = speed\r\n\r\n # Get bitrate\r\n diff1 = []\r\n lastThroughput = self.harmonic_prediction()\r\n lastSegmentDuration = self.seg_duration / Env_Config.ms_in_s\r\n V = lastSegmentDuration\r\n sign = 1\r\n for i in range(len(self.bitrates)):\r\n if self.currentPlaybakcRate * self.bitrates[i] / Env_Config.kb_in_mb > lastThroughput:\r\n # In this case buffer would deplete, leading to a stall, which increases latency and thus the particular probability of selsection of bitrate[i] should be decreased.\r\n sign = -1\r\n # The objective of L2A is to minimize the overall latency=request-response time + buffer length after download+ potential stalling (if buffer less than chunk downlad time)\r\n self.w[i] = self.prev_w[i] + sign * (V /(2 * self.alpha)) * (self.Q + self.v1) * (self.currentPlaybakcRate * self.bitrates[i] / Env_Config.kb_in_mb / lastThroughput) #Lagrangian descent\r\n \r\n temp = [0] * len(self.bitrates)\r\n for i in range(len(self.bitrates)):\r\n temp[i] = abs(self.bitrates[i] - np.dot(self.w, self.bitrates))\r\n \r\n quality = temp.index(min(temp))\r\n # We employ a cautious -stepwise- ascent\r\n if quality > self.lastQuality:\r\n if self.bitrates[self.lastQuality + 1] / Env_Config.kb_in_mb <= lastThroughput:\r\n quality = self.lastQuality + 1\r\n\r\n # Provision against bitrate over-estimation, by re-calibrating the Lagrangian multiplier Q, to be taken into account for the next chunk\r\n if self.bitrates[quality] / Env_Config.kb_in_mb >= lastThroughput:\r\n self.Q = self.react * max(self.v1, self.Q)\r\n self.lastQuality = quality\r\n\r\n print(\"Best reward: quality--{}, speed--{}\".format(self.bitrates[quality], self.speeds[speed_idx]))\r\n\r\n return quality, speed_idx","repo_name":"Leventseleveil/Steamlet","sub_path":"Simulator/algorithms/l2a.py","file_name":"l2a.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7452352266","text":"import numerapi\nimport click\nimport os\n#from final_utils import reconocer_tournamet\nimport numpy as np\n\n\ndef make_submission(name_account ,account, resumen_dict, tournament,PATH):\n #list of targets\n\n for target, info in resumen_dict.items():\n print(info)\n #get csv file\n \n submission, status, PATH = info['root'], info['status'], PATH\n \n name = f'{name_account} prediccion, file: {submission}'\n n_tournamet = tournament[target]\n \n \n if (status == 'waiting') or (status == 'fail'):\n print(f'uploading {name} \\n')\n try:\n #trata de subir la prediccion\n submission_id = account.upload_predictions(file_path = f'{PATH}{submission}_submission_lgbm.csv', tournament=n_tournamet)\n resumen = account.submission_status(submission_id)\n status = 'ok'\n print(resumen)\n except:\n status = 'fail'\n resumen_dict[target]['status'] = status\n resumen_dict[target]['account'] = name_account\n resumen_dict[target]['resumen'] = resumen\n \n #escribe el status de el submission \n \n # check submission status\n np.save(PATH, resumen_dict)\n\n return f'{name_account}, Done!' \n\n\n@click.command()\n@click.argument('n_round')\n\n\ndef main(n_round):\n\n accounts = {'LAGERTHA' : {'public_id' : 'GSMVUEGEEGMCU2LRXB6G4NR4QOXDNHBF',\n 'secret_key': 'QT6WBGGKWD4TADJK4IKMK3BU3XKC3FBC5AKCHLBYKKV5RF2BWWAIUU3YPTS57JUW',\n 'PATH': f'../submission/round {n_round}/RF&LG/resumen_info.npy'} \n }\n \n ##list of targets\n tournament = {'target_bernie':1, 'target_elizabeth':2, \n 'target_jordan':3, 'target_ken':4, 'target_charles':5, 'target_frank':6 ,'target_hillary': 7}\n\n for name, acnt in accounts.items():\n \n current_acnt = numerapi.NumerAPI(acnt['public_id'], acnt['secret_key'])\n resumen_dict = np.load(acnt['PATH']).item()\n # upload predictions\n resumen = make_submission( name, current_acnt, resumen_dict, tournament,acnt['PATH'])\n print(resumen)\n \n return 'Done!'\n \n\nif __name__ == '__main__':\n main()","repo_name":"rsanahi/Numerai","sub_path":"upload_submission.py","file_name":"upload_submission.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"26970631718","text":"import sys; sys.stdin = open('text1.txt', 'r')\n\n# memory exceed\n\n# from collections import deque\n\n# def bfs():\n# deq = deque()\n# deq.append(1)\n# while deq:\n# x = deq.popleft()\n# for i in range(2, N + 1):\n# if arr[x][i] and parent[i] == 0:\n# deq.append(i)\n# parent[i] = x\n\n\n\n# for tc in range(1, int(input()) + 1):\n# N = int(input())\n# arr = [[0] * (N + 1) for _ in range(N + 1)]\n# for _ in range(N - 1):\n# x, y = map(int, input().split())\n# arr[x][y] = 1\n# arr[y][x] = 1\n# parent = [0] * (N + 1)\n\n# bfs()\n# for i in range(2, len(parent)):\n# print(parent[i])\n\n\n# time error\n\n# from collections import defaultdict\n\n# def bfs():\n# s = [1]\n# for x, y in arr:\n# if x == 1:\n# dic[1].add(y)\n# elif y == 1:\n# dic[1].add(x)\n\n# while s:\n# x = s.pop()\n# x_lst = dic.get(x)\n# for i in x_lst:\n# if parents[i] == 0:\n# for p, q in arr:\n# if p == i:\n# dic[i].add(q)\n# elif q == i:\n# dic[i].add(p)\n# parents[i] = x\n# s.append(i)\n\n\n\n# for tc in range(1, int(input()) + 1):\n# N = int(input())\n# arr = [list(map(int, input().split())) for _ in range(N - 1)]\n# dic = defaultdict(set)\n# parents = [0] * (N + 1)\n \n# bfs()\n# for i in range(2, len(parents)):\n# print(parents[i])\n\n\n\n# solve3\n\n# from collections import defaultdict, deque\n\n# for tc in range(1, int(input()) + 1):\n# N = int(input())\n# dic = defaultdict(list)\n# for _ in range(N - 1):\n# x, y = map(int, input().split())\n# dic[x].append(y)\n# dic[y].append(x)\n# parents = [0] * (N + 1)\n\n# deq = deque([1])\n# parents[1] = -1\n# while deq:\n# x = deq.popleft()\n# for y in dic.get(x):\n# if parents[y] == 0:\n# parents[y] = x\n# deq.append(y)\n \n# for i in range(2, len(parents)):\n# print(parents[i])\n\n\n\n# sys.readline\n\nfrom collections import defaultdict, deque\nimport sys\n\ninput = sys.stdin.readline\n\nfor tc in range(1, int(input()) + 1):\n N = int(input())\n dic = defaultdict(list)\n for _ in range(N - 1):\n x, y = map(int, input().split())\n dic[x].append(y)\n dic[y].append(x)\n parents = [0] * (N + 1)\n\n deq = deque([1])\n parents[1] = -1\n while deq:\n x = deq.popleft()\n for y in dic.get(x):\n if parents[y] == 0:\n parents[y] = x\n deq.append(y)\n \n for i in range(2, len(parents)):\n print(parents[i])","repo_name":"titiman1013/Algorithm","sub_path":"21.01.15/BOJ_11725.py","file_name":"BOJ_11725.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"71098767410","text":"class Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n n = len(arr) # Size of the array\n\n # Edge cases:\n\n# if arr[0] > arr[1]:\n# return 0\n# if arr[n - 1] > arr[n - 2]:\n# return n - 1\n\n low = 1\n high = n - 2\n while low <=high:\n mid = (low + high) // 2\n\n # If arr[mid] is the peak:\n if arr[mid - 1] < arr[mid] and mid-1>=0 and arr[mid] > arr[mid + 1] and mid+1 arr[mid - 1]:\n low = mid + 1\n\n # If we are in the right:\n # Or, arr[mid] is a common point:\n else:\n high = mid - 1\n\n","repo_name":"SaiGanesh21/My-leetcode-solutions","sub_path":"0852-peak-index-in-a-mountain-array/0852-peak-index-in-a-mountain-array.py","file_name":"0852-peak-index-in-a-mountain-array.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"22966827564","text":"from detect import *\r\nfrom record import *\r\nfrom database import *\r\n\r\n\r\nif __name__==\"__main__\":\r\n\tprint(\"1.Create Database\")\r\n\tprint(\"2.Register New User\")\r\n\tprint(\"3.Detect Face\")\r\n\tprint(\"4. Press 0 to Quit\")\r\n\twhile True:\r\n\t\toption=int(input(\"Enter Choice:\").strip())\r\n\t\tif option==1:\r\n\t\t\tcreate_required()\r\n\t\telif option==2:\r\n\t\t\tregister()\r\n\t\telif option==3:\r\n\t\t\tdetect_face()\r\n\t\telif option==0:\r\n\t\t\texit(0)\r\n","repo_name":"Ruithlzz09/FACE-RECOGNITION","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17560562578","text":"import json\nimport os\nimport unittest\nfrom unittest import mock\n\nimport datetime as dt\n\nimport backtrader as bt\nimport ccxt\n\nimport livetrading\nfrom cryptotrader.persistence.persistence import Persistence\nfrom cryptotrader.persistence.persistence_factory import PersistenceFactory\nfrom cryptotrader.persistence.persistence_type import PersistenceType\n\nfrom definitions import ROOT_PATH\n\n\nclass TestTrailingStopLossRestore(unittest.TestCase):\n\n def setUp(self):\n self.param_file_path_prefix = 'test/serialization/'\n self.test_folder_prefix = os.path.join(ROOT_PATH, 'test/serialization/')\n\n def test_previousPsarStopLoss_fs(self):\n self.previousPsarStopLossUsed_test(PersistenceType.FS, PersistenceType.FS)\n\n def test_previousPsarStopLossUsed_gcloud_storage(self):\n self.previousPsarStopLossUsed_test(PersistenceType.GOOGLE_CLOUD_STORAGE, PersistenceType.GOOGLE_FIRESTORE)\n\n def previousPsarStopLossUsed_test(self, persistence_type, trade_setup_persistence_type):\n trade_setup_path = Persistence.get_path('binance', 'bnb/usdt')\n setup_name = 'backtestBNBPsarSL'\n trade_setup_persistence = PersistenceFactory.get_persistance(trade_setup_persistence_type,\n trade_setup_path,\n name=setup_name,\n root_path=ROOT_PATH)\n\n iteration = 0\n call_count = 0\n last_iteration = 0\n last_stop_price = None\n\n with open(self.test_folder_prefix + 'ccxt_order_result/limit/limit_buy.json', 'r') as f:\n buy_order_result = json.load(f)\n\n with open(self.test_folder_prefix + 'ccxt_order_result/limit/limit_buy_fetch_order.json', 'r') as f:\n limit_buy_fetch_order_result = json.load(f)\n\n with open(self.test_folder_prefix + 'ccxt_order_result/limit/limit_buy_fetch_order_filled.json', 'r') as f:\n limit_buy_fetch_order_filled_result = json.load(f)\n\n with open(self.test_folder_prefix + 'ccxt_order_result/stop_limit/sl_fetch_order.json', 'r') as f:\n stop_limit_sell_fetch_order_result = json.load(f)\n\n with open(self.test_folder_prefix + 'ccxt_order_result/stop_limit/sl_fill_order.json', 'r') as f:\n stop_limit_sell_fill_order_result = json.load(f)\n\n with open(self.test_folder_prefix + 'ccxt_order_result/cancel.json', 'r') as f:\n cancel_order_result = json.load(f)\n\n def binance_create_order(*args, **kwargs):\n nonlocal last_stop_price\n # return initially the buy order and later the stop-limit-sell order\n if kwargs['type'] == 'limit' and kwargs['side'] == 'buy':\n return buy_order_result\n if kwargs['type'] == 'STOP_LOSS_LIMIT' and kwargs['side'] == 'sell':\n last_stop_price = kwargs['price']\n stop_limit_sell_fetch_order_result['price'] = last_stop_price\n return stop_limit_sell_fetch_order_result\n return None\n\n def binance_fetch_order(*args, **kwargs):\n nonlocal iteration\n nonlocal call_count\n nonlocal last_iteration\n nonlocal last_stop_price\n # call_count is 1-based\n call_count = (call_count + 1) if last_iteration == iteration else 1\n # 1. fetch_order in deserialize() (except on 0'th iteration where there is no deserialization)\n # 2. fetch_order is from before next()\n last_iteration = iteration\n print(iteration)\n order_id = args[0]\n if iteration == 8 and order_id == '87813927' and call_count >= 2:\n return limit_buy_fetch_order_filled_result\n if 8 <= iteration < 20 and order_id == '97799440':\n # call_count == 5 ?\n stop_limit_sell_fetch_order_result['price'] = last_stop_price\n return stop_limit_sell_fetch_order_result\n if iteration == 20 and order_id == '97799440':\n stop_limit_sell_fill_order_result['price'] = last_stop_price\n return stop_limit_sell_fill_order_result\n return limit_buy_fetch_order_result\n\n def binance_cancel_order(*args, **kwargs):\n order_id = args[0]\n if iteration >= 8 and order_id == '97799440':\n return cancel_order_result\n return None\n\n abs_param_file = os.path.join(ROOT_PATH, 'test/backtestBNBPsarSL.json')\n\n cs_persistence = self.initialize_test_data(abs_param_file, persistence_type, trade_setup_persistence)\n\n with mock.patch.object(ccxt.binance, 'cancel_order', side_effect=binance_cancel_order):\n with mock.patch.object(ccxt.binance, 'create_order', side_effect=binance_create_order):\n with mock.patch.object(ccxt.binance, 'fetch_order', side_effect=binance_fetch_order):\n finished = False\n iteration_index = 0\n while not finished:\n last_iteration = iteration\n iteration = iteration_index\n\n livetrading.main(trade_setup_path, setup_name, trade_setup_persistence_type)\n\n trade_setup = self.set_fromdate_for_iteration(trade_setup_persistence)\n finished = trade_setup.get('event_stop')\n\n assert iteration <= 21\n candle_state, path = cs_persistence.get_last_candle_state()\n if iteration == 0:\n assert candle_state.get('ohlc') == {\n \"open\": 6.7299,\n \"high\": 6.7299,\n \"low\": 6.681,\n \"close\": 6.681,\n \"volume\": 35286.44\n }, 'The testing environment didn\\'t return the correct ohlc value.'\n assert candle_state.get('time') == '2019-01-28T04:15:00'\n assert candle_state.get('psar') == 6.907896\n assert candle_state.get('buy_order') is not None\n assert candle_state.get('sar') is not None\n assert candle_state.get('sell_order') is None\n elif iteration == 1:\n assert candle_state.get('ohlc') == {\n \"open\": 6.6872,\n \"high\": 6.6872,\n \"low\": 6.665,\n \"close\": 6.6703,\n \"volume\": 29960.3\n }, 'The testing environment didn\\'t return the correct ohlc value.'\n assert candle_state.get('time') == '2019-01-28T04:30:00'\n assert candle_state.get('psar') == 6.8814853056\n assert candle_state.get('buy_order') is not None\n assert candle_state.get('sar') is not None\n assert candle_state.get('sell_order') is None\n elif iteration == 7:\n assert candle_state.get('ohlc') == {\n \"open\": 6.5028,\n \"high\": 6.5184,\n \"low\": 6.3723,\n \"close\": 6.4399,\n \"volume\": 138693.53\n }, 'The testing environment didn\\'t return the correct ohlc value.'\n assert candle_state.get('time') == '2019-01-28T06:00:00'\n assert candle_state.get('psar') == 6.63879136\n assert candle_state.get('buy_order') is not None\n assert candle_state.get('sar') is not None\n assert candle_state.get('sell_order') is None\n elif iteration == 8:\n assert candle_state.get('ohlc') == {\n \"open\": 6.4399,\n \"high\": 6.5562,\n \"low\": 6.426,\n \"close\": 6.5147,\n \"volume\": 49548.23\n }, 'The testing environment didn\\'t return the correct ohlc value.'\n assert candle_state.get('time') == '2019-01-28T06:15:00'\n assert candle_state.get('psar') == 6.5787\n assert candle_state.get('buy_order') is not None\n assert candle_state.get('sar') is not None\n so = candle_state.get('sell_order')\n assert so is not None\n assert so[\"symbol\"] == 'BNB/USDT'\n assert so[\"type\"] == 'stop_loss_limit'\n assert so[\"side\"] == 'sell'\n assert so[\"price\"] == 6.3100000000000005\n assert so[\"amount\"] == 10.0\n elif iteration == 19:\n assert candle_state.get('ohlc') == {\n \"open\": 6.6506,\n \"high\": 6.6509,\n \"low\": 6.6244,\n \"close\": 6.6456,\n \"volume\": 16550.96\n }, 'The testing environment didn\\'t return the correct ohlc value.'\n assert candle_state.get('time') == '2019-01-28T09:00:00'\n assert candle_state.get('psar') == 6.77766888\n assert candle_state.get('buy_order') is not None\n assert candle_state.get('sar') is not None\n so = candle_state.get('sell_order')\n assert so is not None\n assert so[\"symbol\"] == 'BNB/USDT'\n assert so[\"type\"] == 'stop_loss_limit'\n assert so[\"side\"] == 'sell'\n assert so[\"price\"] == 6.680456\n assert so[\"amount\"] == 10.0\n\n iteration_index += 1\n\n def set_fromdate_for_iteration(self, trade_setup_persistence):\n trade_setup = trade_setup_persistence.get_setup()\n fromdate = dt.datetime(\n trade_setup['fromdate']['year'],\n trade_setup['fromdate']['month'],\n trade_setup['fromdate']['day'],\n trade_setup['fromdate']['hour'],\n trade_setup['fromdate']['minute'])\n # This moves the fromdate forward depending on the timeframe\n # e.g. for the 15min timeframes: {'minutes': 15}\n fromdate = fromdate + bt.datetime.timedelta(**{\n trade_setup['timeframe']: trade_setup['compression']\n })\n ts_from = {}\n ts_from['year'] = fromdate.year\n ts_from['month'] = fromdate.month\n ts_from['day'] = fromdate.day\n ts_from['hour'] = fromdate.hour\n ts_from['minute'] = fromdate.minute\n trade_setup_persistence.update_setup({'fromdate': ts_from})\n return trade_setup_persistence.get_setup()\n\n def initialize_test_data(self, abs_param_file, persistence_type, trade_setup_persistence):\n with open(abs_param_file, 'r') as f:\n prev_data = json.load(f)\n\n trade_parameter = dict(exchange=prev_data['exchange'],\n pair=prev_data['symbol'],\n year=prev_data['fromdate']['year'],\n month=prev_data['fromdate']['month'],\n day=prev_data['fromdate']['day'],\n trade_id=prev_data['name'])\n cs_persistence = PersistenceFactory.get_cs_persistance(persistence_type,\n **trade_parameter,\n root_path=ROOT_PATH)\n cs_persistence.delete_trade_folder()\n\n trade_setup_persistence.delete_setup()\n prev_data['event_stop'] = False\n prev_data['candle_state_persistence_type'] = persistence_type.value\n\n\n # trade_setup_persistence.update_setup({'candle_state_persistence_type': persistence_type.value})\n trade_setup_persistence.save_setup(prev_data)\n\n return cs_persistence\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"sandroboehme/cryptotrader","sub_path":"test/serialization/test_trailing_stop_loss_restore.py","file_name":"test_trailing_stop_loss_restore.py","file_ext":"py","file_size_in_byte":12722,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"13448757646","text":"import sys\n \nn = int(sys.stdin.readline().rstrip())\n \nsequence = list(map(int, sys.stdin.readline().rstrip().split()))\n \ndef prev_permutation(sequence):\n i = len(sequence) - 1\n\n # sequence[i-1] > sequence[i]인 부분을 찾음 => i-1이 바꿔지게 될 위치임.\n while i > 0 and sequence[i-1] < sequence[i]:\n i = i - 1\n \n if i == 0:\n return None\n\n swap_pos = i-1\n j = len(sequence) - 1\n # 오른쪽에서 시작했을 때, 바꿔지게 될 요소보다 작은 수들중 처음 나오는 요소가\n # 바뀌어지게 된다.\n while j > 0 and sequence[swap_pos] <= sequence[j]:\n j = j - 1\n \n sequence[swap_pos], sequence[j] = sequence[j], sequence[swap_pos]\n\n # 바뀌는 점 이후는 내림차순이 되어야 함\n # 위 while문을 보면 알겠지만.. 바뀌는 위치 기준으로 오른쪽은 오름차순이 되어 있음.\n # 따라서, 그냥 뒤집어주면 된다.\n sequence = sequence[:i] + sequence[i:][::-1] \n return sequence\n \n \np = prev_permutation(sequence)\nif p == None:\n print(-1)\nelse:\n print(*p)\n","repo_name":"nbalance97/BOJ","sub_path":"구현/[ 10973 ] [ 순열 ] 이전 순열.py","file_name":"[ 10973 ] [ 순열 ] 이전 순열.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"25351593385","text":"import os\nfrom typing import Any, List, Sequence, Dict\n\nimport disnake\nfrom disnake import Option\nfrom disnake.ext import commands\nfrom disnake.ext.commands import slash_core, InvokableSlashCommand\n\nimport config\n\n\nclass OnLoadHook:\n def __init__(self, func):\n self.func = func\n\n def __call__(self, *args, **kwargs):\n self.func(*args, **kwargs)\n\n\nclass DorsDiscord(commands.Bot):\n def __init__(self, **options: Any):\n super().__init__(**options)\n\n self.plugins = {}\n\n modules = []\n whitelistonly = False\n for module in os.listdir(os.path.dirname(\"modules/\")):\n if module == '__init__.py' or module[-3:] != '.py':\n continue\n module = module[:-3]\n modules.append(module)\n if module in config.whitelistonly_modules:\n whitelistonly = True\n\n self.slash_command()\n\n if whitelistonly:\n for module in config.whitelistonly_modules:\n self.load_module(module)\n else:\n for module in modules:\n if module in config.disabled_modules:\n continue\n self.load_module(module)\n\n def load_module(self, module: str):\n print(\"Loading\", module)\n themodule = __import__(\"modules.\" + module, locals(), globals())\n themodule = getattr(themodule, module)\n\n self.plugins[module] = themodule\n\n funcs = [f for _, f in themodule.__dict__.items() if callable(f)]\n for func in funcs:\n if isinstance(func, InvokableSlashCommand):\n self.add_slash_command(func)\n elif isinstance(func, OnLoadHook):\n func.func(self)\n\n\nslash_command = slash_core.slash_command\n\n\ndef on_load():\n def decorator(func):\n return OnLoadHook(func)\n\n return decorator\n","repo_name":"Polsaker/dors-discord","sub_path":"dors.py","file_name":"dors.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"30512856033","text":"#!/usr/bin/env python\r\nimport json\r\nfrom pprint import pprint\r\nfrom io import BytesIO\r\nfrom PIL import Image\r\nfrom base64 import b64encode\r\n\r\nfrom skimage.io import imread\r\nfrom skimage.transform import resize, rescale\r\nimport numpy as np\r\nfrom marking import load_marking, organize_by_classes\r\n\r\n\r\ndef get_sign(filename, bbox):\r\n full_img = imread(\"../global_data/Traffic_signs/RTSD/imgs/\" + filename)\r\n x, y, w, h = bbox[\"x\"], bbox[\"y\"], bbox[\"w\"],bbox[\"h\"]\r\n m, n, _ = full_img.shape\r\n\r\n cropped = full_img[max(y, 0) : min(y+h, m), max(x, 0) : min(x+w, n)]\r\n resized = (resize(cropped, (48,48,3)) * 255).astype(np.uint8)\r\n return resized\r\n\r\n\r\ndef img_to_base64(img):\r\n stream = BytesIO()\r\n Image.fromarray(img).save(stream, format='PNG')\r\n stream.seek(0)\r\n return b64encode(stream.getvalue()).decode('utf-8')\r\n\r\n\r\ndef get_stats(prefix):\r\n path = '../global_data/Traffic_signs/RTSD'\r\n stats = {}\r\n for phase in ['train', 'test']:\r\n filename = \"{path}/{prefix}_{phase}.json\".format(**locals())\r\n with open(filename) as f:\r\n marking = json.load(f)\r\n\r\n for class_name in marking:\r\n stats.setdefault(class_name, {})\r\n stats[class_name].setdefault(phase, {})\r\n stats[class_name][phase]['imgs'] = len(marking[class_name])\r\n if phase == 'test':\r\n stats[class_name]['filename'] = marking[class_name][0]['pict_name']\r\n stats[class_name]['bbox'] = marking[class_name][0]\r\n # print(marking[class_name][0]['pict_name'])\r\n\r\n id_set = set()\r\n for image in marking[class_name]:\r\n id_set.add(image['sign_id'])\r\n stats[class_name][phase]['phys'] = len(id_set)\r\n return stats\r\n\r\nimport sys\r\ndef print_stats(stats, fhandle=None):\r\n old_out = sys.stdout\r\n if fhandle is not None:\r\n sys.stdout = fhandle\r\n\r\n content = \"{:10}{:>15}{:>15}{:>15}{:>15}\".format(\r\n 'class', 'train_imgs', 'train_phys', 'test_imgs', 'test_phys')\r\n\r\n print(content)\r\n for class_ in sorted(stats.items(), key=lambda x: x[1]['train']['imgs'], reverse=True):\r\n class_name = class_[0]\r\n train_imgs = stats[class_name]['train']['imgs']\r\n test_imgs = stats[class_name]['test']['imgs']\r\n train_phys = stats[class_name]['train']['phys']\r\n test_phys = stats[class_name]['test']['phys']\r\n\r\n content = \"{class_name:10}{train_imgs:15}{train_phys:15}{test_imgs:15}{test_phys:15}\".format(**locals())\r\n print(content)\r\n\r\n if fhandle is not None:\r\n sys.stdout = old_out\r\n\r\n\r\n\r\n\r\nfrom os import listdir\r\n\r\ndef pictogram(class_name):\r\n pict_name = class_name + \".png\"\r\n directory = \"../global_data/Traffic_signs/RTSD/pictograms/\"\r\n if pict_name in listdir(directory):\r\n return (rescale(imread(directory + pict_name), 0.5) * 255).astype(np.uint8)\r\n else:\r\n for pict_name in reversed(sorted(listdir(directory))):\r\n if pict_name.split('.')[0] in class_name and \\\r\n (\"n\" in class_name or \"r\" in class_name or \"3_4_1\" in class_name):\r\n return (rescale(imread(directory + pict_name), 0.5) * 255).astype(np.uint8)\r\n return np.ones((32, 32, 3)).astype(np.uint8) * 255\r\n\r\n\r\n\r\nstyle = \"\"\"\r\n\"\"\"\r\n\r\n\r\ndef write_header(fhandle):\r\n print('', file=fhandle)\r\n print(style, file=fhandle)\r\n header = '\\\r\n '\r\n print(header, file=fhandle)\r\n\r\ndef write_marking_stats(class_stats, prefix='', write_path=''):\r\n with open(\"{write_path}/{prefix}_stats.html\".format(**locals()), 'w') as fhandle:\r\n write_header(fhandle)\r\n\r\n names = sorted(class_stats, reverse=True, key=lambda x: (\r\n class_stats[x]['train']['imgs'], class_stats[x]['train']['phys'],\r\n class_stats[x]['test']['imgs'], class_stats[x]['test']['phys']))\r\n for class_name in names:\r\n train_imgs = class_stats[class_name]['train']['imgs']\r\n train_phys = class_stats[class_name]['train'][\"phys\"]\r\n test_imgs = class_stats[class_name]['test']['imgs']\r\n test_phys = class_stats[class_name]['test'][\"phys\"]\r\n filename = class_stats[class_name][\"filename\"]\r\n bbox = class_stats[class_name][\"bbox\"]\r\n img = img_to_base64(get_sign(filename, bbox))\r\n\r\n print('', file=fhandle)\r\n print(''.format(\r\n img_to_base64(pictogram(class_name))), file=fhandle)\r\n print(''.format(img), file=fhandle)\r\n print(''.format(class_name), file=fhandle)\r\n print(''.format(train_imgs), file=fhandle)\r\n print(''.format(train_phys), file=fhandle)\r\n print(''.format(test_imgs), file=fhandle)\r\n print(''.format(test_phys), file=fhandle)\r\n print('', file=fhandle)\r\n\r\n print('
PictogramSampleClass nametrain imagestrain physicaltest imagestest physical
{}{}{}{}{}
', file=fhandle)\r\n\r\n\r\n\r\ndef extend_stats(stats):\r\n for class_name in stats:\r\n for phase in ['train', 'test']:\r\n if phase not in stats[class_name]:\r\n stats[class_name][phase] = {}\r\n stats[class_name][phase]['imgs'] = 0\r\n stats[class_name][phase]['phys'] = 0\r\n\r\n\r\ndef get_time_marking_stats(path, prefix):\r\n stats = {}\r\n for phase in ['train', 'test']:\r\n phase_marking = load_marking(\"{path}/{prefix}_{phase}.json\".format(**locals()))\r\n marking = organize_by_classes(phase_marking)\r\n\r\n for class_name in marking:\r\n stats.setdefault(class_name, {})\r\n stats[class_name].setdefault(phase, {})\r\n stats[class_name][phase]['imgs'] = len(marking[class_name])\r\n stats[class_name]['filename'] = marking[class_name][0]['pict_name']\r\n stats[class_name]['bbox'] = marking[class_name][0]\r\n\r\n id_set = set()\r\n for image in marking[class_name]:\r\n id_set.add(image['sign_id'])\r\n stats[class_name][phase]['phys'] = len(id_set)\r\n\r\n extend_stats(stats)\r\n return stats\r\n\r\n# autosave23_10_2012_10_01_14_0.jpg\r\n#the first filename in old test marking (sorted)\r\n\r\ndef write_time_marking(marking, path, prefix):\r\n ind = sorted(marking).index(\"autosave23_10_2012_10_01_14_0.jpg\")\r\n train = dict(sorted(marking.items())[:ind + 1])\r\n test = dict(sorted(marking.items())[ind + 1:])\r\n\r\n with open(\"{path}/{prefix}_train.json\".format(**locals()), 'w') as out:\r\n json.dump(train, out, indent=4,sort_keys=True)\r\n\r\n with open(\"{path}/{prefix}_test.json\".format(**locals()), 'w') as out:\r\n json.dump(test,out, indent=4,sort_keys=True)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n stats = get_stats(\"marking\")\r\n print_stats(stats)\r\n write_marking_stats(stats, prefix='split', write_path='./')\r\n\r\n\r\n stats = get_stats('classmarking')\r\n path = '../global_data/Traffic_signs/RTSD/class_stats.txt'\r\n with open(path, 'w')as f:\r\n print_stats(stats, fhandle=f)\r\n write_marking_stats(stats, prefix='class_split', write_path='./')\r\n\r\n prefix = 'time_marking'\r\n path = '../global_data/Traffic_signs/RTSD/'\r\n raw_marking = load_marking('{}/new_marking.json'.format(path))\r\n write_time_marking(raw_marking, path, prefix)\r\n\r\n # time_stats = get_time_marking_stats(path, prefix)\r\n # print_stats(time_stats)\r\n # write_marking_stats(time_stats, prefix='time_split', write_path='./')\r\n\r\n # with open(\"{}/time_marking_test.json\".format(path)) as f:\r\n # test = json.load(f)\r\n # print(sorted(test)[0])\r\n\r\n","repo_name":"moon-and-star/RTSD-classification","sub_path":"imgprocess/marking_stats.py","file_name":"marking_stats.py","file_ext":"py","file_size_in_byte":8486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"7245797878","text":"import json\nfrom pathlib import Path\nfrom typing import List\n\nimport albumentations as A\nimport cv2\nimport numpy as np\nimport torch\nfrom albumentations.pytorch import ToTensorV2\n\n\nclass Letterbox(object):\n def __init__(\n self,\n new_shape=(640, 640),\n color=(114, 114, 114),\n auto=False,\n scaleFill=False,\n scaleup=True,\n *kwargs\n ):\n self.new_shape = new_shape\n self.color = color\n self.auto = auto\n self.scaleFill = scaleFill\n self.scaleup = scaleup\n\n def __call__(self, image, *kwargs):\n shape = image.shape # current shape [width, height]\n if isinstance(self.new_shape, int):\n self.new_shape = (self.new_shape, self.new_shape)\n\n # Scale ratio (new / old)\n r = min(self.new_shape[0] / shape[0], self.new_shape[1] / shape[1])\n if not self.scaleup: # only scale down, do not scale up (for better test mAP)\n r = min(r, 1.0)\n\n # Compute padding\n ratio = r, r # width, height ratios\n new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))\n dw, dh = (\n self.new_shape[1] - new_unpad[0],\n self.new_shape[0] - new_unpad[1],\n ) # wh padding\n if self.auto: # minimum rectangle\n dw, dh = np.mod(dw, 32), np.mod(dh, 32) # wh padding\n elif self.scaleFill: # stretch\n dw, dh = 0.0, 0.0\n new_unpad = (self.new_shape[1], self.new_shape[0])\n ratio = (\n self.new_shape[1] / shape[1],\n self.new_shape[0] / shape[0],\n ) # width, height ratios\n\n dw /= 2 # divide padding into 2 sides\n dh /= 2\n\n if shape[::-1] != new_unpad: # resize\n image = cv2.resize(image, new_unpad, interpolation=cv2.INTER_LINEAR)\n top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))\n left, right = int(round(dw - 0.1)), int(round(dw + 0.1))\n image = cv2.copyMakeBorder(\n image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=self.color\n ) # add border\n return {\"image\": image}\n\n\ndef bytes_to_numpy(image: bytes):\n file_bytes = np.asarray(bytearray(image.read()), dtype=np.uint8)\n opencv_image = cv2.imdecode(file_bytes, 1)\n return opencv_image\n\n\ndef calculate_embed(\n whale_ids: list,\n whale_embeddings: List[List[float]],\n embedding_to_compare: List[float],\n tolerance: float = 0.5,\n):\n \"\"\"\n Сравнение признаков китов со списком признаков китов известных китов из БД.\n\n :param face_ids: Список идентификаторов китов для сравнения.\n :param face_embeddings: Список признаков китов для сравнения.\n :param embedding_to_compare: Признаки сравниваемого китов.\n :param tolerance: Порог \"расстояния\" между китами, при котором лицо признаётся распознанным.\n :return: Возвращает идентификатор + score кита или None в случае неудачи.\n \"\"\"\n # print(embedding_to_compare-whale_embeddings)\n result = {\"status\": False}\n\n embedding_to_compare = np.asarray(embedding_to_compare)\n\n whales_distances = np.linalg.norm(embedding_to_compare - whale_embeddings, axis=1)\n\n # print(whales_distances)\n\n best_match_index = np.argmin(whales_distances)\n\n # print(\"========= embeding to compare\")\n # print(len(embedding_to_compare))\n # print(\"========= best simularity embedding\")\n # print(print(whale_embeddings[best_match_index]))\n # print(f\"LEN DB {len(whale_embeddings)}\")\n # print(\"INDEX\", best_match_index)\n\n whales_distances = np.min(whales_distances)\n\n if whales_distances < tolerance:\n result[\"status\"] = True\n result[\"whale_id\"] = whale_ids[best_match_index]\n result[\"whales_distances\"] = whales_distances\n # confidence = face_distance_to_conf(whales_distances)\n # result[\"confidence\"] = confidence\n return result\n else:\n result[\"whale_id\"] = whale_ids[best_match_index]\n result[\"whales_distances\"] = whales_distances\n # confidence = face_distance_to_conf(whales_distances)\n # result[\"confidence\"] = confidence\n return result\n\n\ndef get_metadata(path: Path):\n if path.exists():\n with path.open(mode=\"r\") as f:\n return json.load(f)\n return {}\n\n\ndef get_numpy_db(path: Path):\n if path.exists():\n return np.load(path.__str__())\n return np.empty(shape=(1, 512))\n","repo_name":"p0wned17/whale_hackathon","sub_path":"service/whale_recognition/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"12726764417","text":"# Part of XYalign\n# Collection of functions related to ploidy estimation and chromosome depth\n# comparison\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport csv\nimport logging\nimport numpy as np\nfrom scipy.stats import ks_2samp\nimport time\n\n\n# Create logger for ploidy submodule\nploidy_logger = logging.getLogger(\"xyalign.ploidy\")\n\n\ndef permutation_test_chromosomes(\n\tdata_frame, first_chrom, second_chrom, chrom_column,\n\tvalue_column, num_perms, output_file=None):\n\t\"\"\"\n\tRuns a permutation test comparing mean values of two chromosomes.\n\n\tParameters\n\t----------\n\tdata_frame : pandas dataframe\n\tfirst_chrom : str\n\t\tThe name of the first chromosome in comparison\n\tsecond_chrom : str\n\t\tThe name of the second chromosome in comparison\n\tchrom_column : str\n\t\tThe name of the column containing chromosome names\n\tvalue_column : str\n\t\tThe name of the column containing the value of interest\n\tnum_perms : int\n\t\tThe number of permutations to use\n\toutput_file : {str, None}\n\t\tIf not None, will print results to this file\n\n\tReturns\n\t-------\n\ttuple\n\t\t(mean of first chrom, mean of second chrom, p-value)\n\n\t\"\"\"\n\tperm_start = time.time()\n\tploidy_logger.info(\n\t\t\"Running permutation test ({} reps) comparing ratio of {} over {}\".format(\n\t\t\tnum_perms, first_chrom, second_chrom))\n\tfirst_vals = data_frame[\n\t\tdata_frame[chrom_column] == first_chrom][value_column]\n\tsecond_vals = data_frame[\n\t\tdata_frame[chrom_column] == second_chrom][value_column]\n\tcombined = np.append(first_vals, second_vals)\n\n\tfirst_mean = np.mean(first_vals)\n\tsecond_mean = np.mean(second_vals)\n\n\tobserved = first_mean / second_mean\n\tperms = []\n\tfor i in range(0, num_perms):\n\t\tnp.random.shuffle(combined)\n\t\tfirst = np.mean(combined[:len(first_vals)])\n\t\tsecond = np.mean(combined[-len(second_vals):])\n\t\tperms.append(first / second)\n\tperms = np.asarray(perms)\n\tsig = len(np.where(perms > observed)) / num_perms\n\tif output_file is not None:\n\t\ta = [\n\t\t\t\"{}_mean\".format(first_chrom),\n\t\t\t\"{}_mean\".format(second_chrom),\n\t\t\t\"{}_{}_ratio\".format(first_chrom, second_chrom),\n\t\t\t\"p_val_({}_/_{})\".format(first_chrom, second_chrom),\n\t\t\t\"perm_dist_2.5\",\n\t\t\t\"perm_dist_50\",\n\t\t\t\"perm_dist_97.5\"]\n\t\tb = [\n\t\t\t\"{}\".format(first_mean),\n\t\t\t\"{}\".format(second_mean),\n\t\t\t\"{}\".format(observed),\n\t\t\t\"{}\".format(sig),\n\t\t\t\"{}\".format(np.percentile(perms, 2.5)),\n\t\t\t\"{}\".format(np.percentile(perms, 50)),\n\t\t\t\"{}\".format(np.percentile(perms, 97.5))]\n\t\twith open(output_file, \"w\") as f:\n\t\t\tw = csv.writer(f, dialect=\"excel-tab\")\n\t\t\tw.writerows([a, b])\n\tploidy_logger.info(\n\t\t\"Permutations on {} and {} complete. Elapsed time: {} seconds\".format(\n\t\t\tfirst_chrom, second_chrom, time.time() - perm_start))\n\treturn (first_mean, second_mean, sig)\n\n\ndef ks_two_sample(\n\tdata_frame, first_chrom, second_chrom, chrom_column,\n\tvalue_column, output_file=None):\n\t\"\"\"\n\tRuns a Two-sample Kolmogorov-Smirnov test\n\n\tParameters\n\t----------\n\n\tdata_frame : pandas dataframe\n\tfirst_chrom : str\n\t\tThe name of the first chromosome in comparison\n\tsecond_chrom : str\n\t\tThe name of the second chromosome in comparison\n\tchrom_column : str\n\t\tThe name of the column containing chromosome names\n\tvalue_column : str\n\t\tThe name of the column containing the value of interest\n\toutput_file : {str, None}\n\t\tIf not None, will print results to this file.\n\n\tReturns\n\t-------\n\n\ttuple\n\t\t(ks_statistic, ks_pvalue)\n\n\t\"\"\"\n\tks_start = time.time()\n\tploidy_logger.info(\n\t\t\"Running KS two sample test on {} and {}\".format(\n\t\t\tfirst_chrom, second_chrom))\n\tfirst_vals = data_frame[\n\t\tdata_frame[chrom_column] == first_chrom][value_column]\n\tsecond_vals = data_frame[\n\t\tdata_frame[chrom_column] == second_chrom][value_column]\n\n\tfirst_mean = np.mean(first_vals)\n\tsecond_mean = np.mean(second_vals)\n\tmean_ratio = first_mean / second_mean\n\n\tresult = ks_2samp(first_vals, second_vals)\n\n\tif output_file is not None:\n\t\ta = [\n\t\t\t\"{}_mean\".format(first_chrom),\n\t\t\t\"{}_mean\".format(second_chrom),\n\t\t\t\"{}_{}_ratio\".format(first_chrom, second_chrom),\n\t\t\t\"ks_statistic\",\n\t\t\t\"p_val\"]\n\t\tb = [\n\t\t\t\"{}\".format(first_mean),\n\t\t\t\"{}\".format(second_mean),\n\t\t\t\"{}\".format(mean_ratio),\n\t\t\t\"{}\".format(result[0]),\n\t\t\t\"{}\".format(result[1])]\n\n\t\twith open(output_file, \"w\") as f:\n\t\t\tw = csv.writer(f, dialect=\"excel-tab\")\n\t\t\tw.writerows([a, b])\n\tploidy_logger.info(\n\t\t\"KS two sample test on {} and {} complete. Elapsed time: {} seconds\".format(\n\t\t\tfirst_chrom, second_chrom, time.time() - ks_start))\n\treturn result\n\n\ndef bootstrap(\n\tdata_frame, first_chrom, second_chrom, chrom_column,\n\tvalue_column, num_reps, output_file=None):\n\t\"\"\"\n\tBootstraps the 95 percent confidence interval of the mean ratio of\n\tmeasure for two chromosomes (chrom1 / chrom2).\n\n\tParameters\n\t----------\n\n\tdata_frame : pandas dataframe\n\tfirst_chrom : str\n\t\tThe name of the first chromosome in comparison\n\tsecond_chrom : str\n\t\tThe name of the second chromosome in comparison\n\tchrom_column : str\n\t\tThe name of the column containing chromosome names\n\tvalue_column : str\n\t\tThe name of the column containing the value of interest\n\tnum_reps : int\n\t\tThe number of bootstrap replicates to use\n\toutput_file : {str, None}\n\t\tIf not None, will print results to this file.\n\n\tReturns\n\t-------\n\ttuple\n\t\t(mean ratio, 0.025 percentile, 0.975 percentile)\n\t\"\"\"\n\tboot_start = time.time()\n\n\tploidy_logger.info(\n\t\t\"Bootstrapping mean depth ratio of {} over {}\".format(\n\t\t\tfirst_chrom, second_chrom))\n\tfirst_vals = data_frame[\n\t\tdata_frame[chrom_column] == first_chrom][value_column]\n\tsecond_vals = data_frame[\n\t\tdata_frame[chrom_column] == second_chrom][value_column]\n\n\tfirst_vals = np.asarray(first_vals)\n\tsecond_vals = np.asarray(second_vals)\n\n\tfirst_mean = np.mean(first_vals)\n\tsecond_mean = np.mean(second_vals)\n\tmean_ratio = first_mean / second_mean\n\n\tsamples = []\n\tdim1 = len(first_vals)\n\tdim2 = len(second_vals)\n\tfor i in range(0, num_reps):\n\t\tindices1 = np.random.random_integers(0, dim1 - 1, dim1)\n\t\tindices2 = np.random.random_integers(0, dim2 - 1, dim2)\n\t\tboot1 = np.take(first_vals, indices1)\n\t\tboot2 = np.take(second_vals, indices2)\n\t\tsamples.append(np.mean(boot1) / np.mean(boot2))\n\n\tsamples = np.asarray(samples)\n\n\tif output_file is not None:\n\t\ta = [\n\t\t\t\"{}_mean\".format(first_chrom),\n\t\t\t\"{}_mean\".format(second_chrom),\n\t\t\t\"{}_{}_ratio\".format(first_chrom, second_chrom),\n\t\t\t\"boot_2.5_percentile\",\n\t\t\t\"boot_50_percentile\",\n\t\t\t\"boot_97.5_percentile\"]\n\t\tb = [\n\t\t\t\"{}\".format(first_mean),\n\t\t\t\"{}\".format(second_mean),\n\t\t\t\"{}\".format(mean_ratio),\n\t\t\t\"{}\".format(np.percentile(samples, 2.5)),\n\t\t\t\"{}\".format(np.percentile(samples, 50)),\n\t\t\t\"{}\".format(np.percentile(samples, 97.5))]\n\t\twith open(output_file, \"w\") as f:\n\t\t\tw = csv.writer(f, dialect=\"excel-tab\")\n\t\t\tw.writerows([a, b])\n\tploidy_logger.info(\n\t\t\"Bootstrapping of {} and {} (ratio) complete. \"\n\t\t\"Elapsed time: {} seconds\".format(\n\t\t\tfirst_chrom, second_chrom, time.time() - boot_start))\n\treturn (mean_ratio, np.percentile(samples, 2.5), np.percentile(samples, 97.5))\n","repo_name":"WilsonSayresLab/XYalign","sub_path":"xyalign/ploidy.py","file_name":"ploidy.py","file_ext":"py","file_size_in_byte":6871,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"26"} +{"seq_id":"24859207797","text":"from safetensors.torch import save_file\n# from huggingface_hub import hf_hub_download\nfrom transformers.utils import cached_file\nimport torch\nimport tqdm\nimport os\n\nDIRECTORY = \"weights\"\n\ndef convert_350m():\n filename = cached_file(\"bigscience/bloom-560m\", filename=\"pytorch_model.bin\")\n data = torch.load(filename, map_location=\"cpu\")\n\n # Need to copy since that call mutates the tensors to numpy\n save_file(data.copy(), os.path.join(DIRECTORY, \"bloom-350m.bin\"))\n\n\ndef convert_testing():\n filename = cached_file(\n \"bigscience/bigscience-small-testing\", filename=\"pytorch_model.bin\"\n )\n data = torch.load(filename, map_location=\"cpu\")\n\n # Need to copy since that call mutates the tensors to numpy\n save_file(data.copy(), os.path.join(DIRECTORY, \"bloom-testing.bin\"))\n\n\ndef convert_full():\n MODEL_ID = \"bigscience/bloom\"\n filenames = [\n (f\"bloom-h.{i}.bin\", f\"pytorch_model_000{i+2:02d}-of-00072.bin\")\n for i in range(0, 70)\n ]\n for (local, filename) in tqdm.tqdm(\n [\n (\"bloom-embedding.bin\", \"pytorch_model_00001-of-00072.bin\"),\n (\"bloom-final.bin\", \"pytorch_model_00072-of-00072.bin\"),\n ]\n + filenames\n ):\n if os.path.exists(local):\n continue\n filename = cached_file(MODEL_ID, filename=filename)\n data = torch.load(filename, map_location=\"cpu\")\n\n save_file(data.copy(), os.path.join(DIRECTORY, local))\n\nif __name__ == \"__main__\":\n convert_testing()\n convert_350m()\n convert_full()\n","repo_name":"Narsil/bloomserver","sub_path":"convert_weights.py","file_name":"convert_weights.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"26"} +{"seq_id":"39494658434","text":"import sys\nimport math\nimport datetime\nimport time, threading\nimport requests\nimport clr\nimport logging\nfrom pathlib import Path\nfrom time import sleep\nfrom functools import wraps\nfrom queue import Queue\n\nglobal System, DataTable, TOM, ADOMD\nfrom dearpygui import *\nfrom multiprocessing import Process, Queue, Lock\nimport multiprocessing\n\n\nlogger = logging.getLogger(__name__)\nlogger.info(\"Loading .Net assemblies...\")\nclr.AddReference(\"System\")\nclr.AddReference(\"System.Data\")\nroot = Path(r\"C:\\Windows\\Microsoft.NET\\assembly\\GAC_MSIL\")\namo_path = str(\n max((root / \"Microsoft.AnalysisServices.Tabular\").iterdir())\n / \"Microsoft.AnalysisServices.Tabular.dll\"\n )\nadomd_path = str(\n max((root / \"Microsoft.AnalysisServices.AdomdClient\").iterdir())\n / \"Microsoft.AnalysisServices.AdomdClient.dll\"\n )\nclr.AddReference(amo_path)\nclr.AddReference(adomd_path)\nimport System\nfrom System.Data import DataTable\nimport Microsoft.AnalysisServices.Tabular as TOM\nimport Microsoft.AnalysisServices.AdomdClient as ADOMD\nfrom Microsoft.AnalysisServices.Tabular import Measure\n\nglobal databaseid_value,localhost_value\n\n\n\ndef gui(databaseid_value,localhost_value):\n set_main_window_title('DAX Format')\n set_style_window_title_align(10, 10)\n set_main_window_size(530, 650)\n add_text(\"input databaseid and localhost\")\n add_text(\"You can via Dax studio to copy that\")\n add_input_text(\"databaseid\",default_value=databaseid_value)\n add_input_text(\"localhost\",default_value=localhost_value)\n add_button(\"Start\", callback=\"start_callback\",width=80,height=40)\n add_text(\"msgmess:\")\n start_dearpygui()\ndef start_callback(sender, data):\n global databaseid_value, localhost_value\n print(get_value(\"databaseid\"))\n print(get_value(\"localhost\"))\n databaseid_value=get_value(\"databaseid\")\n localhost_value = get_value(\"localhost\")\n rename_main()\n\n\ndef tomserver():\n\n conn = \"Provider=MSOLAP;Data Source=\"+localhost_value+\";Initial Catalog='';\"\n # print(conn)\n TOMServer = TOM.Server()\n TOMServer.Connect(conn)\n\n for item in TOMServer.Databases:\n print(\"Compatibility Level: {0} \\nDatabase: {1} \\nCreated: {2}\".\n format(item.Name,item.CompatibilityLevel,item.CreatedTimestamp))\n\n databaseid=databaseid_value\n PowerBIDatabase = TOMServer.Databases[databaseid]\n return PowerBIDatabase\n\n\n\ndef get_measures(PowerBIDatabase):\n measures_list = []\n for table in PowerBIDatabase.Model.Tables:\n CurrentTable = PowerBIDatabase.Model.Tables.Find(table.Name)\n for measure in CurrentTable.Measures:\n measures_list.append({\"Name\":measure.Name,\"Expression\": measure.Expression})\n return measures_list\n\n\ndef get_formatted_dax(Measure_list,q):\n if len(Measure_list)>0:\n for Measure in Measure_list:\n i=0\n while i<4:\n try:\n x = {'Dax': Measure[\"Name\"]+\"=\"+Measure[\"Expression\"], 'ListSeparator': ',', 'DecimalSeparator': '.', 'MaxLineLenght': 0}\n url = 'https://daxtest02.azurewebsites.net/api/daxformatter/daxtokenformat/'\n r = requests.post(url, data=x,timeout=15)\n dax_dict = r.json()\n d1 = dax_dict[\"formatted\"]\n if len(d1)==0:\n print(\"DAX公式错误\")\n break\n result = \"\"\n for i, v in enumerate(d1):\n if i > 0:\n result = result + '\\r\\n'\n for x in v:\n result = result + x[\"string\"]\n\n q.put({\"Name\":Measure[\"Name\"],\"Expression\":result})\n break\n except Exception as e:\n i=i+1\n print(\"第{0}次超时/网络错误\".format(i))\n\n\n\ndef formatted_all_measures(PowerBIDatabase,formatted_mesures):\n # refresh_dict = {\"full\": TOM.RefreshType.Full}\n # print(formatted_mesures)\n for table in PowerBIDatabase.Model.Tables:\n CurrentTable = PowerBIDatabase.Model.Tables.Find(table.Name)\n for measure in CurrentTable.Measures:\n for d in formatted_mesures:\n if measure.Name == d[\"Name\"]:\n # print(d[\"Name\"],d[\"Expression\"])\n measure.Expression = d[\"Expression\"]\n # CurrentTable.RequestRefresh(refresh_dict[\"full\"])\n # PowerBIDatabase.Model.RequestRefresh(refresh_dict[\"full\"])\n PowerBIDatabase.Model.SaveChanges()\n print(\"All Dax has been formatted\")\n\n\ndef multithreading_get_format_dax(measures_list,q):\n if len(measures_list)<20:\n thread_num=len(measures_list)\n else:\n thread_num = 20\n step = math.ceil(len(measures_list) / thread_num)\n thread_list = []\n for i in range(0,thread_num):\n t = threading.Thread(target=get_formatted_dax, args=(measures_list[i*step:(i+1)*step],q,))\n # print(i*step,(i+1)*step)\n thread_list.append(t)\n for i,t,in enumerate(thread_list):\n t.start()\n for i,t,in enumerate(thread_list):\n t.join()\n\ndef rename_main():\n PowerBIDatabase=tomserver()\n q = Queue()\n start_time = time.time()\n measure_list=get_measures(PowerBIDatabase)\n print(\"total measures:{}\".format(len(measure_list)))\n multithreading_get_format_dax(measure_list, q)\n formatted_mesures = []\n while True:\n if not (q.empty()):\n formatted_mesures.append(q.get())\n else:\n break\n\n end_time = time.time()\n formatted_all_measures(PowerBIDatabase,formatted_mesures)\n time_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\n msg=\"time:{0} total measures:{1} ---- take {2} seconds\".format(time_str,len(formatted_mesures),round(end_time - start_time,3))\n print(\" {} measures has been formatted\".format(len(formatted_mesures)))\n print(\"cost time:\", end_time - start_time)\n # print(msg)\n add_text(msg)\n\n\nif __name__ == '__main__':\n try:\n databaseid_value = sys.argv[2]\n localhost_value = sys.argv[1]\n except:\n databaseid_value = \"\"\n localhost_value = \"\"\n gui(databaseid_value,localhost_value)\n","repo_name":"jasonlaw997/DAX-Tools","sub_path":"daxformat_all.py","file_name":"daxformat_all.py","file_ext":"py","file_size_in_byte":6245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"23506086729","text":"import random\nfrom pico2d import *\nimport gfw\nimport gobj\nimport json\n\nPLAYER_SIZE = 270\n\nclass Player:\n RUNNING, FALLING, JUMPING, DOUBLE_JUMP, SLIDING = range(5)\n ANIMS_11x6 = [\n [ 0x40, 0x41, 0x42, 0x43 ], # RUNNING\n [ 0x50 ], # FALLING\n [ 0x57, 0x58 ], # JUMPING\n [ 0x51, 0x52, 0x53, 0x54 ], # DOUBLE_JUMP\n [ 0x59, 0x5A ], # SLIDING\n ]\n ANIMS_13x6 = [\n [ 0x40, 0x41, 0x42, 0x43 ], # RUNNING\n [ 0x50 ], # FALLING\n [ 0x56, 0x57 ], # JUMPING\n [ 0x51, 0x52, 0x53, 0x54 ], # DOUBLE_JUMP\n [ 0x58, 0x59 ], # SLIDING\n ]\n MAGNIFIED_RUN_ANIM = [ 0x44, 0x45, 0x46, 0x47 ]\n BB_DIFFS = [\n (-60,-135,60,0), # RUNNING\n (-60,-135,60,10), # FALLING\n (-60,-135,60,-20), # JUMPING\n (-60,-135,60,-20), # DOUBLE_JUMP\n (-80,-135,80,-68), # SLIDING\n ]\n SLIDE_DURATION = 1.0\n\n GRAVITY = 3000\n JUMP = 1000\n\n #constructor\n def __init__(self):\n self.pos = 150, get_canvas_height() // 2\n self.delta = 0, 0\n # self.image = gfw.image.load(gobj.res('cookie.png'))\n self.time = 0\n self.FPS = 10\n self.mag = 1\n self.mag_speed = 0\n # self.anims = Player.ANIMS_11x6\n self.change_image(0)\n self.state = Player.RUNNING\n # self.char_time = 0\n # self.cookie_name = 'Brave Cookie'\n\n @property\n def state(self):\n return self.__state\n @state.setter\n def state(self, state):\n self.__state = state\n self.anim = self.anims[state]\n def draw(self):\n anim = self.anim\n # if self.state == Player.RUNNING and self.mag > 1:\n # anim = Player.MAGNIFIED_RUN_ANIM\n fidx = round(self.time * self.FPS) % len(anim)\n sprite_num = anim[fidx]\n x, y = sprite_num % 0x10, sprite_num // 0x10\n x = x * (PLAYER_SIZE + 2) + 2\n y = y * (PLAYER_SIZE + 2) + 2\n size = PLAYER_SIZE * self.mag, PLAYER_SIZE * self.mag\n self.image.clip_draw(x, y, PLAYER_SIZE, PLAYER_SIZE, *self.pos, *size)\n\n if self.cookie_time < 3.0:\n font = gfw.font.load(gobj.res('ENCR10B.TTF'), 30)\n font.draw(20, 20, self.cookie_name)\n\n def magnify(self):\n self.mag_speed = 1.0\n def reduce(self):\n self.mag_speed = -1.0\n\n def jump(self):\n if self.state in [Player.FALLING, Player.DOUBLE_JUMP, Player.SLIDING]: \n return\n if self.state == Player.RUNNING:\n self.state = Player.JUMPING\n elif self.state == Player.JUMPING:\n self.state = Player.DOUBLE_JUMP\n self.jump_speed = Player.JUMP * self.mag\n def slide(self):\n if self.state != Player.RUNNING: return\n self.state = Player.SLIDING\n self.time = 0.0\n def update(self):\n self.update_mag()\n self.cookie_time += gfw.delta_time\n self.time += gfw.delta_time\n if self.state == Player.SLIDING and self.time > Player.SLIDE_DURATION:\n self.state = Player.RUNNING\n if self.state in [Player.JUMPING, Player.DOUBLE_JUMP, Player.FALLING]:\n # print('jump speed:', self.jump_speed)\n self.move((0, self.jump_speed * gfw.delta_time))\n self.jump_speed -= Player.GRAVITY * self.mag * gfw.delta_time\n _,foot,_,_ = self.get_bb()\n if foot < 0:\n self.move((0, get_canvas_height()))\n platform = self.get_platform(foot)\n if platform is not None:\n l,b,r,t = platform.get_bb()\n if self.state in [Player.RUNNING, Player.SLIDING]:\n if foot > t:\n self.state = Player.FALLING\n self.jump_speed = 0\n else:\n # print('falling', t, foot)\n if self.jump_speed < 0 and int(foot) <= t:\n self.move((0, t - foot))\n self.state = Player.RUNNING\n self.jump_speed = 0\n # print('Now running', t, foot)\n\n def get_platform(self, foot):\n selected = None\n sel_top = 0\n x,y = self.pos\n for platform in gfw.world.objects_at(gfw.layer.platform):\n l,b,r,t = platform.get_bb()\n if x < l or x > r: continue\n mid = (b + t) // 2\n if foot < mid: continue\n if selected is None:\n selected = platform\n sel_top = t\n else:\n if t > sel_top:\n selected = platform\n sel_top = t\n # if selected is not None:\n # print(l,b,r,t, selected)\n return selected\n\n def move_down_from_platform(self):\n if self.state != Player.RUNNING: return\n _,foot,_,_ = self.get_bb()\n platform = self.get_platform(foot)\n print('can pass:', platform.can_pass)\n if not platform.can_pass: return\n\n x,y = self.pos\n y -= platform.height / 2 + 1\n self.pos = x,y\n\n def update_mag(self):\n if self.mag_speed == 0: return\n\n x,y = self.pos\n _,b,_,_ = self.get_bb()\n diff = y - b\n prev_mag = self.mag\n\n self.mag += self.mag_speed * gfw.delta_time\n if self.mag > 2.0:\n self.mag = 2.0\n self.mag_speed = 0\n elif self.mag < 1.0:\n self.mag = 1.0\n self.mag_speed = 0\n\n new_y = b + diff * self.mag / prev_mag\n self.pos = x,new_y\n\n def move(self, diff):\n self.pos = gobj.point_add(self.pos, diff)\n\n def handle_event(self, e):\n if e.type == SDL_KEYDOWN:\n if e.key == SDLK_RETURN:\n self.slide()\n elif e.key == SDLK_SPACE or e.key == SDLK_UP:\n self.jump()\n elif e.key == SDLK_DOWN:\n self.move_down_from_platform()\n elif e.key == SDLK_m:\n if self.mag == 2 or self.mag_speed > 0:\n self.reduce()\n else:\n self.magnify()\n elif e.key == SDLK_LEFTBRACKET:\n self.change_image(-1)\n elif e.key == SDLK_RIGHTBRACKET:\n self.change_image(1)\n\n def get_bb(self):\n l,b,r,t = Player.BB_DIFFS[self.state]\n b = - PLAYER_SIZE // 2\n x,y = self.pos\n if self.mag != 1:\n l *= self.mag\n b *= self.mag\n r *= self.mag\n t *= self.mag\n return x + l, y + b, x + r, y + t\n\n def __getstate__(self):\n dict = self.__dict__.copy()\n del dict['image']\n return dict\n\n def __setstate__(self, dict):\n # self.__init__()\n self.__dict__.update(dict)\n self.image = gfw.image.load(gobj.RES_DIR + '/animation_sheet.png')\n\n def change_image(self, diff):\n if not hasattr(self, 'cookie_chars'):\n with open(gobj.res('cookies.json'), 'r') as f:\n self.cookie_chars = json.load(f)\n self.cookie_index = 0\n else:\n cookie = self.cookie_chars[self.cookie_index]\n sheet = '../w09-res/out/%s_sheet.png' % cookie[\"id\"]\n gfw.image.unload(sheet)\n self.cookie_index = (self.cookie_index + diff) % len(self.cookie_chars)\n\n cookie = self.cookie_chars[self.cookie_index]\n sheet = '../w09-res/out/%s_sheet.png' % cookie[\"id\"]\n self.image = gfw.image.load(sheet)\n global PLAYER_SIZE\n prev_size = PLAYER_SIZE\n PLAYER_SIZE = cookie[\"size\"]\n self.anims = Player.ANIMS_11x6 if cookie[\"xcount\"] == 11 else Player.ANIMS_13x6\n\n x,y = self.pos\n diff = (PLAYER_SIZE - prev_size) // 2\n self.pos = x, y+diff\n print(cookie)\n\n self.cookie_name = cookie[\"name\"]\n self.cookie_time = 0\n\n","repo_name":"scgyong-kpu/2dgp-2020","sub_path":"w09/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":7839,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"26"} +{"seq_id":"25904455721","text":"# -*- coding: UTF-8 -*-\n\nimport collections\nimport random\nimport math\nimport time\n\nfrom gi.repository import Gtk, GLib\n\nclass mpl:\n from matplotlib.figure import Figure\n from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas\n\nclass UI:\n def __init__(self, sampleinterval=0.1, timewindow=10., size=(600,350)):\n #JOHN: builder and gtkwindow, builder.connect_signals\n b = Gtk.Builder()\n b.add_from_file(\"myui.ui\")\n b.connect_signals(self)\n \n w = b.get_object(\"window1\")\n w.set_default_size(*size)\n \n b.get_object(\"label1\").set_markup(\"ð��ƒ\")\n\n w.connect(\"delete-event\", Gtk.main_quit)\n \n box = b.get_object(\"box1\")\n \n # Data management\n self.offset = 0\n interval = int(sampleinterval*1000)\n bufsize = int(timewindow/sampleinterval)\n self.databuffer = collections.deque([0.0]*bufsize, bufsize)\n self.x = [sampleinterval*i for i in range(-bufsize+1,1)]\n\n # MPL stuff\n self.figure = mpl.Figure()\n self.ax = self.figure.add_subplot(1, 1, 1)\n self.ax.grid(True)\n self.canvas = mpl.FigureCanvas(self.figure)\n self.line, = self.ax.plot(self.x, self.databuffer)\n \n #JOHN: box pack end and timeout and show\n box.pack_start(self.canvas, True, True, 0)\n w.show_all()\n \n GLib.timeout_add(100, self.getdata)\n \n def on_button1_clicked(self, btn):\n self.offset+=20\n\n def on_button2_clicked(self, btn):\n self.offset -= 10\n\n def on_button3_clicked(self, btn):\n self.offset = 0\n\n def getdata(self):\n frequency = 0.5\n noise = random.normalvariate(0., 1.)\n new = 10.*math.sin(time.time()*frequency*2*math.pi) + noise + self.offset\n\n self.databuffer.append( new )\n self.line.set_ydata(self.databuffer)\n self.ax.relim()\n self.ax.autoscale_view(False, False, True)\n self.canvas.draw()\n \n return True\n \nif __name__ == \"__main__\":\n u = UI()\n Gtk.main()\n","repo_name":"strawlab/py4science-vbc","sub_path":"2012-09-14/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"26"} +{"seq_id":"11623936961","text":"import pandas as pd\nfrom .raw2mid import BaseRaw2Mid\n\nr\"\"\"\nR2M_ASSIST_1516\n########################\n\"\"\"\n\n\nclass R2M_ASSIST_1516(BaseRaw2Mid):\n \"\"\"R2M_ASSIST_1516 is a class used to handle the ASSISTment 2015-2016 dataset.\"\"\"\n\n def process(self):\n super().process()\n pd.set_option(\"mode.chained_assignment\", None) # ignore warning\n # 读取原始数据,查看其属性\n raw_data = pd.read_csv(f\"{self.rawpath}/2015_100_skill_builders_main_problems.csv\", encoding='utf-8')\n\n # 获取交互信息\n # 对log_id进行排序,确定order序列\n inter = pd.DataFrame.copy(raw_data).sort_values(by='log_id', ascending=True)\n inter['order'] = range(len(inter))\n inter['label'] = inter['correct']\n df_inter = inter.rename(columns={'sequence_id': 'exer_id', 'user_id': 'stu_id'}).reindex(\n columns=['stu_id', 'exer_id', 'label', 'order', ]).rename(\n columns={'stu_id': 'stu_id:token', 'exer_id': 'exer_id:token', 'label': 'label:float',\n 'order': 'order_id:token'})\n\n # 获取学生信息\n stu = pd.DataFrame(set(raw_data['user_id']), columns=['stu_id', ])\n # stu['classId'] = None\n # stu['gender'] = None\n df_stu = stu.sort_values(by='stu_id', ascending=True)\n\n # 获取习题信息\n exer = pd.DataFrame(set(raw_data['sequence_id']), columns=['exer_id'])\n # exer['cpt_seq'] = None\n # exer['assignment_id'] = None\n df_exer = exer.sort_values(by='exer_id', ascending=True)\n\n # 此处将数据保存到`self.midpath`中\n\n df_inter.to_csv(f\"{self.midpath}/{self.dt}.inter.csv\", index=False, encoding='utf-8')\n # df_stu.to_csv(f\"{self.midpath}/{self.dt}.stu.csv\", index=False, encoding='utf-8')\n # df_exer.to_csv(f\"{self.midpath}/{self.dt}.exer.csv\", index=False, encoding='utf-8')\n pd.set_option(\"mode.chained_assignment\", \"warn\") # ignore warning\n return\n","repo_name":"HFUT-LEC/EduStudio","sub_path":"edustudio/atom_op/raw2mid/assist_1516.py","file_name":"assist_1516.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"26"} +{"seq_id":"74436227909","text":"import Tkinter\nfrom Tkinter import *\nfrom random import *\nimport random\nimport math\nimport matplotlib\nfrom matplotlib.figure import Figure\nfrom matplotlib.pyplot import *\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\nimport tkFileDialog\nimport sqlite3\nimport csv\nimport numpy\n\n\"\"\"\nThis project is a merger of both my final project for this class and the final project for my introduction to programming(which is due on December 8th). Along with Vincent Medina, my midterm project for that class was a gravity simulator. For its final project, we have improved the simulator a great deal. \n\nBeing that it created large sets of information with potential for analysis, for my Everyday Computer Science final project, I added to the program an \"Export CSV\" function. This takes the \"particle and pollision Histories\"(lists that are appended information every iteration), and creates a csv for each. I then made a function for making and loading a database from a csv. This created two tables in the database file and fill them with entries for each line in each csv. With the database of a given simulation's data, I made a viewer for both the entire simulation's data and the data for each particle in it.\n\nThe process to utilize the simulation viewer:\n 1. Under the \"Simulation Management\" menu, select Generate Particles which will open a dialog.\n 2. Input variables into each entry, then hit make.(the top-left corner of the screen is (0,0). The bottom-right corner of the window before it is maximized is (500,500).)\n 3. When ready, under the \"Playback\" menu, select Run.\n - If the simulation is running too slowly:\n + Increase the iteration rate under the \"Simulation Management\" menu. It's default value is 1.0\n + Reduce the number of particles\n - If each iteration is running too slowly:\n + Reduce the distance between particles\n + Increase the mass of each particle\n 4. When ready, pause the simulation and export it to CSV by going to the \"CSV Management\" menu and selecting \"Export to CSV\".\n 5. When complete(currently only indicated by processor usage), make a Database by going to the \"Database Management\" menu and selecting \"Make and Load DB from CSV\". After selecting where you wish to save the DB file and which CSV's you wish to load, the program will create, populate, and index the DB.\n 6. When complete(currently only indicated by processor usage), you may then access the Database to view information about the simulation by selecting the \"Access Database\" menu and selecting \"Simulation Viewer\".\n \n 7. The Simuation Viewer function takes the longest amount of time to run. Be paitient.\n 8. When complete, it opens a window with three graphs and some text.\n 9. The viewer will also have an entry box with a button. By entering the integer name of a particle into the box and hitting the button, a popup will appear with information pertaining to the individual particle. If one does not appear, either the particle has no entries because it was fused into a child particle during initial placement or there is a problem with that particle's entries in the CSV. Note that there will be more particles in the simulation than were initially placed in it. When collisions occur in the simulation, for example, a collision between particle 5 and 6 in a 10 particle simulation would create a new particle named particle 11 and remove the two parent particles.\n\nHope you like it half as much as I enjoyed coding it. This was a very fun project for a very interesting class.\n\nI am also considering again expanding this gravity program for a yet undetermined ISP. I'll talk to you about it when I return in January.\n\nEach line in the particle csv averages to be about 0.00061035 Megabytes, 0.625 Kilobytes, 624 bytes per line\nlines are is per particle per iteration.\n\n\"\"\"\n\nroot = Tk()\n\ndef hello():\n pass\n\nclass Simulation:\n\tdef __init__(self):\n\t\tself.Particle_List = []\n\t\tself.Particle_History = []\n\t\tself.Collision_History = []\n\t\tself.Iteration_Rate = 1.0\n\t\tself.Current_Instance = 0.0\n\t\tself.Active_Particles = 0\n\t\tself.Particle_Iter = 0\n\t\tself.Paused = True\n\t\tself.Gravitational_Constant = 0.00125\n\t\tself.DB = \"\"\n\t\t\n\tdef Clear_Particle_List(self):\n\t\tself.Particle_List = []\n\t\tself.Current_Instance = 0.0\n\t\tself.Particle_History = []\n\t\tself.Collision_History = []\n\t\tself.Paused = True\n\t\tUniverse.space.delete(ALL)\n\t\tUniverse.status_bar.update()\n\t\t\n\tdef Get_Force_Distance(self):\t#Check my map\n\t\tfor p in self.Particle_List:\n\t\t\tOther_List = p.Get_Other_Particles()\n\t\t\tp.xforce = p.yforce = 0\n\t\t\tp.distance_list = []\n\t\t\tfor o in Other_List:\n\t\t\t\tp.Find_Force(o)\n\n\tdef Fuse(self, Parent_1, Parent_2, Child):\n\t\tself.Particle_List.remove(Parent_1)\n\t\tself.Particle_List.remove(Parent_2)\n\t\tself.Particle_List.append(Child)\n\n\tdef Create_Satellite(self, centerParticle, DistanceMassTupleList):\n\t\tNew_List = DistanceMassTupleList\n\t\tcenter = centerParticle\n\t\tfor Tuple in New_List:\n\t\t\tDistance = Tuple[0]\n\t\t\tMass = Tuple[1]\n\t\t\tNew_X = center.x + Distance\n\t\t\tNew_Y = center.y\n\t\t\tSatellite = Particle(New_X, New_Y, 0, 0, Mass)\n\t\t\tOther_List = Satellite.Get_Other_Particles()\n\t\t\tfor o in Other_List:\n\t\t\t\tSatellite.Find_Force(o)\n\t\t\tSatellite.yvel = Satellite.xvel * (-1)\n\t\t\tSatellite.xvel = 0\n\t\n\tdef Update_Particle_History(self):\n\t\tfor p in self.Particle_List:\n\t\t\tname = p.name\n\t\t\tinstance = p.instance\n\t\t\tmass = p.mass\n\t\t\tx = p.x\n\t\t\ty = p.y\n\t\t\txvel = p.xvel\n\t\t\tyvel = p.yvel\n\t\t\txaccel = p.xaccel\n\t\t\tyaccel = p.yaccel\n\t\t\txforce = p.xforce\n\t\t\tyforce = p.yforce\n\t\t\tData = [instance,name,mass,x,y,xvel,yvel,xaccel,yaccel,xforce,yforce]\n\t\t\tself.Particle_History.append(Data)\n\t\t\t\n\tdef One_Step(self):\n\t\tself.Update_Particle_History()\n\t\tself.Current_Instance += self.Iteration_Rate\n\t\tself.Get_Force_Distance()\n\t\tfor p in self.Particle_List:\n\t\t\tUniverse.status_bar.update()\n\t\t\tp.Get_Instance()\n\t\t\tp.Update_Position()\n\t\t\tp.Detect_Collision(p)\n\t\t\tp.Get_Instance()\n\n\tdef csvExport(self):\n\t\tParticleCSVFileHandle = tkFileDialog.asksaveasfilename(parent=root,title=\"Save the Particle CSV as...\")\n\t\tCollisionCSVFileHandle = tkFileDialog.asksaveasfilename(parent=root,title=\"Save the Collision CSV as...\")\n\t\t\n\t\tLineString = \"\"\n\t\tLineString += \"Instance,Name,Mass,X,Y,Xvel,Yvel,Xaccel,Yaccel\\n\"\n\t\tfor i in self.Particle_History:\n\t\t\tLineString += \"%f,%d,%f,%f,%f,%f,%f,%f,%f\" % (i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7],i[8])\n\t\t\tLineString += \"\\n\"\n\t\tPFile = open(ParticleCSVFileHandle,'w')\n\t\tPFile.write(LineString)\n\t\tPFile.close\n\t\t\n\t\tLineString2 = \"\"\n\t\tLineString2 += \"Instance,Parent_A,Parent_B,Child\\n\"\n\t\tfor i in self.Collision_History:\n\t\t\tLineString2 += \"%f,%f,%f,%f\" % (i[0],i[1],i[2],i[3])\n\t\t\tLineString2 += \"\\n\"\n\t\tCFile = open(CollisionCSVFileHandle,'w')\n\t\tCFile.write(LineString2)\n\t\tCFile.close\n\nsim = Simulation()\n\nclass Particle:\n\tdef __init__(self, x, y, xvel, yvel, mass): #No return\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.xvel = xvel\n\t\tself.yvel = yvel\n\t\tself.xaccel = 0\n\t\tself.yaccel = 0\n\t\tself.xforce = 0\n\t\tself.yforce = 0\n\t\tself.mass = float(mass)\n\t\tself.radius = math.sqrt(self.mass)\n\t\tself.instance = 0\n\t\tself.name = 0\n\t\tself.genname()\n\t\tself.distance_list = []\n\t\t#bbox Coordinates for drawing particles around center point\n\t\tself.x0 = self.x - self.radius\n\t\tself.y0 = self.y - self.radius\n\t\tself.x1 = self.x + self.radius\n\t\tself.y1 = self.y + self.radius\n\n\tdef genname(self): # Check me\n\t\tsim.Particle_Iter += 1\n\t\tself.name = sim.Particle_Iter\n\t\t\n\tdef update_bbox_coords(self):\n\t\tself.x0 = (self.x - self.radius)\n\t\tself.y0 = (self.y - self.radius)\n\t\tself.x1 = (self.x + self.radius)\n\t\tself.y1 = (self.y + self.radius)\n\n\tdef Get_Other_Particles(self):\n\t\tO_List = []\n\t\tfor p in sim.Particle_List:\n\t\t\tif self.name != p.name:\n\t\t\t\tO_List.append(p)\n\t\t\telse:\n\t\t\t\tcontinue\n\t\treturn O_List\n\n\tdef Find_Force(self, Other_Particle): #No return, Updates particle\n\t\txdiff = float(self.x - Other_Particle.x)\n\t\tydiff = float(self.y - Other_Particle.y)\n\t\tDistance = abs(math.sqrt((xdiff**2)+(ydiff**2)))\n\t\tif Distance < ((self.radius * 2) + (Other_Particle.radius * 2)):\n\t\t\tself.distance_list.append((Other_Particle,Distance))\n\t\tForce = (sim.Gravitational_Constant * self.mass * Other_Particle.mass) / Distance**2\n\t\tAcceleration = Force / self.mass\n\t\tself.xaccel = (xdiff/float(Distance) * Acceleration)\n\t\tself.xvel -= self.xaccel * sim.Iteration_Rate\n\t\tself.yaccel = (ydiff/float(Distance) * Acceleration)\n\t\tself.yvel -= self.yaccel * sim.Iteration_Rate\n\n\tdef Inelastic_Collision(self, mate):\n\t\tNew_Mass = self.mass + mate.mass\n\t\tXDiff = self.x - mate.x #.x is the x coord center of the circle.\n\t\tYDiff = self.y - mate.y #similar\n\t\tratio = self.mass/(New_Mass)\n\t\tNew_X = mate.x + ((XDiff)*ratio) #sets new center closest to largest mass particle\n\t\tNew_Y = mate.y + ((YDiff)*ratio) #same thing.\n\t\tNew_Xvel = ((self.mass * self.xvel) + (mate.mass * mate.xvel)) / (self.mass + mate.mass)\n\t\tNew_Yvel = ((self.mass * self.yvel) + (mate.mass * mate.yvel)) / (self.mass + mate.mass)\n\t\tz = Particle(New_X, New_Y, New_Xvel, New_Yvel, New_Mass)\n\t\treturn z\n\n#ratio of masses and lack of absolute values on the differences means we don't have\n#to use an if statement to find which mass is largest.\n\n\tdef Detect_Collision(self,p):\n\t\tfor i in self.distance_list:\n\t\t\tUniverse.status_bar.update()\n\t\t\tP = i[0]\n\t\t\tD = i[1]\n\t\t\tif D <= (self.radius + P.radius):\n\t\t\t\tz = self.Inelastic_Collision(P)\n\t\t\t\tCollision_List = [self.instance,self.name, P.name, z.name]\n\t\t\t\tsim.Collision_History.append(Collision_List)\n\t\t\t\ttry:\n\t\t\t\t\tsim.Fuse(p, P, z)\n\t\t\t\texcept ValueError:\n\t\t\t\t\tcontinue\n\t\t\t\tz.Get_Instance()\n\t\t\t\tz.Detect_Collision(z)\n\n\tdef Update_Position(self):\n\t\tself.x += self.xvel * sim.Iteration_Rate\n\t\tself.y += self.yvel * sim.Iteration_Rate\n\n\tdef Get_Instance(self):\n\t\tself.instance = sim.Current_Instance\n\nclass Data_Base():\n\tdef __init__(self):\n\t\tsim.DB = sqlite3.Connection(\"\")\n\t\tself.createDB(sim.DB)\n\tdef Open_DB(self):\n\t\tDB_fh = tkFileDialog.askopenfilename(parent=root,title=\"Open Database...\")\n\t\tsim.DB = sqlite3.Connection(DB_fh)\n\tdef createDB(self,db):\n\t\tParticleTable = \"\"\"\nCREATE TABLE IF NOT EXISTS particle (\n iteration NUMERIC,\n name NUMERIC,\n mass NUMERIC,\n xpos NUMERIC,\n ypos NUMERIC,\n xvel NUMERIC,\n yvel NUMERIC,\n xaccel NUMERIC,\n yaccel NUMERIC\n);\"\"\"\n\t\tCollisionTable = \"\"\"\nCREATE TABLE IF NOT EXISTS collision (\n parent_a NUMERIC,\n parent_b NUMERIC,\n child NUMERIC,\n iteration NUMERIC\n);\"\"\"\n\t\tcur = db.cursor()\n\t\tcur.execute(ParticleTable)\n\t\tcur.execute(CollisionTable)\n\tdef loadData(self,db):\n\t\tPCSV = tkFileDialog.askopenfilename(parent=root,title=\"Open Particle CSV...\")\n\t\tFCSV = tkFileDialog.askopenfilename(parent=root,title=\"Open Collision CSV...\")\n\t\tPFile = csv.reader(open(PCSV))\n\t\tdataIter = (i for i in PFile)\n\t\tdataIter.next() #skip header\n\t\tcur = db.cursor()\n\t\tcur.executemany(\"INSERT INTO particle VALUES (?,?,?,?,?,?,?,?,?)\", dataIter)\n\t\tCFile = csv.reader(open(FCSV))\n\t\tdataIter = (i for i in CFile)\n\t\tdataIter.next() #skip header\n\t\tcur.executemany(\"INSERT INTO collision VALUES (?,?,?,?)\", dataIter)\n\t\tcur.execute('CREATE INDEX IF NOT EXISTS ParticleIDX1 ON particle(name)')\n\t\tcur.execute('CREATE INDEX IF NOT EXISTS ParticleIDX2 ON\tparticle(iteration)')\n\t\tcur.execute('CREATE INDEX IF NOT EXISTS ParticleIDX3 ON\tparticle(xvel)')\n\t\tcur.execute('CREATE INDEX IF NOT EXISTS ParticleIDX4 ON\tparticle(yvel)')\n\t\tcur.execute('CREATE INDEX IF NOT EXISTS ParticleIDX5 ON\tparticle(xaccel)')\n\t\tcur.execute('CREATE INDEX IF NOT EXISTS ParticleIDX6 ON\tparticle(yaccel)')\n\n\tdef Make_DB(self):\n\t\tDB_fh = tkFileDialog.asksaveasfilename(parent=root,title=\"Save the Database as...\")\n\t\tsim.DB = sqlite3.Connection(DB_fh)\n\t\tself.createDB(sim.DB)\n\t\tself.loadData(sim.DB)\n\nDB = Data_Base()\n\nclass Status_Bar:\n\tdef __init__(self, master,iteration,num):\n\t\tself.label = Label(master, text=\"Iteration: %f\" %(iteration), bd=1, relief=SUNKEN, anchor=SE)\n\t\tself.label2 = Label(master, text=\"Active Particles: %d\" %(num), bd=1,relief=SUNKEN, anchor=SE)\n\t\tself.label.pack(side=RIGHT,padx=5)\n\t\tself.label2.pack(side=LEFT,padx=5)\n\n\tdef update(self):\n\t\titeration = sim.Current_Instance\n\t\tself.label.config(text='Iteration: %f' %(round(iteration,2)))\n\t\tsim.Active_Particles = len(sim.Particle_List)\n\t\tself.label2.config(text='Active Particles: %d' %(sim.Active_Particles))\n\t\tself.label.update_idletasks()\n\t\tself.label2.update_idletasks()\n\nclass Main_Window:\n\tdef __init__(self, root):\n\t\troot.wm_title(\"Gravity Simulator\")\n\t\tmenubar = Menu(root)\n\t\t\n\t\tplaymenu = Menu(menubar, tearoff=0)\n\t\tplaymenu.add_command(label=\"Run\", command=Run)\n\t\tplaymenu.add_command(label=\"Pause\", command=Pause)\n\t\tmenubar.add_cascade(label=\"Playback\", menu=playmenu)\n\n\t\tparticlemenu = Menu(menubar, tearoff=0)\n\t\tparticlemenu.add_command(label=\"Add Particle\", command=self.Make_Particle_PopUp)\n\t\tparticlemenu.add_command(label=\"Generate Particles\", command=self.Generate_Random_Particles_PopUp)\n\t\tparticlemenu.add_command(label=\"Set Iteration Rate\", command=self.Set_Iteration_Rate_PopUp)\n\t\tparticlemenu.add_command(label=\"Clear Particles\", command=sim.Clear_Particle_List)\n\t\tmenubar.add_cascade(label=\"Simulation Management\", menu=particlemenu)\n\t\t\n\t\tcsvmenu = Menu(menubar, tearoff=0)\n\t\tcsvmenu.add_command(label=\"Export to CSV\", command=sim.csvExport)\n\t\tmenubar.add_cascade(label=\"CSV Management\", menu=csvmenu)\n\n\t\tdbmenu = Menu(menubar, tearoff=0)\n\t\tdbmenu.add_command(label=\"Make and Load DB from CSV\", command=DB.Make_DB)\n\t\tdbmenu.add_command(label=\"Load DB from .db File\", command=DB.Open_DB)\n\t\tmenubar.add_cascade(label=\"Database Management\", menu=dbmenu)\n\n\t\tviewmenu = Menu(menubar, tearoff=0)\n\t\tviewmenu.add_command(label=\"Simulation Viewer\", command=Open_Simulation_Viewer)\n\t\tviewmenu.add_command(label=\"Particle Viewer\", command=Open_Particle_Viewer)\n\t\tmenubar.add_cascade(label=\"Access Database\", menu=viewmenu)\n\t\t\n\t\thelpmenu = Menu(menubar, tearoff=0)\n\t\thelpmenu.add_command(label=\"How this program works (Does Nothing)\", command=self.How_Program_Works_PopUp)\n\t\thelpmenu.add_command(label=\"How to use this program (Does Nothing)\", command=self.How_To_Use_Program_PopUp)\n\t\thelpmenu.add_command(label=\"Using Data Viewer (Does Nothing)\", command=self.Data_Viewer_PopUp)\n\t\tmenubar.add_cascade(label=\"Help\", menu=helpmenu)\n\t\t\n\t\tmenubar.add_command(label=\"About (Does Nothing)\", command=self.About_PopUp)\n\t\t\n\t\t# display the menu\n\t\troot.config(menu=menubar)\n\t\tself.space = Canvas(root, width=500, height=500, bg=\"black\")\n\t\tself.space.pack(fill=BOTH, expand=YES)\n\t\tself.status_bar = Status_Bar(root,0,0)\n\n\tdef How_Program_Works_PopUp(self):\n\t\tType = \"How_Program_Works\"\n\t\tPop_Up = Toplevel()\n\t\tDialog = PopUp_Window(Pop_Up, Type)\n\t\tPop_Up.mainloop()\n\t\t\n\tdef How_To_Use_Program_PopUp(self):\n\t\tType = \"How_To_Use_Program\"\n\t\tPop_Up = Toplevel()\n\t\tDialog = PopUp_Window(Pop_Up, Type)\n\t\tPop_Up.mainloop()\n\t\t\n\tdef Data_Viewer_PopUp(self):\n\t\tType = \"Data_Viewer\"\n\t\tPop_Up = Toplevel()\n\t\tDialog = PopUp_Window(Pop_Up, Type)\n\t\tPop_Up.mainloop()\n\t\t\n\tdef About_PopUp(self):\n\t\tType = \"About\"\n\t\tPop_Up = Toplevel()\n\t\tDialog = PopUp_Window(Pop_Up, Type)\n\t\tPop_Up.mainloop()\n\t\t\n\tdef Make_Particle_PopUp(self):\n\t\tType = \"Make_Particle\"\n\t\tPop_Up = Toplevel()\n\t\tDialog = PopUp_Window(Pop_Up, Type)\n\t\tPop_Up.mainloop()\n\t\t\n\tdef Generate_Random_Particles_PopUp(self):\n\t\tType = \"Generate_Random_Particles\"\n\t\tPop_Up = Toplevel()\n\t\tDialog = PopUp_Window(Pop_Up, Type)\n\t\tPop_Up.mainloop()\n\t\n\tdef Set_Iteration_Rate_PopUp(self):\n\t\tType = \"Set_Iteration_Rate\"\n\t\tPop_Up = Toplevel()\n\t\tDialog = PopUp_Window(Pop_Up, Type)\n\t\tPop_Up.mainloop()\n\nclass PopUp_Window:\t\n\n\tdef __init__(self, master, PopUp_Type):\n\t\tself.PopUp_Type = PopUp_Type\n\t\tself.master = master\n\t\tself.g = []\n\t\tself.z = []\n\t\tself.b = \"\"\n\t\t\n\t\tif PopUp_Type is \"Set_Iteration_Rate\":\n\t\t\tself.z = [\"Iteration Rate: \"]\n\t\t\tself.IR = DoubleVar()\n\t\t\tself.g = [self.IR]\n\t\t\tself.b = \"Set!\"\n\t\t\tfor i in self.z:\n\t\t\t\tPos_in_List = self.z.index(i)\n\t\t\t\tLabel(master, text=self.z[Pos_in_List]).grid(row=Pos_in_List, sticky=W)\n\t\t\t\tEntry(master, textvariable=self.g[Pos_in_List]).grid(row=Pos_in_List, column=1)\n\t\t\t\t\n\t\t\tMake_Button = Tkinter.Button(self.master, text=self.b, command=self.getAttributes).grid(row=7)\n\t\n\t\telif PopUp_Type is \"Make_Particle\":\n\t\t\tself.z = [\"X - Coordinate: \",\n\t\t\t \"Y - Coordinate: \",\n\t\t\t \"X - Velocity: \",\n\t\t\t \"Y - Velocity: \",\n\t\t\t \"Mass: \"]\n\n\t\t\tself.x = DoubleVar()\n\t\t\tself.y = DoubleVar()\n\t\t\tself.xvel = DoubleVar()\n\t\t\tself.yvel = DoubleVar()\n\t\t\tself.mass = DoubleVar()\n\t\t\t\n\t\t\tself.g = [self.x, self.y, self.xvel, self.yvel, self.mass]\n\t\t\tself.b = \"Make!\"\n\t\t\tfor i in self.z:\n\t\t\t\tPos_in_List = self.z.index(i)\n\t\t\t\tLabel(master, text=self.z[Pos_in_List]).grid(row=Pos_in_List, sticky=W)\n\t\t\t\tEntry(master, textvariable=self.g[Pos_in_List]).grid(row=Pos_in_List, column=1)\n\t\t\t\t\n\t\t\tMake_Button = Tkinter.Button(self.master, text=self.b, command=self.getAttributes).grid(row=7)\n\t\t\n\t\telif PopUp_Type is \"Generate_Random_Particles\":\n\t\t\tself.z = [\"# of Particles: \",\n\t\t\t \"Lowest Mass: \",\n\t\t\t \"Highest Mass: \",\n\t\t\t \"Lowest Initial X\",\n\t\t\t \"Highest Initial X: \",\n\t\t\t \"Lowest Initial Y\",\n\t\t\t \"Highest Initial Y\", \"Min Xvel\",\"Max Xvel\",\"Min Yvel\",\"Max Yvel\"]\n\t\t\tself.n = IntVar()\n\t\t\tself.MinMass = DoubleVar()\n\t\t\tself.MaxMass = DoubleVar()\n\t\t\tself.MinX = DoubleVar()\n\t\t\tself.MaxX = DoubleVar()\n\t\t\tself.MinY = DoubleVar()\n\t\t\tself.MaxY = DoubleVar()\n\t\t\tself.MinXvel = DoubleVar()\n\t\t\tself.MaxXvel = DoubleVar()\n\t\t\tself.MinYvel = DoubleVar()\n\t\t\tself.MaxYvel = DoubleVar()\n\t\t\t\n\t\t\tself.g = [self.n, self.MinMass, self.MaxMass, self.MinX, self.MaxX, self.MinY, self.MaxY, self.MinXvel, self.MaxXvel, self.MinYvel, self.MaxYvel]\n\t\t\tself.b = \"Make!\"\n\t\t\tfor i in self.z:\n\t\t\t\tPos_in_List = self.z.index(i)\n\t\t\t\tLabel(master, text=self.z[Pos_in_List]).grid(row=Pos_in_List, sticky=W)\n\t\t\t\tEntry(master, textvariable=self.g[Pos_in_List]).grid(row=Pos_in_List, column=1)\n\t\t\tMake_Button = Tkinter.Button(self.master, text=self.b, command=self.getAttributes).grid(row=11)\n\t\t\t\n\t\telif PopUp_Type is \"How_Program_Works\":\n\t\t\tpass\n\t\t\n\t\telif PopUp_Type is \"How_To_Use_Program\":\n\t\t\tpass\n\n\t\telif PopUp_Type is \"Data_Viewer\":\n\t\t\tpass\n\n\t\telif PopUp_Type is \"About\":\n\t\t\tpass\n\t\t\n\tdef getAttributes(self):\n\t\tif self.PopUp_Type is \"Set_Iteration_Rate\":\n\t\t\tsim.Iteration_Rate = self.IR.get()\n\t\t\tself.master.destroy()\n\t\n\t\telif self.PopUp_Type is \"Make_Particle\":\n\t\t\tx = self.x.get()\n\t\t\ty = self.y.get()\n\t\t\txvel = self.xvel.get()\n\t\t\tyvel = self.yvel.get()\n\t\t\tmass = self.mass.get()\n\t\t\tnewParticle = Particle(x,y,xvel,yvel,mass)\n\t\t\tsim.Particle_List.append(newParticle)\n\t\t\tUniverse.space.create_oval(newParticle.x0, newParticle.y0,newParticle.x1,newParticle.y1, fill=\"white\")\n\t\t\tUniverse.status_bar.update()\n\t\t\tUniverse.space.update()\n\t\t\tself.master.destroy()\n\t\t\n\t\telif self.PopUp_Type is \"Generate_Random_Particles\":\n\t\t\tn = self.n.get()\n\t\t\tMinMass = self.MinMass.get()\n\t\t\tMaxMass = self.MaxMass.get()\n\t\t\tMinX = self.MinX.get()\n\t\t\tMaxX = self.MaxX.get()\n\t\t\tMinY = self.MinY.get()\n\t\t\tMaxY = self.MaxY.get()\n\t\t\tMinXvel = self.MinXvel.get()\n\t\t\tMaxXvel = self.MaxXvel.get()\n\t\t\tMinYvel = self.MinYvel.get()\n\t\t\tMaxYvel = self.MaxYvel.get()\n\t\t\tself.master.destroy()\n\t\t\tfor i in range(n):\n\t\t\t\tp = Particle(uniform(MinX, MaxX), (uniform(MinY, MaxY)), randint(-1,1)*(uniform(MinXvel,MaxXvel)),randint(-1,1)*(uniform(MinYvel,MaxYvel)),uniform(MinMass,MaxMass))\n\t\t\t\tsim.Particle_List.append(p)\n\t\t\t\tUniverse.space.create_oval(p.x0, p.y0, p.x1, p.y1, fill=\"white\")\n\t\t\t\tUniverse.space.update()\n\t\t\t\tUniverse.status_bar.update()\n\t\t\tfor p in sim.Particle_List:\n\t\t\t\tUniverse.status_bar.update()\n\t\t\t\tOther_List = p.Get_Other_Particles()\n\t\t\t\tfor o in Other_List:\n\t\t\t\t\txdiff = float(p.x - o.x)\n\t\t\t\t\tydiff = float(p.y - o.y)\n\t\t\t\t\tDistance = abs(math.sqrt((xdiff**2)+(ydiff**2)))\n\t\t\t\t\tif Distance < ((p.radius * 2) + (o.radius * 2)):\n\t\t\t\t\t\tp.distance_list.append((o,Distance))\n\t\t\t\t\telse:\n\t\t\t\t\t\tcontinue\n\t\t\t\tp.Detect_Collision(p)\n\nclass Particle_Data_Viewer:\n\tdef __init__(self,p):\n\t\tself.p = p\n\t\tQUERY = Particle_Queries(self.p)\n\t\t\n\t\tself.D_Viewer = Toplevel()\n\t\tself.D_Viewer.wm_title(\"Particle Data Viewer\")\n\t\tFig_1 = Figure(figsize=(8,4), dpi=75)\n\t\tGraph_1 = Fig_1.add_subplot(1.05,1,1)\n\t\tGraph_1.plot(QUERY.Vel_Graph)\n\t\tGraph_1.set_title('Velocity Per Iteration')\n\t\tGraph_1.set_xlabel('Iteration #')\n\t\tGraph_1.set_ylabel('Velocity')\n\t\tcanvas = FigureCanvasTkAgg(Fig_1, master=self.D_Viewer)\n\t\tcanvas.show()\n\t\tcanvas.get_tk_widget().grid(row=0,column=0,sticky=W)\n\t\tcanvas._tkcanvas.grid(row=0,column=0,sticky=W)\n\t\t\n\t\tFig_2 = Figure(figsize=(8,4), dpi=75)\n\t\tGraph_2 = Fig_2.add_subplot(1.05,1,1)\n\t\tGraph_2.plot(QUERY.Accel_Graph)\n\t\tGraph_2.set_title('Acceleration Per Iteration')\n\t\tGraph_2.set_xlabel('Iteration #')\n\t\tGraph_2.set_ylabel('Acceleration')\n\t\tcanvas = FigureCanvasTkAgg(Fig_2, master=self.D_Viewer)\n\t\tcanvas.show()\n\t\tcanvas.get_tk_widget().grid(row=1,column=0,sticky=W)\n\t\tcanvas._tkcanvas.grid(row=1,column=0,sticky=W)\n\t\ttext_info = Message(self.D_Viewer, text=\"\"\"\n\t\tParticle # %d\n\t\tCreated on Iteration # %f\n\t\tRemoved on Iteration # %f \\n\n\t\tActive for %f iterations \\n\n\t\tAverage Velocity: %f\n\t\tLowest Velocity: %f\n\t\tHighest Velocity: %f\n\t\tStarting Velocity: %f\n\t\tFinal Velocity: %f \\n\n\t\tAverage Acceleration: %f\n\t\tLowest Acceleration: %f\n\t\tHighest Acceleration: %f\n\t\tStarting Acceleration: %f\n\t\tFinal Acceleration: %f \\n\n\t\tHighest X: %f\n\t\tLowest X: %f\n\t\tHighest Y: %f\n\t\tLowest Y: %f \\n\n\t\tStarting Position: (%f, %f)\n\t\tFinal Position: (%f, %f) \\n\n\t\t\"\"\"%(QUERY.Particle_Name,QUERY.birth,QUERY.death,QUERY.lifespan,\n\t\tQUERY.avg_vel,QUERY.min_vel,QUERY.max_vel,QUERY.init_vel,QUERY.final_vel,\n\t\tQUERY.avg_accel,QUERY.min_accel,QUERY.max_accel,QUERY.init_accel,QUERY.final_accel,\n\t\tQUERY.min_x,QUERY.max_x,QUERY.min_y,QUERY.max_y,QUERY.init_x,QUERY.init_y,QUERY.final_x,QUERY.final_y))\n\t\ttext_info.grid(column=1,row=0,sticky=N,rowspan=2)\n\nclass Particle_Queries:\n\tdef __init__(self,p):\n\t\tcur = sim.DB.cursor()\n\t\tself.Particle_Name = int(p)\n\t\tself.Vel_Graph,self.avg_vel,self.min_vel,self.max_vel,self.init_vel,self.final_vel = self.QUERY_Particle_Velocities(sim.DB,p)\n\t\tself.Accel_Graph,self.avg_accel,self.min_accel,self.max_accel,self.init_accel,self.final_accel = self.QUERY_Particle_Accels(sim.DB,p)\n\t\tself.x,self.y,self.min_x,self.max_x,self.min_y,self.max_y,self.init_x,self.init_y,self.final_x,self.final_y = self.QUERY_Particle_Positions(sim.DB,p)\n\t\tself.birth,self.death,self.lifespan = self.QUERY_Particle_Iterations(sim.DB,p)\n\n\tdef Get_Particle_Data(self,db,Particle_Name,Column_Type):\n\t\tUniverse.space.update()\n\t\tUniverse.status_bar.update()\n\t\tif Column_Type is \"velocity\":\n\t\t\tCol_X = \"xvel\"\n\t\t\tCol_Y = \"yvel\"\n\t\t\tcur = db.cursor()\n\t\t\tcur.execute(\"SELECT ALL iteration,%s,%s FROM particle WHERE name = %s\" %(Col_X,Col_Y,Particle_Name))\n\t\t\tdata = cur.fetchall()\n\t\t\tdata.sort()\n\t\t\tw = [(i[1],i[2]) for i in data]\n\t\t\treturn w\n\t\telif Column_Type is \"accelleration\":\n\t\t\tCol_X = \"xaccel\"\n\t\t\tCol_Y = \"yaccel\"\n\t\t\tcur = db.cursor()\n\t\t\tcur.execute(\"SELECT ALL iteration,%s,%s FROM particle WHERE name = %s\" %(Col_X,Col_Y,Particle_Name))\n\t\t\tdata = cur.fetchall()\n\t\t\tdata.sort()\n\t\t\tw = [(i[1],i[2]) for i in data]\n\t\t\treturn w\n\t\telif Column_Type is \"position\":\n\t\t\tCol_X = \"xpos\"\n\t\t\tCol_Y = \"ypos\"\n\t\t\tcur = db.cursor()\n\t\t\tcur.execute(\"SELECT ALL iteration,%s,%s FROM particle WHERE name = %s\" %(Col_X,Col_Y,Particle_Name))\n\t\t\tdata = cur.fetchall()\n\t\t\tdata.sort()\n\t\t\tw = [(i[1],i[2]) for i in data]\n\t\t\treturn w\n\t\telif Column_Type is \"iteration\":\n\t\t\tCol_X = 'iteration'\n\t\t\tcur = db.cursor()\n\t\t\tcur.execute(\"SELECT ALL iteration FROM particle WHERE name = %s\" %(Particle_Name))\n\t\t\tdata = cur.fetchall()\n\t\t\tdata.sort()\n\t\t\treturn data\n\t\n\tdef Merge_XY(self,In_List): #get magnitude\n\t\tz = []\n\t\tfor i in In_List:\n\t\t\tx = i[0]\n\t\t\ty = i[1]\n\t\t\tmerge = math.sqrt((x * x) + (y * y))\n\t\t\tz.append(merge)\n\t\treturn z\n\t\n\tdef QUERY_Particle_Velocities(self,db,Particle_Name):\n\t\ta = self.Get_Particle_Data(db,Particle_Name,\"velocity\")\n\t\tb = self.Merge_XY(a)\t\t# List Of Velocities for Particle sorted by iteration\n\t\tc = numpy.mean(b)\t# Average Velocity of Particle\n\t\td = min(b)\t\t\t# Minimum Velocity of Particle\n\t\te = max(b)\t\t\t# Maximum Velocity of Particle\n\t\tf = b[0]\t\t\t# Initial Velcoity of Particle\n\t\tg = b\n\t\tg.reverse()\n\t\th = g[0]\t\t\t# Final Velocity of Particle\n\t\treturn (b,c,d,e,f,h)\n\t\n\tdef QUERY_Particle_Accels(self,db,Particle_Name):\n\t\ta = self.Get_Particle_Data(db,Particle_Name,'accelleration')\n\t\tb = self.Merge_XY(a)\t\t# List of accelerations for Particle sorted by iteration\n\t\tc = numpy.mean(b)\t# Average Acceleration of Particle\n\t\td = min(b)\t\t\t# Minimum Acceleration of Particle\n\t\te = max(b)\t\t\t# Maximum Acceleration of Particle\n\t\tf = b[0]\t\t\t# Initial Acceleration of Particle\n\t\tg = b\n\t\tg.reverse()\n\t\th = g[0]\t\t\t# Final Acceleration of Particle\n\t\treturn (b,c,d,e,f,h)\n\t\n\tdef QUERY_Particle_Positions(self,db,Particle_Name):\n\t\ta = self.Get_Particle_Data(db,Particle_Name,'position')\n\t\tx = [i[0] for i in a]\n\t\ty = [i[1] for i in a]\n\t\tminx = min(x)\n\t\tmaxx = max(x)\n\t\tminy = min(y)\n\t\tmaxy = max(y)\n\t\tinitx = x[0]\n\t\tinity = y[0]\n\t\tx.reverse()\n\t\ty.reverse()\n\t\tfinalx = x[0]\n\t\tfinaly = x[0]\n\t\tx.reverse()\n\t\ty.reverse()\n\t\treturn (x,y,minx,maxx,miny,maxy,initx,inity,finalx,finaly)\n\n\tdef QUERY_Particle_Iterations(self,db,Particle_Name):\n\t\ta = self.Get_Particle_Data(db,Particle_Name,'iteration')\n\t\tt = [i[0] for i in a]\n\t\tb = t[1]\n\t\tc = max(t)\n\t\td = c - b\n\t\treturn (b,c,d)\n\nclass Simulation_Data_Viewer:\n\tdef __init__(self):\n\t\tQUERY = Simulation_Queries()\n\t\tmaster = Toplevel()\n\t\tmaster.wm_title(\"Simulation Data Viewer\")\n\t\t\n\t\tFig_1 = Figure(figsize=(5,4), dpi=75)\n\t\tGraph_1 = Fig_1.add_subplot(1.25,1,1)\n\t\tGraph_1.set_title('Average Velocity Per Iteration')\n\t\tGraph_1.set_xlabel('Iteration')\n\t\tGraph_1.set_ylabel('Average Velocity')\n\n\t\tFig_2 = Figure(figsize=(5,4), dpi=75)\n\t\tGraph_2 = Fig_2.add_subplot(1.25,1,1)\n\t\tGraph_2.set_title('Average Acceleration Per Iteration')\n\t\tGraph_2.set_xlabel('Iteration')\n\t\tGraph_2.set_ylabel('Average Acceleration')\n\n\t\tFig_3 = Figure(figsize=(5,4), dpi=75)\n\t\tGraph_3 = Fig_3.add_subplot(1.25,1,1)\n\t\tGraph_3.set_title('Active Particles Per Iteration')\n\t\tGraph_3.set_xlabel('Iteration')\n\t\tGraph_3.set_ylabel('Active Particles')\n\t\t\n\t\tGraph_1.plot(QUERY.Velocity_Averages_Per_Iteration)\n\t\tcanvas1 = FigureCanvasTkAgg(Fig_1, master=master)\n\t\tcanvas1.show()\n\t\tcanvas1.get_tk_widget().grid(row=0,column=0)\n\t\tcanvas1._tkcanvas.grid(row=0,column=0)\n\t\t\n\t\tGraph_2.plot(QUERY.Acceleration_Averages_Per_Iteration)\n\t\tcanvas2 = FigureCanvasTkAgg(Fig_2, master=master)\n\t\tcanvas2.show()\n\t\tcanvas2.get_tk_widget().grid(row=0,column=1)\n\t\tcanvas2._tkcanvas.grid(row=0,column=1)\n\t\t\n\t\tGraph_3.plot(QUERY.Particles_Per_Iteration)\n\t\tcanvas3 = FigureCanvasTkAgg(Fig_3, master=master)\n\t\tcanvas3.show()\n\t\tcanvas3.get_tk_widget().grid(row=0,column=2)\n\t\tcanvas3._tkcanvas.grid(row=0,column=2)\n\t\ttext_info = Message(master, text=\"\"\"Initial Iteration #: %f\\n Final Iteration #: %f \\n Length of Simulation: %f\"\"\" %(QUERY.Init_Iter,QUERY.Final_Iter,QUERY.Sim_Length))\n\t\ttext_info.grid(row=1,column=0)\n\t\tcur = sim.DB.cursor()\n\t\tcur.execute(\"SELECT DISTINCT name FROM particle\")\n\t\tdata = cur.fetchall()\n\t\tnum = len(data)\n\t\tparticle_range = Message(master, text=\"Particle's Name's Range from 1 to %d\" %(num))\n\t\tparticle_range.grid(row=1,column=2)\n\t\tself.E1_value = DoubleVar()\n\t\tE1 = Tkinter.Entry(master, textvariable=self.E1_value).grid(row=1,column=1)\n\t\tMake_Button = Tkinter.Button(master, text='View Particle', command=self.getAttributes).grid(row=2,column=1)\n\t\t\n\tdef getAttributes(self):\n\t\tnext_particle = self.E1_value.get()\n\t\tx = int(next_particle)\n\t\tOpen_Particle_Viewer(x)\n\nclass Simulation_Queries:\n\tdef __init__(self):\n\t\tself.Iter_Iter,self.Init_Iter,self.Final_Iter,self.Sim_Length = self.Get_Simulation_Length()\n\t\tself.Particles_Per_Iteration = self.Get_Particles_Per_Iteration()\n\t\tself.Velocity_Averages_Per_Iteration = self.Get_Avg_Vel_Graph()\n\t\tself.Acceleration_Averages_Per_Iteration = self.Get_Avg_Accel_Graph()\n\n\tdef Merge_XY(self,In_List): #get magnitude\n\t\tz = []\n\t\tfor i in In_List:\n\t\t\tx = i[0]\n\t\t\ty = i[1]\n\t\t\tmerge = math.sqrt((x * x) + (y * y))\n\t\t\tz.append(merge)\n\t\treturn z\n\t\t\n\tdef Get_Simulation_Length(self):\n\t\tUniverse.space.update()\n\t\tUniverse.status_bar.update()\n\t\tcur = sim.DB.cursor()\n\t\tcur.execute(\"SELECT DISTINCT iteration FROM particle\")\n\t\td = cur.fetchall()\n\t\talpha = min(d)\n\t\tomega = max(d)\n\t\tSim_Length = omega[0] - alpha[0]\n\t\treturn (d,alpha[0],omega[0],Sim_Length)\n\n\tdef Get_Particles_Per_Iteration(self):\n\t\tUniverse.space.update()\n\t\tUniverse.status_bar.update()\n\t\tcur = sim.DB.cursor()\n\t\tParticles_Per_Iteration = []\n\t\tself.Iter_Iter.sort()\n\t\tfor i in self.Iter_Iter:\n\t\t\tcur.execute(\"SELECT DISTINCT name FROM particle WHERE iteration = %f\" %(i))\n\t\t\tnum = len(cur.fetchall())\n\t\t\tParticles_Per_Iteration.append(num)\n\t\treturn Particles_Per_Iteration\n\n\tdef Get_Avg_Vel_Graph(self):\n\t\tUniverse.space.update()\n\t\tUniverse.status_bar.update()\n\t\tcur = sim.DB.cursor()\n\t\tIter_Velocity_Averages = []\n\t\tself.Iter_Iter.sort()\n\t\tfor i in self.Iter_Iter:\n\t\t\tcur.execute(\"SELECT DISTINCT name FROM particle WHERE iteration = %f\" %(i))\n\t\t\tdata = cur.fetchall()\n\t\t\tIter_Velocities = []\n\t\t\tfor p in data:\n\t\t\t\tcur.execute(\"SELECT ALL xvel,yvel FROM particle WHERE iteration = %f AND name = %d\" %(i[0],p[0]))\n\t\t\t\td = cur.fetchall()\n\t\t\t\tVelocity = self.Merge_XY(d)\n\t\t\t\tIter_Velocities.append(float(Velocity[0]))\n\t\t\tAverage = numpy.mean(Iter_Velocities)\n\t\t\tIter_Velocity_Averages.append(Average)\n\t\treturn Iter_Velocity_Averages\n\n\tdef Get_Avg_Accel_Graph(self):\n\t\tUniverse.space.update()\n\t\tUniverse.status_bar.update()\n\t\tcur = sim.DB.cursor()\n\t\tIter_Acceleration_Averages = []\n\t\tself.Iter_Iter.sort()\n\t\tfor i in self.Iter_Iter:\n\t\t\tcur.execute(\"SELECT DISTINCT name FROM particle WHERE iteration = %f\" %(i))\n\t\t\tdata = cur.fetchall()\n\t\t\tIter_Accel = []\n\t\t\tfor p in data:\n\t\t\t\tcur.execute(\"SELECT ALL xaccel,yaccel FROM particle WHERE iteration = %f AND name = %d\" %(i[0],p[0]))\n\t\t\t\td = cur.fetchall()\n\t\t\t\tAcceleration = self.Merge_XY(d)\n\t\t\t\tIter_Accel.append(float(Acceleration[0]))\n\t\t\tAverage = numpy.mean(Iter_Accel)\n\t\t\tIter_Acceleration_Averages.append(Average)\n\t\treturn Iter_Acceleration_Averages\n\ndef Open_Simulation_Viewer():\n\tSim_Viewer = Simulation_Data_Viewer()\n\ndef Open_Particle_Viewer(p):\n\tParticle_Viewer = Particle_Data_Viewer(p)\n\ndef Run():\n\tsim.Paused = False\n\twhile sim.Paused is False:\n\t\tsim.One_Step()\n\t\tUniverse.status_bar.update()\n\t\tUniverse.space.delete(ALL)\n\t\tfor i in sim.Particle_List:\n\t\t\ti.update_bbox_coords()\n\t\t\tUniverse.space.create_oval(i.x0, i.y0, i.x1, i.y1, fill=\"white\") #change color to i.color #setl in make_particle function\n\t\tUniverse.space.update()\n\ndef Pause():\n\tsim.Paused = True\n\ndef Open_Viewer(Viewer_Type):\n\tif Viewer_Type is 'particle':\n\t\tx = Particle_Data_Viewer()\n\tif Viewer_Type is 'simulation':\n\t\tx = Simulation_Data_Viewer\n\nUniverse = Main_Window(root)\nmainloop()\n","repo_name":"jackRogers/GravitySim","sub_path":"Gravity_Project_4.0.py","file_name":"Gravity_Project_4.0.py","file_ext":"py","file_size_in_byte":30790,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"26"} +{"seq_id":"2183613302","text":"# This file is part of Pynguin.\n#\n# Pynguin is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Pynguin is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with Pynguin. If not, see .\n\n\ndef difficult_branches(a: str, x: int, y: int) -> None:\n if x == 1337:\n if y == 42:\n print(\"Yes\")\n else:\n print(\"No\")\n\n if a == \"a\":\n if y == -1:\n print(\"Maybe\")\n else:\n print(\"I don't know\")\n\n if str(x) == a:\n print(\"Can you repeat the question?\")\n","repo_name":"se2p/artifact-pynguin-ssbse2020","sub_path":"software/pynguin/tests/fixtures/examples/difficult.py","file_name":"difficult.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"26"} +{"seq_id":"7334694388","text":"import unittest\nimport pandas as pd\nimport numpy as np\nfrom stock import Stock\nfrom portfolio import Portfolio\nfrom risk_analysis import RiskAnalysisTool\n\nclass TestStock(unittest.TestCase):\n def test_stock(self):\n data = {\n \"Date\": pd.to_datetime(['2004-01-02', '2004-01-05']),\n \"Close\": [4.124000072, 4.100999832],\n \"Symbol\": ['NVO', 'NVO']\n }\n df = pd.DataFrame(data)\n\n stock = Stock('NVO', 'Novo Nordisk')\n stock.retrieve_historical_prices(df)\n\n self.assertEqual(stock.symbol, 'NVO')\n self.assertEqual(stock.name, 'Novo Nordisk')\n self.assertEqual(stock.historical_prices, df['Close'].tolist())\n self.assertEqual(stock.historical_dates, df['Date'].tolist())\n\n returns = stock.calculate_returns()\n expected_return = (df['Close'].iloc[1] - df['Close'].iloc[0]) / df['Close'].iloc[0]\n self.assertEqual(returns, [expected_return])\n\n\nclass TestPortfolio(unittest.TestCase):\n def test_portfolio(self):\n # Create a new portfolio\n portfolio = Portfolio()\n\n # Create a new stock\n stock = Stock('NVO', 'Novo Nordisk')\n stock.historical_prices = [4.124000072, 4.100999832, 4.097000122, 4.004000187]\n\n # Add the stock to the portfolio\n portfolio.add_stock(stock, 0.5)\n\n # Check that the stock was added to the portfolio\n self.assertEqual(portfolio.stocks[0], stock)\n self.assertEqual(portfolio.allocation[0], 0.5)\n\n # Remove the stock from the portfolio\n portfolio.remove_stock(stock)\n\n # Check that the portfolio is now empty\n self.assertFalse(portfolio.stocks)\n self.assertFalse(portfolio.allocation)\n \nclass TestRiskAnalysisTool(unittest.TestCase):\n def test_risk_analysis_tool(self):\n # Create a new portfolio\n portfolio = Portfolio()\n\n # Create new stocks\n stock1 = Stock('NVO', 'Novo Nordisk')\n stock1.historical_prices = [4.124000072, 4.100999832, 4.097000122, 4.004000187]\n stock2 = Stock('AAPL', 'Apple Inc.')\n stock2.historical_prices = [144.000, 147.050, 149.070, 148.500]\n\n # Mock returns for the stocks\n stock1.historical_returns = np.random.normal(0, 0.01, size=100)\n stock2.historical_returns = np.random.normal(0, 0.01, size=100)\n\n # Add the stocks to the portfolio\n portfolio.add_stock(stock1, 0.5)\n portfolio.add_stock(stock2, 0.5)\n\n # Create a new risk analysis tool\n risk_tool = RiskAnalysisTool(portfolio)\n\n # Calculate VaR and CVaR\n var = risk_tool.calculate_var(0.95)\n cvar = risk_tool.calculate_cvar(0.95)\n\n # Perform Monte Carlo simulation\n portfolio_values = risk_tool.perform_monte_carlo_simulation(10)\n\n self.assertIsInstance(var, float)\n self.assertIsInstance(cvar, float)\n self.assertEqual(len(portfolio_values), 10)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Kasperkst/stock_analysis","sub_path":"test_stock.py","file_name":"test_stock.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"73866269829","text":"#########\n# At Risk Roads Analysis_Kaitlyn Bishop.py\n# Created May 20, 2021\n#\n# Purpose: Streamlines a roads intersection analysis with stream buffer zones and a user input burn area\n#################################################################\n\n\n# imports module for ArcGIS functions and classes\nimport arcpy\n\n# Sets the current worskpace, which will need to be changed to match were the streams and roads data are located. The workspace is where data are\n# located and new feature classes will be added to. Overwritting of duplicates in the workspace is allowed.\narcpy.env.workspace = \"C:/Users/.../Default.gdb\"\narcpy.env.overwriteOutput = True\n\n# Creates variables for the streams and roadways feature classes in our workspace\nstreamsAll = \"streams\"\nroadsAll = \"roadways\"\n\n# Creates a loop statement to allow for user input and checks the input for existence \n# and that it is a polygon feature class. If these conditions are met, a prompt is given to allow the user\n# to specify the output variable name. It is noted that duplicate names will be overwritten.\nwhile True:\n print(\"Type full pathway for fire boundary feature class in Oregon. Please use forward slashes.\")\n fireBound = input()\n roadsClip = input(\"Name ouput feature to be created in environment. Take care to not create duplicate names.\")\n if arcpy.Exists(fireBound) and arcpy.da.Describe(fireBound)[\"shapeType\"] == \"Polygon\":\n print(\"Name ouput feature to be created in environment. Duplicate names will be overwritten.\")\n roadsClip = input\n break\n else:\n print(\"Feature class not found or is not polygon shapetype\")\n\n# error exception class to hold code and produce an output for the exception that occured rather\ntry:\n\n # Creates a new featureclass for the intersection of the user input fire boundary and \n # the streams layer, and displays that the process has been completed\n streamIntersect = \"fireBound_streams\"\n arcpy.Intersect_analysis([fireBound, streamsAll], streamIntersect)\n print(\"Streams clipped to fire boundary input\")\n\n # Creates new feature classes for high flow, medium flow, and low flow streams within\n # the fire boundary streams featureclass, and ensures that the selection clause is formatted\n # properly, since the fire boundaries stream featureclass is in the workspace geodatabase\n highFlow = \"high_flow_streams\"\n mediumFlow = \"medium_flow_streams\"\n lowFlow = \"low_flow_streams\"\n delimfield = arcpy.AddFieldDelimiters(streamIntersect,\"Fpasize\")\n whereHigh = delimfield + \" = 'Large'\"\n whereMedium = delimfield + \" = 'Medium'\"\n whereLow = delimfield + \" = 'Low'\"\n arcpy.Select_analysis(streamIntersect, highFlow, whereHigh)\n arcpy.Select_analysis(streamIntersect, mediumFlow, whereMedium)\n arcpy.Select_analysis(streamIntersect, lowFlow, whereLow)\n\n # Creates a 250m buffer for high flow streams, a 150m buffer for medium flow streams, \n # and a 50m buffer for low flow streams, and displays that the buffers have been created \n # for each flow type\n highBuffer = \"high_flow_streams_250m\"\n medBuffer = \"medium_flow_streams_150m\"\n lowBuffer = \"low_flow_streams_50m\"\n bufferDist_high = \"250 meters\"\n bufferDist_med = \"150 meters\"\n bufferDist_low = \"50 meters\"\n arcpy.Buffer_analysis(highFlow, highBuffer, bufferDist_high, \"\",\"\",\"ALL\")\n arcpy.Buffer_analysis(mediumFlow, medBuffer, bufferDist_med, \"\",\"\",\"ALL\")\n arcpy.Buffer_analysis(lowFlow, lowBuffer, bufferDist_low, \"\",\"\",\"ALL\")\n print(\"Buffer zones created for streams based on flow type\")\n \n # Combines all the flow buffers into a new featureclass, and displays that the buffers have been\n # unioned into one new featureclass\n unionFeatures = [highBuffer, medBuffer, lowBuffer]\n streamUnion = \"stream_buffer_areas\"\n arcpy.Union_analysis(unionFeatures, streamUnion)\n print(\"Stream buffers union created.\")\n\n # Uses the combined buffer featureclass to select and export the roadways within the buffer areas\n # into a new feature class for the high risk roadways, which was specified by the user\n arcpy.Clip_analysis(roadsAll, streamUnion, roadsClip)\n\n # Displays that our final feature class for roadways at risk from streams in the burn area\n # has been created.\n print(\"High risk roadways feature class created.\")\n\n# exception statement for when a geoprocessing tool encounters an error that prints the error message\n# rather than immediately stopping the running of the script\nexcept arcpy.ExecuteError:\n print(arcpy.GetMessages(2))\n\n# exception statement for when an error occurs that prints that an error has been encountered, not\n#not related to geoprocessed, rather than immediately stopping the running of the script\nexcept:\n print(\"A non-geoprocessing error has occured\")\n \n","repo_name":"krebishop/At-Risk-Roadways-Analysis","sub_path":"At Risk Roads Anlysis_Kaitlyn Bishop.py","file_name":"At Risk Roads Anlysis_Kaitlyn Bishop.py","file_ext":"py","file_size_in_byte":4816,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"26"} +{"seq_id":"29122115278","text":"from setuptools import setup\nimport os\nimport sys\n\n_here = os.path.abspath(os.path.dirname(__file__))\n\nif sys.version_info[0] < 3:\n with open(os.path.join(_here, \"README.rst\")) as f:\n long_description = f.read()\nelse:\n with open(os.path.join(_here, \"README.rst\"), encoding=\"utf-8\") as f:\n long_description = f.read()\n\nsetup(\n name=\"swag\",\n version=\"0.0\",\n description=(\"SWA-Gaussian repo\"),\n long_description=long_description,\n author=\"Wesley Maddox, Timur Garipov, Pavel Izmailov, Dmitry Vetrov, Andrew Gordon Wilson\",\n author_email=\"wm326@cornell.edu\",\n url=\"https://github.com/wjmaddox/swa_gaussian\",\n license=\"MPL-2.0\",\n packages=[\"swag\"],\n install_requires=[\n \"tqdm==4.26.0\",\n \"numpy>=1.14.3\",\n \"torchvision>=0.2.1\",\n \"gpytorch>=0.1.0rc4\",\n \"tabulate>=0.8.2\",\n \"scipy>=1.1.0\",\n \"setuptools>=39.1.0\",\n \"matplotlib>=2.2.2\",\n \"torch>=1.0.0\",\n \"Pillow>=5.4.1\",\n \"scikit_learn>=0.20.2\",\n ],\n include_package_data=True,\n classifiers=[\n \"Development Status :: 0\",\n \"Intended Audience :: Science/Research\",\n \"Programming Language :: Python :: 3.6\",\n ],\n)\n","repo_name":"wjmaddox/swa_gaussian","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":406,"dataset":"github-code","pt":"26"} +{"seq_id":"74441314947","text":"## saida de dados em python\n\n\"\"\"\nCOMANDO NO VISUALG COMANDO EM PYTHON\n\nescreva/escreval print\n\n\n\nTIPO PLACEHOLDER DE FORMATAÇÃO(não é mais utilizado)\n\nint %d\nfloat %f\nsrt %s\n\"\"\"\n\nx = 10\ny = 20\nprint(x)\nprint(y)\n\nx1: float\nx2 = 2.3456\nprint(\"{:.2f}\".format(x))\n\nidade: int\nsalario: float\nnome: str\nsexo: str\n\nidade = 32\nsalario = 4560.9\nnome = \"Maria Silva\"\nsexo = \"F\"\n\nprint(f\"A funcionaria {nome}, sexo {sexo}, ganha {salario: .2f} e tem {idade} anos \")\nprint(\"A funcionaria {:s}, sexo {:s}, ganha {:.2f} e tem {: d} anos \".format(nome, sexo, salario, idade))\n","repo_name":"renannrocha/LP-course","sub_path":"linguagem_Python/aulas/saidaDeDados.py","file_name":"saidaDeDados.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"33207609390","text":"import random\n\nTENTATIVAS = 20\n\nLISTA_PRIMOS = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, \n 31, 37, 41, 43, 47, 53, 59, 61, 67, \n 71, 73, 79, 83, 89, 97, 101, 103, \n 107, 109, 113, 127, 131, 137, 139, \n 149, 151, 157, 163, 167, 173, 179, \n 181, 191, 193, 197, 199, 211, 223, \n 227, 229, 233, 239, 241, 251, 257, \n 263, 269, 271, 277, 281, 283, 293, \n 307, 311, 313, 317, 331, 337, 347, 349] \n\nclass MillerRabin:\n def __init__(self) -> None:\n self.rng = random.SystemRandom()\n\n def low_level_prime(n): \n while True:\n prime_candidate = MillerRabin.random_n_bits_number(n) \n for divisor in LISTA_PRIMOS: \n if prime_candidate % divisor == 0 and divisor**2 <= prime_candidate:\n # se o candidato a primo for divisivel por um primo, ou algum primo ao quadrado\n # for menor ou igual ao candidato a primo, ele nao eh primo\n\n break\n else:\n return prime_candidate\n\n def trial_composite(round_tester, even_component, prime_candidate, max_divisions_by_two):\n # isso aqui eh um metodo auxiliar pra testar se um numero eh primo por meio do teste de primalidade do Miller-Rabin,\n # mas eu nao sei explicar nadica de nada disso, entao fica aqui a implementacao\n \n if pow(round_tester, even_component, prime_candidate) == 1: \n return False\n\n for i in range(max_divisions_by_two): \n if pow(round_tester, 2**i * even_component, prime_candidate) == prime_candidate-1: \n return False\n return True\n\n def miller_rabin(prime_candidate):\n # eu realmente nao sei explicar o metodo de miller-rabin\n\n max_divisions_by_two = 0\n even_component = prime_candidate-1\n\n while even_component % 2 == 0: \n even_component >>= 1\n max_divisions_by_two += 1\n assert(2 ** max_divisions_by_two * even_component == prime_candidate-1) \n \n for _ in range(TENTATIVAS): \n round_tester = random.randrange(2, prime_candidate) \n if MillerRabin.trial_composite(round_tester, even_component, prime_candidate, max_divisions_by_two): \n return False\n return True\n\n @staticmethod\n def random_n_bits_number(n):\n # retornando um numero aleatorio de 128 bits em dua representacao decimal\n\n return random.randrange(2 ** (n-1) + 1, 2 ** n - 1) \n \n @staticmethod\n def get_prime_n_bits(n):\n prime = 0\n while True: \n prime_candidate = MillerRabin.low_level_prime(n) \n \n if not MillerRabin.miller_rabin(prime_candidate): \n # se o candidato a primo nao passou no teste de primalidade, ele nao eh primo\n\n continue\n else:\n # se ele passar o teste de primalidade, ele eh o primeiro primo de n bits que da pra pegar\n \n prime = prime_candidate\n break\n\n return prime\n\n # Realiza um teste único de primalidade Miller-Rabin.\n def teste_unico(self, numero: int, witness: int) -> bool:\n exp = numero - 1\n rem = 0\n\n while (not exp & 1):\n # Faz um shift\n exp >>= 1\n rem += 1\n \n x = pow(witness, exp, numero)\n \n if (x == 1) or (x == numero - 1):\n return True\n \n for i in range(rem - 1):\n x = pow(x, 2, numero)\n \n if x == (numero - 1):\n return True\n \n return False\n\n # Verifica se um número é primo de acordo com o teste de Miller-Rabin.\n def eh_primo(self, number: int, k=40) -> bool:\n # Casos triviais\n if number <= 1: return False\n if number <= 3: return True\n if number % 2 == 0 or number % 3 == 0: return False\n\n for i in range(k):\n witness = self.rng.randrange(2, number - 1)\n \n if (not self.teste_unico(number, witness)): \n return False\n \n return True\n\n # Gera um número primo aleatório usando o teste de primalidade Miller-Rabin\n def gera_primo(self) -> int:\n while True:\n # Shift para ficar no range ideal de no mínimo 1024 bits.\n numero_gerado = (random.SystemRandom().randrange(1 << 1024 - 1, 1 << 1024) << 1) + 1\n \n if self.eh_primo(numero_gerado):\n return numero_gerado\n","repo_name":"kleberjr/rsa-generator-and-verifier","sub_path":"src/miller_rabin.py","file_name":"miller_rabin.py","file_ext":"py","file_size_in_byte":4648,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"26"} +{"seq_id":"32491751974","text":"import json\nimport time\nimport requests\nfrom bs4 import BeautifulSoup\nfrom options import subDataOptions, dataListOptions\nfrom crawler import extractSubData, extractDataList\nfrom utils import get_key_from_value, sanitize_filename, checkAndCreateFolder, select_file, postProcessToJson\nfrom vars import OUTPUT_FOLDER, ERRORS_FOLDER, DATABASE_FOLDER\nfrom magnetSnatcher import magnetSnatcher\n\n\ndef main():\n opt = int(\n input(\n \"\"\"\\nWelcome to X-Tractor\nThis is a simple web scraper for 1337x.to\nPlease select an option:\n1. Extract sub data from a list of pages\n2. Extract data from a list of pages\n3. Extract magnet links from generateed .json file in outputs directory\\n\"\"\"\n )\n )\n checkAndCreateFolder(OUTPUT_FOLDER)\n checkAndCreateFolder(ERRORS_FOLDER)\n checkAndCreateFolder(DATABASE_FOLDER)\n if opt == 1:\n try:\n optionNo = int(\n input(\n f\"\"\"{json.dumps(subDataOptions(), indent=4)}\\n\\nSelect Category enter the number of the selected option and press enter \"\"\"\n )\n )\n optionName = get_key_from_value(subDataOptions(), optionNo)\n if optionName is None:\n raise Exception(\"Invalid option\")\n\n start = int(input(\"Enter start page: \"))\n stop = int(input(\"Enter stop page: \"))\n if start < 1 or stop < 1 or stop < start:\n raise Exception(\"Invalid page number\")\n\n except Exception as e:\n print(\"Invalid input : \", e)\n return\n extractSubData(range(start, stop + 1), optionNo, optionName)\n elif opt == 2:\n try:\n optionNo = int(\n input(\n f\"\"\"{json.dumps(dataListOptions(), indent=4)}\\n\\nSelect Category enter the number of the selected option and press enter \"\"\"\n )\n )\n\n optionName = get_key_from_value(dataListOptions(), optionNo)\n if optionName is None:\n raise Exception(\"Invalid option\")\n start = int(input(\"Enter start page: \"))\n stop = int(input(\"Enter stop page: \"))\n if start < 1 or stop < 1 or stop < start:\n raise Exception(\"Invalid page number\")\n\n except Exception as e:\n print(\"Invalid input: \", e)\n return\n extractDataList(range(start, stop + 1), optionNo, optionName)\n elif opt == 3:\n try:\n results = []\n filePath = select_file()\n fileName = filePath.split(\"/\")[-1]\n with open(filePath, \"r\") as f:\n datas = json.load(f)\n for i,data in enumerate(datas):\n print(f\"Processing {i+1}/{len(datas)}\")\n values = magnetSnatcher(data,fileName)\n if values is not None:\n results.append(values)\n print(\"Writing to file ...\")\n fileName = f'{DATABASE_FOLDER}{fileName}'\n with open(fileName, \"a\") as f:\n json.dump(results, f)\n f.write(\"\\n\")\n except Exception as e:\n print(\"Invalid input: \", e)\n return\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"rishav-jha-mech/1377x-Extractor","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"34271224632","text":"# -*- coding: utf-8 -*-\n# __author__ = 'Gz'\nimport requests\nimport time\nimport yaml\nimport json\nimport csv\nimport os\nimport shutil\nimport time\n\nPATH = os.path.dirname(os.path.abspath(__file__))\n\n\ndef config_reader(yaml_file):\n yf = open(yaml_file)\n yx = yaml.load(yf)\n yf.close()\n return yx\n\n\nconfig = config_reader(PATH + '/../test_plan.yml')\nmaster_host = config['master_host']\ndir = str(config['dir'])\nplan = config['plan']\nduration = config['duration']\ncheck_stat_time = 1\ntry:\n os.mkdir(PATH + '/../report/' + dir)\nexcept:\n shutil.rmtree(PATH + '/../report/' + dir)\n os.mkdir(PATH + '/../report/' + dir)\n\n\nclass RunLocustTestPlant():\n def start(self, locust_count, hatch_rate):\n url = master_host + 'swarm'\n post_data = {'locust_count': locust_count, 'hatch_rate': hatch_rate}\n response = requests.post(url, data=post_data)\n return response\n\n def stop(self):\n url = master_host + 'stop'\n response = requests.get(url)\n print(response.text)\n print('测试结束-。-')\n\n def get_csv_report(self, locust_count):\n request_csv_url = master_host + 'stats/requests/csv'\n distribution_csv_url = master_host + 'stats/distribution/csv'\n response_request_csv = None\n response_distribution_csv = None\n response_request_csv = requests.get(request_csv_url)\n with open(PATH + '/../report/' + dir + '/' + str(locust_count) + '_request_report.csv', 'w') as request_f:\n print(response_request_csv.text)\n request_f.write(response_request_csv.text)\n response_distribution_csv = requests.get(distribution_csv_url)\n with open(PATH + '/../report/' + dir + '/' + str(locust_count) + '_distribution_report.csv',\n 'w') as distribution_f:\n print(response_distribution_csv.text)\n distribution_f.write(response_distribution_csv.text)\n\n def get_state(self):\n url = master_host + 'stats/requests'\n state = json.loads(requests.get(url).text)\n fail_ratio = state['fail_ratio']\n total_rps = state['total_rps']\n user_count = state['user_count']\n fail_number = 0\n for i in state['stats']:\n if i['name'] == 'Total':\n fail_number = i['num_failures']\n return {'fail_ratio': fail_ratio, 'fail_number': fail_number, 'total_rps': total_rps, 'user_count': user_count}\n\n def get_all_reports(self):\n report_dir = PATH + '/../' + dir\n csvs = os.walk(report_dir)\n files = []\n files_temp = []\n for i in csvs:\n files_temp = i[2]\n for dir_f in files_temp:\n if ('.D' not in dir_f) or ('all' not in dir_f):\n files.append(dir_f)\n distribution_first_line = ['Name', '# requests', '50%', '66%', '75%', '80%', '90%', '95%', '98%', '99%', '100%']\n request_first_line = ['Method', 'Name', '# requests', '# failures', 'Median response time',\n 'Average response time',\n 'Min response time', 'Max response time', 'Average Content Size', 'Requests/s']\n distribution = []\n request = []\n if len(files) > 0:\n for i in files:\n with open(PATH + '/../' + dir + '/' + i) as f:\n csv_data = csv.reader(f)\n if 'distribution' in i:\n usr_number = i.split('_')[0]\n for h in csv_data:\n last_line = h\n distribution_temp = {}\n for g in range(len(distribution_first_line)):\n distribution_temp.update({distribution_first_line[g]: last_line[g]})\n distribution_temp.update({'User Number': usr_number})\n distribution_temp.pop('Name')\n distribution.append(distribution_temp)\n else:\n usr_number = i.split('_')[0]\n for z in csv_data:\n last_line = z\n request_temp = {}\n for g in range(len(request_first_line)):\n request_temp.update({request_first_line[g]: last_line[g]})\n request_temp.update({'User Number': usr_number})\n request_temp.pop('Method')\n request_temp.pop('Name')\n request.append(request_temp)\n else:\n assert 1 + 1 > 2, '未发现csv报告'\n distribution_report_first_line = ['User Number', '# requests', '50%', '66%', '75%', '80%', '90%', '95%',\n '98%', '99%', '100%']\n request_report_first_line = ['User Number', '# requests', '# failures',\n 'Median response time',\n 'Average response time',\n 'Min response time', 'Max response time', 'Average Content Size', 'Requests/s']\n with open(PATH + '/../' + dir + '/' + 'distribution_all_report.csv', 'w') as distribution_report:\n dw = csv.DictWriter(distribution_report, distribution_report_first_line)\n dw.writeheader()\n for row in distribution:\n dw.writerow(row)\n with open(PATH + '/../' + dir + '/' + 'request_all_report.csv', 'w') as request_report:\n dw = csv.DictWriter(request_report, request_report_first_line)\n dw.writeheader()\n for row in request:\n dw.writerow(row)\n\n def get_false(self, locust_count):\n now_user_number = self.get_state()['user_count']\n now_fail_number = self.get_state()['fail_number']\n if int(now_fail_number) > 0:\n print('出现错误!!!!')\n time.sleep(duration)\n fail_report_name = str(locust_count) + 'fail'\n self.get_csv_report(fail_report_name)\n return False\n else:\n return now_user_number\n\n def run_test(self, locust_count, hatch_rate, duration):\n start = self.start(locust_count, hatch_rate)\n if json.loads(start.text)['success']:\n while True:\n now_user_number = self.get_false(locust_count)\n if str(now_user_number) == 'False':\n return False\n else:\n if now_user_number >= locust_count:\n time.sleep(duration)\n self.get_csv_report(locust_count)\n return True\n else:\n time.sleep(check_stat_time)\n else:\n print(str(locust_count) + '启动失败!')\n\n def run_plan(self):\n for i in plan:\n plan_locust_count = i['locust_count']\n plan_hatch_rate = i['hatch_rate']\n print('执行用户数为' + str(plan_locust_count) + '的测试')\n test = self.run_test(plan_locust_count, plan_hatch_rate, duration)\n if test is False:\n print(test)\n print('在用户数为' + str(plan_locust_count) + '时出现错误')\n break\n self.stop()\n self.get_all_reports()\n\n\n","repo_name":"ZhaoGuan/gz_locust","sub_path":"basics_function/test_plant.py","file_name":"test_plant.py","file_ext":"py","file_size_in_byte":7315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"9272105023","text":"def is_isogram(string):\n D = {}\n for i in range(0, len(string)):\n letter = string[i].lower()\n if letter in D:\n return False\n else:\n D[letter] = True\n D[letter] = 1\n\n return True\n","repo_name":"RandomSeeded/pythonToys","sub_path":"isogram.py","file_name":"isogram.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"26"} +{"seq_id":"615152396","text":"import sys\nimport copy\nimport app.setup\n\ndef isSafeFloodFill(v):\n return v == '.' or v == 'O' or v == '*'\n\n\ndef floodfill(pos, grid, numSafe, length):\n if numSafe >= length:\n return numSafe\n\n y = pos['y'] - 1\n x = pos['x'] - 1\n if isSafeFloodFill(grid[y][x]):\n grid[y][x] = 1\n numSafe = numSafe + 1\n n = safezone(pos, grid, True)\n for i in range(len(n)):\n numSafe = floodfill(n[i], grid, numSafe, length)\n\n return numSafe\n\n# Check safe spot to go\n# beware \"* \" is part of the body\ndef isSafetoGo(v, failsafe):\n if failsafe:\n return True\n else:\n return v == '.' or v == 'O' or v == '*'\n\ndef printGridStatus(src, grid):\n up = {'x': src['x'], 'y': src['y'] - 1}\n down = {'x': src['x'], 'y': src['y'] + 1}\n right = {'x': src['x'] + 1, 'y': src['y']}\n left = {'x': src['x'] - 1, 'y': src['y']}\n print(\"==========Grid checking point===========\")\n print(\"Grid up position is: \", grid[up['y'] - 1][up['x'] - 1])\n print(\"Grid down position is: \", grid[down['y'] - 1][down['x'] - 1])\n print(\"Grid right position is: \", grid[right['y'] - 1][right['x'] - 1])\n print(\"Grid left position is: \", grid[left['y'] - 1][left['x'] - 1])\n print(\"==========Grid checking end=============\")\n\n\ndef safezone(src, grid, failsafe):\n safe = []\n up = {'x': src['x'], 'y': src['y'] + 1}\n down = {'x': src['x'], 'y': src['y'] - 1}\n right = {'x': src['x'] + 1, 'y': src['y']}\n left = {'x': src['x'] - 1, 'y': src['y']}\n\n # print(\"up: \", up)\n # print(\"down: \", down)\n # print(\"right: \", right)\n # print(\"left: \", left)\n\n\n height = len(grid)\n width = len(grid[1])\n\n # print(\"height: \", height)\n # print(\"width: \", width)\n if 0 < up['y'] <= height:\n if grid[up['y']-1][up['x']-1] == '.' or grid[up['y']-1][up['x']-1] == 'O' or grid[up['y']-1][up['x']-1] == '*':\n safe.append(up)\n\n if 0 < down['y'] <= height:\n if grid[down['y'] - 1][down['x'] - 1] == '.' or grid[down['y'] - 1][down['x'] - 1] == 'O' or grid[down['y']-1][down['x']-1] == '*':\n safe.append(down)\n\n if 0 < right['x'] <= width:\n if grid[right['y'] - 1][right['x'] - 1] == '.' or grid[right['y'] - 1][right['x'] - 1] == 'O' or grid[right['y']-1][right['x']-1] == '*':\n safe.append(right)\n\n if 0 < left['x'] <= width:\n if grid[left['y'] - 1][left['x'] - 1] == '.' or grid[left['y'] - 1][left['x'] - 1] == 'O' or grid[left['y']-1][left['x']-1] == '*':\n safe.append(left)\n\n return safe\n\n\ndef heuristic(grid, state, my_moves, enemy_moves):\n score = 0\n\n # Handle head-on-head collisions\n if state['me']['body'][0]['x'] == state['target']['body'][0]['x'] and state['me']['body'][0]['y'] == state['target']['body'][0]['y']:\n # checking size\n if len(state['me']['body']) > len(state['target']['body']):\n # I am bigger, I win\n print(\"I am bigger. Go for kill!!!!\")\n score = score + 2147483647\n elif len(state['me']['body']) <= len(state['target']['body']):\n print(\"let's run!!! I am small or same!!!!\")\n # I am smaller, I lose\n return -2147483648\n else:\n # It is a draw, we die anyways\n # It is not a bounty snake, you need to win to win\n return -2147483648\n\n\n # My win/lose condition\n if len(my_moves) == 0:\n # no more moves, I am trapped\n return -2147483648\n\n if state['me']['health'] <= 0:\n # out of health\n return -2147483648\n\n # get all the food position from current state\n food = []\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] == 'O':\n food.append({'x': j, 'y': i})\n\n floodfill_grid = copy.deepcopy(grid)\n floodfill_grid[state['me']['body'][0]['y']-1][state['me']['body'][0]['x']-1] = '.'\n floodfill_depth = (2 * len(state['me']['body'])) + len(food)\n accessible_squares = floodfill(state['me']['body'][0], floodfill_grid, 0, floodfill_depth)\n percent_accessible = accessible_squares/ float(len(grid)*len(grid[1]))\n\n # print(\"accessible_squares: \", accessible_squares)\n # print(\"percent_accessible\", percent_accessible)\n\n if accessible_squares <= len(state['me']['body']):\n # this can be a death trap\n if percent_accessible != 0:\n return -9999999 * (1 / percent_accessible)\n else:\n return -9999999\n\n if len(enemy_moves) == 0:\n # enemy have no more move\n score = score + 2147483647\n\n if state['target']['health'] <= 0:\n # enemy have no more health\n score = score + 2147483647\n\n enemy_floodfill_grid = copy.deepcopy(grid)\n enemy_floodfill_grid[state['target']['body'][0]['y']-1][state['target']['body'][0]['x']-1] = '.'\n enemy_floodfill_depth = (2 * len(state['target']['body'])) + len(food)\n enemy_accessible_squares = floodfill(state['target']['body'][0], enemy_floodfill_grid, 0, enemy_floodfill_depth)\n enemy_percent_accessible = enemy_accessible_squares / float(len(grid) * len(grid[1]))\n\n # print(\"enemy accessible_squares: \", enemy_accessible_squares)\n # print(\"enemy percent_accessible\", enemy_percent_accessible)\n\n if enemy_accessible_squares <= len(state['target']['body']):\n # target is going for death trap\n score = score + 9999999\n\n foodweight = 0\n LOW_FOOD = 5\n HUNGER_HEALTH = 60\n\n if len(food) <= LOW_FOOD:\n foodweight = 200 - (2 * state['me']['health'])\n else:\n if state['me']['health'] <= HUNGER_HEALTH or len(state['me']['body']) < 10:\n foodweight = 100 - state['me']['health']\n\n if foodweight > 0:\n for i in range(len(food)):\n d = app.setup.Util.mandis(state['me']['body'][0], food[i])\n score = score - (d * foodweight) - i\n\n # hang out near enemy head\n aggressive_weight = 100\n if len(food) <= LOW_FOOD:\n aggressive_weight = state['me']['health']\n\n killsquares = safezone(state['target']['body'][0], grid, True)\n enemy_last_direction = app.setup.Util.distance(state['target']['body'][1], state['target']['body'][0])\n for i in range(len(killsquares)):\n dist = app.setup.Util.mandis(state['me']['body'][0], killsquares[i])\n direction = app.setup.Util.distance(state['target']['body'][0], killsquares[i])\n if direction == enemy_last_direction:\n score = score - (dist * (2 * aggressive_weight))\n else:\n score = score - (dist * aggressive_weight)\n\n # avoid the edge of the board\n if (state['me']['body'][0]['x'] == 1 or\n state['me']['body'][0]['x'] == len(grid[1]) or\n state['me']['body'][0]['y'] == 1 or\n state['me']['body'][0]['y'] == len(grid)):\n score = score - 25000\n\n\n if score < 0:\n score = score * (1/percent_accessible)\n elif score > 0:\n score = score * percent_accessible\n\n # print(score)\n return score\n\nclass Algorithm:\n\n @staticmethod\n def alphabeta(grid, state, depth, alpha, beta, alphaMove, betaMove, maxPlayer, prev_grid, prev_target_move):\n\n moves = {}\n my_moves = safezone(state['me']['body'][0], grid, True)\n enemy_moves = {}\n\n # get the target moves\n if maxPlayer:\n enemy_moves = safezone(state['target']['body'][0], grid, True)\n else:\n enemy_moves = prev_target_move\n\n # True if calculating alpha at this depth, false if calculating beta\n if maxPlayer:\n moves = my_moves\n neck = state['me']['body'][1]\n if neck in moves:\n moves.remove(neck)\n print(\"my moves:\", moves)\n else:\n moves = enemy_moves\n neck = state['target']['body'][1]\n if neck in moves:\n moves.remove(neck)\n # print(\"enemy moves:\", moves)\n\n # sometime it run overtime, try 4 first (5 --> 4)\n MAX_RECURSION_DEPTH = 4\n # use getrecursionlimit to prevent runtime error\n\n if (depth == MAX_RECURSION_DEPTH\n or len(moves) == 0\n or state['me']['health'] <= 0 or state['target']['health'] <= 0\n or (state['me']['body'][0]['x'] == state['target']['body'][0]['x'] and state['me']['body'][0]['y'] == state['target']['body'][0]['y'])):\n\n\n # if depth == MAX_RECURSION_DEPTH:\n # print(\"Reach Max depth!!!\")\n # else:\n # print(\"Reach end game state\")\n\n return heuristic(grid, state, my_moves, enemy_moves), None\n\n if maxPlayer:\n for i in range(len(moves)):\n new_grid = copy.deepcopy(grid)\n new_state = copy.deepcopy(state)\n eating = False\n\n if new_grid[moves[i]['y']-1][moves[i]['x']-1] == 'O':\n eating = True\n new_state['me']['health'] = 100\n else:\n new_state['me']['health'] = new_state['me']['health'] - 1\n\n body_length = len(state['me']['body']) - 1\n if (body_length > 1 and\n (new_state['me']['body'][body_length]['x'] == new_state['me']['body'][body_length]['x'] and\n new_state['me']['body'][body_length]['y'] == new_state['me']['body'][body_length]['y'])\n ):\n pass\n else:\n new_grid[new_state['me']['body'][body_length]['y']-2][new_state['me']['body'][body_length]['x']-2] = '.'\n\n # remove the tail from the state\n new_state['me']['body'].pop()\n\n # move head in state and on grid\n if body_length > 1:\n new_grid[new_state['me']['body'][0]['y']-1][new_state['me']['body'][0]['x']-1] = '#'\n\n new_state['me']['body'].insert(0, moves[i])\n new_grid[moves[i]['y']-1][moves[i]['x']-1] = '@'\n\n # if eating, add to snake's body\n print(\"===============me info==================\")\n if eating:\n x = new_state['me']['body'][body_length]['x']\n y = new_state['me']['body'][body_length]['y']\n new_state['me']['body'].append({\"x\": x, \"y\": y})\n eating = False\n print(\"new state(ate):\", new_state['me']['body'])\n\n # mark whether tail is safe spot or not\n length = len(new_state['me']['body']) - 1\n print(\"length: \", length)\n me_x = new_state['me']['body'][length]['x']\n me_x_other = new_state['me']['body'][length-1]['x']\n me_y = new_state['me']['body'][length]['y']\n me_y_other = new_state['me']['body'][length-1]['y']\n print(\"me_x, me_x_other: \", me_x, \",\", me_x_other)\n print(\"me_y, me_y_other: \", me_y, \",\", me_y_other)\n\n if length > 1 and me_x == me_x_other and me_y == me_y_other:\n new_grid[me_x-1][me_y-1] = '#'\n app.setup.Util.printMap(new_grid)\n else:\n new_grid[me_x-1][me_y-1] = '*'\n\n print(\"=========================================\")\n # print out new map\n # app.setup.Util.printMap(new_grid)\n # print(\"Alpha moves choices: \", moves)\n\n newAlpha, tempMove = app.algorithm.Algorithm.alphabeta(new_grid, new_state, depth+1, alpha, beta, alphaMove, betaMove, False, grid, enemy_moves)\n if newAlpha > alpha:\n alpha = newAlpha\n alphaMove = moves[i]\n\n if beta <= alpha:\n break\n\n # print(\"alphaMove: \", alphaMove)\n # print(\"alpha: \", alpha)\n\n return alpha, alphaMove\n else:\n for i in range(len(moves)):\n new_grid = copy.deepcopy(grid)\n new_state = copy.deepcopy(state)\n eating = False\n\n if prev_grid[moves[i]['y']-1][moves[i]['x']-1] == 'O':\n eating = True\n new_state['target']['health'] = 100\n else:\n new_state['target']['health'] = new_state['target']['health'] - 1\n\n body_length = len(state['target']['body']) - 1\n if (body_length > 1 and\n (new_state['target']['body'][body_length]['x'] == new_state['target']['body'][body_length-1]['x'] and\n new_state['target']['body'][body_length]['y'] == new_state['target']['body'][body_length-1]['y'])\n ):\n pass\n else:\n new_grid[new_state['target']['body'][body_length]['y']-2][new_state['target']['body'][body_length]['x']-2] = '.'\n\n new_state['target']['body'].pop()\n\n if body_length > 1:\n new_grid[new_state['target']['body'][0]['y']-1][new_state['target']['body'][0]['x']-1] = '#'\n\n new_state['target']['body'].insert(0, moves[i])\n new_grid[moves[i]['y']-1][moves[i]['x']-1] = '@'\n\n print(\"===============target info=================\")\n if eating:\n x = new_state['target']['body'][body_length]['x']\n y = new_state['target']['body'][body_length]['y']\n new_state['target']['body'].append({\"x\": x, \"y\": y})\n eating = False\n print(\"new state(ate):\", new_state['target']['body'])\n\n # print(new_state)\n length = len(new_state['target']['body']) - 1\n target_x = new_state['target']['body'][length]['x']\n target_x_other = new_state['target']['body'][length-1]['x']\n target_y = new_state['target']['body'][length]['y']\n target_y_other = new_state['target']['body'][length-1]['y']\n print(\"target_x, me_x_other: \", target_x, \",\", target_x_other)\n print(\"target_y, me_y_other: \", target_y, \",\", target_y_other)\n\n if length > 1 and target_x == target_x_other and target_y == target_y_other:\n new_grid[target_x-1][target_y-1] = '#'\n app.setup.Util.printMap(new_grid)\n else:\n new_grid[target_x-1][target_y-1] = '*'\n print(\"=========================================\")\n # print out new map\n # app.setup.Util.printMap(new_grid)\n\n newBeta, tempMove = app.algorithm.Algorithm.alphabeta(new_grid, new_state, depth + 1, alpha, beta, alphaMove, betaMove, True, {}, {})\n if newBeta < beta:\n beta = newBeta\n betaMove = moves[i]\n\n if beta <= alpha:\n break\n\n # print(\"betaMove: \", betaMove)\n # print(\"beta: \", beta)\n\n return beta, betaMove\n","repo_name":"KaiChao15/battle_2020","sub_path":"app/algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":15456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"43387193342","text":"# pylint: disable-all\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nfrom replay.splitters import ColdUserRandomSplitter\nfrom tests.utils import spark\n\n\n@pytest.fixture()\ndef log():\n return pd.DataFrame(\n {\n \"user_id\": list(range(5000)),\n \"item_id\": list(range(5000)),\n \"relevance\": [1] * 5000,\n \"timestamp\": [1] * 5000,\n }\n )\n\n\n@pytest.fixture()\n@pytest.mark.usefixtures(\"spark\")\ndef log_spark(spark, log):\n return spark.createDataFrame(log)\n\n\n@pytest.mark.parametrize(\n \"dataset_type\",\n [\n pytest.param(\"log_spark\", marks=pytest.mark.spark),\n pytest.param(\"log\", marks=pytest.mark.core),\n ]\n)\ndef test_splitting(dataset_type, request):\n ratio = 0.25\n log = request.getfixturevalue(dataset_type)\n cold_user_splitter = ColdUserRandomSplitter(ratio, query_column=\"user_id\")\n cold_user_splitter.seed = 27\n train, test = cold_user_splitter.split(log)\n\n if isinstance(log, pd.DataFrame):\n test_users = test.user_id.unique()\n train_users = train.user_id.unique()\n real_ratio = len(test_users) / len(log)\n else:\n test_users = test.toPandas().user_id.unique()\n train_users = train.toPandas().user_id.unique()\n real_ratio = len(test_users) / log.count()\n\n assert not np.isin(test_users, train_users).any()\n assert np.isclose(\n real_ratio, ratio, atol=0.01\n ) # Spark weights are random ¯\\_(ツ)_/¯\n\n\ndef test_invalid_test_size():\n with pytest.raises(ValueError):\n ColdUserRandomSplitter(test_size=1.2, query_column=\"user_id\")\n","repo_name":"wowMalow/RePlay","sub_path":"tests/splitters/test_cold_user_randrom_splitter.py","file_name":"test_cold_user_randrom_splitter.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"26"} +{"seq_id":"18875160147","text":"#!/usr/bin/env python\nimport gtk, webkit\n\n#Raphael\nclass Doge():\n\n def __init__(self):\n #Create window\n self.much_window = gtk.Window()\n self.much_window.connect('destroy', lambda w: gtk.main_quit())\n self.much_window.fullscreen()\n\n self.much_window.set_title('Raphael')\n\n # Create view for webpage\n self.very_view = gtk.ScrolledWindow()\n self.such_webview = webkit.WebView()\n self.such_webview.open('http://192.168.43.212/3.html')\n self.very_view.add(self.such_webview)\n\n # Add everything and initialize\n self.raphael_container = gtk.VBox()\n self.raphael_container.pack_start(self.very_view)\n self.much_window.add(self.raphael_container)\n\n self.much_window.show_all()\n gtk.main()\n\nwow = Doge()","repo_name":"delroy2826/Programs_MasterBranch","sub_path":"Raphael.py","file_name":"Raphael.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"1422415935","text":"# -*- coding: utf-8 -*-\n# author:pross\n\nimport hashlib\nimport time\nimport xmltodict\nfrom flask import Flask, make_response, request\nimport logging\n\nfrom app.dispatch.handler import MsgDispatcher\n\napp = Flask(__name__)\napp.debug = True\n\n\n@app.route('/') # 默认网址\ndef index():\n return 'Index Page'\n\n\n@app.route('/robot', methods=['GET', 'POST'])\ndef wechat_auth(): # 处理微信请求的处理函数,get方法用于认证,post方法取得微信转发的数据\n if request.method == 'GET':\n data = request.args\n if len(data) == 0:\n return \"hello, this is handle view\"\n token = 'mywechat'\n signature = data.get('signature', '')\n timestamp = data.get('timestamp', '')\n nonce = data.get('nonce', '')\n echostr = data.get('echostr', '')\n # print(signature, timestamp, nonce, echostr)\n list = [token, timestamp, nonce]\n list.sort()\n temp = ''.join(list)\n sha1 = hashlib.sha1(temp.encode('utf-8'))\n hashcode = sha1.hexdigest()\n # print(hashcode)\n if hashcode == signature:\n return make_response(echostr)\n else:\n return \"\"\n else: # 接收消息\n xml_data = request.stream.read()\n print(xml_data)\n # 转发,解析数据\n MsgDispatcher(xml_data)\n # 解析数据\n dict_data = xmltodict.parse(xml_data)\n msg_type = dict_data['xml']['MsgType']\n print(xml_data)\n # dispatchers = handle.MsgDispatcher(xml_data)\n # data = dispatchers.dispatch()\n if msg_type == 'text':\n content = dict_data['xml']['Content']\n resp_xml = {\n 'xml': {\n 'ToUserName': dict_data['xml']['FromUserName'],\n 'FromUserName': dict_data['xml']['ToUserName'],\n 'CreateTime': int(time.time()),\n 'MsgType': 'text',\n 'Content': content,\n }\n }\n response_msg = xmltodict.unparse(resp_xml)\n print(response_msg)\n\n return response_msg\n\n\nif __name__ == '__main__':\n app.run(host=\"127.0.0.1\", port=8088)\n","repo_name":"prosscode/wechat-records-assistant","sub_path":"app/launch.py","file_name":"launch.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"15086521229","text":"from typing import List\nclass Solution:\n def searchInsert(self, nums: List[int], target: int) -> int:\n l = 0\n r = len(nums) -1\n \n while l < r:\n mid = (l+r) // 2\n if nums[mid] == target:\n return mid \n elif target > nums[mid]:\n l = mid + 1\n else:\n r = mid - 1\n\n if target == nums[l] or target < nums[l]:\n return l \n return l + 1\n\n\n\ndef main():\n array = [1]\n solution = Solution()\n print(solution.searchInsert(array, 1))\n\n\nmain()\n ","repo_name":"GGGoingdown/DS-ALG","sub_path":"Leetcode/Easy/35_search_insert_position.py","file_name":"35_search_insert_position.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"41562719675","text":"import flask\nimport util.constants as const\n\nimport util.constants as constants\nimport util.authentication as auth\nfrom flask import redirect, render_template, make_response\nfrom werkzeug.utils import secure_filename\nimport time\nimport bcrypt\n\nMONTHS={1:\"January\",2:\"Febuary\",3:\"March\",4:\"April\",5:\"May\",6:\"June\",7:\"July\",8:\"August\",9:\"September\",10:\"October\",11:\"November\",12:\"December\"}\n\ndef getAucInfo(id, conn):\n db = conn[const.DB_AUCTION]\n aucEntry = db.find_one({\"auction id\": id})\n\n if aucEntry == None:\n return {}\n else:\n return aucEntry\n #endIf\n#endDef\n\n\ndef auction_submit_response(request, conn):\n auctiondb = conn[constants.DB_AUCTION]\n form = request.form\n endTime = int(time.time() + (int(form.get('time'))*60))\n username = auth.get_user(conn)\n\n cookieName = constants.COOKIE_AUTH_TOKEN\n authToken = request.cookies.get(cookieName)\n salt = bcrypt.gensalt()\n aucID = bcrypt.hashpw((str(time.time())+authToken).encode(),salt).decode()[-10:-1]#takes the last 10 chars of the generated hash and uses that for the aucID\n print(aucID)\n aucID = aucID.replace(\"/\",\"M\").replace(\"\\\\\",\"N\")\n\n ending = time.localtime(int(endTime))\n month = MONTHS.get(ending.tm_mon,\"NULL\")\n day = str(ending.tm_mday)\n hour = str(ending.tm_hour)\n minute = str(ending.tm_min)\n seconds = str(ending.tm_sec)\n timeStr = month + \" \" + day +\", \" +hour+\":\"+minute+\":\"+seconds\n\n #The end time is a time given in seconds since the last epoch. It indicates the end time of the auction. And we can derive the seconds remaining from that.\n db_insert_dict = {\n 'title': form.get('title'),\n 'description': form.get('description'),\n 'auction id': aucID,\n 'bid': form.get('bid'),\n 'time': timeStr,\n 'timeSeconds': endTime,\n 'auction_owner': username,\n 'image': request.files.get('upload').filename,\n 'winner': \"\"\n }\n file = request.files.get('upload')\n allowed_filetype = '.' in file.filename and \\\n file.filename.split('.')[-1].lower() in constants.IMG_FILE_FORMATS\n\n if file is None or not allowed_filetype:\n return render_template('errormsg.html', msg='missing file field')\n for val in db_insert_dict.values():\n if val is None:\n return render_template('errormsg.html',\n msg='missing fields, unable to create auction')\n filename = secure_filename(file.filename)\n filename = f'{username}-{filename}'\n print('-----------filename--------', filename)\n file.save('./public/images/' + filename)\n db_insert_dict['image'] = '/images/' + filename\n\n auctiondb.insert_one(db_insert_dict)\n return redirect('/auction-add')\n\ndef auction_display_response(conn):\n auctiondb = conn[constants.DB_AUCTION]\n db_cursor = auctiondb.find({})\n display_fields = []\n for i in db_cursor:\n print(i['_id'])\n print('item in display_fields', i)\n display_fields.append(\n {'id': i.get('auction id'), 'title': i.get('title'), 'image': i.get('image'), 'description': i.get('description'), 'bid': i.get('bid'), 'winner': i.get('winner'), 'time': i.get('time')}\n )\n \n print('display_fields', display_fields)\n return display_fields\n\ndef auction_format(title, postID, description, imgPath, bid, winner, endTime):#NOT IN USE\n ending = time.localtime(int(endTime))\n month = MONTHS.get(ending.tm_mon,\"NULL\")\n day = str(ending.tm_mday)\n hour = str(ending.tm_hour)\n minute = str(ending.tm_min)\n seconds = str(ending.tm_sec)\n auctionHTML = '
'\n auctionHTML += '
';\n auctionHTML += '' + title + '';\n auctionHTML += '
';\n auctionHTML += '';\n auctionHTML += '

' + description + '

'\n auctionHTML += '

Current highest bid: ' + bid + \"

\"\n auctionHTML += '

Current leader: ' + winner + '

';\n auctionHTML += '

Auction Ends: '+ month + \" \" + day +\", \" +hour+\":\"+minute+\":\"+seconds+'

';\n auctionHTML += '' +\\\n '' +\\\n '
' +\\\n '
'\n return auctionHTML\n","repo_name":"Leslie-Archibald/PenguinProdigies","sub_path":"util/auction.py","file_name":"auction.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"69896727749","text":"import json\nimport requests\nimport yfinance as yf\n\nbudget = 1000000\n\n# Set the start and end date\nstart_date = '2023-01-01'\nend_date = '2023-02-01'\n\n# Set the ticker list\ntickerList = ['AAL', 'DAL', 'UAL', 'LUV', 'HA']\n\n# Initialize portfolio with all money in cash\nportfolio = {'cash': budget, 'stock': tickerList[0]}\n\n# dates = []\n\n# Track transactions made\ntransactions = []\n\noutput = []\n\ndates = []\n\n# Get the data for each ticker and calculate predicted price increase for each day based on open prices\ntickerData = {}\npercentChange = {}\nfor ticker in tickerList:\n data = yf.download(ticker, start_date, end_date)\n prices = []\n for x in list(data.index):\n dates.append(x.strftime(\"%Y-%m-%d\"))\n\n for price in data[\"Open\"]:\n prices.append(price)\n tickerData[ticker] = prices\n \n #array of the percent change in price for each day\n percentChange[ticker] = []\n for i in range(1, len(prices)):\n percentChange[ticker].append((prices[i] - prices[i-1]) / prices[i-1])\n \n\n# Loop through each day\n\npercentSymbol = []\n\n\nfor i in range(len(percentChange[tickerList[0]])):\n highestChange = -1\n highestChangeTicker = \"\"\n\n for ticker in tickerList:\n if percentChange[ticker][i] > highestChange:\n highestChange = percentChange[ticker][i]\n highestChangeTicker = ticker\n percentSymbol.append([highestChangeTicker, highestChange])\n # print(\"The highest change between day \" + str(i) + \" and day \" + str(i+1) + \" is \" + str(highestChange) + \" for \" + highestChangeTicker)\n \n\nprint(\"[0-1], [1-2], [2-3], ...\")\nprint(percentSymbol)\n\n# Get Start Point\ns = 0\nwhile(percentSymbol[s][1] < 0):\n s += 1\n\n# Update Output for BUY\ntemp = {}\ntemp[\"date\"] = dates[s]\ntemp[\"action\"] = \"BUY\"\ntemp[\"ticker\"] = percentSymbol[s][0]\noutput.append(temp)\n\n# x = requests.post(\"https://api.csgames2023.sandbox.croesusfin.cloud/swagger/iCroesusValidation\", json = output)\n\n# print(x)\n\nwith open('output.json', 'w') as f:\n f.write(str(output))\n","repo_name":"BorhanSaflo/CSGames2023-transaction-optimization","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"20755709553","text":"# Exercício 77: Crie um programa que tenha uma tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar, para cada palavra, quais são as suas vogais.\nlista_palavras = ('APRENDER','PROGRAMAR','LINGUAGEM','PYTHON','CURSO','GRATIS','ESTUDAR','PRATICAR','TRABALHAR','MERCADO','PROGRAMADOR','FUTURO')\nfor palavra in lista_palavras:\n print(f'\\nNa palavra {palavra} temos:',end=' ')\n for letra in palavra:\n if letra in 'AEIOU':\n print(letra.lower(),end=' ')\n \"\"\"if 'A' in palavra:\n print('a',end=' ')\n if 'E' in palavra:\n print('e',end=' ')\n if 'I' in palavra:\n print('i',end=' ')\n if 'O' in palavra:\n print('o',end=' ')\n if 'U' in palavra:\n print('u',end=' ')\"\"\"\n","repo_name":"brunamanzi/Python_ExerciciosCursoemVideo_BM","sub_path":"ex077.py","file_name":"ex077.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"28226896813","text":"import functools\nfrom typing import List\n\nimport cv2\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport trimesh.transformations as tra\nfrom torch import Tensor\n\n\nclass Camera(object):\n \"\"\"\n Simple pinhole camera model. Contains parameters for projecting from depth to xyz, and saving information about camera position for planning.\n TODO: Move this to utils/cameras.py?\n \"\"\"\n\n @staticmethod\n def from_width_height_fov(\n width: float,\n height: float,\n fov_degrees: float,\n near_val: float = 0.1,\n far_val: float = 4.0,\n ):\n \"\"\"Create a simple pinhole camera given minimal information only. Fov is in degrees\"\"\"\n horizontal_fov_rad = np.radians(fov_degrees)\n h_focal_length = width / (2 * np.tan(horizontal_fov_rad / 2))\n v_focal_length = width / (\n 2 * np.tan(horizontal_fov_rad / 2) * float(height) / width\n )\n principal_point_x = (width - 1.0) / 2\n principal_point_y = (height - 1.0) / 2\n return Camera(\n (0, 0, 0),\n (0, 0, 0, 1),\n height,\n width,\n h_focal_length,\n v_focal_length,\n principal_point_x,\n principal_point_y,\n near_val,\n far_val,\n np.eye(4),\n None,\n None,\n horizontal_fov_rad,\n )\n\n def __init__(\n self,\n pos,\n orn,\n height,\n width,\n fx,\n fy,\n px,\n py,\n near_val,\n far_val,\n pose_matrix,\n proj_matrix,\n view_matrix,\n fov,\n *args,\n **kwargs,\n ):\n self.pos = pos\n self.orn = orn\n self.height = height\n self.width = width\n self.px = px\n self.py = py\n self.fov = fov\n self.near_val = near_val\n self.far_val = far_val\n self.fx = fx\n self.fy = fy\n self.pose_matrix = pose_matrix\n self.pos = pos\n self.orn = orn\n self.K = np.array([[self.fx, 0, self.px], [0, self.fy, self.py], [0, 0, 1]])\n\n def to_dict(self):\n \"\"\"create a dictionary so that we can extract the necessary information for\n creating point clouds later on if we so desire\"\"\"\n info = {}\n info[\"pos\"] = self.pos\n info[\"orn\"] = self.orn\n info[\"height\"] = self.height\n info[\"width\"] = self.width\n info[\"near_val\"] = self.near_val\n info[\"far_val\"] = self.far_val\n info[\"proj_matrix\"] = self.proj_matrix\n info[\"view_matrix\"] = self.view_matrix\n info[\"max_depth\"] = self.max_depth\n info[\"pose_matrix\"] = self.pose_matrix\n info[\"px\"] = self.px\n info[\"py\"] = self.py\n info[\"fx\"] = self.fx\n info[\"fy\"] = self.fy\n info[\"fov\"] = self.fov\n return info\n\n def get_pose(self):\n return self.pose_matrix.copy()\n\n def depth_to_xyz(self, depth):\n \"\"\"get depth from numpy using simple pinhole self model\"\"\"\n indices = np.indices((self.height, self.width), dtype=np.float32).transpose(\n 1, 2, 0\n )\n z = depth\n # pixel indices start at top-left corner. for these equations, it starts at bottom-left\n x = (indices[:, :, 1] - self.px) * (z / self.fx)\n y = (indices[:, :, 0] - self.py) * (z / self.fy)\n # Should now be height x width x 3, after this:\n xyz = np.stack([x, y, z], axis=-1)\n return xyz\n\n def fix_depth(self, depth):\n if isinstance(depth, np.ndarray):\n depth = depth.copy()\n else:\n # Assuming it's a torch tensor instead\n depth = depth.clone()\n\n depth[depth > self.far_val] = 0\n depth[depth < self.near_val] = 0\n return depth\n\n\ndef z_from_opengl_depth(depth, camera: Camera):\n near = camera.near_val\n far = camera.far_val\n # return (2.0 * near * far) / (near + far - depth * (far - near))\n return (near * far) / (far - depth * (far - near))\n\n\n# We apply this correction to xyz when computing it in sim\n# R_CORRECTION = R1 @ R2\nT_CORRECTION = tra.euler_matrix(0, 0, np.pi / 2)\nR_CORRECTION = T_CORRECTION[:3, :3]\n\n\ndef opengl_depth_to_xyz(depth, camera: Camera):\n \"\"\"get depth from numpy using simple pinhole camera model\"\"\"\n indices = np.indices((camera.height, camera.width), dtype=np.float32).transpose(\n 1, 2, 0\n )\n z = depth\n # pixel indices start at top-left corner. for these equations, it starts at bottom-left\n # indices[..., 0] = np.flipud(indices[..., 0])\n x = (indices[:, :, 1] - camera.px) * (z / camera.fx)\n y = (indices[:, :, 0] - camera.py) * (z / camera.fy) # * -1\n # Should now be height x width x 3, after this:\n xyz = np.stack([x, y, z], axis=-1) @ R_CORRECTION\n return xyz\n\n\ndef depth_to_xyz(depth, camera: Camera):\n \"\"\"get depth from numpy using simple pinhole camera model\"\"\"\n indices = np.indices((camera.height, camera.width), dtype=np.float32).transpose(\n 1, 2, 0\n )\n z = depth\n # pixel indices start at top-left corner. for these equations, it starts at bottom-left\n x = (indices[:, :, 1] - camera.px) * (z / camera.fx)\n y = (indices[:, :, 0] - camera.py) * (z / camera.fy)\n # Should now be height x width x 3, after this:\n xyz = np.stack([x, y, z], axis=-1)\n return xyz\n\n\ndef smooth_mask(mask, kernel=None, num_iterations=3):\n \"\"\"Dilate and then erode.\n\n Arguments:\n mask: the mask to clean up\n\n Returns:\n mask: the dilated mask\n mask2: dilated, then eroded mask\n \"\"\"\n if kernel is None:\n kernel = np.ones((5, 5))\n mask = mask.astype(np.uint8)\n mask1 = cv2.dilate(mask, kernel, iterations=num_iterations)\n # second step\n mask2 = mask\n mask2 = cv2.erode(mask2, kernel, iterations=num_iterations)\n mask2 = np.bitwise_and(mask, mask2)\n return mask1, mask2\n\n\ndef rotate_image(imgs: List[np.ndarray]) -> List[np.ndarray]:\n \"\"\"stretch specific routine to flip and rotate sideways images for normal viewing\"\"\"\n imgs = [np.rot90(np.fliplr(np.flipud(x))) for x in imgs]\n return imgs\n\n\ndef build_mask(\n target: Tensor, val: float = 0.0, tol: float = 1e-3, mask_extra_radius: int = 5\n) -> Tensor:\n \"\"\"Build mask where all channels are (val - tol) <= target <= (val + tol)\n Optionally, dilate by mask_extra_radius\n\n Args:\n target (Tensor): [B, N_channels, H, W] input tensor\n val (float): Value to use for masking. Defaults to 0.0.\n tol (float): Tolerance for mask. Defaults to 1e-3.\n mask_extra_radius (int, optional): Dilate by mask_extra_radius pix . Defaults to 5.\n\n Returns:\n _type_: Mask of shape target.shape\n \"\"\"\n assert (\n target.ndim == 4\n ), f\"target should be of shape [B, N_channels, H, W], was {target.shape}\"\n if target.shape[1] == 1:\n masks = [target[:, t] for t in range(target.shape[1])]\n masks = [(t >= val - tol) & (t <= val + tol) for t in masks]\n mask = functools.reduce(lambda a, b: a & b, masks).unsqueeze(1)\n else:\n mask = (target >= val - tol) & (target <= val + tol)\n mask = 0 != F.conv2d(\n mask.float(),\n torch.ones(1, 1, mask_extra_radius, mask_extra_radius, device=mask.device),\n padding=(mask_extra_radius // 2),\n )\n return (~mask).expand_as(target)\n\n\ndef dilate_or_erode_mask(mask: Tensor, radius: int, num_iterations=1) -> Tensor:\n \"\"\"\n Dilate or erode a binary mask using a square kernel.\n\n This function either dilates or erodes a 2D binary mask based on the given radius\n and number of iterations. A positive radius value will dilate the mask, while a\n negative radius value will erode it.\n\n Parameters:\n -----------\n mask : torch.Tensor\n A 2D binary mask of shape (H, W), where H is the height and W is the width.\n The dtype must be torch.bool.\n radius : int\n The radius of the square kernel used for dilation or erosion. A positive value\n will dilate the mask, while a negative value will erode it.\n num_iterations : int, optional\n The number of times the dilation or erosion operation should be applied.\n Default is 1.\n\n Returns:\n --------\n Tensor : torch.Tensor\n A dilated or eroded 2D binary mask of the same shape as the input mask.\n\n Raises:\n -------\n AssertionError\n If the dtype of the input mask is not torch.bool.\n\n Example:\n --------\n >>> mask = torch.tensor([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype=torch.bool)\n >>> dilated_mask = dilate_or_erode_mask(mask, radius=1)\n >>> eroded_mask = dilate_or_erode_mask(mask, radius=-1)\n\n \"\"\"\n assert mask.dtype == torch.bool, mask.dtype\n abs_radius = abs(radius)\n erode = radius < 0\n if erode:\n mask = ~mask\n mask = mask.half()\n conv_kernel = torch.ones(\n (1, 1, abs_radius, abs_radius), dtype=mask.dtype, device=mask.device\n )\n for _ in range(num_iterations):\n mask = mask.half()\n mask = F.conv2d(mask, conv_kernel, padding=\"same\")\n mask = mask > 0.0\n if erode:\n mask = ~mask\n return mask\n\n\ndef get_cropped_image_with_padding(self, image, bbox, padding: float = 1.0):\n \"\"\"\n Crop an image based on a bounding box with optional padding.\n\n Given an image and a bounding box, this function returns a cropped version of\n the image. Padding can be applied to extend the area of the cropped region.\n\n Parameters:\n -----------\n image : torch.Tensor\n Input image tensor of shape (C, H, W), where C is the number of channels,\n H is the height, and W is the width.\n bbox : torch.Tensor\n A bounding box tensor of shape (2, 2), where the first row contains the\n (y, x) coordinates of the top-left corner, and the second row contains the\n (y, x) coordinates of the bottom-right corner.\n padding : float, optional\n Padding factor applied to the bounding box dimensions. Default is 1.0, which\n means no padding. A value greater than 1.0 will increase the cropped area.\n\n Returns:\n --------\n cropped_image : torch.Tensor\n The cropped image tensor of shape (C, H', W'), where H' and W' are the\n dimensions of the cropped region.\n\n Example:\n --------\n >>> image = torch.rand(3, 100, 100)\n >>> bbox = torch.tensor([[10, 20], [50, 60]])\n >>> cropped_image = get_cropped_image_with_padding(image, bbox, padding=1.2)\n\n Notes:\n ------\n The function ensures that the cropped region does not exceed the original image\n dimensions. If the padded bounding box does, it will be clipped to fit within\n the image.\n\n \"\"\"\n im_h = image.shape[1]\n im_w = image.shape[2]\n # bbox = iv.bbox\n x = bbox[0, 1]\n y = bbox[0, 0]\n w = bbox[1, 1] - x\n h = bbox[1, 0] - y\n x = 0 if (x - (padding - 1) * w / 2) < 0 else int(x - (padding - 1) * w / 2)\n y = 0 if (y - (padding - 1) * h / 2) < 0 else int(y - (padding - 1) * h / 2)\n y2 = im_h if y + int(h * padding) >= im_h else y + int(h * padding)\n x2 = im_w if x + int(w * padding) >= im_w else x + int(w * padding)\n cropped_image = image[\n :,\n y:y2,\n x:x2,\n ]\n return cropped_image\n\n\ndef interpolate_image(image: Tensor, scale_factor: float = 1.0, mode: str = \"nearest\"):\n \"\"\"\n Interpolates images by the specified scale_factor using the specific interpolation mode.\n This method uses `torch.nn.functional.interpolate` by temporarily adding batch dimension and channel dimension for 2D inputs.\n image (Tensor): image of shape [3, H, W] or [H, W]\n scale_factor (float): multiplier for spatial size\n mode: (str): algorithm for interpolation: 'nearest' (default), 'bicubic' or other interpolation modes at https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html\n \"\"\"\n\n if len(image.shape) == 2:\n image = image.unsqueeze(0)\n\n image_downsampled = (\n torch.nn.functional.interpolate(\n image.unsqueeze(0).float(),\n scale_factor=scale_factor,\n mode=mode,\n )\n .squeeze()\n .squeeze()\n .bool()\n )\n return image_downsampled\n","repo_name":"facebookresearch/home-robot","sub_path":"src/home_robot/home_robot/utils/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":12228,"program_lang":"python","lang":"en","doc_type":"code","stars":507,"dataset":"github-code","pt":"26"} +{"seq_id":"5106777251","text":"__sets = {}\n\nimport networks.vgg16\nimport networks.vgg16_convs\nimport networks.resnet50\nimport tensorflow as tf\nfrom fcn.config import cfg\n\nif cfg.TRAIN.SINGLE_FRAME:\n if cfg.NETWORK == 'VGG16':\n __sets['vgg16_convs'] = networks.vgg16_convs(cfg.INPUT, cfg.TRAIN.NUM_CLASSES, cfg.TRAIN.NUM_UNITS, cfg.TRAIN.SCALES_BASE, cfg.TRAIN.VERTEX_REG, cfg.TRAIN.TRAINABLE)\n if cfg.NETWORK == 'RESNET50':\n __sets['resnet50'] = networks.resnet50(cfg.INPUT, cfg.TRAIN.NUM_CLASSES, cfg.TRAIN.SCALES_BASE)\n if cfg.NETWORK == 'FCN8VGG':\n __sets['fcn8_vgg'] = networks.fcn8_vgg(cfg.TRAIN.NUM_CLASSES, cfg.TRAIN.MODEL_PATH)\nelse:\n __sets['vgg16'] = networks.vgg16(cfg.INPUT, cfg.TRAIN.NUM_STEPS, cfg.TRAIN.NUM_CLASSES, cfg.TRAIN.NUM_UNITS, cfg.TRAIN.SCALES_BASE)\n\ndef get_network(name):\n \"\"\"Get a network by name.\"\"\"\n if not __sets.has_key(name):\n raise KeyError('Unknown network: {}'.format(name))\n return __sets[name]\n\ndef list_networks():\n \"\"\"List all registered imdbs.\"\"\"\n return __sets.keys()\n","repo_name":"yuxng/DA-RNN","sub_path":"lib/networks/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":172,"dataset":"github-code","pt":"26"} +{"seq_id":"73095643267","text":"\"\"\"\"\"\"\nimport unittest\nimport math\nfrom tempfile import NamedTemporaryFile\nfrom decimal import Decimal\n\nfrom cookie_clicker.buildings import Building\nfrom cookie_clicker.clicker_state import ClickerState\nfrom cookie_clicker.utils import Config\n\nD = Decimal\n\n\nclass BaseFactoryTest(unittest.TestCase):\n \"\"\"\"\"\"\n\n def setUp(self):\n super(BaseFactoryTest, self).__init__()\n\n self.building_info = dict(\n Cursor=dict(cost=D(15), cps=D(str(0.1))),\n Grandma=dict(cost=D(100), cps=D(1)),\n )\n\n self.growth_factor = D(115) / 100\n\n def new_factory(self, building_info=None, **kwargs):\n self.state = ClickerState.new(building_info or self.building_info,\n **kwargs)\n return self.state.factory\n\n\nclass CreationTest(BaseFactoryTest):\n \"\"\"\"\"\"\n\n def test_creation_from_dict(self):\n factory = self.new_factory()\n\n self.assertIsNotNone(factory)\n self.assertTrue(hasattr(factory, \"buildings\"))\n\n self.assertSetEqual(\n set(factory.buildings), set(self.building_info.keys()),\n \"Buildings should be the same as in the dictionary!\")\n\n def test_creation_from_file(self):\n\n _file = NamedTemporaryFile()\n Config.dump(_file.name, self.building_info)\n\n factory = self.new_factory(_file.name)\n factory0 = self.new_factory()\n\n self.assertSetEqual(set(factory.buildings),\n set(self.building_info.keys()),\n \"Buildings should be the same as in the file!\")\n\n self.assertSetEqual(\n set(factory.buildings), set(factory0.buildings),\n \"Buildings should be the same as created from dictionary!\")\n\n\nclass BuildingTest(BaseFactoryTest):\n \"\"\"\"\"\"\n\n def setUp(self):\n super(BuildingTest, self).setUp()\n self.factory = self.new_factory(growth_factor=self.growth_factor)\n\n def test_first_build(self):\n\n building = self.factory[\"Cursor\"]\n\n self.assertIsNotNone(building,\n \"BuildingFactory.build should return something\")\n self.assertIsInstance(building, Building)\n\n self.assertEqual(building.name, \"Cursor\")\n self.assertEqual(building.cost, self.building_info[\"Cursor\"][\"cost\"])\n self.assertEqual(building.cps, self.building_info[\"Cursor\"][\"cps\"])\n\n self.state.buy(\"Cursor\")\n self.assertEqual(building.count, 1)\n\n def test_build_multiple(self):\n building0 = self.state.buy(\"Cursor\")\n building1 = self.factory[\"Cursor\"]\n\n self.assertIs(building0, building1,\n \"Should be the same building instance!\")\n\n cost_should = self.building_info[\"Cursor\"][\"cost\"] * self.growth_factor\n self.assertEqual(\n building1.cost, math.ceil(cost_should),\n \"Building must be more expensive after another build!!\")\n\n self.assertEqual(building1.cps, self.building_info[\"Cursor\"][\"cps\"],\n \"CPS must be the same after another build!\")\n\n building1 = self.state.buy(\"Cursor\")\n self.assertEqual(building1.count, 2)\n\n def test_build_not_present(self):\n\n building = self.state.buy(\"NotCursor\")\n self.assertIsNone(building,\n \"BuildingFactory.build should return something\")\n\n\nclass StateTest(BaseFactoryTest):\n \"\"\"\"\"\"\n\n def setUp(self):\n super(StateTest, self).setUp()\n self.factory = self.new_factory(growth_factor=self.growth_factor)\n\n @unittest.skip\n def test_state_init(self):\n self.assertTrue(hasattr(self.factory, \"state\"),\n \"Factory should have a state!\")\n\n self.assertIsInstance(self.factory.state, ClickerState)\n\n def test_cps_after_cursor_build(self):\n self.assertEqual(self.state.cps, 0, \"Initial CPS should be 0!\")\n\n self.state.buy(\"Cursor\")\n\n cps_should = self.building_info[\"Cursor\"][\"cps\"]\n self.assertEqual(self.state.cps, cps_should,\n f\"CPS with one Cursor should be {cps_should}!\")\n\n def test_cookies_after_cursor_build(self):\n self.assertEqual(self.state.current_cookies, 15,\n \"Initial cookies should be 15!\")\n\n self.state.buy(\"Cursor\")\n\n self.assertEqual(self.state.current_cookies, 0,\n f\"Cookies after one Cursor should be 0!\")\n\n def test_time_for_first_cursor(self):\n\n time = self.state.time_until(self.factory[\"Cursor\"])\n self.assertEqual(time, 0, \"Time for the first cursor should be 0!\")\n\n def test_time_for_next_cursor(self):\n building = self.state.buy(\"Cursor\")\n\n time = self.state.time_until(self.factory[\"Cursor\"])\n cost = building.cost\n cps = self.state.cps\n\n time_should = cost / cps\n self.assertEqual(\n time, time_should,\n f\"Time for the second cursor should be {time_should}!\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"chtheiss/cookie_clicker_simulator","sub_path":"tests/buildings/factory_tests.py","file_name":"factory_tests.py","file_ext":"py","file_size_in_byte":5014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"17576013965","text":"# Testes Unitários\nfrom unittest import TestCase, main\nfrom cliente import Cliente\nfrom item import Item\n\nclass testCliente(TestCase):\n\n def test_consolidar_compra(self):\n cliente01 = Cliente('Jorge', 'teste@gmail.com', '13245678942')\n p1 = Item('Item de Test', preco=100)\n p2 = Item('Item de Test2', preco=200)\n\n cliente01.adiciona_item(p1.make_item())\n cliente01.adiciona_item(p2.make_item())\n self.assertEqual(300, cliente01.consolidar_compra())\n \n def test_remover_item(self):\n cliente02 = Cliente('Jorge', 'teste@gmail.com', '13245678942')\n p4 = Item('Item de Test', preco=100)\n p5 = Item('Item de Test2', preco=200)\n p6 = Item('Item de Test2', preco=20)\n \n\n cliente02.adiciona_item(p4.make_item())\n cliente02.adiciona_item(p5.make_item())\n cliente02.adiciona_item(p6.make_item())\n\n cliente02.remover_item(p5.make_item())\n\n self.assertEqual(120, cliente02.consolidar_compra())\n\nclass testsItem(TestCase):\n\n def test_make_item(self):\n nome = 'Teste01'\n descricao = 'apenas um test'\n preco = 200\n\n item1 = Item('Teste01', descricao='apenas um test', preco=200)\n\n test_item = {\n 'nome': nome,\n 'descricao': descricao,\n 'preco': preco\n }\n\n self.assertDictEqual(test_item, item1.make_item())\n\nif __name__ == '__main__':\n main()","repo_name":"ThiagoNFerreira/PythonFund","sub_path":"aulas/app/e_comerce/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"26"} +{"seq_id":"35440363150","text":"import json\nfrom datetime import datetime, timedelta\nfrom sqlite3 import Row\nfrom typing import Optional\n\nfrom fastapi.param_functions import Query\nfrom pydantic import BaseModel\n\nDEFAULT_MEMPOOL_CONFIG = (\n '{\"mempool_endpoint\": \"https://mempool.space\", \"network\": \"Mainnet\"}'\n)\n\n\nclass CreateCharge(BaseModel):\n onchainwallet: str = Query(None)\n lnbitswallet: str = Query(None)\n name: str = Query(None)\n description: str = Query(...)\n webhook: str = Query(None)\n completelink: str = Query(None)\n completelinktext: str = Query(\"Back to Merchant\")\n custom_css: Optional[str]\n time: int = Query(..., ge=1)\n amount: int = Query(..., ge=1)\n zeroconf: bool = Query(False)\n extra: str = DEFAULT_MEMPOOL_CONFIG\n\n\nclass ChargeConfig(BaseModel):\n mempool_endpoint: Optional[str]\n network: Optional[str]\n webhook_success: Optional[bool] = False\n webhook_message: Optional[str]\n\n\nclass Charges(BaseModel):\n id: str\n name: Optional[str]\n description: Optional[str]\n onchainwallet: Optional[str]\n onchainaddress: Optional[str]\n lnbitswallet: Optional[str]\n payment_request: Optional[str]\n payment_hash: Optional[str]\n webhook: Optional[str]\n completelink: Optional[str]\n completelinktext: Optional[str] = \"Back to Merchant\"\n custom_css: Optional[str]\n extra: str = DEFAULT_MEMPOOL_CONFIG\n time: int\n amount: int\n zeroconf: bool\n balance: int\n pending: Optional[int] = 0\n timestamp: int\n last_accessed_at: Optional[int] = 0\n\n @classmethod\n def from_row(cls, row: Row) -> \"Charges\":\n return cls(**dict(row))\n\n @property\n def time_left(self):\n life_in_seconds = self.last_accessed_at - self.timestamp\n life_left_in_secods = self.time * 60 - life_in_seconds\n return life_left_in_secods / 60\n\n @property\n def time_elapsed(self):\n return self.time_left < 0\n\n @property\n def paid(self):\n if self.balance >= self.amount:\n return True\n else:\n return False\n\n @property\n def config(self) -> ChargeConfig:\n charge_config = json.loads(self.extra)\n return ChargeConfig(**charge_config)\n\n def must_call_webhook(self):\n return self.webhook and self.paid and self.config.webhook_success is False\n\n\nclass SatsPayThemes(BaseModel):\n css_id: str = Query(None)\n title: str = Query(None)\n custom_css: str = Query(None)\n user: Optional[str]\n\n @classmethod\n def from_row(cls, row: Row) -> \"SatsPayThemes\":\n return cls(**dict(row))\n\n\nclass WalletAccountConfig(BaseModel):\n mempool_endpoint: str\n receive_gap_limit: int\n change_gap_limit: int\n sats_denominated: bool\n network: str\n","repo_name":"lnbits/satspay","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"26"} +{"seq_id":"73003461830","text":"n = int(input())\n\ntotal = 10000\nfor i in range(n//3 + 1):\n for j in range(n//5 + 1):\n kg = 3 * i + 5 * j\n\n if kg == n and i + j < total:\n total = i + j\n\nif total == 10000:\n print(-1)\nelse:\n print(total)","repo_name":"comojin1994/Algorithm_Study","sub_path":"Uijeong/Python/Math1/2839.py","file_name":"2839.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"27595892753","text":"from decimal import Decimal, getcontext\nfrom adapters import CacheAdapter\n\n\ngetcontext().prec = 8\n\n\nclass LiquiAdapter(CacheAdapter):\n \"\"\" Exchange adapter for Liqui\n\n >>> b = LiquiAdapter()\n >>> b._get_price('btc_usd')\n 123.00\n\n \"\"\"\n def _get_price(self, pair):\n # Liqui flips, e.g. btc_gbg = gbg_btc\n pair_cut = list(pair.split('_'))\n pair = '{1}_{0}'.format(*pair_cut)\n ticker_url = 'https://api.liqui.io/api/3/ticker/' + pair\n r = self.s.get(ticker_url)\n j = r.json()\n print('liqui', j)\n if pair in j and 'last' in j[pair]:\n return Decimal(str(j[pair]['last']))\n raise Exception('error reading ticker data from liqui')\n","repo_name":"Someguy123/steem-value","sub_path":"adapters/LiquiAdapter.py","file_name":"LiquiAdapter.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"26"} +{"seq_id":"24587547430","text":"import unittest\nfrom subprocess import Popen\nfrom threading import Thread\n\n\nclass TestZlychDanychMenuGlowneTestCases(unittest.TestCase):\n def setUp(self) -> None:\n from sys import warnoptions\n if not warnoptions:\n import warnings\n warnings.simplefilter(\"ignore\", ResourceWarning)\n import FunctionGlobal\n import FunctionWrongData\n self.function_global = FunctionGlobal\n\n self.test_id = \"TS003\"\n self.the_process = self.function_global.ForSetUp().correct_main_menu_entry()\n self.the_log = \"\"\n\n self.countdown_function_1 = FunctionGlobal.CountExecution(2)\n self.countdown_function_2 = FunctionGlobal.CountExecution(2)\n self.countdown_function_3 = FunctionGlobal.CountExecution(3)\n self.blank_data_written_test_case = FunctionWrongData.BlankDataWrittenTestCase(self.the_process)\n self.meaningless_chars_test_case = FunctionWrongData.MeaninglessCharsTestCase(self.the_process)\n self.wrong_command_test_case = FunctionWrongData.WrongCommandTestCase(self.the_process)\n\n def test_zlych_danych_menu_glowne_1_czesc(self):\n self.countdown_function_1.start()\n first = True\n while not self.countdown_function_1.finished:\n if first:\n self.blank_data_written_test_case.start()\n first = False\n if self.blank_data_written_test_case.finished:\n break\n Thread.join(self=self.countdown_function_1)\n self.the_log += self.blank_data_written_test_case.this_log\n if self.blank_data_written_test_case.finished:\n self.function_global.ForTearDown().save_log_to_file(self.test_id, self.the_log)\n self.assertFalse(self.blank_data_written_test_case.finished, self.test_id + \". Nieoczekiwany komunikat zamiast braku reakcji.\")\n\n def test_zlych_danych_menu_glowne_2_czesc(self):\n self.countdown_function_2.start()\n first = True\n while not self.countdown_function_2.finished:\n if first:\n self.meaningless_chars_test_case.start()\n first = False\n if self.meaningless_chars_test_case.finished:\n break\n Thread.join(self=self.countdown_function_2)\n self.the_log += self.meaningless_chars_test_case.this_log\n if self.meaningless_chars_test_case.finished:\n self.function_global.ForTearDown().save_log_to_file(self.test_id, self.the_log)\n self.assertFalse(self.meaningless_chars_test_case.finished, self.test_id + \". Nieoczekiwany komunikat zamiast braku reakcji.\")\n\n def test_zlych_danych_menu_glowne_3_czesc(self):\n self.countdown_function_3.start()\n first = True\n while not self.countdown_function_3.finished:\n if first:\n self.wrong_command_test_case.start()\n first = False\n if self.wrong_command_test_case.finished:\n break\n Thread.join(self=self.countdown_function_3)\n self.the_log += self.wrong_command_test_case.this_log\n if not self.wrong_command_test_case.finished:\n self.function_global.ForTearDown().save_log_to_file(self.test_id, self.the_log)\n self.assertTrue(self.wrong_command_test_case.finished, self.test_id + \". Nieoczekiwana prosba o wpisanie danych.\")\n elif \"Wpisano niepoprawna\" not in self.wrong_command_test_case.this_log:\n self.the_log += self.function_global.CommonTestCases().clear_remaining_input(self.the_process)\n self.function_global.ForTearDown().save_log_to_file(self.test_id, self.the_log)\n self.assertIn(\"Wpisano niepoprawna\", self.wrong_command_test_case.this_log, self.test_id + \". Brak informacji o niepoprawnej komendzie.\")\n\n def tearDown(self) -> None:\n self.function_global.ForTearDown().close_program(self.the_process)\n self.function_global.ForTearDown().delete_pages_file()\n self.function_global = None\n self.test_id = None\n self.the_process = None\n self.the_log = None\n self.countdown_function_1 = None\n self.countdown_function_2 = None\n self.countdown_function_3 = None\n self.blank_data_written_test_case = None\n self.meaningless_chars_test_case = None\n self.wrong_command_test_case = None\n","repo_name":"jakubkuba97/TestGPWPlus","sub_path":"Testy/TestZlychDanychMenuGlowne.py","file_name":"TestZlychDanychMenuGlowne.py","file_ext":"py","file_size_in_byte":4343,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"26"} +{"seq_id":"3098606172","text":"# -*- coding:utf-8 -*-\nimport sys\ninput=sys.stdin.readline\n\ndef solution():\n N= int(input())\n d=[]\n for _ in range(N):\n age, name= map(lambda x: int(x) if x.isdigit() else x , input().split())\n d.append([name, age])\n \n # (나이)를 기준으로 정렬\n d.sort(key=lambda x:x[1])\n\n for name, age in d:\n print(age, name)\n \nif __name__=='__main__':\n solution()\n","repo_name":"algorithm2020/Algorithm_CEK","sub_path":"BOJ/10814.py","file_name":"10814.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"22787835088","text":"from string import ascii_lowercase\n\n\nclass BinaryIndexedTree:\n\n def __init__(self, n=0, init=0, data=None):\n if data is None:\n self.data = [init] * n\n else:\n self.data = list(data)\n\n self.tree = self.data_to_tree(self.data)\n self.n = len(self.data)\n if self.n == 0:\n self.pow2_le_n = 0\n else:\n self.pow2_le_n = 1 << (self.n.bit_length() - 1)\n\n @staticmethod\n def data_to_tree(data):\n n = len(data)\n tree = [0] * n\n s = [0] * (n + 1)\n for i in range(1, n + 1):\n s[i] = s[i - 1] + data[i - 1]\n tree[i - 1] = s[i] - s[i - (i & -i)]\n\n return tree\n\n def add(self, i, x):\n if i < 0 or i >= self.n:\n raise IndexError(f'{i} is out of range')\n\n self.data[i] += x\n\n i += 1\n while i <= self.n:\n self.tree[i - 1] += x\n i += (i & -i)\n\n def sum(self, right=None):\n \"\"\"sum of [0, right).\"\"\"\n if right is None:\n right = self.n\n\n i = min(right, self.n)\n s = 0\n while i > 0:\n s += self.tree[i - 1]\n i -= (i & -i)\n\n return s\n\n def interval_sum(self, left, right=None):\n \"\"\"sum of [left, right).\"\"\"\n return self.sum(right) - self.sum(left)\n\n def lower_bound(self, k):\n if k <= 0:\n return self.n\n\n idx = 0\n pow2 = self.pow2_le_n\n while pow2 > 0:\n if idx + pow2 <= self.n and self.tree[idx + pow2 - 1] < k:\n k -= self.tree[idx + pow2 - 1]\n idx += pow2\n pow2 >>= 1\n\n return idx\n\n def __len__(self):\n return self.n\n\n def __getitem__(self, i):\n return self.data[i]\n\n def __setitem__(self, i, x):\n self.add(i, x - self.data[i])\n\n def __repr__(self):\n return f'{self.__class__.__name__}(data={self.data})'\n\n\nN = int(input())\nS = input()\nQ = int(input())\n\nqueries = []\nfor _ in range(Q):\n queries.append(input().split())\n\nbits = {c: BinaryIndexedTree(N) for c in ascii_lowercase}\nfor i in range(N):\n bits[S[i]].add(i, 1)\n\nlt = BinaryIndexedTree(N - 1)\nfor i in range(N - 1):\n if S[i] > S[i + 1]:\n lt.add(i, 1)\n\ns = [c for c in S]\nfor query in queries:\n if query[0] == '1':\n x, c = query[1:]\n x = int(x) - 1\n\n if x > 0:\n prev_lt = s[x - 1] > s[x]\n curr_lt = s[x - 1] > c\n if prev_lt is not curr_lt:\n if prev_lt:\n lt.add(x - 1, -1)\n else:\n lt.add(x - 1, 1)\n\n if x < N - 1:\n prev_lt = s[x] > s[x + 1]\n curr_lt = c > s[x + 1]\n if prev_lt is not curr_lt:\n if prev_lt:\n lt.add(x, -1)\n else:\n lt.add(x, 1)\n\n bits[s[x]].add(x, -1)\n s[x] = c\n bits[c].add(x, 1)\n else:\n left, right = map(int, query[1:])\n left -= 1\n right -= 1\n\n if lt.interval_sum(left, right) > 0:\n print('No')\n continue\n\n count = {}\n min_ci = -1\n max_ci = -1\n for i, c in enumerate(ascii_lowercase):\n count[c] = bits[c].interval_sum(left, right + 1)\n if count[c] > 0:\n if min_ci == -1:\n min_ci = i\n max_ci = i\n\n min_ci += 1\n max_ci -= 1\n for i in range(min_ci, max_ci + 1):\n c = ascii_lowercase[i]\n if count[c] != bits[c].sum():\n print('No')\n break\n else:\n print('Yes')\n","repo_name":"mr4msm/pseudo_multiset","sub_path":"example/abc285_f.py","file_name":"abc285_f.py","file_ext":"py","file_size_in_byte":3666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"71260244233","text":"from typing import Union, Tuple, List, Dict, Optional\nimport os\nfrom pathlib import Path\n\nfrom sklearn import metrics\nimport matplotlib.pyplot as plt\nfrom tensorflow import keras\nimport numpy as np\n\nfrom global_utils import results_dir\n\nRESULTS_PATH = results_dir(\"12\")\n\n\ndef history_path(model: keras.Model) -> Path:\n os.makedirs(RESULTS_PATH / \"metrics\", exist_ok=True)\n return RESULTS_PATH / \"metrics\" / f\"{model.name}.npz\"\n\n\ndef save_history(model: keras.Model, history: keras.callbacks.History, overwrite: bool):\n \"\"\"Stores a model's training history\n\n Args:\n model (keras.Model): A Keras Model.\n history (keras.callbacks.History): The training history.\n overwrite (bool): Should previous history be overwritten?\n \"\"\"\n path = history_path(model)\n if overwrite or not os.path.exists(path):\n np.savez(path, **history.history)\n\n\ndef load_history(model: keras.Model) -> Optional[keras.callbacks.History]:\n \"\"\"Load a model's training history\n\n Args:\n model (keras.Model): A Keras Model.\n\n Returns:\n keras.callbacks.History: The model's training history.\n \"\"\"\n path = history_path(model)\n try:\n history = keras.callbacks.History()\n with np.load(path) as f:\n history.history = dict(f)\n history.epoch = list(range(len(history.history[\"loss\"])))\n except:\n history = None\n return history\n\n\ndef optimize_model(\n model: keras.Model,\n data: Tuple[Tuple[np.array, np.array], Tuple[np.array, np.array]],\n optimizer: Union[str, keras.optimizers.Optimizer],\n batch_size,\n starting_val_accuracy=0.0,\n verbose=0,\n max_epochs=15,\n) -> keras.callbacks.History:\n \"\"\"Evaluates the performance of a model fitted with the specified optimizer.\n It implements early stopping.\n\n Args:\n data: A tuple containing ((x_train, y_train), (x_test, y_test)) as numpy arrays.\n model (keras.Model): A Keras model. It is required to have a name.\n optimizer (Union[str, keras.optimizers.Optimizer]): A valid Keras optimizer.\n batch_size (int): The batch size used for training.\n verbose (int, optional): Verbosity of model.fit. Defaults to 0.\n max_epochs (int, optional): Maximum number of epochs. Defaults to 15.\n Returns:\n keras.callbacks.History: Fit history, complete with per-epoch validation metrics\n \"\"\"\n (x_train, y_train), (x_test, y_test) = data\n model.compile(\n loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n optimizer=optimizer,\n metrics=[\"accuracy\"],\n )\n # The model is fit with EarlyStopping on the validation accuracy, preventing it to waste time overfitting\n history = model.fit(\n x_train,\n y_train,\n epochs=max_epochs,\n batch_size=batch_size,\n shuffle=True,\n validation_data=(x_test, y_test),\n callbacks=[\n keras.callbacks.EarlyStopping(\n monitor=\"val_accuracy\",\n # Improvements <= 1e-4 in validation accuracy are considered noise\n min_delta=1e-4,\n mode=\"max\",\n # We wait 3 epochs before declaring overfitting\n patience=10,\n baseline=starting_val_accuracy,\n restore_best_weights=True,\n ),\n #  Checkpointing the model\n keras.callbacks.ModelCheckpoint(\n f'{RESULTS_PATH / \"models\" / model.name / \"{epoch:03d}-{val_accuracy:.4f}.hdf5\"}',\n monitor=\"val_accuracy\",\n save_best_only=True,\n mode=\"max\",\n verbose=min(verbose, 1),\n ),\n ],\n verbose=verbose,\n )\n return history\n\n\ndef plot_wrong_predictions(\n fig: plt.Figure,\n model: keras.Model,\n x_test: np.array,\n y_true: np.array,\n rows: int,\n cols: int,\n verbose=0,\n):\n y_predicted = np.argmax(model.predict(x_test, verbose=verbose), axis=-1)\n wrong = y_predicted != y_true\n for i, (digit_image, prediction, correct, _) in enumerate(\n zip(x_test[wrong], y_predicted[wrong],\n y_true[wrong], range(rows * cols))\n ):\n ax = fig.add_subplot(rows, cols, i + 1)\n ax.imshow(digit_image.reshape((28, 28, 1)), cmap=\"gray\")\n ax.set_title(f\"guess: {prediction} true: {correct}\")\n ax.set_axis_off()\n\n\ndef plot_fits(\n training_histories: Dict[str, keras.callbacks.History],\n axes: List[List[plt.Axes]],\n):\n \"\"\"Plots training histories on provided axes.\n\n Args:\n training_results (Dict[str, keras.callbacks.History]): Training histories.\n axes (List[List[plt.Axes]]): Matplotlib Axes. Must be a 2x2 matrix.\n \"\"\"\n axes[0, 0].set_title(\"Training\")\n axes[0, 1].set_title(\"Validation\")\n axes[1, 0].set_xlabel(\"epoch\")\n axes[1, 1].set_xlabel(\"epoch\")\n axes[0, 0].set_ylabel(\"Categorical crossentropy\")\n axes[1, 0].set_ylabel(\"Accuracy\")\n for axs, metric in zip(axes, [\"loss\", \"accuracy\"]):\n for ax, prefix in zip(axs, [\"\", \"val_\"]):\n ax.grid(which=\"both\")\n for name, history in training_histories.items():\n ax.plot(\n history.epoch,\n history.history[prefix + metric],\n label=name,\n )\n axes[1, 1].legend()\n\n\ndef plot_confusion_matrices(\n fig: plt.Figure,\n models: List[keras.Model],\n x_test: np.array,\n y_true: np.array,\n rows: int,\n cols: int,\n):\n \"\"\"Plots confusion matrices for the classifiers in model using provided data\n\n Args:\n fig (plt.Figure): A Figure object.\n models (List[keras.Model]): Keras Classifiers to be evaluated.\n x_test (np.array): Data to be classified.\n y_test (np.array): True data labels.\n rows (int): Number of rows in the resulting grid.\n cols (int): Number of columns in the resulting grid.\n \"\"\"\n fig.suptitle(\"Confusion matrices\")\n for i, model in enumerate(models):\n y_predicted = np.argmax(model.predict(x_test, verbose=0), axis=-1)\n ax = fig.add_subplot(rows, cols, i + 1)\n ax.set_title(model.name)\n metrics.ConfusionMatrixDisplay.from_predictions(\n y_true, y_predicted, ax=ax, colorbar=False\n )\n","repo_name":"dnstudent/esercizi_lsn","sub_path":"solutions/ex12/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19137400471","text":"import os\nimport typing\nfrom functools import cached_property\n\nfrom returns import returns\n\nfrom utils import convert_items\nfrom . import t\nfrom .base import JsonFileProcessor, AbstractProcessor\n\n\nclass FishProcessor(JsonFileProcessor):\n FILENAME = os.path.join('Data', 'Fish')\n\n WEATHER_SUNNY = 'sunny'\n WEATHER_RAINY = 'rainy'\n WEATHER_BOTH = 'both'\n WEATHER_MAP = {\n WEATHER_BOTH: (WEATHER_SUNNY, WEATHER_RAINY),\n }\n\n DIFFICULTY_SKIP = {'trap'}\n ID_SKIP = {\n '152', # Seaweed\n '153', # Green Algae\n '157', # White Algae\n }\n\n RESULT_KEY = 'fish'\n\n @staticmethod\n @returns(list)\n def _parse_time_ranges(value: str) -> t.Fish.TimeRanges:\n hours = convert_items(value.split(' '), int)\n for i in range(0, len(hours), 2):\n yield hours[i], hours[i + 1]\n\n @classmethod\n def _parse_weather(cls, value: str) -> t.Fish.Weathers:\n if value in cls.WEATHER_MAP:\n return cls.WEATHER_MAP[value]\n else:\n return (value,)\n\n def _parse_fish(self, id_: t.Fish.Id, value: str) -> t.Fish | None:\n # https://stardewvalleywiki.com/Modding:Fish_data#Fish_data_and_spawn_criteria\n name, difficulty, *other_fields = value.split('/')\n if difficulty in self.DIFFICULTY_SKIP:\n return\n\n (\n behavior,\n min_size, max_size,\n time_ranges,\n _,\n weather,\n _,\n max_depth,\n spawn_multi,\n depth_multi,\n min_level,\n *other_fields_2,\n ) = other_fields\n\n if self.parent.lang_code is not None:\n try:\n localized_name = other_fields_2[-1]\n except IndexError:\n localized_name = name\n else:\n localized_name = name\n\n return t.Fish(\n id=id_,\n en_name=name,\n name=localized_name,\n time_ranges=self._parse_time_ranges(time_ranges),\n weather=self._parse_weather(weather),\n min_level=int(min_level),\n max_depth=int(max_depth),\n spawn_multi=float(spawn_multi),\n depth_multi=float(depth_multi),\n behavior=behavior,\n difficulty=int(difficulty),\n size_range=(int(min_size), int(max_size)),\n )\n\n @cached_property\n @returns(dict)\n def _fish(self) -> dict[t.Fish.Id, t.Fish]:\n for fish_id, value in self._raw_data.items():\n if fish_id in self.ID_SKIP:\n continue\n fish = self._parse_fish(fish_id, value)\n if fish is None:\n continue\n yield fish_id, fish\n\n def __contains__(self, fish_id: t.Fish.Id) -> bool:\n return fish_id in self._fish\n\n @cached_property\n @returns(dict)\n def _en_name_id_map(self) -> dict[t.Fish.EnName, t.Fish.Id]:\n for fish_id, fish in self._fish.items():\n yield fish.en_name, fish_id\n\n def get_id_from_en_name(self, en_name: t.Fish.EnName) -> t.Fish.Id | None:\n return self._en_name_id_map.get(en_name)\n\n @property\n def _extend_processors(self) -> typing.Iterator['Processor']:\n from .locations import LocationProcessor\n yield self.parent.get_processor(LocationProcessor)\n from .bundles import AllBundleProcessor\n yield self.parent.get_processor(AllBundleProcessor)\n from .gifts import GiftProcessor\n yield self.parent.get_processor(GiftProcessor)\n\n def _extend(self):\n for fish in self._fish.values():\n for processor in self._extend_processors:\n processor.extend_fish(fish)\n\n @cached_property\n def _fish_extended(self) -> dict[str, t.Fish]:\n self._extend()\n return self._fish\n\n def __call__(self, result: t.Result):\n result.fish = self._fish_extended\n\n\nclass AbstractExtendFishProcessor(AbstractProcessor):\n def extend_fish(self, fish: t.Fish) -> None:\n raise NotImplementedError\n\n\nProcessor = typing.TypeVar('Processor', bound=AbstractExtendFishProcessor)\n","repo_name":"MichaelKim0407/starfish-valley","sub_path":"prepare-data/src/processors/fish.py","file_name":"fish.py","file_ext":"py","file_size_in_byte":4110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"24703462204","text":"# import basic modules required\r\nimport cv2\r\nimport os\r\nimport traceback\r\nimport numpy as np\r\n\r\n\r\n# MANUAL CONFIGURATION\r\n# ~====================~\r\n\r\n# replace this with a different\r\n# module if you want to capture your\r\n# frames from somewhere else\r\n# (such as a live feed)\r\n# make sure to include a get_frame() method!\r\nimport get_frame as get_frame\r\n\r\n# optionally upscale the image\r\n# if you're working with smaller frames\r\n# (upscaled after processing is complete)\r\nupscale_to = (1000, 600)\r\nupscale = False\r\n\r\n# show/hide error messages\r\ndisplay_error_messages = True\r\nerror_message_colour = (255, 255, 255)\r\n\r\n# pick which file to run the filter\r\n# from - this can be any python file\r\n# but make sure to include the filter\r\n# start and filter end markers!\r\nfilter_filename = 'filter.py'\r\n\r\n# ~====================~\r\n\r\n\r\n# just a default filter_image function\r\n# used so that the program doesn't crash\r\n# if there's no filter defined in the\r\n# filter file\r\ndef filter_image(image): return image\r\n\r\n\r\n# track exceptions & save the last output\r\n# image, so that we can display exceptions\r\n# to the user without spamming them over\r\n# and over in the console\r\nlast_exception = None\r\nlast_output_image = None\r\n\r\nlast_update_mtime = -1\r\n\r\nwhile 1:\r\n image = get_frame.get_frame()\r\n\r\n if last_output_image is None:\r\n last_output_image = image\r\n\r\n current_update_mtime = os.path.getmtime(filter_filename)\r\n if current_update_mtime > last_update_mtime:\r\n last_update_mtime = current_update_mtime\r\n\r\n filter_code = open(filter_filename, 'r').read().split(\r\n '# start filter', 1)[-1].split(\r\n '# end filter', 1)[0]\r\n execution_valid = True\r\n try:\r\n exec(filter_code)\r\n image_out = filter_image(image)\r\n if image_out is not None:\r\n last_output_image = image_out.copy()\r\n except Exception as e:\r\n this_exception = traceback.format_exc()\r\n if last_exception != this_exception:\r\n last_exception = this_exception\r\n print()\r\n print(\" Exception\")\r\n print(\" ~=========~\")\r\n print()\r\n print(this_exception)\r\n image_out = last_output_image\r\n execution_valid = False\r\n\r\n try:\r\n if upscale:\r\n resized_image = cv2.resize(image_out, upscale_to)\r\n else:\r\n resized_image = image_out\r\n\r\n # write some error message text onto the displayed image\r\n if not execution_valid:\r\n exception_msg = f\"{filter_filename} exception\"\r\n (w, h), b = cv2.getTextSize(exception_msg, cv2.FONT_HERSHEY_COMPLEX, 0.6, 1)\r\n cv2.rectangle(resized_image, (0, 0), (w+5, h+b+4), (0, 0, 0), -1)\r\n cv2.putText(resized_image,\r\n exception_msg, (2, 16),\r\n cv2.FONT_HERSHEY_COMPLEX, 0.6,\r\n (255, 255, 255), 1)\r\n if display_error_messages:\r\n write_lines = [x for x in last_exception.split('\\n') if x]\r\n largest_w = 5\r\n for line in write_lines:\r\n if not line:\r\n continue\r\n (w, h), b = cv2.getTextSize(\r\n line, cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.6, 1)\r\n w += 5\r\n h += 6\r\n if w > largest_w:\r\n largest_w = w\r\n cv2.rectangle(resized_image, (0, 20),\r\n (largest_w, 30+len(write_lines)*16),\r\n (0, 0, 0), -1)\r\n for index, line in enumerate(write_lines):\r\n x, y = (2, 32+16*index)\r\n cv2.putText(resized_image,\r\n line, (x, y+5),\r\n cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.6,\r\n error_message_colour, 1)\r\n\r\n cv2.imshow('Filtered Image', resized_image)\r\n\r\n except:\r\n pass\r\n\r\n if cv2.waitKey(25) & 0xFF == ord('q'):\r\n cv2.destroyAllWindows()\r\n break\r\n","repo_name":"Machine-builder/CV2-Live-Edit","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4171,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"27"} +{"seq_id":"27739060040","text":"## https://leetcode.com/problems/coin-change/\n\nclass Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n MAX = float('inf')\n dp = [0] + [MAX] * amount\n\n for i in range(1, amount + 1):\n dp[i] = min([dp[i - c] if i - c >= 0 else MAX for c in coins]) + 1\n return [dp[amount], -1][dp[amount] == MAX]\n\n\n # def minCoins(amount, coins, dp):\n # ans = float('inf')\n # for i in range(len(coins)):\n # if amount-coins[i]>=0:\n # subAns = 0\n # if dp[amount-coins[i]] != -1:\n # subAns = dp[amount-coins[i]]\n # else:\n # minCoins(amount-coins[i], coins, dp)\n # if subAns != float('inf') and subAns +1 < ans:\n # ans = subAns + 1\n # dp[amount] = ans\n # return dp[amount]\n\n # if not amount:\n # return 0\n # if not coins:\n # return -1\n # dp = [-1 for _ in range(amount+1)]\n # dp[0] = 0\n # return minCoins(amount, coins, dp)\n\n \nConsole\n","repo_name":"piyushmakhija5/leetcode_practice","sub_path":"data_structures/322_coin_change.py","file_name":"322_coin_change.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"69947210952","text":"\"\"\"Stage that loads a catalog from GCRCatalogs.\"\"\"\nimport GCRCatalogs\nimport pandas as pd\nfrom rail.creation.engine import Creator\nfrom rail.core.data import PqHandle\nfrom ceci.config import StageParameter as Param\n\n\nclass GCRCreator(Creator):\n \"\"\"Creator that returns a catalog from GCRCatalogs.\n\n For info on GCRCatalogs, see https://github.com/LSSTDESC/gcr-catalogs\n\n Parameters\n ----------\n gcr_root_dir : str, default=\"/global/cfs/cdirs/lsst/shared\"\n The path to the GCR Catalogs.\n catalog_name : str, default=\"cosmoDC2_v1.1.4_small\"\n The name of the GCR catalog to load. See https://github.com/LSSTDESC/gcr-catalogs/blob/master/examples/GCRCatalogs%20Demo.ipynb for how to get available options.\n quantities : list, default=[redshift, mag_u_lsst, mag_g_lsst, ..., size_true, size_minor_true]\n The quantities to query from the catalog. See https://github.com/LSSTDESC/gcr-catalogs/blob/master/GCRCatalogs/SCHEMA.md for all options.\n filters : list, default=[\"mag_i_lsst < 26.5\"]\n Filters that are passed to the GCR Query.\n \"\"\"\n\n name = \"GCRLoader\"\n outputs = [(\"output\", PqHandle)]\n\n config_options = Creator.config_options.copy()\n config_options.update(\n gcr_root_dir=Param(\n str,\n \"/global/cfs/cdirs/lsst/shared\",\n msg=\"The path to the GCR catalogs.\",\n ),\n catalog_name=Param(\n str,\n \"cosmoDC2_v1.1.4_small\",\n msg=\"The name of the GCR catalog to load.\",\n ),\n quantities=Param(\n list,\n [\"redshift\"]\n + [f\"mag_{band}_lsst\" for band in \"ugrizy\"]\n + [\"size_true\", \"size_minor_true\"],\n msg=\"The quantities to query from the catalog.\",\n ),\n filters=Param(\n list,\n [\"mag_i_lsst < 26.5\"],\n msg=\"Filters passed to the GCR query.\",\n ),\n )\n\n def __init__(self, args, comm=None):\n Creator.__init__(self, args, comm=comm)\n\n # Provides override for unit test\n self._catalog_override = None\n\n def run(self):\n \"\"\"Load the GCR catalog, subsample, and return pandas DataFrame.\"\"\"\n # Set the GCRCatalog path\n GCRCatalogs.set_root_dir(self.config.gcr_root_dir)\n\n # Load the catalog\n # In the unit test, this override is provided\n if self._catalog_override is not None:\n gc = GCRCatalogs.load_catalog(*self._catalog_override)\n # Otherwise, proceed as normal\n else: # pragma: no cover\n gc = GCRCatalogs.load_catalog(self.config.catalog_name)\n\n # Query the requested quantities\n cat = gc.get_quantities(self.config.quantities, filters=self.config.filters)\n\n # Convert to a DataFrame\n cat = pd.DataFrame(cat)\n\n # Downsample\n cat = cat.sample(n=self.config.n_samples, random_state=self.config.seed)\n cat = cat[self.config.quantities]\n\n self.add_data(\"output\", cat)\n","repo_name":"LSSTDESC/rail_astro_tools","sub_path":"src/rail/creation/engines/gcr_engine.py","file_name":"gcr_engine.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"72964458312","text":"from flask import Blueprint, render_template, jsonify, request\nfrom transformers import pipeline\n\nsummarization = Blueprint('summarization',__name__)\n\n@summarization.route(\"/summarization\")\ndef summarization_index():\n data = {\n \"title\": \"Summarization Papermu\",\n \"selected\": \"paper\"\n }\n\n return render_template(\"summarization/index.html\", data=data)\n\n@summarization.route(\"/summarization/check\")\ndef summarization_check():\n data = {\n \"title\": \"Check Summarization Papermu\",\n \"selected\": \"paper\"\n }\n\n return render_template(\"summarization/check.html\", data=data)\n\n@summarization.route(\"/summarization/predict\", methods=[\"POST\"])\ndef summarization_predict():\n summary = \"\"\n\n summary = request.form['abstract']\n\n summarizer = pipeline(\"summarization\")\n result_summary = summarizer(summary)\n\n data = {\n \"title\": \"Hasil Summarization Papermu\",\n \"selected\": \"paper\",\n \"summary_text\": result_summary[0][\"summary_text\"]\n }\n\n return render_template(\"summarization/predict.html\", data=data)\n\n@summarization.route(\"/api/v1/summarization/predict\", methods=[\"POST\"])\ndef api_predict_summarization():\n try:\n if request.get_json() is None or request.get_json()['abstract'] is None:\n data = {\n \"status\": False,\n \"response_code\": 400,\n \"message\": \"Bad Request\"\n }\n\n return jsonify(data)\n summary = request.get_json()['abstract']\n summarizer = pipeline(\"summarization\")\n result_summary = summarizer(summary)\n data = {\n \"status\": True,\n \"response_code\": 200,\n \"message\": \"Success Summarization Paragraph\",\n \"summary_text\": result_summary[0][\"summary_text\"]\n }\n\n return jsonify(data)\n except KeyError:\n data = {\n \"status\": False,\n \"response_code\": 400,\n \"message\": \"Bad Request\"\n }\n return jsonify(data)\n","repo_name":"ArtificialIfElse/AIC-COMPFEST13","sub_path":"Deployment/summarization.py","file_name":"summarization.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"29930680961","text":"# You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.\n\n# You may assume the two numbers do not contain any leading zero, except the number 0 itself.\n\n# Follow up:\n# What if you cannot modify the input lists? In other words, reversing the lists is not allowed.\n\n# Example:\n\n# Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)\n# Output: 7 -> 8 -> 0 -> 7\n\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n sol = ListNode(0)\n curr = sol\n p = self.reverseList(l1)\n q = self.reverseList(l2)\n carry = 0\n\n while p != None or q != None:\n\n if p != None:\n x = p.val\n else:\n x = 0\n\n if q != None:\n y = q.val\n else:\n y = 0\n\n sum = x + y + carry\n\n carry = sum // 10\n\n curr.next = ListNode(sum % 10)\n curr = curr.next\n\n if p != None:\n p = p.next\n else:\n p = None\n\n if q != None:\n q = q.next\n else:\n q = None\n\n if carry > 0:\n curr.next = ListNode(carry)\n\n return self.reverseList(sol.next)\n\n\n\n\n\n#7 -> 2 -> 4 -> 3 -> None\n\n#3 -> 4 -> 2 -> 7 -> None\n def reverseList(self,head):\n prevNode = None\n currNode = head\n while(currNode != None):\n temp = currNode.next\n currNode.next = prevNode\n prevNode = currNode\n currNode = temp\n return prevNode\n \n \n \n","repo_name":"jinwei15/java-PythonSyntax-Leetcode","sub_path":"LeetCode/src/AddTwoNumbersII.py","file_name":"AddTwoNumbersII.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"30874419225","text":"n, d, k, c = map(int, input().split())\nsushi = []\nfor _ in range(n):\n sushi.append(int(input()))\nsushi = sushi + sushi[:k-1]\n\nselected = set()\nanswer = 0\n\nfor start in range(len(sushi)):\n end = start + k\n selected = set(sushi[start: end])\n s = len(selected)\n if c not in selected:\n s += 1\n if s > answer:\n answer = s\nprint(answer)","repo_name":"Choi-jw-96/Algo-","sub_path":"13Week_TwoPointer/2531/2531_nninzy.py","file_name":"2531_nninzy.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"7817466111","text":"import csv\nimport pprint\nimport logging\nimport time\nfrom logging.handlers import TimedRotatingFileHandler\n\nfrom wallerexplorer.interrupt_test import open_ethlog\nimport requests\nimport json\nfrom db_data.database import Process_data\n\nlogger = logging.getLogger(\"LOGETH\")\nlogger.setLevel(logging.DEBUG)\nch = TimedRotatingFileHandler('ethlog', when=\"D\", interval=1, backupCount=5, )\n# logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nformat = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nch.setFormatter(format)\nlogger.addHandler(ch)\n\n\ndef hex_dec(value):\n return (int(value, 16) / 10 ** 18)\n\n\ndef write_to_csv(name, data):\n with open(\"%s.csv\" % name, mode='a', newline='')as f:\n # writer = csv.writer(f)\n # writer.writerow(args)\n f.write(data + '\\n')\n\n\ndef counter(num):\n total = 0\n total = sum(total, num)\n return total\n\n\ndef getBlockByNumber(number):\n list = []\n url = 'http://192.168.3.31:8545'\n body = {\"method\": \"eth_getBlockByNumber\",\n \"params\": [str(hex(number)), True], \"id\": 1, \"jsonrpc\": \"2.0\"}\n r = requests.post(url=url, data=json.dumps(body), headers={\n \"Content-Type\": \"application/json\"})\n # result = r.json()['result']['hash']\n blockhash = r.json()['result']['hash']\n blockNumber = r.json()['result']['number']\n timestamp = r.json()['result']['timestamp']\n date = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(int(timestamp, 16)))\n transactions = r.json()['result']['transactions']\n for transaction in transactions:\n from_add = transaction['from']\n to_add = transaction['to']\n if to_add == None:\n to_add = transaction['creates']\n transaction_hash = transaction['hash']\n value = transaction['value'] # 发送的以太数量,单位:wei\n gas = transaction['gas'] # Gas价格\n gasPrice = transaction['gasPrice'] # Gas使用量最大限额\n transactionIndex = transaction['transactionIndex']\n input_data = transaction['input']\n eth_transaction = (from_add, to_add, blockhash, int(blockNumber, 16), date,\n int(gas, 16), int(gasPrice, 16), input_data, int(timestamp, 16),\n int(transactionIndex, 16), transaction_hash, hex_dec(value))\n list.append(eth_transaction)\n\n return list\n\n\n# getBlockByNumber()\n\n\ndef getTransactionByBlockHashAndIndex(hash, index=1):\n # 返回指定块内具有指定索引序号的交易。\n url = 'http://192.168.3.31:8545'\n body = {\"method\": \"eth_getTransactionByBlockHashAndIndex\",\n \"params\": [str(hash), str(hex(index))], \"id\": 1,\n \"jsonrpc\": \"2.0\"}\n r = requests.post(url=url, data=json.dumps(body), headers={\n \"Content-Type\": \"application/json\"})\n result = r.json()['result']['hash']\n # print(result)\n input = r.json()['result']['from']\n output = r.json()['result']['to']\n return result\n\n\n# getTransactionByBlockHashAndIndex('0x1')\n\n\ndef getTransactionByHash(hash):\n url = 'http://192.168.3.31:8545'\n body = {\"method\": \"eth_getTransactionByHash\",\n \"params\": [str(hash)], \"id\": 1, \"jsonrpc\": \"2.0\"}\n r = requests.post(url=url, data=json.dumps(body), headers={\n \"Content-Type\": \"application/json\"})\n result = r.json()['result']\n # print(result)\n # hash = r.json()['result']['hash']\n input = r.json()['result']['from']\n output = r.json()['result']['to']\n value = r.json()['result']['value'] # 发送的以太数量,单位:wei\n gas = r.json()['result']['gas'] # Gas价格\n gasPrice = r.json()['result']['gasPrice'] # Gas使用量最大限额\n blockHash = r.json()['result']['blockHash']\n blockNumber = r.json()['result']['blockNumber']\n transactionIndex = r.json()['result']['transactionIndex']\n input_data = r.json()['result']['input']\n # transaction = (hash + \",\" + input + \",\" + output + \",\" + value\n # + \",\" + gas + \",\" + gasPrice)\n transaction = (hash, input, output, hex_dec(value), int(gas, 16), int(gasPrice, 16))\n print(hash)\n return transaction\n\n\n# getTransactionByHash()\n\n# for i in range(1100000, 1100010):\n# blockhash = getBlockByNumber(i)\n# # write_to_csv(\"块哈希\", blockhash)\n# try:\n# j = 0\n# while True:\n# hash = getTransactionByBlockHashAndIndex(blockhash[0], j)\n# # write_to_csv('交易哈希', hash)\n# data = getTransactionByHash(hash)\n# # write_to_csv('交易详情', data)\n# data1 = (2, 3, 4, 5, 6, 7)\n# process_data.insert_eth_transation(*data)\n# j += 1\n# except:\n# continue\n# # , '交易哈希', '输入', '输出',\n# # '发送以太的数量', 'Gas价格', 'Gas使用量最大限额'\n# print(\"总共耗时:\", time.time() - start)\n\nprocess_data = Process_data()\n\n\ndef eth_get_transaction(num=10700000, index=0):\n start = time.time()\n for i in range(num, 10700100):\n transaction_list = getBlockByNumber(i)\n print(i, end='\\t')\n blocknumber = i\n try:\n blockhash = transaction_list[0][2]\n except:\n continue\n # j = 0\n print(index)\n for tran in transaction_list[index:]:\n process_data.insert_address(tran[0])\n process_data.insert_address(tran[1])\n process_data.insert_eth_transaction_new(*tran)\n # transaction_index = tran[-3]\n print(blocknumber,end='\\t')\n j = transaction_list.index(tran)\n print(j)\n logger.debug(str(blocknumber) + \" - \" + str(j))\n index = 0\n # print(transaction_index)\n\n print('块高:' + str(blocknumber) + '\\t' + '块哈希:' + blockhash + '\\t' + \"一共有交易:\", end='')\n length = len(transaction_list)\n print(length)\n\n print(\"总共耗时:\", time.time() - start)\n\n\nif open_ethlog():\n num, index = open_ethlog()[0], open_ethlog()[1]\n eth_get_transaction(num, index+1)\nif open_ethlog() == None:\n eth_get_transaction()\n","repo_name":"MrSnake-P/BLOG","sub_path":"07-ethRPC.py","file_name":"07-ethRPC.py","file_ext":"py","file_size_in_byte":6157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"69823809671","text":"from snakemake.shell import shell\nfrom snakemake_wrapper_utils.base import WrapperBase\n\n\nclass Wrapper(WrapperBase):\n def __init__(self, snakemake) -> None:\n super().__init__(snakemake)\n\n def parser(self):\n commond = self.snakemake.params.get(\"command\", \"seq\")\n assert commond in [\n \"amplicon\", \"bam\", \"common\", \"concat\", \"convert\", \"duplicate\",\n \"fa2fq\", \"faidx\", \"fish\", \"fq2fa\", \"fx2tab\", \"genautocomplete\",\n \"grep\", \"head\", \"head-genome\", \"locate\", \"merge-slides\", \"mutate\",\n \"pair\", \"range\", \"rename\", \"replace\", \"restart\", \"rmdup\",\n \"sample\", \"sana\", \"scat\", \"seq\", \"shuffle\", \"sliding\", \"sort\", \n \"split\", \"split2\", \"stats\", \"subseq\", \"sum\", \"tab2fx\", \"translate\"\n ], \"command not support!\"\n\n self.extra_input = \" \".join(\n [\n f\"--{key.replace('_','-')} {value}\"\n if key in [\"bed\", \"gtf\"]\n else f\"--{key.replace('_','-')}-file {value}\"\n for key, value in self.snakemake.input.items()\n ][1:]\n )\n\n self.extra_output = \" \".join(\n [\n f\"--{key.replace('_','-')} {value}\"\n if key in [\"read1\", \"read2\"]\n else f\"--{key.replace('_','-')}-file {value}\"\n for key, value in self.snakemake.output.items()\n ][1:]\n )\n\n \n def run(self):\n shell(\n \"seqkit {self.snakemake.params.command}\"\n \" --threads {self.snakemake.threads}\"\n \" {self.extra_input}\"\n \" {self.extra_output}\"\n \" {self.extra}\"\n \" --out-file {self.snakemake.output[0]}\"\n \" {self.snakemake.input[0]}\"\n \" {self.log}\"\n )\n \n\nif __name__ == \"__main__\":\n wrapper = Wrapper(snakemake)\n","repo_name":"dxsbiocc/Workflow","sub_path":"wrappers/seqkit/wrapper.py","file_name":"wrapper.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"27"} +{"seq_id":"12151446261","text":"from setuptools import setup, find_packages\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\nwith open(path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\n\ndef get_requirements(filename='requirements.txt'):\n deps = []\n with open(filename, 'r') as f:\n for pkg in f.readlines():\n if pkg.strip():\n deps.append(pkg)\n return deps\n\n\nsetup(\n name='ys-downloader',\n version='0.0.0',\n description='',\n long_description=long_description,\n long_description_content_type='text/markdown',\n author='appleholic',\n keywords='ys_downloader',\n packages=find_packages(),\n install_requires=get_requirements(),\n python_requires='>=3.5',\n entry_points={\n 'console_scripts': ['download-ys=ys_downloader.run:main'],\n }\n)\n","repo_name":"AppleHolic/youtube_sound_downloader","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"37956710407","text":"from flask import Flask, request, jsonify, g\nfrom flask_restful import Resource, Api\nimport json\n\n\napp = Flask(__name__)\napi = Api(app)\nrobot_driver = None\n\n\nclass LEDs(Resource):\n def get(self, led_id):\n state = robot_driver.get_led_state(int(led_id))\n app.logger.info(f\"Get the LED {led_id} state: {state}\")\n return {\"led_index\": led_id, \"state\": state}\n\n def post(self, led_id):\n state = robot_driver.toggle_led_state(int(led_id))\n app.logger.info(f\"Toggle the LED {led_id} state to: {state}\")\n return {\"led_index\": led_id, \"state\": state}\n\n\nclass Buttons(Resource):\n def post(self, button_id):\n app.logger.info(f\"Simulate the button {button_id} trigger\")\n robot_driver.trigger_button_cb(int(button_id))\n\n return {\"success\": True}\n\n\nclass Knobs(Resource):\n def post(self, knob_id):\n try:\n request_data = json.loads(request.data)\n state = robot_driver.set_knob_state(int(knob_id),\n float(request_data['value']))\n app.logger.info(f\"Set the Knob {knob_id} state to: {state}\")\n return {\"knob_id\": knob_id, \"state\": state}\n except KeyError:\n return {\"message\": \"Invalid response\"}\n\n def get(self, knob_id):\n state = robot_driver.get_knob_state(int(knob_id))\n app.logger.info(f\"Get the knob {knob_id} state: {state}\")\n return {\"knob_id\": knob_id, \"state\": state}\n\n\nclass Servos(Resource):\n def post(self, servo_id):\n servo_id = int(servo_id)\n try:\n request_data = json.loads(request.data)\n position = float(request_data['position'])\n duration = request_data.get('duration')\n duration = float(duration) if duration else None\n\n if duration:\n steps = int(request_data.get('steps', 10))\n robot_driver.set_servo_stepped(\n servo_id, position, duration, steps)\n else:\n robot_driver.set_servo_position(\n servo_id, position)\n except KeyError:\n return {\"message\": \"Invalid\"}\n\n\napi.add_resource(LEDs, \"/leds/\")\napi.add_resource(Buttons, \"/buttons/\")\napi.add_resource(Knobs, \"/knobs/\")\napi.add_resource(Servos, \"/servos/\")\n\n\ndef run_server(driver):\n global robot_driver\n\n robot_driver = driver\n app.run(host=\"0.0.0.0\", port=5432, debug=True)\n","repo_name":"cjacoby/robotwedding","sub_path":"robot/servers/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"71134574471","text":"import geojson\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import interpolate\n\nclass Track:\n\n track = 0\n curr = \"S0\"\n name = {}\n pit = \"nopit\"; #nopit, pit\n fork1 = \"left\"; #left, middle, right\n fork2 = \"left\"; #left, right\n fork3 = \"left\"; #left, right\n\n # \n def __init__(self, trackName):\n with open(\"app/track/\" + trackName + \".geojson\", \"r\") as f:\n self.track = geojson.load(f)\n for i in range(len(self.track[\"features\"])):\n self.name.update({self.track[\"features\"][i][\"properties\"][\"name\"]: i})\n \n # example call setFork(\"right\", \"right\", \"right\") takes the longest route\n def setForks(self, f1, f2, f3):\n self.fork1 = f1\n self.fork2 = f2\n self.fork3 = f3\n\n # example call pitNext() forces car to take the ONLY the next pit\n def pitNext(self):\n self.pit = \"pit\"\n\n # returns current name like \"S0\"\n def getCurr(self):\n return self.curr\n\n # returns next name like \"S1\"\n def getNext(self, p1=None):\n if(p1 == None):\n p1 = self.curr\n match = lambda s: self._getPoint(p1)[\"properties\"][\"name\"] == s\n if(match(\"S5\")):\n return self._getPoint(p1)[\"properties\"][self.fork1]\n if(match(\"S8\")):\n return self._getPoint(p1)[\"properties\"][self.fork2]\n if(match(\"S10\")):\n return self._getPoint(p1)[\"properties\"][self.fork3]\n if(match(\"S21\")):\n if(self.pit == \"pit\"):\n self.pit = \"nopit\"\n return self._getPoint(p1)[\"properties\"][\"pit\"]\n return self._getPoint(p1)[\"properties\"][\"nopit\"]\n return self._getPoint(p1)[\"properties\"][\"next\"]\n\n # iterates curr to next name\n def goNext(self):\n self.curr = self.getNext()\n\n # returns something like -0.25% slope\n def getPercentSlope(self, p1=None, p2=None):\n if(p1 == None and p2 == None):\n p1 = self.curr\n p2 = self.getNext()\n return (\n 100 * (self._getElevation(p2) - self._getElevation(p1))\n / (self.getDistance(p1, p2))\n )\n # gets turning radius of next segment in feet\n def getRadius(self, p1=None):\n if(p1 == None):\n p1 = self.curr\n if(\"radius\" in self._getPoint(p1)[\"properties\"]):\n return self._getPoint(p1)[\"properties\"][\"radius\"]\n return float(\"inf\")\n \n # gets distance in feet from A to B and supports paths\n def getDistance(self, p1, p2):\n distance = 0\n dest = p2\n while self.getNext(p1) != dest:\n distance += self._getDirectDistance(p1, p2)\n p1 = p2\n p2 = self.getNext(p2)\n return distance + self._getDirectDistance(p1, p2)\n\n def generateMinimap(self):\n line = geojson.LineString([])\n start = self.getCurr()\n while self.getNext(self.getCurr()) != start:\n lat, lon = self._getCoords()\n line[\"coordinates\"].append([lon, lat])\n self.goNext()\n for i in range(2):\n lat, lon = self._getCoords()\n line[\"coordinates\"].append([lon, lat])\n self.goNext()\n f = geojson.Feature(geometry=line)\n fc = geojson.FeatureCollection([f])\n with open(\"app/track/minimap.geojson\", \"w\") as f:\n geojson.dump(fc, f, indent=4)\n \n # WIP curves need to be more tangent-like\n def interpolateMinimap(self):\n x = []\n y = []\n start = self.getCurr()\n while self.getNext(self.getCurr()) != start:\n lat, lon = self._getCoords()\n x.append(lon)\n y.append(lat)\n self.goNext()\n lat, lon = self._getCoords()\n x.append(lon)\n y.append(lat)\n self.goNext()\n\n tck, u = interpolate.splprep([x, y], s=0)\n unew = np.arange(0, 1, .01)\n out = interpolate.splev(unew, tck)\n plt.figure()\n plt.plot(x, y, 'x', out[0], out[1], x, y, 'b')\n plt.legend(['Linear', 'Cubic Spline', 'True'])\n plt.axis([-95.68512414004034, -95.6651136503342, 38.917864784928895, 38.93202447381995])\n plt.title('Spline of parametrically-defined curve')\n plt.show()\n\n # private functions you shouldn't have to use\n def _getPoint(self, p1=None):\n if(p1 == None):\n p1 = self.curr\n return self.track[\"features\"][self.name[p1]]\n\n def _getCoords(self, p1=None):\n if(p1 == None):\n p1 = self.curr\n return (\n self._getPoint(p1)[\"geometry\"][\"coordinates\"][1],\n self._getPoint(p1)[\"geometry\"][\"coordinates\"][0]\n )\n\n def _getElevation(self, p1=None):\n if(p1 == None):\n p1 = self.curr\n return self._getPoint(p1)[\"properties\"][\"elevation\"]\n\n def _getDirectDistance(self, p1, p2):\n lat1, lon1 = self._getCoords(p1)\n lat2, lon2 = self._getCoords(p2)\n x = 288200 * (lon2 - lon1)\n y = 364000 * (lat2 - lat1)\n d = math.sqrt(x * x + y * y)\n if(\"radius\" in self._getPoint(p1)[\"properties\"]):\n r = self.getRadius(p1)\n return 2*r*math.asin(d/(2*r))\n return d\n \n# testing\ndef test():\n t = Track(\"dynamic\")\n t.setForks(\"left\", \"left\", \"left\")\n\n while t.getNext(t.getCurr()) != \"S0\":\n print(t.getCurr())\n t.goNext()\n print(t.getCurr())\n t.goNext()\n\n print(\"shortest track length: \" + str(t.getDistance(\"S0\", \"S0\"))) #\n t.pitNext()\n print(\"above length with pit lap: \" + str(t.getDistance(\"S0\", \"S0\"))) # this inherently 2 laps to make it to the finish line after a pit\n t.setForks(\"right\", \"right\", \"right\")\n print(\"longest track length: \" + str(t.getDistance(\"S0\", \"S0\")/5280))\n # t.generateMinimap()\n t.interpolateMinimap()\n\ntest()","repo_name":"lhr-solar/DataAcquisition","sub_path":"grafana/track/track.py","file_name":"track.py","file_ext":"py","file_size_in_byte":5817,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"965059737","text":"from datetime import timedelta\nimport requests\nfrom bs4 import BeautifulSoup as BS\nfrom db_connection import *\nfrom asyncpg import UniqueViolationError\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler\n\n\nscheduler = AsyncIOScheduler()\nscheduler.start()\n\n\nasync def add_price(url: str):\n price, change = parse(url)\n obj = Price(price=1, change=1)\n await obj.create()\n try:\n obj = Price(price=price, change=change)\n await obj.create()\n except UniqueViolationError:\n print('Объект не добавлен')\n\n\ndef parse(url: str) -> tuple:\n request = requests.get(url)\n html = BS(request.content, 'html.parser')\n elements = html.select('.sc-18a2k5w-1')\n for element in elements:\n if \"$\" in element.text:\n value = element.text\n price = value[:value.find('.0') + 3]\n change = value.replace(price, '').replace('\\xa0', '')\n data = (price, change)\n return data\n\n\nasync def create_job(delay: int, times: int, url: str):\n value = parse(url)\n for i in range(times):\n run_date = datetime.datetime.now() + timedelta(seconds=delay * i)\n scheduler.add_job(add_price, 'date', run_date=run_date, kwargs={'url': url})\n\n","repo_name":"2tieatie/for_job","sub_path":"funcs.py","file_name":"funcs.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"73111690951","text":"\"\"\"Tests for utils_search.py that don't depend on code in dtool-lookup-server.\n\nFor the future when the functionality of utils_search is split into a separate\npython package.\n\"\"\"\n\nimport random\nimport string\nimport shutil\nimport tempfile\n\nfrom contextlib import contextmanager\n\nimport pytest\n\nfrom pymongo import MongoClient\n\nfrom dtoolcore import DataSetCreator, DataSet\n\nfrom dtool_lookup_server.utils import generate_dataset_info\n\n# Things tested in this module\nfrom dtool_lookup_server_search_plugin_mongo.utils_search import MongoSearch\nfrom dtool_lookup_server_search_plugin_mongo.utils_search import _dict_to_mongo_query\n\n\nMONGO_URI = \"mongodb://localhost:27017\"\n\n\ndef random_string(\n size=9,\n prefix=\"test_dtool_lookup_server_mongo_search\",\n chars=string.ascii_uppercase + string.ascii_lowercase + string.digits\n):\n return prefix + ''.join(random.choice(chars) for _ in range(size))\n\n\n@pytest.fixture\ndef tmp_mongo_db(request):\n tmp_mongo_db_name = random_string()\n client = MongoClient(MONGO_URI)\n\n @request.addfinalizer\n def teardown():\n client.drop_database(tmp_mongo_db_name)\n\n return tmp_mongo_db_name\n\n\n@contextmanager\ndef tmp_dir():\n d = tempfile.mkdtemp()\n yield d\n shutil.rmtree(d)\n\n\ndef update_base_uri(ds_info, base_uri):\n ds_uri = base_uri + \"/\" + ds_info[\"uuid\"]\n ds_info[\"uri\"] = ds_uri\n ds_info[\"base_uri\"] = base_uri\n return ds_info\n\n\ndef create_dataset_info(base_uri, name, readme, items_content, tags, annotations, creator): # NOQA\n with tmp_dir() as d:\n with DataSetCreator(name, d, readme, creator) as ds_creator:\n for ic in items_content:\n handle = ic + \".txt\"\n fpath = ds_creator.prepare_staging_abspath_promise(handle)\n with open(fpath, \"w\") as fh:\n fh.write(ic)\n for tag in tags:\n ds_creator.put_tag(tag)\n for key, value in annotations.items():\n ds_creator.put_annotation(key, value)\n dataset = DataSet.from_uri(ds_creator.uri)\n ds_info = generate_dataset_info(dataset, base_uri)\n\n ds_info = update_base_uri(ds_info, base_uri)\n\n return ds_info\n\n\nclass _MockApp(object):\n \"Class to mock a Flask app to hold a config dict.\"\n pass\n\n\n##############################################################################\n# Here are the tests\n##############################################################################\n\ndef test_lookup_uris(tmp_mongo_db): # NOQA\n\n ds_info_1 = create_dataset_info(\n \"s3://store1\",\n \"apple-gala\",\n \"---\\ndescription: gala apples\",\n [\"barrel1\", \"barrel2\"],\n [\"red\", \"yellow\"],\n {\"type\": \"fruit\"},\n \"farmer\"\n )\n ds_info_2 = update_base_uri(ds_info_1.copy(), \"s3://store2\")\n uuid = ds_info_1[\"uuid\"]\n\n both_base_uris = [\"s3://store1\", \"s3://store2\"]\n only_store2 = [\"s3://store2\"]\n\n mongo_search = MongoSearch()\n app = _MockApp()\n app.config = {\n \"SEARCH_MONGO_URI\": MONGO_URI,\n \"SEARCH_MONGO_DB\": tmp_mongo_db,\n \"SEARCH_MONGO_COLLECTION\": \"datasets\"\n }\n mongo_search.init_app(app)\n\n # Should be empty. Nothing registered yet.\n assert mongo_search.lookup_uris(uuid, both_base_uris) == []\n\n # Register a dataset.\n mongo_search.register_dataset(ds_info_1)\n assert mongo_search.lookup_uris(uuid, both_base_uris) == [\n {\n \"base_uri\": ds_info_1[\"base_uri\"],\n \"name\": ds_info_1[\"name\"],\n \"uri\": ds_info_1[\"uri\"],\n \"uuid\": ds_info_1[\"uuid\"]\n }\n ]\n\n # Register the same dataset in different base URI\n mongo_search.register_dataset(ds_info_2)\n assert len(mongo_search.lookup_uris(uuid, both_base_uris)) == 2 # NOQA\n\n # Make sure only the dataset from store2 is retrievd if limited\n # that base URI.\n assert mongo_search.lookup_uris(uuid, only_store2) == [\n {\n \"base_uri\": ds_info_2[\"base_uri\"],\n \"name\": ds_info_2[\"name\"],\n \"uri\": ds_info_2[\"uri\"],\n \"uuid\": ds_info_2[\"uuid\"]\n }\n ]\n\n # Make sure nothing is returned if there are no base URIs.\n assert len(mongo_search.lookup_uris(uuid, [])) == 0 # NOQA\n\n\ndef test_register_basic(tmp_mongo_db): # NOQA\n\n ds_info = create_dataset_info(\n base_uri=\"s3://store\",\n name=\"apple-gala\",\n readme=\"---\\ndescription: gala apples\",\n items_content=[\"barrel1\", \"barrel2\"],\n tags=[\"red\", \"yellow\"],\n annotations={\"type\": \"fruit\"},\n creator=\"farmer\"\n )\n\n mongo_search = MongoSearch()\n app = _MockApp()\n app.config = {\n \"SEARCH_MONGO_URI\": MONGO_URI,\n \"SEARCH_MONGO_DB\": tmp_mongo_db,\n \"SEARCH_MONGO_COLLECTION\": \"datasets\"\n }\n mongo_search.init_app(app)\n\n # Should be empty. Nothing registered yet.\n assert len(mongo_search.search({\"base_uris\": [\"s3://store\"]})) == 0\n\n # Register a dataset.\n mongo_search.register_dataset(ds_info)\n assert len(mongo_search.search({\"base_uris\": [\"s3://store\"]})) == 1\n\n # Register the same dataset again. Shoud not result in a duplicate record.\n mongo_search.register_dataset(ds_info.copy())\n assert len(mongo_search.search({\"base_uris\": [\"s3://store\"]})) == 1\n\n\ndef test_register_raises_when_metadata_too_large(tmp_mongo_db): # NOQA\n\n from dtool_lookup_server import ValidationError\n\n readme_lines = [\"---\"]\n for i in range(100000):\n key = \"here_is_a_long_key_{}\".format(i)\n value = \"here_is_a_long_value_{}\".format(i) * 10\n readme_lines.append(\"{}: {}\".format(key, value))\n ds_info = create_dataset_info(\n \"s3://store\",\n \"apple-gala\",\n \"\\n\".join(readme_lines),\n [\"barrel1\", \"barrel2\"],\n [\"red\", \"yellow\"],\n {\"type\": \"fruit\"},\n \"farmer\"\n )\n\n mongo_search = MongoSearch()\n app = _MockApp()\n app.config = {\n \"SEARCH_MONGO_URI\": MONGO_URI,\n \"SEARCH_MONGO_DB\": tmp_mongo_db,\n \"SEARCH_MONGO_COLLECTION\": \"datasets\"\n }\n mongo_search.init_app(app)\n\n with pytest.raises(ValidationError):\n mongo_search.register_dataset(ds_info)\n\n\ndef test_search_free_text(tmp_mongo_db):\n\n mongo_search = MongoSearch()\n app = _MockApp()\n app.config = {\n \"SEARCH_MONGO_URI\": MONGO_URI,\n \"SEARCH_MONGO_DB\": tmp_mongo_db,\n \"SEARCH_MONGO_COLLECTION\": \"datasets\"\n }\n mongo_search.init_app(app)\n\n # Add datasets.\n mongo_search.register_dataset(\n create_dataset_info(\n base_uri=\"s3://farmshop\",\n name=\"farmshop-apples\",\n readme=\"---\\ndescription: apples\",\n items_content=[\"barrel1\", \"barrel2\"],\n tags=[\"red\", \"yellow\", \"healthy\"],\n annotations={\"type\": \"fruit\"},\n creator=\"farmer\"\n )\n )\n mongo_search.register_dataset(\n create_dataset_info(\n base_uri=\"s3://farmshop\",\n name=\"farmshop-carrots\",\n readme=\"---\\ndescription: carrots for good eyesight\",\n items_content=[\"tray1\", \"tray2\"],\n tags=[\"orange\", \"healthy\"],\n annotations={\"type\": \"vegetable\"},\n creator=\"farmerson\"\n )\n )\n mongo_search.register_dataset(\n create_dataset_info(\n base_uri=\"s3://supermarket\",\n name=\"supermarket-apples\",\n readme=\"---\\ndescription: apples\",\n items_content=[\"tray1\", \"tray2\", \"tray3\"],\n tags=[\"red\", \"yellow\", \"healthy\"],\n annotations={\"type\": \"fruit\"},\n creator=\"farmer\"\n )\n )\n\n # Define base URIs for query.\n only_farmshop = [\"s3://farmshop\"]\n only_supermarket = [\"s3://supermarket\"]\n both_shops = [\"s3://farmshop\", \"s3://supermarket\"]\n\n # Test the basis of authorization.\n assert len(mongo_search.search({\"base_uris\": only_farmshop})) == 2\n assert len(mongo_search.search({\"base_uris\": only_supermarket})) == 1\n assert len(mongo_search.search({\"base_uris\": both_shops})) == 3\n\n # Test negative search.\n query = {\"base_uris\": both_shops, \"free_text\": \"dontexist\"}\n assert len(mongo_search.search(query)) == 0\n\n # Test free text admin metadata.\n query = {\"base_uris\": both_shops, \"free_text\": \"farmer\"}\n assert len(mongo_search.search(query)) == 2\n query = {\"base_uris\": both_shops, \"free_text\": \"farmerson\"}\n assert len(mongo_search.search(query)) == 1\n query = {\"base_uris\": only_supermarket, \"free_text\": \"farmerson\"}\n assert len(mongo_search.search(query)) == 0\n\n # Test free text readme.\n query = {\"base_uris\": both_shops, \"free_text\": \"eyesight\"}\n assert len(mongo_search.search(query)) == 1\n query = {\"base_uris\": only_farmshop, \"free_text\": \"eyesight\"}\n assert len(mongo_search.search(query)) == 1\n query = {\"base_uris\": only_supermarket, \"free_text\": \"eyesight\"}\n assert len(mongo_search.search(query)) == 0\n\n # Test free text item content.\n query = {\"base_uris\": both_shops, \"free_text\": \"tray2\"}\n assert len(mongo_search.search(query)) == 2\n query = {\"base_uris\": both_shops, \"free_text\": \"tray3\"}\n assert len(mongo_search.search(query)) == 1\n query = {\"base_uris\": only_farmshop, \"free_text\": \"tray3\"}\n assert len(mongo_search.search(query)) == 0\n\n # Test free text tags.\n query = {\"base_uris\": both_shops, \"free_text\": \"red\"}\n assert len(mongo_search.search(query)) == 2\n query = {\"base_uris\": both_shops, \"free_text\": \"orange\"}\n assert len(mongo_search.search(query)) == 1\n query = {\"base_uris\": only_supermarket, \"free_text\": \"orange\"}\n assert len(mongo_search.search(query)) == 0\n\n # Test free text annotations.\n query = {\"base_uris\": both_shops, \"free_text\": \"fruit\"}\n assert len(mongo_search.search(query)) == 2\n query = {\"base_uris\": both_shops, \"free_text\": \"vegetable\"}\n assert len(mongo_search.search(query)) == 1\n query = {\"base_uris\": only_supermarket, \"free_text\": \"vegetable\"}\n assert len(mongo_search.search(query)) == 0\n\n # Test tags.\n query = {\"base_uris\": both_shops, \"tags\": [\"healthy\"]}\n assert len(mongo_search.search(query)) == 3\n query = {\"base_uris\": both_shops, \"tags\": [\"healthy\", \"orange\"]}\n assert len(mongo_search.search(query)) == 1\n query = {\"base_uris\": only_supermarket, \"tags\": [\"healthy\", \"orange\"]}\n assert len(mongo_search.search(query)) == 0\n\n # Test creator usernames.\n query = {\"base_uris\": both_shops, \"creator_usernames\": [\"farmer\"]}\n assert len(mongo_search.search(query)) == 2\n query = {\"base_uris\": both_shops, \"creator_usernames\": [\"farmer\", \"farmerson\"]} # NOQA\n assert len(mongo_search.search(query)) == 3\n query = {\"base_uris\": only_supermarket, \"creator_usernames\": [\"farmerson\"]}\n assert len(mongo_search.search(query)) == 0\n\n # Test uuid (need to get the uuid first).\n query = {\"base_uris\": both_shops, \"free_text\": \"eyesight\"}\n hits = mongo_search.search(query)\n uuid = hits[0][\"uuid\"]\n query = {\"base_uris\": both_shops, \"uuids\": [uuid]}\n assert len(mongo_search.search(query)) == 1\n query = {\"base_uris\": only_supermarket, \"uuids\": [uuid]}\n assert len(mongo_search.search(query)) == 0\n\n\n##############################################################################\n# Test the _dict_to_mongo_query helper function.\n##############################################################################\n\ndef test_empty_dict():\n \"\"\"An empty dict should return query for all datasets.\"\"\"\n assert _dict_to_mongo_query({}) == {}\n\n\ndef test_free_text():\n \"\"\"Should return {\"$text\": {\"$search\": \"free_text_here\"}}\"\"\"\n query = dict(free_text=\"free_text_here\")\n expected_mongo_query = {\"$text\": {\"$search\": \"free_text_here\"}}\n assert _dict_to_mongo_query(query) == expected_mongo_query\n\n\ndef test_creator_usernames():\n # Test single creator username.\n query = dict(creator_usernames=[\"grumpy\"])\n expected_mongo_query = {\"creator_username\": \"grumpy\"}\n assert _dict_to_mongo_query(query) == expected_mongo_query\n\n # Test multiple creator usernames.\n query = dict(creator_usernames=[\"grumpy\", \"dopey\"])\n expected_mongo_query = {\"$or\": [\n {\"creator_username\": \"grumpy\"},\n {\"creator_username\": \"dopey\"}\n ]}\n assert _dict_to_mongo_query(query) == expected_mongo_query\n\n # Test empty list.\n query = dict(creator_usernames=[])\n assert _dict_to_mongo_query(query) == {}\n\n\ndef test_base_uris():\n # Test single base URI.\n query = dict(base_uris=[\"s3://snow-white\"])\n expected_mongo_query = {\"base_uri\": \"s3://snow-white\"}\n assert _dict_to_mongo_query(query) == expected_mongo_query\n\n # Test multiple base URIs.\n query = dict(base_uris=[\"s3://snow-white\", \"s3://mr-men\"])\n expected_mongo_query = {\"$or\": [\n {\"base_uri\": \"s3://snow-white\"},\n {\"base_uri\": \"s3://mr-men\"}\n ]}\n assert _dict_to_mongo_query(query) == expected_mongo_query\n\n\ndef test_tags():\n # Test single tag.\n query = dict(tags=[\"evil\"])\n expected_mongo_query = {\"tags\": \"evil\"}\n assert _dict_to_mongo_query(query) == expected_mongo_query\n\n # Test multiple tags.\n query = dict(tags=[\"evil\", \"good\"])\n expected_mongo_query = {\"tags\": {\"$all\": [\"evil\", \"good\"]}}\n assert _dict_to_mongo_query(query) == expected_mongo_query\n\n # Test empty list.\n query = dict(tags=[])\n assert _dict_to_mongo_query(query) == {}\n\n\ndef test_combinations():\n query = dict(\n free_text=\"apple\",\n base_uris=[\"s3://snow-white\"],\n creator_usernames=[\"grumpy\", \"dopey\"],\n tags=[\"good\", \"evil\"]\n )\n expected_mongo_query = {}\n expected_mongo_query = {\n \"$and\": [\n {\"$text\": {\"$search\": \"apple\"}},\n {\"$or\": [\n {\"creator_username\": \"grumpy\"},\n {\"creator_username\": \"dopey\"}\n ]\n },\n {\"base_uri\": \"s3://snow-white\"},\n {\"tags\": {\"$all\": [\"good\", \"evil\"]}}\n ]\n }\n assert _dict_to_mongo_query(query) == expected_mongo_query\n","repo_name":"jic-dtool/dtool-lookup-server-search-plugin-mongo","sub_path":"tests/test_utils_search_standalone.py","file_name":"test_utils_search_standalone.py","file_ext":"py","file_size_in_byte":14028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"12088166593","text":"# ------------------------------------------------------------------------------\n# Author: Erik Buchholz\n# E-mail: e.buchholz@unsw.edu.au\n# ------------------------------------------------------------------------------\nimport logging\nfrom unittest import TestCase\n\nimport numpy as np\nimport pandas as pd\nfrom haversine import haversine, haversine_vector\nfrom raopt.preprocessing import metrics as m\n\nlogging.basicConfig(level=logging.ERROR)\n\n\nclass Test(TestCase):\n\n def setUp(self) -> None:\n self.t1 = {\n 'latitude': [\n 1, 2, 3, 4, 5, 6, 7, 8, 9\n ],\n 'longitude': [\n 1, 2, 3, 4, 5, 6, 7, 8, 9\n ]\n }\n self.t2 = {\n 'latitude': [\n 5, 5, 5, 5, 5, 5, 5, 5, 5\n ],\n 'longitude': [\n 5, 5, 5, 5, 5, 5, 5, 5, 5\n ]\n }\n super().setUpClass()\n\n def test_euclidean_distance(self):\n t1 = pd.DataFrame(self.t1)\n t2 = pd.DataFrame(self.t2)\n self.assertEqual(\n 0,\n m.euclidean_distance_pd(t1, t1)\n )\n self.assertEqual(\n 0,\n m.euclidean_distance_pd(t1, t1, False)\n )\n self.assertEqual(\n 0,\n m.euclidean_distance_pd(t2, t2) / 1000\n )\n self.assertEqual(\n 0,\n m.euclidean_distance_pd(t2, t2, False)\n )\n self.assertAlmostEqual(\n 3.14,\n m.euclidean_distance_pd(t1, t2, False),\n 2\n )\n self.assertAlmostEqual(\n 349,\n m.euclidean_distance_pd(t1, t2) / 1000,\n 0\n )\n\n def test__async_euclidean_distance(self):\n t1 = np.array([[1, 1], [2, 2], [3, 3], [4, 4], [\n 5, 5], [6, 6], [7, 7], [8, 8], [9, 9]])\n t2 = np.array([[5, 5], [5, 5], [5, 5], [5, 5], [\n 5, 5], [5, 5], [5, 5], [5, 5], [5, 5]])\n with self.assertRaises(ValueError):\n m._async_euclidean_distance(t1, t2)\n t1 = np.append(t1, [[10, 10]], axis=0)\n self.assertAlmostEqual(\n 3.14,\n m._async_euclidean_distance(t1, t2, False),\n 2\n )\n self.assertAlmostEqual(\n 349,\n m._async_euclidean_distance(t1, t2) / 1000,\n 0\n )\n\n def test_hausdorff_distance(self):\n t1 = pd.DataFrame(self.t1)\n t2 = pd.DataFrame(self.t2)\n self.assertEqual(\n 0,\n m.hausdorff_distance_pd(t1, t1)\n )\n self.assertEqual(\n m.hausdorff_distance_pd(t1, t2),\n m.hausdorff_distance_pd(t2, t1)\n )\n self.assertAlmostEqual(\n 629,\n m.hausdorff_distance_pd(t2, t1) / 1000,\n 0\n )\n self.assertAlmostEqual(\n np.sqrt(np.sum(np.square(np.array([5, 5]) - np.array([1, 1])))),\n m.hausdorff_distance_pd(t2, t1, use_haversine=False),\n 0\n )\n\n def test_haversine_vector(self):\n self.assertAlmostEqual(\n 941,\n haversine(\n (50.0359, 5.4253), (58.3838, 3.0412)\n ),\n 0\n )\n self.assertAlmostEqual(\n 132,\n haversine(\n (50., 40.), (51., 41.)\n ),\n 0\n )\n self.assertAlmostEqual(\n 2356,\n haversine(\n (5., 80.), (15., 99.)\n ),\n 0\n )\n\n def test_haversine_vector_pd(self):\n t1 = [[50.0359, 5.4253]]\n t2 = [[58.3838, 3.0412]]\n self.assertAlmostEqual(\n 941,\n haversine_vector(t1, t2)[0],\n 0\n )\n t1 = [\n [50.0359, 5.4253],\n [50., 40.],\n [5., 80.]\n ]\n t2 = [\n [58.3838, 3.0412],\n [51., 41.],\n [15., 99.]\n ]\n tmp = m.haversine_vector(t1, t2)\n for i, v in enumerate([941, 132, 2356]):\n self.assertAlmostEqual(\n v,\n tmp[i],\n 0\n )\n\n def test_jaccard_index(self):\n t1 = [\n [0, 0],\n [2, 2],\n [2, 0],\n [0, 2],\n [1, 1]\n ]\n self.assertAlmostEqual(\n 1,\n m.jaccard_index(t1, t1)\n )\n t2 = [\n [0, 0],\n [-2, -2],\n [-2, 0],\n [0, -2],\n [-1, -1]\n ]\n self.assertAlmostEqual(\n 0,\n m.jaccard_index(t1, t2)\n )\n t3 = [\n [0, 0],\n [1, 1],\n [1, 0],\n [0, 1],\n [0.5, 0.5]\n ]\n self.assertAlmostEqual(\n 0.25,\n m.jaccard_index(t1, t3)\n )\n t3 = [\n [0, 0],\n [1, 2],\n [1, 0],\n [0, 2],\n [0.5, 0.5]\n ]\n self.assertAlmostEqual(\n 0.5,\n m.jaccard_index(t1, t3)\n )\n","repo_name":"erik-buchholz/RAoPT","sub_path":"test/test_metrics.py","file_name":"test_metrics.py","file_ext":"py","file_size_in_byte":5048,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"27"} +{"seq_id":"99315420","text":"import sys\nr=sys.stdin.readline\nknight_move=[(2,-1),(2,1),(-2,1),(-2,-1),(1,2),(-1,2),(1,-2),(-1,-2)]\n#나이트의 이동 변위를 미리 생성\ncur=r().strip()\ncur=(ord(cur[0])-ord('a'),int(cur[1]))\n#현좌표를 ord함수로 변환하여 저장\nans=0\nfor dx,dy in knight_move:\n nx,ny=cur[0]+dx,cur[1]+dy\n if 1<=nx<=8 and 1<=ny<=8:\n ans+=1\nprint(ans)\n\n#시공간에 큰 변수는 없어보인다\n#변위를 어떻게나타낼지 생각해보면 매우 간단","repo_name":"murane/PS","sub_path":"Python/동빈북/구현/4-2_왕실의나이트.py","file_name":"4-2_왕실의나이트.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18612901397","text":"# -*- coding: utf-8 -*-\r\n\r\nimport json\r\nimport pytz\r\nfrom datetime import datetime, timedelta\r\nfrom django.views.generic import TemplateView\r\nfrom django.http import JsonResponse\r\nfrom django.utils.timezone import make_aware\r\nfrom django.utils import timezone\r\nfrom django.conf import settings\r\nfrom django.contrib.auth.mixins import LoginRequiredMixin\r\n\r\nfrom web.models import AgendaEvento, AgendaEventoColor, AgendaEventoPredefinido\r\nfrom web.views.eventoPredefinido import get_color\r\nfrom web.util.utiles import is_ajax\r\n\r\n\r\ndef defecto_agenda(request):\r\n if AgendaEventoColor.objects.filter(usuario=request.user).exists():\r\n return\r\n\r\n for color in ['#00ACAC', '#348FE2', '#F59C1A', '#FF5B57', '#2D353C', '#32A932', '#FV5597']:\r\n c = AgendaEventoColor()\r\n c.usuario = request.user\r\n c.color = color\r\n c.save()\r\n\r\n p = AgendaEventoPredefinido()\r\n p.usuario = request.user\r\n p.color = AgendaEventoColor.objects.get(usuario=request.user, color='#00ACAC')\r\n p.inicio = '00:00'\r\n p.duracion = 60 * 24\r\n p.titulo = 'Viaje'\r\n p.save()\r\n\r\n p = AgendaEventoPredefinido()\r\n p.usuario = request.user\r\n p.color = AgendaEventoColor.objects.get(usuario=request.user, color='#348FE2')\r\n p.inicio = '15:30'\r\n p.duracion = 60\r\n p.titulo = 'Reunión'\r\n p.save()\r\n\r\n\r\nclass CalendarioView(LoginRequiredMixin, TemplateView):\r\n template_name = 'web/calendario/calendario.html'\r\n\r\n def dispatch(self, request, *args, **kwargs):\r\n defecto_agenda(request)\r\n return super().dispatch(request, *args, **kwargs)\r\n\r\n def get_context_data(self, **kwargs):\r\n context = super().get_context_data(**kwargs)\r\n eventos = list()\r\n for q in AgendaEventoPredefinido.objects.filter(usuario=self.request.user):\r\n eventos.append({\r\n 'id': q.pk,\r\n 'title': q.titulo,\r\n 'inicio': q.inicio,\r\n 'duracion': q.horas,\r\n 'color': q.color.color,\r\n })\r\n context['eventos'] = eventos\r\n context['nav_activa'] = 'calendario'\r\n return context\r\n\r\n def get_colores(self, request):\r\n term = request.POST.get('term')\r\n page = int(request.POST.get('page'))\r\n\r\n limit = 100\r\n offset = (page - 1) * limit\r\n\r\n query = AgendaEventoColor.objects.filter(usuario=self.request.user)\r\n if term:\r\n query.filter(color__icontains=term)\r\n\r\n query = query.order_by('color')\r\n count = query.count()\r\n query = query[offset:limit + offset]\r\n\r\n data = list()\r\n for d in query:\r\n data.append({\r\n 'id': d.pk,\r\n 'text': d.color,\r\n })\r\n\r\n final = offset + limit\r\n mas = count > final\r\n\r\n resul = {\r\n 'results': data,\r\n 'pagination': {\r\n 'more': mas\r\n }\r\n }\r\n return JsonResponse(resul, safe=False)\r\n\r\n def getall_colores(self):\r\n data = AgendaEventoColor.objects.filter(usuario=self.request.user).values_list('id', 'color')\r\n return JsonResponse({'err': False, 'param': list(data)}, safe=False)\r\n\r\n def post(self, request, *args, **kwargs):\r\n if is_ajax(request):\r\n param = request.POST.get('param')\r\n if param:\r\n if param == 'colores': # llama select2\r\n return self.get_colores(request)\r\n\r\n param = json.loads(param)\r\n accion = param.get('accion')\r\n data = param.get('data', dict())\r\n if accion == 'colores':\r\n return self.getall_colores()\r\n elif accion == 'agendaEvento':\r\n q = AgendaEvento.objects.filter(pk=param.get('id')).first()\r\n data = {field.name: str(getattr(q, field.name)) for field in AgendaEvento._meta.fields}\r\n return JsonResponse({'err': False, 'param': data}, safe=False)\r\n elif accion == 'borra':\r\n AgendaEvento.objects.filter(pk=data.get('id')).delete()\r\n else:\r\n if accion == 'receive':\r\n inicio = datetime.strptime(data.get('start'), '%d/%m/%Y %H:%M')\r\n inicio = pytz.timezone(settings.TIME_ZONE).localize(inicio).astimezone(pytz.timezone('UTC'))\r\n pre = AgendaEventoPredefinido.objects.filter(pk=data.get('id')).first()\r\n aevt = AgendaEvento()\r\n aevt.usuario = request.user\r\n aevt.color = pre.color\r\n aevt.titulo = pre.titulo\r\n aevt.dia_completo = True if pre.duracion % (60*24) == 0 and pre.inicio == '00:00' else False\r\n aevt.inicio = inicio\r\n aevt.fin = aevt.inicio + timedelta(minutes=pre.duracion)\r\n else:\r\n if accion in ['resize', 'drop']:\r\n aevt = AgendaEvento.objects.filter(pk=data.get('id')).first()\r\n elif accion == 'actualiza':\r\n color = data.get('color')\r\n qcolor = get_color(request, color)\r\n aevt = AgendaEvento.objects.filter(pk=data.get('id')).first()\r\n if not aevt:\r\n aevt = AgendaEvento()\r\n aevt.usuario = request.user\r\n aevt.color = qcolor\r\n aevt.titulo = data.get('titulo')\r\n aevt.dia_completo = True if data.get('completo', '') == 'on' else False\r\n aevt.aviso_email = True if data.get('email') == 'on' else False\r\n aevt.aviso_movil = True if data.get('movil') == 'on' else False\r\n\r\n aevt.email_enviado = None\r\n aevt.movil_enviado = None\r\n\r\n inicio = datetime.strptime(data.get('inicio'), '%d/%m/%Y %H:%M')\r\n if data.get('fin', ''):\r\n try:\r\n fin = datetime.strptime(data.get('fin'), '%d/%m/%Y %H:%M')\r\n except:\r\n fin = inicio\r\n else:\r\n fin = inicio\r\n aevt.dia_completo = True\r\n\r\n inicio = pytz.timezone(settings.TIME_ZONE).localize(inicio).astimezone(pytz.timezone('UTC'))\r\n fin = pytz.timezone(settings.TIME_ZONE).localize(fin).astimezone(pytz.timezone('UTC'))\r\n\r\n if inicio > fin:\r\n aevt.inicio = fin\r\n aevt.fin = inicio\r\n elif inicio == fin: # si son iguales añado un minuto\r\n aevt.inicio = inicio\r\n aevt.fin = fin + timedelta(minutes=1)\r\n else:\r\n aevt.inicio = inicio\r\n aevt.fin = fin\r\n aevt.save()\r\n return JsonResponse({'err': None, \"param\": {}})\r\n else:\r\n start = datetime.strptime(request.POST.get('start'), '%Y-%m-%dT%H:%M:%S.%fZ')\r\n end = datetime.strptime(request.POST.get('end'), '%Y-%m-%dT%H:%M:%S.%fZ')\r\n aware_start = make_aware(start)\r\n aware_end = make_aware(end)\r\n data = list()\r\n for q in AgendaEvento.objects.filter(usuario=self.request.user, inicio__lte=aware_end, fin__gte=aware_start):\r\n inicio = timezone.localtime(q.inicio)\r\n fin = timezone.localtime(q.fin)\r\n start = inicio.strftime('%Y-%m-%d') if q.dia_completo else inicio.strftime('%Y-%m-%d %H:%M:%S')\r\n end = fin.strftime('%Y-%m-%d') if q.dia_completo else fin.strftime('%Y-%m-%d %H:%M:%S')\r\n data.append({\r\n 'id': q.pk,\r\n 'title': q.titulo,\r\n 'start': start,\r\n 'end': end,\r\n 'color': q.color.color,\r\n })\r\n return JsonResponse({'data': data})\r\n","repo_name":"juhegue/notas","sub_path":"web/views/calendario.py","file_name":"calendario.py","file_ext":"py","file_size_in_byte":8459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"28117026656","text":"# For Streamlit:\n\nfrom __future__ import absolute_import, division, print_function\nimport random\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport streamlit as st\nimport tensorflow as tf\nfrom PIL import Image\nfrom tensorflow import keras\nfrom keras import Model, layers\nfrom keras.datasets import mnist\nimport io\n\n\n# Below is markdown for Streamlit.\nst.title('Neural Network Example')\n\nst.subheader('Neural Network Example Using Streamlit Framework')\n\nst.image(Image.open('pict/neural_network_overview.jfif'), caption='', width=400)\n\nst.markdown(\n \"\"\"\n The object was to build a 2-hidden layers fully connected neural network (a.k.a multilayer perceptron) with TensorFlow.\n\n This example is using a low-level approach to better understand all mechanics behind building neural networks and the training process.\n\n You can find example used in Jupyter Notebooks here:\n https://github.com/aymericdamien/TensorFlow-Examples/blob/master/tensorflow_v2/notebooks/3_NeuralNetworks/neural_network.ipynb\n\n This example is using MNIST handwritten digits (picture below). The dataset contains 60,000 examples for training and 10,000 examples for testing. The digits have been size-normalized and centered in a fixed-size image (28x28 pixels) with values from 0 to 255.\n\n In this example, each image will be converted to float32, normalized to [0, 1] and flattened to a 1-D array of 784 features (28*28).\n\n \"\"\", unsafe_allow_html=True)\n\nst.image(Image.open('pict/mnist_dataset_overview.png'), caption='')\n\n# MNIST dataset parameters.\nnum_classes = 10 # total classes (0-9 digits).\nnum_features = 784 # data features (img shape: 28*28).\n\n# Initial Training parameters.\nlearning_rate = 0.1\ntraining_steps = 2000\nbatch_size = 256\ndisplay_step = 100\n\n# Form Streamlit Input\n\nst.markdown(\n \"\"\"\nDefault training parameters:\n\n**Learning Rate** = 0.1\n\n**Training Steps** = 2000\n\n**Batch Size** = 256\n\n**Display Step** = 100\n \"\"\"\n)\n\n# Initialize shuffle_button_state\nst.session_state.shuffle_button_state = st.session_state.shuffle_button_state if hasattr(\n st.session_state, 'shuffle_button_state') else False\n\nwith st.form(\"initial_params\"):\n st.markdown(\"**Change default parameters**\")\n training_steps = st.number_input(\n label='Training steps: ', value=training_steps, step=50)\n display_step = st.number_input(\n label=\"Display step: \", value=display_step, step=50)\n learning_rate = st.number_input(\n label='learning rate: ', value=learning_rate, step=.1)\n batch_size = st.number_input(\n label=\"batch size: \", value=batch_size)\n\n # Every form must have a submit button.\n if not st.form_submit_button(\"Apply\"):\n if not st.session_state.shuffle_button_state:\n st.stop()\n\n\n# Below is markdown for Streamlit.\nst.markdown(\n \"\"\"\n\nMNIST default dataset parameters.\n\n**Number of classes** = 10 (total classes 0-9 digits).\n\n**Number of features** = 784 (data features).\n\n \"\"\"\n)\n\n\n# Network parameters.\nn_hidden_1 = 128 # 1st layer number of neurons.\nn_hidden_2 = 256 # 2nd layer number of neurons.\n\n# Prepare MNIST data.\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n# Convert to float32.\nx_train, x_test = np.array(x_train, np.float32), np.array(x_test, np.float32)\n# Flatten images to 1-D vector of 784 features (28*28).\nx_train, x_test = x_train.reshape(\n [-1, num_features]), x_test.reshape([-1, num_features])\n# Normalize images value from [0, 255] to [0, 1].\nx_train, x_test = x_train / 255., x_test / 255.\n# Use tf.data API to shuffle and batch data.\ntrain_data = tf.data.Dataset.from_tensor_slices((x_train, y_train))\ntrain_data = train_data.repeat().shuffle(5000).batch(batch_size).prefetch(1)\n\n\n# Create TF Model.\n# NeuralNet class is based on Keras Model class\nclass NeuralNet(Model):\n # Set layers.\n def __init__(self):\n super(NeuralNet, self).__init__()\n # First fully-connected hidden layer.\n self.fc1 = layers.Dense(n_hidden_1, activation=tf.nn.relu)\n # First fully-connected hidden layer.\n self.fc2 = layers.Dense(n_hidden_2, activation=tf.nn.relu)\n # Second fully-connecter hidden layer.\n self.out = layers.Dense(num_classes)\n\n # Set forward pass.\n def call(self, x, is_training=False):\n x = self.fc1(x)\n x = self.fc2(x)\n x = self.out(x)\n if not is_training:\n # tf cross entropy expect logits without softmax, so only\n # apply softmax when not training.\n x = tf.nn.softmax(x)\n return x\n\n\n# Build neural network model.\nneural_net = NeuralNet()\n# Cross-Entropy Loss.\n# Note that this will apply 'softmax' to the logits.\n\n\ndef cross_entropy_loss(x, y):\n # Convert labels to int 64 for tf cross-entropy function.\n y = tf.cast(y, tf.int64)\n # Apply softmax to logits and compute cross-entropy.\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=x)\n # Average loss across the batch.\n return tf.reduce_mean(loss)\n\n# Accuracy metric.\n\n\ndef accuracy(y_pred, y_true):\n # Predicted class is the index of highest score in prediction vector (i.e. argmax).\n correct_prediction = tf.equal(\n tf.argmax(y_pred, 1), tf.cast(y_true, tf.int64))\n return tf.reduce_mean(tf.cast(correct_prediction, tf.float32), axis=-1)\n\n\n# Stochastic gradient descent optimizer.\noptimizer = tf.optimizers.SGD(learning_rate)\n# Optimization process.\n\n\ndef run_optimization(x, y):\n # Wrap computation inside a GradientTape for automatic differentiation.\n with tf.GradientTape() as g:\n # Forward pass.\n pred = neural_net(x, is_training=True)\n # Compute loss.\n loss = cross_entropy_loss(pred, y)\n\n # Variables to update, i.e. trainable variables.\n trainable_variables = neural_net.trainable_variables\n\n # Compute gradients.\n gradients = g.gradient(loss, trainable_variables)\n\n # Update W and b following gradients.\n optimizer.apply_gradients(zip(gradients, trainable_variables))\n\n\n# Run training for the given number of steps.\nst.markdown(\n \"\"\"\n\n **_The results below are for the training that was ran for the given number of steps._**\n\n \"\"\", unsafe_allow_html=True)\n\n\n@st.experimental_singleton\ndef train_model(training_steps, display_step, learning_rate, batch_size):\n step_list = []\n loss_list = []\n acc_list = []\n\n for step, (batch_x, batch_y) in enumerate(train_data.take(training_steps), 1):\n # Run the optimization to update W and b values.\n run_optimization(batch_x, batch_y)\n\n if step % display_step == 0:\n pred = neural_net(batch_x, is_training=True)\n loss = cross_entropy_loss(pred, batch_y)\n acc = accuracy(pred, batch_y)\n\n step_list.append(step)\n loss_list.append(loss)\n acc_list.append(acc)\n return step_list, loss_list, acc_list, neural_net\n\n\nstep_list, loss_list, acc_list, neural_net = train_model(\n training_steps, display_step, learning_rate, batch_size)\n\ndf = pd.DataFrame(\n data={\"Step\": step_list, \"Loss\": loss_list, \"Accuracy\": acc_list}\n)\n\n# CSS to inject contained in a string to hide index (first column) in Streamlit app.\nhide_table_row_index = \"\"\"\n \n \"\"\"\n\n# Inject CSS with Markdown (in Streamlit)\nst.markdown(hide_table_row_index, unsafe_allow_html=True)\n\nst.table(df)\n\n# Test model on validation set.\npred = neural_net(x_test, is_training=False)\n\n# Below is markdown for Streamlit.\nst.markdown(\n \"\"\"\n Test model on validation set.\n\n **_Test Accuracy:_**\n\n \"\"\", unsafe_allow_html=True)\n\nst.write(\"Test Accuracy: %f\" % accuracy(pred, y_test))\n\n# Visualize predictions.\n# Predict and provide 5 random images from data set.\nn_images = 5\n\n\ndef shuffle_images():\n st.session_state.shuffle_button_state = True\n st.session_state.test_images = []\n for i in range(n_images):\n rand_index = random.randint(0, len(x_test)-1)\n st.session_state.test_images.append(x_test[rand_index])\n st.session_state.test_images = np.array(st.session_state.test_images)\n\n\nif (not hasattr(st.session_state, 'test_images')):\n shuffle_images()\n\npredictions = neural_net(st.session_state.test_images)\n\n# Below is markdown for Streamlit.\nst.markdown(\n \"\"\"\n **_Model and image predictions are displayed below._**\n \"\"\", unsafe_allow_html=True)\n\n# Display image and model prediction.\nfor i in range(n_images):\n plt.imshow(np.reshape(\n st.session_state.test_images[i], [28, 28]), cmap='gray')\n\n with io.BytesIO() as img_buf:\n plt.savefig(img_buf, format='png')\n st.image(img_buf, width=200)\n\n st.write(\"Model prediction: %i\" % np.argmax(predictions.numpy()[i]))\n\n\nst.markdown(\n \"\"\"\n \n ***If you want to reshuffle images, click the button below.***\n\n \"\"\"\n)\n\n# Button Widget in Streamlit\nst.button(\"Shuffle Images\", on_click=shuffle_images)\n","repo_name":"PolusAI/examples","sub_path":"tutorials/streamlit/MNIST/neural-model.py","file_name":"neural-model.py","file_ext":"py","file_size_in_byte":9013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18383845282","text":"#Pong Game based on this tutorial -https://youtu.be/LH8WgrUWG_I\n#Added graphics and sound\n#Add a game start countdown\n# I played around with the Ai made it somtimes go in the wrong direction !!\n# 2 Balls after 5 Points \n# Countdown before play\n#Created on IDLE on Mac sound would need to be changed for Windows or Linux\n\n#Need to do this to get the keys to repeat\n\n#defaults write -g ApplePressAndHoldEnabled -bool false\n\n\n\nimport turtle\nimport os\nimport time\nimport random\n\n\nwn = turtle.Screen()\nwn.title (\"Pong Game\")\nwn.bgcolor(\"Black\")\nwn.setup(width=800, height=600)\nwn.tracer(0)\nwn.bgpic(\"Stars_800_600.gif\")\n#Score\nscore_a = 0\nscore_b = 0\n\n\n#Paddle A\npaddle_a = turtle.Turtle()\nturtle.register_shape(\"paddle_a.gif\")\npaddle_a.speed(0)\npaddle_a.shape(\"paddle_a.gif\")\n#paddle_a.color(\"cyan\")\n#paddle_a.shapesize(stretch_wid=5, stretch_len=1)\npaddle_a.penup()\npaddle_a.goto(-350, 0)\n\n#Paddle B\npaddle_b = turtle.Turtle()\nturtle.register_shape(\"paddle_b.gif\")\npaddle_b.speed(0)\npaddle_b.shape(\"paddle_b.gif\")\n#paddle_b.color(\"magenta\")\n#paddle_b.shapesize(stretch_wid=5, stretch_len=1)\npaddle_b.penup()\npaddle_b.goto(350, 0)\n\n#Ball\nball1 = turtle.Turtle()\nball1.speed(0)\nball1.shape(\"square\")\nball1.color(\"yellow\")\nball1.penup()\nball1.goto(0, 0)\nball1.dx = 3\nball1.dy = 3\n\n#Ball 2\nball2 = turtle.Turtle()\nball2.speed(0)\nball2.shape(\"square\")\nball2.color(\"yellow\")\nball2.penup()\nball2.goto(0, 0)\nball2.dx = -2\nball2.dy = 2\nball2.ht()\n\n#Ball 3\nball3 = turtle.Turtle()\nball3.speed(0)\nball3.shape(\"square\")\nball3.color(\"yellow\")\nball3.penup()\nball3.goto(0, 0)\nball3.dx = 1\nball3.dy = -1\nball3.ht()\n\n#ball 2\nball4 = turtle.Turtle()\nball4.speed(0)\nball4.shape(\"square\")\nball4.color(\"yellow\")\nball4.penup()\nball4.goto(0, 0)\nball4.dx = -1\nball4.dy = 1\nball4.ht()\n\n#balls = [ball1, ball2, ball3, ball4]\nballs = [ball1]\n\nballcount =1\n\n#Pen\npen = turtle.Turtle()\npen.speed(0)\npen.color(\"white\")\npen.penup()\npen.hideturtle()\npen.goto(0, 260)\npen.write(\"Player A: 0 Player B: 0\", align=\"center\", font=(\"Courier\", 24, \"normal\"))\n\n#Pen\npen2 = turtle.Turtle()\npen2.speed(0)\npen2.color(\"white\")\npen2.penup()\npen2.hideturtle()\npen2.goto(0, 0)\n\n#Functions\ndef paddle_a_up():\n y = paddle_a.ycor()\n y += 25\n paddle_a.sety(y)\n\ndef paddle_a_down():\n y = paddle_a.ycor()\n y -= 25\n paddle_a.sety(y)\n\ndef paddle_b_up():\n y = paddle_b.ycor()\n y += 20\n paddle_b.sety(y)\n\ndef paddle_b_down():\n y = paddle_b.ycor()\n y -= 20\n paddle_b.sety(y)\n\n #AI function\n\ndef paddle_bai_up():\n y = paddle_b.ycor()\n y += (random.randint(-4,10))\n paddle_b.sety(y)\n\ndef paddle_bai_down():\n y = paddle_b.ycor()\n y -= (random.randint(-4,10))\n paddle_b.sety(y)\n\ndef time_delay():\n time_stamp = time.time()\n while time.time() < time_stamp + 20:\n print() \ndef count_down():\n\n for count in range(3,0,-1):\n os.system(\"afplay sfx_menu_move4.wav&\")\n pen2.write((count), align=\"center\", font=(\"Courier\", 30, \"normal\"))\n \n time.sleep(1)\n pen2.clear()\n \n \n \n\n#Keyboard binding onkey or onkeypress\nwn.listen()\nwn.onkey(paddle_a_up, \"w\")\nwn.onkey(paddle_a_down, \"s\")\nwn.onkey(paddle_b_up, \"Up\")\nwn.onkey(paddle_b_down, \"Down\")\n\ncount_down()\n\n# Main Game Loop\nwhile True:\n wn.update()\n for ball in balls:\n \n #Move the ball\n ball.setx(ball.xcor() + ball.dx)\n ball.sety(ball.ycor() + ball.dy)\n\n \n\n #Border Checking\n if ball.ycor() > 290:\n ball.sety(290)\n ball.dy *= -1\n os.system(\"afplay bounce.wav&\")\n\n if ball.ycor() < -290:\n ball.sety(-290)\n ball.dy *= -1\n os.system(\"afplay bounce.wav&\")\n \n if ball.xcor() > 390:\n ball.goto(0, 0)\n ball.dx *= -1\n score_a += 1\n pen.clear()\n pen.write(\"Player A: {} Player B: {}\".format(score_a, score_b), align=\"center\", font=(\"Courier\", 24, \"normal\"))\n os.system(\"afplay sfx_sounds_falling3.wav&\")\n #Pause countdown\n count_down()\n\n \n if ball.xcor() < -390:\n ball.goto(0, 0)\n ball.dx *= -1\n score_b +=1\n pen.clear()\n pen.write(\"Player A: {} Player B: {}\".format(score_a, score_b), align=\"center\", font=(\"Courier\", 24, \"normal\"))\n os.system(\"afplay sfx_sounds_falling3.wav&\")\n #Pause countdown\n count_down()\n\n \n#Paddle and Ball collisions\n\n if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_b.ycor() +50 and ball.ycor() > paddle_b.ycor() -50):\n ball.setx(340)\n ball.dx *= -1\n ball.color(\"magenta\")\n \n os.system(\"afplay bounce.wav&\")\n \n if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddle_a.ycor() +50 and ball.ycor() > paddle_a.ycor() -50):\n ball.setx(-340)\n ball.dx *= -1\n ball.color(\"cyan\")\n os.system(\"afplay bounce.wav&\")\n\n\n\n\n # AI Player\n closest_ball = balls[0]\n for ball in balls:\n if ball.xcor() > closest_ball.xcor():\n closest_ball = ball\n\n #if ball.xcor() > ball2.xcor():\n if paddle_b.ycor() < closest_ball.ycor() and abs(paddle_b.ycor() -closest_ball.ycor()) > 10: \n paddle_bai_up()\n\n elif paddle_b.ycor() > closest_ball.ycor()and abs(paddle_b.ycor() -closest_ball.ycor()) > 10: \n paddle_bai_down()\n\n \n if score_a >4 or score_b>4:\n if ballcount == 1:\n balls.append(ball2)\n ball2.st()\n ballcount = 2\n \n \n \n \n \n \n \n","repo_name":"manleystudios/Pong-Game","sub_path":"Pong Game - Turtle .py","file_name":"Pong Game - Turtle .py","file_ext":"py","file_size_in_byte":5676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"15792893692","text":"from setuptools import setup, find_packages\nfrom codecs import open\nfrom os import path\n\n__version__ = '1.5.1'\n\nhere = path.abspath(path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\n# get the dependencies and installs\nwith open(path.join(here, 'requirements.txt'), encoding='utf-8') as f:\n all_reqs = f.read().split('\\n')\n\ninstall_requires = [x.strip() for x in all_reqs if 'git+' not in x]\ndependency_links = [x.strip().replace('git+', '') for x in all_reqs if x.startswith('git+')]\n\nsetup(\n name='knmy',\n version=__version__,\n description='Python package for downloading and processing weather data from the automated weather stations of the Dutch Meteorological Institute (KNMI).',\n long_description=long_description,\n url='https://github.com/barthoekstra/knmy',\n download_url='https://github.com/barthoekstra/knmy/tarball/' + __version__,\n license='BSD',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'Programming Language :: Python :: 3',\n ],\n keywords='',\n packages=find_packages(exclude=['docs', 'tests*']),\n include_package_data=True,\n setup_requires=['pytest-runner'],\n tests_require=['mock', 'pytest', 'sh>=1.08'],\n author='Bart Hoekstra',\n install_requires=install_requires,\n dependency_links=dependency_links,\n author_email='barthoekstra@gmail.com',\n python_requires='>=3.4',\n)\n","repo_name":"barthoekstra/knmy","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"36327226766","text":"class MyClass:\n variable = 42\n\n def foo(self): # We'll explain self parameter later\n print(\"Hello from function foo\")\n\n\n# `my_object` holds an object of the class \"MyClass\" that contains\n# the `variable` and the `foo` function\nmy_object = MyClass()\n\nmy_object.foo() # Calls the `foo` method defined in MyClass\nprint(my_object.variable) # Prints the value of the `variable` attribute defined in MyClass\n","repo_name":"jetbrains-academy/introduction_to_python","sub_path":"Classes and objects/Definition/class_definition.py","file_name":"class_definition.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"27"} +{"seq_id":"9900712399","text":"import torch\nimport os\nfrom IPython import embed\n\n\ndef save_checkpoint(path, epoch, model, optimizer, accuracy):\n '''\n 保存三个键值对,epoch,整个model,optimizer(lr)\n '''\n state_dict = {\n 'epoch': epoch,\n 'model': model.state_dict(),\n 'optimizer': optimizer,\n 'acc': accuracy}\n torch.save(state_dict, path)\n\n\ndef load_checkpoint(path, model, optimizer=None, model_only=False):\n '''\n 将path路径下的文件加载到model和optimizer, epoch赋给start_epoch\n return start_epoch 开始的epoch\n '''\n if not os.path.exists(path):\n print('Sorry, don\\'t have checkpoint.pth file, continue training!')\n return 0, 0\n checkpoint = torch.load(path)\n model.load_state_dict(checkpoint['model'])\n if model_only:\n return\n optimizer = checkpoint['optimizer']\n start_epoch = checkpoint['epoch']\n acc = checkpoint['acc']\n return start_epoch, acc\n # return start_epoch\n\n\ndef load_acc(path):\n checkpoint = torch.load(path)\n acc = checkpoint['acc']\n return acc\n\n\n# print(load_acc('../checkpoints/checkpoint_resnet18.pth.tar'))\n","repo_name":"dingjiongfeng/One-pixel-attack","sub_path":"utils/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"34085186900","text":"n = int(input(\"n=\"))\n\n\nfor a in range(n+1):\n continue\nlst = []\ni = 2\nwhile i <= n:\n if a[i] != 0:\n lst.append(a[i])\n for j in range(i, n+1, i):\n a[j] = 0\n i += 1\nprint(lst)","repo_name":"David2261/Python_Algorithms","sub_path":"grokking_algorithms/sieve_eratosthenes.py","file_name":"sieve_eratosthenes.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"20811088779","text":"import pytest\nfrom bable_interface.models import Packet\nfrom bable_interface.BaBLE import Payload, ReadCentral\n\n\ndef test_build():\n \"\"\" Test building a packet. \"\"\"\n packet = Packet.build(\n payload_module=ReadCentral,\n controller_id=0,\n connection_handle=0x0040,\n attribute_handle=0x0003\n )\n\n assert isinstance(packet, Packet)\n assert packet.controller_id == 0\n assert packet.payload_type == Payload.Payload.ReadCentral\n assert packet.get('connection_handle') == 0x0040\n assert packet.get('attribute_handle') == 0x0003\n\n # Try to get a parameter that does not exist in the protocol\n with pytest.raises(KeyError):\n Packet.build(\n payload_module=ReadCentral,\n does_not_exist=\"test\"\n )\n\n\ndef test_extract():\n \"\"\" Test extract packet information from raw bytes. \"\"\"\n # These raw bytes are from the ReadCentral packet built in test_build()\n raw_payload = bytearray(b'\\x10\\x00\\x00\\x00\\x0c\\x00\\x10\\x00\\x0c\\x00\\x09\\x00\\x04\\x00\\x0a\\x00\\x0c\\x00\\x00\\x00\\x1c\\x00'\n b'\\x00\\x00\\x00\\x0b\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x08\\x00\\x08\\x00'\n b'\\x06\\x00\\x04\\x00\\x08\\x00\\x00\\x00\\x03\\x00\\x40\\x00')\n packet = Packet.extract(raw_payload)\n\n assert isinstance(packet, Packet)\n assert packet.controller_id == 0\n assert packet.payload_type == Payload.Payload.ReadCentral\n assert packet.get('connection_handle') == 0x0040\n assert packet.get('attribute_handle') == 0x0003\n\n # Test with a wrong payload bytes (random)\n raw_payload2 = bytearray(b'\\x10\\x00\\x00\\x00\\x0c\\x00')\n with pytest.raises(Exception):\n Packet.extract(raw_payload2)\n\n\ndef test_serialize():\n \"\"\" Test to serialize a packet (getting raw bytes from packet object). \"\"\"\n packet = Packet(\n payload_type=Payload.Payload.ReadCentral,\n controller_id=0,\n connection_handle=0x0040,\n attribute_handle=0x0003\n )\n\n assert packet.serialize() is not None\n\n\ndef test_get():\n \"\"\" Test to get packet parameters. \"\"\"\n packet = Packet(\n payload_type=Payload.Payload.ReadCentral,\n controller_id=0,\n connection_handle=0x0040,\n attribute_handle=0x0003\n )\n\n # Test to get a single parameter\n assert packet.get('connection_handle') == 0x0040\n\n # Test to get a dictionary with multiple parameters\n expected_dict = {'connection_handle': 0x0040, 'attribute_handle': 0x0003}\n assert packet.get_dict(['connection_handle', 'attribute_handle']) == expected_dict\n\n # Test to get a dictionary with format function\n expected_dict['attribute_handle'] = 'test'\n assert packet.get_dict(['connection_handle', ('attribute_handle', lambda value: 'test')]) == expected_dict\n","repo_name":"iotile/baBLE","sub_path":"interfaces/python/tests/test_packet.py","file_name":"test_packet.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"27"} +{"seq_id":"20357562768","text":"import pandas as pd\nfrom pessoa import Pessoa\n\nlista = []\n\nwith pd.ExcelFile(\"teste1.xlsx\") as f:\n data_frame = pd.read_excel(f);\n # Percorrendo o DataFrame linha a linha para manipula-lo com precisao \n for indice, coluna in data_frame.iterrows():\n # print(indice, coluna[\"alunos\"], coluna[\"idades\"])\n\n # Criando objetos da minha classe Pessoa com as linhas do DataFrame\n obj = Pessoa(coluna[\"alunos\"], coluna[\"idades\"])\n lista.append(obj)\n\nfor pessoas in lista:\n print(pessoas)","repo_name":"BrunoEMedeiros/PythonUnifafibe_2023","sub_path":"final/exemplo2.py","file_name":"exemplo2.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"1009442044","text":"from app import db\nfrom app.models.board import Board\nfrom app.models.card import Card\nfrom flask import request, Blueprint, make_response, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nimport datetime\nfrom datetime import datetime, date, time, timezone\nfrom dotenv import load_dotenv\nimport os\nimport requests\nimport json\n\nboards_bp = Blueprint(\"boards\", __name__, url_prefix=\"/boards\")\ncards_bp = Blueprint(\"cards\", __name__, url_prefix=\"/cards\")\n\ndef post_message_to_slack(text, blocks=None):\n requests.post('https://slack.com/api/chat.postMessage',\n headers={'Authorization': f\"Bearer {os.environ.get('SLACK_BOT_TOKEN')}\"},\n data={'channel': f\"{os.environ.get('SLACK_CHANNEL')}\", 'text': text})\n\n@boards_bp.route(\"\", methods=[\"GET\"], strict_slashes=False)\ndef boards_index():\n \n boards = Board.query.all()\n boards_response = []\n \n if boards is None:\n return jsonify(boards_response), 200\n\n else:\n for board in boards:\n boards_response.append({\n \"id\": board.board_id,\n \"title\": board.title,\n \"owner\": board.owner\n })\n return jsonify(boards_response), 200\n\n\n@boards_bp.route(\"\", methods=[\"POST\"], strict_slashes=False)\ndef handle_boards():\n request_body = request.get_json()\n\n if \"title\" not in request_body or \"owner\" not in request_body:\n return jsonify({\"details\": \"Invalid data\"}), 400\n \n new_board = Board(title= request_body[\"title\"],\n owner= request_body[\"owner\"])\n\n db.session.add(new_board)\n db.session.commit()\n\n return jsonify({\"id\": new_board.title}), 201\n\n\n@boards_bp.route(\"//cards\", methods=[\"GET\"], strict_slashes=False)\ndef handle_single_board(board_id):\n\n board = Board.query.get(board_id)\n cards = board.cards\n print(cards)\n\n if board is None:\n return jsonify(f\"board {board_id} doesn't exist.\"), 404\n \n else:\n board_cards = []\n \n for card in cards:\n board_cards.append({\"id\": card.card_id,\n \"message\": card.message, \n \"likes\": card.likes_count\n })\n \n return jsonify({\"id\": board.board_id,\n \"title\": board.title,\n \"owner\": board.owner,\n \"cards\": board_cards\n }), 200\n\n\n@boards_bp.route(\"/cards\", methods=[\"POST\"], strict_slashes=False)\ndef handle_board_cards(board_id):\n request_body = request.get_json()\n \n board = Board.query.get_or_404(board_id)\n\n if \"message\" not in request_body:\n return jsonify({\"details\": \"Invalid data\"}), 400\n\n elif len(request_body[\"message\"]) > 40:\n return jsonify({\"details\": \"message must be less than 40 characters.\"}), 400\n \n new_card = Card(message= request_body[\"message\"],\n board_id= board_id)\n\n db.session.add(new_card)\n db.session.commit()\n\n post_message = f\"A new card has been created on board #{board_id} with the following message: {new_card.message}.\"\n post_message_to_slack(post_message)\n\n return jsonify({\"id\": new_card.card_id,\n \"message\": new_card.message}), 201\n\n\n@cards_bp.route(\"/\", methods=[\"DELETE\"], strict_slashes=False)\ndef delete_single_card(card_id):\n card = Card.query.get(card_id)\n \n if card is None:\n return jsonify(f\"card {card_id} doesn't exist.\"), 404\n \n db.session.delete(card)\n db.session.commit()\n\n return jsonify(f\"id: {card_id} has been deleted.\"), 200\n\n\n@cards_bp.route(\"\", methods=[\"PUT\"], strict_slashes=False)\ndef handle_likes_count(card_id):\n \n card = Card.query.get(card_id)\n \n card.likes_count += 1\n \n db.session.commit()\n \n return jsonify({\"likes_count\": card.likes_count}), 200","repo_name":"seraphina97/back-end-inspiration-board","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"33641885661","text":"# coding: utf-8\n\n\"\"\"\n Netilion API Documentation\n\n Welcome to the Netilion API Documentation, which provides interactive access and documentation to our REST API. Please visit our developer portal for further instructions and information: https://developer.netilion.endress.com/ # noqa: E501\n\n OpenAPI spec version: 01.00.00\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nclass ThresholdResponse(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'id': 'int',\n 'name': 'str',\n 'description': 'str',\n 'key': 'str',\n 'unit_id': 'int',\n 'value': 'float',\n 'tolerance': 'float',\n 'threshold_type': 'str',\n 'notification': 'bool'\n }\n\n attribute_map = {\n 'id': 'id',\n 'name': 'name',\n 'description': 'description',\n 'key': 'key',\n 'unit_id': 'unit_id',\n 'value': 'value',\n 'tolerance': 'tolerance',\n 'threshold_type': 'threshold_type',\n 'notification': 'notification'\n }\n\n def __init__(self, id=None, name=None, description=None, key=None, unit_id=None, value=None, tolerance=None, threshold_type=None, notification=None): # noqa: E501\n \"\"\"ThresholdResponse - a model defined in Swagger\"\"\" # noqa: E501\n self._id = None\n self._name = None\n self._description = None\n self._key = None\n self._unit_id = None\n self._value = None\n self._tolerance = None\n self._threshold_type = None\n self._notification = None\n self.discriminator = None\n self.id = id\n self.name = name\n if description is not None:\n self.description = description\n self.key = key\n if unit_id is not None:\n self.unit_id = unit_id\n self.value = value\n self.tolerance = tolerance\n self.threshold_type = threshold_type\n self.notification = notification\n\n @property\n def id(self):\n \"\"\"Gets the id of this ThresholdResponse. # noqa: E501\n\n Id of object # noqa: E501\n\n :return: The id of this ThresholdResponse. # noqa: E501\n :rtype: int\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id):\n \"\"\"Sets the id of this ThresholdResponse.\n\n Id of object # noqa: E501\n\n :param id: The id of this ThresholdResponse. # noqa: E501\n :type: int\n \"\"\"\n if id is None:\n raise ValueError(\"Invalid value for `id`, must not be `None`\") # noqa: E501\n\n self._id = id\n\n @property\n def name(self):\n \"\"\"Gets the name of this ThresholdResponse. # noqa: E501\n\n name of the threshold. The name of the threshold. # noqa: E501\n\n :return: The name of this ThresholdResponse. # noqa: E501\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"Sets the name of this ThresholdResponse.\n\n name of the threshold. The name of the threshold. # noqa: E501\n\n :param name: The name of this ThresholdResponse. # noqa: E501\n :type: str\n \"\"\"\n if name is None:\n raise ValueError(\"Invalid value for `name`, must not be `None`\") # noqa: E501\n\n self._name = name\n\n @property\n def description(self):\n \"\"\"Gets the description of this ThresholdResponse. # noqa: E501\n\n description of the threshold. The description of the threshold. # noqa: E501\n\n :return: The description of this ThresholdResponse. # noqa: E501\n :rtype: str\n \"\"\"\n return self._description\n\n @description.setter\n def description(self, description):\n \"\"\"Sets the description of this ThresholdResponse.\n\n description of the threshold. The description of the threshold. # noqa: E501\n\n :param description: The description of this ThresholdResponse. # noqa: E501\n :type: str\n \"\"\"\n\n self._description = description\n\n @property\n def key(self):\n \"\"\"Gets the key of this ThresholdResponse. # noqa: E501\n\n key of the threshold. This key is related to the keys set in asset values. # noqa: E501\n\n :return: The key of this ThresholdResponse. # noqa: E501\n :rtype: str\n \"\"\"\n return self._key\n\n @key.setter\n def key(self, key):\n \"\"\"Sets the key of this ThresholdResponse.\n\n key of the threshold. This key is related to the keys set in asset values. # noqa: E501\n\n :param key: The key of this ThresholdResponse. # noqa: E501\n :type: str\n \"\"\"\n if key is None:\n raise ValueError(\"Invalid value for `key`, must not be `None`\") # noqa: E501\n\n self._key = key\n\n @property\n def unit_id(self):\n \"\"\"Gets the unit_id of this ThresholdResponse. # noqa: E501\n\n Id of the unit used for the threshold value property. # noqa: E501\n\n :return: The unit_id of this ThresholdResponse. # noqa: E501\n :rtype: int\n \"\"\"\n return self._unit_id\n\n @unit_id.setter\n def unit_id(self, unit_id):\n \"\"\"Sets the unit_id of this ThresholdResponse.\n\n Id of the unit used for the threshold value property. # noqa: E501\n\n :param unit_id: The unit_id of this ThresholdResponse. # noqa: E501\n :type: int\n \"\"\"\n\n self._unit_id = unit_id\n\n @property\n def value(self):\n \"\"\"Gets the value of this ThresholdResponse. # noqa: E501\n\n the threshold value # noqa: E501\n\n :return: The value of this ThresholdResponse. # noqa: E501\n :rtype: float\n \"\"\"\n return self._value\n\n @value.setter\n def value(self, value):\n \"\"\"Sets the value of this ThresholdResponse.\n\n the threshold value # noqa: E501\n\n :param value: The value of this ThresholdResponse. # noqa: E501\n :type: float\n \"\"\"\n if value is None:\n raise ValueError(\"Invalid value for `value`, must not be `None`\") # noqa: E501\n\n self._value = value\n\n @property\n def tolerance(self):\n \"\"\"Gets the tolerance of this ThresholdResponse. # noqa: E501\n\n the threshold tolerance, should be a positive value # noqa: E501\n\n :return: The tolerance of this ThresholdResponse. # noqa: E501\n :rtype: float\n \"\"\"\n return self._tolerance\n\n @tolerance.setter\n def tolerance(self, tolerance):\n \"\"\"Sets the tolerance of this ThresholdResponse.\n\n the threshold tolerance, should be a positive value # noqa: E501\n\n :param tolerance: The tolerance of this ThresholdResponse. # noqa: E501\n :type: float\n \"\"\"\n if tolerance is None:\n raise ValueError(\"Invalid value for `tolerance`, must not be `None`\") # noqa: E501\n\n self._tolerance = tolerance\n\n @property\n def threshold_type(self):\n \"\"\"Gets the threshold_type of this ThresholdResponse. # noqa: E501\n\n the threshold type, tree values can be given for now, 'low' if the it is a lower threshold, 'high' if it is an upper threshold and 'deviation' if it is as deviation from reference values # noqa: E501\n\n :return: The threshold_type of this ThresholdResponse. # noqa: E501\n :rtype: str\n \"\"\"\n return self._threshold_type\n\n @threshold_type.setter\n def threshold_type(self, threshold_type):\n \"\"\"Sets the threshold_type of this ThresholdResponse.\n\n the threshold type, tree values can be given for now, 'low' if the it is a lower threshold, 'high' if it is an upper threshold and 'deviation' if it is as deviation from reference values # noqa: E501\n\n :param threshold_type: The threshold_type of this ThresholdResponse. # noqa: E501\n :type: str\n \"\"\"\n if threshold_type is None:\n raise ValueError(\"Invalid value for `threshold_type`, must not be `None`\") # noqa: E501\n\n self._threshold_type = threshold_type\n\n @property\n def notification(self):\n \"\"\"Gets the notification of this ThresholdResponse. # noqa: E501\n\n Whether the threshold should send notifications when exceeded # noqa: E501\n\n :return: The notification of this ThresholdResponse. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._notification\n\n @notification.setter\n def notification(self, notification):\n \"\"\"Sets the notification of this ThresholdResponse.\n\n Whether the threshold should send notifications when exceeded # noqa: E501\n\n :param notification: The notification of this ThresholdResponse. # noqa: E501\n :type: bool\n \"\"\"\n if notification is None:\n raise ValueError(\"Invalid value for `notification`, must not be `None`\") # noqa: E501\n\n self._notification = notification\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(ThresholdResponse, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ThresholdResponse):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","repo_name":"endresshauser-lp/netilion-api-py","sub_path":"src/netilion_api/models/threshold_response.py","file_name":"threshold_response.py","file_ext":"py","file_size_in_byte":10764,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"15048506316","text":"#!/usr/bin/env python\n\n\"\"\"Setup script for Comparable.\"\"\"\n\nimport setuptools\n\nfrom comparable import __project__, __version__\n\nimport os\nif os.path.exists('README.rst'):\n README = open('README.rst').read()\nelse:\n README = \"\" # a placeholder, readme is generated on release\nCHANGES = open('CHANGES.md').read()\n\n\nsetuptools.setup(\n name=__project__,\n version=__version__,\n\n description=\"Base class to enable objects to be compared for similarity.\",\n url='https://github.com/jacebrowning/comparable',\n author='Jace Browning',\n author_email='jacebrowning@gmail.com',\n\n packages=setuptools.find_packages(),\n\n entry_points={'console_scripts': []},\n\n long_description=(README + '\\n' + CHANGES),\n license='LGPL',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)', # pylint: disable=C0301\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Topic :: Software Development :: Libraries',\n ],\n\n install_requires=open('requirements.txt').readlines(),\n)\n","repo_name":"jacebrowning/comparable","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"10836428818","text":"from __future__ import annotations\n\nfrom unittest import mock\n\nimport pandas as pd\nimport pytest\nfrom pandas.api.types import is_numeric_dtype\n\nimport a2rl as wi\n\n\ndef test_list_sample_datasets():\n assert wi.list_sample_datasets() == [\"chiller\", \"rtu\"]\n\n\n@pytest.mark.parametrize(\n \"dataset, expected_shape, expected_sar_d\",\n (\n # Expected answers for the Chiller dataset\n (\n \"chiller\",\n (9153, 5),\n {\n \"states\": [\"condenser_inlet_temp\", \"evaporator_heat_load_rt\"],\n \"actions\": [\"staging\"],\n \"rewards\": [\"system_power_consumption\"],\n },\n ),\n # Expected answers for the RTU dataset\n (\n \"rtu\",\n (4335, 8),\n {\n \"states\": [\n \"outside_humidity\",\n \"outside_temperature\",\n \"return_humidity\",\n \"return_temperature\",\n ],\n \"actions\": [\"economizer_enthalpy_setpoint\", \"economizer_temperature_setpoint\"],\n \"rewards\": [\"power\"],\n },\n ),\n ),\n)\ndef test_sample_dataset_path(dataset, expected_shape, expected_sar_d):\n dirname = wi.sample_dataset_path(dataset)\n df = wi.read_csv_dataset(dirname)\n assert df.sar_d == expected_sar_d\n assert df.shape == expected_shape\n\n\n@mock.patch(\"a2rl.DiscreteTokenizer.check_numerical_columns\")\n@mock.patch(\"a2rl.DiscreteTokenizer.check_categorical_columns\")\n@mock.patch(\"a2rl.utils.assert_mdp\")\ndef test_read_csv_dataset_test_mdp(mock_cnc, mock_ccc, mock_assert_mdp):\n # This test only ensures that the only accepted exception is NotMDPDataError.\n # Any other errors are considered as bug in the implementation.\n wi.read_csv_dataset(wi.sample_dataset_path(\"chiller\"), test_mdp=True)\n mock_assert_mdp.assert_called()\n\n\n@pytest.fixture\ndef df() -> wi.WiDataFrame:\n return wi.WiDataFrame(\n {\n \"a\": [0, 0, 1, 1, 2],\n \"b\": [1, 2, 3, 4, 5],\n \"c\": [2, 3, 4, 5, 6],\n \"d\": [3, 4, 5, 6, 7],\n \"e\": [4, 5, 6, 7, 8],\n \"f\": [5, 6, 7, 8, 9],\n },\n states=[\"a\", \"b\"],\n actions=[\"c\"],\n rewards=[\"d\"],\n )\n\n\n@pytest.mark.parametrize(\n \"forced_categories,expected_types\",\n (\n ([\"a\", \"b\"], [False, False, True, True, True, True]),\n (None, [True] * 6),\n ),\n)\ndef test_forced_categories(df, tmp_path, forced_categories, expected_types):\n metadata = wi.Metadata(**df.sar_d, forced_categories=forced_categories)\n p = tmp_path / f\"mydataset-{wi.utils.timestamp()}\"\n p.mkdir()\n wi.save_metadata(metadata, p / \"metadata.yaml\", compact=True)\n df.to_csv(p / \"data.csv\", index=False)\n\n df2 = wi.read_csv_dataset(p)\n if pd.__version__ >= \"1.5.0\":\n is_numeric_series = [is_numeric_dtype(ser) for _, ser in df2.items()]\n else:\n is_numeric_series = [is_numeric_dtype(ser) for _, ser in df2.iteritems()]\n assert is_numeric_series == expected_types\n","repo_name":"awslabs/amazon-accessible-rl-sdk","sub_path":"test/test_dataset.py","file_name":"test_dataset.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"27"} +{"seq_id":"26115994732","text":"from django.urls import path\nfrom .views import *\nfrom .models import *\nfrom .forms import *\nfrom django.contrib.auth.views import LogoutView\n\nurlpatterns = [\n \n path(\"hola/\",miprimersaludo,name=\"hola\"),\n path(\"html/\",probandotemplate, name = \"probandotemplate\"),\n path(\"\", inicio, name =\"inicio\"),\n path(\"lugares/\",lugares, name = \"lugares\"),\n path(\"amigos/\",formularioinicio, name=\"amigos\"),\n path(\"juguetes/\",juguetes, name =\"juguetes\"),\n path(\"comida/\",comida, name=\"comida\"),\n path(\"busquedaDni/\",busquedaDni,name=\"busquedadni\"),\n path(\"resultadobusqueda/\",buscar,name=\"buscar\"),\n path(\"leerAmigos/\",leerAmigos,name=\"leerAmigos\"),\n path(\"eliminarAmigo/\",eliminarAmigos,name=\"eliminarAmigo\"),\n path(\"editarAmigo/\",editarAmigos,name=\"editarAmigo\"),\n path(\"login/\",login_request,name=\"login\"),\n path(\"register/\",registro,name=\"register\"),\n path(\"logout/\",LogoutView.as_view(template_name='AppProyectoFinal/logout.html'),name=\"logout\"),\n path(\"editarperfil/\",editarPerfil,name=\"editarperfil\"),\n\n]\n ","repo_name":"Ricardodasilva1987/EntregaInter31100","sub_path":"AppProyectoFinal/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"73750066951","text":"from config_util import parse_args\nimport os\nimport sys\n\ndef gen_test_cfg(test_nc, trained_jsn, test_cfg, csv_path, tmp):\n\t\n\tbuf = open(test_cfg, 'w') \n\tprint >>buf, \"train = false\"\n\tprint >>buf, \"ff_output_format = csv\"\n\tprint >>buf, \"ff_input_file = %s\" %(test_nc)\n\tprint >>buf, \"parallel_sequences = 10\"\n\tprint >>buf, \"cache_path = %s\" %(tmp)\n\tprint >>buf, \"revert_std = false\"\n\tprint >>buf, \"input_left_context = 0\"\n\tprint >>buf, \"input_right_context = 0\"\n\tprint >>buf, \"network = %s\" %(trained_jsn)\n\tprint >>buf, \"ff_output_file= %s\" %(csv_path)\n\tbuf.close()\n\ndef gen_sh_train(test_file, test_cfg):\n\tbuf = open(test_file, 'w')\n\tprint >>buf, \"#!/bin/bash\"\n\tprint >>buf, \"currennt\\t--options_file %s\" %(test_cfg)\n\tbuf.close()\n\tos.system(\"chmod +x %s\" %(test_file))\n\tos.system(\"bash %s\" %(test_file))\n\ndef csv2txt(csv_path, mean_path, gen_par_dyn, dim_target):\n\tbuf = open('run_csv2txt.sh', 'w') \n\tprint >>buf, \"csv_path=%s\" %(csv_path)\n\tprint >>buf, \"mean_path=%s\" %(mean_path)\n\tprint >>buf, \"gen_par_dyn=%s\" %(gen_par_dyn)\n\tprint >>buf, \"dim_target=%d\" %(dim_target) \n\tprint >>buf, \"matlab -nojvm -nosplash -nodesktop -r \\\"file_input='$csv_path', mean_file='$mean_path',file_output='$gen_par_dyn',dim_target=$dim_target;csv2txt;quit\\\"\"\n\tbuf.close()\n\tos.system(\"bash run_csv2txt.sh\")\n\ndef postprocess(gv_path, gen_par_dyn, gen_par, mean_path, dim_target):\n\tbuf = open('run_postprocess.sh', 'w') \n\tprint >>buf, \"gv_path=%s\" %(gv_path)\n\tprint >>buf, \"mean_path=%s\" %(mean_path)\n\tprint >>buf, \"gen_par_dyn=%s\" %(gen_par_dyn)\n\tprint >>buf, \"gen_par=%s\" %(gen_par)\n\tprint >>buf, \"dim_target=%d\" %(dim_target) \n\tprint >>buf, \"matlab -nojvm -nosplash -nodesktop -r \\\"gv_file='$gv_path', mean_file='$mean_path',gen_par_dyn='$gen_par_dyn',gen_par='$gen_par',dim_target=$dim_target;postprocess;quit\\\"\"\n\tbuf.close()\n\tos.system(\"bash run_postprocess.sh\")\n\n\ndef wav_syn(gen_par, wav_path, dim_target):\n\tbuf = open('run_wav_syn.sh', 'w')\n\tprint >>buf, \"gen_par=%s\" %(gen_par)\n\tprint >>buf, \"wav_path=%s\" %(wav_path)\n\tprint >>buf, \"dim_target=%d\" %(dim_target) \n\tprint >>buf, \"matlab -nojvm -nosplash -nodesktop -r \\\"gen_par='$gen_par',wav_path='$wav_path',dim_target=$dim_target;wav_syn;quit\\\"\"\n\tbuf.close()\n\tos.system(\"bash run_wav_syn.sh\")\n\t\n\nif __name__ == '__main__':\n\targs = parse_args()\n\targs.config.write(sys.stdout)\n\n\tdim_target = args.config.getint('data', 'dim_target')\n\tnc_path = args.config.get('net', 'nc_path')\n\ttest_nc = nc_path + '/test.nc' ###\n\ttrained_jsn = args.config.get('test', 'trained_jsn')\n\t\n\tnet_path = args.config.get('net', 'net_path')\n\tcfg_path = net_path + '/cfg'\n\ttest_cfg = cfg_path +'/' + 'test_' + os.path.basename(trained_jsn).split('.')[0] + '.cfg'\n\ttmp = net_path + '/tmp'\n\n\tresult_path = args.config.get('test', 'result_path')\n\tresult_path = result_path + '/' + os.path.basename(trained_jsn).split('.')[0]\n\tcsv_path = result_path + '/csv'\n\tif not os.path.exists(csv_path):\n\t\tos.makedirs(csv_path)\n\n\t#gen_test_cfg(test_nc, trained_jsn,test_cfg, csv_path, tmp)\n\n\tsh_path = net_path + '/sh'\n\ttest_file = sh_path + '/test_' + os.path.basename(trained_jsn).split('.')[0] + '.sh'\n\t#gen_sh_train(test_file, test_cfg)\n\t\n\n\tmean_path = args.config.get('feature', 'mean_path')\n\tgen_par_dyn = result_path + '/gen_par_dyn'\n\tif not os.path.exists(gen_par_dyn):\n\t\tos.makedirs(gen_par_dyn)\n\t#csv2txt(csv_path, mean_path, gen_par_dyn, dim_target)\n###########calculate error#######################################\n\t\n###########postprocess#######################################\n\tgv_path = args.config.get('feature', 'gv_path')\n\tgen_par = result_path + '/gen_par'\n\tif not os.path.exists(gen_par):\n\t\tos.makedirs(gen_par)\n\tpostprocess(gv_path, gen_par_dyn, gen_par, mean_path, dim_target)\n\n###########gen_wav#######################################\n\twav_path = result_path + '/wav'\n\tif not os.path.exists(wav_path):\n\t\tos.makedirs(wav_path)\n\twav_syn(gen_par, wav_path, dim_target)\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"YiAthena/DNN_TTS","sub_path":"version_modified/gen_test.py","file_name":"gen_test.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"13253450388","text":"# -*- coding: utf-8 -*-\n\nfrom django.urls import reverse_lazy\nfrom django.shortcuts import redirect\nfrom django.http import HttpResponse\n\nfrom djangosige.apps.base.custom_views import CustomView, CustomCreateView, CustomListView, CustomUpdateView\n\nfrom djangosige.apps.vendas.forms import OrcamentoVendaForm, PedidoVendaForm, ItensVendaFormSet, PagamentoFormSet\nfrom djangosige.apps.vendas.models import OrcamentoVenda, PedidoVenda, ItensVenda, Pagamento\nfrom djangosige.apps.cadastro.models import MinhaEmpresa\nfrom djangosige.apps.login.models import Usuario\nfrom djangosige.configs.settings import MEDIA_ROOT\n\nfrom geraldo.generators import PDFGenerator\nfrom datetime import datetime\nimport io\n\nfrom .report_vendas import VendaReport\n\n\nclass AdicionarVendaView(CustomCreateView):\n\n def get_success_message(self, cleaned_data):\n return self.success_message % dict(cleaned_data, id=self.object.pk)\n\n def get_context_data(self, **kwargs):\n context = super(AdicionarVendaView, self).get_context_data(**kwargs)\n return self.view_context(context)\n\n def get(self, request, form_class, *args, **kwargs):\n self.object = None\n\n form = self.get_form(form_class)\n form.initial['vendedor'] = request.user.first_name or request.user\n form.initial['data_emissao'] = datetime.today().strftime('%d/%m/%Y')\n\n produtos_form = ItensVendaFormSet(prefix='produtos_form')\n pagamento_form = PagamentoFormSet(prefix='pagamento_form')\n\n return self.render_to_response(self.get_context_data(form=form,\n produtos_form=produtos_form,\n pagamento_form=pagamento_form))\n\n def post(self, request, form_class, *args, **kwargs):\n self.object = None\n # Tirar . dos campos decimais\n req_post = request.POST.copy()\n\n for key in req_post:\n if ('desconto' in key or\n 'quantidade' in key or\n 'valor' in key or\n 'frete' in key or\n 'despesas' in key or\n 'seguro' in key or\n 'total' in key):\n req_post[key] = req_post[key].replace('.', '')\n\n request.POST = req_post\n\n form = self.get_form(form_class)\n produtos_form = ItensVendaFormSet(request.POST, prefix='produtos_form')\n pagamento_form = PagamentoFormSet(\n request.POST, prefix='pagamento_form')\n\n if (form.is_valid() and produtos_form.is_valid() and pagamento_form.is_valid()):\n self.object = form.save(commit=False)\n self.object.save()\n\n for pform in produtos_form:\n if pform.cleaned_data != {}:\n itens_venda_obj = pform.save(commit=False)\n itens_venda_obj.venda_id = self.object\n itens_venda_obj.calcular_pis_cofins()\n itens_venda_obj.save()\n\n pagamento_form.instance = self.object\n pagamento_form.save()\n\n return self.form_valid(form)\n\n return self.form_invalid(form=form,\n produtos_form=produtos_form,\n pagamento_form=pagamento_form)\n\n\nclass AdicionarOrcamentoVendaView(AdicionarVendaView):\n form_class = OrcamentoVendaForm\n template_name = \"vendas/orcamento_venda/orcamento_venda_add.html\"\n success_url = reverse_lazy('vendas:listaorcamentovendaview')\n success_message = \"Orçamento de venda %(id)s adicionado com sucesso.\"\n permission_codename = 'add_orcamentovenda'\n\n def view_context(self, context):\n context['title_complete'] = 'ADICIONAR ORÇAMENTO DE VENDA'\n context['return_url'] = reverse_lazy('vendas:listaorcamentovendaview')\n return context\n\n def get(self, request, *args, **kwargs):\n form_class = self.get_form_class()\n return super(AdicionarOrcamentoVendaView, self).get(request, form_class, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n form_class = self.get_form_class()\n return super(AdicionarOrcamentoVendaView, self).post(request, form_class, *args, **kwargs)\n\n\nclass AdicionarPedidoVendaView(AdicionarVendaView):\n form_class = PedidoVendaForm\n template_name = \"vendas/pedido_venda/pedido_venda_add.html\"\n success_url = reverse_lazy('vendas:listapedidovendaview')\n success_message = \"Pedido de venda %(id)s adicionado com sucesso.\"\n permission_codename = 'add_pedidovenda'\n\n def view_context(self, context):\n context['title_complete'] = 'ADICIONAR PEDIDO DE VENDA'\n context['return_url'] = reverse_lazy('vendas:listapedidovendaview')\n return context\n\n def get(self, request, *args, **kwargs):\n form_class = self.get_form_class()\n return super(AdicionarPedidoVendaView, self).get(request, form_class, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n form_class = self.get_form_class()\n return super(AdicionarPedidoVendaView, self).post(request, form_class, *args, **kwargs)\n\n\nclass VendaListView(CustomListView):\n\n def get_context_data(self, **kwargs):\n context = super(VendaListView, self).get_context_data(**kwargs)\n return self.view_context(context)\n\n\nclass OrcamentoVendaListView(VendaListView):\n template_name = 'vendas/orcamento_venda/orcamento_venda_list.html'\n model = OrcamentoVenda\n context_object_name = 'all_orcamentos'\n success_url = reverse_lazy('vendas:listaorcamentovendaview')\n permission_codename = 'view_orcamentovenda'\n\n def view_context(self, context):\n context['title_complete'] = 'ORÇAMENTOS DE VENDA'\n context['add_url'] = reverse_lazy('vendas:addorcamentovendaview')\n return context\n\n\nclass OrcamentoVendaVencidosListView(OrcamentoVendaListView):\n success_url = reverse_lazy('vendas:listaorcamentovendavencidoview')\n\n def view_context(self, context):\n context['title_complete'] = 'ORÇAMENTOS DE VENDA VENCIDOS'\n context['add_url'] = reverse_lazy('vendas:addorcamentovendaview')\n return context\n\n def get_queryset(self):\n return OrcamentoVenda.objects.filter(data_vencimento__lte=datetime.now().date(), status='0')\n\n\nclass OrcamentoVendaVencimentoHojeListView(OrcamentoVendaListView):\n success_url = reverse_lazy('vendas:listaorcamentovendahojeview')\n\n def view_context(self, context):\n context['title_complete'] = 'ORÇAMENTOS DE VENDA COM VENCIMENTO DIA ' + \\\n datetime.now().date().strftime('%d/%m/%Y')\n context['add_url'] = reverse_lazy('vendas:addorcamentovendaview')\n return context\n\n def get_queryset(self):\n return OrcamentoVenda.objects.filter(data_vencimento=datetime.now().date(), status='0')\n\n\nclass PedidoVendaListView(VendaListView):\n template_name = 'vendas/pedido_venda/pedido_venda_list.html'\n model = PedidoVenda\n context_object_name = 'all_pedidos'\n success_url = reverse_lazy('vendas:listapedidovendaview')\n permission_codename = 'view_pedidovenda'\n\n def view_context(self, context):\n context['title_complete'] = 'PEDIDOS DE VENDA'\n context['add_url'] = reverse_lazy('vendas:addpedidovendaview')\n return context\n\n\nclass PedidoVendaAtrasadosListView(PedidoVendaListView):\n success_url = reverse_lazy('vendas:listapedidovendaatrasadosview')\n\n def view_context(self, context):\n context['title_complete'] = 'PEDIDOS DE VENDA ATRASADOS'\n context['add_url'] = reverse_lazy('vendas:addpedidovendaview')\n return context\n\n def get_queryset(self):\n return PedidoVenda.objects.filter(data_entrega__lte=datetime.now().date(), status='0')\n\n\nclass PedidoVendaEntregaHojeListView(PedidoVendaListView):\n success_url = reverse_lazy('vendas:listapedidovendahojeview')\n\n def view_context(self, context):\n context['title_complete'] = 'PEDIDOS DE VENDA COM ENTREGA DIA ' + \\\n datetime.now().date().strftime('%d/%m/%Y')\n context['add_url'] = reverse_lazy('vendas:addpedidovendaview')\n return context\n\n def get_queryset(self):\n return PedidoVenda.objects.filter(data_entrega=datetime.now().date(), status='0')\n\n\nclass EditarVendaView(CustomUpdateView):\n\n def get_success_message(self, cleaned_data):\n return self.success_message % dict(cleaned_data, id=self.object.pk)\n\n def get_context_data(self, **kwargs):\n context = super(EditarVendaView, self).get_context_data(**kwargs)\n return self.view_context(context)\n\n def get(self, request, form_class, *args, **kwargs):\n\n form = form = self.get_form(form_class)\n form.initial['total_sem_imposto'] = self.object.get_total_sem_imposto()\n\n produtos_form = ItensVendaFormSet(\n instance=self.object, prefix='produtos_form')\n itens_list = ItensVenda.objects.filter(venda_id=self.object.id)\n produtos_form.initial = [{'total_sem_desconto': item.get_total_sem_desconto(),\n 'total_impostos': item.get_total_impostos(),\n 'total_com_impostos': item.get_total_com_impostos()} for item in itens_list]\n\n pagamento_form = PagamentoFormSet(\n instance=self.object, prefix='pagamento_form')\n\n if ItensVenda.objects.filter(venda_id=self.object.pk).count():\n produtos_form.extra = 0\n if Pagamento.objects.filter(venda_id=self.object.pk).count():\n pagamento_form.extra = 0\n\n return self.render_to_response(self.get_context_data(form=form, produtos_form=produtos_form, pagamento_form=pagamento_form))\n\n def post(self, request, form_class, *args, **kwargs):\n # Tirar . dos campos decimais\n req_post = request.POST.copy()\n\n for key in req_post:\n if ('desconto' in key or\n 'quantidade' in key or\n 'valor' in key or\n 'frete' in key or\n 'despesas' in key or\n 'seguro' in key or\n 'total' in key):\n req_post[key] = req_post[key].replace('.', '')\n\n request.POST = req_post\n\n form = self.get_form(form_class)\n produtos_form = ItensVendaFormSet(\n request.POST, prefix='produtos_form', instance=self.object)\n pagamento_form = PagamentoFormSet(\n request.POST, prefix='pagamento_form', instance=self.object)\n\n if (form.is_valid() and produtos_form.is_valid() and pagamento_form.is_valid()):\n self.object = form.save(commit=False)\n self.object.save()\n\n for pform in produtos_form:\n if pform.cleaned_data != {}:\n itens_venda_obj = pform.save(commit=False)\n itens_venda_obj.venda_id = self.object\n itens_venda_obj.calcular_pis_cofins()\n itens_venda_obj.save()\n\n pagamento_form.instance = self.object\n pagamento_form.save()\n\n return self.form_valid(form)\n\n return self.form_invalid(form=form,\n produtos_form=produtos_form,\n pagamento_form=pagamento_form)\n\n\nclass EditarOrcamentoVendaView(EditarVendaView):\n form_class = OrcamentoVendaForm\n model = OrcamentoVenda\n template_name = \"vendas/orcamento_venda/orcamento_venda_edit.html\"\n success_url = reverse_lazy('vendas:listaorcamentovendaview')\n success_message = \"Orçamento de venda %(id)s editado com sucesso.\"\n permission_codename = 'change_orcamentovenda'\n\n def view_context(self, context):\n context['title_complete'] = 'EDITAR ORÇAMENTO DE VENDA N°' + \\\n str(self.object.id)\n context['return_url'] = reverse_lazy('vendas:listaorcamentovendaview')\n return context\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n form_class = self.get_form_class()\n return super(EditarOrcamentoVendaView, self).get(request, form_class, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n form_class = self.get_form_class()\n return super(EditarOrcamentoVendaView, self).post(request, form_class, *args, **kwargs)\n\n\nclass EditarPedidoVendaView(EditarVendaView):\n form_class = PedidoVendaForm\n model = PedidoVenda\n template_name = \"vendas/pedido_venda/pedido_venda_edit.html\"\n success_url = reverse_lazy('vendas:listapedidovendaview')\n success_message = \"Pedido de venda %(id)s editado com sucesso.\"\n permission_codename = 'change_pedidovenda'\n\n def view_context(self, context):\n context['title_complete'] = 'EDITAR PEDIDO DE VENDA N°' + \\\n str(self.object.id)\n context['return_url'] = reverse_lazy('vendas:listapedidovendaview')\n return context\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n form_class = self.get_form_class()\n return super(EditarPedidoVendaView, self).get(request, form_class, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n form_class = self.get_form_class()\n return super(EditarPedidoVendaView, self).post(request, form_class, *args, **kwargs)\n\n\nclass GerarPedidoVendaView(CustomView):\n permission_codename = ['add_pedidovenda', 'change_pedidovenda', ]\n\n def get(self, request, *args, **kwargs):\n orcamento_id = kwargs.get('pk', None)\n orcamento = OrcamentoVenda.objects.get(id=orcamento_id)\n itens_venda = orcamento.itens_venda.all()\n pagamentos = orcamento.parcela_pagamento.all()\n novo_pedido = PedidoVenda()\n\n for field in orcamento._meta.fields:\n setattr(novo_pedido, field.name, getattr(orcamento, field.name))\n\n novo_pedido.venda_ptr = None\n novo_pedido.pk = None\n novo_pedido.id = None\n novo_pedido.status = '0'\n orcamento.status = '1' # Baixado\n orcamento.save()\n novo_pedido.orcamento = orcamento\n novo_pedido.save()\n\n for item in itens_venda:\n item.pk = None\n item.id = None\n item.save()\n novo_pedido.itens_venda.add(item)\n\n for pagamento in pagamentos:\n pagamento.pk = None\n pagamento.id = None\n pagamento.save()\n novo_pedido.parcela_pagamento.add(pagamento)\n\n return redirect(reverse_lazy('vendas:editarpedidovendaview', kwargs={'pk': novo_pedido.id}))\n\n\nclass CancelarOrcamentoVendaView(CustomView):\n permission_codename = 'change_orcamentovenda'\n\n def get(self, request, *args, **kwargs):\n venda_id = kwargs.get('pk', None)\n instance = OrcamentoVenda.objects.get(id=venda_id)\n instance.status = '2'\n instance.save()\n return redirect(reverse_lazy('vendas:editarorcamentovendaview', kwargs={'pk': instance.id}))\n\n\nclass CancelarPedidoVendaView(CustomView):\n permission_codename = 'change_pedidovenda'\n\n def get(self, request, *args, **kwargs):\n venda_id = kwargs.get('pk', None)\n instance = PedidoVenda.objects.get(id=venda_id)\n instance.status = '2'\n instance.save()\n return redirect(reverse_lazy('vendas:editarpedidovendaview', kwargs={'pk': instance.id}))\n\n\nclass GerarCopiaVendaView(CustomView):\n\n def get(self, request, instance, redirect_url, *args, **kwargs):\n itens_venda = instance.itens_venda.all()\n pagamentos = instance.parcela_pagamento.all()\n\n instance.pk = None\n instance.id = None\n instance.status = '0'\n instance.save()\n\n for item in itens_venda:\n item.pk = None\n item.id = None\n item.save()\n instance.itens_venda.add(item)\n\n for pagamento in pagamentos:\n pagamento.pk = None\n pagamento.id = None\n pagamento.save()\n instance.parcela_pagamento.add(pagamento)\n\n return redirect(reverse_lazy(redirect_url, kwargs={'pk': instance.id}))\n\n\nclass GerarCopiaOrcamentoVendaView(GerarCopiaVendaView):\n permission_codename = 'add_orcamentovenda'\n\n def get(self, request, *args, **kwargs):\n venda_id = kwargs.get('pk', None)\n instance = OrcamentoVenda.objects.get(id=venda_id)\n redirect_url = 'vendas:editarorcamentovendaview'\n return super(GerarCopiaOrcamentoVendaView, self).get(request, instance, redirect_url, *args, **kwargs)\n\n\nclass GerarCopiaPedidoVendaView(GerarCopiaVendaView):\n permission_codename = 'add_pedidovenda'\n\n def get(self, request, *args, **kwargs):\n venda_id = kwargs.get('pk', None)\n instance = PedidoVenda.objects.get(id=venda_id)\n redirect_url = 'vendas:editarpedidovendaview'\n return super(GerarCopiaPedidoVendaView, self).get(request, instance, redirect_url, *args, **kwargs)\n\n\nclass GerarPDFVenda(CustomView):\n\n def gerar_pdf(self, title, venda, user_id):\n resp = HttpResponse(content_type='application/pdf')\n\n venda_pdf = io.BytesIO()\n venda_report = VendaReport(queryset=[venda, ])\n venda_report.title = title\n\n venda_report.band_page_footer = venda_report.banda_foot\n\n try:\n usuario = Usuario.objects.get(pk=user_id)\n m_empresa = MinhaEmpresa.objects.get(m_usuario=usuario)\n flogo = m_empresa.m_empresa.logo_file\n logo_path = '{0}{1}'.format(MEDIA_ROOT, flogo.name)\n if flogo != 'imagens/logo.png':\n venda_report.topo_pagina.inserir_logo(logo_path)\n\n venda_report.band_page_footer.inserir_nome_empresa(\n m_empresa.m_empresa.nome_razao_social)\n if m_empresa.m_empresa.endereco_padrao:\n venda_report.band_page_footer.inserir_endereco_empresa(\n m_empresa.m_empresa.endereco_padrao.format_endereco_completo)\n if m_empresa.m_empresa.telefone_padrao:\n venda_report.band_page_footer.inserir_telefone_empresa(\n m_empresa.m_empresa.telefone_padrao.telefone)\n except:\n pass\n\n venda_report.topo_pagina.inserir_data_emissao(venda.data_emissao)\n if isinstance(venda, OrcamentoVenda):\n venda_report.topo_pagina.inserir_data_validade(\n venda.data_vencimento)\n elif isinstance(venda, PedidoVenda):\n venda_report.topo_pagina.inserir_data_entrega(venda.data_entrega)\n venda_report.band_page_header = venda_report.topo_pagina\n\n if venda.cliente.tipo_pessoa == 'PJ':\n venda_report.dados_cliente.inserir_informacoes_pj()\n elif venda.cliente.tipo_pessoa == 'PF':\n venda_report.dados_cliente.inserir_informacoes_pf()\n\n if venda.cliente.endereco_padrao:\n venda_report.dados_cliente.inserir_informacoes_endereco()\n if venda.cliente.telefone_padrao:\n venda_report.dados_cliente.inserir_informacoes_telefone()\n if venda.cliente.email_padrao:\n venda_report.dados_cliente.inserir_informacoes_email()\n\n venda_report.band_page_header.child_bands.append(\n venda_report.dados_cliente)\n\n venda_report.dados_produtos.band_detail.set_band_height(\n len(ItensVenda.objects.filter(venda_id=venda)))\n venda_report.banda_produtos.elements.append(\n venda_report.dados_produtos)\n venda_report.band_page_header.child_bands.append(\n venda_report.banda_produtos)\n\n venda_report.band_page_header.child_bands.append(\n venda_report.totais_venda)\n\n if venda.cond_pagamento:\n venda_report.banda_pagamento.elements.append(\n venda_report.dados_pagamento)\n venda_report.band_page_header.child_bands.append(\n venda_report.banda_pagamento)\n\n venda_report.observacoes.inserir_vendedor()\n venda_report.band_page_header.child_bands.append(\n venda_report.observacoes)\n\n venda_report.generate_by(PDFGenerator, filename=venda_pdf)\n pdf = venda_pdf.getvalue()\n resp.write(pdf)\n\n return resp\n\n\nclass GerarPDFOrcamentoVenda(GerarPDFVenda):\n permission_codename = 'change_orcamentovenda'\n\n def get(self, request, *args, **kwargs):\n venda_id = kwargs.get('pk', None)\n\n if not venda_id:\n return HttpResponse('Objeto não encontrado.')\n\n obj = OrcamentoVenda.objects.get(pk=venda_id)\n title = 'Orçamento de venda nº {}'.format(venda_id)\n\n return self.gerar_pdf(title, obj, request.user.id)\n\n\nclass GerarPDFPedidoVenda(GerarPDFVenda):\n permission_codename = 'change_pedidovenda'\n\n def get(self, request, *args, **kwargs):\n venda_id = kwargs.get('pk', None)\n\n if not venda_id:\n return HttpResponse('Objeto não encontrado.')\n\n obj = PedidoVenda.objects.get(pk=venda_id)\n title = 'Pedido de venda nº {}'.format(venda_id)\n\n return self.gerar_pdf(title, obj, request.user.id)\n","repo_name":"thiagopena/djangoSIGE","sub_path":"djangosige/apps/vendas/views/vendas.py","file_name":"vendas.py","file_ext":"py","file_size_in_byte":21090,"program_lang":"python","lang":"pt","doc_type":"code","stars":379,"dataset":"github-code","pt":"27"} +{"seq_id":"6629871376","text":"import math\nimport numpy as np\nfrom scipy.stats import rankdata\nfrom metric.metric_at_k import MetricAtK\n\n\nclass NDCGAtK(MetricAtK):\n \"\"\"NDCGAtK class. Inherits the MetricAtK class.\n\n The NDCGAtK is used to calculate the Normalized Discounted Cumulative Gain\n metric.\n \"\"\"\n def __init__(self, k):\n \"\"\"Inits NDCGAtK with its k value.\n k must be greater than 0.\n Raises:\n TypeError: The k value is not an integer or is not set.\n ValueError: The k value is smaller than 1.\n \"\"\"\n super().__init__('NDCG', k)\n\n def evaluate(self, y_true, y_pred):\n \"\"\"Evaluates the given predictions with the NDCG metric.\n\n Calculates the NDCG on the passed predicted and true values at k.\n\n Args:\n y_true: A PyTorch tensor of true values. Only one value per row\n can be > 0!\n y_pred: A PyTorch tensor of predicted values.\n\n Returns:\n Will return a float with the calculated NDCG value.\n The NDCG definition is:\n math::\n NDCG@K = Z_k \\\\sum_{i=1}^{K} \\\\frac{2^r_i - 1}{log_2 (i + 1)}\n r_i = 1 if in true set, 0 otherwise\n From:\n https://www.comp.nus.edu.sg/~kanmy/papers/cikm15-trirank-cr.pdf\n\n Raises:\n TypeError: An error occured while accessing the arguments -\n one of the arguments is NoneType.\n ValueError: An error occured when checking the dimensions of the\n y_pred and y_true arguments. One or both are not a 2D arrays,\n or they are 2D but of different sizes along those dimensions.\n If y_true has more than one true value per row this error\n is raised. This is also raised if the output is not in [0,1].\n \"\"\"\n self._check_input(y_true, y_pred)\n y_true = y_true.cpu().numpy()\n y_pred = y_pred.cpu().numpy()\n\n self._check_args_numpy(y_pred, y_true)\n # Check only one ground truth value = 1 per row in y_true.\n y_true[y_true > 0] = 1\n y_true[y_true < 0] = 0\n for x in np.sum(y_true, axis=1):\n if x != 1:\n raise ValueError('Incorrect format of argument: y_true. \\\n Input must have only one true value \\\n per row.')\n rows = y_pred.shape[0]\n cols = y_pred.shape[1]\n NDCG = 0\n for i in range(rows):\n rank = rankdata(-y_pred[i], method='min')\n rank[rank > self._k] = 0\n for j in range(cols):\n if y_pred[i][j] <= 0 or rank[j] < 1:\n continue\n NDCG += (2**y_true[i][j] - 1)\\\n / math.log(rank[j]+1, 2)\n result = NDCG / rows\n if not (0 <= result <= 1):\n raise ValueError('The output of NDCGAtK.evaluate must be in [0,1]')\n return result\n","repo_name":"swisscom/ai-research-mamo-framework","sub_path":"metric/NDCG_at_k.py","file_name":"NDCG_at_k.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"27"} +{"seq_id":"74531165511","text":"import joblib\n\n\nclass ModelIO:\n\n @staticmethod\n def save_model(model, filepath):\n try:\n joblib.dump(model, filepath)\n print(\"Successfully saved model to file: \" + filepath)\n return True\n except:\n print(\"Failed to save model to file: \" + filepath)\n return False\n\n @staticmethod\n def load_model(filepath):\n try:\n loaded_model = joblib.load(filepath)\n return True, loaded_model\n except Exception as e:\n print(\"Failed to load model from file: \", filepath)\n print(e)\n return False, None\n","repo_name":"yinzhusS2023/CMU-DSSE-SalaryRegression","sub_path":"IO/ModelIO.py","file_name":"ModelIO.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"21636735855","text":"import svox2\nimport torch\nimport torch.nn.functional as F\nfrom svox2.utils import Timing\n\ntorch.random.manual_seed(2)\n# torch.random.manual_seed(8289)\n\ndevice = 'cuda:0'\ntorch.cuda.set_device(device)\ndtype = torch.float32\ngrid = svox2.SparseGrid(\n reso=128,\n center=[0.0, 0.0, 0.0],\n radius=[1.0, 1.0, 1.0],\n basis_dim=9,\n use_z_order=True,\n device=device,\n background_nlayers=0,\n basis_type=svox2.BASIS_TYPE_SH)\ngrid.opt.backend = 'cuvol'\ngrid.opt.sigma_thresh = 0.0\ngrid.opt.stop_thresh = 0.0\ngrid.opt.background_brightness = 0.0\n\nprint(grid.sh_data.shape)\n\n# Render using a white color to obtain equivalent to alpha rendering\nfrom svox2.utils import SH_C0\ngrid.sh_data.data = torch.zeros_like(grid.sh_data.data.view(-1, 3, grid.basis_dim))\ngrid.sh_data.data[..., 0] = 0.5 / SH_C0\ngrid.sh_data.data = grid.sh_data.data.flatten(1, 2)\ngrid.density_data.data[:] = 1.0\n\nif grid.use_background:\n\tgrid.background_data.data[..., -1] = 0.5\n\tgrid.background_data.data[..., :-1] = torch.randn_like(\n grid.background_data.data[..., :-1]) * 0.01\n\nif grid.basis_type == svox2.BASIS_TYPE_3D_TEXTURE:\n grid.basis_data.data.normal_()\n grid.basis_data.data += 1.0\n\nENABLE_TORCH_CHECK = True\n# N_RAYS = 5000 #200 * 200\nN_RAYS = 200 * 200\norigins = torch.randn((N_RAYS, 3), device=device, dtype=dtype) * 3\ndirs = torch.randn((N_RAYS, 3), device=device, dtype=dtype)\n\n# from training.networks_plenoxel import RaySampler, PoseSampler\n# img_res = 32\n# ps = PoseSampler(range_azim=(180, 45), range_polar=(90, 15), radius=8, dist='normal')\n# rs = RaySampler(img_resolution=img_res, fov=30)\n# pose = ps.sample()\n# origins, dirs = rs.sample_at(pose[None, :3, :4], rs.img_resolution)\n# origins = origins.cuda()\n# dirs = dirs.cuda()\n\n# origins = torch.clip(origins, -0.8, 0.8)\n\n# origins = torch.tensor([[-0.6747068762779236, -0.752697229385376, -0.800000011920929]], device=device, dtype=dtype)\n# dirs = torch.tensor([[0.6418760418891907, -0.37417781352996826, 0.6693176627159119]], device=device, dtype=dtype)\ndirs /= torch.norm(dirs, dim=-1, keepdim=True)\n\n# start = 71\n# end = 72\n# origins = origins[start:end]\n# dirs = dirs[start:end]\n# print(origins.tolist(), dirs.tolist())\n\n# breakpoint()\nrays = svox2.Rays(origins, dirs)\n\nrgb_gt = torch.zeros((origins.size(0), 4), device=device, dtype=dtype)\n\n# grid.requires_grad_(True)\n\n# samps = grid.volume_render(rays, use_kernel=True)\n# sampt = grid.volume_render(grid, origins, dirs, use_kernel=False)\n\nwith Timing(\"ours\"):\n samps = grid.volume_render(rays, use_kernel=True, render_alpha=True)\nassert all([(a == samps[:, 0]).all() for a in samps.T[1:]]), 'Alpha map and rendered color images do not match.'\n\n# Check internal gradients, i.e. white color vs alpha\ndensity_grads_s = []\ngrid.sh_data.grad = None\ngrid.density_data.grad = None\nfor i in range(4):\n a = grid.volume_render(rays, use_kernel=True, render_alpha=True)[:, i]\n s = F.mse_loss(a, rgb_gt[:, i])\n with Timing(\"ours_backward\"):\n s.backward()\n density_grads_s.append(grid.density_data.grad.clone().cpu())\n grid.sh_data.grad = None\n grid.density_data.grad = None\ndensity_grads_s = torch.stack(density_grads_s)\nprint('Error gradients color/alpha', [(g - density_grads_s[0]).abs().max().item() for g in density_grads_s[1:]])\n\n# Check gradients wrt torch implementation\ns = F.mse_loss(samps, rgb_gt)\n\nprint(s)\nprint('bkwd..')\nwith Timing(\"ours_backward\"):\n s.backward()\ngrid_sh_grad_s = grid.sh_data.grad.clone().cpu()\ngrid_density_grad_s = grid.density_data.grad.clone().cpu()\ngrid.sh_data.grad = None\ngrid.density_data.grad = None\nif grid.basis_type == svox2.BASIS_TYPE_3D_TEXTURE:\n grid_basis_grad_s = grid.basis_data.grad.clone().cpu()\n grid.basis_data.grad = None\nif grid.use_background:\n grid_bg_grad_s = grid.background_data.grad.clone().cpu()\n grid.background_data.grad = None\n\nif ENABLE_TORCH_CHECK:\n with Timing(\"torch\"):\n sampt = grid.volume_render(rays, use_kernel=False, render_alpha=True)\n assert all([(a == sampt[:, 0]).all() for a in sampt.T[1:]]), 'Alpha map and rendered color images do not match.'\n\n print('Do ours and torch output match?', torch.isclose(samps, sampt).all().item())\n\n s = F.mse_loss(sampt, rgb_gt)\n with Timing(\"torch_backward\"):\n s.backward()\n grid_sh_grad_t = grid.sh_data.grad.clone().cpu() if grid.sh_data.grad is not None else torch.zeros_like(grid_sh_grad_s)\n grid_density_grad_t = grid.density_data.grad.clone().cpu() if grid.density_data.grad is not None else torch.zeros_like(grid_density_grad_s)\n if grid.basis_type == svox2.BASIS_TYPE_3D_TEXTURE:\n grid_basis_grad_t = grid.basis_data.grad.clone().cpu()\n if grid.use_background:\n grid_bg_grad_t = grid.background_data.grad.clone().cpu() if grid.background_data.grad is not None else torch.zeros_like(grid_bg_grad_s)\n\n E = torch.abs(grid_sh_grad_s-grid_sh_grad_t)\n Ed = torch.abs(grid_density_grad_s-grid_density_grad_t)\n if grid.basis_type == svox2.BASIS_TYPE_3D_TEXTURE:\n Eb = torch.abs(grid_basis_grad_s-grid_basis_grad_t)\n if grid.use_background:\n Ebg = torch.abs(grid_bg_grad_s-grid_bg_grad_t)\n print('err', torch.abs(samps - sampt).max())\n print('err_sh_grad\\n', E.max())\n print(' mean\\n', E.mean())\n print('err_density_grad\\n', Ed.max())\n print(' mean\\n', Ed.mean())\n if grid.basis_type == svox2.BASIS_TYPE_3D_TEXTURE:\n print('err_basis_grad\\n', Eb.max())\n print(' mean\\n', Eb.mean())\n if grid.use_background:\n print('err_background_grad\\n', Ebg.max())\n print(' mean\\n', Ebg.mean())\n print()\n print('g_ours sh min/max\\n', grid_sh_grad_s.min(), grid_sh_grad_s.max())\n print('g_torch sh min/max\\n', grid_sh_grad_t.min(), grid_sh_grad_t.max())\n print('g_ours sigma min/max\\n', grid_density_grad_s.min(), grid_density_grad_s.max())\n print('g_torch sigma min/max\\n', grid_density_grad_t.min(), grid_density_grad_t.max())\n if grid.basis_type == svox2.BASIS_TYPE_3D_TEXTURE:\n print('g_ours basis min/max\\n', grid_basis_grad_s.min(), grid_basis_grad_s.max())\n print('g_torch basis min/max\\n', grid_basis_grad_t.min(), grid_basis_grad_t.max())\n if grid.use_background:\n print('g_ours bg min/max\\n', grid_bg_grad_s.min(), grid_bg_grad_s.max())\n print('g_torch bg min/max\\n', grid_bg_grad_t.min(), grid_bg_grad_t.max())\n","repo_name":"autonomousvision/voxgraf","sub_path":"voxgraf-plenoxels/test/test_render_gradcheck_alpha.py","file_name":"test_render_gradcheck_alpha.py","file_ext":"py","file_size_in_byte":6508,"program_lang":"python","lang":"en","doc_type":"code","stars":120,"dataset":"github-code","pt":"27"} +{"seq_id":"74663566152","text":"import torch\nimport torch.nn.functional as F\nfrom misc.vocab import SOS_ID, EOS_ID\n\n\nclass TopKDecoder(torch.nn.Module):\n r\"\"\"\n Top-beam_size decoding with beam search.\n Args:\n decoder_rnn (DecoderRNN): An object of DecoderRNN used for decoding.\n beam_size (int): Size of the beam.\n Inputs: inputs, encoder_hidden, q_enc_outputs, function, teacher_forcing_ratio\n each sequence is a list of token IDs. It is used for teacher forcing when provided. (default is `None`)\n - **encoder_hidden** (num_layers * num_directions, batch_size, hidden_size): tensor containing the features\n in the dec_hidden state `h` of encoder. Used as the initial dec_hidden state of the decoder.\n - **q_enc_outputs** (batch, seq_len, hidden_size): tensor with containing the outputs of the encoder.\n Used for attention mechanism (default is `None`).\n - **function** (torch.nn.Module): A function used to generate symbols from decoder dec_hidden state\n (default is `torch.nn.functional.log_softmax`).\n Outputs: dec_outputs, dec_hidden, ret_dict\n - **dec_outputs** (batch): batch-length list of tensors with size (max_len, hidden_size) containing the\n outputs of the decoder.\n - **dec_hidden** (num_layers * num_directions, batch, hidden_size): tensor containing the last dec_hidden\n state of the decoder.\n - **ret_dict**: dictionary containing additional information as follows {*length* : list of integers\n representing lengths of output sequences, *topk_length*: list of integers representing lengths of beam search\n sequences, *sequence* : list of sequences, where each sequence is a list of predicted token IDs,\n *topk_sequence* : list of beam search sequences, each beam is a list of token IDs, *inputs* : target\n outputs if provided for decoding}.\n \"\"\"\n\n def __init__(self,\n config,\n decoder,\n device):\n super(TopKDecoder, self).__init__()\n self.config = config\n self.decoder = decoder\n self.device = device\n\n def forward(self,\n dec_hidden=None,\n q_enc_outputs=None,\n q_inputs_length=None,\n c_enc_outputs=None,\n c_turn_length=None,\n f_enc_outputs=None,\n f_topk_length=None):\n\n batch_size, beam_size = self.config.batch_size, self.config.beam_size\n vocab_size = self.config.vocab_size\n max_len = self.config.r_max_len\n\n # [batch_size * beam_size, 1]\n self.pos_index = (torch.LongTensor(range(batch_size))\n * beam_size).view(-1, 1).to(self.device)\n\n # Inflate the initial dec_hidden states to be of size: batch_size*beam_size x h\n # ... same way for q_enc_outputs and dec_outputs\n dec_hidden = dec_hidden.repeat(1, beam_size, 1)\n # [max_len, batch_size * beam_size, hidden_size]\n q_enc_outputs = q_enc_outputs.repeat(1, beam_size, 1)\n q_inputs_length = q_inputs_length.repeat(beam_size)\n\n if c_enc_outputs is not None:\n c_enc_outputs = c_enc_outputs.repeat(1, beam_size, 1)\n c_turn_length = c_turn_length.repeat(beam_size)\n\n if f_enc_outputs is not None:\n f_enc_outputs = f_enc_outputs.repeat(1, beam_size, 1)\n f_topk_length = f_topk_length.repeat(beam_size)\n\n # Initialize the scores; for the first step,\n # ignore the inflated copies to avoid duplicate entries in the top beam_size\n sequence_scores = torch.Tensor(batch_size * beam_size, 1).to(self.device)\n sequence_scores.fill_(-float('Inf'))\n sequence_scores.index_fill_(0, torch.LongTensor(\n [i * beam_size for i in range(0, batch_size)]).to(self.device), 0.0)\n\n # Initialize the dec_input vector\n # [batch_size * beam_size, 1]\n dec_input = torch.LongTensor(\n [[SOS_ID] * batch_size * beam_size]).to(self.device).transpose(0, 1)\n\n # Store decisions for backtracking\n stored_scores = list()\n stored_predecessors = list()\n stored_emitted_symbols = list()\n\n for _ in range(0, max_len):\n # output: [batch_size * beam_size, vocab_size]\n output, dec_hidden, _ = self.decoder(\n dec_input.transpose(0, 1), # [1, batch_size * beam_size]\n dec_hidden,\n q_enc_outputs=q_enc_outputs,\n q_enc_length=q_inputs_length,\n c_enc_outputs=c_enc_outputs,\n c_enc_length=c_turn_length,\n f_enc_outputs=f_enc_outputs,\n f_enc_length=f_topk_length\n )\n\n # output: [1, batch_size * beam_size, vocab_size]\n output = output.squeeze(0).contiguous()\n\n # log_softmax_output: [batch_size * beam_size, vocab_size]\n log_softmax_output = F.log_softmax(output, dim=1)\n\n # To get the full sequence scores for the new candidates, add the local\n # scores for t_i to the predecessor scores for t_(i-1)\n # sequence_scores = sequence_scores.repeat(1, vocab_size)\n # [batch_size * beam_size, 1] + [batch_size * beam_sizes] -> [batch_size * beam_size, vocab_size]\n # print('log_softmax_output: ', log_softmax_output.shape)\n # print('sequence_scores: ', sequence_scores.shape)\n sequence_scores = sequence_scores + log_softmax_output\n # [batch_size, beam_size]\n scores, candidates = sequence_scores.view(batch_size, -1).topk(beam_size, dim=1)\n\n dec_input = (candidates % vocab_size).view(batch_size * beam_size, 1) # [batch_size, beam_size, 1]\n sequence_scores = scores.view(batch_size * beam_size, 1)\n\n # Update fields for next timestep\n predecessors = (candidates / vocab_size +\n self.pos_index.expand_as(candidates)).view(batch_size * beam_size, 1)\n\n dec_hidden = dec_hidden.index_select(1, predecessors.squeeze())\n\n # Update sequence scores and erase scores for end-of-sentence symbol so that they aren't expanded\n stored_scores.append(sequence_scores.clone())\n eos_indices = dec_input.data.eq(EOS_ID)\n if eos_indices.nonzero().dim() > 0:\n sequence_scores.data.masked_fill_(eos_indices, -float('inf'))\n\n # Cache results for backtracking\n stored_predecessors.append(predecessors)\n stored_emitted_symbols.append(dec_input)\n\n # Do backtracking to return the optimal values\n score, topk_length, topk_sequence = self._backtrack(\n stored_predecessors,\n stored_emitted_symbols,\n stored_scores,\n batch_size,\n beam_size,\n max_len\n )\n\n metadata = {}\n metadata['score'] = score\n metadata['topk_length'] = topk_length\n metadata['topk_sequence'] = topk_sequence\n\n metadata['length'] = [seq_len[0] for seq_len in topk_length]\n metadata['sequence'] = [seq[0] for seq in topk_sequence]\n return metadata\n\n def _backtrack(self, predecessors, symbols, scores, batch_size, beam_size, max_len):\n \"\"\"Backtracks over batch to generate optimal beam_size-sequences.\n Args:\n predecessors [(batch*beam_size)] * sequence_length: A Tensor of predecessors\n symbols [(batch*beam_size)] * sequence_length: A Tensor of predicted tokens\n scores [(batch*beam_size)] * sequence_length: A Tensor containing sequence scores for every token t = [0, ... , seq_len - 1]\n batch_size: Size of the batch\n hidden_size: Size of the dec_hidden state\n Returns:\n output [(batch, beam_size, vocab_size)] * sequence_length: A list of the output probabilities (p_n)\n from the last layer of the decoder, for every n = [0, ... , seq_len - 1]\n from the last layer of the decoder, for every n = [0, ... , seq_len - 1]\n score [batch, beam_size]: A list containing the final scores for all top-beam_size sequences\n length [batch, beam_size]: A list specifying the length of each sequence in the top-beam_size candidates\n topk_sequence (batch, beam_size, sequence_len): A Tensor containing predicted sequence\n \"\"\"\n # batch_size, beam_size = self.config.batch_size, self.config.beam_size\n\n topk_sequence = list()\n # Placeholder for last dec_hidden state of top-beam_size sequences.\n # the last dec_hidden state of decoding.\n # Placeholder for lengths of top-beam_size sequences\n topk_length = [[max_len] * beam_size for _ in range(batch_size)]\n\n # thus they are sorted here\n sorted_score, sorted_idx = scores[-1].view(\n batch_size, beam_size).topk(beam_size)\n # initialize the sequence scores with the sorted last step beam scores\n score = sorted_score.clone()\n\n batch_eos_found = [0] * batch_size # the number of eos_id found\n # in the backward loop below for each batch\n\n t = max_len - 1\n # initialize the back pointer with the sorted order of the last step beams.\n # add self.pos_index for indexing variable with batch_size*beam_size as the first dimension.\n t_predecessors = (\n sorted_idx + self.pos_index.expand_as(sorted_idx)).view(batch_size * beam_size)\n while t >= 0:\n # Re-order the variables with the back pointer\n current_symbol = symbols[t].index_select(0, t_predecessors)\n # Re-order the back pointer of the previous step with the back pointer of\n # the current step\n t_predecessors = predecessors[t].index_select(0, t_predecessors).squeeze()\n\n # This tricky block handles dropped sequences that see eos_id earlier.\n # The basic idea is summarized below:\n #\n # Terms:\n # Ended sequences = sequences that see eos_id early and dropped\n # Survived sequences = sequences in the last step of the beams\n #\n # Although the ended sequences are dropped during decoding,\n # their generated symbols and complete backtracking information are still\n # in the backtracking variables.\n # For each batch, everytime we see an eos_id in the backtracking process,\n # 1. If there is survived sequences in the return variables, replace\n # the one with the lowest survived sequence score with the new ended\n # sequences\n # 2. Otherwise, replace the ended sequence with the lowest sequence\n # score with the new ended sequence\n #\n eos_indices = symbols[t].data.squeeze(1).eq(EOS_ID).nonzero()\n if eos_indices.dim() > 0:\n for i in range(eos_indices.size(0)-1, -1, -1):\n # Indices of the eos_id symbol for both variables\n # with batch_size*beam_size as the first dimension, and batch_size, beam_size for\n # the first two dimensions\n idx = eos_indices[i]\n b_idx = int(idx[0] / beam_size)\n # The indices of the replacing position\n # according to the replacement strategy noted above\n res_k_idx = beam_size - \\\n (batch_eos_found[b_idx] % beam_size) - 1\n batch_eos_found[b_idx] += 1\n res_idx = b_idx * beam_size + res_k_idx\n\n # Replace the old information in return variables\n # with the new ended sequence information\n t_predecessors[res_idx] = predecessors[t][idx[0]]\n\n current_symbol[res_idx, :] = symbols[t][idx[0]]\n score[b_idx, res_k_idx] = scores[t][idx[0]].data[0]\n topk_length[b_idx][res_k_idx] = t + 1 # record the back tracked results\n topk_sequence.append(current_symbol)\n\n t -= 1\n\n # Sort and re-order again as the added ended sequences may change\n # the order (very unlikely)\n score, re_sorted_idx = score.topk(beam_size)\n for b_idx in range(batch_size):\n topk_length[b_idx] = [topk_length[b_idx][k_idx.item()]\n for k_idx in re_sorted_idx[b_idx, :]]\n\n re_sorted_idx = (re_sorted_idx + self.pos_index.expand_as(re_sorted_idx)).view(batch_size * beam_size)\n\n # Reverse the sequences and re-order at the same time\n # It is reversed because the backtracking happens in reverse time order\n topk_sequence = [step.index_select(0, re_sorted_idx).view(batch_size, beam_size, -1) for step in reversed(topk_sequence)]\n\n score = score.data\n\n return score, topk_length, topk_sequence\n","repo_name":"AotY/DSTC7-End-to-End-Conversation-Modeling","sub_path":"modules/topk_decoder.py","file_name":"topk_decoder.py","file_ext":"py","file_size_in_byte":13025,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"2698498430","text":"class Node:\n def __init__(self, value):\n self.data = value\n self.next = None\n\n\nclass Linkedlist:\n def __init__(self):\n self.head = None\n\n def deleteFrontnode(self, position):\n\n temp =self.head\n\n if temp is None:\n print(\"list is empty !!!\")\n if position ==0:\n self.head = temp.next\n temp =None\n\n def deleteLastnode(self):\n if self.head is None:\n print(\"list is empty !!!\")\n temp = self.head\n\n\n def deleteAtnode(self, position):\n pass\n \n\n def printList(self):\n while(self.head):\n print(self.head.data)\n self.head = self.head.next\n\nlist = Linkedlist()\nlist.head = Node(1)\nsecond = Node(2)\nthird = Node(55)\nfourth = Node(77)\nfifth = Node(88)\nsixth = Node(99)\nlist.head.next = second\nsecond.next = third\nthird.next = fourth\nfourth.next = fifth\nfifth.next =sixth\n\nlist.deleteFrontnode(0)\nlist.deleteAtnode(2)\nlist.printList()\n\n\n","repo_name":"Sheersha-jain/Linked-List","sub_path":"single-node-deletion.py","file_name":"single-node-deletion.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"20600649994","text":"import re\n\nfrom resources.lib import utils\nfrom resources.lib.adultsite import AdultSite\n\nsite = AdultSite(\"trannyteca\", \"[COLOR hotpink]Trannyteca[/COLOR]\", \"https://www.trannyteca.com/\", \"trannyteca.png\", 'trannyteca')\n\n\n@site.register(default_mode=True)\ndef Main():\n site.add_dir('[COLOR hotpink]Categories[/COLOR]', site.url, 'Categories', site.img_cat)\n site.add_dir('[COLOR hotpink]Search[/COLOR]', site.url + '?s=', 'Search', site.img_search)\n List(site.url)\n utils.eod()\n\n\n@site.register()\ndef List(url):\n listhtml = utils.getHtml(url, site.url)\n items = re.compile(r'([^<]+)', re.DOTALL | re.IGNORECASE).findall(listhtml)\n for img, vurl, name in items:\n name = utils.cleantext(name)\n site.add_download_link(name, vurl, 'Playvid', img, name)\n nextp = re.search(r'class=\"next\\s*page-numbers\"\\s*href=\"([^\"]+)', listhtml, re.DOTALL)\n if nextp:\n nextp = nextp.group(1)\n curr_pg = re.findall(r'class=\"page-numbers current\"[^\\d]+(\\d+)', listhtml)[0]\n last_pg = re.findall(r'class=\"page-numbers\"[^\\d]+(\\d+)', listhtml)[-1]\n site.add_dir('Next Page... (Currently in Page {0} of {1})'.format(curr_pg, last_pg), nextp, 'List', site.img_next)\n\n utils.eod()\n\n\n@site.register()\ndef Playvid(url, name, download=None):\n vp = utils.VideoPlayer(name, download)\n html = utils.getHtml(url, site.url)\n links = re.findall(r\"px_repros\\[.+?=\\s*'([^']+)\", html)\n if not links:\n utils.notify('Oh oh', 'No playable video found')\n vp.progress.close()\n return\n pattern = r'''([^<]+)', re.DOTALL | re.IGNORECASE).findall(cathtml)\n for catpage, name in cats:\n site.add_dir(name, catpage, 'List', '')\n utils.eod()\n\n\n@site.register()\ndef Search(url, keyword=None):\n searchUrl = url\n if not keyword:\n site.search_dir(url, 'Search')\n else:\n title = keyword.replace(' ', '+')\n searchUrl = searchUrl + title\n List(searchUrl)\n","repo_name":"dobbelina/repository.dobbelina","sub_path":"plugin.video.cumination/resources/lib/sites/trannyteca.py","file_name":"trannyteca.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","stars":223,"dataset":"github-code","pt":"27"} +{"seq_id":"4823154577","text":"print('=*='*20)\r\nfrase1 = 'CADASTRO DE PESSOAS'\r\nprint (f'O {frase1} tem...')\r\nprint('=*='*20)\r\n\r\nidade = int(input('Idade: '))\r\nsexo = str(input('Sexo [M/F]: ')).strip().upper()[0]\r\nwhile sexo not in 'MF':\r\n sexo = str(input('Sexo [M/F]:')).strip().upper()[0]\r\ncm = 0\r\nm = 0\r\nmaior = 0\r\ni = ''\r\n\r\nwhile True:\r\n if idade > 18:\r\n maior += 1\r\n if sexo == 'M':\r\n cm += 1\r\n if sexo == 'F' and idade < 20:\r\n m += 1\r\n i = str(input('Deseja continuar? [S/N] ')).strip().upper()[0]\r\n while i not in 'SN':\r\n i = str(input('Deseja continuar? [S/N] ')).strip().upper()[0]\r\n\r\n if i == 'N':\r\n break\r\n else:\r\n idade = int(input('Idade: '))\r\n sexo = str(input('Sexo [M/F]:')).strip().upper()[0]\r\n while sexo not in 'MF':\r\n sexo = str(input('Sexo [M/F]:')).strip().upper()[0]\r\n\r\nprint(f'{maior} Pessoas tem mais de 18 anos!')\r\nprint(f'{cm} Homens foram cadastrados!')\r\nprint(f'{m} Mulheres tem menos de 20 anos!')\r\n","repo_name":"romulojuca/exercicios_python","sub_path":"Exercicios_Mundo2_Guanabara/IdadeSexoMouF.py","file_name":"IdadeSexoMouF.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"11122999975","text":"import numpy as np\nimport sklearn.preprocessing as prep\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n'''\n 说明:\n 本段代码运行所展示出的自编码��效果,主要是将提取高维特征(输入->隐藏层)和重构(隐藏层->输出层)分开处理\n 前提条件是将输入的标准数据用高斯噪声加以影响,使得自编码器展现出提取高维特征,屏蔽噪声信号的效果\n 总体网络结构是三层:输入层,隐藏层,输出层\n 输入层:由所读取的输入数据原型所决定,额外加上高斯噪声\n 隐藏层:由操作者自定义神经元数目,一般少于输入层\n 输出层:模型与输入数据原型完全一致,降噪\n 最终通过计算loss值,来反应重构后的预测值与数据原值之间的差距大小,进而反应降噪效果\n'''\n\n\n# Xavier初始化器,让初始化的参数处于一个不低不高的水平\ndef xavier_init(fan_in, fan_out, constant=1):\n low = -constant * np.sqrt(6.0 / (fan_in + fan_out))\n high = constant * np.sqrt(6.0 / (fan_in + fan_out))\n return tf.random_uniform((fan_in, fan_out), minval=low, maxval=high, dtype=tf.float32)\n\n\nclass AdditiveGaussianNoiseAutoencoder(object):\n # 构造函数\n def __init__(self, n_input, n_hidden, transfer_function=tf.nn.softplus, optimizer=tf.train.AdamOptimizer(),\n scale=0.1):\n # 输入的特征数\n self.n_input = n_input\n # 隐藏层节点数\n self.n_hidden = n_hidden\n # 隐藏层激活函数,默认softplus\n self.transfer = transfer_function\n # 高斯噪声系数,默认0.1\n self.scale = tf.placeholder(tf.float32)\n self.training_scale = scale\n # 神经网络初始化参数\n network_weights = self._initialize_weights()\n # 获取初始化的神经网络\n self.weights = network_weights\n # 初始化输入的模型,列数为n_input个\n self.x = tf.placeholder(tf.float32, [None, self.n_input])\n # 计算隐藏层,输入数据首先融入噪声,然后与权值w1相乘,最后加上偏值b1\n self.hidden = self.transfer(tf.add(tf.matmul(self.x + scale * tf.random_normal((n_input,)), self.weights['w1']),\n self.weights['b1']))\n # 计算预测输出值,将隐藏层的结果与权值矩阵w2相乘,在于偏值b2相加作为得出输出的结果\n self.reconstruction = tf.add(tf.matmul(self.hidden, self.weights['w2']), self.weights['b2'])\n # 计算损失函数,计算预测值与数据本身之间的误差\n self.cost = 0.5 * tf.reduce_mean(tf.pow(tf.subtract(self.reconstruction, self.x), 2.0))\n # 选择默认Adam优化器对损失函数进行优化\n self.optimizer = optimizer.minimize(self.cost)\n # 初始化全局变量\n init = tf.global_variables_initializer()\n self.sess = tf.Session()\n self.sess.run(init)\n\n # 权值初始化函数\n def _initialize_weights(self):\n # 声明权重值字典,一共四个key,w1,b1,w2,b2\n all_weights = dict()\n # w1权重矩阵介于输入层和隐藏层之间,所以行数为n_input,列数为n_hidden\n all_weights['w1'] = tf.Variable(xavier_init(self.n_input, self.n_hidden))\n # b1偏值作用于输入层和隐藏层之间,所以尺寸为n_hidden大小\n all_weights['b1'] = tf.Variable(tf.zeros([self.n_hidden], dtype=tf.float32))\n # w2权重矩阵介于隐藏层和预测结果层之间,所以行数为n_hidden,列数为n_input,因为输出和输入的尺寸一样\n all_weights['w2'] = tf.Variable(tf.zeros([self.n_hidden, self.n_input], dtype=tf.float32))\n # b2偏值作用于隐藏层和预测结果层之间,所以尺寸为n_input大小,因为输出和输入的尺寸一样\n all_weights['b2'] = tf.Variable(tf.zeros([self.n_input], dtype=tf.float32))\n return all_weights\n\n # 计算损失函数和运行优化器\n def partial_fit(self, X):\n cost, opt = self.sess.run((self.cost, self.optimizer), feed_dict={self.x: X, self.scale: self.training_scale})\n return cost\n\n # 单独计算损失函数\n def calc_total_cost(self, X):\n return self.sess.run(self.cost, feed_dict={self.x: X, self.scale: self.training_scale})\n\n # 单独计算隐含层输出结果,用来提取数据的高阶特征,是整体拆分的前半部分\n def transform(self, X):\n return self.sess.run(self.hidden, feed_dict={self.x: X, self.scale: self.training_scale})\n\n # 将隐含层的高阶特征复原为原始数据,是整体拆分的后半部分\n def generate(self, hidden=None):\n if hidden is None:\n hidden = np.random.normal(size=self.weights['b1'])\n return self.sess.run(self.reconstruction, feed_dict={self.hidden: hidden})\n\n # 包括transform和generate两部分的重构\n def reconstruct(self, X):\n return self.sess.run(self.reconstruction, feed_dict={self.x: X, self.scale: self.training_scale})\n\n # 获取权重w1\n def getWeights(self):\n return self.sess.run(self.weights['w1'])\n\n # 获��偏值b1\n def getBiases(self):\n return self.sess.run(self.weights['b1'])\n\n\n# 读取数据集\nmnist = input_data.read_data_sets('MNIST_data', one_hot=True)\n\n\n# 数据标准化处理函数\ndef standard_scale(X_train, X_test):\n preprocessor = prep.StandardScaler().fit(X_train)\n X_train = preprocessor.transform(X_train)\n X_test = preprocessor.transform(X_test)\n return X_train, X_test\n\n\n# 最大限度不重复地获取数据\ndef get_random_block_from_data(data, batch_size):\n start_index = np.random.randint(0, len(data) - batch_size)\n return data[start_index:(start_index + batch_size)]\n\n\n# 标准化训练集和测试集\nX_train, X_test = standard_scale(mnist.train.images, mnist.test.images)\n# 总训练样本数\nn_samples = int(mnist.train.num_examples)\n# 训练轮数20\ntraining_epochs = 20\n# 每一次训练束大小128\nbatch_size = 128\n# 设置每一轮显示一次loss值\ndisplay_step = 1\n\nautoencoder = AdditiveGaussianNoiseAutoencoder(n_input=784, n_hidden=200, transfer_function=tf.nn.softplus,\n optimizer=tf.train.AdamOptimizer(learning_rate=0.001),\n scale=0.01)\n\nfor epoch in range(training_epochs):\n avg_cost = 0\n # 计算一共有多少束数据集\n total_batch = int(n_samples / batch_size)\n for i in range(total_batch):\n # 获取预设大小的数据集\n batch_xs = get_random_block_from_data(X_train, batch_size)\n cost = autoencoder.partial_fit(batch_xs)\n avg_cost += cost / n_samples * batch_size\n if epoch % display_step == 0:\n print(\"Epoch:\", '%04d' % (epoch + 1), \"cost=\", \"{:.9f}\".format(avg_cost))\n\nprint(\"Total cost: \" + str(autoencoder.calc_total_cost(X_test)))\n","repo_name":"littleheap/Tensorflow-in-Action","sub_path":"2.TensorFlow实现自编码器及多层感知器/2.1 自编码器.py","file_name":"2.1 自编码器.py","file_ext":"py","file_size_in_byte":6993,"program_lang":"python","lang":"zh","doc_type":"code","stars":47,"dataset":"github-code","pt":"27"} +{"seq_id":"7173464064","text":"import random\r\nimport sqlite3\r\nimport pickle\r\n\r\n\r\nlinked_list_representation = []\r\n\r\n# Data is set limited to 1000 points to avoid generating similar data.\r\nwhile 1:\r\n n_size = int(input(\"Please select size of database between 100 and 1000: \"))\r\n # Check limits\r\n if n_size >= 100 and n_size <= 1000 :\r\n break\r\n\r\n# Make the initial friends\r\n\r\npath = './dummy data/'\r\ndbfile = 'dummydata_'\r\n\r\ndatabase = path + dbfile + str(n_size) + \".db\"\r\n\r\n\r\nconn = sqlite3.connect(database)\r\ncurr = conn.cursor()\r\ncurr.execute('SELECT COUNT(*) FROM Data')\r\nrows = curr.fetchone()\r\nno_of_people = rows[0]\r\nconn.commit()\r\n\r\nall_people = [int(i) for i in range(no_of_people)] \r\n\r\nmin_friends = 50\r\nmax_friends = 100\r\nposs_friend = [int(i) for i in range(min_friends,max_friends)]\r\n\r\nprint(random.choice(poss_friend))\r\n\r\nfor i in all_people:\r\n #assuming each person has 50-99 friend\r\n\r\n temp_choice = (random.sample(all_people, random.choice(poss_friend)))\r\n temp_choice.sort()\r\n try:\r\n temp_choice.remove(i)\r\n except:\r\n pass\r\n linked_list_representation.append(temp_choice)\r\n\r\nprint(linked_list_representation)\r\n\r\nsave_filename = './friends network/' + 'linked_list_' + dbfile + str(n_size) +'.pkl'\r\n\r\nwith open(save_filename,'wb') as f:\r\n pickle.dump(linked_list_representation,f)","repo_name":"erYash15/Social-Media-Friend-Recommendation","sub_path":"making_friends.py","file_name":"making_friends.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"37261358858","text":"class 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 Space: O(1)\n \"\"\"\n\n def flatten(self, root: TreeNode) -> None:\n if root is None:\n return\n\n def nodes(node: TreeNode) -> tuple:\n if node is not None:\n left, right = node.left, node.right\n node.left = node.right = None\n yield node\n yield from nodes(left)\n yield from nodes(right)\n\n it = iter(nodes(root))\n parent = next(it)\n for node in it:\n parent.right = parent = node\n","repo_name":"Vasilic-Maxim/LeetCode-Problems","sub_path":"problems/114. Flatten Binary Tree to Linked List/1 - DFS [Generator].py","file_name":"1 - DFS [Generator].py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"42112819482","text":"import youtube_dl\nfrom flask import Flask\n\nfrom flask_restful import Api, Resource, reqparse\n\ndef download_song(url):\n ydl_opts = {\n 'format': 'bestaudio/best',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'mp3',\n 'preferredquality': '192',\n }],\n }\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n return ydl.download([url])\n\n\napp = Flask(__name__)\napi = Api(app)\n\nparser = reqparse.RequestParser()\nparser.add_argument('url')\n\n\nclass Song(Resource):\n def get(self):\n url = parser.parse_args()['url']\n download_success = download_song(url)\n return {'downloaded': bool(download_success)}\n\n\napi.add_resource(Song, '/')\n\nif __name__ == '__main__':\n app.run(debug=True, use_reloader=True)\n","repo_name":"mihirk/bub-server","sub_path":"bub/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"5464862049","text":"from django.utils import timezone\nfrom django.db import models\n\n\n# Create your models here.\nclass BaseModel(models.Model):\n created_date = models.DateTimeField(verbose_name=\"Created date\", editable=False)\n modified_date = models.DateTimeField(verbose_name=\"Modification Date\")\n\n class Meta:\n abstract = True\n\n\nclass League(BaseModel):\n league_pk = models.AutoField(\n db_column=\"league_pk\",\n primary_key=True,\n verbose_name=\"Primary key of the table\",\n help_text=\"Primary key of the table\",\n )\n\n league_id = models.BigIntegerField(\n verbose_name=\"Id League\",\n unique=True,\n null=False,\n blank=False,\n help_text=\"Id League\",\n )\n\n league_name = models.CharField(\n max_length=255,\n verbose_name=\"League name\",\n null=False,\n blank=False,\n help_text=\"Name of the league\",\n )\n\n league_slug = models.SlugField(\n max_length=255,\n verbose_name=\"Slug\",\n null=False,\n blank=False,\n help_text=\"Slug of the league\",\n )\n\n league_sport = models.CharField(\n max_length=6,\n verbose_name=\"Sport\",\n null=False,\n blank=False,\n help_text=\"Sport of the league\",\n )\n\n league_image = models.SlugField(\n max_length=500,\n verbose_name=\"Image of the league\",\n null=False,\n blank=False,\n help_text=\"Image of the league\",\n )\n\n league_light_image = models.ImageField(\n max_length=255,\n verbose_name=\"Light Image\",\n null=False,\n blank=False,\n help_text=\"Light Image of the league\",\n )\n\n league_dark_image = models.ImageField(\n max_length=255,\n verbose_name=\"Dark Image of the league\",\n null=False,\n blank=False,\n help_text=\"Dark Image of the league\",\n )\n\n league_region = models.CharField(\n max_length=255,\n verbose_name=\"Region\",\n null=False,\n blank=False,\n help_text=\"Region of the league\",\n )\n\n league_priority = models.IntegerField(\n verbose_name=\"Priority\", default=0, help_text=\"Priority of the league\"\n )\n\n league_display_priority_position = models.IntegerField(\n verbose_name=\"Display priority position\",\n null=False,\n blank=False,\n help_text=\"Display priority position\",\n )\n\n league_display_priority_status = models.BooleanField(\n verbose_name=\"Display Priority Status\",\n null=False,\n blank=False,\n help_text=\"Display priority status\",\n )\n\n class meta:\n db_table = \"league\"\n\n def save(self, *args, **kwargs):\n \"\"\"On save, update timestamps\"\"\"\n if not self.league_pk:\n self.created_date = timezone.now()\n self.modified_date = timezone.now()\n return super(League, self).save(*args, **kwargs)\n\n\nclass Tournament(BaseModel):\n tournament_pk = models.AutoField(\n db_column=\"tournament_pk\",\n primary_key=True,\n verbose_name=\"Primary key of the table\",\n help_text=\"Primary key of the table\",\n )\n tournament_id = models.BigIntegerField(\n unique=True, verbose_name=\"Tournament Id\", help_text=\"Tournament ForeignKey\"\n )\n tournament_name = models.CharField(\n verbose_name=\"Name\",\n max_length=255,\n null=False,\n blank=False,\n help_text=\"Tournament name\",\n )\n tournament_slug = models.SlugField(\n verbose_name=\"Slug\",\n max_length=255,\n null=False,\n blank=False,\n help_text=\"Tournament slug\",\n )\n tournament_sport = models.CharField(\n verbose_name=\"Sport\",\n max_length=255,\n null=False,\n blank=False,\n help_text=\"Tournament sport\",\n )\n tournament_start_date = models.DateField(\n verbose_name=\"Start Date\",\n null=False,\n blank=False,\n help_text=\"Tournament start date\",\n )\n tournament_end_date = models.DateField(\n verbose_name=\"End Date\",\n null=False,\n blank=False,\n help_text=\"Tournament end date\",\n )\n\n class meta:\n db_table = \"tournament\"\n\n def save(self, *args, **kwargs):\n \"\"\"On save, update timestamps\"\"\"\n if not self.tournament_pk:\n self.created_date = timezone.now()\n self.modified_date = timezone.now()\n return super(Tournament, self).save(*args, **kwargs)\n\n\nclass Team(BaseModel):\n team_pk = models.AutoField(\n db_column=\"team_pk\",\n primary_key=True,\n verbose_name=\"Primary key of the table\",\n help_text=\"Primary key of the table\",\n )\n\n team_id = models.BigIntegerField(\n verbose_name=\"Team\",\n unique=True,\n null=False,\n blank=False,\n help_text=\"Team ForeignKey\",\n )\n\n team_name = models.CharField(\n verbose_name=\"Name\",\n max_length=255,\n null=False,\n blank=False,\n help_text=\"Team name\",\n )\n team_acronym = models.CharField(\n verbose_name=\"Acronym\",\n max_length=255,\n null=False,\n blank=False,\n help_text=\"Team acronym\",\n )\n team_slug = models.SlugField(\n verbose_name=\"Slug\",\n max_length=255,\n null=False,\n blank=False,\n help_text=\"Team slug\",\n )\n\n class meta:\n db_table = \"team\"\n\n def save(self, *args, **kwargs):\n \"\"\"On save, update timestamps\"\"\"\n if not self.team_pk:\n self.created_date = timezone.now()\n self.modified_date = timezone.now()\n return super(Team, self).save(*args, **kwargs)\n\n\nclass Player(BaseModel):\n player_pk = models.AutoField(\n db_column=\"player_pk\",\n primary_key=True,\n verbose_name=\"Primary key of the table\",\n help_text=\"Primary key of the table\",\n )\n\n player_id = models.BigIntegerField(\n verbose_name=\"Player\",\n unique=True,\n null=False,\n blank=False,\n help_text=\"Player identifier\",\n )\n\n team_id = models.BigIntegerField(\n verbose_name=\"Team\", null=True, blank=True, help_text=\"Team ForeignKey\"\n )\n\n player_handle = models.CharField(\n verbose_name=\"Handle\",\n max_length=16,\n null=False,\n blank=False,\n help_text=\"Player handle\",\n )\n\n player_name = models.CharField(\n verbose_name=\"Name\",\n max_length=255,\n null=False,\n blank=False,\n help_text=\"Player name\",\n )\n\n class meta:\n db_table = \"player\"\n\n def save(self, *args, **kwargs):\n \"\"\"On save, update timestamps\"\"\"\n if not self.player_pk:\n self.created_date = timezone.now()\n self.modified_date = timezone.now()\n return super(Player, self).save(*args, **kwargs)\n\n\nclass Game(BaseModel):\n game_pk = models.AutoField(\n db_column=\"game_pk\",\n primary_key=True,\n verbose_name=\"Primary key of the table\",\n help_text=\"Primary key of the table\",\n )\n\n game_id = models.BigIntegerField(\n verbose_name=\"Game\",\n null=False,\n blank=False,\n unique=True,\n help_text=\"Game identifier\",\n )\n game_platform_id = models.CharField(\n verbose_name=\"Platform\",\n max_length=255,\n null=False,\n blank=False,\n help_text=\"Game plataform identifier\",\n )\n game_year = models.IntegerField(\n verbose_name=\"Year\", null=False, blank=False, help_text=\"Game year\"\n )\n\n class meta:\n db_table = \"game\"\n\n def save(self, *args, **kwargs):\n \"\"\"On save, update timestamps\"\"\"\n if not self.game_pk:\n self.created_date = timezone.now()\n self.modified_date = timezone.now()\n return super(Game, self).save(*args, **kwargs)\n\n\nclass GameDetail(BaseModel):\n game_detail_pk = models.AutoField(\n db_column=\"game_detail_pk\",\n primary_key=True,\n verbose_name=\"Primary key of the table\",\n help_text=\"Primary key of the table\",\n )\n\n game_id = models.ForeignKey(\n Game,\n db_column=\"game_id\",\n verbose_name=\"Game\",\n null=False,\n blank=False,\n help_text=\"Game identifier\",\n on_delete=models.CASCADE,\n )\n player_id = models.BigIntegerField(\n db_column=\"player_id\",\n verbose_name=\"Player\",\n null=False,\n blank=False,\n help_text=\"Player identifier\",\n )\n game_detail_player_match = models.BooleanField(\n verbose_name=\"Player equal to player table\",\n null=False,\n blank=False,\n default=False,\n help_text=\"Player match with the player table?\",\n )\n\n class meta:\n db_table = \"game_detail\"\n\n def save(self, *args, **kwargs):\n \"\"\"On save, update timestamps\"\"\"\n if not self.game_detail_pk:\n self.created_date = timezone.now()\n self.modified_date = timezone.now()\n return super(GameDetail, self).save(*args, **kwargs)\n\n\nclass StageName(BaseModel):\n stage_name_pk = models.AutoField(\n db_column=\"stage_name_pk\",\n primary_key=True,\n verbose_name=\"Primary key of the table\",\n help_text=\"Primary key of the table\",\n )\n\n stage_name_name = models.CharField(\n verbose_name=\"Stage name\",\n max_length=50,\n null=False,\n blank=False,\n help_text=\"Stage name\",\n )\n\n class meta:\n db_table = \"stage_name_name\"\n\n\nclass StageType(BaseModel):\n stage_type_pk = models.AutoField(\n db_column=\"stage_type_pk\",\n primary_key=True,\n verbose_name=\"Primary key of the table\",\n help_text=\"Primary key of the table\",\n )\n\n stage_type_name = models.CharField(\n verbose_name=\"Section\",\n max_length=50,\n null=False,\n blank=False,\n help_text=\"Stage type name\",\n )\n\n class meta:\n db_table = \"stage_type_name\"\n\n\nclass StageSlug(BaseModel):\n stage_slug_pk = models.AutoField(\n db_column=\"stage_slug_pk\",\n primary_key=True,\n verbose_name=\"Primary key of the table\",\n help_text=\"Primary key of the table\",\n )\n\n stage_slug_slug = models.CharField(\n verbose_name=\"Stage slug\",\n max_length=50,\n null=False,\n blank=False,\n help_text=\"Stage type name\",\n )\n\n class meta:\n db_table = \"stage_type_name\"\n\n\nclass Stage(BaseModel):\n stage_pk = models.AutoField(\n db_column=\"stage_pk\",\n primary_key=True,\n verbose_name=\"Primary key of the table\",\n help_text=\"Primary key of the table\",\n )\n tournament_id = models.ForeignKey(\n Tournament,\n db_column=\"tournament_id\",\n verbose_name=\"Tournament\",\n null=True,\n help_text=\"Tournament ForeignKey\",\n on_delete=models.CASCADE,\n )\n stage_name = models.ForeignKey(\n StageName,\n on_delete=models.DO_NOTHING,\n verbose_name=\"Stage\",\n null=False,\n blank=False,\n help_text=\"Stage name\",\n )\n stage_type = models.ForeignKey(\n StageType,\n on_delete=models.DO_NOTHING,\n verbose_name=\"Type\",\n blank=True,\n null=True,\n help_text=\"Stage type\",\n )\n stage_slug = models.ForeignKey(\n StageSlug,\n on_delete=models.DO_NOTHING,\n verbose_name=\"Slug\",\n null=False,\n blank=False,\n help_text=\"Stage slug\",\n )\n\n class meta:\n db_table = \"stage\"\n\n def save(self, *args, **kwargs):\n \"\"\"On save, update timestamps\"\"\"\n if not self.stage_pk:\n self.created_date = timezone.now()\n self.modified_date = timezone.now()\n return super(Stage, self).save(*args, **kwargs)\n\n\nclass SectionName(BaseModel):\n section_name_pk = models.AutoField(\n db_column=\"section_name_pk\",\n primary_key=True,\n verbose_name=\"Primary key of the table\",\n help_text=\"Primary key of the table\",\n )\n\n section_name = models.CharField(\n verbose_name=\"Section Name\",\n max_length=50,\n null=False,\n blank=False,\n help_text=\"Section name\",\n )\n\n class meta:\n db_table = \"section_name\"\n\n\nclass Section(BaseModel):\n section_pk = models.AutoField(\n db_column=\"section_pk\",\n primary_key=True,\n verbose_name=\"Primary key of the table\",\n help_text=\"Primary key of the table\",\n )\n\n stage_id = models.ForeignKey(\n Stage,\n db_column=\"stage_pk\",\n verbose_name=\"Stage\",\n on_delete=models.CASCADE,\n help_text=\"Stage ForeignKey\",\n )\n\n section_name = models.ForeignKey(\n SectionName,\n verbose_name=\"Section\",\n on_delete=models.CASCADE,\n null=False,\n blank=False,\n help_text=\"Section name\",\n )\n\n class meta:\n db_table = \"section\"\n\n def save(self, *args, **kwargs):\n \"\"\"On save, update timestamps\"\"\"\n if not self.section_pk:\n self.created_date = timezone.now()\n self.modified_date = timezone.now()\n return super(Section, self).save(*args, **kwargs)\n\n\nclass MatchType(BaseModel):\n match_type_pk = models.AutoField(\n db_column=\"match_type_pk\",\n primary_key=True,\n )\n match_type_name = models.CharField(verbose_name=\"Match type name\", max_length=50)\n\n class meta:\n db_table = \"match_type\"\n\n\nclass MatchState(BaseModel):\n match_state_pk = models.AutoField(\n db_column=\"match_state_pk\",\n primary_key=True,\n )\n match_state_name = models.CharField(verbose_name=\"Match state name\", max_length=50)\n\n class meta:\n db_table = \"match_state\"\n\n\nclass MatchMode(BaseModel):\n match_mode_pk = models.AutoField(\n db_column=\"match_mode_pk\",\n primary_key=True,\n )\n match_mode_name = models.CharField(verbose_name=\"Match mode name\", max_length=50)\n\n class meta:\n db_table = \"match_mode\"\n\n\nclass MatchStrategy(BaseModel):\n match_strategy_pk = models.AutoField(\n db_column=\"match_strategy_pk\", primary_key=True\n )\n match_strategy_name = models.CharField(\n max_length=50, verbose_name=\"Match strategy name\"\n )\n\n class meta:\n db_table = \"match_strategy\"\n\n\nclass Match(BaseModel):\n match_pk = models.AutoField(\n db_column=\"match_pk\",\n primary_key=True,\n verbose_name=\"Primary key of the table\",\n help_text=\"Primary key of the table\",\n )\n\n section_id = models.ForeignKey(\n Section,\n db_column=\"section_pk\",\n verbose_name=\"Section Detail\",\n on_delete=models.CASCADE,\n help_text=\"Section ForeignKey\",\n )\n match_type = models.ForeignKey(MatchType, on_delete=models.DO_NOTHING)\n match_state = models.ForeignKey(\n MatchState, on_delete=models.DO_NOTHING, help_text=\"Match state\"\n )\n match_mode = models.ForeignKey(\n MatchMode, on_delete=models.DO_NOTHING, help_text=\"Match mode\"\n )\n match_strategy = models.ForeignKey(\n MatchStrategy,\n on_delete=models.DO_NOTHING,\n verbose_name=\"Strategy\",\n help_text=\"Match strategy\",\n )\n\n class meta:\n db_table = \"match\"\n\n def save(self, *args, **kwargs):\n \"\"\"On save, update timestamps\"\"\"\n if not self.match_pk:\n self.created_date = timezone.now()\n self.modified_date = timezone.now()\n return super(Match, self).save(*args, **kwargs)\n\n\nclass MatchDetail(BaseModel):\n match_detail_pk = models.AutoField(\n db_column=\"match_detail_pk\",\n primary_key=True,\n verbose_name=\"Primary key of the table\",\n help_text=\"Primary key of the table\",\n )\n\n match_id = models.ForeignKey(\n Match,\n verbose_name=\"Match\",\n on_delete=models.CASCADE,\n help_text=\"Match ForeignKey\",\n )\n\n team_id = models.ForeignKey(\n Team, verbose_name=\"Team\", on_delete=models.CASCADE, help_text=\"Team identifier\"\n )\n\n match_detail_match_team_integrant = models.BooleanField(\n verbose_name=\"Match Integrant\",\n default=False,\n null=False,\n help_text=\"Match team integrants with integrants table?\",\n )\n\n match_detail_win = models.BooleanField(\n verbose_name=\"Win Game?\", null=False, blank=False, help_text=\"Win the game?\"\n )\n\n class meta:\n db_table = \"match_detail\"\n\n def save(self, *args, **kwargs):\n \"\"\"On save, update timestamps\"\"\"\n if not self.match_detail_pk:\n self.created_date = timezone.now()\n self.modified_date = timezone.now()\n return super(MatchDetail, self).save(*args, **kwargs)\n","repo_name":"yonathanavila/bckPower","sub_path":"base/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":16615,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"38474053712","text":"\"\"\"\nslots1 = [[10,50],[60,120],[140,210]], slots2 = [[0,15],[60,70]]\n[(0,15),(10,50),(60,120),(60,70),(140,210)]\n\"\"\"\n\nimport heapq\nclass Solution:\n def minAvailableDuration(self, slots1: List[List[int]], slots2: List[List[int]], duration: int) -> List[int]:\n lst = [(s, e) for s, e in slots1 + slots2 if s + duration <= e]\n heapq.heapify(lst)\n while len(lst) > 1:\n top = heapq.heappop(lst)\n other = lst[0]\n if other[0] + duration <= top[1]:\n return [other[0], other[0] + duration]\n return []","repo_name":"jsphweid/chops","sub_path":"lc/answers/meeting-scheduler/2022.03.25-19.52.27.py","file_name":"2022.03.25-19.52.27.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"71457771591","text":"from project_1 import TimeZone, Account\nimport unittest\nfrom datetime import datetime, timedelta\n\n#there are a whole bunch more tests one could add\n\ndef run_tests(test_class):\n suite = unittest.TestLoader().loadTestsFromTestCase(test_class)\n runner = unittest.TextTestRunner(verbosity=2)\n result = runner.run(suite)\n\nclass TestAccount(unittest.TestCase):\n\n def setUp(self):\n self.acc_no = 110020\n self.first_name = 'FIRST'\n self.last_name = 'LAST'\n self.balance = 100.00\n self.tz = TimeZone('TZ', 1, 30)\n\n def create_account(self):\n return Account(self.acc_no, self.first_name, self.last_name, self.balance, self.tz)\n \n def test_create_timezone(self):\n tz = TimeZone('ABC', -1, -30)\n self.assertEqual('ABC', tz.name)\n self.assertEqual(timedelta(hours=-1, minutes=-30), tz.offset)\n \n def test_timezones_equal(self):\n tz1 = TimeZone('ABC', -1, -30)\n tz2 = TimeZone('ABC', -1, -30)\n self.assertEqual(tz1, tz2)\n \n def test_timezones_not_equal(self):\n tz = TimeZone('ABC', -1, -30)\n \n test_timezones = (\n TimeZone('DEF', -1, -30),\n TimeZone('ABC', -1, 0),\n TimeZone('ABC', 1, -30)\n )\n for i, test_tz in enumerate(test_timezones): #see how to do this in pytest \n with self.subTest(test_name=f'Test #{i}'):\n self.assertNotEqual(tz, test_tz)\n\n def test_create_account(self): \n a = self.create_account()\n\n self.assertEqual(self.acc_no, a.acc_no)\n self.assertEqual(self.first_name, a.first_name)\n self.assertEqual(self.last_name, a.last_name)\n self.assertEqual(self.first_name + ' ' + self.last_name, a.full_name)\n self.assertEqual(self.tz, a.time_zone)\n self.assertEqual(self.balance, a.balance)\n\n def test_create_account_blank_first_name(self):\n self.first_name = ''\n with self.assertRaises(ValueError):\n a = self.create_account()\n self.first_name = None\n with self.assertRaises(ValueError):\n a = self.create_account()\n\n def test_create_account_blank_last_name(self):\n self.last_name = ''\n with self.assertRaises(ValueError):\n a = self.create_account()\n self.last_name = None\n with self.assertRaises(ValueError):\n a = self.create_account()\n\n def test_create_account_negative_balance(self):\n self.balance = -100.00\n with self.assertRaises(ValueError):\n a = self.create_account()\n\n def test_account_deposit_negative_amount(self):\n deposit_value = -100\n a = self.create_account()\n with self.assertRaises(ValueError):\n conf_code = a.deposit(deposit_value)\n\n def test_account_withdraw_ok(self):\n withdraw_value = 20\n a = self.create_account()\n conf_code = a.withdraw(withdraw_value)\n self.assertEqual(self.balance-withdraw_value, a.balance)\n self.assertIn('W-', conf_code)\n\n def test_account_withdraw_overdraw(self):\n withdraw_value = 200\n a = self.create_account()\n conf_code = a.withdraw(withdraw_value)\n self.assertIn('X-', conf_code)\n self.assertEqual(self.balance, a.balance)\n \n\nrun_tests(TestAccount)\n\n\n","repo_name":"EmPlatts/UdemyPython3_DeepDive-My_Solutions","sub_path":"Part_4-OOP/project_1/project_1_unittests.py","file_name":"project_1_unittests.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"42413653046","text":"\r\nimport os\r\nfrom mmseg.apis import inference_segmentor, init_segmentor, show_result_pyplot\r\nfrom mmseg.core.evaluation import get_palette\r\nfrom mim.commands.download import download\r\nfrom mmcv.cnn.utils.sync_bn import revert_sync_batchnorm\r\n\r\ndef main():\r\n img_path = './photos/IMG_0004_512x512.JPG'\r\n #img_path = './photos/IMG_0004.JPG'\r\n \r\n device = 'cpu'\r\n \r\n model_dir = 'models'\r\n os.makedirs(model_dir, exist_ok=True)\r\n \r\n # モデル\r\n #checkpoint_name = 'deeplabv3plus_r101-d8_512x512_20k_voc12aug'\r\n #checkpoint_name = 'deeplabv3plus_r101-d8_512x512_40k_voc12aug'\r\n #checkpoint_name = 'deeplabv3plus_r50-d8_512x512_80k_ade20k'\r\n #checkpoint_name = 'knet_s3_fcn_r50-d8_8x2_512x512_adamw_80k_ade20k'\r\n #checkpoint_name = 'segformer_mit-b0_512x512_160k_ade20k'\r\n checkpoint_name = 'segmenter_vit-b_mask_8x1_512x512_160k_ade20k'\r\n \r\n config_fname = checkpoint_name + '.py'\r\n checkpoint = download(package=\"mmsegmentation\", configs=[checkpoint_name], dest_root=model_dir)[0]\r\n \r\n model = init_segmentor(os.path.join('models', config_fname), os.path.join(model_dir, checkpoint), device = 'cpu')\r\n if device=='cpu':\r\n model = revert_sync_batchnorm(model)\r\n\r\n result = inference_segmentor(model, img_path)\r\n \r\n # 表示\r\n #show_result_pyplot(model, img_path, result, get_palette('voc12aug'))\r\n show_result_pyplot(model, img_path, result, get_palette('ade20k'))\r\n\r\n\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n main()\r\n","repo_name":"yo16/semantic_segmentation_deeplabv3","sub_path":"src/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"73062777993","text":"# ##############################\n# # Title: Globals\n# # Desc: House Global values for use across the program\n# # Author: Arjun Singh\n# ##############################\n\n# Map\nx, y = 500, 500\na = 0\nyaw = 0\npoints = [(0, 0), (0, 0)]\n\n# Global variables\nglobal img\nglobal auto_deadline\n\n# State\ncurrent_state = \"manual\"\n\n# Filter\ncurrent_filter = \"normal\"\n","repo_name":"ArjunHarvard/MobGuardian","sub_path":"mob_guard/globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"7794983090","text":"def celsius(f):\n return (f - 32) * 5 / 9\n\n\ndef farenheit(c):\n return c * (9 / 5) + 32\n\n\nprint('---Convertir unidades de temperatura')\nunidad_original = (input('unidad a convertir: [C] a F o [F] a C: ')).lower()\nif unidad_original == 'f' or unidad_original == 'c':\n try:\n temperatura_original = float(input('Temperatura a convertir:'))\n except ValueError:\n print(\"Valor de peso no valido, por favor inserte un valor valido\")\n else:\n if unidad_original == 'f':\n temperatura_convertida = celsius((temperatura_original))\n print(f'{temperatura_original} F son equivalentes a {temperatura_convertida} C')\n elif unidad_original == 'c':\n temperatura_convertida = farenheit((temperatura_original))\n print(f'{temperatura_original} C son equivalentes a {temperatura_convertida} F')\nelse:\n print(\"unidad no valida, por favor inserte una unidad correcta\")","repo_name":"edumarg/python_ejercises","sub_path":"conversor_temepratura.py","file_name":"conversor_temepratura.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"39395841396","text":"import win32com.client\r\n\r\ndef str_count(text, substr): #количество вхождений подстроки в строку\r\n return len(text.split(substr))-1\r\n\r\n\r\npos=2\r\nfn=[u'c:\\\\rasp_zach\\\\1.xlsx',\r\n u'c:\\\\rasp_zach\\\\2.xlsx',\r\n u'c:\\\\rasp_zach\\\\3.xlsx',\r\n u'c:\\\\rasp_zach\\\\4.xlsx',\r\n u'c:\\\\rasp_zach\\\\5.xlsx']\r\n\r\nofn=u'c:\\\\rasp_zach\\\\zach.xlsx'\r\nmas= [['23 декабря понедельник', 6, 16], \r\n ['24 декабря вторник', 16, 28], \r\n ['25 декабря среда', 28, 40],\r\n ['26 декабря четверг', 40, 52],\r\n ['27 декабря пятница', 52, 64],\r\n ['28 декабря суббота', 64, 76]]\r\nExcel = win32com.client.Dispatch(\"Excel.Application\")\r\nowb = Excel.Workbooks.Open(ofn)\r\nosheet = owb.ActiveSheet\r\nfor fi in range(0,5):\r\n print(fn[fi])\r\n wb = Excel.Workbooks.Open(fn[fi])\r\n sheet = wb.ActiveSheet\r\n i=1\r\n while i<300:\r\n rw=2 # строка с шифрами групп\r\n #gr=str(currentSheet.cell(row=rw, column=i).value)\r\n gr=str(sheet.Cells(rw,i).value)\r\n #print(gr)\r\n if len(gr)>4:\r\n if str_count(gr, '-')>1:\r\n for mm in range(0,6):\r\n den=mas[mm][0]\r\n for z in range(mas[mm][1],mas[mm][2]):\r\n predm=str(sheet.Cells(z,i).value)\r\n if len(predm)>7:\r\n kto=str(sheet.Cells(z,i+2).value)\r\n gde=str(sheet.Cells(z,i+3).value)\r\n gde=gde.replace('.0','')\r\n kurs=str(fi+1)\r\n vremya=str(sheet.Cells(z,3).value)\r\n osheet.Cells(pos,1).value=kto\r\n osheet.Cells(pos,2).value=den\r\n osheet.Cells(pos,3).value=vremya\r\n osheet.Cells(pos,4).value=predm\r\n osheet.Cells(pos,5).value=kurs\r\n osheet.Cells(pos,6).value=gr\r\n osheet.Cells(pos,7).value=gde\r\n pos=pos+1\r\n #print(den+' '+gr+' '+ predm+' '+ kto+' '+ gde)\r\n i=i+1\r\n wb.Close() \r\nowb.Save()\r\nowb.Close()\r\n#закрываем COM объект\r\nExcel.Quit()","repo_name":"RusAl84/Mirea-rasp-zach-parser","sub_path":"print_rasp2.py","file_name":"print_rasp2.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"32898856637","text":"\nimport ta_ziften_zenith_declare\n\nfrom splunktaucclib.rest_handler.endpoint import (\n field,\n validator,\n RestModel,\n MultipleModel,\n)\nfrom splunktaucclib.rest_handler import admin_external, util\nfrom splunk_aoblib.rest_migration import ConfigMigrationHandler\n\nutil.remove_http_proxy_env_vars()\n\n\nfields_additional_parameters = [\n field.RestField(\n 'zenith_ar_management_host_ip',\n required=False,\n encrypted=False,\n default='',\n validator=validator.String(\n min_len=0, \n max_len=8192, \n )\n ), \n field.RestField(\n 'zenith_ar_username',\n required=False,\n encrypted=False,\n default='',\n validator=validator.String(\n min_len=0, \n max_len=8192, \n )\n ), \n field.RestField(\n 'zenith_ar_api_key',\n required=False,\n encrypted=False,\n default='',\n validator=validator.String(\n min_len=0, \n max_len=8192, \n )\n )\n]\nmodel_additional_parameters = RestModel(fields_additional_parameters, name='additional_parameters')\n\n\nendpoint = MultipleModel(\n 'ta_ziften_zenith_settings',\n models=[\n model_additional_parameters\n ],\n)\n\n\nif __name__ == '__main__':\n admin_external.handle(\n endpoint,\n handler=ConfigMigrationHandler,\n )\n","repo_name":"asimchamp/Splunk_Apps","sub_path":"SplunkBase/1872_Ziften_Zenith_Add-on/2.1.0/TA-ziften/bin/TA_Ziften_Zenith_rh_settings.py","file_name":"TA_Ziften_Zenith_rh_settings.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"13679958061","text":"fruit=input().lower().strip()\r\n\r\n#Product count\r\nac=fruit.count('a')\r\nbc=fruit.count('b')\r\ncc=fruit.count('c')\r\ndc=fruit.count('d')\r\n\r\n#logic section\r\nif ac>=4 or cc>=6:\r\n rcc=cc//6\r\n rc=cc%6\r\n raa = ac//4\r\n ra=ac%4\r\n total =100*raa+ra*35+250*rcc+rc*50+bc*65+dc*85\r\n print(\"{:.2f}\".format(total))\r\nelse:\r\n total = ac*35+bc*65+cc*50+dc*85\r\n print(\"{:.2f}\".format(total))","repo_name":"Pratibha-01/Fruit_store","sub_path":"fruit_store.py","file_name":"fruit_store.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"32706626465","text":"\"\"\"\nThis script creates a txt file which contains all of the words in statis/sound/words/\nand tries it's best to match up the word with the filename.\n\"\"\"\n\nimport os\nimport sys\nimport re\nimport unicodedata\n\nDIRECTORY = \"/home/brent/Repositories/CreeTutor/CreeTutorBackEnd/lettergame/static/lettergame/sound/Words\"\n#Open words and get all the words\nwith open('/home/brent/Repositories/CreeTutor/Linguistics/words_e.txt', 'r') as words:\n words_list = words.readlines()\n for i in range(len(words_list)):\n words_list[i] = unicodedata.normalize('NFC', words_list[i])\n\n#Open sentences.txt and get all the sentences\nwith open('/home/brent/Repositories/CreeTutor/Linguistics/sentences.txt', 'r') as sents:\n sents_list = sents.readlines()\n\n#create a dictionary\nwords_dict = {}\n\n\n\nwith open(\"/home/brent/Repositories/CreeTutor/Linguistics/words_complete.txt\",'w') as doc:\n #get a sorted list of filenames\n files = []\n for filename in os.listdir(DIRECTORY):\n files.append(unicodedata.normalize('NFC', filename))\n files.sort()\n event = 1\n for word in words_list:\n comp = re.compile(word.strip())\n word = unicodedata.normalize('NFC', word).strip()\n for f in files:\n string = f.split('.')[0].split('-')[0].split('_')[0]\n if event ==0:\n sys.stdout.write(string + '\\n')\n for i in string:\n sys.stdout.write(str(ord(i))+'\\n')\n sys.stdout.write(word + '\\n')\n for i in word:\n sys.stdout.write(str(ord(i))+'\\n')\n event =+1\n if re.fullmatch(comp,string)!=None:\n if word in words_dict.keys():\n words_dict[word].append(f)\n else:\n words_dict[word] = [f]\n if word in words_dict.keys():\n doc.write(re.sub('e','ê',word) + '\\t' + \",\".join(words_dict[word]) + \"\\n\")\n else:\n doc.write(re.sub('e','ê',word) + '\\n')\n","repo_name":"EdTeKLA/Cree-Tutor","sub_path":"Linguistics/filenames.py","file_name":"filenames.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"22760152404","text":"\"\"\"Module for custom nn.Module\"\"\"\nfrom typing import Any, Union\nfrom abc import abstractmethod\nimport types\n\nimport torch\nfrom torch import nn\n\n\n__all__ = [\n \"Module\"\n]\n\n\nclass Module(nn.Module):\n \"\"\"Custom nn.Module\n\n Example:\n ```python\n # Custom network\n class Net(Module):\n ...\n # Function used for normal forward\n @Module.register(\"forward\")\n def _ff(self, ...):\n ...\n # Function used for computing loss\n @Module.register(\"loss\")\n def _loss(self, ...):\n ...\n\n net = Net()\n # Call net._ff\n y = net(\"forward\", x)\n # Call net._loss\n loss = net(\"loss\", y, label)\n ```\n \"\"\"\n @staticmethod\n def register(key):\n \"\"\"Decorator for register forward function into module.\n\n Args:\n key (str): The key for registering a forward function.\n \"\"\"\n def _wrapped(fn: Any):\n if isinstance(fn, property):\n fn.fget._vlutilsModuleMappedFunction = key\n else:\n fn._vlutilsModuleMappedFunction = key\n return fn\n return _wrapped\n\n def __init__(self):\n super().__init__()\n self._functions = dict()\n for methodname in dir(self):\n method = getattr(self, methodname)\n if isinstance(method, property):\n method = method.fget\n if hasattr(method, \"_vlutilsModuleMappedFunction\"):\n self._functions[method._vlutilsModuleMappedFunction] = method\n\n def _replicate_for_data_parallel(self):\n replica = super()._replicate_for_data_parallel()\n # Redirect mapped function to new replica.\n replica._functions = {k: types.MethodType(v.__func__, replica) for k, v in replica._functions.items()}\n return replica\n\n @abstractmethod\n def _forward(self, *args: Any, **kwargs: Any) -> Any:\n raise NotImplementedError\n\n def forward(self, key: Union[torch.Tensor, str], *args: Any, **kwargs: Any) -> Any:\n \"\"\"Custom forward function\n\n Args:\n key (str): Key of the target fuction.\n\n Returns:\n Any: Result.\n \"\"\"\n if not isinstance(key, str):\n args = (key, ) + args\n return self._forward(*args, **kwargs)\n return self._functions[key](*args, **kwargs)\n","repo_name":"VL-Group/vlutils","sub_path":"vlutils/base/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"27276993453","text":"import wx\nfrom threading import *\n\nfrom remoteIR import remote #read data from IR receiver\n\nimport logging\n\n\n\n\n# Define notification event for thread completion\nEVT_RESULT_ID = wx.NewIdRef()\n\ndef evt_result(win, func):\n \"\"\"Define Result Event.\"\"\"\n win.Connect(-1, -1, EVT_RESULT_ID, func)\n\nclass ResultEvent(wx.PyEvent):\n \"\"\"Simple event to carry arbitrary result data.\"\"\"\n def __init__(self, data):\n \"\"\"Init Result Event.\"\"\"\n wx.PyEvent.__init__(self)\n self.SetEventType(EVT_RESULT_ID)\n self.data = data\n\n# Thread class that executes processing\nclass WorkerThread(Thread):\n \n \n \n \"\"\"Worker Thread Class.\"\"\"\n def __init__(self, notify_window):\n \n \"\"\"Init Worker Thread Class.\"\"\"\n Thread.__init__(self, daemon = True)\n self._notify_window = notify_window\n self._want_abort = False\n self.receiverIR=remote()\n # This starts the thread running on creation, but you could\n # also make the GUI thread responsible for calling this\n self.start()\n\n def run(self):\n logging.debug(\"Thread running!\")\n \"\"\"Run Worker Thread.\"\"\"\n # This is the code executing in the new thread. You will\n # need to structure your processing so that you periodically\n # peek at the abort variable\n while self._want_abort==False:\n codigo = self.receiverIR.Getcode()\n logging.debug(\"IR code: \"+str(codigo))\n \n if self._want_abort:\n # Use a result of None to acknowledge the abort (of\n # course you can use whatever you'd like or even\n # a separate event type)\n wx.PostEvent(self._notify_window, ResultEvent(None))\n return\n # Here's where the result would be returned (this is an\n # example fixed result of the number 10, but it could be\n # any Python object)\n wx.PostEvent(self._notify_window, ResultEvent(codigo))\n\n def abort(self):\n logging.debug(\"Thread aborted!\")\n \"\"\"abort worker thread.\"\"\"\n # Method for use by main thread to signal an abort\n self._want_abort = 1\n","repo_name":"freseco/pyerir","sub_path":"sourcecode/mythreadIR.py","file_name":"mythreadIR.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"3119679794","text":"import numpy as np\n\nfrom src.matching.get_matching_classifier import MatchingClassifier\n\n\ndef test_matching_classifier():\n mc = MatchingClassifier()\n term_pairs = [(\"stemi\", \"nstemi\"), (\"stroke\", \"fracture\")]\n matches = mc.predict(term_pairs)\n assert list(matches) == [\"y\", \"n\"], \"Failed to match entities correctly.\"\n\n embedding_pairs = [\n (mc.embedding(t1), mc.embedding(t2)) for t1, t2 in term_pairs\n ]\n vec_1 = np.vstack([v1 for v1, v2 in embedding_pairs])\n vec_2 = np.vstack([v2 for v1, v2 in embedding_pairs])\n match_probs = mc.predict_proba_from_embeddings(vec_1, vec_2)\n assert match_probs[0] > 0.5, \"%s and %s should match\" % term_pairs[0]\n assert match_probs[1] < 0.5, \"%s and %s should match\" % term_pairs[1]\n","repo_name":"davidlibland/scratch-python","sub_path":"clustering/clustering_algorithms/src/matching/tests/test_matching_classifier.py","file_name":"test_matching_classifier.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"29630138107","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.svm import LinearSVC\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import classification_report\n\n\ndef parse_ombd(omdb):\n # filter out movies with no plot\n omdb = omdb[omdb['omdb_plot'] != 'N/A']\n omdb = omdb.reset_index()\n omdb = omdb.drop(columns='index')\n return omdb\n\n\ndef parse_wikidata(wikidata):\n # filter out movies with no publication date \n wikidata = wikidata[wikidata['publication_date'].notnull()].copy()\n # parse year from format \"yyyy-mm-dd\" and convert it to int to compare\n wikidata[['year', 'month', 'date']] = wikidata['publication_date'].str.split('-', expand=True)\n wikidata['year'] = wikidata['year'].astype(int)\n wikidata = wikidata[(wikidata['year'] < 2019) & (wikidata['year'] > 1979)]\n wikidata = wikidata.reset_index()\n wikidata = wikidata[['year', 'imdb_id']]\n return wikidata\n\n\ndef parse_plot(omdb):\n # 1. convert all letters to lowercase\n # 2. keep letters and digits\n # [\\w] == [A-Za-z0-9_] == match any alphabet and digit\n # [^\\w] == negate \\w == match any character NOT alphabet and digit\n # [\\'-] == in case of words with ' and -\n omdb_plot = omdb['omdb_plot'].str.lower().str.replace(r'[^\\w\\s\\'-]', '')\n return omdb_plot.tolist()\n\n\ndef parse_genre(omdb):\n # convert Series into list and return unique elements of that list\n genres = np.concatenate(omdb['omdb_genres'])\n return np.unique(genres)\n\n\ndef plot_text_length_histogram(omdb):\n counts = omdb['omdb_plot'].str.len()\n fig, ax = plt.subplots()\n counts.hist(bins=np.arange(0,5000,50), figsize=(16, 9), ax=ax)\n plt.title('Characters in Plots')\n plt.xlabel('Characters', fontsize=12)\n plt.ylabel('Plots', fontsize=12)\n ax.set_axisbelow(True)\n ax.grid(linestyle=':')\n plt.savefig('output/text_in_plot.png')\n plt.show()\n\n\ndef plot_genre_vs_occurrence(genres, count):\n counts = pd.DataFrame({'genre':genres, 'count':np.sum(count, axis=0)})\n fig, ax = plt.subplots()\n counts.plot(x='genre', y='count', kind='bar', legend=False, figsize=(16, 9), ax=ax)\n ax.set_axisbelow(True)\n ax.grid(linestyle=':')\n plt.title('Number of Occurrences of each Genre')\n plt.ylabel('Occurrences', fontsize=12)\n plt.xlabel('Genres', fontsize=12)\n plt.xticks(rotation=35, ha='right')\n plt.savefig('output/genre_vs_occurrence.png')\n plt.show()\n\n\ndef plot_genre_trend(genre_trend):\n fig, ax = plt.subplots()\n genre_trend.plot(figsize=(16, 9), ax=ax)\n ax.set_axisbelow(True)\n ax.grid(linestyle=':')\n plt.title('Trends in Movie Popularity for Different Genres over Time')\n plt.ylabel('Movies', fontsize=12)\n plt.xlabel('Year', fontsize=12)\n plt.legend(title='Genres')\n plt.savefig('output/genre_trend.png')\n plt.show()\n\n\ndef plot_genre_correlation(correlation):\n fig, ax = plt.subplots()\n correlation.plot(kind='bar', legend=False, figsize=(16, 9), ax=ax)\n ax.set_axisbelow(True)\n ax.grid(linestyle=':')\n plt.title('Correlation between Genre and Year')\n plt.ylabel('Correlation Coefficient', fontsize=12)\n plt.xlabel('Genres', fontsize=12)\n plt.xticks(rotation=35, ha='right')\n plt.savefig('output/genre_correlation.png')\n plt.show()\n\n\ndef find_optimal_parameter(method ,X_train, X_test, y_train, y_test, genres):\n if method == 'NB':\n pipeline = Pipeline([\n ('tfidf', TfidfVectorizer(stop_words='english')),\n ('clf', OneVsRestClassifier(MultinomialNB(fit_prior=True, class_prior=None))),\n ])\n if method == 'SVM':\n pipeline = Pipeline([\n ('tfidf', TfidfVectorizer(stop_words='english')),\n ('clf', OneVsRestClassifier(LinearSVC())),\n ])\n if method == 'LR':\n pipeline = Pipeline([\n ('tfidf', TfidfVectorizer(stop_words='english')),\n ('clf', OneVsRestClassifier(LogisticRegression(solver='sag'))),\n ])\n parameters = {\n 'tfidf__max_df': (0.25, 0.5, 0.75),\n 'tfidf__min_df': (0.005, 0.01, 0.015),\n 'tfidf__ngram_range': [(1, 1), (1, 2), (1, 3)],\n 'clf__estimator__C': [0.01, 0.1, 1],\n 'clf__estimator__class_weight': ['balanced', None],\n }\n\n # cross validate and select the best parameter configuration at the same time\n grid_search_tune = GridSearchCV(pipeline, parameters, cv=3, n_jobs=2, verbose=3)\n grid_search_tune.fit(X_train, y_train)\n\n best_clf = grid_search_tune.best_estimator_\n predictions = best_clf.predict(X_test)\n\n print(classification_report(y_test, predictions, target_names=genres))\n print()\n print(\"Best parameters:\")\n print(grid_search_tune.best_estimator_.steps)\n print()\n\n\ndef print_input_prediction(mlb, X_test, predictions):\n target_names = mlb.inverse_transform(predictions)\n for item, labels in zip(X_test, target_names):\n print('{0}... => {1}\\n'.format(item[0:40], ', '.join(labels)))\n\n\ndef main():\n omdb = pd.read_json('data/omdb-data.json.gz', orient='record', lines=True, encoding='utf-8')\n wikidata = pd.read_json('data/wikidata-movies.json.gz', orient='record', lines=True, encoding='utf-8')\n \n omdb = parse_ombd(omdb)\n genres = parse_genre(omdb)\n\n # index all labels - pick n labels to be 1, all other are 0\n mlb = MultiLabelBinarizer()\n y = mlb.fit_transform(omdb['omdb_genres'])\n X = parse_plot(omdb)\n X_train, X_test, y_train, y_test = train_test_split(X, y)\n \n plot_genre_vs_occurrence(genres, y)\n plot_text_length_histogram(omdb)\n\n # find_optimal_parameter('NB' ,X_train, X_test, y_train, y_test, genres)\n # find_optimal_parameter('SVM' ,X_train, X_test, y_train, y_test, genres)\n # find_optimal_parameter('LR' ,X_train, X_test, y_train, y_test, genres)\n\n # get parameter values from tests above\n classifier = Pipeline(steps=[\n ('tfidf', TfidfVectorizer(stop_words='english', max_df=0.25, min_df=0.005, ngram_range=(1, 1))),\n ('clf', OneVsRestClassifier(LinearSVC())),\n ])\n\n classifier.fit(X_train, y_train)\n predictions = classifier.predict(X_test)\n\n # print_input_prediction(mlb, X_test, predictions)\n print('==========================================================================')\n print('Summary of Prediction Accuracy')\n print('==========================================================================')\n print(classification_report(y_test, predictions, target_names=genres))\n print('The warning means that there is no F-score to calculate for the specified\\n'\n 'labels, so the F-score for them are considered to be 0.0. Since we wanted\\n'\n 'an average of the score, we must take into account that the score of 0 was\\n'\n 'included in the calculation; hence scikit-learn displays the warning.\\n')\n print('The reason for the missing values is that some labels in y_test (truth) do\\n'\n 'not appear in predictions. In other words, the labels are never predicted.')\n print('--------------------------------------------------------------------------\\n')\n\n wikidata = parse_wikidata(wikidata)\n genre_trend = pd.merge(omdb, wikidata, on='imdb_id')\n # https://stackoverflow.com/questions/42012152/unstack-a-pandas-column-containing-lists-into-multiple-rows\n # explode list of column to rows\n genre_trend = pd.DataFrame({\n 'genre': np.concatenate(genre_trend['omdb_genres']),\n 'year': np.repeat(genre_trend['year'], genre_trend['omdb_genres'].str.len()),\n })\n top_ten_genres = genre_trend.groupby('genre')['year'].count().reset_index(name='count')\n top_ten_genres = top_ten_genres.sort_values('count', ascending=False).reset_index()\n top_ten_genres = top_ten_genres['genre'].tolist()[:10]\n\n # https://stackoverflow.com/questions/47998025/python-line-plot-for-values-grouped-by-multiple-columns\n genre_trend = genre_trend.groupby(['year', 'genre'])['genre'].count()\n genre_trend = genre_trend.unstack()\n genre_trend = genre_trend[top_ten_genres]\n plot_genre_trend(genre_trend)\n\n # https://stackoverflow.com/questions/34896455/how-to-do-pearson-correlation-of-selected-columns-of-a-pandas-data-frame/34896835\n # correlate a column with multiple columns\n print('==========================================================================')\n print('Correlation between Genre and Year')\n print('==========================================================================')\n genre_trend['year'] = genre_trend.index\n corr = genre_trend[genre_trend.columns[0:]].corr()['year'][:-1]\n plot_genre_correlation(corr)\n print(corr)\n print('--------------------------------------------------------------------------')\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"kent-lee/natural-language-processing","sub_path":"movies_analysis.py","file_name":"movies_analysis.py","file_ext":"py","file_size_in_byte":9043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70927966152","text":"def Zeros(n):\n\t'''\n\tA function that returns the number of trailing zeros after computing the factorial of it's parameter\n\n\tParameter: n: int, number to calculate the number of trailing zeros in it's factorial.\n\n\tReturns: number of trailiing zeros.\n\n\t@author: Babatunde Koiki\n\tCreated on: 06-05-2020 \n\t'''\n\tdef fact(y):\n\t\tf = 1\n\t\tfor _ in range(y, 0, -1):\n\t\t\tf *= _\n\t\treturn str(f)[::-1] \n\tcount = 0\n\tfor i in fact(n):\n\t\tif i != '0':\n\t\t\treturn count\n\t\telse: count +=1\n\nprint(Zeros(6))","repo_name":"Babatunde13/30daysofcode","sub_path":"Back End/Beginner/DAY6.PY","file_name":"DAY6.PY","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"752775695","text":"# coding=utf-8\nfrom PyQt6 import QtWidgets, QtCore\nfrom PyQt6.QtCore import QFile, QTextStream\nfrom PyQt6.QtWidgets import QApplication\n\nfrom warframeAlert.services.optionHandlerService import OptionsHandler\nfrom warframeAlert.services.translationService import translate\nfrom warframeAlert.utils.commonUtils import int_to_bool, bool_to_int\n\nLANGUAGE_TYPE = {\n 0: \"it\",\n 1: \"en\"\n}\n\nTHEME = {\n 0: \"standard\",\n 1: \"light\",\n 2: \"dark\"\n}\n\n\nclass ConfigOtherWidget():\n ConfigOtherWidget = None\n\n def __init__(self) -> None:\n self.ConfigOtherWidget = QtWidgets.QWidget()\n\n self.gridOtherConfig = QtWidgets.QGridLayout(self.ConfigOtherWidget)\n\n self.ConfifOtherLabel = QtWidgets.QLabel(translate(\"configOtherWidget\", \"extraOptions\"))\n self.DebugConfigLabel = QtWidgets.QLabel(translate(\"configOtherWidget\", \"debugOptions\"))\n self.WarningConfigLabel = QtWidgets.QLabel(translate(\"configOtherWidget\", \"alertPt1\") + \"\\n\" +\n translate(\"configOtherWidget\", \"alertPt2\"))\n\n self.DebugConfig = QtWidgets.QCheckBox(\"Debug\")\n self.InitConfig = QtWidgets.QCheckBox(translate(\"configOtherWidget\", \"firstInstallation\"))\n self.TrayConfig = QtWidgets.QCheckBox(translate(\"configOtherWidget\", \"minimizeOnClose\"))\n\n self.ComboBoxLangageLabel = QtWidgets.QLabel(translate(\"configOtherWidget\", \"language\"))\n self.ComboBoxLangageLabel.setToolTip(translate(\"configOtherWidget\", \"languageTooltip\"))\n\n self.ComboBoxLangage = QtWidgets.QComboBox(self.ConfigOtherWidget)\n\n self.ComboBoxLangage.addItem(translate(\"configOtherWidget\", \"it\"))\n self.ComboBoxLangage.addItem(translate(\"configOtherWidget\", \"en\"))\n\n self.ComboBoxLangage.setCurrentIndex(find_language_index())\n self.ComboBoxLangage.currentIndexChanged.connect(update_language_app)\n\n self.ComboBoxThemeLabel = QtWidgets.QLabel(translate(\"configOtherWidget\", \"theme\"))\n self.ComboBoxThemeLabel.setToolTip(translate(\"configOtherWidget\", \"themeTooltip\"))\n\n self.ComboBoxTheme = QtWidgets.QComboBox(self.ConfigOtherWidget)\n\n self.ComboBoxTheme.addItem(\"Standard\")\n self.ComboBoxTheme.addItem(\"Light\")\n self.ComboBoxTheme.addItem(\"Dark\")\n\n current_theme = OptionsHandler.get_option(\"Theme\")\n self.ComboBoxTheme.setCurrentIndex(current_theme)\n self.ComboBoxTheme.currentIndexChanged.connect(apply_stylesheet)\n\n self.gridOtherConfig.addWidget(self.ConfifOtherLabel, 0, 0)\n self.gridOtherConfig.addWidget(self.WarningConfigLabel, 1, 0, 1, 2)\n self.gridOtherConfig.addWidget(self.DebugConfigLabel, 2, 0)\n self.gridOtherConfig.addWidget(self.DebugConfig, 3, 0)\n self.gridOtherConfig.addWidget(self.InitConfig, 3, 1)\n self.gridOtherConfig.addWidget(self.TrayConfig, 4, 0, 1, 2)\n self.gridOtherConfig.addWidget(self.ComboBoxLangageLabel, 5, 0)\n self.gridOtherConfig.addWidget(self.ComboBoxThemeLabel, 5, 1)\n self.gridOtherConfig.addWidget(self.ComboBoxLangage, 6, 0)\n self.gridOtherConfig.addWidget(self.ComboBoxTheme, 6, 1)\n\n self.ConfigOtherWidget.setLayout(self.gridOtherConfig)\n self.gridOtherConfig.setAlignment(QtCore.Qt.AlignmentFlag.AlignTop)\n\n self.DebugConfig.setChecked(int_to_bool(OptionsHandler.get_option(\"Debug\")))\n self.InitConfig.setChecked(int_to_bool(OptionsHandler.get_option(\"FirstInit\")))\n self.TrayConfig.setChecked(int_to_bool(OptionsHandler.get_option(\"TrayIcon\")))\n\n self.DebugConfig.clicked.connect(\n lambda: OptionsHandler.set_option(\"Debug\", bool_to_int(self.DebugConfig.isChecked())))\n self.InitConfig.clicked.connect(\n lambda: OptionsHandler.set_option(\"FirstInit\", bool_to_int(self.InitConfig.isChecked())))\n self.TrayConfig.clicked.connect(\n lambda: OptionsHandler.set_option(\"TrayIcon\", bool_to_int(self.TrayConfig.isChecked())))\n\n apply_stylesheet(current_theme)\n\n def get_widget(self) -> QtWidgets.QWidget:\n return self.ConfigOtherWidget\n\n\ndef find_language_index() -> int:\n language = OptionsHandler.get_option(\"Language\", str)\n for language_type in LANGUAGE_TYPE:\n if (LANGUAGE_TYPE[language_type] == language):\n return language_type\n\n\ndef update_language_app(language_index: int) -> None:\n OptionsHandler.set_option(\"Language\", LANGUAGE_TYPE[language_index])\n\n\n# https://stackoverflow.com/questions/48256772/dark-theme-for-qt-widgets\ndef apply_stylesheet(index: int) -> None:\n OptionsHandler.set_option(\"Theme\", index)\n if (index != 0):\n path = \"assets/theme/\" + THEME[index] + \"/stylesheet.qss\"\n app = QApplication.instance()\n file = QFile(path)\n file.open(QFile.OpenModeFlag.ReadOnly | QFile.OpenModeFlag.Text)\n stream = QTextStream(file)\n app.setStyleSheet(stream.readAll())\n","repo_name":"DPPaolo/WarframeAlert","sub_path":"warframeAlert/components/widget/ConfigOtherWidget.py","file_name":"ConfigOtherWidget.py","file_ext":"py","file_size_in_byte":4922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"25544399430","text":"def factorial(n):\n if n == 1:\n return n\n else:\n return n * factorial(n-1)\n\ndef rightZeros(n):\n numberString = str(factorial(n))\n numberZeros = 0\n for digit in numberString:\n if digit == \"0\":\n numberZeros += 1\n return numberZeros\n\n\n","repo_name":"GinnyN/Lemontech-Test","sub_path":"Programacion/NFactorial.py","file_name":"NFactorial.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19765717033","text":"# result=[]\n# def rec(n,result):\n# if n[0]==\"c\":\n# return \"\"\n# else:\n# result.append(n[0])\n# return rec(n[1:],result)\n# print(rec([\"a\",\"b\",\"c\",\"d\",\"e\"],result))\n# print(result)\n\n\ndef subarr(arr,i,j):\n if len(arr)==j:\n return \"\"\n elif i>j:\n return subarr(arr,0,j+1)\n else:\n blank.append(arr[i:j+1])\n return subarr(arr,i+1,j)\nblank=[]\nsubarr([1,4,6,24,5],0,0)\nprint(blank)","repo_name":"Ishita9024/NatWest_PreBootCamp","sub_path":"DSA_PRAC/Recursion/namePrint.py","file_name":"namePrint.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"20967999171","text":"import feedparser as fp\nimport json\nimport newspaper\nfrom newspaper import Article\nfrom time import mktime\nfrom datetime import datetime\n\n# Set the limit for number of articles to download\nLIMIT = 4000\nlabel = \"FAKE\"\n\nfile = open('fake_real_news.csv', 'a', encoding='utf-8')\n\ndata = {}\ndata['newspapers'] = {}\n\nLINKS = ['https://www.thedailymash.co.uk/', 'http://www.thecivilian.co.nz/', 'https://www.thespoof.com/',\n 'https://www.thebeaverton.com/', 'https://www.newyorker.com/humor/borowitz-report', 'https://www.theonion.com/' ]\n\nreallinks = ['http://edition.cnn.com/', 'http://www.bbc.com/', 'https://www.theguardian.com/international', \n 'http://www.foxnews.com/', 'http://www.nbcnews.com/', 'https://www.washingtonpost.com/' ]\n\nLINKS = reallinks\nlabel = \"REAL\"\n\ncount = 1\nid_ = 0\n\n# Iterate through each news company\nfor link in LINKS:\n\n paper = newspaper.build(link, memoize_articles=False)\n\n noneTypeCount = 0\n for content in paper.articles:\n if count > LIMIT:\n break\n try:\n content.download()\n content.parse()\n except Exception as e:\n print(e)\n print(\"continuing...\")\n continue\n # Again, for consistency, if there is no found publish date the article will be skipped.\n # After 10 downloaded articles from the same newspaper without publish date, the company will be skipped.\n if content.publish_date is None:\n print(count, \" Article has date of type None...\")\n noneTypeCount = noneTypeCount + 1\n if noneTypeCount > 10:\n print(\"Too many noneType dates, aborting...\")\n noneTypeCount = 0\n break\n count = count + 1\n continue\n \n body = content.text\n body = body.replace(\"\\n\", \"\")\n\n string = str(id_) + ';' + content.title + ';\"' + content.text + '\";' + label + \"\\n\"\n id_ += 1\n file.write(string)\n\nfile.close()\n","repo_name":"noninoULB/FAKE-NEWS","sub_path":"NewsScraper.py","file_name":"NewsScraper.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"20938804599","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\ngit_label.py\n---------------------------------------------------------------------------------------\nAuthor: Trieu Phat Luu\nContact: tpluu2207@gmail.com\nCreated on: 06/17/2020 03:36:18\n\"\"\"\n\n#%%\n# =====================================IMPORT PACKAGES=================================\n# Standard Packages\nimport argparse\nimport os\n\n# FileIO Packages\nimport json\n\n# Web pages and URL Related\nimport requests\n\n# GUI and User Interfaces Packages\nimport pyautogui\n\n# Utilities\nimport time\n\n\n# =====================================DEFINES=================================\n\nGIT_AUTH = os.environ.get(\"GIT_AUTH\")\n\nscript_dir = os.path.abspath(os.path.dirname(__file__))\n\nREPO = os.path.basename(os.path.dirname(script_dir))\n\n# =====================================START=========================================\n\n# Web pages and URL Related\n# ======================================================================================\n# MAIN\n\n\ndef load_json(json_filepath):\n output = None\n if not os.path.isfile(json_filepath):\n print(f\"{json_filepath} is not a file\")\n return output\n\n print(f\"START-Loading json file: {json_filepath}\")\n start_time = time.time()\n with open(json_filepath, \"r\") as fid:\n output = json.load(fid)\n\n elapsed_time = time.time() - start_time\n hours, rem = divmod(elapsed_time, 3600)\n minutes, seconds = divmod(rem, 60)\n msg = \"DONE-\" \"Elapsed Time: {hours:0>2}:{mins:0>2}:{secs:0>2}\\t\".format(\n hours=int(hours), mins=int(minutes), secs=int(seconds),\n )\n print(msg)\n return output\n\n\ndef save_json(json_data, json_filepath):\n with open(json_filepath, \"w\") as fid:\n json.dump(json_data, fid)\n\n\ndef parse_issue_config(issue_filepath):\n issue_config = load_json(issue_filepath)\n body_contents = issue_config[\"body\"]\n body_str = \"\"\n for l in body_contents:\n body_str = body_str + f\"{l}\\r\\n\"\n issue_config[\"body\"] = body_str\n return issue_config\n\n\ndef get_args_parser():\n parser = argparse.ArgumentParser(\n prog=os.path.basename(os.path.abspath(__file__)),\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"Additional Info\",\n )\n parser.add_argument(\n \"--verbose\", action=\"store_true\", required=False, help=\"verbose\"\n )\n parser.add_argument(\n \"-f\",\n type=str,\n default=\"git_issue_template.json\",\n help=\"input issue config filepath\",\n )\n return parser\n\n\ndef get_latest_issue_id():\n issue_id = None\n url = f\"https://api.github.com/repos/luutp/{REPO}/issues\"\n token = {\n \"Authorization\": f\"token {GIT_AUTH}\",\n \"Accept\": \"application/vnd.github.inertia-preview+json\",\n }\n data_dict = {\n \"sort\": \"created\",\n \"per_page\": 2,\n }\n try:\n r = requests.get(url, data=json.dumps(data_dict), headers=token)\n print(f\"Status code: {r.status_code}\")\n latest_issue = r.json()[0]\n issue_id = latest_issue[\"id\"]\n except Exception as e:\n print(e)\n return issue_id\n\n\ndef list_project_columns(project_id):\n url = f\"https://api.github.com/projects/{project_id}/columns\"\n # url = f\"https://api.github.com/luutp/projects\"\n token = {\n \"Authorization\": f\"token {GIT_AUTH}\",\n \"Accept\": \"application/vnd.github.inertia-preview+json\",\n }\n outputs = None\n try:\n r = requests.get(url, headers=token, timeout=10)\n if r.status_code == 304:\n print(f\"FAILED. Status: {r.status_code} Not Modified\")\n print(f\"{r.text}\")\n elif r.status_code == 401:\n print(f\"FAILED. Status: {r.status_code} Unauthorized\")\n print(f\"{r.text}\")\n elif r.status_code == 403:\n print(f\"FAILED. Status: {r.status_code} Forbidden\")\n print(f\"{r.text}\")\n elif r.status_code == 200:\n outputs = r.json()\n print(f\"Status code: {r.status_code}\")\n print(\"SUCCESSFUL!\")\n except Exception as e:\n print(e)\n return outputs\n\n\ndef create_project_card(column_id, issue_id):\n url = f\"https://api.github.com/projects/columns/{column_id}/cards\"\n token = {\n \"Authorization\": f\"token {GIT_AUTH}\",\n \"Accept\": \"application/vnd.github.inertia-preview+json\",\n }\n data_dict = {\"content_id\": issue_id, \"content_type\": \"Issue\"}\n r = requests.post(url, data=json.dumps(data_dict), headers=token)\n print(f\"Status code: {r.status_code}\")\n print(r.text)\n print(\"DONE\")\n\n\ndef main(args):\n column_id = 15043895\n # https://github.com/luutp/printstore/projects/1#column-15043895\n # Parse input arguments\n config_filepath = args.f\n\n url = f\"https://api.github.com/repos/luutp/{REPO}/issues\"\n token = {\"Authorization\": f\"token {GIT_AUTH}\"}\n\n print(\"Create github issue\")\n config_dict = parse_issue_config(config_filepath)\n print(config_dict)\n\n r = requests.post(url, data=json.dumps(config_dict), headers=token, timeout=10)\n print(f\"Status code: {r.status_code}\")\n\n # Remove file\n os.remove(config_filepath)\n # Close IDE\n pyautogui.hotkey(\"ctrl\", \"w\", interval=0.15)\n # Get latest issue ID\n issue_id = get_latest_issue_id()\n if issue_id is not None:\n create_project_card(column_id, issue_id)\n\n\n# =====================================DEBUG===================================\n\nif __name__ == \"__main__\":\n args = get_args_parser().parse_args()\n main(args)\n","repo_name":"luutp/cookiecutter_pypackage","sub_path":".vscode/git_create_issue.py","file_name":"git_create_issue.py","file_ext":"py","file_size_in_byte":5469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"28908411027","text":"import requests\nimport unittest\nimport allure\nimport os\n\nfrom dotenv import load_dotenv\n\nfrom authentication.auth_token import BearerAuth\n\n\nclass AirportApiTest(unittest.TestCase):\n # load env variables\n load_dotenv()\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Runs before each test case\"\"\"\n cls.BASE_URL = os.environ.get(\"BASE_URL\")\n cls.AIRPORT_API_KEY = os.environ.get(\"API_TOKEN\")\n\n @allure.feature('Get Airports')\n def test_get_airports(self):\n \"\"\"Returns all airports, limited to 30 per page\"\"\"\n url = f'{self.BASE_URL}/airports'\n response = requests.get(url)\n response_body = response.json()\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.headers[\"Content-Type\"], \"application/json; charset=utf-8\")\n self.assertEqual(len(response_body[\"data\"]), 30)\n\n @allure.feature('Calculate distance between airports')\n def test_calculate_distance_between_airports(self):\n url = f'{self.BASE_URL}/airports/distance'\n payload = {\"from\": \"KIX\", \"to\": \"SFO\"}\n\n response = requests.post(url, data=payload)\n response_body = response.json()\n\n self.assertEqual(response.status_code, 200)\n\n attributes = response_body[\"data\"][\"attributes\"]\n\n # assert attributes.keys() >= {'kilometers', 'miles', 'nautical_miles'}\n self.assertTrue(all(key in attributes for key in ('kilometers', 'miles', 'nautical_miles')))\n self.assertEqual(attributes[\"kilometers\"], 8692.066508240026)\n self.assertEqual(attributes[\"miles\"], 5397.239853492001)\n self.assertEqual(attributes[\"nautical_miles\"], 4690.070954910584)\n\n @allure.feature('Endpoint which requires authentication')\n def test_requires_authentication(self):\n url = f'{self.BASE_URL}/favorites'\n payload = {\"airport_id\": 'JFK', \"note\": \"My usual layover when visiting family\"}\n\n response = requests.post(url, data=payload)\n\n self.assertEqual(response.status_code, 401)\n\n @allure.feature('User save and delete favority airports')\n def test_allows_user_save_and_delete_their_favorite_airports(self):\n # Check that a user can create a favorite airport.\n url = f'{self.BASE_URL}/favorites'\n payload = {\"airport_id\": \"JFK\", \"note\": \"My usual layover when visiting family\"}\n\n response = requests.post(url, data=payload, auth=BearerAuth(self.AIRPORT_API_KEY))\n response_body = response.json()\n attributes = response_body[\"data\"][\"attributes\"]\n\n self.assertEqual(response.status_code, 201)\n self.assertEqual(attributes[\"airport\"][\"name\"], 'John F Kennedy International Airport')\n self.assertEqual(attributes[\"note\"], 'My usual layover when visiting family')\n\n favorite_id = response_body[\"data\"][\"id\"]\n\n # Check that a user can update the note of the created favorite.\n payload = {\"note\": 'My usual layover when visiting family and friends'}\n url = f'{self.BASE_URL}/favorites/{favorite_id}'\n\n response = requests.put(url, data=payload, auth=BearerAuth(self.AIRPORT_API_KEY))\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(attributes[\"note\"], 'My usual layover when visiting family')\n\n # Check that a user can delete the created favorite.\n response = requests.delete(url, data=payload, auth=BearerAuth(self.AIRPORT_API_KEY))\n self.assertEqual(response.status_code, 204)\n\n # Verify that the record was deleted.\n response = requests.get(url, data=payload, auth=BearerAuth(self.AIRPORT_API_KEY))\n self.assertEqual(response.status_code, 404)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"robinn96/Python-Api-Request","sub_path":"tests/airport_test.py","file_name":"airport_test.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18501661904","text":"import match_sim\nimport match_state\nimport team\nimport player\nimport stats\nimport yaml\nfrom os import listdir\nfrom os.path import isfile, join\n\ndef adjust_batting_stats(pl):\n stat = pl.batting_stats\n stat.matches_played -= 1\n if pl.balls_played > 0:\n stat.batt_innings -= 1\n stat.not_outs -= pl.is_batting\n stat.runs_scored -= pl.runs_scored\n if stat.batt_innings-stat.not_outs !=0:\n stat.average = round(stat.runs_scored/(stat.batt_innings-stat.not_outs),2)\n else:\n stat.average = 0\n stat.balls_faced -= pl.balls_played\n if pl.runs_scored >= 100:\n stat.centuries -= 1\n if pl.runs_scored >= 50:\n stat.fifties -= 1\n stat.fours -= pl.num_fours\n stat.sixes -= pl.num_sixes\n if pl.runs_scored == 0 and pl.balls_played > 0:\n stat.zeros += 1\n if pl.runs_scored == stat.highest_score and pl.balls_played > 0:\n stat.highest_score = -1\n if stat.balls_faced > 0:\n stat.strike_rate = round((stat.runs_scored/stat.balls_faced)* 100,2)\n else:\n stat.strike_rate = 0\n\ndef adjust_bowling_stats(pl):\n stat = pl.bowling_stats\n stat.matches_played -= 1\n if pl.balls_bowled > 0:\n stat.bowl_innings -= 1\n #print pl.name,stat.balls_bowled,pl.balls_bowled\n stat.balls_bowled = int(stat.balls_bowled) - pl.balls_bowled\n #print pl.name,stat.balls_bowled,pl.balls_bowled\n stat.calculate_overs_bowled()\n #print stat.overs_bowled,stat.balls_bowled\n stat.runs_conceded -= pl.runs_conceded\n stat.wickets_taken -= pl.wickets_taken\n if stat.wickets_taken != 0:\n stat.average = round(stat.runs_conceded/stat.wickets_taken,2)\n else:\n stat.average = 0\n if stat.balls_bowled != 0:\n i,d = divmod(stat.overs_bowled,1)\n stat.economy = round(stat.runs_conceded/(i + 100*d/6),2)\n else:\n stat.economy = 0\n if pl.wickets_taken == 4:\n stat.fourwi -= 1\n if pl.wickets_taken > 4:\n stat.fivewi -= 1\n if stat.wickets_taken > 0:\n stat.strike_rate = round(stat.balls_bowled/stat.wickets_taken,2)\n else:\n stat.strike_rate = 0\n\n\ndef adjust_player_stats(pl):\n adjust_batting_stats(pl)\n adjust_bowling_stats(pl)\n\ndef adjust_team_stats(team):\n for pl in team.player_list:\n adjust_player_stats(pl)\n\ndef adjust_match_stats(matchState):\n adjust_team_stats(matchState.team_a)\n adjust_team_stats(matchState.team_b)\n\ndef yaml_dump(filepath,data):\n filepath = '/home/shashank/intern_17/data/updated_player_stats/' + filepath\n with open(filepath,\"w\") as file_descriptor:\n yaml.dump(data,file_descriptor)\n\ndef write_to_yaml(f_name,state):\n team_a_name = state.team_a.name\n team_b_name = state.team_b.name\n data_yaml = {team_a_name:[{'batting averages':[]},{'bowling averages':[]}],team_b_name:[{'batting averages':[]},{'bowling averages':[]}]}\n\n team_a_bat_stats = data_yaml[team_a_name][0]['batting averages']\n team_b_bat_stats = data_yaml[team_b_name][0]['batting averages']\n team_a_bowl_stats = data_yaml[team_a_name][1]['bowling averages']\n team_b_bowl_stats = data_yaml[team_b_name][1]['bowling averages']\n\n for pl in state.team_a.player_list:\n team_a_bat_stats.append(bat_pl_dict(pl))\n team_a_bowl_stats.append(bowl_pl_dict(pl))\n\n for pl in state.team_b.player_list:\n team_b_bat_stats.append(bat_pl_dict(pl))\n team_b_bowl_stats.append(bowl_pl_dict(pl))\n\n yaml_dump(f_name,data_yaml)\n\n\ndef bat_pl_dict(pl):\n pl_dict = {}\n pl_dict['100'] = str(int(pl.batting_stats.centuries))\n pl_dict['4s'] = str(int(pl.batting_stats.fours))\n pl_dict['50'] = str(int(pl.batting_stats.fifties))\n pl_dict['6s'] = str(int(pl.batting_stats.sixes))\n pl_dict['Ave'] = str(pl.batting_stats.average)\n pl_dict['BF'] = str(int(pl.batting_stats.balls_faced))\n pl_dict['Inns'] = str(int(pl.batting_stats.batt_innings))\n pl_dict['Mat'] = str(int(pl.batting_stats.matches_played))\n pl_dict['NO'] = str(int(pl.batting_stats.not_outs))\n pl_dict['Player'] = pl.name\n pl_dict['Runs'] = str(int(pl.batting_stats.runs_scored))\n pl_dict['0'] = str(int(pl.batting_stats.zeros))\n pl_dict['HS'] = str(int(pl.batting_stats.highest_score))\n pl_dict['SR'] = str(pl.batting_stats.strike_rate)\n pl_dict['Span'] = pl.batting_stats.span\n return pl_dict\n\ndef bowl_pl_dict(pl):\n pl_dict = {}\n pl_dict['4'] = str(int(pl.bowling_stats.fourwi))\n pl_dict['5'] = str(int(pl.bowling_stats.fivewi))\n pl_dict['Ave'] = str(pl.bowling_stats.average)\n pl_dict['Econ'] = str(pl.bowling_stats.economy)\n pl_dict['Mat'] = str(int(pl.bowling_stats.matches_played))\n pl_dict['Inns'] = str(int(pl.bowling_stats.bowl_innings))\n pl_dict['Overs'] = str(pl.bowling_stats.overs_bowled)\n pl_dict['Player'] = pl.name\n pl_dict['Runs'] = str(int(pl.bowling_stats.runs_conceded))\n pl_dict['Wkts'] = str(int(pl.bowling_stats.wickets_taken))\n pl_dict['SR'] = str(pl.bowling_stats.strike_rate)\n pl_dict['Span'] = str(pl.bowling_stats.span)\n\n return pl_dict\n\ndef update_stats(name):\n bbb = match_sim.load_ball_by_ball_data(name)\n matchState = match_sim.initialize_match(bbb,name)\n match_sim.simulate_match(bbb,matchState)\n adjust_match_stats(matchState)\n write_to_yaml(name,matchState)\n\nif __name__ == '__main__':\n mypath = '/home/shashank/intern_17/data/player_stats/335982.yaml'\n '''onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]\n for i in range (619,len(onlyfiles)):\n print 'Updating : ',i,onlyfiles[i]'''\n update_stats('335982.yaml'.replace('~',''))\n","repo_name":"ssivalenka/Dynamic-Winner-Prediction-2017","sub_path":"scripts/adjust_stats.py","file_name":"adjust_stats.py","file_ext":"py","file_size_in_byte":5590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"16608628205","text":"class Solution:\n def romanToInt(self, s: str) -> int:\n dict_value = {\"I\" : 1, \"V\" : 5, \"X\" : 10, \"L\" : 50, \"C\" : 100, \"D\" : 500, \"M\" : 1000, \"IV\" : 4, \"IX\" : 9, \"XL\": 40, \"XC\" : 90, \"CD\":400, \"CM\":900}\n output_sum = 0\n # defining the output_sum as 0\n if len(s) >= 1 and len(s) <=15:\n if \"IV\" in s:\n IV_count = s.count(\"IV\")\n output_sum += (IV_count * dict_value[\"IV\"])\n s = s.replace(\"IV\", \"\")\n if \"IX\" in s:\n IX_count = s.count(\"IX\")\n output_sum += (IX_count * dict_value[\"IX\"])\n s = s.replace(\"IX\", \"\")\n if \"XL\" in s:\n XL_count = s.count(\"XL\")\n output_sum += (XL_count * dict_value[\"XL\"])\n s = s.replace(\"XL\", \"\")\n if \"XC\" in s:\n XC_count = s.count(\"XC\")\n output_sum += (XC_count * dict_value[\"XC\"])\n s = s.replace(\"XC\", \"\")\n if \"CD\" in s:\n CD_count = s.count(\"CD\")\n output_sum += (CD_count * dict_value[\"CD\"])\n s = s.replace(\"CD\", \"\")\n if \"CM\" in s:\n CM_count = s.count(\"CM\")\n output_sum += (CM_count * dict_value[\"CM\"])\n s = s.replace(\"CM\", \"\")\n for i in s:\n if i in dict_value and i in ['I', 'V', 'X', 'L', 'C', 'D', 'M']:\n output_sum += dict_value[i]\n if output_sum >= 1 and output_sum <= 3999:\n return output_sum\n ","repo_name":"Praveensridhar14/LeetCode-Solutions","sub_path":"Easy/RomanToInteger.py","file_name":"RomanToInteger.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"72876032712","text":"import orbital_elements.convert as convert\nfrom orbital_elements.coe.keplerian_solution import KeplerianSolution as KepSol\n\n__author__ = \"Nathan I. Budd\"\n__email__ = \"nibudd@gmail.com\"\n__copyright__ = \"Copyright 2017, LASR Lab\"\n__license__ = \"MIT\"\n__version__ = \"0.1\"\n__status__ = \"Production\"\n__date__ = \"02 Mar 2017\"\n\n\nclass KeplerianSolution(object):\n \"\"\"Keplerian solution for position-velocity elements.\n\n Attributes:\n X0: ndarray\n (1, 6) array of initial states ordered as (rx, ry, rz, vx, vy, vz),\n where\n rx = position x-component\n ry = position y-component\n rz = position z-component\n vx = velocity x-component\n vy = velocity y-component\n vz = velocity z-component\n mu: float, optional\n Standard Gravitational Parameter. Defaults to 1.0, the standard\n value in canonical units.\n \"\"\"\n\n def __init__(self, X0, mu=1.0):\n self.X0 = X0\n self.mu = mu\n\n def __call__(self, T):\n \"\"\"Calculate position-velocity solution.\n\n Args:\n T: ndarray\n (m, 1) array of times.\n\n Returns:\n X: ndarray\n (m, 6) array of states.\n \"\"\"\n X_coe = KepSol(convert.coe_rv(self.X0), mu=self.mu)(T)\n return convert.rv_coe(X_coe)\n","repo_name":"lasr/orbital_elements","sub_path":"rv/keplerian_solution.py","file_name":"keplerian_solution.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19440418108","text":"import rclpy\nfrom rclpy.node import Node\n\nfrom std_msgs.msg import String\n\nfrom sensor_msgs.msg import JointState\nimport math\nfrom geometry_msgs.msg import PoseStamped\nfrom geometry_msgs.msg import Pose\nfrom geometry_msgs.msg import Point\nimport numpy as np\nfrom math import cos, sin\nfrom geometry_msgs.msg import Quaternion\n\nclass MinimalSubscriber(Node):\n\n def __init__(self):\n super().__init__('ForwardKin')\n self.subscription = self.create_subscription(JointState,'/joint_states',self.listener_callback,10)\n self.subscription # prevent unused variable warning\n\n\n self.publisher_ = self.create_publisher(PoseStamped, 'curent_position', 10)\n\n def listener_callback(self, msg: JointState):\n t1, t2, t3, t4, t5 = msg.position\n a = self.calculatePosition(t1, t2, t3, t4,t5, 0.138 ,0.135, 0.147, 0.05, 0.0565)\n self.timer_callback(a)\n\n def timer_callback(self, pos):\n x, y, z, q = pos\n msg = PoseStamped()\n pose = Pose()\n position = Point()\n position.x = x\n position.y = y\n position.z = z\n pose.orientation= q\n pose.position = position\n msg.pose = pose\n msg.header.frame_id = \"base\"\n self.publisher_.publish(msg)\n\n def calculatePosition(self, theta1, theta2, theta3, theta4, theta5, l1, l2, l3, l4, l5):\n x = (l2*sin(theta2)+l3*cos( theta2+theta3) +l4*cos(theta2+theta3+theta4) + l5*cos(theta2+theta3+theta4)) * cos(theta1)\n y = (l2*sin(theta2)+l3*cos( theta2+theta3) +l4*cos(theta2+theta3+theta4) + l5*cos(theta2+theta3+theta4)) * sin(theta1)\n z = (l2*cos(theta2)-l3*sin( theta2+theta3) -l4*sin(theta2+theta3+theta4) - l5*sin(theta2+theta3+theta4)) + l1\n rz = theta1\n ry = theta2 + theta3 + theta4\n qz_global = self.euler_to_quaternion(0, 0, theta1)\n qy = self.euler_to_quaternion(0, theta2 + theta3 + theta4, 0)\n qz_local = self.euler_to_quaternion(0, 0, -theta5)\n q_local = self.multiply_quaternions(qy, qz_local)\n return x,y,z, self.multiply_quaternions(qz_global, qy)\n \n def euler_to_quaternion(self, roll, pitch, yaw):\n qx = sin(roll/2) * cos(pitch/2) * cos(yaw/2) - cos(roll/2) * sin(pitch/2) * sin(yaw/2)\n qy = cos(roll/2) * sin(pitch/2) * cos(yaw/2) + sin(roll/2) * cos(pitch/2) * sin(yaw/2)\n qz = cos(roll/2) * cos(pitch/2) * sin(yaw/2) - sin(roll/2) * sin(pitch/2) * cos(yaw/2)\n qw = cos(roll/2) * cos(pitch/2) * cos(yaw/2) + sin(roll/2) * sin(pitch/2) * sin(yaw/2)\n return Quaternion(x=qx, y=qy, z=qz, w=qw)\n \n def multiply_quaternions(self, q1, q2):\n w = q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z\n x = q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y\n y = q1.w * q2.y - q1.x * q2.y + q1.y * q2.w + q1.z * q2.x\n z = q1.w * q2.z + q1.x * q2.z - q1.y * q2.x + q1.z * q2.w\n mag = x*x + y*y + z*z + w*w\n mag = math.sqrt(mag)\n w /= mag\n x /= mag\n y /= mag\n z /= mag\n return Quaternion(x=x, y=y, z=z, w=w)\n\n\ndef main(args=None):\n rclpy.init(args=args)\n\n minimal_publisher = MinimalSubscriber()\n\n rclpy.spin(minimal_publisher)\n\n # Destroy the node explicitly\n # (optional - otherwise it will be done automatically\n # when the garbage collector destroys the node object)\n minimal_publisher.destroy_node()\n rclpy.shutdown()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Padamadam/ROS2","sub_path":"lab6/lab6/some_node.py","file_name":"some_node.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"37580040468","text":"# def solution(topping):\n# # 동일한 가짓수의 토핑 -> 절반을 나누는 경우의 수\n# answer = 0\n# for i in range(1, len(topping)):\n# cheolsu, brother = list(set(topping[:i])), list(set(topping[i:]))\n# if len(cheolsu) == len(brother):\n# answer += 1 \n# return answer \n\n# from collections import Counter\n\n# def solution(topping):\n# dict = Counter(topping)\n# set_dict = set()\n# answer = 0\n\n# for i in topping:\n# dict[i] -= 1\n# set_dict.add(i) # 동생 토핑 추가\n# if dict[i] == 0: # 토핑 다 주고 나면 철수는 토핑 없어짐\n# dict.pop(i)\n# if len(dict) == len(set_dict): # 토핑 가짓수 같을 때마다 answer +=1\n# answer += 1\n# return answer\n\n\ndef solution(topping):\n cheolsu = {}\n brother = set()\n answer = 0\n\n for t in topping:\n if t in cheolsu:\n cheolsu[t] += 1\n else:\n cheolsu[t] = 1\n \n for t in topping:\n if cheolsu[t]:\n cheolsu[t] -= 1\n brother.add(t)\n if cheolsu[t] == 0:\n cheolsu.pop(t)\n if len(cheolsu) == len(brother):\n answer += 1\n return answer \n \nprint(solution([1, 2, 1, 3, 1, 4, 1, 2]))\n\n\n\n","repo_name":"yezyvibe/Algorithm_PS","sub_path":"Programmers/p_롤케이크자르기.py","file_name":"p_롤케이크자르기.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18499520669","text":"from flask import Flask, request\nfrom config import os, TOKEN, DEBUG, WEBHOOK_URL\nfrom waitress import serve\nfrom main.teleg_bot import updater, bot, Update\nfrom main.teleg_bot_wbhk import dispatcher, setup_for_Flask\nfrom handlers.deleter import delete\n\n\napp = Flask(__name__)\n\n\n@app.route('/' + TOKEN, methods=['POST', 'GET'])\ndef getMessage():\n update = Update.de_json(\n request.get_json(force=True), bot)\n dispatcher.process_update(update)\n delete()\n return \"running\", 200\n\n\n@app.route(\"/\")\ndef reset_webhook():\n updater.bot.delete_webhook()\n updater.bot.set_webhook(url=WEBHOOK_URL + TOKEN)\n return \"Running\", 200\n\n\n# All false to use flask builting\n# Set use_polling true for polling\nuse_polling = True\n# Set only use_builtin_server true for python telegram bot's builtin test server\nuse_builtin_server = False\n# Set only use_waitress_server true for production server\nuse_waitress_server = False\nif __name__ == \"__main__\":\n\n if use_polling:\n # updater.bot.delete_webhook()\n updater.bot.delete_webhook()\n updater.start_polling()\n print(\"*****************Start polling..*****************\")\n\n elif use_builtin_server:\n updater.bot.delete_webhook()\n updater.start_webhook(listen=\"0.0.0.0\",\n port=80,\n webhook_url=WEBHOOK_URL + TOKEN,\n )\n\n print(\"*****************Using Pyteleg builtin server*****************\")\n updater.idle()\n elif not use_waitress_server:\n # for dev\n setup_for_Flask()\n print(\"*****************Using Flask builtin server*****************\")\n updater.bot.delete_webhook()\n updater.bot.set_webhook(url=WEBHOOK_URL + TOKEN)\n app.run(debug=DEBUG, host=\"0.0.0.0\",\n port=int(os.environ.get('PORT', 80)), threaded=True)\n else:\n # for production\n setup_for_Flask()\n print(\"*****************Using Waitress production server*****************\")\n updater.bot.delete_webhook()\n updater.bot.set_webhook(url=WEBHOOK_URL + TOKEN)\n serve(app, host='0.0.0.0', port=int(\n os.environ.get('PORT', 80)))\n","repo_name":"Radi-dev/Telegram-Insta-engagement-bot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"21794111617","text":"\nfrom collections import Counter\n\ndef word_frequecy(words : str) : \n\n counter = dict()\n\n for word in words : \n if word in counter.keys() : \n counter[word] += 1\n else : \n counter[word] = 1 \n\n for key, value in counter.items() : \n if value > 1 : \n print(\"{} {}\".format(key, value))\n else : \n print(key)\n\n\nif __name__ == '__main__' : \n word_frequecy([\"code\", \"while\", \"code\"])","repo_name":"AnkitAvi11/Data-Structures-And-Algorithms","sub_path":"Data Structures/Arrays/word.py","file_name":"word.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"27"} +{"seq_id":"25808869283","text":"import warnings\n\nimport numpy as np\nimport pandas as pd\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\n\nfrom covid_19_ita.utils import watermark\nfrom covid_health.ita import prep_pcm_dpc\n\n\ntamponi_korea = (\n \"https://docs.google.com/spreadsheets/d/\"\n \"1nKRkOwnGV7RgsMnsYE6l96u4xxl3ZaNiTluPKEPaWm8/export?format=csv&\"\n \"id=1nKRkOwnGV7RgsMnsYE6l96u4xxl3ZaNiTluPKEPaWm8&gid=306770783\"\n)\ndate_korea = (\n \"https://docs.google.com/spreadsheets/d/\"\n \"1nKRkOwnGV7RgsMnsYE6l96u4xxl3ZaNiTluPKEPaWm8/export?format=csv&\"\n \"id=1nKRkOwnGV7RgsMnsYE6l96u4xxl3ZaNiTluPKEPaWm8&gid=9649165\"\n)\n\n\ndef decumulate(\n dataframe: pd.DataFrame, col, newcol, first_val: object = 0\n) -> np.ndarray:\n series = dataframe[col]\n result = np.append(\n [first_val], series.iloc[1:].values - series.iloc[:-1].values\n )\n dataframe[newcol] = result\n return dataframe\n\n\ndef bar_line_plot(\n df,\n x=\"date_report\",\n bary=[ # col_name, label, color, trace_kwargs\n (\"new_positives\", \"Nuovi Casi\", \"#FF8A5B\", {}),\n (\"new_deaths\", \"Decessi\", \"#EA526F\", {}),\n (\"new_discharged\", \"Dimessi/Guariti\", \"#25CED1\", {}),\n ],\n barmode=\"stack\",\n liney=(\n \"being_tested\",\n \"Test Effettuati\",\n \"firebrick\",\n {\"mode\": \"lines+markers\"},\n ),\n yscale=100,\n secondaryy=False,\n y1_title=\"N. Casi -- N. Test Effettuati/100\",\n y2_title=\"N. Test Effettuati\",\n title=\"
Andamento del Contagio in Korea del Sud
\"\n ''\n \" Casi Attivi, Dimessi/Guariti, Decessi e Test Effettuati\",\n fonte=\"Fonte: Korea Centers for Desease Control and Prevention\",\n):\n\n fig = make_subplots(specs=[[{\"secondary_y\": secondaryy}]])\n\n for col_name, label, color, trace_kwargs in bary:\n trace = (\n go.Bar(\n x=df[x],\n y=df[col_name],\n name=label,\n marker=dict(color=color),\n opacity=0.75,\n **trace_kwargs\n ),\n )\n fig.add_trace(trace[0], secondary_y=False)\n\n fig.update_layout(barmode=barmode)\n\n # -- TESTS\n col_name, label, color, trace_kwargs = liney\n line_trace = go.Scatter(\n x=df[x],\n y=df[col_name] / yscale,\n name=label,\n line=dict(color=color, width=0.75,),\n marker=dict(symbol=134),\n **trace_kwargs\n )\n fig.add_trace(line_trace, secondary_y=secondaryy)\n\n if secondaryy:\n fig.update_yaxes(\n title=dict(text=y2_title, font=dict(size=11)),\n range=(0, (df[liney[0]] / yscale).max() * 1.1),\n secondary_y=True,\n showgrid=False,\n )\n\n fig.update_yaxes(\n title=dict(text=y1_title, font=dict(size=11)), secondary_y=False\n )\n\n fig.update_layout(\n margin={\"t\": 80, \"l\": 40, \"r\": 20, \"autoexpand\": False},\n title=dict(text=title, x=0.5,),\n template=\"plotly_white\",\n width=750,\n height=500,\n legend=dict(orientation=\"h\"),\n annotations=[\n dict(\n text=fonte,\n font=dict(size=9, color=\"grey\"),\n showarrow=False,\n xref=\"paper\",\n yref=\"paper\",\n y=-0.24,\n )\n ],\n )\n\n watermark(fig)\n\n return fig\n\n\ndef prep_dpc_regions():\n regioni = prep_pcm_dpc.parse_covid_data(\"dpc-regions\")\n regioni.time = regioni.time.dt.floor(\"d\")\n regioni[\"active\"] = (\n regioni[\"tot_n_cases\"]\n - regioni[\"n_discharged_recovered\"]\n - regioni[\"n_deceased\"]\n )\n regioni = regioni[~regioni.region.str.startswith(\"In fase di\")]\n regioni[\"region\"] = regioni[\"region\"].str.strip()\n\n ssets = []\n with warnings.catch_warnings(record=True):\n for ix, sset in regioni.groupby(\"region\"):\n sset[\"being_tested\"] = np.append(\n [0], sset[\"n_tested\"].values[1:] - sset[\"n_tested\"].values[:-1]\n )\n sset.loc[sset[\"being_tested\"].values < 0, \"being_tested\"] = 0\n sset = decumulate(sset, \"n_deceased\", \"new_deceased\")\n sset = decumulate(sset, \"n_discharged_recovered\", \"new_discharged\")\n ssets.append(sset.sort_values(\"time\"))\n regioni = pd.concat(ssets)\n return regioni\n\n\ndef prep_dpc_ita():\n ita_df = (\n prep_dpc_regions()\n .groupby(\"time\", as_index=False)[\n [\n \"n_hospitalized\",\n \"n_intensive_care\",\n \"tot_n_hospitalized\",\n \"n_home_quarantine\",\n \"totale_positivi\",\n \"variazione_totale_positivi\",\n \"nuovi_positivi\",\n \"n_discharged_recovered\",\n \"n_deceased\",\n \"tot_n_cases\",\n \"n_tested\",\n \"being_tested\",\n ]\n ]\n .sum()\n )\n ita_df = decumulate(ita_df, \"n_deceased\", \"new_deceased\")\n ita_df = decumulate(ita_df, \"n_discharged_recovered\", \"new_discharged\")\n ita_df[\"active\"] = (\n ita_df[\"tot_n_cases\"]\n - ita_df[\"n_discharged_recovered\"]\n - ita_df[\"n_deceased\"]\n )\n ita_df[\"epidemic_start\"] = ita_df[ita_df.tot_n_cases >= 100].time.min()\n ita_df[\"epidemic_age\"] = (\n ita_df[\"time\"] - ita_df[\"epidemic_start\"]\n ).dt.days\n ita_df[\"second_disch_totest\"] = np.append(\n [0] * 14, ita_df[\"new_discharged\"].iloc[:-14]\n )\n return ita_df\n\n\ndef prep_korea():\n korea_df = pd.read_csv(tamponi_korea).iloc[:, :-2]\n korea_df = korea_df.replace({\"\": np.nan})\n korea_df = korea_df.astype(\n {\n \"positive\": float,\n \"death\": float,\n \"discharged\": float,\n \"unknown\": float,\n }\n )\n korea_df[\"date_report\"] = pd.to_datetime(korea_df[\"date_report\"])\n korea_df = korea_df.rename(columns={\"unknown\": \"being_tested\"})\n korea_df = korea_df.groupby(\"date_report\", as_index=False).agg(\n {\n \"suspected cases\": \"max\",\n \"positive\": \"max\",\n \"discharged\": \"max\",\n \"death\": \"max\",\n \"negative\": \"max\",\n \"being_tested\": \"sum\",\n }\n )\n korea_df[\"active\"] = (\n korea_df[\"positive\"] - korea_df[\"death\"] - korea_df[\"discharged\"]\n )\n korea_df[\"epidemic_start\"] = korea_df[korea_df.positive >= 100][\n \"date_report\"\n ].min()\n korea_df[\"epidemic_age\"] = (\n korea_df[\"date_report\"] - korea_df[\"epidemic_start\"]\n ).dt.days\n korea_df = korea_df.sort_values(\"date_report\", ascending=True)\n korea_df = decumulate(korea_df, \"positive\", \"new_positives\")\n korea_df = decumulate(korea_df, \"death\", \"new_deaths\")\n korea_df = decumulate(korea_df, \"discharged\", \"new_discharged\")\n korea_df[\"second_disch_totest\"] = np.append(\n [0] * 14, korea_df[\"new_discharged\"].iloc[:-14]\n )\n return korea_df\n\n\ndef line_double_trace(\n elements,\n secondary_elements=None,\n main_line_mode=\"lines+markers+text\",\n secondary_line_dash=\"solid\",\n main_line_width=1.75,\n secondary_line_width=0.75,\n label_format=\"{:.0f}\",\n label_each=3,\n primary_y_title=\"Numero Tamponi Eseguiti\",\n secondary_y_title=\"Nuovi Casi Positivi\",\n title=\"
Numero di Tamponi Eseguiti vs Nuovi Casi COVID-19
\"\n 'Differenza tra italia e Korea del '\n \"Sud\",\n xaxis_title=\"N. Giorni Trascorsi dal 100° Caso Ufficiale\",\n source=\"Fonte: Dipartimento di Protezione Civile Italiana, \"\n \"Korea Centers for Desease Control and Prevention

\",\n source_y=-0.49,\n primary_y_kwargs={},\n secondary_y_kwargs={},\n layout_kwargs={},\n):\n \"\"\"\n elements = [(x: array, y: array, name: str, color: str, textcolor: str)]\n secondary_elements = [(x: array, y: array, name: str, color: str)]\n \"\"\"\n\n fig = make_subplots(\n specs=[[{\"secondary_y\": True if secondary_elements else False}]]\n )\n\n for x, y, name, color, textcolor in elements:\n fig.add_trace(\n go.Scatter(\n x=x,\n y=y,\n text=[\n label_format.format(x) if n % label_each == 0 else \"\"\n for n, x in enumerate(y)\n ],\n name=name,\n # --- LINE\n textposition=\"top center\",\n textfont=dict(color=textcolor),\n line=dict(color=color, width=main_line_width,),\n mode=main_line_mode,\n marker=dict(color=color),\n line_shape=\"spline\",\n # ---\n opacity=0.75,\n showlegend=True,\n )\n )\n\n if secondary_elements:\n for x, y, name, color in secondary_elements:\n fig.add_trace(\n go.Scatter(\n x=x,\n y=y,\n name=name,\n # --- LINE\n line=dict(\n color=color,\n width=secondary_line_width,\n dash=secondary_line_dash,\n ),\n mode=\"lines\",\n line_shape=\"spline\",\n # ---\n opacity=0.75,\n showlegend=True,\n ),\n secondary_y=True,\n )\n\n # Primary\n fig.update_yaxes(\n title=dict(text=primary_y_title, font=dict(size=11)),\n secondary_y=False,\n **primary_y_kwargs\n )\n\n # Secondary\n fig.update_yaxes(\n title=dict(text=secondary_y_title, font=dict(size=11)),\n secondary_y=True,\n showgrid=False,\n **secondary_y_kwargs\n )\n\n _layout_kwargs_std = dict(\n title=dict(text=title, x=0.5, y=0.98),\n margin={\"l\": 40, \"r\": 10, \"t\": 80, \"b\": 140, \"autoexpand\": False},\n template=\"plotly_white\",\n width=700,\n height=450,\n showlegend=True,\n legend=dict(orientation=\"h\", y=-0.22, x=0.5, xanchor=\"center\"),\n # yaxis=dict(range=(0, 400)),\n xaxis=dict(title=xaxis_title),\n annotations=[\n dict(\n font=dict(size=9, color=\"grey\"),\n showarrow=False,\n yref=\"paper\",\n xref=\"paper\",\n text=source,\n y=source_y,\n )\n ],\n )\n _layout_kwargs_std.update(layout_kwargs)\n\n fig.update_layout(**_layout_kwargs_std)\n watermark(fig)\n\n return fig\n","repo_name":"buildnn/covid-19-ita","sub_path":"src/covid_19_ita/figures/tortuga.py","file_name":"tortuga.py","file_ext":"py","file_size_in_byte":10567,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"16019437607","text":"import pygame\nfrom pygame.locals import *\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\n\nverticies = (\n (1, -1, -1),\n (1, 1, -1),\n (-1, 1, -1),\n (-1, -1, -1),\n (1, -1, 1),\n (1, 1, 1),\n (-1, -1, 1),\n (-1, 1, 1)\n )\n\nedges = (\n (0,1),\n (0,3),\n (0,4),\n (2,1),\n (2,3),\n (2,7),\n (6,3),\n (6,4),\n (6,7),\n (5,1),\n (5,4),\n (5,7)\n )\n\nsurfaces = {\n (0, 1, 2, 3),\n (3, 2, 7, 6),\n (6, 7, 5, 4),\n (4, 5, 1, 0),\n (1, 5, 7, 2),\n (4, 0, 3, 6)\n}\n\ndef Cube():\n glBegin(GL_QUADS)\n for surface in surfaces:\n glColor3fv((0,1,0))\n for vertex in surface:\n glColor3fv((1,1,1))\n glVertex3fv(verticies[vertex])\n glEnd()\n\n\n glBegin(GL_LINES)\n for edge in edges:\n for vertex in edge:\n glColor3fv((0,0,1))\n glVertex3fv(verticies[vertex])\n glEnd()\n\n\ndef main():\n pygame.init()\n display = (800,600)\n pygame.display.set_mode(display, DOUBLEBUF|OPENGL)\n\n gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)\n\n glTranslatef(0.0,0.0, -20)\n\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_d:\n glRotate(10, 0, 1, 0)\n if event.key == pygame.K_a:\n glRotate(10, 0, -1, 0)\n if event.key == pygame.K_s:\n glRotate(10, 0, 0, -1)\n if event.key == pygame.K_w:\n glRotate(10, 0, 0, 1)\n if event.key == pygame.K_RIGHT:\n glTranslate(1,0,0)\n if event.key == pygame.K_LEFT:\n glTranslate(-1, 0, 0)\n if event.key == pygame.K_UP:\n glTranslate(0, 0, -1)\n if event.key == pygame.K_DOWN:\n glTranslate(0, 0, 1)\n\n\n\n glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)\n Cube()\n pygame.display.flip()\n pygame.time.wait(10)\n\n\nmain()","repo_name":"triton11/threeD","sub_path":"openpyGL.py","file_name":"openpyGL.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"1452939557","text":"friends = ['다현', '정연', '쯔위', '사나', '지효']\n\ndef insert_value(location, name):\n if location < 0 or location > len(friends):\n print(\"범위를 벗어났습니다.\")\n return\n \n friends.append(None)\n size = len(friends)\n\n for _ in range(size - 1, location, -1):\n friends[_] = friends[_ - 1]\n friends[_ - 1] = None\n \n friends[location] = name\n\ninsert_value(2, '솔라')\nprint(friends)\ninsert_value(6, '문별')\nprint(friends)","repo_name":"kimch0612/Algorithm_Python","sub_path":"week-4/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"5357474557","text":"from flask import Flask, request, render_template, redirect\nimport os\napp = Flask(__name__)\nimg = os.path.join('static') \n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef index():\n file = os.path.join(img,'image.png') \n if request.method == \"POST\":\n user_name = request.form[\"user_name\"]\n return redirect(f\"/fullname/{user_name}\")\n return render_template(\"4-1.html\",image=file)\n\n@app.route(\"/fullname/\")\ndef fullname(user_name):\n file = os.path.join(img,'image.png') \n return render_template(\"full.html\", name=user_name,image=file )\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"alibahadorim/WebPage-Input","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"27172782758","text":"# coding: utf-8\n\nr\"\"\"ydeos_weights __init__.py.\"\"\"\n\n__project_name__ = \"ydeos_weights\"\n__description__ = \"Weights and masses model\"\n\n__version__ = \"2021.09.30\"\n__author__ = \"Guillaume Florent\"\n__author_email__ = \"florentsailing@gmail.com\"\n__license__ = 'GPL v3'\n__url__ = \"https://gitub.com/ydeos/ydeos_weights\"\n__download_url__ = \"https://github.com/ydeos/ydeos_weights/releases/tag/\" + __version__\n","repo_name":"ydeos/ydeos_weights","sub_path":"ydeos_weights/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"21698729514","text":"#cd G:/My Drive/12/Senior Research/code/final\r\nimport time\r\nimport serial\r\nfrom arduinoSender import sendToArduino, configureSerial\r\nimport SETUP\r\n\r\ndef mainArduinoComms():\r\n writeToArduino = True\r\n encodingType = 'utf-8'\r\n\r\n # initialize lines from schedule.txt file\r\n file = open(\"schedule.txt\", \"r\")\r\n lines = file.readlines()\r\n file.close()\r\n init = True\r\n previousMinute = None\r\n dispensedInMinute = set() # keep track of medications dispensed in current minute\r\n\r\n if writeToArduino:\r\n configureSerial()\r\n time.sleep(5)\r\n print(\"configured serial\")\r\n #pass\r\n # open serial port\r\n #serialChannel = serial.Serial(\"/dev/ttyACM0\", 115200, timeout=1)\r\n #serialChannel = serial.Serial(\"COM3\", 9600, timeout=1)\r\n #serialChannel.reset_input_buffer()\r\n #serialChannel.reset_output_buffer()\r\n\r\n while True:\r\n #check the current day on the raspberry pi's system clock\r\n currentDay = time.strftime(\"%a\") #would display as Mon, Tues, Wed, Thurs, Fri, Sat, or Sun\r\n currentHour = time.strftime(\"%H\") #would display as 00, 01, 02, ..., 23\r\n #print(currentHour)\r\n currentMinute = time.strftime(\"%M\") #would display as 00, 01, 02, ..., 59\r\n if init:\r\n previousMinute = currentMinute\r\n init = False\r\n\r\n #every 30 secs, check schedule.txt file to see if there are any meds to be taken\r\n #if there are, send the data to the Arduino to be dispensed (note, since Arduino's ring buffer is 16 bytes, only 4 meds can be dispensed at once)\r\n #if there are not, wait 30 seconds and check again\r\n\r\n #read schedule.txt file if values have been updated\r\n if(SETUP.updatedSchedule == True):\r\n file = open(\"schedule.txt\", \"r\")\r\n lines = file.readlines()\r\n file.close()\r\n print(\"Arduino side updated SCHEDULE!\")\r\n SETUP.updatedSchedule = False\r\n\r\n #schedule.txt structure: day(Mon Tues Wed Thurs Fri Sat Sun)\\thour(0-23)\\tminute(0-59)\\ttray number\\tamount to dispense\\tmedication name\r\n #example: Mon 12 30 1 1 Tylenol\r\n #split each line into a list of strings and comp\r\n\r\n for line in lines:\r\n line = line.split(SETUP.delimiter)\r\n if line[0] == currentDay and int(line[1]) == int(currentHour) and int(line[2]) == int(currentMinute):\r\n #send data to Arduino as tray number\\tamount to dispense\r\n med_key = (line[5], line[3], line[4]) # medication name, tray number, amount to dispense\r\n if med_key not in dispensedInMinute:\r\n data = str(line[3]) + str(SETUP.arduinoDelimiter) + str(line[4])\r\n print(\"Data sent to arduino:\", data)\r\n if writeToArduino:\r\n sendToArduino(data)\r\n time.sleep(2)\r\n\r\n print(\"Dispensing \" + line[5] + \" from tray \" + line[3] + \" for \" + line[4] + \" pills\")\r\n dispensedInMinute.add(med_key) # add medication to set of dispensed medications for current minute\r\n\r\n # reset dispensedInMinute at the beginning of a new minute\r\n if previousMinute != currentMinute:\r\n dispensedInMinute.clear()\r\n\r\n #wait 10 seconds before checking again\r\n time.sleep(SETUP.checkScheduleInterval)\r\n previousMinute = currentMinute","repo_name":"kathIine/meds","sub_path":"TJSTAR/raspberrypi/ArduinoComms.py","file_name":"ArduinoComms.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"29084116443","text":"from pycep_correios import get_address_from_cep, WebService\nimport openpyxl\n\nclass Planilha:\n def __init__(self,name):\n self.fileName = name\n self.workbook = openpyxl.load_workbook(f\"planilhas/{self.fileName}.xlsx\")\n self.worksheet = self.workbook[\"Orçamento \"]\n\n def init(self):\n for index, row in enumerate(self.worksheet.iter_rows(9,539)):\n print(index)\n cep = str(row[3].value)[:5] + \"-\" + str(row[3].value)[5:]\n\n try:\n address = get_address_from_cep(cep, webservice=WebService.CORREIOS)\n self.newCells(address,row)\n except Exception as err:\n row[0].value = str(err)\n\n self.workbook.save(f\"planilhas/{self.fileName}-Modified.xlsx\")\n \n def newCells(self,address,row):\n row[4].value = address[\"logradouro\"]\n row[5].value = address[\"bairro\"]\n row[6].value = address[\"cidade\"]","repo_name":"ThiagoCComelli/consulta-planilha-testes","sub_path":"Planilha.py","file_name":"Planilha.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"43684656422","text":"import math\nfrom functools import reduce\nfrom collections import deque\n\ndef s(generator, splitter, mapper):\n return [ mapper(s) for s in generator().split(splitter) ]\n\n# スペース区切りの入力を読み込んで数値リストにして返します。\ndef get_nums_l():\n return [ int(s) for s in input().split(\" \")]\n\n# 改行区切りの入力をn行読み込んで数値リストにして返します。\ndef get_nums_n(n):\n return [ int(input()) for _ in range(n)]\n\nn,m = get_nums_l()\n\n# 与えられたカード小さい順\nnums = sorted(get_nums_l())\n\n# 変更操作大きい順\nchanges = []\n\nfor j in range(m):\n b,c = get_nums_l()\n changes.append((b,c))\nchanges.sort(key=lambda c:c[1], reverse=True)\n\n# 新カード大きい順\nnnn = []\nfor change in changes:\n b,c = change\n nnn.extend([c] * b)\n\n if len(nnn) >= n:\n break\n\nsumm=0\nlen_nnn = len(nnn)\nfor i in range(n):\n if i < len_nnn:\n summ += max(nums[i], nnn[i])\n else:\n summ += nums[i]\n\nprint(summ)","repo_name":"mui-nyan/AtCoder","sub_path":"abc/abc127/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"25434456339","text":"import requests\n\ndef get_response(q):\n \n return requests.get(f'https://newsapi.org/v2/everything?q={q}&from=2021-10-21&sortBy=publishedAt&apiKey=c90cc5c1426844ceaad1d1cb3af6dec7').json()\n\ndef display_articles(articles):\n\n num = len(articles)\n if len(articles) > 5:\n print(\"Showing top 5 results\\n\\n------------------------------\\n\")\n num = 5\n\n for x in range(num):\n\n print(articles[x]['title'], \"by\", articles[x]['author'])\n print(\"Article from\", articles[x]['source']['name'], \"\\n\")\n\n print(articles[x]['description'])\n print(\"Read more on\", articles[x]['url'], \"\\n\\n------------------------------\\n\")\n\ndef get_input():\n\n response = get_response(input(\"Query (e.g. Tesla): \"))\n\n if response['status'] == 'ok':\n\n print(f\"\\n{response['totalResults']} total results.\")\n\n display_articles(response['articles'])\n\nprint(\"News - API from www.newsapi.org\")\n\nget_input()","repo_name":"nayakrujul/python-scripts","sub_path":"From API/NewsAPI.py","file_name":"NewsAPI.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"4400388697","text":"import os\nimport re\n\nfrom selenium.common.exceptions import NoSuchElementException, TimeoutException, StaleElementReferenceException\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nfrom config.config_parser import ConfigParser\nfrom common_lib.ui.data_generator import DataGenerators\nfrom common_lib.ui.default_data import DEFAULT_VALUES\n\nTIMEOUT_SEC = 10\n\n\nclass BasePage:\n def __init__(self, driver):\n self.common_config = ConfigParser('/common.ini').config\n self.root_url = self.common_config.get('main_url', 'main_url')\n self.driver = driver\n\n def get_driver_version(self):\n if os.environ['BROWSER'] == 'chrome':\n return re.findall(r'(\\w+.\\w+.\\w+.\\w+) ', self.driver.capabilities['chrome']['chromedriverVersion'])[0]\n elif os.environ['BROWSER'] == 'firefox':\n return self.driver.capabilities['moz:geckodriverVersion']\n\n def open_page(self, url=\"\"):\n try:\n self.driver.get('{}{}'.format(self.root_url, url))\n except TimeoutException:\n self.driver.refresh()\n\n def click(self, *locator):\n self.wait_until_element_is_visible(locator)\n self.driver.find_element(*locator).click()\n\n def move_to_element(self, *locator):\n self.wait_until_element_is_visible(locator)\n element = self.driver.find_element(*locator)\n actions = ActionChains(self.driver)\n actions.move_to_element(element)\n actions.perform()\n\n def is_displayed(self, *locator):\n return self.driver.find_element(*locator).is_displayed()\n\n def wait_until_element_is_visible(self, locator, timeout=TIMEOUT_SEC):\n try:\n WebDriverWait(self.driver, timeout).until(EC.visibility_of_element_located(locator))\n except TimeoutException:\n raise AssertionError(f'Element {locator} missed. It takes more than {timeout} sec to load an element')\n\n def is_editable(self, *locator, **kwargs):\n random_str = DataGenerators.generate_random_alphanumeric_str()\n if kwargs.get('date_format'):\n random_str = DEFAULT_VALUES.get('Date of Construction')\n self.type(random_str, *locator)\n return self.get_field_input_value(*locator) == random_str\n\n def type(self, text, *locator, **kwargs):\n self.wait_until_element_is_visible(locator)\n element = self.driver.find_element(*locator)\n if not kwargs.get('without_clear'):\n element.clear()\n element.send_keys(text)\n\n def open_dropdown_and_click_on_value(self, dropdown, dropdown_value):\n self.click(*dropdown)\n self.click(*dropdown_value)\n\n def get_field_input_value(self, *locator):\n return self.driver.find_element(*locator).get_attribute('value')\n\n def get_value_from_grid_or_dropdown(self, *locator):\n return self.driver.find_element(*locator).text\n","repo_name":"Vikkach/devchallenge.it-qa-1","sub_path":"common_lib/ui/base_page.py","file_name":"base_page.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"15409972277","text":"class ListNode:\r\n def __init__(self, val=0, next=None):\r\n self.val = val\r\n self.next = next\r\n\r\ndef addTwoNumbers(l1, l2):\r\n node = ListNode()\r\n current = node\r\n carry = 0\r\n\r\n while l1 or l2 or carry:\r\n sum_val = carry\r\n\r\n if l1:\r\n sum_val += l1.val\r\n l1 = l1.next\r\n if l2:\r\n sum_val += l2.val\r\n l2 = l2.next\r\n\r\n carry = sum_val // 10\r\n current.next = ListNode(sum_val % 10)\r\n current = current.next\r\n\r\n return node.next\r\n\r\n# Example usage\r\n# Create the first linked list: 2 -> 4 -> 3\r\nl1 = ListNode(2)\r\nl1.next = ListNode(4)\r\nl1.next.next = ListNode(3)\r\n\r\n# Create the second linked list: 5 -> 6 -> 4\r\nl2 = ListNode(5)\r\nl2.next = ListNode(6)\r\nl2.next.next = ListNode(4)\r\n\r\n# Add the linked lists\r\nresult = addTwoNumbers(l1, l2)\r\n\r\n# Print the resulting linked list: 7 -> 0 -> 8\r\ncurrent = result\r\nwhile current:\r\n print(current.val, end=\" -> \")\r\n current = current.next\r\nprint(\"None\")\r\n","repo_name":"369harshit/Day5-LL","sub_path":"AddTwoNumber_representedByLL.py","file_name":"AddTwoNumber_representedByLL.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"1156001317","text":"class Solution:\n def productExceptSelf(self, nums: list[int]) -> list[int]:\n len_ = len(nums)\n pre = [1] * len_\n suf = [1] * len_\n ans = [1] * len_\n for i in range(0, len_):\n pre[i] = (pre[i-1] if i!=0 else 1) * nums[i]\n for i in range(len_-1,-1,-1):\n # print(i)\n suf[i] = (suf[i+1] if i!=len_-1 else 1) * nums[i]\n # print(pre)\n # print(suf)\n for i in range(len_):\n ans[i] = (pre[i-1] if i !=0 else 1) * (suf[i+1] if i!= len_-1 else 1)\n\n return ans \n\nclass Solution:\n def productExceptSelf(self, nums: list[int]) -> list[int]:\n len_ = len(nums)\n pre = suf = 1\n ans = [1] * len_\n for i in range(len_):\n ans[i] *= pre\n ans[-1-i] *= suf\n pre *= nums[i]\n suf *= nums[-1-i]\n return ans\n \n\n\n\n\n \ntestCase = [1,2,3,4]\nS = Solution()\nresult = S.productExceptSelf(testCase)\nprint(result)\n\n\n","repo_name":"vincentkali/leetcCodeRecord","sub_path":"238. Product of Array Except Self.py","file_name":"238. Product of Array Except Self.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"11751948797","text":"from django.shortcuts import render, get_object_or_404\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import EmployeeForm, EmployeeProfileForm\n\n# @login_required(login_url='/login/')\ndef employee_list(request):\n context = {}\n context['title'] = 'Employees'\n context['users'] = User.objects.all()\n return render(request, 'employee/employee_list.html', context)\n\ndef employee_details(request, id=None):\n context = {}\n context['user'] = get_object_or_404(User, id=id)\n return render(request, 'employee/employee_details.html', context)\n\ndef employee_edit(request, id=None):\n context = {}\n context['title'] = 'Employees'\n return render(request, 'employee/employee_edit.html', context)\n\ndef employee_delete(request, id=None):\n context = {}\n context['title'] = 'Employees'\n return render(request, 'employee/employee_delete.html', context)\n\ndef employee_add(request):\n form = EmployeeProfileForm(request.POST or None)\n context = {}\n if request.method == 'POST':\n context['message'] = 'This is POST request'\n else:\n context['message'] = 'This is GET request'\n\n context['title'] = 'Employee Profile'\n context['form'] = form\n\n return render(request, 'employee/employee_add.html', context)\n","repo_name":"charlicoder/charliwallet","sub_path":"employee/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"23604301384","text":"import pathlib as pt\nimport numpy as np\n\nparsable_methods = {\n 'LkebCurve': '_parseLkebCurve',\n 'LkebCurveSet': '_parseLkebCurveSet'\n}\n\n\nclass Data:\n def __init__(self, data_file):\n with open(data_file, 'r') as f:\n self.lines = f.readlines()\n self.data_class = self._datatypeFromLines(self.lines)\n self.file_path = pt.Path(data_file)\n getattr(\n self, parsable_methods[self.data_class]\n )()\n\n def _datatypeFromLines(self, lines):\n dataClass = self.lines[0].split(' ')[1]\n parsableClasses = ['LkebCurve', 'LkebCurveSet']\n assert dataClass in parsableClasses, Exception(\n f'{dataClass} not in parsable data types {parsableClasses}')\n return dataClass\n\n def _parseLkebCurveSet(self):\n self.dataType = self.lines[1].split(' ')[-1].strip('\\n')\n self.dimensions = int(self.lines[2].split(' ')[-1])\n self.numberOfCurves = int(self.lines[3].split(' ')[-1])\n self.numberOfPointsPerCurve = []\n self.closed = True\n self.data = []\n\n dtypeMethod = getattr(np, self.dataType)\n\n curveStartPoint = 7\n\n for _ in np.arange(self.numberOfCurves):\n nPoints = int(self.lines[curveStartPoint - 2].split(' ')[-1])\n self.numberOfPointsPerCurve.append(nPoints)\n lines = self.lines[curveStartPoint: (curveStartPoint + nPoints)]\n self.data.append(\n Data.linesToArray(lines, dtypeMethod=dtypeMethod)\n )\n curveStartPoint += nPoints + 2\n\n delattr(self, 'lines')\n\n def _parseLkebCurve(self):\n self.dataType = self.lines[2].split(' ')[-1].strip('\\n')\n self.dimensions = int(self.lines[3].split(' ')[-1])\n self.numberOfPoints = int(self.lines[4].split(' ')[-1])\n self.closed = bool(int(self.lines[5].split(' ')[-1]))\n lines = self.lines[12:(12+self.numberOfPoints)]\n dtypeMethod = getattr(np, self.dataType)\n self.data = self.linesToArray(\n lines, dtypeMethod=dtypeMethod\n )\n delattr(self, 'lines')\n\n @classmethod\n def linesToArray(cls, lines, dtypeMethod=np.float, delimeter=' '):\n nPoints = len(lines)\n nDimensions = len(lines[0].split(delimeter))\n array = np.zeros((nPoints, nDimensions))\n\n for i, line in enumerate(lines):\n array[i] = np.array(\n line.strip('\\n').split(delimeter)\n ).astype(dtypeMethod)\n\n return array.T\n","repo_name":"Chr1sC0de/pymethods","sub_path":"pymethods/parse/angiography/AngiographyData.py","file_name":"AngiographyData.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"27"} +{"seq_id":"36238577629","text":"from django.test import TestCase\nfrom django.urls import include, path\nfrom rest_framework.test import APITestCase, URLPatternsTestCase\nfrom app.tests.base_test import BaseTest\n\nfrom datasets import views as v\nimport logging\nlogging.disable(logging.CRITICAL)\n\n\nclass AcrisRealMasterViewTests(BaseTest, TestCase):\n\n def tearDown(self):\n self.clean_tests()\n\n def test_list(self):\n self.acrismaster_factory(doctype=\"DEED\", documentid=\"1\")\n self.acrismaster_factory(doctype=\"DEED\", documentid=\"2\")\n\n response = self.client.get('/acrisrealmasters/', format=\"json\")\n content = response.data\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(content), 2)\n\n def test_retrieve(self):\n self.acrismaster_factory(doctype=\"DEED\", documentid=\"1\")\n\n response = self.client.get('/acrisrealmasters/1/')\n content = response.data\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(content[\"documentid\"], '1')\n\n def test_acrismaster_acrisparties(self):\n master = self.acrismaster_factory(doctype=\"DEED\", documentid=\"1\")\n self.acrisparty_factory(master=master)\n self.acrisparty_factory(master=master)\n\n response = self.client.get('/acrisrealmasters/1/acrisrealparties/')\n content = response.data\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(content), 2)\n","repo_name":"ANHD-NYC-CODE/anhd-council-backend","sub_path":"datasets/tests/views/test_acrisrealmaster.py","file_name":"test_acrisrealmaster.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"27"} +{"seq_id":"6856062717","text":"# -*- coding: utf-8 -*\n# author: qh\n# date: 2017/11/28\n# 3-2 多项式回归\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nfrom torch import nn, optim\nfrom torch.autograd import Variable\n\n\nw_target = torch.FloatTensor([0.5, 3, 2.4]).unsqueeze(1)\nb_target = torch.FloatTensor([0.9])\n\n\ndef make_features(x):\n \"\"\"\n build features for a matrix with colums [x, x^2, x^3]\n \n torch.squeeze(input, dim=None, out=None)\n Returns a Tensor with all the dimensions of input of size 1 removed.\n 默认是去掉所有维度中维度大小为1的维度并返回\n 若指定了dim(从0开始),则判断该维度大小是否为1,若为1则去掉\n\n torch.unsqueeze(input, dim, out=None)\n Returns a new tensor with a dimension of size one inserted at the specified position.\n 在指定位置插入一个1维tensor\n \"\"\"\n x = x.unsqueeze(1)\n return torch.cat([x ** i for i in range(1, 4)], 1)\n\ndef f(x):\n \"\"\"\n 模拟函数,输入一个x得到一个y\n \"\"\"\n return x.mm(w_target) + b_target[0]\n\ndef plot_function(model):\n \"\"\"\n 画图\n \"\"\"\n x_data = make_features(torch.arange(-1, 1, 0.1))\n y_data = f(x_data)\n if torch.cuda.is_available():\n y_pred = model(Variable(x_data).cuda())\n x = torch.arange(-1, 1, 0.1).numpy()\n y = y_data.numpy()\n y_p = y_pred.cpu().data.numpy()\n plt.xlabel('x')\n plt.ylabel('y')\n plt.plot(x, y, 'ro', label='real curve')\n plt.plot(x, y_p, label='fitting curve')\n plt.legend(loc='best')\n plt.show()\n\n# print funciton describe\ndef poly_desc(w, b):\n des = 'y = {:.2f} + {:.2f}*x + {:.2f}*x^2 + {:.2f}*x^3'.format(\n b[0], w[0], w[1], w[2])\n return des\n\ndef get_batch(batch_size = 32):\n \"\"\"\n 随机生成一些数来得到每次的训练集\n \"\"\"\n random = torch.randn(batch_size)\n x = make_features(random)\n y = f(x)\n if torch.cuda.is_available():\n return Variable(x).cuda(), Variable(y).cuda()\n else:\n return Variable(x), Variable(y)\n\nclass poly_model(nn.Module):\n \"\"\"\n 建立多项式模型\n \"\"\"\n def __init__(self):\n super(poly_model, self).__init__()\n # 定义输入输出是3*1维的\n self.poly = nn.Linear(3, 1)\n\n def forward(self, x):\n out = self.poly(x)\n return out\n\n# 如果cuda可用则用cuda加速\n# class torch.nn.DataParallel(module, device_ids=None, output_device=None, dim=0)[source]\n# 在模块级别上实现数据并行。\n# http://pytorch-cn.readthedocs.io/zh/latest/package_references/torch-nn/#torchnn\nif torch.cuda.is_available():\n model = poly_model().cuda()\n # model = poly_model()\n # model = torch.nn.DataParallel(model).cuda()\nelse:\n model = poly_model()\n\n# 定义损失函数,nn.MSELoss代表平方损失函数\ncriterion = nn.MSELoss()\n\n# 定义优化函数, SGD代表随机梯度下降 ,lr代表学习速度\n# 例子 optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) \n# 使用SGD(随机梯度下降)优化,学习率为0.001,动量为0.9\n# 此处的1e-3代表 0.001,即10的-3次方\noptimizer = optim.SGD(model.parameters(), lr = 1e-3)\n\n# 定义总的循环次数\nepoch = 0\nwhile True:\n # Get data\n batch_x, batch_y = get_batch()\n # forward pass\n output = model(batch_x)\n loss = criterion(output, batch_y)\n print_loss = loss.data[0]\n optimizer.zero_grad()\n # Backward pass\n loss.backward()\n # 优化参数\n optimizer.step()\n epoch += 1\n if print_loss < 1e-3:\n torch.save(model.state_dict(), './poly.pth')\n break\n\nprint('Loss: {:.6f} after {} batches'.format(print_loss, epoch))\nprint('==> Learned function:\\t' + poly_desc(model.poly.weight.data.view(-1),\n model.poly.bias.data))\nprint('==> Actual function:\\t' + poly_desc(w_target.view(-1), b_target))\nplot_function(model)","repo_name":"qianhaoq/pytorch_test","sub_path":"chapter-3/3-2polynomial.py","file_name":"3-2polynomial.py","file_ext":"py","file_size_in_byte":3872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"74506097350","text":"\"\"\"\nja3requests.__version__\n~~~~~~~~~~~~~~~~~~~~~~~\n\nVersion information.\n\"\"\"\n\n__title__ = \"ja3requests\"\n__description__ = \"An http request library that can customize ja3 or h2 fingerprints.\"\n__url__ = \"https://github.com/lxjmaster/ja3requests\"\n__version__ = \"1.0.2\"\n__author__ = \"Mast Luo\"\n__author_email__ = \"379501669@qq.com\"\n__license__ = \"Apache-2.0 license\"\n__copyright__ = \"Copyright Mast Luo\"\n","repo_name":"lxjmaster/ja3requests","sub_path":"ja3requests/__version__.py","file_name":"__version__.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"27"} +{"seq_id":"74711775752","text":"def main():\n limit_str = input('Enter an integer limit: ')\n\n try:\n limit = int(limit_str)\n except ValueError as e:\n print('You must enter a valid integer')\n return\n\n sum = 0\n for i in range(limit):\n if (i % 3 == 0) or (i % 5 == 0):\n sum += i\n print(sum)\n\nif __name__ == '__main__':\n main()\n","repo_name":"lifesci/project-euler","sub_path":"1/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"33378628894","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 3 23:15:00 2018\n\n@author: soojunghong\n\"\"\"\n#-----------------\n# Import textblob \n#-----------------\nfrom textblob import TextBlob\nwiki = TextBlob(\"Python is a high-level, general-purpose programming language.\")\nwiki.tags\n\n\n#------------------------\n# Text analysis example\n#------------------------\nfrom textblob import TextBlob\nblob = TextBlob(\"ITP is a two-year graduate program located in the Tisch School of the Arts. Perhaps the best way to describe us is as a Center for the Recently Possible.\")\n\nfor sentence in blob.sentences:\n print(sentence)\n\nfrom sklearn.datasets import fetch_20newsgroups\n\ndataset = fetch_20newsgroups(shuffle=True, random_state=1, remove=('headers', 'footers', 'quotes'))\ndocuments = dataset.data\ndocuments\n\n\n#------------------------------\n# get definition from product\n#------------------------------\n\nimport csv \nimport os\nimport pandas as pd\n \ndef getProductsInfoInOrder(orderID, data, productInfo, product_dept) :\n order = data[data['order_id'] == orderID] \n prodList = []\n if(order.empty) : \n #print(\"[Warning] There is no order in this data set!!!\")\n prodList.append(None)\n else : \n prodList = order['product_id'].tolist()\n return prodList\n\n \ndef printAllProductsInOrder(orderID, data, productInfo) :\n #data = readCSV(path_data, data_order_prior) \n #productInfo = readCSV(path_data, data_products)\n products = []\n order = data[data['order_id'] == orderID] \n if(order.empty) : \n print(\"There is no order in this data set\")\n prodList = order['product_id'].tolist()\n for ord in prodList : \n prod = productInfo[productInfo[\"product_id\"] == ord].product_name\n print(prod)\n products.append(prod)\n return products\n\n\ndef readCSV(filePath, fileName): \n csv_path = os.path.join(filePath,fileName)\n return pd.read_csv(csv_path) \n\n\ndef getFullDefinition(product_name):\n word1 = product_name.values[0]\n product_name = TextBlob(word1)\n #wordsLeng = len(product_name.words)\n for subPro in product_name.words :\n print(Word(subPro).definitions)\n \n\ndef getFullDefinitionFromLastword(product_name):\n #print(type(product_name)) #series type\n #print(product_name)\n #print(product_name.size)\n if(product_name.size == 0) : \n return Word(\"None\")\n word1 = product_name.values[0]\n product_name = TextBlob(word1.decode('latin-1')) #('utf-8')) #you have to decode \n wordsLeng = len(product_name.words)\n #decodedProd = (product_name.words[wordsLeng-1]).decode('utf-8')\n #defs = Word(decodedProd).definitions\n defs = Word(product_name.words[wordsLeng-1]).definitions\n if (len(defs) == 0) :\n return Word(\"None\") #there is no definition\n \n return Word(product_name.words[wordsLeng-1]).definitions[0]\n\n\ndef getProductDescOfAdjective(prod) : \n productName = prod.values[0]\n productName\n product_name = TextBlob(productName)\n #product_name_len = len(product_name.words)\n product_adj = product_name.words[0]\n adj = Word(product_adj)\n adjDesc = adj.definitions\n\n return adjDesc\n\n\n\ndef getProductDescOfNoun(prod) : \n productName = prod.values[0]\n productName\n product_name = TextBlob(productName)\n product_name_len = len(product_name.words)\n product_noun = product_name.words[product_name_len - 1]\n noun = Word(product_noun)\n nounDesc = noun.definitions\n\n return nounDesc\n\n\n\ndef getProductFirstDescOfNoun(prod) : \n productName = prod.values[0]\n productName\n product_name = TextBlob(productName)\n \n print(product_name.words)\n \n \n \"\"\"\n wordList = []\n # line = line.replace(';', ':')\n for w in product_name.words : \n w = w.decode.encode('utf-8')\n w = w.replace('-', '')\n wordList.append(w)\n \n product_name_len = len(wordList)\n print(product_name_len)\n print(wordList)\n product_noun = wordList[product_name_len - 1]\n noun = Word(product_noun)\n nounDesc = noun.definitions\n print(nounDesc[0].decode.encode('utf-8')) \n return nounDesc[0].decode.encode('utf-8') \n \"\"\"\n\n \n\"\"\"\ndef mostFrequentlyPurchasedByUser(userID) : \n from collections import Counter\n product = readCSV(path_data, data_products)\n orders = readCSV(path_data, data_orders)\n dept = readCSV(path_data, data_dept)\n product_dept = productInfo.merge(dept, on='department_id', how='inner')\n user_products_id = []\n ordersPerUser = orders[orders[\"user_id\"] == userID]\n for ordr in ordersPerUser.order_id : \n #print(ordr)\n currlist = getProductsInfoInOrder(ordr, data, productInfo, product_dept)\n for p in currlist : \n #print(product[product[\"product_id\"] == p].product_name) \n user_products_id.append(p)\n #print(user_products_id)\n c = Counter(user_products_id)\n mostfreq_id = c.most_common(1)\n #print(mostfreq_id)\n mostfreq =product.loc[product['product_id'] == mostfreq_id[0][0]] \n return mostfreq\n\"\"\" \n\n\ndef threeMostFrequentlyPurchasedByUser(userID, product, orders, dept) : \n from collections import Counter\n# product = readCSV(path_data, data_products)\n# orders = readCSV(path_data, data_orders)\n# dept = readCSV(path_data, data_dept)\n product_dept = productInfo.merge(dept, on='department_id', how='inner')\n user_products_id = []\n ordersPerUser = orders[orders[\"user_id\"] == userID]\n for ordr in ordersPerUser.order_id : \n #print(ordr)\n currlist = getProductsInfoInOrder(ordr, data, productInfo, product_dept)\n #print(currlist)\n for p in currlist : \n #print(product[product[\"product_id\"] == p].product_name) \n user_products_id.append(p)\n #print(user_products_id)\n c = Counter(user_products_id)\n mostfreq_id = c.most_common(1) # 1 most frequent \n mostfreq_id1 = c.most_common(2) # 2 most frequent\n mostfreq_id2 = c.most_common(3) # 3 most frequent\n \n threeMost = []\n mostfreq =product.loc[product['product_id'] == mostfreq_id[0][0]] \n threeMost.append(mostfreq) \n secondfreq =product.loc[product['product_id'] == mostfreq_id1[1][0]] \n threeMost.append(secondfreq) \n thirdfreq =product.loc[product['product_id'] == mostfreq_id2[2][0]] \n threeMost.append(thirdfreq)\n return threeMost\n\n\n\ndef tenMostFrequentlyPurchasedByUser(userID, product, orders, dept) : \n from collections import Counter\n product_dept = productInfo.merge(dept, on='department_id', how='inner')\n user_products_id = []\n ordersPerUser = orders[orders[\"user_id\"] == userID]\n for ordr in ordersPerUser.order_id : \n #print(ordr)\n currlist = getProductsInfoInOrder(ordr, data, productInfo, product_dept)\n if(len(currlist) != 0) : \n for p in currlist : \n #print(product[product[\"product_id\"] == p].product_name) \n user_products_id.append(p)\n #print(user_products_id)\n c = Counter(user_products_id)\n tenMost = []\n if (len(c) > 10) : \n for i in range(1,11) : \n prod = c.most_common(i)\n tenMost.append(product.loc[product['product_id'] == prod[i-1][0]])\n else : \n return \"None\"\n return tenMost\n \n \"\"\" \n mostfreq_id = c.most_common(1) # 1 most frequent \n mostfreq_id1 = c.most_common(2) # 2 most frequent\n mostfreq_id2 = c.most_common(3) # 3 most frequent\n \n threeMost = []\n mostfreq =product.loc[product['product_id'] == mostfreq_id[0][0]] \n threeMost.append(mostfreq) \n secondfreq =product.loc[product['product_id'] == mostfreq_id1[1][0]] \n threeMost.append(secondfreq) \n thirdfreq =product.loc[product['product_id'] == mostfreq_id2[2][0]] \n threeMost.append(thirdfreq)\n return threeMost\n \"\"\"\n \n\ndef MostFrequentlyPurchasedByUser(userID, product, orders, dept) : \n from collections import Counter\n# product = readCSV(path_data, data_products)\n# orders = readCSV(path_data, data_orders)\n# dept = readCSV(path_data, data_dept)\n product_dept = productInfo.merge(dept, on='department_id', how='inner')\n user_products_id = []\n ordersPerUser = orders[orders[\"user_id\"] == userID]\n for ordr in ordersPerUser.order_id : \n #print(ordr)\n currlist = getProductsInfoInOrder(ordr, data, productInfo, product_dept)\n #print(currlist)\n for p in currlist : \n #print(product[product[\"product_id\"] == p].product_name) \n user_products_id.append(p)\n #print(user_products_id)\n c = Counter(user_products_id)\n mostfreq_id = c.most_common(1) # 1 most frequent \n print(mostfreq_id)\n \n mostfreq =product.loc[product['product_id'] == mostfreq_id[0][0]] \n return mostfreq\n\n\n\ndef getMostFreqWordsInProductDefinition(userID, product, orders, dept):\n #from collections import Counter\n user_products_names = []\n product_names_desc = []\n product_dept = productInfo.merge(dept, on='department_id', how='inner')\n ordersPerUser = orders[orders[\"user_id\"] == userID]\n for ordr in ordersPerUser.order_id : \n #print(ordr)\n currlist = getProductsInfoInOrder(ordr, data, productInfo, product_dept)\n for p in currlist : \n #print(product[product[\"product_id\"] == p].product_name) \n pName = product[product[\"product_id\"] == p].product_name\n user_products_names.append(pName)\n #print(user_products_names)\n #product_names_desc = []\n for n in user_products_names : \n product_names_desc.append(getProductFirstDescOfNoun(n))\n \n #get most frequent words from all descriptions \n #eg = TextBlob(product_names_desc[1])\n #print(eg.noun_phrases) \n \n all_nouns = []\n for desc in product_names_desc : \n tmp_desc = TextBlob(desc)\n #print(tmp_desc.noun_phrases)\n for phr in tmp_desc.noun_phrases : \n all_nouns.append(phr)\n #print(type(all_nouns)) #list - probably WordList\n from collections import Counter\n c = Counter(all_nouns) \n print(c.most_common(1))\n \n return product_names_desc \n \n \n#---------\n# data \n#--------- \npath_data = \"/Users/soojunghong/Documents/safariML/ML_python/kaggle/InstacartAnalysis/data/\"\ndata_aisle = \"aisles.csv\"\ndata_dept = \"departments.csv\"\ndata_order_prior = \"order_products_prior.csv\"\ndata_order_train = \"order_products_train.csv\"\ndata_orders = \"orders.csv\"\ndata_products = \"products.csv\"\n\nreadCSV(path_data, data_orders)\nreadCSV(path_data, data_products)\ndata = readCSV(path_data, data_order_prior) \ndata\nproductInfo = readCSV(path_data, data_products)\nproductInfo \nproducts = printAllProductsInOrder(9, data, productInfo) #number of products : 49687\nproducts\nproducts[0]\n\n\n#------------------------------------\n# for each product, get definition\n#------------------------------------\nfrom textblob import Word\nfrom textblob.wordnet import VERB\n\nproductName = products[0].values[0]\nproductName\nproduct_name = TextBlob(productName)\ntype(product_name.words)\nproduct_name_len = len(product_name.words)\nproduct_name_len\nproduct_adj = product_name.words[0]\nproduct_adj\nproduct_noun = product_name.words[product_name_len - 1]\nproduct_noun\n# ToDo : if the product name contains, comma, the noun should be string before the comma\n\nadj = Word(product_adj)\nadj.definitions\n\nnoun = Word(product_noun)\nnoun.definitions\n\n# test of getting description of adjective of product and description of noun in product name\nproducts[1] \ngetFullDefinition(products[1]) \ndescNoun = getProductDescOfNoun(products[1])\nlen(descNoun)\ndescNoun[0]\n\ndescAdj = getProductDescOfAdjective(products[1])\ndescAdj[0]\n\nproducts[3]\ngetFullDefinitionFromLastword(products[3])\n\n\n#-------------------------------\n# Bag-of-Words in Scikit-learn \n#-------------------------------\nfrom sklearn.datasets import fetch_20newsgroups\n\ndataset = fetch_20newsgroups(shuffle=True, random_state=1, remove=('headers', 'footers', 'quotes'))\ndocuments = dataset.data\ndocuments\n\nfrom sklearn.feature_extraction.text import CountVectorizer \nvectorizer = CountVectorizer()\nA = vectorizer.fit_transform(documents)\nprint(A)\n\n#list all terms and associated dictionary which maps each unique term to a corresponding column in the matrix\nterms = vectorizer.get_feature_names()\nlen(terms) #how many terms in the column \n\nvocab = vectorizer.vocabulary_\nvocab[\"world\"] #which column corresponds to a term \n\n#--------------------------------------------------------\n# TF-IDF (term frequency, Inversed Document Frequency)\n#--------------------------------------------------------\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nvectorizer = TfidfVectorizer()\nA = vectorizer.fit_transform(documents)\nprint(A)\n\nfrom sklearn import decomposition\nk = 10\nmodel = decomposition.NMF(n_components = k, init = \"nndsvd\") # initialize with SVD\nW = model.fit_transform(A)\nH = model.components_\n\nprint(W)\nprint(H)\n\n#--------------------------------------------------------------------------\n# idea : get description of all products that user ordered and find topic \n#--------------------------------------------------------------------------\nimport pandas as pd;\nimport numpy as np;\nimport scipy as sp;\nimport sklearn;\nimport sys;\nfrom nltk.corpus import stopwords;\nimport nltk;\nfrom gensim.models import ldamodel\nimport gensim.corpora;\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer;\nfrom sklearn.decomposition import NMF;\nfrom sklearn.preprocessing import normalize;\nimport pickle;\nimport re;\n\ndef get_lda_topics(model, num_topics):\n word_dict = []\n for i in range(num_topics):\n words = model.show_topic(i, topn=20)\n \n for i in words : \n #print i[0]\n word_dict.append(i[0])\n #word_dict['Topic # ' + '{:02d}'.format(i+1)] = [i[0] for i in words]; #format(i+1) is to start topic index from 1 (since 0 is CS people' index )\n return pd.DataFrame(word_dict)\n\n\ndef findTopic(data) : #data_text is dataframe \n data_text = data[['favorite_product_desc']]; # we only need text column from the original data\n data_text = data_text.astype('str')\n \n for idx in range(len(data_text)):\n #remove stop words\n # org #data_text.iloc[idx]['favorite_product_desc'] = [word for word in data_text.iloc[idx]['favorite_product_desc'].split(' ') if word not in stopwords.words()]\n data_text.iloc[idx]['favorite_product_desc'] = [word for word in data_text.iloc[idx]['favorite_product_desc'].split(' ') if word not in stopwords.words()]\n \n #print logs to monitor output\n #if idx % 1000 == 0:\n # sys.stdout.write('\\rc = ' + str(idx) + ' / ' + str(len(data_text)));\n \n documents = []\n for value in data_text.iloc[0:].values:\n # add into list 'documents', value is narray \n \n # value is narray\n for i in range(len(value)): #print(value[i][0])\n for j in range(len(value[i])) :\n value[i][j] = re.sub('[^a-zA-Z0-9-_*.]', '', value[i][j])\n \n documents.append(value)\n\n train_headlines = [value[0] for value in data_text.iloc[0:].values]; \n \n num_topics = 10\n id2word = gensim.corpora.Dictionary(train_headlines)\n\n corpus = [id2word.doc2bow(text) for text in train_headlines] #doc2bow : The function doc2bow() simply counts the number of occurrences of each distinct word, converts the word to its integer word id and returns the result as a sparse vector.\n\n lda = ldamodel.LdaModel(corpus=corpus, id2word=id2word, num_topics=num_topics)\n ret = get_lda_topics(lda, num_topics) #ret is list type\n #print(ret) \n return ret\n\n\"\"\"\n# similarity between definition\nfrom textblob.wordnet import Synset\noctopus = Synset(products[1].values[0]+'.n.01')\nshrimp = Synset('shrimp.n.03')\noctopus.path_similarity(shrimp)\n\nprod = TextBlob(products[1].values[0])\nprod.words\nnum = len(prod.words)\nnum\nWord(prod.words[num-1]).definitions \nWord(prod.words[num-1]).synsets \nmush1 = Synset('mushroom.n.01')\nmush2 = Synset('mushroom.n.02')\nmush1.path_similarity(mush2)\n\"\"\"\n\n\"\"\"\n#---------------------------------------------------------------------------\n# for all users, get 3 most frequently purchased products, \n# and get definitions of products and extract relevant words \n#---------------------------------------------------------------------------\n\"\"\"\n# userID starts from 1 to 206209\n\n#-------------------------------------------------------------------------------\n# for each user, get their 3 most frequently purchased products \n# and find out the topic out of it, this topic will be user profile's name\n#------------------------------------------------------------------------------- \na\n#-----------------------------------------------------------------------------------\n# Find out topic from all users by analyzing 10 most frequently purchased products\n# total number of users : 206209\n#-----------------------------------------------------------------------------------\nuserID = 4\nmProduct = tenMostFrequentlyPurchasedByUser(userID, product, orders, dept)\nmProduct\nfor p in mProduct : \n #print(p.product_name)\n #print(getFullDefinitionFromLastword(p.product_name))\n defPROD = getFullDefinitionFromLastword(p.product_name) #products[1]) \n if(defPROD != '') :\n df = df.append({'userID':userID, 'favorite_product_desc':defPROD}, ignore_index=True)\n \ndf\n# topics.iloc[0] \n\nfrom collections import Counter\ntopics = findTopic(df)\nmyList = topics.iloc[:, 0]\ntopicList = myList.tolist()\nc = Counter(topicList)\nmostfreq_id = c.most_common(1) # 1 most frequent - #instead of the 0th topic, get the top most frequent topic\nmostfreq_id\n\n \n#------------------------------------------------------------------------------------------------\n# Based on customer's top 10 most frequent purchased product, topic modeling the topic of user\n#------------------------------------------------------------------------------------------------\ndef topicOfUser(userID, product, orders, dept) :\n # create dataframe df \n import pandas as pd\n df = pd.DataFrame(columns=('userID', 'favorite_product_desc'))\n \n mProduct = tenMostFrequentlyPurchasedByUser(userID, product, orders, dept)\n if(mProduct != \"None\") : \n for p in mProduct : \n defPROD = getFullDefinitionFromLastword(p.product_name) #products[1]) \n if(defPROD != '') :\n df = df.append({'userID':userID, 'favorite_product_desc':defPROD}, ignore_index=True)\n \n from collections import Counter\n topics = findTopic(df)\n myList = topics.iloc[:, 0]\n topicList = myList.tolist()\n c = Counter(topicList)\n mostfreq_id = c.most_common(1) # 1 most frequent - #instead of the 0th topic, get the top most frequent topic\n return mostfreq_id\n \n else :\n return \"None\"\n \n# find out topic of all customers and put it in their profile \nproduct = readCSV(path_data, data_products)\norders = readCSV(path_data, data_orders)\ndept = readCSV(path_data, data_dept)\n\n#ToDo\nfor i in range(1, 10): #:206209) : \n print(topicOfUser(i, product, orders, dept)) \n \n\n \n#--------------------------------------------------------------\n# Create User Profile : \n#--------------------------------------------------------------\nimport pandas as pd\n#d = {'userID' : [1,2,3], 'userProfileName': ['organic', 'lifegoods', 'meatperson'], 'shoppingHour' : ['morning', 'afternoon', 'evening']}\n#df = pd.DataFrame(data=d)\n#df\n\n# initializa dataframe \nd = {'userID':[], 'userProfileName':[]}\ndf = pd.DataFrame(data = d)\ndf\n\nfor i in range(1,100): \n row = pd.DataFrame({'userID':[i], 'userProfileName':[topicOfUser(i, product, orders, dept)]})\n df = df.append(row)\n\ndf \n#df = df.append(row2)\n#df","repo_name":"SoojungHong/InstacartAnalysis","sub_path":"NLP_exercise.py","file_name":"NLP_exercise.py","file_ext":"py","file_size_in_byte":19829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"72379096071","text":"import pickle\n\nwith open('model/car_model.pkl', 'rb') as f:\n car_model = pickle.load(f)\n\nwith open('model/scaler_x.pkl', 'rb') as f:\n scaler_x = pickle.load(f)\n\nwith open('model/scaler_y.pkl', 'rb') as f:\n scaler_y = pickle.load(f)\n\ndef car_price(AccelSec, TopSpeed_KmH, Range_Km, \n Efficiency_WhKm, FastCharge_KmH, Seats):\n 'This function gets AccelSec, TopSpeed_KmH, Range_Km, Efficiency_WhKm\\\n, FastCharge_KmH and Seats of car. It returns price of car in rupees'\n x = scaler_x.transform([[AccelSec, TopSpeed_KmH, Range_Km, \n Efficiency_WhKm, FastCharge_KmH, Seats]])\n y = car_model.predict(x)\n y = scaler_y.inverse_transform(y.reshape(1, -1))\n return y[0][0]*88.8","repo_name":"Adhiban1/EV-Market-Segmentation","sub_path":"CarPrice.py","file_name":"CarPrice.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"16569235845","text":"def func(a):\n a = a[::-1]\n total = len(a)\n for i in range(total):\n if a[i] == '1':\n return total - i - 1\n return -1\n\n\nfor t in range(int(input())):\n a = input()\n print(func(a))\n","repo_name":"734mh4rdc0d3/GeeksForGeeks-Must-Do-Programming-","sub_path":"Arrays/21/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"29349934259","text":"from replit import clear\n\ndef add(n1, n2):\n return n1 + n2\n\ndef substract(n1, n2):\n return n1 - n2\n\ndef multiply(n1, n2):\n return n1 * n2\n\ndef divide(n1, n2):\n return n1 / n2\n\noperations = {\n \"+\": add,\n \"-\": substract,\n \"*\": multiply,\n \"/\": divide,\n }\n\ndef first_calculation():\n num1 = int(input(\"What is the first number? \"))\n num2 = int(input(\"What is the second number? \"))\n for symbol in operations:\n print(symbol)\n operation_symbol = input(\"Pick an operation symbol. \")\n selected_operation = operations[operation_symbol]\n print(f\"{num1} {operation_symbol} {num2} = {selected_operation(num1, num2)}\")\n return selected_operation(num1, num2)\n \n\ndef additional_calculation():\n previousN = result\n nextN = int(input(\"What is the second number? \"))\n for symbol in operations:\n print(symbol)\n operation_symbol = input(\"Pick an operation symbol. \")\n selected_operation = operations[operation_symbol]\n print(f\"{previousN} {operation_symbol} {nextN} = {selected_operation(previousN, nextN)}\")\n return selected_operation(previousN, nextN)\n\ncontinue_calculation = True\nfirst = True\nresult = 0\n\nwhile continue_calculation:\n if first == True:\n result = first_calculation()\n first = False\n else:\n result = additional_calculation()\n proceed = input(f\"Type 'y' to continue calculating with {result}. Type 'n' to start a new caclulation. \")\n first = False\n if proceed == \"n\":\n clear()\n first = True\n result = 0\n","repo_name":"edwardjanson/python_projects","sub_path":"008_calculator/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70320981512","text":"#! This should simulate the results from arXiv:1712.08581\n\nfrom qiskit import QuantumProgram, QISKitError,QuantumJob,QuantumRegister,ClassicalRegister,QuantumCircuit\nfrom qiskit import available_backends, execute, register, get_backend\nfrom qiskit.tools.visualization import circuit_drawer\nimport numpy as np\n\nfrom QCTools import QHelperFunctions as hlp\n\nshots = 8192\n\nhlp.configure('/home/camelto2/Research/quantum_computing','Qconfig_ibmq_experience')\n\ndef exact(U):\n return 0.5*(U-np.sqrt(16+U**2))-U/2\n\ndef setup():\n q = QuantumRegister(2)\n c = ClassicalRegister(2)\n Q = QuantumCircuit(q,c)\n return q,c,Q\n\ndef ground_state(q,Q):\n Q.h(q) #applies to each one\n\ndef adiabatic_evolution(q,Q,delta,tau,Nsteps):\n #Adiabatic evolution\n for m in range(1,Nsteps+1):\n #apply exp(i delta (X1+X2) ) \n for i in range(len(q)):\n Q.rx(-2.0*delta,q[i])\n \n #apply exp(-i m delta^2/ (2tau) Z1 Z2) \n Q.cx(q[0],q[1])\n Q.rz(m*delta**2/tau,q[1])\n Q.cx(q[0],q[1])\n\ndef M2_adiabatic_evolution(q,Q,delta,Nsteps):\n #Adiabatic evolution\n for m in range(1,Nsteps+1):\n #apply exp(i delta (X1+X2) ) \n for i in range(len(q)):\n Q.rx(-2.0*delta,q[i])\n \n #apply exp(-i m delta^2/ (2tau) Z1 Z2) \n # tau = INF so no Rz rotation\n Q.cx(q[0],q[1])\n Q.cx(q[0],q[1])\n\ndef measure(q,c,Q,measurement):\n if measurement == 'X1':\n Q.h(q[0])\n elif measurement == 'X2':\n Q.h(q[1])\n Q.measure(q,c)\n\n #backend = hlp.lowest_pending_jobs()\n #print(\"the best backend is \" + backend)\n backend = 'ibmqx4'\n\n\n job = execute(Q,backend=backend,shots=shots)\n\n hlp.watch_job(job)\n print(job.status)\n\n result = job.result()\n return result\n\ndef analyze(H1,H2,H3,U):\n states=['00','10','01','11']\n scaledH1 = { k: v/shots for k,v in H1.get_counts().items()}\n scaledH2 = { k: v/shots for k,v in H2.get_counts().items()}\n scaledH3 = { k: v/shots for k,v in H3.get_counts().items()}\n\n for state in states:\n if state not in scaledH1:\n scaledH1[state] = 0.0\n if state not in scaledH2:\n scaledH2[state] = 0.0\n if state not in scaledH3:\n scaledH3[state] = 0.0\n\n X1 = scaledH1['00']+scaledH1['10'] - (scaledH1['01']+scaledH1['11'])\n X2 = scaledH2['00']+scaledH2['01'] - (scaledH2['10']+scaledH2['11'])\n Z1Z2 = scaledH3['00'] + scaledH3['11'] - scaledH3['01'] - scaledH3['10']\n en = -(X1+X2)+0.5*U*Z1Z2\n\n print('X1',X1,scaledH1)\n print('X2',X2,scaledH2)\n print('Z1Z2',Z1Z2,scaledH3)\n print('En',en)\n\n return en\n\n\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n import pickle\n data = {'M1': [], 'M2': []}\n Us = [0,1,2,3,4,5,6]\n data['U'] = Us\n for U in Us:\n q,c,Q = setup() #for measuring \n ground_state(q,Q)\n adiabatic_evolution(q,Q,0.1,0.1,U)\n res1 = measure(q,c,Q,'X1')\n\n q,c,Q = setup() #for measuring \n ground_state(q,Q)\n adiabatic_evolution(q,Q,0.1,0.1,U)\n res2 = measure(q,c,Q,'X2')\n\n q,c,Q = setup() #for measuring \n ground_state(q,Q)\n adiabatic_evolution(q,Q,0.1,0.1,U)\n res3 = measure(q,c,Q,'Z1Z2')\n E = analyze(res1,res2,res3,U)\n data['M1'].append(E)\n\n for U in Us:\n q,c,Q = setup() #for measuring \n ground_state(q,Q)\n if U != 0:\n adiabatic_evolution(q,Q,0.25,1.25/U,5)\n else:\n M2_adiabatic_evolution(q,Q,0.25,5)\n res1 = measure(q,c,Q,'X1')\n\n q,c,Q = setup() #for measuring \n ground_state(q,Q)\n if U != 0:\n adiabatic_evolution(q,Q,0.25,1.25/U,5)\n else:\n M2_adiabatic_evolution(q,Q,0.25,5)\n\n res2 = measure(q,c,Q,'X2')\n q,c,Q = setup() #for measuring \n ground_state(q,Q)\n if U != 0:\n adiabatic_evolution(q,Q,0.25,1.25/U,5)\n else:\n M2_adiabatic_evolution(q,Q,0.25,5)\n res3 = measure(q,c,Q,'Z1Z2')\n E = analyze(res1,res2,res3,U)\n\n data['M2'].append(E)\n\n #plt.scatter(data['U'],data['M1'],label='M1')\n #plt.scatter(data['U'],data['M2'],label='M2')\n #plt.plot(np.linspace(0,6,100),exact(np.linspace(0,6,100)),label='exact')\n #plt.legend()\n #plt.show()\n with open('ibmqx4.p','wb') as f:\n pickle.dump(data,f)\n","repo_name":"MitasGroup/QCTools","sub_path":"2-site-hubbard.py","file_name":"2-site-hubbard.py","file_ext":"py","file_size_in_byte":4393,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"26616778591","text":"import numpy as np\n\ndef func(x):\n return np.sum([(-1*x[0]) * np.sin(np.sqrt(np.abs(x[0]))), (-1*x[1]) * np.sin(np.sqrt(np.abs(x[1])))])\n\n# print(\"(-400, -400): \", func([-400,-400]))\n# print(\"(-410, -410): \", func([-410,-410]))\n# print(\"(-415, -415): \", func([-415,-415]))\n\n#to update the first time for the exercise, noting that individual best are the individuals and alphas, r's are given\ndef update_rule_once(x, v, omega, best):\n # r1 = r2 = r\n r = 0.5\n #a1 = a2 = a\n alpha = 1\n new_v = omega * v + alpha * r * (best - x) \n x = x + new_v\n for i in range(2):\n if x[i] > 500:\n x[i] = 500\n elif x[i] < -500:\n x[i] = -500\n return x \n\n#initial positions\nx1 = np.array([-400,-400])\nx2 = np.array([-410,-410])\nx3 = np.array([-415,-415])\n\n#velocities\nv1 = np.array([-50,-50])\nv2 = np.array([-50,-50])\nv3 = np.array([-50,-50])\n\nfor om in [2,0.5,0.1]:\n print(\"Value of omega: \", om)\n x1_up = update_rule_once(x1,v1, om, x3)\n print(\"x1 After first update: \", x1_up, \"fitness: \", func(x1_up))\n x2_up = update_rule_once(x2,v1, om, x3)\n print(\"x2 After first update: \", x2_up, \"fitness: \", func(x2_up))\n x3_up = update_rule_once(x3,v1, om, x3)\n print(\"x3 After first update: \", x3_up, \"fitness: \", func(x3_up))\n\n\n","repo_name":"gerwindekruijf/NaturalComputing","sub_path":"Exs2/ex2_1.py","file_name":"ex2_1.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"43700669857","text":"from OpenGL.GL import *\nfrom OpenGL.GLU import *\nfrom OpenGL.GLUT import *\nimport matplotlib.image as PngImage\nimport numpy as np\nimport math\n\n\n\ndef Bottle_Function(x):\n m = 0.25\n n = 0.5\n c = 5/4*math.pi\n return m * math.sin(x+c) + n\n\n\nclass Bottle:\n def __init__(self):\n self.texture = glGenTextures(1)\n\n # 初始化光线\n parray = [-1.5, -2, 0.5, 1.0]\n sarray = [1.0, 1.0, 1.0, 0.7]\n glLightfv(GL_LIGHT0, GL_POSITION, parray)\n glLightfv(GL_LIGHT0, GL_DIFFUSE, sarray)\n glEnable(GL_LIGHTING)\n glEnable(GL_LIGHT0)\n\n # 设置texture\n img = PngImage.imread('TexturesCom_WindowsBacklit0016_M.jpg')\n img = np.asarray(img * 255, dtype=np.uint8)\n color = GL_RGBA\n glBindTexture(GL_TEXTURE_2D, self.texture)\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP | GL_REPEAT)\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP | GL_REPEAT)\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)\n glTexImage2D(GL_TEXTURE_2D, 0, color, img.shape[0], img.shape[1], 0, color, GL_UNSIGNED_BYTE, img)\n glEnable(GL_TEXTURE_2D)\n\n # 初始化setting\n glEnable(GL_DEPTH_TEST)\n glEnable(GL_POLYGON_SMOOTH)\n\n\n def Circle(self, z, r, tex=True):\n if not tex:\n glDisable(GL_TEXTURE_2D)\n glBegin(GL_POLYGON)\n glNormal3f(0.0, 0.0, 1.0)\n for a in range(0, 360,2):\n theta = a * math.pi / 180\n x = math.sin(theta)\n y = math.cos(theta)\n if tex:\n glTexCoord2fv([x, y])\n glVertex3fv([x * r, y * r, z])\n glEnd()\n\n if not tex:\n glEnable(GL_TEXTURE_2D)\n\n # 自变量 R, 因变量 圆的半径 在每一个位置R, 画出不同半径的圆\n def Draw_Process(self):\n delta = 1 / 512\n R = 0.9\n z = -R\n while z <= -R + 4 * delta:\n l = (z + R) / R * math.pi\n r = Bottle_Function(l)/2\n self.Circle(z=z, r=r, tex=False)\n z += delta\n while z <= -R/4:\n r = Bottle_Function(0)/2\n self.Circle(z=z, r=r)\n z += delta\n while z <= 0:\n l = (-z*2 + R/2) / R * math.pi - 5/4*math.pi\n r = Bottle_Function(l)/2 - Bottle_Function(3/4*math.pi)/2 + Bottle_Function(0)/2\n self.Circle(z=z, r=r)\n z += delta\n while z <= R:\n self.Circle(z=z, r=r)\n z += delta\n\n def start(self):\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n glPushMatrix()\n glMatrixMode(GL_MODELVIEW)\n glRotatef(125.0, 1.0, 0.0, 0.0)\n self.Draw_Process()\n glPopMatrix()\n glFlush()\n\nif __name__ == \"__main__\":\n glutInit()\n glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH)\n glutInitWindowSize(768, 768)\n glutCreateWindow('MyBottle')\n MyBottle = Bottle()\n glutDisplayFunc(MyBottle.start)\n glutMainLoop()","repo_name":"Caotingjia/-Project","sub_path":"曹庭嘉-16307130302/曹庭嘉Project2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"43110962672","text":"# This module is to update the model with remote commands.\n\n# Import Python Libs\nfrom __future__ import absolute_import\nimport logging\nimport os\nimport json\n\n# Local imports\nfrom . import keyring\nfrom . import utils\nfrom . import util_which\nfrom . import constants\n\n\nlog = logging.getLogger(__name__)\n\n\nclass Error(Exception):\n \"\"\"\n Error\n \"\"\"\n\n def __str__(self):\n doc = self.__doc__.strip()\n return ': '.join([doc] + [str(a) for a in self.args])\n\n\nclass connection():\n \"\"\"\n Basic connection tool.\n \"\"\"\n def __init__(self, model):\n self.model = model\n\n\n def arguments_get(self):\n if not self.has_connected():\n self.connect()\n if self.has_connected():\n return [\n '--connect-timeout',\n '%s' % (constants.ceph_remote_call_timeout),\n \"--keyring\",\n self.model.connection.keyring_path,\n \"--name\",\n self.model.connection.keyring_identity,\n ]\n raise Error(\"Failed to connect to cluster\")\n\n\n def has_connected(self):\n if self.model.connection.keyring_type is None:\n return False\n if self.model.connection.keyring_path is None:\n return False\n if self.model.connection.keyring_identity is None:\n return False\n return True\n\n\n def connect(self):\n if self.has_connected() is True:\n return True\n keyring_obj = keyring.keyring_facard(self.model)\n for keytype in [\"admin\", \"osd\", \"mds\", \"rgw\", \"mon\"]:\n log.debug(\"Trying keyring:%s\" % (keytype))\n keyring_obj.key_type = keytype\n keyring_path = keyring_obj.keyring_path_get()\n if not os.path.isfile(keyring_path):\n log.debug(\"Skipping keyring %s\" % (keyring_path))\n continue\n keyring_identity = keyring_obj.keyring_identity_get()\n arguments = [\n util_which.which_ceph.path,\n '--connect-timeout',\n '%s' % (constants.ceph_remote_call_timeout),\n \"--keyring\",\n keyring_path,\n \"--name\",\n keyring_identity,\n \"-f\",\n \"json-pretty\",\n \"status\"\n ]\n output = utils.execute_local_command(arguments)\n if output[\"retcode\"] != 0:\n continue\n self.model.cluster_status = json.loads(output[\"stdout\"].strip())\n self.model.connection.keyring_type = keytype\n self.model.connection.keyring_path = keyring_path\n self.model.connection.keyring_identity = keyring_identity\n return True\n return False\n","repo_name":"oms4suse/python-ceph-cfg","sub_path":"ceph_cfg/remote_connection.py","file_name":"remote_connection.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"20"} +{"seq_id":"42190304707","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # 인공지능 \n# * MNIST 데이터셋 학습 모델 정확도 99%올리기\n\n# # 1. Library\n\n# In[1]:\n\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.init as init\nimport torchvision.datasets as dataset # for loading dataset (mnist)\nimport torchvision.transforms as transforms # for processing datasets\nfrom torch.utils.data import DataLoader # for making dataset easier to use \n\nfrom matplotlib import pyplot as plt\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint(\"device: gpu\") if torch.cuda.is_available() else print(\"device: cpu\")\n\n\n# # 2. Hyper parameter setting\n\n# In[2]:\n\n\n# hypter parameter setting\nlearning_rate = 1e-4\nepochs = 80\ndisplay_step = 10\nbatch_size = 20\n\n#epochs = 50,batch_size = 16 -->97% (SGD)\n#epochs=80, batch_size=20 -->98% (SGD)\n#epochs=80, batch_size=20 --> (ADAM)\n\nactivation = nn.ReLU()\nmax_pool = nn.MaxPool2d(2,2) # kerel size, stride size, padding size \n\n\n# # 3. Load data & Pre-process data\n\n# In[3]:\n\n\n# load data\ntrain_data = dataset.MNIST(\"./\", train = True, transform = transforms.ToTensor(), target_transform = None, download = True)\ntest_data = dataset.MNIST(\"./\", train = False, transform = transforms.ToTensor(), target_transform = None, download = True)\n\n# check the data\nprint('len(train_data): ', len(train_data))\nprint('len(test_data): ', len(test_data))\n\nx_train, y_train = train_data[0]\nprint('data', x_train)\nprint('data shape: ', x_train.shape)\nprint('label: ', y_train)\n\nplt.figure()\nplt.imshow(x_train[0])\nplt.show()\n\n# Pre-process (batch, shuffle)\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size = batch_size, shuffle = True, num_workers = 1, drop_last = True)\ntest_loader = torch.utils.data.DataLoader(test_data, batch_size = batch_size, shuffle = True, num_workers = 1, drop_last = True)\n\n# check the data \nexamples = enumerate(train_loader)\nbatch_idx, (example_data, example_target) = next(examples)\n\nprint('data shape:', example_data.shape)\nprint('label:', example_target)\n\nplt.figure()\nplt.imshow(example_data[0][0])\nplt.show()\n\n\n# # 4. Model & Optimization and Loss function\n\n# In[5]:\n\n\nclass CNN(nn.Module):\n def __init__(self):\n super(CNN, self).__init__() # for initializing nn.Module (parent class)\n self.feature_extraction = nn.Sequential(\n nn.Conv2d(1, 16, 5), # number of input channel, number of output channel, kernel size \n activation, # we can set stride size and padding size. if we do not set the these parameters, default value is 1, 0.\n nn.Conv2d(16, 32,5),\n activation,\n max_pool,\n nn.Conv2d(32,64,5),\n activation,\n max_pool\n )\n self.classifier = nn.Sequential(\n nn.Linear(64 * 3 * 3, 100),\n activation,\n nn.Linear(100, 10)\n )\n def forward(self, x):\n extracted_feature = self.feature_extraction(x) # [32, 64, 3, 3]\n flatten = extracted_feature.view(batch_size, -1) # [32, 576 (64 * 3 * 3)]\n result = self.classifier(flatten)\n return result\n\nmodel = CNN().to(device)\nmodel.train()\nloss_function = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr = learning_rate)\n\n\n# # 5. Train & Test\n\n# In[6]:\n\n\nloss_array = []\n\n# train the model\nfor i in range(epochs):\n for index, [data, label] in enumerate(train_loader):\n data = data.to(device)\n label = label.to(device)\n \n optimizer.zero_grad()\n output = model.forward(data)\n loss = loss_function(output, label)\n loss.backward()\n optimizer.step()\n \n if i % display_step == 0:\n print('{} epoch loss: {}'.format(i,loss))\n loss_array.append(loss.cpu().detach().numpy())\n\n\n# In[7]:\n\n\nplt.figure()\nplt.plot(loss_array)\nplt.show()\n\n\n# In[8]:\n\n\n#test the model\nmodel.eval()\ncorrect = 0\ntotal = 0\n\nprediction_list = []\nlabel_list = []\n\nwith torch.no_grad():\n for index, [data, label] in enumerate(test_loader):\n data = data.to(device)\n label = label.to(device)\n \n output = model.forward(data)\n _, prediction_index = torch.max(output, 1)\n \n prediction_list.append(prediction_index)\n label_list.append(label)\n \n total += label.size(0)\n correct += (prediction_index == label).sum().float()\n\n print(\"Accuracy of the model: {}\".format(correct/total))\n\n\n# # 정확도 99%로 만점 완성 !\n\n# # 6. Advanced: Learning rate scheduler\n\n# In[9]:\n\n\n#learning rate scheduler\nimport torch.optim as optim\n\nloss_function = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\nscheduler = optim.lr_scheduler.StepLR(optimizer, step_size = 1, gamma = 0.99) # this function decreast learning for each step size\n\nfor i in range(epochs):\n scheduler.step()\n for index, [image, label] in enumerate(train_loader):\n x = image.to(device)\n y = label.to(device)\n \n optimizer.zero_grad()\n output = model.forward(x)\n loss = loss_function(output, y)\n loss.backward()\n optimizer.step()\n \n \n if i % display_step ==0:\n print('{} epoch lr: {}'.format(i,scheduler.get_lr()))\n print('{} epoch loss: {}'.format(i,loss))\n loss_array.append(loss.cpu().detach().numpy())\n\n#plot the loss \nplt.figure()\nplt.plot(loss_array)\nplt.show() \n\n#test the model\ncorrect = 0\ntotal = 0\nwith torch.no_grad():\n for index, [data, label] in enumerate(test_loader):\n data = data.to(device)\n label = label.to(device)\n \n output = model.forward(data)\n _, result = torch.max(output, 1)\n \n total += label.size(0)\n correct += (result == label).sum().float()\n\n print(\"Accuracy of the model: {}\".format(correct/total))\n\n","repo_name":"youngbinwoo/AI","sub_path":"Deep Learing/Pytorch_CNN/MNIST.py","file_name":"MNIST.py","file_ext":"py","file_size_in_byte":5891,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"31811329756","text":"\"\"\"\nThis script initializes data to run tests which involves creation of domains, user_gorups,\nusers, client, token etc.\n\n\"\"\"\n# Standard imports\nimport time\nfrom datetime import datetime\n\n# 3rd party imports\nfrom werkzeug.security import gen_salt\n\n# Application specific imports\nfrom user_service.common.constants import INPUT, PRE_DEFINED\nfrom user_service.common.models.misc import CustomField\nfrom user_service.common.models.user import Domain, User, UserGroup, Token, Client, Role\nfrom user_service.common.tests.fake_testing_data_generator import fake\nfrom user_service.modules.constants import NUMBER_OF_SAVED_CUSTOM_FIELDS, TEST_CUSTOM_FIELDS\nfrom user_service.user_app import logger\n\nTEST_PASSWORD = \"pbkdf2:sha512:1000$lf3teYeJ$7bb470eb0a2d10629e4835cac771e51d2b1e9ed577b849c27551ab7b244274a10109c8d7a7b8786f4de176b764d9763e4fd1954ad902d6041f6d46fab16219c6\"\n\n\ndef create_test_domains(names):\n \"\"\"\n This function takes list of domain names, creates domains with given names and then returns domains list.\n :param list | tuple names: list of domain names\n :rtype: tuple[list]\n \"\"\"\n domains = []\n for domain_name in names:\n domain = Domain(name=domain_name)\n Domain.save(domain)\n logger.debug('create_test_domain: Created a test domain with name %s', domain.name)\n domains.append(domain)\n return domains, [domain.id for domain in domains]\n\n\ndef create_user_groups(group_names, domain_ids):\n \"\"\"\n This function creates user groups in database. It takes group names ad domain ids as input.\n :param list(string) group_names: user group names\n :param list(int | long) domain_ids: domain ids\n :rtype: tuple[list]\n \"\"\"\n assert len(group_names) == len(domain_ids), 'group names and domain ids should be equal'\n groups = []\n for group_name, domain_id in zip(group_names, domain_ids):\n user_group = UserGroup.get_by_name(group_name)\n if not user_group:\n user_group = UserGroup.add_groups([{'name': group_name}], domain_id)[0]\n logger.debug('create_user_groups: Created a user group: %s', user_group.name)\n groups.append(user_group)\n return groups, [group.id for group in groups]\n\n\ndef create_test_user(email, domain_id, group_id):\n \"\"\"\n This function creates a test user with given domain and group with `TEST_ADMIN` as role.\n :param string email: user's email address\n :param int | long domain_id: user's domain id\n :param int | long group_id: user's group id\n :rtype: User\n \"\"\"\n user = User.get_by_email(email)\n role = Role.get_by_name('TEST_ADMIN')\n if not user:\n user = User(email=email, domain_id=domain_id, user_group_id=group_id, password=TEST_PASSWORD, role_id=role.id)\n User.save(user)\n logger.debug('create_test_user: Created a test user: %s', user.name)\n return user\n\n\ndef create_user_with_domain_admin_role(domain_id, group_id):\n \"\"\"\n This function creates a test user with given domain and group with `TEST_ADMIN` as role.\n :param int | long domain_id: user's domain id\n :param int | long group_id: user's group id\n :rtype: User\n \"\"\"\n timestamp = str(time.time()) + gen_salt(10)\n role = Role.get_by_name('DOMAIN_ADMIN')\n user = User(email=fake.word() + timestamp, domain_id=domain_id, user_group_id=group_id, password=TEST_PASSWORD, role_id=role.id)\n User.save(user)\n logger.debug('create_test_user: Created a test user: %s', user.name)\n return user\n\n\ndef create_test_client(client_id, client_secret):\n \"\"\"\n This function creates a test client.\n :param string client_id: client unique id\n :param string client_secret: client secret\n :rtype: Client\n \"\"\"\n client = Client(client_id=client_id, client_secret=client_secret, client_name='test_client')\n return Client.save(client)\n\n\ndef create_test_token(user_id, client_id):\n \"\"\"\n This function creates a access token for given test user.\n :param int | long user_id: user primary id\n :param string client_id: client unique id\n :rtype: Token\n \"\"\"\n\n token = Token(client_id=client_id, user_id=user_id, token_type='Bearer',\n access_token=gen_salt(60),\n refresh_token=gen_salt(60), expires=datetime(2020, 12, 31))\n return Token.save(token)\n\n\ndef create_test_custom_fields(domain_id):\n for custom_field in TEST_CUSTOM_FIELDS:\n custom_field = CustomField(domain_id=domain_id, name=custom_field['name'], type=custom_field['type'],\n added_time=datetime.now())\n CustomField.save(custom_field)\n custom_fields = CustomField.get_domain_custom_fields(domain_id)\n items = [custom_field.to_json() for custom_field in custom_fields]\n return {'custom_fields': items}\n\n\ndef create_test_data():\n \"\"\"\n To create test data (Domains, Users, Groups, Client, Token etc.)\n :rtype: dict\n \"\"\"\n timestamp = str(time.time()) + gen_salt(10)\n # Create two domains\n domain_names = [\"test_domain_first\", \"test_domain_second\"]\n domain_names = [name + timestamp for name in domain_names]\n domains, domain_ids = create_test_domains(domain_names)\n\n # # Create user groups\n group_names = [\"test_group_first\", \"test_group_second\"]\n group_names = [group_name + timestamp for group_name in group_names]\n groups, group_ids = create_user_groups(group_names, domain_ids)\n\n # Create 3 users\n\n user_emails = [(\"test_email@test.com\", \"test_email_same_domain@test.com\"), (\"test_email_second@test.com\",)]\n user_emails = [(timestamp + email for email in domain_emails) for domain_emails in user_emails]\n user_data = zip(user_emails, domain_ids, group_ids)\n\n users = []\n for emails, domain_id, group_id in user_data:\n for email in emails:\n users.append(create_test_user(email, domain_id, group_id))\n\n # Creating user with domain_admin role\n users.append(create_user_with_domain_admin_role(domain_ids[0], group_ids[0]))\n user_ids = [user.id for user in users]\n\n # Create client\n client_id = gen_salt(40)\n client_secret = gen_salt(55)\n client = create_test_client(client_id, client_secret)\n\n tokens = []\n # Create token for all test users\n for user_id in user_ids:\n tokens.append(create_test_token(user_id, client_id))\n\n # Creating Custom Fields\n custom_fields = create_test_custom_fields(users[0].domain_id)\n\n return {\n 'domains': [domain.to_json() for domain in domains],\n 'users': [user.to_json(include_fields=('id', 'domain_id', 'email', 'role_id',\n 'user_group_id')) for user in users],\n 'groups_ids': group_ids,\n 'client': client.to_json(),\n 'tokens': [token.to_json() for token in tokens],\n 'custom_fields': custom_fields\n }\n","repo_name":"josepharceneaux/ecs-stuff","sub_path":"user_service/modules/generate_test_data.py","file_name":"generate_test_data.py","file_ext":"py","file_size_in_byte":6794,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"13513452018","text":"import py_rootbox as rb\nimport math\n\n\n#\n#\n#\nclass My_Soil(rb.SoilLookUp):\n\n def getValue(self, pos, root):\n print(pos.z)\n return 0.1 + abs(pos.z / 100.)\n\n def __str__(self):\n return \"mysoil\"\n\n\nrs = rb.RootSystem()\nname = \"Anagallis_femina_Leitner_2010\"\nrs.openFile(name)\n\nsoil = My_Soil()\n\n# Manually set scaling function and tropism parameters\nsigma = [0.4, 1., 1., 1., 1. ] * 2\nfor i in range(0, 10):\n p = rs.getRootTypeParameter(i + 1)\n p.dx = 0.25 # adjust resolution\n p.tropismS = sigma[i]\n p.ln = p.ln / 10\n p.nob = p.nob * 10\n p.lns = 0 # variation comes with branching propability anyway\n p.sbp = soil\n\n# Simulation\nrs.initialize()\nsimtime = 120.\ndt = 1.\nN = simtime / dt\nfor i in range(0, round(N)):\n rs.simulate(dt, True)\n\nrs.write(\"results/example_depth_branching.vtp\") # root system\n\n","repo_name":"Plant-Root-Soil-Interactions-Modelling/CPlantBox","sub_path":"tutorial/examples/drafts/example_depth_branching.py","file_name":"example_depth_branching.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"20"} +{"seq_id":"18249301934","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('course', '0010_auto_20151214_1714'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='coursechapter',\n name='parent',\n field=models.ForeignKey(to='course.CourseChapter', blank=True, null=True, related_name='children', on_delete=models.CASCADE),\n preserve_default=True,\n ),\n migrations.AlterUniqueTogether(\n name='coursechapter',\n unique_together=set([]),\n ),\n ]\n","repo_name":"apluslms/a-plus","sub_path":"course/migrations/0011_auto_20151215_1133.py","file_name":"0011_auto_20151215_1133.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"20"} +{"seq_id":"25350468927","text":"from invoke import task\n\nfrom tasks.common import VENV_PREFIX\n\nENV_VAR_PREFIX = \"SITE_URL=http://127.0.0.1:8000 \"\n\n\n@task(optional=[\"clean\"])\ndef build(ctx, clean=True, local=True):\n \"\"\"Build documentation\"\"\"\n argument = \"\"\n if clean:\n argument += \" --clean\"\n\n cmd = f\"{VENV_PREFIX} mkdocs build {argument}\"\n if local:\n cmd = f\"{ENV_VAR_PREFIX}{cmd}\"\n\n ctx.run(cmd)\n\n\n@task(default=True)\ndef serve(ctx, local=True):\n \"\"\"Run local server\"\"\"\n cmd = f\"{VENV_PREFIX} mkdocs serve\"\n if local:\n cmd = f\"{ENV_VAR_PREFIX}{cmd}\"\n ctx.run(cmd)\n\n\n@task\ndef deploy(ctx):\n \"\"\"Deploy to github page\"\"\"\n ctx.run(f\"{VENV_PREFIX} mkdocs gh-deploy\")\n","repo_name":"Lee-W/bahamut_ani_stat","sub_path":"tasks/doc.py","file_name":"doc.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"20"} +{"seq_id":"25412306557","text":"import csv\nimport argparse\nfrom Person import Person\nfrom PersonDAO import PersonDAO\ndef main(csv_file):\n \n dao = PersonDAO('persons.db')\n with open(csv_file, newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n del row[\"id\"]\n p = Person(**row)\n dao.save(p)\n\n\n \n\n\nif __name__=='__main__':\n p = argparse.ArgumentParser()\n p.add_argument('csv_file',help=\"csv_file\")\n args =p.parse_args()\n \n main(args.csv_file)\n\n","repo_name":"fgaurat/pythonperf_18092023","sub_path":"tp08/main_insert.py","file_name":"main_insert.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"4069112278","text":"import aipy \nimport capo as C\nimport sys\nimport numpy as np\nimport bm_prms \nimport healpy as hp\n\nu_old=np.load('u_old.npy')/3.0;v_old=np.load('v_old.npy')/3.0;w_old=np.load('w_old.npy')/3.0\nnside=256\nnpix = hp.nside2npix(nside)\nipix=np.arange(npix)\nlmax=3*nside - 1;l,m = hp.Alm.getlm(lmax)\ntheta,phi = hp.pix2ang(nside,ipix)\ns=np.array(hp.pix2vec(nside,ipix))\ntx=s[0];ty=s[1];tz=s[2]\n\nfreqs=np.linspace(0.117,0.182,num=203)#aipy likes GHz units.[0:4]\nnfreq=freqs.size\nnu = np.outer(np.linspace(117e6,182e6,num=nfreq),np.ones(npix))\nc=3e8\ndef rotate_hmap(map,rot):\n\tnpix = map.shape[0]\n\tnside = hp.npix2nside(npix)\n\n\trotmap = np.zeros(npix)\n\tipix = np.arange(npix)\n\tt,p = hp.pix2ang(nside,ipix)\n\n\tr = hp.Rotator(rot=rot)\n\n\t# For each pixel in the new map, find where it would have come \n\t# from in the old \n\ttrot,prot = r(t,p)\n\tipix_rot = hp.ang2pix(nside,trot,prot)\n\n\trotmap = map[ipix_rot]\n\n\treturn rotmap\n\n\nbeams = np.zeros((freqs.shape[0],npix))#selected only few frequency channels\nfor i, freq in enumerate(freqs):\n\tbm = bm_prms.prms['beam'](np.array([freq]),nside=nside,lmax=20,mmax=20,deg=7)\n\tbm.set_params(bm_prms.prms['bm_prms'])\n\tpx = range(hp.nside2npix(nside))\n\txyz = hp.pix2vec(nside,px)\n\tpoly = np.array([h.map[px] for h in bm.hmap])\n\tAxx = np.polyval(poly,freq)\n\tAxx = np.where(xyz[-1] >= 0, Axx, 0)\n\tAxx /= Axx.max()\n\tAxx = Axx*Axx\n\tbeams[i,:] = rotate_hmap(Axx,[21,120]) #[0,0]=north pole, [0,90]=equator, [21,120]=about right for PAPER\n\t\nnp.save('XX_beam_maps.npy',beams)\nbeam = beams\n###calculating blm's at single frequency\n\nblm=np.zeros((u_old.size,l.size),dtype='complex128')\nfor i in range(u_old.size):\n\tblm[i]=hp.map2alm(beam[100]*np.exp(-2j*np.pi*nu[100][0]/c*(u_old[i]*tx+v_old[i]*ty+w_old[i]*tz)),lmax=lmax)\nnp.save('blm_freq150.npy',blm)\t\n\t\n\n\n\n\n\n\n\n\n\t\n","repo_name":"tamiratgebeyehu/analysis_scripts_for_project_with_bigdata","sub_path":"paper_primary_beam.py","file_name":"paper_primary_beam.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"1716753003","text":"#dicionary as structure\nconfis = {\n \"browser\":\"opera\",\n \"aut\":\"google site\",\n \"test\": \"smoke\",\n \"log\": True\n}\n\n\ndef func_var1():\n name: str = \"phuccd\"\n salary: int = 1500\n print(\"Hello world\")\n print(\"name is: \" + name )\n print(\" salary is \", + salary )\n\nfunc_var1()\n\ndef getDic(key):\n return confis.get(key)\n\nprint(getDic(\"browser\"))","repo_name":"CDXRACI/learnning","sub_path":"python_testautomation/functions/func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"23423021966","text":"import pytest\nfrom http import HTTPStatus\nfrom pbench.server.api.resources.query_apis.controllers_list import ControllersList\nfrom pbench.test.unit.server.query_apis.commons import Commons\n\n\nclass TestControllersList(Commons):\n \"\"\"\n Unit testing for resources/ControllersList class.\n\n In a web service context, we access class functions mostly via the\n Flask test client rather than trying to directly invoke the class\n constructor and `post` service.\n \"\"\"\n\n @pytest.fixture(autouse=True)\n def _setup(self, client):\n super()._setup(\n cls_obj=ControllersList(client.config, client.logger),\n pbench_endpoint=\"/controllers/list\",\n elastic_endpoint=\"/_search?ignore_unavailable=true\",\n payload={\n \"user\": \"drb\",\n \"access\": \"private\",\n \"start\": \"2020-08\",\n \"end\": \"2020-10\",\n },\n empty_es_response_payload=self.EMPTY_ES_RESPONSE_PAYLOAD,\n )\n\n @pytest.mark.parametrize(\n \"user\", (\"drb\", \"badwolf\", \"no_user\"),\n )\n def test_query(\n self,\n client,\n server_config,\n query_api,\n find_template,\n build_auth_header,\n user,\n pbench_token,\n ):\n \"\"\"\n Check the construction of Elasticsearch query URI and filtering of the response body.\n The test will run once with each parameter supplied from the local parameterization,\n and, for each of those, multiple times with different values of the build_auth_header fixture.\n \"\"\"\n\n # By default, ask for all \"private\" data for the \"user\" parameter; we\n # expect success when \"user\" matches our authentication token user\n # (drb) or when the authentication token is an administrator. These\n # cases are injected via the `build_auth_header` fixture.\n payload = {\n \"user\": user,\n \"access\": \"private\",\n \"start\": \"2020-08\",\n \"end\": \"2020-10\",\n }\n\n # \"no_user\" means omitting the \"user\" parameter entirely, which means\n # asking for data for all users. We add \"access\": \"public\" so that\n # we can expect success regardless of the authenticated user.\n if user == \"no_user\":\n del payload[\"user\"]\n payload[\"access\"] = \"public\"\n\n response_payload = {\n \"took\": 1,\n \"timed_out\": False,\n \"_shards\": {\"total\": 1, \"successful\": 1, \"skipped\": 0, \"failed\": 0},\n \"hits\": {\n \"total\": {\"value\": 2, \"relation\": \"eq\"},\n \"max_score\": None,\n \"hits\": [],\n },\n \"aggregations\": {\n \"controllers\": {\n \"doc_count_error_upper_bound\": 0,\n \"sum_other_doc_count\": 0,\n \"buckets\": [\n {\n \"key\": \"unittest-controller1\",\n \"doc_count\": 2,\n \"runs\": {\n \"value\": 1.59847315581e12,\n \"value_as_string\": \"2020-08-26T20:19:15.810Z\",\n },\n },\n {\n \"key\": \"unittest-controller2\",\n \"doc_count\": 1,\n \"runs\": {\n \"value\": 1.6,\n \"value_as_string\": \"2020-09-26T20:19:15.810Z\",\n },\n },\n ],\n }\n },\n }\n\n index = self.build_index(\n server_config, self.date_range(self.payload[\"start\"], self.payload[\"end\"])\n )\n\n expected_status = self.get_expected_status(\n payload, build_auth_header[\"header_param\"]\n )\n response = query_api(\n \"/controllers/list\",\n \"/_search?ignore_unavailable=true\",\n payload,\n index,\n expected_status,\n headers=build_auth_header[\"header\"],\n status=expected_status,\n json=response_payload,\n )\n assert response.status_code == expected_status\n if response.status_code == HTTPStatus.OK:\n res_json = response.json\n assert isinstance(res_json, list)\n assert len(res_json) == 2\n assert res_json[0][\"key\"] == \"unittest-controller1\"\n assert res_json[0][\"controller\"] == \"unittest-controller1\"\n assert res_json[0][\"results\"] == 2\n assert res_json[0][\"last_modified_value\"] == 1.59847315581e12\n assert res_json[0][\"last_modified_string\"] == \"2020-08-26T20:19:15.810Z\"\n assert res_json[1][\"key\"] == \"unittest-controller2\"\n assert res_json[1][\"controller\"] == \"unittest-controller2\"\n assert res_json[1][\"results\"] == 1\n assert res_json[1][\"last_modified_value\"] == 1.6\n assert res_json[1][\"last_modified_string\"] == \"2020-09-26T20:19:15.810Z\"\n","repo_name":"rohankumardubey/pbench","sub_path":"lib/pbench/test/unit/server/query_apis/test_controllers_list.py","file_name":"test_controllers_list.py","file_ext":"py","file_size_in_byte":5110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"41029949082","text":"from mcpi.minecraft import Minecraft\nimport time\nimport math\nmc = Minecraft.create()\n\ntry:\n timer = int(input(\"How long shall we sprint for?: \"))\nexcept:\n mc.postToChat(\"Please enter a valid int for the timer\")\n\nmc.postToChat(\"Ready\")\ntime.sleep(1)\nmc.postToChat(\"Set\")\ntime.sleep(1)\nmc.postToChat(\"Go!\")\n\npos_start = mc.player.getTilePos()\nx_start = pos_start.x\ny_start = pos_start.y\nz_start = pos_start.z\n\nfor t in range(0, timer, 1):\n time.sleep(1)\n mc.postToChat(str(timer - t) + \" seconds left; \" +\n \" X: \" + str(mc.player.getTilePos().x) +\n \" Y: \" + str(mc.player.getTilePos().y) +\n \" Z: \" + str(mc.player.getTilePos().z))\n\npos_end = mc.player.getTilePos()\nx_end = pos_end.x\ny_end = pos_end.y\nz_end = pos_end.z\n\nx_travel = x_end - x_start\ny_travel = y_end - y_start\nz_travel = z_end - z_start\n\nmc.postToChat(\"You travelled \" + str(x_travel) + \" from X\")\nmc.postToChat(\"You travelled \" + str(y_travel) + \" from Y\")\nmc.postToChat(\"You travelled \" + str(z_travel) + \" from Z\")\n\n# Pythagorean calculation\ndistance = math.sqrt(math.pow((x_end - x_start), 2) +\n math.pow((y_end - y_start), 2) +\n math.pow((z_end - z_start), 2))\n\nmc.postToChat(\"You travelled a calculated distance of: \" + str(distance))","repo_name":"t04glovern/pyCraft","sub_path":"chapter04-strings/sprintPythagorean.py","file_name":"sprintPythagorean.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"70310916850","text":"import CM\nimport MeCab\nfrom utility.util import util\nfrom tqdm import tqdm\n\nclass PoetoyCognitiveModelBySA:\n def __init__(self, parameter):\n self._wakati = MeCab.Tagger(\"-Owakati\")\n self._parameter = parameter\n self._sam = CM.SpreadingActivationModel(self._parameter)\n self._util = util()\n \n\n def CognitivePoetory(self, courpusPath):\n with open(courpusPath, mode=\"r\") as f:\n poetry = f.readlines()\n\n for i, line in enumerate(tqdm(poetry)):\n splitWords = self._wakati.parse(line).split()\n #print(splitWords)\n for word in splitWords:\n self._sam.activation(word)\n self._util.saveGraph(self._sam.getLexiconNetwork(), f\"line{i}_network.gml\")\n\n\n ","repo_name":"tkck110213/PoetryModel-Python","sub_path":"source/PCM.py","file_name":"PCM.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"16944635873","text":"'''\nDan Boneh, Xavier Boyen, and Hovav Shacham\n\n| From: \"Short Group Signatures\n| Published in: CRYPTO 2004\n| Available from: n/a\n| Notes: An extended abstract of this paper appeared in Advances in Cryptology (2004)\n\n* type: digital signature scheme\n* setting: Pairing\n\n:Authors: J Ayo Akinyele\n:Date: 12/2010\n'''\nfrom toolbox.pairinggroup import *\nfrom toolbox.PKSig import PKSig\nfrom charm.engine.util import *\nimport sys, random, string\n\ndebug=False\nclass ShortSig(PKSig):\n def __init__(self, groupObj):\n PKSig.__init__(self)\n global group, debug\n group = groupObj\n debug = False\n \n def keygen(self, n):\n g1, g2 = group.random(G1), group.random(G2)\n h = group.random(G1)\n xi1, xi2 = group.random(), group.random()\n\n u,v = h ** ~xi1, h ** ~xi2\n gamma = group.random(ZR)\n w = g2 ** gamma\n gpk = { 'g1':g1, 'g2':g2, 'h':h, 'u':u, 'v':v, 'w':w }\n gmsk = { 'xi1':xi1, 'xi2':xi2 }\n \n x = [group.random(ZR) for i in range(n)]\n A = [gpk['g1'] ** ~(gamma + x[i]) for i in range(n)]\n gsk = {}\n if debug: print(\"\\nSecret keys...\")\n for i in range(n):\n if debug: print(\"User %d: A = %s, x = %s\" % (i, A[i], x[i]))\n gsk[i] = (A[i], x[i]) \n return (gpk, gmsk, gsk)\n \n def sign(self, gpk, gsk, M):\n alpha, beta = group.random(), group.random()\n A, x = gsk[0], gsk[1]\n T1 = gpk['u'] ** alpha\n T2 = gpk['v'] ** beta\n T3 = A * (gpk['h'] ** (alpha + beta))\n \n gamma1 = x * alpha\n gamma2 = x * beta\n r = [group.random() for i in range(5)]\n \n R1 = gpk['u'] ** r[0]\n R2 = gpk['v'] ** r[1]\n R3 = (pair(T3, gpk['g2']) ** r[2]) * (pair(gpk['h'], gpk['w']) ** (-r[0] - r[1])) * (pair(gpk['h'], gpk['g2']) ** (-r[3] - r[4]))\n R4 = (T1 ** r[2]) * (gpk['u'] ** -r[3])\n R5 = (T2 ** r[2]) * (gpk['v'] ** -r[4])\n \n c = group.hash((M, T1, T2, T3, R1, R2, R3, R4, R5), ZR)\n s1, s2 = r[0] + c * alpha, r[1] + c * beta\n s3, s4 = r[2] + c * x, r[3] + c * gamma1\n s5 = r[4] + c * gamma2\n return { 'T1':T1, 'T2':T2, 'T3':T3, 'R3':R3,'c':c, 's_alpha':s1, 's_beta':s2, 's_x':s3, 's_gamma1':s4, 's_gamma2':s5 }\n \n def verify(self, gpk, M, sigma): \n \"\"\"alternative verification check for BGLS04 which allows it to be batched\"\"\"\n c, T1, T2, T3 = sigma['c'], sigma['T1'], sigma['T2'], sigma['T3']\n salpha, sbeta = sigma['s_alpha'], sigma['s_beta']\n sx, sgamma1, sgamma2 = sigma['s_x'], sigma['s_gamma1'], sigma['s_gamma2']\n R3 = sigma['R3']\n \n R1 = (gpk['u'] ** salpha) * (T1 ** -c)\n R2 = (gpk['v'] ** sbeta) * (T2 ** -c)\n R4 = (T1 ** sx) * (gpk['u'] ** -sgamma1)\n R5 = (T2 ** sx) * (gpk['v'] ** -sgamma2)\n if c == group.hash((M, T1, T2, T3, R1, R2, R3, R4, R5), ZR):\n if debug: print(\"c => '%s'\" % c)\n if debug: print(\"Valid Group Signature for message: '%s'\" % M)\n pass\n else:\n if debug: print(\"Not a valid signature for message!!!\")\n return False\n \n if ((pair(T3, gpk['g2']) ** sx) * (pair(gpk['h'],gpk['w']) ** (-salpha - sbeta)) * (pair(gpk['h'], gpk['g2']) ** (-sgamma1 - sgamma2)) * (pair(T3, gpk['w']) ** c) * (pair(gpk['g1'], gpk['g2']) ** -c) ) == R3: \n return True\n else:\n return False\n \n def open(self, gpk, gmsk, M, sigma):\n t1, t2, t3, xi1, xi2 = sigma['T1'], sigma['T2'], sigma['T3'], gmsk['xi1'], gmsk['xi2']\n \n A_prime = t3 / ((t1 ** xi1) * (t2 ** xi2))\n return A_prime\n \ndef main():\n #if ( (len(sys.argv) != 7) or (sys.argv[1] == \"-help\") or (sys.argv[1] == \"--help\") ):\n #sys.exit(\"Usage: python \" + sys.argv[0] + \" [# of valid messages] [# of invalid messages] [size of each message] [prefix name of each message] [name of valid output dictionary] [name of invalid output dictionary]\")\n\n groupObj = PairingGroup(MNT160)\n n = 3 # how manu users in the group\n user = 1 # which user's key to sign a message with\n \n sigTest = ShortSig(groupObj)\n \n (gpk, gmsk, gsk) = sigTest.keygen(n)\n\n message = 'Hello World this is a message!'\n if debug: print(\"\\n\\nSign the following M: '%s'\" % (message))\n \n signature = sigTest.sign(gpk, gsk[user], message)\n \n result = sigTest.verify(gpk, message, signature)\n #if result:\n # print(\"Verify signers identity...\")\n # index = sigTest.open(gpk, gmsk, message, signature)\n # i = 0\n # while i < n:\n # if gsk[i][0] == index:\n # print('Found index of signer: %d' % i)\n # print('A = %s' % index)\n # i += 1\n assert result, \"Signature Failed\"\n if debug: print('Successful Verification!')\n\n '''\n numValidMessages = int(sys.argv[1])\n numInvalidMessages = int(sys.argv[2])\n messageSize = int(sys.argv[3])\n prefixName = sys.argv[4]\n validOutputDictName = sys.argv[5]\n invalidOutputDictName = sys.argv[6]\n\n f_gpk = open('gpk.charmPickle', 'wb')\n pick_gpk = objectToBytes(gpk, groupObj)\n f_gpk.write(pick_gpk)\n f_gpk.close()\n\n validOutputDict = {}\n validOutputDict[0] = {}\n validOutputDict[0]['gpk'] = 'gpk.charmPickle'\n\n invalidOutputDict = {}\n invalidOutputDict[0] = {}\n invalidOutputDict[0]['gpk'] = 'gpk.charmPickle'\n\n for index in range(0, numValidMessages):\n if (index != 0):\n validOutputDict[index] = {}\n validOutputDict[index]['gpk'] = 'gpk.charmPickle'\n\n message = \"\"\n for randomChar in range(0, messageSize):\n message += random.choice(string.printable)\n\n signature = sigTest.sign(gpk, gsk[user], message)\n assert sigTest.verify(gpk, message, signature)\n\n f_message = open(prefixName + str(index) + '_ValidMessage.pythonPickle', 'wb')\n validOutputDict[index]['M'] = prefixName + str(index) + '_ValidMessage.pythonPickle'\n\n f_sig = open(prefixName + str(index) + '_ValidSignature.charmPickle', 'wb')\n validOutputDict[index]['sigma'] = prefixName + str(index) + '_ValidSignature.charmPickle'\n\n pickle.dump(message, f_message)\n f_message.close()\n\n pick_sig = objectToBytes(signature, groupObj)\n\n f_sig.write(pick_sig)\n f_sig.close()\n\n del message\n del signature\n del f_message\n del f_sig\n del pick_sig\n\n #print(validOutputDict)\n\n dict_pickle = objectToBytes(validOutputDict, groupObj)\n f = open(validOutputDictName, 'wb')\n f.write(dict_pickle)\n f.close()\n del dict_pickle\n del f\n\n for index in range(0, numInvalidMessages):\n if (index != 0):\n invalidOutputDict[index] = {}\n invalidOutputDict[index]['gpk'] = 'gpk.charmPickle'\n\n message = \"\"\n for randomChar in range(0, messageSize):\n message += random.choice(string.printable)\n\n signature = sigTest.sign(gpk, gsk[user], message)\n assert sigTest.verify(gpk, message, signature)\n\n f_message = open(prefixName + str(index) + '_InvalidMessage.pythonPickle', 'wb')\n invalidOutputDict[index]['M'] = prefixName + str(index) + '_InvalidMessage.pythonPickle'\n randomIndex = random.randint(0, (messageSize - 1))\n oldValue = message[randomIndex]\n newValue = random.choice(string.printable)\n while (newValue == oldValue):\n newValue = random.choice(string.printable)\n\n if (messageSize == 1):\n message = newValue\n elif (randomIndex != (messageSize -1) ):\n message = message[0:randomIndex] + newValue + message[(randomIndex + 1):messageSize]\n else:\n message = message[0:randomIndex] + newValue\n\n f_sig = open(prefixName + str(index) + '_InvalidSignature.charmPickle', 'wb')\n invalidOutputDict[index]['sigma'] = prefixName + str(index) + '_InvalidSignature.charmPickle'\n\n pickle.dump(message, f_message)\n f_message.close()\n\n pick_sig = objectToBytes(signature, groupObj)\n\n f_sig.write(pick_sig)\n f_sig.close()\n\n del message\n del signature\n del f_message\n del f_sig\n del pick_sig\n\n dict_pickle = objectToBytes(invalidOutputDict, groupObj)\n f = open(invalidOutputDictName, 'wb')\n f.write(dict_pickle)\n f.close()\n del dict_pickle\n del f\n '''\n\nif __name__ == \"__main__\":\n debug = False\n main()\n","repo_name":"JHUISI/auto-tools","sub_path":"auto_batch/archive/codegenCCS12_ARCHIVE/BBS/groupsig_bgls04_var.py","file_name":"groupsig_bgls04_var.py","file_ext":"py","file_size_in_byte":8585,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"20"} +{"seq_id":"71804894130","text":"#K-Means Clustering using Sklearn Datasets_Iris\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n#================================================\r\n#Load Data\r\n#================================================\r\n\r\nfrom sklearn.datasets import load_iris\r\niris = load_iris()\r\nprint(dir(iris))\r\n\r\n#================================================\r\n#Create DataFrame\r\n#================================================\r\n\r\ndfIris = pd.DataFrame(\r\n iris['data'],\r\n columns = ['sepal_length','sepal_width','petal_length','petal_width']\r\n)\r\ndfIris['target'] = iris['target']\r\ndfIris['jenis'] = dfIris['target'].apply(\r\n lambda x: iris['target_names'][x]\r\n)\r\nprint(dfIris.head())\r\n\r\n#================================================\r\n#Split Datasets\r\n#================================================\r\n\r\ndfSetosa = dfIris[dfIris['jenis'] == 'setosa']\r\ndfVersicolor = dfIris[dfIris['jenis'] == 'versicolor']\r\ndfVirginica = dfIris[dfIris['jenis'] == 'virginica']\r\n\r\nprint(dfSetosa)\r\nprint(dfVersicolor)\r\nprint(dfVirginica)\r\n\r\n#================================================\r\n#K-Means Clustering\r\n#================================================\r\n\r\nfrom sklearn.cluster import KMeans\r\nmodel = KMeans(n_clusters = 3, random_state = 0)\r\n\r\n#Training\r\nmodel.fit(dfIris[['petal_length', 'petal_width']])\r\n\r\n#Prediction\r\nprediction = model.predict(dfIris[['petal_length', 'petal_width']])\r\nprint(prediction)\r\ndfIris['prediction'] = prediction\r\nprint(dfIris)\r\n\r\n#Split dataset: dfSetosaP, dfVersicolorP, dfVirginicaP\r\ndfSetosaPredict = dfIris[dfIris['prediction'] == 0]\r\ndfVersicolorPredict = dfIris[dfIris['prediction'] == 2]\r\ndfVirginicaPredict = dfIris[dfIris['prediction'] == 1]\r\n\r\n#Centroids\r\ncentroids = model.cluster_centers_\r\nprint(centroids)\r\n\r\n#================================================\r\n#Plot Original Data vs K-Means Prediction\r\n#================================================\r\n\r\nplt.figure('KMeans_Iris', figsize = (13, 6))\r\n\r\n#Plot Petal Length vs Petal Width (Original)\r\nplt.subplot(121)\r\nplt.scatter(\r\n dfSetosa['petal_length'],\r\n dfSetosa['petal_width'],\r\n color = 'r'\r\n)\r\nplt.scatter(\r\n dfVersicolor['petal_length'],\r\n dfVersicolor['petal_width'],\r\n color = 'lightgreen'\r\n)\r\nplt.scatter(\r\n dfVirginica['petal_length'],\r\n dfVirginica['petal_width'],\r\n color = 'b'\r\n)\r\n\r\n#Plot Centroids (Original)\r\nplt.scatter(\r\n centroids[:,0],\r\n centroids[:,1],\r\n marker = '*',\r\n color = 'y',\r\n s = 300\r\n)\r\n\r\nplt.legend(['Setosa', 'Versicolor', 'Virginica', 'Centroids'])\r\nplt.xlabel('Petal Length (cm)')\r\nplt.ylabel('Petal Width (cm)')\r\nplt.title('Original Data')\r\nplt.grid(True)\r\n\r\n#Plot Petal Length vs Petal Width (Prediction)\r\nplt.subplot(122)\r\nplt.scatter(\r\n dfSetosaPredict['petal_length'],\r\n dfSetosaPredict['petal_width'],\r\n color = 'r'\r\n)\r\nplt.scatter(\r\n dfVersicolorPredict['petal_length'],\r\n dfVersicolorPredict['petal_width'],\r\n color = 'lightgreen'\r\n)\r\nplt.scatter(\r\n dfVirginicaPredict['petal_length'],\r\n dfVirginicaPredict['petal_width'],\r\n color = 'b'\r\n)\r\n\r\n#Plot Centroids (Prediction)\r\nplt.scatter(\r\n centroids[:,0],\r\n centroids[:,1],\r\n marker = '*',\r\n color = 'y',\r\n s = 300\r\n)\r\n\r\nplt.legend(['Setosa', 'Versicolor', 'Virginica', 'Centroids'])\r\nplt.xlabel('Petal Length (cm)')\r\nplt.ylabel('Petal Width (cm)')\r\nplt.title('K-Means Prediction')\r\nplt.grid(True)\r\n\r\n\r\nplt.show()","repo_name":"karinagustina/KMeans_Clustering","sub_path":"KMeans_Iris.py","file_name":"KMeans_Iris.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"5074556263","text":"\nimport os\n\ndef open_file():\n while True:\n try:\n filename_str = input(\"Input a file name: \")\n file_obj = open(filename_str, \"r\")\n break\n # Catches all errors, as there are multiple that can happen when opening files.\n # The error that it catches is, however, specified.\n except Exception as e:\n print(e)\n return file_obj\n\ndef fp_setup(file_pointer):\n file_pointer.seek(0)\n file_pointer.readline()\n file_pointer.readline()\n\ndef get_us_value(fp):\n fp_setup(fp)\n for line in fp:\n if \"United States\" in line[:25]:\n return float(line[-5:])\n\ndef get_min_value_and_state(fp):\n fp_setup(fp)\n min_value = 100.00\n for line in fp:\n state = str(line[:25])\n try:\n percentage = float(line[-5:])\n except(ValueError):\n continue\n if percentage < min_value:\n min_value = percentage\n min_state = state\n return min_state, min_value\n\ndef get_max_value_and_state(fp):\n fp_setup(fp)\n max_value = 0.00\n for line in fp:\n state = str(line[:25])\n try:\n percentage = float(line[-5:])\n except(ValueError):\n continue\n if percentage > max_value:\n max_value = percentage\n max_state = state\n return max_state, max_value\n\ndef display_herd_immunity(fp):\n print(\"\\nStates with insufficient Measles herd immunity.\")\n print(\"{:<25s}{:>5s}\".format(\"State\",\"Percent\"))\n fp_setup(fp)\n for line in fp:\n state = str(line[:25])\n try:\n percentage = float(line[-5:])\n except(ValueError):\n continue\n if percentage < 90.0:\n print(\"{:<25s}{:>5s}%\".format(state, str(percentage)))\n\ndef write_herd_immunity(fp):\n file_obj_out = open(\"herd.txt\", \"w\")\n file_obj_out.write(\"States with insufficient Measles herd immunity.\\n\")\n file_obj_out.write(\"{:<25s}{:>5s}\\n\".format(\"State\",\"Percent\"))\n fp_setup(fp)\n for line in fp:\n state = str(line[:25])\n try:\n percentage = float(line[-5:])\n except(ValueError):\n continue\n if percentage < 90.0:\n file_obj_out.write(\"{:<25s}{:>5s}%\\n\".format(state, str(percentage)))\n file_obj_out.close()\n\ndef main():\n file_pointer = open_file()\n print(file_pointer.readline())\n overall = get_us_value(file_pointer)\n min_state, min_value = get_min_value_and_state(file_pointer)\n max_state, max_value = get_max_value_and_state(file_pointer)\n print(\"Overall US MMR coverage: {}%\".format(overall))\n print(\"State with minimal MMR coverage: {} {}%\".format(min_state.rstrip(), min_value))\n print(\"State with maximum MMR coverage: {} {}%\".format(max_state.rstrip(), max_value))\n display_herd_immunity(file_pointer)\n write_herd_immunity(file_pointer)\n file_pointer.close()\n\nif __name__ == \"__main__\":\n main()","repo_name":"shurj0/CSE-231","sub_path":"Project 5/proj05.py","file_name":"proj05.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72314807410","text":"import face_recognition\nimport numpy\nimport os\nimport csv\n\n# Training the SVC classifier\n\n# The training data would be all the face encodings from all the known images and the labels are their names\nencodings = []\nnames = []\n\n# Training directory\ntrain_dir = os.listdir('./train_dir/')\n\n# Loop through each person in the training directory\nfor i in range(1, len(train_dir), 1):\n pix = os.listdir(\"./train_dir/\" + train_dir[i])\n\n # Loop through each training image for the current train_dir[i]\n # for j in range(0, len(pix), 30):\n j = 0\n for img in pix:\n if j > 300:\n break\n # Get the face encodings for the face in each image file\n face = face_recognition.load_image_file(\"./train_dir/\" + train_dir[i] + \"/\" + img)\n # face = face_recognition.load_image_file(\"./train_dir/\" + train_dir[i] + \"/\" + pix[j])\n face_bounding_boxes = face_recognition.face_locations(face)\n\n #If training image containsv exactly one face\n if len(face_bounding_boxes) == 1:\n print(img + \"...\")\n face_enc = face_recognition.face_encodings(face)[0]\n # Add face encoding for current image with corresponding label (name) to the training data\n encodings.append(face_enc)\n names.append(train_dir[i])\n else:\n print(train_dir[i] + \"/\" + img + \" was skipped and can't be used for training\")\n # print(train_dir[i] + \"/\" + pix[j]+ \" was skipped and can't be used for training\")\n j += 1\n\n# Create and train the SVC classifier\n# print(encodings)\n# print(names)\nnumpy.savetxt(\"encodings.csv\", encodings, delimiter = \",\")\nwith open('names.csv', 'w') as result_file:\n wr = csv.writer(result_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n for name in names:\n wr.writerow([name])","repo_name":"andreidimaano/BTSFacialRecognition","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"20"} +{"seq_id":"40288975138","text":"from typing import List\n\nclass Solution:\n\tdef sortArrayByParity(self, nums: List[int]) -> List[int]:\n\t\t\n\t\ti, j = 0, len(nums) - 1 \n\t\twhile i <= j:\n\t\t\tif nums[i] % 2 != 0:\n\t\t\t\tnums[i], nums[j] = nums[j], nums[i]\n\t\t\t\tj -= 1\n\t\t\telse: i += 1\n\t\treturn nums\n\t\t\n\t\t\t\t\na = Solution()\nnums = [3, 7, 4, 5, 1, 3, 5]\nnums = [3,1,2,4]\nprint(a.sortArrayByParity(nums))\t\t\n\t\t\t\n\n","repo_name":"Mvitimin/Python_algorithms","sub_path":"Sort/sort-array-by-parity.py","file_name":"sort-array-by-parity.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"9651007629","text":"from django.contrib import admin\nfrom .models import Entrepreneur\n\n\nclass EntrepreneurAdmin(admin.ModelAdmin):\n list_display = (\n \"id\",\n \"entrepreneur\",\n \"pitchTitle\",\n \"pitchIdea\",\n \"askAmount\",\n \"equity\",\n \"created_at\",\n \"updated_at\",\n )\n list_filter = (\"entrepreneur\", \"created_at\")\n\n\nadmin.site.register(Entrepreneur, EntrepreneurAdmin)\n","repo_name":"rudrakshi99/XharkTank","sub_path":"entrepreneur/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"73369556850","text":"from os import system\n\nwhile True:\n system('clear')\n cor={'y':'\\033[33m','g':'\\033[32m','off':'\\033[m'}\n n = int(input('Digite um número:{} '.format(cor['y'])))\n\n print('{}O dobro de {} vale: {}{}{}.'.format(cor['off'],n,cor['g'],(n*2),cor['off']))\n print('O triplo de {} vale: {}{}{}.'.format(n,cor['g'],(n*3),cor['off']))\n print('A raiz quadrada de {} vale: {}{:.2f}{}.'.format(n,cor['g'],(n**(1/2)),cor['off']))\n opc = str(input('\\nDeseja continuar?[S/N] '))\n\n if opc in 'Nn':\n break\n","repo_name":"Emerson53na/exercicios-python-3","sub_path":"006 Dobro, Triplo, Raiz Quadrada.py","file_name":"006 Dobro, Triplo, Raiz Quadrada.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"71370925809","text":"import re\nfrom pathlib import Path\nimport pandas as pd\nfrom psyke.utils.logic import pretty_theory\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom psyke import Extractor\nfrom datasets import PATH as DATA_PATH, CensusIncome, BreastCancer\n\nPATH = Path(__file__).parents[0]\nMAX_FEATURES_IN_RULE: int = 20\nMAX_RULES: int = 20\n\n\ndef generate_missing_knowledge():\n\n def generate_knowledge(data_name):\n data = pd.read_csv(DATA_PATH / (data_name + '-data.csv'))\n predictor = DecisionTreeClassifier(max_depth=MAX_FEATURES_IN_RULE, max_leaf_nodes=MAX_RULES)\n train, _ = train_test_split(data, random_state=0, train_size=0.5)\n train_x, train_y = train.iloc[:, :-1], train.iloc[:, -1]\n predictor.fit(train_x, train_y)\n extractor = Extractor.cart(predictor, max_depth=MAX_FEATURES_IN_RULE, max_leaves=MAX_RULES)\n knowledge = extractor.extract(train)\n knowledge = pretty_theory(knowledge)\n # Substitute X =< N.5 with X < N\n knowledge = re.sub(r\"([A-Z][a-zA-Z0-9_]*)[ ]=<[ ]([+-]?([0-9]*))[.]?[0-9]+\", r\"\\g<1> < \\g<2>\", knowledge)\n # Substitute X > N.5 with X > N\n knowledge = re.sub(r\"([A-Z][a-zA-Z0-9_]*)[ ]>[ ]([+-]?([0-9]*))[.]?[0-9]+\", r\"\\g<1> > \\g<2>\", knowledge)\n # Substitute 0.0 with 0 and 1.0 with 1\n knowledge = re.sub(r\"0.0\", r\"0\", knowledge)\n knowledge = re.sub(r\"1.0\", r\"1\", knowledge)\n with open(PATH / (data_name + \".pl\"), \"w\") as text_file:\n text_file.write(knowledge)\n\n generate_knowledge(CensusIncome.name)\n generate_knowledge(BreastCancer.name)\n","repo_name":"pikalab-unibo/ski-qos-jaamas-experiments-2022","sub_path":"knowledge/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"71372218289","text":"def hex_to_binary(hex_string):\n try:\n # Convert the hexadecimal string to an integer\n decimal_number = int(hex_string, 16)\n\n # Convert the decimal number to binary representation\n binary_string = bin(decimal_number)[2:] # [2:] removes the '0b' prefix\n\n return binary_string\n except ValueError:\n raise ValueError(\"Invalid hexadecimal string\")\n\n# Test the function\nif __name__ == \"__main__\":\n hex_input = input(\"Enter a hexadecimal number: \")\n try:\n binary_output = hex_to_binary(hex_input)\n print(\"Binary representation:\", binary_output)\n except ValueError as e:\n print(\"Error:\", e)\n","repo_name":"armancher/some-practicing-codes","sub_path":"hex.py","file_name":"hex.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7059300226","text":"import os\nfrom fastapi import APIRouter\nfrom fastapi.responses import FileResponse\n\n\nrouter = APIRouter(prefix=\"/images\")\n\n\n@router.get(\"/restaurant-image\")\ndef get_restaurant_image(restaurant_name: str, size: int = None):\n if size is None:\n return FileResponse(\n os.path.join(\n \"img\",\n \"restaurant_image\",\n f\"{''.join(restaurant_name.lower().split(' '))}.webp\",\n ),\n media_type=\"image/webp\",\n )\n\n return FileResponse(\n os.path.join(\n \"img\",\n \"restaurant_image\",\n f\"{''.join(restaurant_name.lower().split(' '))}-{size}.webp\",\n ),\n media_type=\"image/webp\",\n )\n\n\n@router.get(\"/dish-image\")\ndef get_dish_image(dish_name: str, size: int = None):\n if size is None:\n return FileResponse(\n os.path.join(\n \"img\",\n \"dishes_image\",\n f\"{''.join(dish_name.lower().split(' '))}-500.webp\", # noqa\n ),\n media_type=\"image/webp\",\n )\n\n return FileResponse(\n os.path.join(\n \"img\",\n \"dishes_image\",\n f\"{''.join(dish_name.lower().split(' '))}-{size}.webp\", # noqa\n ),\n media_type=\"image/webp\",\n )\n","repo_name":"JugBones/indodish-backend","sub_path":"src/images/routers.py","file_name":"routers.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"32311981709","text":"#!/usr/bin/env python3\n\nimport fileinput\n\ndef valid(s):\n s = str(s)\n has_repeat = False\n prev = s[0]\n for c in s[1:]:\n if c < prev:\n return False\n if c == prev:\n has_repeat = True\n prev = c\n return has_repeat\n\ndef count(start, end):\n return sum(1 for i in filter(valid, range(start, end+1)))\n\nfor line in fileinput.input():\n print(count(*map(int, line.split('-'))))\n break\n","repo_name":"balshetzer/AdventOfCode","sub_path":"2019/4a.py","file_name":"4a.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"13477069948","text":"import numpy as np\nimport random\nimport math\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\n\nimport time\nimport datetime as dt\n\nimport os\n\nnp.random.seed(1)\nrandom.seed(1)\n\n# Sidelength of the grid\n# GRID_SIZE = 100\n# decide whether or not to animate the simulation\nANIMATE_SIM = False\n# Generating the grid, with dtype integer\n# grid = np.zeros((GRID_SIZE, GRID_SIZE), dtype=int) + 1\n# grid = (np.random.randint(0, 2, size=(GRID_SIZE, GRID_SIZE)) * 2) - 1\n\ndef accept_change(delta_energy, t_red):\n # calculate the chance given a t_red and change in energy\n p = math.exp(- delta_energy / t_red)\n # generate a random number between 0 and 1. This function is quicker\n # than np.random.rand() by a factor 100.\n num = random.random()\n # equivalent to if p> num: return True, if p <= num: return False\n return p > num\n\n\ndef local_energy_flipped(lattice, x_pos, y_pos, GRID_SIZE):\n # doesn't have a minus sign because lattice[x,y] has been flipped\n # get the left, right, top and bottom spin value\n left = lattice[y_pos, (x_pos - 1) % GRID_SIZE]\n right = lattice[y_pos, (x_pos + 1) % GRID_SIZE]\n top = lattice[(y_pos + 1) % GRID_SIZE, x_pos]\n bottom = lattice[(y_pos - 1) % GRID_SIZE, x_pos]\n # we multiply the spin values with the spin value at x_pos, y_pos\n # factor 2, because we don't want to count anything double\n delta_energy = lattice[y_pos, x_pos] * 2 * (left + right + top + bottom)\n return delta_energy\n\ndef total_energy_simple(lattice, GRID_SIZE):\n lattice_energy = []\n # comments!!!\n for y_pos, lattice_row in enumerate(lattice):\n lattice_row_energy = []\n for x_pos, s_i in enumerate(lattice_row):\n y_energy = lattice[(y_pos+1) % GRID_SIZE, x_pos % GRID_SIZE] + lattice[(y_pos-1) % GRID_SIZE, x_pos % GRID_SIZE]\n x_energy = lattice_row[(x_pos-1) % GRID_SIZE] + lattice_row[(x_pos+1) % GRID_SIZE]\n local_energy = -(x_energy + y_energy)*s_i\n lattice_row_energy.append(local_energy)\n lattice_energy.append(lattice_row_energy) \n # factor 0.5 because we don't want to count double\n return 0.5 * np.sum(lattice_energy)\n \n\ndef total_energy_quick(lattice, GRID_SIZE):\n # initialising empty energy array\n energy = np.zeros_like(lattice)\n # multiplying every spin by it's left neighbour\n energy -= np.take(lattice, np.arange(1, GRID_SIZE + 1), axis=1, mode=\"wrap\")\n # multiplying every spin by it's right neighbour\n energy -= np.take(lattice, np.arange(-1, GRID_SIZE -1), axis=1, mode=\"wrap\")\n # multiplying every spin by it's below neighbour\n energy -= np.take(lattice, np.arange(1, GRID_SIZE + 1), axis=0, mode=\"wrap\")\n # multiplying every spin by it's top neighbour\n energy -= np.take(lattice, np.arange(-1, GRID_SIZE -1), axis=0, mode=\"wrap\")\n\n # factor 0.5 because we don't want to count double\n return 0.5 * np.sum(energy * lattice, dtype=np.int64)\n\n\n# def calc_stop_sim(perc, energy_list, i, index, calc_freq):\n# a = np.average(energy_list[max(i // calc_freq - 50 * (i // index) // calc_freq,0):max(i // calc_freq - 25 * (i // index) // calc_freq,1)])\n# b = np.average(energy_list[max(i // calc_freq - 25 * (i // index) // calc_freq,0):i // calc_freq])\n\n# newperc = np.abs((a-b)/(a) * 100)\n# min_i = max(i // calc_freq - 25 * (i // index) // calc_freq,0)\n# max_i = i // calc_freq\n# # print(a,b)\n# # print(\"{} out of {}, diff = {:.2f}\".format(index, 1000, newperc))\n\n \n# stop = (newperc < 2 and perc < 2)\n# return stop, newperc, (min_i, max_i)\n\ndef simulate(t_red, grid, iterations, calc_freq):\n # initialise equilibrium checkpoints\n # these will be 10k, 30K, 50K, 70K, 100K, 300K, 500K and so forth\n a = [1,3,5,7]\n b = 10**np.arange(4, 8)\n checkpoints = (b[:,np.newaxis]*a).flatten()\n \n # retrieve size of grid\n GRID_SIZE = len(grid[:,0])\n \n # initialise energy and magnetisation, we will update these values\n energy = total_energy_quick(grid, GRID_SIZE)\n mag = np.sum(grid)\n \n # initialise energy and magnetisation lists, to append new values to\n energy_list = []\n mag_list = []\n \n \n \n # initialise the percentage difference between a range of iterations\n # \n old_percentage = 100\n \n for i in range(0, iterations):\n # initialise accept value\n accept_flip = False\n # choosing random coordinates\n rand_x = int(random.random() * GRID_SIZE)\n rand_y = int(random.random() * GRID_SIZE)\n # is the same as\n # rand_x = np.random.randint(0, GRID_SIZE)\n # but about 1000 times as fast\n \n # calculate the difference in energy\n delta_energy = local_energy_flipped(grid, rand_x, rand_y, GRID_SIZE)\n\n # if delta_energy is less than zero, accept the change\n if delta_energy <= 0:\n accept_flip = True\n \n # if delta_energy is more than zero, accept the change\n # with the probability as given in the algorithm\n elif accept_change(delta_energy, t_red):\n accept_flip = True\n # if we accept a flip, we flip the spin and update the energy and\n # magnetisation\n if accept_flip:\n grid[rand_y, rand_x] *= -1\n energy = energy + delta_energy\n mag = mag + 2 * grid[rand_y, rand_x]\n \n # calculate and append all observables, every calc_freq times.\n # this means that our energy_list is calc_freq smaller than the \n # amount of iterations.\n if i % calc_freq == 0:\n \n # append our magnetisation and energy values to their lists\n energy_list.append(energy)\n mag_list.append(mag)\n\n # in checkpoints, there is a list of iteration vallues for which\n # we check if we are in equilibrium.\n # If we are in equilibrium, we will stop the simulation\n \n # initialise stop value\n stop = False\n \n # check if we are at a checkpoint, and if we are, get the \n # location of our value in the checkpoints list\n if i in checkpoints:\n index = np.where(checkpoints == i)[0][0]\n \n # we are going to use index - 2, so make sure we can actually\n # subtract 2.\n if index > 2:\n \n # we create 2 ranges, between min_1 and max_1, and\n # between min_2 and max_2. We divide by calc_freq to\n # keep our indices in line with the smaller size of the\n # energy list.\n # this would for example be between 10k and 30k, and\n # between 30k and 50k\n min_1 = checkpoints[max(index - 2,0)] // calc_freq\n max_1 = checkpoints[max(index-1,0)] // calc_freq\n min_2 = checkpoints[max(index-1,0)] // calc_freq\n max_2 = checkpoints[index] // calc_freq\n \n # the big range, consisting of both smaller ranges\n equilibrium_range = (min(min_1,max_1),max(min_2,max_2))\n \n # calculate the average energies over these ranges\n average_1 = np.average(energy_list[min(min_1,max_1): max(min_1,max_1)])\n average_2 = np.average(energy_list[min(min_2,max_2): max(min_2,max_2)])\n\n # calculate the prercentagewise difference between\n # these energies.\n new_percentage = abs((average_1 - average_2) / average_1 * 100)\n \n # if the difference between the two averages is small,\n # and this was also the case for the previous check,\n # we stop the simulation.\n # this means that over our whole range, our average\n # has not changed much, so we are in equilibrium.\n if new_percentage < 1.6 and old_percentage < 1.6:\n stop = True\n print(\"tred: {} indices: {}\".format(t_red, equilibrium_range))\n break\n # update the old_percentage, so we can use it again\n # next time.\n old_percentage = new_percentage\n print(\"tred: {:.2f} i: {:.4e}, perc: {:.2f}, index: {:.4e}\".format(t_red, i, new_percentage, index))\n # we want to stop the simulation because we are in equilibrium,\n # so we break the iterations loop.\n if stop:\n break\n\n output_data = {\"energy\":energy_list, \"magnetisation\":mag_list, \"grid\":grid}\n return output_data, equilibrium_range\n\ndef calculate_values(en, maglist, indices):\n capacity = np.var(en[indices[0]:indices[1]])\n mag = np.average(maglist[indices[0]:indices[1]])\n mag_abs = np.average(np.abs(maglist[indices[0]:indices[1]]))\n avg_en = np.average(en[indices[0]:indices[1]])\n return capacity, mag, mag_abs, avg_en\n\ndef calc_remaining_time(starttime, cur_iter, max_iter):\n\n telapsed = time.time() - starttime\n testimated = (telapsed/cur_iter)*(max_iter)\n\n finishtime = starttime + testimated\n finishtime = dt.datetime.fromtimestamp(finishtime).strftime(\"%H:%M:%S\") # in time\n\n lefttime = testimated-telapsed # in seconds\n\n return (int(telapsed), int(lefttime), finishtime)\n\ndef multiprocessing_wrapper(GRID_SIZE, temp_reduced, max_iterations, calc_freq, random):\n if random:\n grid = (np.random.randint(0, 2, size=(GRID_SIZE, GRID_SIZE),dtype=int) * 2) - 1\n else:\n grid = np.zeros((GRID_SIZE, GRID_SIZE), dtype=int) + 1\n data, equilibrium_range = simulate(temp_reduced,\n grid,\n max_iterations,\n calc_freq)\n \n capacity, mag, mag_abs, avg_en = calculate_values(data[\"energy\"],\n data[\"magnetisation\"],\n equilibrium_range)\n\n return (temp_reduced, capacity, mag, mag_abs, avg_en)\ndef savearray(relative_path, name, array):\n if not os.path.exists(relative_path):\n os.makedirs(relative_path)\n with open(relative_path + \"/\" + name, \"wb\") as file:\n np.save(file, array)\n \n\ndef sim_multiple(GRID_SIZE,\n temp_steps,\n min_temp,\n max_temp,\n max_iterations,\n calc_freq,\n averages,\n random=False,\n multiprocessing=False):\n \n tredlist = np.linspace(min_temp, max_temp, temp_steps)\n clist = []\n maglist = []\n mag_abslist = []\n enlist = []\n \n resultarr = np.empty((averages, temp_steps, 5))\n \n if multiprocessing:\n import multiprocessing\n from joblib import Parallel, delayed\n num_cores = multiprocessing.cpu_count()\n\n for j in range(0, averages):\n results = np.array(Parallel(\n n_jobs=num_cores, verbose=50)(\n delayed(multiprocessing_wrapper)(\n GRID_SIZE, \n tred, \n max_iterations, \n calc_freq, \n random) for tred in tredlist))\n resultarr[j, :, :] = results\n resultarr = resultarr\n \n if not multiprocessing:\n for avg_index in range(0, averages):\n start = time.time()\n for j, tred in enumerate(tredlist):\n # maybe use the same grid every time?\n if random:\n grid = (np.random.randint(0, 2, size=(GRID_SIZE, GRID_SIZE)) * 2) - 1\n else:\n grid = np.zeros((GRID_SIZE, GRID_SIZE), dtype=int) + 1\n data, equilibrium_range = simulate(tred,\n grid,\n max_iterations,\n calc_freq)\n \n capacity, mag, mag_abs, avg_en = calculate_values(\n data[\"energy\"],\n data[\"magnetisation\"],\n equilibrium_range)\n clist.append(capacity)\n maglist.append(mag)\n mag_abslist.append(mag_abs)\n enlist.append(avg_en)\n \n if j % 5 == 0:\n time_left = calc_remaining_time(start, j+1, temp_steps)\n print(\"time elapsed: %s(s), time left: %s(s), estimated finish time: %s\"%time_left)\n \n results = np.array((tredlist, clist, maglist, mag_abslist, enlist))\n resultarr[avg_index, :, :] = results\n namestring = \"data_{}_{}_{:.1f}-{:.1f}_{}_{}.dat\".format(\n GRID_SIZE,\n temp_steps,\n min_temp,\n max_temp,\n calc_freq,\n averages)\n savearray(\"data\",namestring,resultarr)\n # resultarr[:,:,0] is the temp_reduced list for average 1\n # resultarr[:,:,1] is heat capacity, 2 is magnetisation, 3 is absolute magnetisation, 4 is energy\n # resultarr[1,:,0] gives the temp_reduced for average 2 and so forth\n return resultarr\n\n\n\n# plotting the heat capacity etc. vs. the reduced temperature\n# we give our arguments\nGRID_SIZE = 20\ntemp_steps = 20\nmin_temp = 1\nmax_temp = 4\nmax_iterations = 10**7\ncalc_freq = 10\naverages = 1\n\n# the function with our arguments\nvalues_sim_multiple = sim_multiple(GRID_SIZE,\n temp_steps,\n min_temp,\n max_temp,\n max_iterations,\n calc_freq,\n averages,\n random=False,\n multiprocessing=True)\nt_red = values_sim_multiple[0,:,0]\nheat_capacity = values_sim_multiple[0,:,1]\nheat_capacity_average = np.average(values_sim_multiple[:,:,1],axis=0)\nheat_capacity_stdev = np.std(values_sim_multiple[:,:,1],axis=0)\n\nmagnetisation = values_sim_multiple[0,:,2]\nmagnetisation_average = np.average(values_sim_multiple[:,:,2],axis=0)\nmagnetisation_stdev = np.std(values_sim_multiple[:,:,2],axis=0)\n\nabsolute_magnetisation = values_sim_multiple[0,:,3]\nabsolute_magnetisation_average = np.average(values_sim_multiple[:,:,3],axis=0)\nabsolute_magnetisation_stdev = np.std(values_sim_multiple[:,:,3],axis=0)\n\nenergy = values_sim_multiple[0,:,4]\nenergy_average = np.average(values_sim_multiple[:,:,4],axis=0)\nenergy_stdev = np.std(values_sim_multiple[:,:,4],axis=0)\n\n\nfig,ax = plt.subplots(4, sharex=True, sharey=False, figsize=(5, 15))\n\nif averages == 1:\n ax[0].errorbar(t_red,heat_capacity,fmt='b.')\n ax[1].errorbar(t_red,magnetisation,fmt='r.')\n ax[2].errorbar(t_red,absolute_magnetisation,fmt='k.')\n ax[3].errorbar(t_red,energy,fmt='m.')\nelse:\n ax[0].errorbar(t_red,heat_capacity_average, yerr=heat_capacity_stdev, fmt='b.')\n ax[1].errorbar(t_red,magnetisation_average, yerr=magnetisation_stdev, fmt='r.')\n ax[2].errorbar(t_red,absolute_magnetisation_average, yerr=absolute_magnetisation_stdev, fmt='k.')\n ax[3].errorbar(t_red,energy_average, yerr=energy_stdev,fmt='m.')\n\nax[0].set_ylabel(r'$\\langle C \\rangle$') # fix units\nax[1].set_ylabel(r'$\\langle m \\rangle$') # fix units\nax[2].set_ylabel(r'$\\langle |m| \\rangle$') # fix units\nax[3].set_ylabel(r'$\\langle E \\rangle$') # fix units\n\nfig.savefig(\"data/data_{}_{}_{}-{}_{}_{}.png\".format(\n GRID_SIZE, temp_steps, min_temp, max_temp, calc_freq, averages))\n\n# animating the simulation, needs a different structure\n\ndef init():\n global energy\n global energies\n global xrange\n energy = total_energy_quick(grid)\n im.set_data(grid)\n line.set_xdata(xrange)\n line.set_ydata(energies)\n \n return [im, line]\n\ndef animate(i):\n global energy\n global grid\n global energies\n global xrange\n for j in range(0, 1000):\n accept = False\n # choosing random coordinates\n rand_x = int(random.random() * GRID_SIZE)\n rand_y = int(random.random() * GRID_SIZE)\n # is the same as\n # rand_x = np.random.randint(0, GRID_SIZE)\n # but about 1000 times as fast\n \n # calculate the difference in energy\n delta_energy = local_energy_flipped(grid, rand_x, rand_y)\n \n # if delta_energy is less than zero, accept the change\n # and update the energy\n if delta_energy <= 0:\n energy = energy + delta_energy\n accept = True\n # if delta_energy is more than zero, accept the change\n # with the probability as given in the algorithm\n elif accept_change(delta_energy, t_red):\n energy = energy + delta_energy\n accept = True\n if accept:\n grid[rand_y, rand_x] *= -1\n energies.append(energy)\n xrange.append(i)\n im.set_array(grid)\n line.set_xdata(xrange)\n line.set_ydata(energies)\n # line = [xrange, energies]\n ax[1].set_ylim(min(energies) - 100, max(energies) + 100)\n return [im, line]\n\n\nif ANIMATE_SIM:\n t_red = 5\n \n fig, ax = plt.subplots(1, 2)\n # ax = plt.axes(xlim=(0, GRID_SIZE), ylim=(0, GRID_SIZE))\n # ax[0].set_xlim(0, GRID_S)\n ax[1].set_xlim(0, 1000)\n # ax[1].set_ylim(-GRID_SIZE**2, 0)\n energies = []\n xrange = []\n im=ax[0].imshow(grid,interpolation='none')\n line,=ax[1].plot(xrange, energies)\n # initialization function: plot the background of each frame\n anim = animation.FuncAnimation(fig, animate, init_func=init,\n frames=1000, interval=1)\n","repo_name":"Xetalim/Statfysproject","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":18063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"11869391268","text":"from Deck import Deck, calc_att_plus_hp_for_cards\nfrom States import GameState\nfrom Action import Action\nimport itertools\n\nclass Game:\n def __init__(self, players, state=None, can_print=False, gather_metadata=False):\n self.players = players\n self.state = GameState.generate_starting_state(Deck.generete_deck(20), Deck.generete_deck(20)) if state is None else state\n self.can_print = can_print\n\n def move(self):\n self.state.turn_start()\n self.draw()\n move = []\n mtcs_size = None\n done = False\n while not done:\n if self.players[self.state.player_turn].name == 'MTCSPlayer' or\\\n self.players[self.state.player_turn].name == 'RandomPlayer' or\\\n self.players[self.state.player_turn].name == 'HeuristicPlayer':\n actions = self.players[self.state.player_turn].move(self.state)\n for action in actions:\n print(action) if self.can_print else None\n if len(action) > 1 and action[0] == Action.PlayCard:\n if action[1] not in [c.id for c in self.state.curr_player().hand]:\n continue\n if len(action) > 1 and action[0] == Action.AttackHero:\n if action[1] not in [c.id for c in self.state.curr_player().on_table]:\n continue\n if len(action) > 2:\n if action[2] not in [c.id for c in self.state.other_player().on_table]:\n continue\n\n move.append(action)\n self.state.make_action(*action)\n self.draw()\n done = True\n\n if self.players[self.state.player_turn].name == 'MTCSPlayer':\n mtcs_size = self.players[self.state.player_turn].tree.num_nodes()\n else:\n action = self.players[self.state.player_turn].move(self.state)\n print(action) if self.can_print else None\n if 0 < len(action) <= 3:\n self.state.make_action(*action)\n self.draw()\n else:\n done = True\n self.state.turn_stop()\n\n return move, mtcs_size\n\n def winner_id(self):\n if self.state.player_states[0].hp > 0 and self.state.player_states[1].hp > 0:\n raise Exception('game not finished')\n return 0 if self.state.player_states[0].hp > 0 else 1\n\n def curr_player_id(self):\n return self.state.player_turn\n\n def play(self):\n self.draw()\n moves = []\n sizes = []\n mtcs_num_ppls = []\n other_num_ppls = []\n mtcs_table_scores = []\n other_table_scores = []\n while not self.state.is_done():\n m, mtcs_size = self.move()\n mtcs_num_ppls.append(len(self.state.player_states[0 if self.players[0].name == 'MTCSPlayer' else 1].on_table))\n other_num_ppls.append(len(self.state.player_states[0 if self.players[0].name != 'MTCSPlayer' else 1].on_table))\n mtcs_table_scores.append(calc_att_plus_hp_for_cards(self.state.player_states[0 if self.players[0].name == 'MTCSPlayer' else 1].on_table))\n other_table_scores.append(calc_att_plus_hp_for_cards(self.state.player_states[0 if self.players[0].name != 'MTCSPlayer' else 1].on_table))\n moves.append(m)\n if mtcs_size is not None:\n sizes.append(mtcs_size)\n # input('click enter...')\n winner_id = self.winner_id()\n print('winner chicken dinner: {}{}'.format(self.players[winner_id].name, winner_id)) if self.can_print else None\n return winner_id, list(itertools.chain.from_iterable([[e[0] for e in m] for m in moves if len(m) > 0])), self.state.turn_index // 2 + 1, sizes, mtcs_num_ppls, other_num_ppls, mtcs_table_scores, other_table_scores\n\n def draw(self):\n if not self.can_print:\n return\n print('||||||||||||||||||||||||||||||||||||||||||||||||||||||||')\n strings_to_print = [\n (\"{}{}: HP:{} MANA:{} {}\", lambda i: [self.players[i].name, i, self.state.player_states[i].hp, self.state.player_states[i].mana, 'turn' if self.state.player_turn == i else '']),\n (\"Deck left: {}\", lambda i: [len(self.state.player_states[i].deck)]),\n (\"Hand: {}\", lambda i: [[str(e) for e in self.state.player_states[i].hand]]),\n (\"Table: {}\", lambda i: [[str(e) for e in self.state.player_states[i].on_table]])\n ]\n for i in range(len(self.players)):\n for s, args in strings_to_print if i % 2 == 0 else strings_to_print[::-1]:\n print(s.format(*args(i)))\n print('--------')\n\n\n","repo_name":"olorules/HeartMCTS","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":4775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"1821864844","text":"from __future__ import annotations\n\nfrom builtins import id as identifier\nfrom typing import TYPE_CHECKING, Iterator, NoReturn\nfrom weakref import WeakValueDictionary\n\nfrom travertino.node import Node\n\nfrom toga.platform import get_platform_factory\nfrom toga.style import Pack, TogaApplicator\n\nif TYPE_CHECKING:\n from toga.app import App\n from toga.window import Window\n\n\nclass WidgetRegistry(WeakValueDictionary):\n # WidgetRegistry is implemented as a subclass of WeakValueDictionary, because it\n # provides a mapping from ID to widget. However, it exposes a set-like API; add()\n # and update() take instances to be added, and iteration is over values. The\n # mapping is weak so the registry doesn't retain a strong reference to the widget,\n # preventing memory cleanup.\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def __setitem__(self, key: str, value: Widget) -> NoReturn:\n # We do not want to allow setting items directly but to use the \"add\"\n # method instead.\n raise RuntimeError(\"Widgets cannot be directly added to a registry\")\n\n def update(self, widgets: list[Widget]) -> None:\n for widget in widgets:\n self.add(widget)\n\n def add(self, widget: Widget) -> None:\n if widget.id in self:\n # Prevent from adding the same widget twice\n # or adding 2 widgets with the same id\n raise KeyError(f\"There is already a widget with the id {widget.id!r}\")\n super().__setitem__(widget.id, widget)\n\n def remove(self, id: str) -> None:\n del self[id]\n\n def __iter__(self) -> Iterator[Widget]:\n return iter(self.values())\n\n def __repr__(self) -> str:\n return \"{\" + \", \".join(f\"{k!r}: {v!r}\" for k, v in self.items()) + \"}\"\n\n\nclass Widget(Node):\n _MIN_WIDTH = 100\n _MIN_HEIGHT = 100\n\n def __init__(\n self,\n id: str | None = None,\n style=None,\n ):\n \"\"\"Create a base Toga widget.\n\n This is an abstract base class; it cannot be instantiated.\n\n :param id: The ID for the widget.\n :param style: A style object. If no style is provided, a default style\n will be applied to the widget.\n \"\"\"\n super().__init__(\n style=style if style else Pack(),\n applicator=TogaApplicator(self),\n )\n\n self._id = str(id if id else identifier(self))\n self._window = None\n self._app = None\n self._impl = None\n\n self.factory = get_platform_factory()\n\n def __repr__(self) -> str:\n return f\"<{self.__class__.__name__}:0x{identifier(self):x}>\"\n\n @property\n def id(self) -> str:\n \"\"\"The DOM identifier for the widget.\n\n This id can be used to target CSS directives.\n \"\"\"\n return self._id\n\n @property\n def tab_index(self) -> int | None:\n \"\"\"The position of the widget in the focus chain for the window.\n\n .. note::\n\n This is a beta feature. The ``tab_index`` API may change in\n future.\n \"\"\"\n return self._impl.get_tab_index()\n\n @tab_index.setter\n def tab_index(self, tab_index: int) -> None:\n self._impl.set_tab_index(tab_index)\n\n def _assert_can_have_children(self):\n if not self.can_have_children:\n raise ValueError(f\"{type(self).__name__} cannot have children\")\n\n def add(self, *children: Widget) -> None:\n \"\"\"Add the provided widgets as children of this widget.\n\n If a child widget already has a parent, it will be re-parented as a\n child of this widget. If the child widget is already a child of this\n widget, there is no change.\n\n :param children: The widgets to add as children of this widget.\n :raises ValueError: If this widget cannot have children.\n \"\"\"\n self._assert_can_have_children()\n for child in children:\n if child.parent is not self:\n # remove from old parent\n if child.parent:\n child.parent.remove(child)\n\n # add to new parent\n super().add(child)\n\n # set app and window\n child.app = self.app\n child.window = self.window\n\n self._impl.add_child(child._impl)\n\n # Whatever layout we're a part of needs to be refreshed\n self.refresh()\n\n def insert(self, index: int, child: Widget) -> None:\n \"\"\"Insert a widget as a child of this widget.\n\n If a child widget already has a parent, it will be re-parented as a\n child of this widget. If the child widget is already a child of this\n widget, there is no change.\n\n :param index: The position in the list of children where the new widget\n should be added.\n :param child: The child to insert as a child of this node.\n :raises ValueError: If this widget cannot have children.\n \"\"\"\n self._assert_can_have_children()\n if child.parent is not self:\n # remove from old parent\n if child.parent:\n child.parent.remove(child)\n\n # add to new parent\n super().insert(index, child)\n\n # set app and window\n child.app = self.app\n child.window = self.window\n\n self._impl.insert_child(index, child._impl)\n\n # Whatever layout we're a part of needs to be refreshed\n self.refresh()\n\n def remove(self, *children: Widget) -> None:\n \"\"\"Remove the provided widgets as children of this node.\n\n Any nominated child widget that is not a child of this widget will\n not have any change in parentage.\n\n Refreshes the widget after removal if any children were removed.\n\n :param children: The child nodes to remove.\n :raises ValueError: If this widget cannot have children.\n \"\"\"\n self._assert_can_have_children()\n\n removed = False\n for child in children:\n if child.parent is self:\n removed = True\n super().remove(child)\n\n child.app = None\n child.window = None\n\n self._impl.remove_child(child._impl)\n\n # If we removed something, whatever layout we're a part of needs to be refreshed\n if removed:\n self.refresh()\n\n def clear(self) -> None:\n \"\"\"Remove all child widgets of this node.\n\n Refreshes the widget after removal if any children were removed.\n\n :raises ValueError: If this widget cannot have children.\n \"\"\"\n self._assert_can_have_children()\n self.remove(*self.children)\n\n @property\n def app(self) -> App | None:\n \"\"\"The App to which this widget belongs.\n\n When setting the app for a widget, all children of this widget will be\n recursively assigned to the same app.\n\n :raises ValueError: If this widget is already associated with another app.\n \"\"\"\n return self._app\n\n @app.setter\n def app(self, app: App | None) -> None:\n # If the widget is already assigned to an app\n if self._app:\n if self._app == app:\n # If app is the same as the previous app, return\n return\n\n # Deregister the widget from the old app\n self._app.widgets.remove(self.id)\n\n self._app = app\n self._impl.set_app(app)\n for child in self.children:\n child.app = app\n\n if app is not None:\n # Add this widget to the application widget registry\n app.widgets.add(self)\n\n @property\n def window(self) -> Window | None:\n \"\"\"The window to which this widget belongs.\n\n When setting the window for a widget, all children of this widget will be\n recursively assigned to the same window.\n \"\"\"\n return self._window\n\n @window.setter\n def window(self, window: Window | None) -> None:\n # Remove the widget from the widget registry it is currently a part of\n if self.window is not None:\n self.window.widgets.remove(self.id)\n\n self._window = window\n self._impl.set_window(window)\n\n for child in self.children:\n child.window = window\n\n if window is not None:\n # Add this widget to the window's widget registry\n window.widgets.add(self)\n\n @property\n def enabled(self) -> bool:\n \"\"\"Is the widget currently enabled? i.e., can the user interact with the widget?\"\"\"\n return self._impl.get_enabled()\n\n @enabled.setter\n def enabled(self, value: bool) -> None:\n self._impl.set_enabled(bool(value))\n\n def refresh(self) -> None:\n self._impl.refresh()\n\n # Refresh the layout\n if self._root:\n # We're not the root of the node hierarchy;\n # defer the refresh call to the root node.\n self._root.refresh()\n else:\n # We can't compute a layout until we have a container\n if self._impl.container:\n super().refresh(self._impl.container)\n self._impl.container.refreshed()\n\n def focus(self) -> None:\n \"\"\"Give this widget the input focus.\n\n This method is a no-op if the widget can't accept focus. The ability of a widget\n to accept focus is platform-dependent. In general, on desktop platforms you can\n focus any widget that can accept user input, while on mobile platforms focus is\n limited to widgets that accept text input (i.e., widgets that cause the virtual\n keyboard to appear).\n \"\"\"\n self._impl.focus()\n","repo_name":"beeware/toga","sub_path":"core/src/toga/widgets/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":9682,"program_lang":"python","lang":"en","doc_type":"code","stars":3828,"dataset":"github-code","pt":"20"} +{"seq_id":"4682526517","text":"import glob\nfrom PIL import Image\nimport PIL\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nfrom glob import glob\nimport os\n\nimport tensorflow as tf\n\ntrain_rate = 7\ndata_dir = [\"airplane\", \"automobile\", \"bird\", \"cat\", \"deer\", \"dog\", \"frog\", \"horse\", \"ship\", \"truck\"]\n\n\ndef get_paths(data_dir, extention, train_rate=7):\n num_total = len(glob(os.path.join(data_dir[0], extention)))\n\n tr_data = []\n tr_target = []\n val_data = []\n val_target = []\n\n for ind, class_ in enumerate(data_dir): \n tmp = glob(os.path.join(class_, \"*.png\")) \n num_size = len(tmp)\n num_train = int(num_size*train_rate/10)\n tr_class = np.array([ind]*num_train)\n val_class = np.array([ind]*(num_total-num_train))\n\t\n tr_data.append(tmp[:num_train])\n tr_target.append(tr_class)\n val_data.append(tmp[num_train:])\n val_target.append(val_class)\n return (tr_data, tr_target, val_data, val_target, num_total, num_train)\n \n\ndef read_img(paths, size):\n tr_img = []\n for class_ in paths:\n tmp = []\n for img in class_:\n pil_obj = PIL.Image.open(img) \n pil_obj = pil_obj.resize(size, Image.ANTIALIAS)\n tmp.append(np.array(pil_obj))\n tr_img.append(tmp)\n tr_img = np.array(tr_img)\n return tr_img\n\ndef get_path_v2(filename):\n paths = []\n labels = []\n with open(filename, 'r') as f:\n for line in f.readlines():\n line = line.split(\" \")\n paths.append(line[0])\n labels.append(int(line[1][0]))\n return paths, labels\n\n\ndef read_img_v2(paths, size): \n imgs = []\n for path in paths:\n pil_obj = PIL.Image.open(path)\n pil_obj = pil_obj.resize(size, Image.ANTIALIAS)\n\n imgs.append(np.array(pil_obj))\n\n imgs = np.array(imgs)\n return imgs\n\nIMAGENET_MEAN = tf.constant([123.68, 116.779, 103.939], dtype=tf.float32)\ndef read_img_v3(paths, size): \n imgs = []\n\n for path in paths: \n# pil_obj = PIL.Image.open(path)\n# pil_obj = pil_obj.resize(size, Image.ANTIALIAS)\n img_decoded = tf.image.decode_png(path, channels=3)\n img_resized = tf.image.resize_images(img_decoded, [size[0], size[1]])\n img_centered = tf.subtract(img_resized, IMAGENET_MEAN)\n # RGB -> BGR\n img_bgr = img_centered[:, :, ::-1]\n# imgs.append(np.array(pil_obj))\n\n# imgs = np.array(imgs)\n return img_bgr\n\ndef read_dicom_img(paths, size):\n return\n\n\n#tr_data, val_data, _, _, _ = get_paths(data_dir, \"*.png\")\n#tr_img = read_img(tr_data, (28, 28))\n#print(tr_img)\n#print(tr_img.shape)\n#print(len(tr_img))\n\n\n\n\n\n\n\n","repo_name":"kang2000h/Deep_Learning","sub_path":"model/cnn/finetune_alexnet/read_data.py","file_name":"read_data.py","file_ext":"py","file_size_in_byte":2656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"70964964209","text":"#! /usr/bin/env python3\n\nfrom typing import *\n\nT = TypeVar('T')\n\nimport time\nimport resource\n\ndef delayediter(seq: Iterable[T], delay=None) -> Iterable[T]:\n for v in seq:\n if delay:\n time.sleep(delay)\n yield v\n\n\ndef timediter(seq: Iterable[T]) -> Iterable[Tuple[float, T]]:\n for v in seq:\n yield (time.time(), v)\n\n\nstarttime = lasttime = time.perf_counter()\n\ndef stopwatch() -> Tuple[float, float]:\n global lasttime\n\n now = time.perf_counter()\n result = (now - starttime, now - lasttime)\n lasttime = now\n\n return result\n\n\ndef peakmem() -> int:\n return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n","repo_name":"chuanconggao/extratools","sub_path":"extratools/debugtools.py","file_name":"debugtools.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":162,"dataset":"github-code","pt":"20"} +{"seq_id":"13987352187","text":"from bs4 import BeautifulSoup as soup \r\nfrom urllib.request import urlopen as uReq\r\nimport requests\r\nimport pandas as pd\r\nimport numpy as np\r\nimport re\r\n\r\n\r\ndef leer_url(url):\r\n\tmy_url = url\r\n\tuClient = uReq(my_url)\r\n\tpage_html = uClient.read()\r\n\tuClient.close()\r\n\tpage_soup = soup(page_html, \"html.parser\")\r\n\treturn page_soup\r\n\r\n\r\ndef lista_links_principales(numero_paginas):\r\n\r\n\tlinks_principales= [0 for _ in range(numero_paginas)] #10\r\n\tlinks_principales[0]= 'https://www.computrabajo.com.co/trabajo-de-electricista'\r\n\r\n\tfor i in range(1,numero_paginas):\r\n\t\tlinks_principales[i]='https://www.computrabajo.com.co/trabajo-de-electricista?p=' + str(i) \r\n\r\n\tdel links_principales[1]\r\n\r\n\treturn links_principales\r\n\r\ndef listaEmpleos(url):\r\n\tdef isBlank (myString):\r\n\t if myString and myString.strip():\r\n\t #myString is not None AND myString is not empty or blank\r\n\t return False\r\n\t #myString is None OR myString is empty or blank\r\n\t return True\r\n\r\n\tpage_soup = leer_url(url)\r\n\tcontainers = page_soup.findAll(\"div\",{\"class\":\"iO\"})\r\n\tk=len(containers)\r\n\ti=0\r\n\t#campos de la tabla\r\n\tid_oferta = [0 for _ in range(k)]\r\n\tfecha = [0 for _ in range(k)]\r\n\tcargo=[0 for _ in range(k)]\r\n\tlink_oferta=[0 for _ in range(k)]\r\n\t\r\n\t#1. Extraer la informacion de los campos\r\n\r\n\tfor i in range(k):\r\n\t\t#ID OFERTA\r\n\t\ttry:\r\n\t\t\tid_oferta[i] = containers[i].find(\"a\",{\"class\":\"js-o-link\"})['href'].split('-')[-1]\r\n\t\texcept AttributeError:\r\n\t\t\tid_oferta[i]=\"\"\r\n\r\n\t\t#FECHA\r\n\t\ttry:\r\n\t\t\tfecha[i] = containers[i].find(\"span\",{\"class\":\"dO\"}).get_text()\r\n\t\t\t\r\n\t\texcept AttributeError:\r\n\t\t\tfecha[i]=\"\"\r\n\t\t\r\n\t\t#CARGO\r\n\t\ttry:\r\n\t\t\tcargo[i] = containers[i].find(\"a\",{\"class\":\"js-o-link\"}).string\r\n\t\t\tcargo[i] = cargo[i].strip()\r\n\t\texcept AttributeError:\r\n\t\t\tcargo[i]=\"\"\r\n\r\n\t\t#link de la oferta\r\n\t\ttry:\r\n\t\t\tlink_oferta[i] = containers[i].find(\"a\",{\"class\":\"js-o-link\"})['href']\r\n\t\texcept AttributeError:\r\n\t\t\tlink_oferta[i]=\"\"\r\n\r\n\t\ti+=1\r\n\t\r\n\t#2. creando un Dataframe con las ofertas recopiladas\r\n\ttabla1 = pd.DataFrame(list(zip(id_oferta,fecha,cargo, link_oferta)),\r\n columns =['id_oferta','fecha','cargo','link_oferta']) \r\n\r\n\treturn tabla1\r\n\r\n#Definir una ARAÑA --> funcion que tome como entrada la lista 'link_oferta'\r\n# navega cada uno de los link y genera un DF con:\r\n# id_oferta, cargo, descripcion, experiencia\r\n\r\n\r\ndef link_spider(links, cantidad_links):\r\n\t\r\n\tk= cantidad_links\r\n\ti=0\r\n\r\n\t#campos de la tabla2\r\n\tid_oferta = [0 for _ in range(k)]\r\n\tempresa=[0 for _ in range(k)]\r\n\tcargo=[0 for _ in range(k)]\r\n\tdescripcion=[0 for _ in range(k)]\r\n\t\t\r\n\t#itera sobre todas las url guardadas en 'links'\r\n\r\n\tfor i in range(k):\r\n\r\n\t\tpage_soup = leer_url(links[i])\r\n\t\t\r\n\t\tcontainer = page_soup.find(\"div\",{\"id\":\"MainContainer\"})\r\n\t\t\r\n\t#1. Extraer la informacion de los campos\r\n\t\t#ID OFERTA\r\n\t\ttry:\r\n\t\t\tid_oferta[i] = links[i].split('-')[-1]\r\n\t\texcept AttributeError:\r\n\t\t\tid_oferta[i]=\"\"\r\n\r\n\t\t#EMPRESA\r\n\t\ttry:\r\n\t\t\tempresa[i] = container.find(\"a\",{\"id\":\"urlverofertas\"}).get_text().strip()\r\n\t\texcept AttributeError:\r\n\t\t \tempresa[i]=\"\"\r\n\r\n\t\t#CARGO\r\n\t\ttry:\r\n\t\t\tcargo[i] = container.find(\"h1\",{\"class\":\"m0\"}).get_text().strip()\r\n\t\texcept AttributeError:\r\n\t\t\tcargo[i]=\"\"\r\n\r\n\t\t#DESCRIPCION\r\n\t\ttry:\r\n\t\t\tdescripcion[i] = container.find(\"section\",{\"class\":\"boxWhite fl w_100 detail_of mb20 bWord\"}).get_text().strip()\r\n\t\t\tdescripcion[i] = re.sub(r'(^[ \\t]+|[ \\t]+(?=:))', '', descripcion[i], flags=re.M)\r\n\t\t\r\n\t\texcept AttributeError:\r\n\t\t\tdescripcion[i]=\"\"\r\n\r\n\t\ti+=1\r\n\r\n\t#2. creando un Dataframe con las ofertas recopiladas\r\n\ttabla2 = pd.DataFrame(list(zip(id_oferta,empresa, cargo, descripcion)), \r\n columns =['id_oferta','empresa','cargo','descripcion']) \r\n\r\n\treturn tabla2\r\n\r\n\r\n\r\n#1. Crear el listado de links principales\r\n# recibe como parametro el numero de páginas principales a navegar\r\n\r\nlinks_principales = lista_links_principales(10)\r\n\r\n\r\n#2. Leer cada link principal y obtener la tabla de empleos (con sus links secundarios)\r\nTabla_empleos = pd.DataFrame(columns =['id_oferta','fecha','cargo','link_oferta'])\r\n\r\nfor link in links_principales:\r\n\tTabla_empleos = Tabla_empleos.append(listaEmpleos(link), ignore_index = True)\r\n\r\nTabla_empleos.to_excel('Electricista_1_20210107.xls')\r\n\r\n#3. Crear el listado de links secundarios, \r\n\r\nlinks_secundarios = Tabla_empleos.link_oferta.apply(lambda x: 'https://www.computrabajo.com.co' + x)\r\ncantidad_links = len(links_secundarios)\r\n\r\n#Tabla_descripcion = pd.DataFrame(columns =['id_oferta','empresa','cargo','descripcion'])\r\n\r\nTabla_descripcion = link_spider(links_secundarios,cantidad_links)\r\nprint(Tabla_descripcion.head())\r\nTabla_descripcion.to_excel('Electricista_2_20210107.xls')\r\n","repo_name":"danielpaloma/job_offers_analyzer","sub_path":"listaEmpleos_v2.py","file_name":"listaEmpleos_v2.py","file_ext":"py","file_size_in_byte":4640,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"23376242952","text":"import argparse\nimport os\nfrom typing import List\n\nimport numpy as np\n\nfrom project import read_office, config\nfrom project.SLAMGraph import SLAMGraph\nfrom project.annotators.AnnotatorImage import AnnotatorImage\nfrom project.annotators.AnnotatorPointCloud import AnnotatorPointCloud\nfrom project.associators.AssociatorAnnot import AssociatorAnnot\nfrom project.associators.AssociatorFront import AssociatorFront\nfrom project.measurements.MeasureError import MeasureError\nfrom project.pcdBuilders.PcdBuilderLiving import PcdBuilderLiving\nfrom project.pcdBuilders.PcdBuilderOffice import PcdBuilderOffice\nfrom project.pcdBuilders.PcdBuilderPointCloud import PcdBuilderPointCloud\nfrom project.PostProcessing import PostProcessing\nfrom project.Visualisation import Visualisation\n\n\ndef create_data_list_living(main_data_path: str):\n depth = os.listdir(main_data_path)\n depth = sorted(depth, key=lambda x: int(x[:-4]))\n main_data_list = list(map(lambda x: os.path.join(main_data_path, x), depth))\n return main_data_list\n\n\ndef create_annot_list_office(main_data_path: str):\n depth = os.listdir(main_data_path)\n depth = sorted(depth, key=lambda x: int(x[9:-4]))\n main_data_list = list(map(lambda x: os.path.join(main_data_path, x), depth))\n return main_data_list\n\n\ndef create_main_lists_office(main_data_path: str):\n png_files, depths_files = read_office.provide_filenames(main_data_path)\n return png_files, depths_files\n\n\ndef create_main_and_annot_list(main_data_path: str):\n annot_list = []\n main_data_list = []\n\n folders = os.listdir(main_data_path)\n\n for j, folder in enumerate(folders):\n cur_path = os.path.join(main_data_path, folder)\n npy, pcd = os.listdir(cur_path)\n\n cur_path_to_annot = os.path.join(cur_path, npy)\n cur_path_to_main_data = os.path.join(cur_path, pcd)\n\n annot_list.append(cur_path_to_annot)\n main_data_list.append(cur_path_to_main_data)\n return annot_list, main_data_list\n\n\ndef main(\n main_data_path: str,\n annot_path: str,\n which_format: int,\n first_node: int,\n first_gt_node: int,\n num_of_nodes: int,\n ds_filename_gt: str,\n):\n\n camera = config.CAMERA_ICL\n pcds = []\n\n if which_format == 1 or which_format == 2:\n if which_format == 1:\n main_data_list = create_data_list_living(main_data_path)[\n first_node : first_node + num_of_nodes\n ]\n annot_list = create_data_list_living(annot_path)[\n first_node : first_node + num_of_nodes\n ]\n else:\n annot_list = create_annot_list_office(annot_path)\n png_list, main_data_list = create_main_lists_office(main_data_path)\n png_list = png_list[first_node : first_node + num_of_nodes]\n main_data_list = main_data_list[first_node : first_node + num_of_nodes]\n if verbose:\n print(main_data_list)\n annot = AnnotatorImage(annot_list)\n if which_format == 1:\n pcd_b = PcdBuilderLiving(camera, annot)\n else:\n pcd_b = PcdBuilderOffice(camera, annot)\n for i, image in enumerate(main_data_list):\n pcds.append(pcd_b.build_pcd(main_data_list[i], i))\n associator = AssociatorAnnot()\n associator.associate(pcds)\n\n else:\n annot_list, main_data_list = create_main_and_annot_list(main_data_path)\n annot_list = annot_list[first_node : first_node + num_of_nodes]\n main_data_list = main_data_list[first_node : first_node + num_of_nodes]\n\n annot = AnnotatorPointCloud(annot_list)\n reflection = np.asarray(\n [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]\n )\n pcd_b = PcdBuilderPointCloud(\n camera, annot, reflection\n ) # reflection is needed due to dataset (icl nuim) particularities\n\n for i, file in enumerate(annot_list):\n pcds.append(pcd_b.build_pcd(main_data_list[i], i))\n\n associator = AssociatorFront()\n associator.associate(pcds)\n\n max_tracks = PostProcessing.post_process(pcds)\n\n slam_graph = SLAMGraph()\n graph_estimated_state = slam_graph.estimate_graph(pcds, max_tracks)\n\n measure_error = MeasureError(ds_filename_gt, len(annot_list), num_of_nodes)\n measure_error.measure_error(first_node, first_gt_node, graph_estimated_state)\n\n visualisation = Visualisation(graph_estimated_state)\n visualisation.visualize(pcds, graph_estimated_state)\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(\n description=\"Benchmarks a trajectory, built by an algorithm\"\n )\n parser.add_argument(\n \"main_data\", type=str, help=\"Directory where main information files are stored\"\n )\n parser.add_argument(\n \"annot\", type=str, help=\"Directory where color images are stored\"\n )\n parser.add_argument(\n \"which_format\",\n type=int,\n choices=[1, 2, 3],\n help=\"living room = 1, office = 2, point clouds = 3\",\n )\n parser.add_argument(\n \"first_node\", type=int, help=\"From what node algorithm should start\"\n )\n parser.add_argument(\n \"first_gt_node\", type=int, help=\"From what node gt references start\"\n )\n parser.add_argument(\"num_of_nodes\", type=int, help=\"Number of needed nodes\")\n parser.add_argument(\n \"ds_filename_gt\", type=str, help=\"Filename of a file with gt references\"\n )\n args = parser.parse_args()\n\n main(\n args.main_data,\n args.annot,\n args.which_format,\n args.first_node,\n args.first_gt_node,\n args.num_of_nodes,\n args.ds_filename_gt,\n )\n","repo_name":"prime-slam/SLAM-Backend-Evaluation","sub_path":"project/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5639,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"1463422343","text":"#!/usr/bin/python3\nimport os\nimport sys\nimport glob\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\n\ndef make_species_set(species_file):\n\n \"\"\" Function to make a species database \"\"\"\n\n species_set = set()\n with open(species_file) as f:\n for l in f:\n species = l.rstrip()\n species_set.add(species)\n\n print(\"***************************************\\n\")\n print(\"Total number of species under analysis: \", len(species_set))\n return species_set\n\ndef calculate_total_orthogroups():\n\n \"\"\" Function to calculate total number of orthogroups \"\"\"\n\n total_orthogroups = 0\n for orthogroup in glob.glob(\"*.fa\"):\n total_orthogroups += 1\n\n return total_orthogroups\n\ndef make_single_copy_families(total_orthogroups, species_set):\n\n \"\"\" Function to remove paralogs and replace with gaps \"\"\"\n\n orthogroup_count = 0\n species_rep = {}\n\n for orthogroup in glob.glob(\"*.fa\"):\n orthogroup_count += 1\n print(\"Orthogroup under analysis: \", orthogroup)\n print(\"Orthologs analysed: \", orthogroup_count, \"/\", total_orthogroups)\n inhandle = SeqIO.parse(orthogroup, \"fasta\")\n\n species_count = {}\n for species in species_set:\n species_count[species] = 0\n\n all_descriptions = {}\n for record in inhandle:\n record_description = record.description.replace(\" \", \"_\")\n all_descriptions[record_description] = str(record.seq)\n for species in species_set:\n if species in record_description:\n species_count[species] += 1\n\n sc_orthgroup_species = set()\n mc_orthgroup_species = set()\n nc_orthgroup_species = set()\n removed_species = set()\n\n for key, val in species_count.items():\n if val == 1:\n sc_orthgroup_species.add(key)\n elif val > 1:\n mc_orthgroup_species.add(key)\n removed_species.add(key)\n else:\n nc_orthgroup_species.add(key)\n removed_species.add(key)\n\n ofile = open(orthogroup[:9] + \"_sc.faa\", \"w\")\n for description, seq in all_descriptions.items():\n for species in sc_orthgroup_species:\n if species in description:\n ofile.write(\">\" + description + \"\\n\" + seq + \"\\n\")\n ofile.close()\n\n Total_species = len(species_set)\n Species_with_sc = len(sc_orthgroup_species)\n Species_with_mc = len(mc_orthgroup_species)\n Species_with_nc = len(nc_orthgroup_species)\n\n sequences = 0\n sc_orthogroup = SeqIO.parse(orthogroup[:9] +\"_sc.faa\", \"fasta\")\n for sequence in sc_orthogroup:\n sequences += 1\n if sequences == Species_with_sc:\n print(\"sc orthofile correctly printed\")\n else:\n print(\"Error with code\")\n\n species_representation = (Species_with_sc/Total_species)*100\n o_file = orthogroup[:9] + \"_sc.faa\"\n species_rep[o_file] = species_representation\n\n return species_rep\n\ndef move_orthogroups(total_orthogroups,species_rep, cutoff):\n\n \"\"\" Function to move files based on % species representation \"\"\"\n\n more_dir = \"Orthogroups_more_than_%\" + str(cutoff)\n less_dir = \"Orthogroups_less_than_%\" + str(cutoff)\n\n os.mkdir(more_dir)\n os.mkdir(less_dir)\n\n ofile = open(\"species_rep.csv\",\"w\")\n more_files = 0\n completed = 0\n for key, val in species_rep.items():\n ofile.write(key + \",\" + str(val) + \"\\n\")\n completed += 1\n if val >= int(cutoff):\n more_files += 1\n my_command = \"mv \" + key + \" \" + more_dir\n os.system(my_command)\n line1 = \"\\nCurrent single copy families:{}\".format(more_files)\n line2 = \"Searched: %\" + str((completed/total_orthogroups)*100)\n print(line1,line2)\n\n if val <= int(cutoff):\n my_command = \"mv \" + key + \" \" + less_dir\n os.system(my_command)\n\n return(more_files)\n\ndef clean_up():\n\n \"\"\" Move original files \"\"\"\n\n print(\"\\n*****************************************************************\")\n print(\"Cleaning up - all files being moved to labled sub-directory\")\n os.mkdir(\"Original_orthogroups\")\n os.mkdir(\"Results\")\n\n my_c = \"\"\"for file in *.fa; do \\n mv \"$file\" Original_orthogroups \\n done\"\"\"\n os.system(my_c)\n\n my_c = \"mv *.csv Results\"\n os.system(my_c)\n\ndef output(more_files,cutoff):\n\n print(\"\\n*****************************************************************\")\n print(\"\\nprem3 has finished\")\n line1 = \"All single copy families above %{}\".format(cutoff)\n line2 = \"have been moved to their own directory\"\n print(line1,line2)\n print(\"{} single copy files have been generated\".format(more_files))\n print(\"Thanks for using prem3\")\n print(\"\\n*****************************************************************\")\n\ndef main():\n species_set = make_species_set(species_file)\n total_orthogroups = calculate_total_orthogroups()\n species_rep = make_single_copy_families(total_orthogroups,species_set)\n more_files = move_orthogroups(total_orthogroups,species_rep, cutoff)\n clean_up()\n output(more_files,cutoff)\n\nif __name__ == \"__main__\":\n species_file = sys.argv[1]\n cutoff = sys.argv[2]\n main()\n","repo_name":"ak-andromeda/ALE_methods","sub_path":"prem3.py","file_name":"prem3.py","file_ext":"py","file_size_in_byte":5329,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"19674999322","text":"# © 2020 - today Numigi (tm) and all its contributors (https://bit.ly/numigiens)\n# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).\n\nimport pytest\nfrom datetime import datetime, timedelta\nfrom ddt import ddt, data, unpack\nfrom odoo.exceptions import ValidationError\nfrom odoo.addons.recording_external_revenue.tests.common import \\\n ExternalRevenueCase\n\n\n@ddt\nclass TestConversion(ExternalRevenueCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.recording.state = \"validated\"\n cls.partner = cls.believe.with_context(force_company=cls.company.id)\n cls.product = cls.stream.with_context(force_company=cls.company.id)\n cls.operation_date = datetime.now().date() + timedelta(10)\n cls.period_start_date = datetime.now().date() + timedelta(5)\n cls.period_end_date = datetime.now().date() + timedelta(15)\n cls.quantity = 5\n cls.gross_amount_per_unit = 10\n cls.gross_amount = 50\n cls.commission_amount = 20\n cls.net_amount = 30\n cls.revenue = cls._create_revenue(\n analytic_account_id=cls.analytic_account.id,\n artist_id=cls.artist.id,\n commission_amount=cls.commission_amount,\n country_id=cls.canada.id,\n currency_id=cls.cad.id,\n fiscal_position=\"revenue\",\n gross_amount=cls.gross_amount,\n gross_amount_per_unit=cls.gross_amount_per_unit,\n net_amount=cls.net_amount,\n operation_date=cls.operation_date,\n partner_id=cls.partner.id,\n period_end_date=cls.period_end_date,\n period_start_date=cls.period_start_date,\n platform_id=cls.spotify.id,\n quantity=cls.quantity,\n recording_id=cls.recording.id,\n state_id=cls.quebec.id,\n subplatform_id=cls.spotify_premium.id,\n tax_base=\"net_amount\",\n tax_id=cls.tax.id,\n product_id=cls.product.id,\n company_id=cls.company.id,\n )\n\n cls.journal = cls.env[\"account.journal\"].create(\n {\n \"name\": \"External Revenues (CAD)\",\n \"code\": \"EXTCAD\",\n \"type\": \"general\",\n \"company_id\": cls.company.id,\n }\n )\n\n cls.eur_journal = cls.env[\"account.journal\"].create(\n {\n \"name\": \"External Revenues (EUR)\",\n \"code\": \"EXTEUR\",\n \"type\": \"general\",\n \"company_id\": cls.company.id,\n \"currency_id\": cls.eur.id,\n }\n )\n\n cls.journal_mapping = cls.env[\"recording.journal.mapping\"].create(\n {\n \"journal_id\": cls.journal.id,\n \"currency_id\": cls.cad.id,\n \"company_id\": cls.company.id,\n }\n )\n\n cls.eur_journal_mapping = cls.env[\"recording.journal.mapping\"].create(\n {\n \"journal_id\": cls.eur_journal.id,\n \"currency_id\": cls.eur.id,\n \"company_id\": cls.company.id,\n }\n )\n\n cls.receivable_account = cls._create_account(\n name=\"Receivable\",\n code=\"111111\",\n company_id=cls.company.id,\n user_type_id=cls.env.ref(\"account.data_account_type_receivable\").id,\n reconcile=True,\n )\n\n cls.tax_account = cls._create_account(\n name=\"Taxes\",\n code=\"222222\",\n company_id=cls.company.id,\n user_type_id=cls.env.ref(\n \"account.data_account_type_current_liabilities\"\n ).id,\n )\n\n cls.revenue_account = cls._create_account(\n name=\"Revenue\",\n code=\"444444\",\n company_id=cls.company.id,\n user_type_id=cls.env.ref(\"account.data_account_type_revenue\").id,\n )\n\n cls.other_revenue_account = cls._create_account(\n name=\"Other Revenue\",\n code=\"444445\",\n company_id=cls.company.id,\n user_type_id=cls.env.ref(\"account.data_account_type_revenue\").id,\n )\n\n cls.product.property_account_income_id = cls.revenue_account\n\n cls.tax.account_id = cls.tax_account.id\n cls.partner.property_account_receivable_id = cls.receivable_account\n\n cls.tps = cls._create_tax(\n name=\"TPS\",\n amount=5,\n amount_type=\"percent\",\n company_id=cls.company.id,\n account_id=cls.tax_account.id,\n )\n cls.tps_account = cls._create_account(\n name=\"Quebec Tax (TPS)\",\n code=\"222223\",\n company_id=cls.company.id,\n user_type_id=cls.env.ref(\n \"account.data_account_type_current_liabilities\"\n ).id,\n )\n\n cls.fixed_amount_tax = cls._create_fixed_amount_tax(1000)\n\n cls.fiscal_position_quebec = cls._create_fiscal_position(\n name=\"Quebec\",\n company_id=cls.company.id,\n state_ids=[(4, cls.quebec.id)],\n country_id=cls.canada.id,\n auto_apply=True,\n )\n cls._create_fiscal_position_tax_rule(\n cls.fiscal_position_quebec, cls.tax, cls.tps\n )\n\n @classmethod\n def _create_fiscal_position(cls, **kwargs):\n return cls.env[\"account.fiscal.position\"].create(kwargs)\n\n @classmethod\n def _create_fiscal_position_tax_rule(cls, position, src_tax, dest_tax):\n return cls.env[\"account.fiscal.position.tax\"].create(\n {\n \"position_id\": position.id,\n \"tax_src_id\": src_tax.id,\n \"tax_dest_id\": dest_tax.id,\n }\n )\n\n @classmethod\n def _create_fiscal_position_account_rule(cls, position, src_account,\n dest_account):\n return cls.env[\"account.fiscal.position.account\"].create(\n {\n \"position_id\": position.id,\n \"account_src_id\": src_account.id,\n \"account_dest_id\": dest_account.id,\n }\n )\n\n @classmethod\n def _create_account(cls, **kwargs):\n return cls.env[\"account.account\"].create(kwargs)\n\n @classmethod\n def _create_revenue(cls, **kwargs):\n return cls.env[\"recording.external.revenue\"].create(kwargs)\n\n @classmethod\n def _create_fixed_amount_tax(cls, amount):\n return cls._create_tax(\n name=\"Tax defined on product\",\n amount=amount,\n amount_type=\"fixed\",\n company_id=cls.company.id,\n account_id=cls.tax_account.id,\n )\n\n @classmethod\n def _find_jobs(cls, revenue):\n return (\n cls.env[\"queue.job\"]\n .search(\n [\n (\"model_name\", \"=\", \"recording.external.revenue\"),\n (\"method_name\", \"=\", \"generate_journal_entry\"),\n ]\n )\n .filtered(lambda j: j.record_ids == [revenue.id])\n )\n\n def test_schedule_generate_journal_entries(self):\n self.env[\n \"recording.external.revenue\"].schedule_generate_journal_entries(\n self.company\n )\n assert len(self._find_jobs(self.revenue)) == 1\n\n def test_journal_entry_posted(self):\n entry = self.revenue.generate_journal_entry()\n assert entry.state == \"posted\"\n\n def test_journal_mapping(self):\n entry = self.revenue.generate_journal_entry()\n assert entry.journal_id == self.journal\n\n def test_no_journal_found(self):\n self.journal_mapping.unlink()\n with pytest.raises(ValidationError):\n self.revenue.generate_journal_entry()\n\n def test_deprecated_account(self):\n self.revenue_account.deprecated = True\n with pytest.raises(ValidationError):\n self.revenue.generate_journal_entry()\n\n def test_operation_date(self):\n entry = self.revenue.generate_journal_entry()\n assert entry.date == self.period_end_date\n\n def test_journal_accounts(self):\n entry = self.revenue.generate_journal_entry()\n assert len(entry.line_ids) == 3\n assert len(self._get_revenue_line(entry)) == 1\n assert len(self._get_tax_line(entry)) == 1\n assert len(self._get_receivable_line(entry)) == 1\n\n @data(\n (\"net_amount\", 10, 3),\n (\"net_amount\", 20, 6),\n (\"gross_amount\", 10, 5),\n (\"gross_amount\", 20, 10),\n )\n @unpack\n def test_tax_amount(self, tax_base, percent, expected_amount):\n self.revenue.tax_base = tax_base\n self.tax.amount_type = \"percent\"\n self.tax.amount = percent\n entry = self.revenue.generate_journal_entry()\n assert self._get_tax_line(entry).credit == expected_amount\n\n def test_tax_defined_on_product(self):\n self.revenue.tax_id = False\n self.stream.taxes_id = self.fixed_amount_tax\n entry = self.revenue.generate_journal_entry()\n assert self._get_tax_line(entry).credit == self.fixed_amount_tax.amount\n\n def test_tax_defined_on_revenue_account(self):\n self.revenue.tax_id = False\n self.revenue_account.tax_ids = self.fixed_amount_tax\n entry = self.revenue.generate_journal_entry()\n assert self._get_tax_line(entry).credit == self.fixed_amount_tax.amount\n\n def test_fiscal_position_used_on_product_taxes(self):\n self.revenue.tax_id = False\n self.stream.taxes_id = self.fixed_amount_tax\n self._create_fiscal_position_tax_rule(\n self.fiscal_position_quebec, self.fixed_amount_tax, self.tps\n )\n entry = self.revenue.generate_journal_entry()\n assert self._get_tax_line(entry).credit == 1.5 # 0.05 * self.net_amount\n\n def test_fiscal_position_used_on_account_taxes(self):\n self.revenue.tax_id = False\n self.revenue_account.tax_ids = self.fixed_amount_tax\n self._create_fiscal_position_tax_rule(\n self.fiscal_position_quebec, self.fixed_amount_tax, self.tps\n )\n entry = self.revenue.generate_journal_entry()\n assert self._get_tax_line(entry).credit == 1.5 # 0.05 * self.net_amount\n\n def test_revenue_account(self):\n entry = self.revenue.generate_journal_entry()\n assert self._get_revenue_line(entry).account_id == self.revenue_account\n\n def test_revenue_account_mapped_with_fiscal_position(self):\n self._create_fiscal_position_account_rule(\n self.fiscal_position_quebec,\n self.revenue_account,\n self.other_revenue_account,\n )\n entry = self.revenue.generate_journal_entry()\n assert self._get_revenue_line(\n entry).account_id == self.other_revenue_account\n\n def test_no_available_fiscal_position(self):\n self.revenue.state_id = False\n self.revenue.country_id = self.env.ref(\"base.fr\")\n with pytest.raises(ValidationError):\n self.revenue.generate_journal_entry()\n\n def test_fiscal_position_defined_on_partner(self):\n self.revenue.write(\n {\"fiscal_position\": \"partner\", \"country_id\": False,\n \"state_id\": False}\n )\n self.revenue.partner_id.write(\n {\"country_id\": self.canada.id, \"state_id\": self.quebec.id}\n )\n self._create_fiscal_position_account_rule(\n self.fiscal_position_quebec,\n self.revenue_account,\n self.other_revenue_account,\n )\n entry = self.revenue.generate_journal_entry()\n assert self._get_revenue_line(\n entry).account_id == self.other_revenue_account\n\n def test_no_fiscal_position_found_for_the_partner(self):\n self.revenue.write(\n {\"fiscal_position\": \"partner\", \"country_id\": False,\n \"state_id\": False}\n )\n self.partner.state_id = False\n self.partner.country_id = self.env.ref(\"base.fr\")\n with pytest.raises(ValidationError):\n self.revenue.generate_journal_entry()\n\n def test_amount_in_foreign_currency(self):\n self._set_currency_rate(self.eur, 0.8)\n self.revenue.currency_id = self.eur\n self.receivable_account.currency_id = self.eur\n self.revenue_account.currency_id = self.eur\n self.tax.amount = 10\n\n entry = self.revenue.generate_journal_entry()\n\n revenue_line = self._get_revenue_line(entry)\n assert revenue_line.credit == 37.5 # net_amount / 0.8\n assert revenue_line.amount_currency == -30 # net_amount\n assert revenue_line.currency_id == self.eur\n\n tax_line = self._get_tax_line(entry)\n assert tax_line.credit == 3.75 # net_amount * 10% / 0.8\n assert tax_line.amount_currency == -3\n assert tax_line.currency_id == self.eur\n\n receivable_line = self._get_receivable_line(entry)\n assert receivable_line.debit == 41.25\n assert receivable_line.amount_currency == 33 # net_amount * (1 + 10%) / 0.8\n assert receivable_line.currency_id == self.eur\n\n def test_use_proper_currency_rate(self):\n self._set_currency_rate(self.eur, 0.3, self.period_start_date)\n self._set_currency_rate(self.eur, 0.5, self.operation_date)\n self._set_currency_rate(self.eur, 0.8, self.period_end_date)\n self.revenue.currency_id = self.eur\n entry = self.revenue.generate_journal_entry()\n revenue_line = self._get_revenue_line(entry)\n assert revenue_line.credit == 37.5 # net_amount / 0.5\n\n def _set_currency_rate(self, currency, rate, date=None):\n values = {\n \"name\": date or datetime.now().date(),\n \"rate\": rate,\n \"company_id\": self.company.id,\n }\n currency.write({\"rate_ids\": [(0, 0, values)]})\n\n def _get_revenue_line(self, move):\n return move.line_ids.filtered(\n lambda\n l: l.account_id in self.revenue_account | self.other_revenue_account\n )\n\n def _get_receivable_line(self, move):\n return move.line_ids.filtered(\n lambda l: l.account_id == self.receivable_account)\n\n def _get_tax_line(self, move):\n return move.line_ids.filtered(\n lambda l: l.account_id == self.tax_account)\n\n def test_due_date_with_no_payment_term(self):\n self.partner.property_payment_term_id = None\n entry = self.revenue.generate_journal_entry()\n receivable_line = self._get_receivable_line(entry)\n assert receivable_line.date_maturity == self.period_end_date\n\n def test_payment_term_30_days(self):\n payment_term = self._create_payment_term(\n name=\"30 Days\", lines=[(\"balance\", 0, 30, \"day_after_invoice_date\")]\n )\n self.partner.property_payment_term_id = payment_term\n entry = self.revenue.generate_journal_entry()\n receivable_line = self._get_receivable_line(entry)\n expected_due_date = self.period_end_date + timedelta(30)\n assert receivable_line.date_maturity == expected_due_date\n\n def test_2_payment_term_lines(self):\n payment_term = self._create_payment_term(\n name=r\"50% after 15 days / 50% after 30 days\",\n lines=[\n (\"percent\", 50, 15, \"day_after_invoice_date\"),\n (\"balance\", 0, 30, \"day_after_invoice_date\"),\n ],\n )\n self.partner.property_payment_term_id = payment_term\n entry = self.revenue.generate_journal_entry()\n receivable_line = self._get_receivable_line(entry)\n assert len(receivable_line) == 2\n\n @classmethod\n def _create_payment_term(cls, name, lines):\n line_vals = (\n {\n \"value\": value,\n \"value_amount\": value_amount,\n \"days\": days,\n \"option\": option,\n }\n for value, value_amount, days, option in lines\n )\n return cls.env[\"account.payment.term\"].create(\n {\"name\": name, \"line_ids\": [(0, 0, v) for v in line_vals]}\n )\n\n def test_analytic_account(self):\n entry = self.revenue.generate_journal_entry()\n\n revenue_line = self._get_revenue_line(entry)\n assert revenue_line.analytic_account_id == self.analytic_account\n\n tax_line = self._get_tax_line(entry)\n assert not tax_line.analytic_account_id\n\n receivable_line = self._get_receivable_line(entry)\n assert not receivable_line.analytic_account_id\n\n def test_if_already_posted__raise_error(self):\n self.revenue.generate_journal_entry()\n with pytest.raises(ValidationError):\n self.revenue.generate_journal_entry()\n\n def test_revenue_id_in_journal_entry_reference(self):\n move = self.revenue.generate_journal_entry()\n assert str(self.revenue.id) in move.ref\n\n def test_can_not_delete_posted_revenue(self):\n self.revenue.generate_journal_entry()\n with pytest.raises(ValidationError):\n self.revenue.unlink()\n\n def test_can_not_edit_posted_revenue(self):\n self.revenue.generate_journal_entry()\n with pytest.raises(ValidationError):\n self.revenue.analytic_account_id = False\n\n def test_recording_dimensions(self):\n entry = self.revenue.generate_journal_entry()\n revenue_line = self._get_revenue_line(entry)\n assert revenue_line.artist_id == self.artist\n assert revenue_line.recording_id == self.recording\n\n def test_partner(self):\n entry = self.revenue.generate_journal_entry()\n\n revenue_line = self._get_revenue_line(entry)\n assert revenue_line.partner_id == self.partner\n\n tax_line = self._get_tax_line(entry)\n assert tax_line.partner_id == self.partner\n\n receivable_line = self._get_receivable_line(entry)\n assert receivable_line.partner_id == self.partner\n\n def test_recording_not_validated(self):\n self.recording.state = \"to_validate\"\n with pytest.raises(ValidationError):\n self.revenue.generate_journal_entry()\n\n def test_currency_and_amount_currency_1(self):\n self.company.currency_id = self.cad\n move_id = self.revenue.generate_journal_entry()\n assert not move_id.mapped('line_ids.currency_id')\n assert all([l.amount_currency == 0 for l in\n move_id.mapped('line_ids')])\n\n def test_currency_and_amount_currency_2(self):\n self.company.currency_id = self.eur\n move_id = self.revenue.generate_journal_entry()\n assert all(\n [l.currency_id == self.cad and l.amount_currency != 0 for l in\n move_id.mapped('line_ids')])\n","repo_name":"Numigi/odoo-entertainment-addons","sub_path":"recording_external_revenue_account/tests/test_generate_journal_entries.py","file_name":"test_generate_journal_entries.py","file_ext":"py","file_size_in_byte":18605,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"20"} +{"seq_id":"17515822318","text":"from mifiel import Template\nfrom mifiellib import BaseMifielCase\n\nimport json\nimport responses\nimport os.path\n\nclass TestTemplate(BaseMifielCase):\n def setUp(self):\n super(TestTemplate, self).setUp()\n self.tmpl = Template(self.client)\n\n def mock_tmpl_response(self, method, url, tmpl_id):\n responses.add(\n method=method,\n url=url,\n body=json.dumps({\n 'id': tmpl_id,\n 'name': 'some name'\n }),\n status=200,\n content_type='application/json',\n )\n\n @responses.activate\n def test_get(self):\n tmpl_id = 'some-tmpl-id'\n url = self.client.url().format(path='templates/' + tmpl_id)\n self.mock_tmpl_response(responses.GET, url, tmpl_id)\n\n tmpl = Template.find(self.client, tmpl_id)\n\n req = self.get_last_request()\n self.assertEqual(req.body, None)\n self.assertEqual(req.method, 'GET')\n self.assertEqual(req.url, url)\n self.assertEqual(tmpl.id, tmpl_id)\n assert req.headers['Authorization'] is not None\n\n @responses.activate\n def test_all(self):\n url = self.client.url().format(path='templates')\n responses.add(\n method=responses.GET,\n url=url,\n body=json.dumps([{\n 'id': 'some-doc-id',\n 'callback_url': 'some'\n }]),\n status=200,\n content_type='application/json',\n )\n\n docs = Template.all(self.client)\n self.assertEqual(len(docs), 1)\n\n @responses.activate\n def test_delete(self):\n url = self.client.url().format(path='templates')\n url = '{}/{}'.format(url, 'some-doc-id')\n responses.add(\n method=responses.DELETE,\n url=url,\n body=json.dumps({\n 'status': 'success',\n 'message': 'Destroyed document#some-doc-id',\n 'data': { 'id': 'some-doc-id'}\n }),\n status=200,\n content_type='application/json',\n )\n response = Template.delete(self.client, 'some-doc-id')\n self.assertEqual(response['status'], 'success')\n\n @responses.activate\n def test_update(self):\n tmpl_id = 'some-tmpl-id'\n url = self.client.url().format(path='templates/' + tmpl_id)\n self.mock_tmpl_response(responses.PUT, url, tmpl_id)\n\n tmpl = Template(self.client)\n tmpl.id = tmpl_id\n tmpl.random_param = 'random-param'\n tmpl.other_param = 'other-param'\n tmpl.save()\n\n req = self.get_last_request()\n self.assertEqual(req.method, 'PUT')\n self.assertEqual(req.url, url)\n self.assertEqual(tmpl.id, tmpl_id)\n assert req.headers['Authorization'] is not None\n\n def test_update_without_id(self):\n tmpl = Template(self.client)\n tmpl.callback_url = 'some-callback'\n self.assertFalse(tmpl.save())\n\n @responses.activate\n def test_create(self):\n tmpl_id = 'some-tmpl-id'\n url = self.client.url().format(path='templates')\n self.mock_tmpl_response(responses.POST, url, tmpl_id)\n\n content = '
' \\\n 'Name NAME' \\\n 'Date DATE' \\\n '
'\n tmpl = Template.create(\n client=self.client,\n name='mywhheehss1o',\n description='Confidential disclosure agreement',\n header='
some header html
',\n content=content,\n footer='
some footer html
'\n )\n\n req = self.get_last_request()\n self.assertEqual(req.method, 'POST')\n self.assertEqual(req.url, url)\n self.assertEqual(tmpl.id, tmpl_id)\n assert req.headers['Authorization'] is not None\n","repo_name":"Mifiel/python-api-client","sub_path":"test/mifiellib/test_template.py","file_name":"test_template.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"20"} +{"seq_id":"17199212014","text":"# https://www.codewars.com/kata/55bf01e5a717a0d57e0000ec\ndef persistence(n):\n def mul(n):\n c = 1\n for i in str(n):\n c *= int(i)\n return c\n\n count = 0\n while n // 10 > 0:\n n = mul(n)\n count += 1\n return count\n\n\nprint(persistence(999))\n","repo_name":"tonigvz/PracticePython","sub_path":"solutions/persistentbugger/pers.py","file_name":"pers.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"28591068797","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = 'David Hoese'\nSITENAME = 'David Hoese'\nSITEURL = ''\nLICENSE_URL = \"https://github.com/djhoese/djhoese.github.io-src/blob/master/LICENSE\"\nLICENSE = \"MIT\"\nTHEME = 'theme'\nINDEX_SAVE_AS = 'blog_index.html'\nDISQUS_SITENAME = 'https-djhoese-github-io'\n\nPATH = 'content'\n\n# Set the article URL\nARTICLE_URL = 'blog/{date:%Y}/{date:%m}/{date:%d}/{slug}/'\nARTICLE_SAVE_AS = 'blog/{date:%Y}/{date:%m}/{date:%d}/{slug}/index.html'\n\nTIMEZONE = 'US/Central'\n\nDEFAULT_LANG = 'en'\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\nDEFAULT_PAGINATION = 10\n\n# Uncomment following line if you want document-relative URLs when developing\n#RELATIVE_URLS = True\n\nMARKUP = ['md']\nPLUGIN_PATHS = ['./plugins', './plugins/pelican-plugins']\nPLUGINS = [\n 'summary', # auto-summarizing articles\n 'feed_summary', # use summaries for RSS, not full articles\n 'ipynb.liquid', # for embedding notebooks\n 'liquid_tags.img', # embedding images\n 'liquid_tags.video', # embedding videos\n 'liquid_tags.youtube', # embedding videos\n 'liquid_tags.vimeo', # embedding videos\n 'liquid_tags.include_code', # including code blocks\n 'liquid_tags.literal',\n 'liquid_tags.notebook',\n 'twitter_card',\n]\nIGNORE_FILES = ['.ipynb_checkpoints']\nLIQUID_CONFIGS = ((\"IPYNB_EXPORT_TEMPLATE\", \"notebook.tpl\", \"\"), )\n\n# Notebook plugin\nCODE_DIR = 'downloads/code'\nNOTEBOOK_DIR = 'downloads/notebooks'\nEXTRA_HEADER = open('_nb_header.html').read()\n\nTWITTER_USERNAME = 'djhoese'\nGITHUB_USERNAME = 'djhoese'\nSTACKOVERFLOW_ADDRESS = 'https://stackexchange.com/users/192194/djhoese'\nSHOW_ARCHIVES = True\nSHOW_FEED = False # Need to address large feeds\n\nENABLE_MATHJAX = True\n\nSTATIC_PATHS = ['images', 'figures', 'videos', 'downloads', 'favicon.ico']\n\n\n# Blogroll\nLINKS = (('PyTroll', 'http://pytroll.github.io/'),\n ('VisPy', 'http://vispy.org/'),\n )\n\n# Social widget\nSOCIAL = (('Github', 'https://github.com/{}/'.format(GITHUB_USERNAME)),\n ('Twitter', 'https://twitter.com/{}'.format(TWITTER_USERNAME)),\n )\n\n#=============\n# Twitter Card\n#=============\n# https://dev.twitter.com/cards\nTWITTER_CARD_USE = True # (False)\nTWITTER_CARD_SITE = '' # The site's Twitter handle like @my_blog\nTWITTER_CARD_SITE_ID = '' # The site's Twitter ID\nTWITTER_CARD_CREATOR = '@djhoese' # Your twitter handle like @monkmartinez\nTWITTER_CARD_CREATOR_ID = '' # The site creator's id\nGRAVATAR_URL = ''\n\n","repo_name":"djhoese/djhoese.github.io-src","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72543851568","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport cv2\nimport libbgs\nfrom mean_shift_lib import mean_shift as ms\n\n\n#光流检测的参数\nlk_params = dict( winSize = (15, 15),#搜索窗口的大小\n maxLevel = 2,#最大的金字塔层数\n # 指定停止条件,具体没懂\n criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))\n\n#角点检测的参数\nfeature_params = dict( maxCorners = 1000,#最大角点数\n qualityLevel = 0.3,#角点最低质量\n minDistance = 7,#角点间最小欧式距离\n blockSize = 7 )#这个没懂,我做角点检测时只设置了上面几个参数,望指教\n\n\nclass App:\n def __init__(self, video_src):\n self.track_len = 10\n self.detect_interval = 2\n self.tracks = []\n self.cam = cv2.VideoCapture(video_src)\n self.frame_idx = 0\n\n def run(self):\n\n #bgs = libbgs.DPAdaptiveMedian()\n\n while True:\n #cv2.waitKey(500)\n ret, frame = self.cam.read()#通过摄像头获取一张图片\n if ret:\n frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)#转化为灰度图\n vis = frame.copy()#赋值frame的值,不覆盖frame本身\n\n if len(self.tracks) > 0:#检测到角点后进行光流跟踪\n img0, img1 = self.prev_gray, frame_gray\n p0 = np.float32([tr[-1] for tr in self.tracks]).reshape(-1, 1, 2)#对np数组进行重塑\n #前一帧的角点和当前帧的图像作为输入来得到角点在当前帧的位置,有点绕,具体实现有兴趣就去看源码吧\n p1, st, err = cv2.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params)\n #当前帧跟踪到的角点及图像和前一帧的图像作为输入来找到前一帧的角点位置\n p0r, st, err = cv2.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params)\n d = abs(p0-p0r).reshape(-1, 2).max(-1)#得到角点回溯与前一帧实际角点的位置变化关系\n good = d < 1#判断d内的值是否小于1,大于1跟踪被认为是错误的跟踪点,为什么是1不知道\n new_tracks = []\n #将跟踪正确的点列入成功跟踪点\n for tr, (x, y), good_flag in zip(self.tracks, p1.reshape(-1, 2), good):\n if not good_flag:\n continue\n tr.append((x, y))\n if len(tr) > self.track_len:\n del tr[0]\n new_tracks.append(tr)\n cv2.circle(vis, (x, y), 2, (0, 255, 0), -1)#画圆\n self.tracks = new_tracks\n\n #以上一振角点为初始点,当前帧跟踪到的点为终点划线\n cv2.polylines(vis, [np.int32(tr) for tr in self.tracks], False, (0, 255, 0))\n\n #draw_str(vis, (20, 20), 'track count: %d' % len(self.tracks))\n\n newFrame =np.zeros((500,500))\n\n #if self.frame_idx % self.detect_interval == 0:#每5帧检测一次特征点\n mask = np.zeros_like(frame_gray) # 初始化和视频大小相同的图像\n mask[:] = 255 # 将mask赋值255也就是算全部图像的角点\n\n pointsList = []\n\n for x, y in [np.int32(tr[-1]) for tr in self.tracks]: # 跟踪的角点画圆\n cv2.circle(mask, (x, y), 5, 0, -1)\n curPoint = [float(x), float(y)]\n pointsList.append(curPoint)\n resPoints = np.array(pointsList)\n\n res = self.mean_shift_runner(resPoints)\n newFrame = self.process_shiftPoints(res, frame.shape[0], frame.shape[1])\n\n p = cv2.goodFeaturesToTrack(frame_gray, mask=mask, **feature_params) # 角点检测\n if p is not None:\n for x, y in np.float32(p).reshape(-1, 2):\n self.tracks.append([(x, y)]) # 将检测到的角点放在待跟踪序列中\n\n self.frame_idx += 1\n self.prev_gray = frame_gray\n\n\n\n #img_output = bgs.apply(vis)\n cv2.imshow('lk_track', vis)\n cv2.moveWindow('lk_track', 100, 100)\n\n cv2.imshow('nf', newFrame)\n cv2.moveWindow('nf', 100, 300)\n\n # cv2.imshow('res',img_output)\n #cv2.moveWindow('res', 100, 300)\n\n ch = 0xFF & cv2.waitKey(1)#按esc退出\n if ch == 27:\n break\n\n def mean_shift_runner(self,points):\n print(points)\n\n mean_shifter = ms.MeanShift()\n mean_shift_result = mean_shifter.cluster(points, kernel_bandwidth=3)\n\n print(mean_shift_result.shifted_points)\n print(\"===========================\")\n return mean_shift_result.shifted_points\n\n\n\n def process_shiftPoints(self,points,dimensionX,dimensionY):\n result = np.zeros((500,500))\n for i in range(len(points)):\n print(points[i])\n X = int(points[i][0])\n Y = int(points[i][1])\n result[X][Y] = 255\n return result\n\n\ndef main():\n # import sys\n # try: video_src = sys.argv[1]\n # except: video_src = 0\n #\n # print __doc__\n # App(video_src).run()\n\n\n video_src = \"../dataset/Shake/cars7.avi\"\n App(video_src).run()\n\n\n\n\n\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n main()\n","repo_name":"evercx/Foreground_Target_Extraction","sub_path":"core/LK.py","file_name":"LK.py","file_ext":"py","file_size_in_byte":5458,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"20"} +{"seq_id":"73923856712","text":"from PIL import Image, ImageFilter\nfrom os import listdir\nfrom os.path import isfile, join\n\n\ndef loop_images(source, dest):\n onlyfiles = [f for f in listdir(source) if isfile(join(source, f))]\n for file in onlyfiles:\n if (file == \".DS_Store\"):\n continue\n print(\"reading file: \", file)\n img = Image.open(source + file)\n blurred = blur_image(img)\n blurred.save(dest + \"blurred_\" + file)\n img.save(dest + file)\n\n\ndef blur_image(img):\n return img.filter(ImageFilter.GaussianBlur(5))\n\n\nloop_images(\"images_rotated_32/\", \"images_rotated_blurred_32/\")","repo_name":"EinarJohnsen/image_classification_ict440","sub_path":"image_blurer.py","file_name":"image_blurer.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"25942825986","text":"from threading import Thread, Lock\nfrom django.db import models\n\nlock = Lock()\n\n\nclass ThreadWithReturnValue(Thread):\n def __init__(\n self,\n group=None,\n target=None,\n name=None,\n args=(),\n kwargs={},\n Verbose=None\n ):\n Thread.__init__(self, group, target, name, args, kwargs)\n self._return = None\n self.exc = None\n\n def run(self):\n lock.acquire()\n print('running')\n if self._target is not None:\n try:\n self._return = self._target(\n *self._args,\n **self._kwargs\n )\n except Exception as e:\n self.exc = e\n\n def join(self, *args):\n print('joining')\n Thread.join(self, *args)\n print('joined')\n lock.release()\n if self.exc:\n raise self.exc\n return self._return\n\n\nclass BaseQuerySet(models.query.QuerySet):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # Iterate in a thread-safe manner\n def __iter__(self):\n thread = ThreadWithReturnValue(target=super().__iter__)\n thread.start()\n return thread.join()\n\n\nclass BaseManager(models.Manager):\n def get_queryset(self):\n return BaseQuerySet(model=self.model)\n\n # Get in a thread-safe manner\n def get(self, *args, **kwargs):\n thread = ThreadWithReturnValue(target=super().get,\n args=args, kwargs=kwargs)\n thread.start()\n return thread.join()\n\n\nclass BaseModel(models.Model):\n objects = BaseManager()\n\n # Save in a thread-safe manner\n def save(self, *args, **kwargs):\n thread = ThreadWithReturnValue(\n target=super().save,\n args=args,\n kwargs=kwargs\n )\n thread.start()\n return thread.join()\n\n # Delete in a thread-safe manner\n def delete(self, *args, **kwargs):\n thread = ThreadWithReturnValue(\n target=super().delete,\n args=args,\n kwargs=kwargs\n )\n thread.start()\n return thread.join()\n\n class Meta:\n abstract = True\n\n\nclass Example(BaseModel):\n name = models.CharField(max_length=100)\n description = models.CharField(max_length=255)\n","repo_name":"vitornere/django-orm-async-adapter","sub_path":"example/example/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"38474344232","text":"\"\"\"\n===== Initial Thoughts =====\nCan be solved simply by storing letters -> widths in a dict then iterating over the string\neach time string goes to the next \"line\" you can increment a counter +1. \n\nif limit is instead 10\nso if a => 6\naaa we'll have 6,6,6 => [3, 6]\nif a => 4 and aaaa, 4-4, 4-4 => [2, 8]\n4,4,4,4... we'll accumulate \n4-4 (since 12 would be >10, we reset counter to 0, incremenet line counter by 1)\n\n=== Implemented Approach ===\nimplementing the above, seems pretty straight-forward...\n\n~~Complexity Analysis\nTime - O(n)\nSpace - O(1)\n\"\"\"\n\nclass Solution:\n def numberOfLines(self, widths: List[int], s: str) -> List[int]:\n get_width = lambda char: widths[ord(char) - ord(\"a\")]\n width_counter = 0\n line_counter = 1\n for char in s:\n width = get_width(char)\n if (width + width_counter) > 100:\n width_counter = width\n line_counter += 1\n else:\n width_counter += width\n return [line_counter, width_counter]\n","repo_name":"jsphweid/chops","sub_path":"lc/answers/number-of-lines-to-write-string/2021.09.22-20.55.50.py","file_name":"2021.09.22-20.55.50.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"31663869488","text":"from data.globalConstants import *\r\n# Barry Windham\r\nname = 'Barry Windham'\r\n\r\n# General Card Definitions: \r\n# 1000 = OC\r\n# 1001 = OC/TT\r\n# 1002 = DC\r\nGeneralCard = [1002, 1000, 1000, 1000, 1002, 1002, 1001, 1000, 1000, 1000, 1002]\r\n\r\n# Offensive Card Definitions:\r\n# 1003 = Pin attempt move (P/A)\r\n# 1004 = Submission Move (*)\r\n# 1005 = Specialty Move (S)\r\n# 1006 = Disqualification Move (DQ)\r\n# 1008 = Regular Offensive Move\r\n# 1009 = Grudge Match Move (XX)\r\n# 1010 = Ropes Move (ROPES)\r\nOffensiveCard = \\\r\n[ {'MOVE_POINTS': 7, 'MOVE_TYPE': 1008, 'MOVE_NAME': 'OUTSIDE ARM BAR'},\r\n {'MOVE_POINTS': 6, 'MOVE_TYPE': 1003, 'MOVE_NAME': 'RIGHT UPPERCUT'},\r\n {'MOVE_TYPE': 1005, 'MOVE_NAME': 'BULLDOG'},\r\n { 'MOVE_NAME': 'ATTACK DELTOID MUSCLE',\r\n 'MOVE_POINTS': 7,\r\n 'MOVE_TYPE': 1008},\r\n {'MOVE_POINTS': 8, 'MOVE_TYPE': 1008, 'MOVE_NAME': 'AERIAL HIP TOSS'},\r\n {'MOVE_POINTS': 8, 'MOVE_TYPE': 1008, 'MOVE_NAME': 'FLYING DROPKICK'},\r\n { 'MOVE_NAME': 'ARM WHIP INTO RING POST',\r\n 'MOVE_POINTS': 8,\r\n 'MOVE_TYPE': 1008},\r\n {'MOVE_POINTS': 7, 'MOVE_TYPE': 1008, 'MOVE_NAME': 'TWISTING REVERSE'},\r\n {'MOVE_POINTS': 7, 'MOVE_TYPE': 1008, 'MOVE_NAME': 'ARMDRAG TAKE-DOWN'},\r\n {'MOVE_POINTS': 6, 'MOVE_TYPE': 1009, 'MOVE_NAME': 'COWBOY LARIAT'},\r\n {'MOVE_TYPE': 1010, 'MOVE_NAME': 'ROPES'}]\r\n\r\n# Defensive Card Definitions:\r\n# 0 = B - No points on defense\r\n# 2 = A - 2 points on defense\r\n# 4 = C - 4 points on defense and neutralize offensive move\r\n# 5 = Reverse - Reverse offensive move\r\nDefensiveCard = [0, 0, 0, 2, 2, 2, 0, 4, 5, 2, 2]\r\n\r\n# Specialty Card Definitions:\r\n# 1003 = Pin attempt move (P/A)\r\n# 1004 = Submission Move (*)\r\n# 1005 = Specialty Move (S)\r\nSpecialty = { 'BULLDOG': [ {'MOVE_POINTS': 11, 'MOVE_TYPE': 1005},\r\n {'MOVE_POINTS': 9, 'MOVE_TYPE': 1005},\r\n {'MOVE_POINTS': 9, 'MOVE_TYPE': 1003},\r\n {'MOVE_POINTS': 10, 'MOVE_TYPE': 1005},\r\n {'MOVE_POINTS': 10, 'MOVE_TYPE': 1003},\r\n {'MOVE_POINTS': 11, 'MOVE_TYPE': 1005}]}\r\n\r\n# Ropes Card Definitions:\r\n# 1003 = Pin attempt move (P/A)\r\n# 1004 = Submission Move (*)\r\n# 1005 = Specialty Move (S)\r\n# 1006 = Disqualification Move (DQ)\r\n# 1008 = Regular Offensive Move\r\n# 1009 = Grudge Match Move (XX)\r\n# 1010 = Ropes Move (ROPES)\r\n# 1014 = No Action (NA)\r\nRopes = \\\r\n[ {'MOVE_POINTS': 0, 'MOVE_TYPE': 1014, 'MOVE_NAME': 'NA'},\r\n {'MOVE_POINTS': 10, 'MOVE_TYPE': 1008, 'MOVE_NAME': 'FLYING BODYPRESS'},\r\n {'MOVE_POINTS': 0, 'MOVE_TYPE': 1014, 'MOVE_NAME': 'NA'},\r\n {'MOVE_POINTS': 7, 'MOVE_TYPE': 1008, 'MOVE_NAME': 'SPIN UNDER TAKE-DOWN'},\r\n {'MOVE_POINTS': 7, 'MOVE_TYPE': 1008, 'MOVE_NAME': 'FLYING DROPKICK'},\r\n {'MOVE_POINTS': 5, 'MOVE_TYPE': 1008, 'MOVE_NAME': 'COWBOY LARIAT'},\r\n {'MOVE_POINTS': 8, 'MOVE_TYPE': 1003, 'MOVE_NAME': 'FLYING DROP KICK'},\r\n {'MOVE_POINTS': 9, 'MOVE_TYPE': 1003, 'MOVE_NAME': 'BACK BODY DROP'},\r\n {'MOVE_POINTS': 0, 'MOVE_TYPE': 1014, 'MOVE_NAME': 'NA'},\r\n {'MOVE_POINTS': 6, 'MOVE_TYPE': 1008, 'MOVE_NAME': 'LARIAT'},\r\n {'MOVE_POINTS': 0, 'MOVE_TYPE': 1014, 'MOVE_NAME': 'NA'}]\r\n\r\nSub = (2, 4)\r\nTagTeam = (8, 12)\r\nPriority = (3, 3)\r\nnameSet = \"Promoter's Dream\"\r\n","repo_name":"BackupTheBerlios/pws","sub_path":"Wrestlers/BarryWindham.py","file_name":"BarryWindham.py","file_ext":"py","file_size_in_byte":3319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"3450579288","text":"from django import template\nfrom remember.models import UserLogFB,RememberPlaceFB,RememberPlaceVk,UserLogVk\nfrom django.contrib.auth.models import User\nimport re\nregister = template.Library()\n\nusers_modelAll = [UserLogFB,UserLogVk]\nremembers_modelsAll = [RememberPlaceVk,RememberPlaceFB]\n#\n@register.filter\ndef verify_user(value):\n global first_name\n first_name = value\n for elements in users_modelAll:\n try:\n fullname = elements.objects.get(user=value)\n list_releted = [res for data in elements.objects.all() if data.user == value for res in data.releted_place]\n len_change_list = len(list(set(list_releted)))\n\n if len_change_list == 0:\n return \"You don't have any memories\"\n return \"Add more memories\"\n\n except:\n provider = None\n for obj in User.objects.all():\n if obj.first_name == value:\n provider = obj.username\n matches = re.findall('id[1-9]*', provider)\n\n if len(matches) == 0:\n try:\n create_user = UserLogFB.objects.create(user=value)\n create_user.save()\n return \"You don't have any memories\"\n except:\n return \"You don't have any memories\"\n\n try:\n create_user = UserLogVk.objects.create(user=value)\n create_user.save()\n return \"You don't have any memories\"\n except:\n return \"You don't have any memories\"\n\n#\n@register.simple_tag\ndef place():\n dict_user_name = dict()\n\n for objects in users_modelAll:\n for data in objects.objects.all():\n if data.user == first_name:\n for tuple_obj in data.releted_place.values_list():\n dict_user_name[tuple_obj[1]] = [tuple_obj[2]]\n\n return dict_user_name\n\n\n#\n@register.simple_tag\ndef tag_pk():\n return first_name\n","repo_name":"Shohmasud/place_remember","sub_path":"remember/templatetags/filters_tags_templatetags.py","file_name":"filters_tags_templatetags.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"17524928291","text":"import os\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"prs_project.settings\")\n\nimport django\nimport json\nimport numpy as np\n\nimport pyLDAvis\nimport pyLDAvis.gensim\n\nimport operator\nimport math\n\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.stem.porter import PorterStemmer\nfrom stop_words import get_stop_words\nfrom gensim import corpora, models, similarities\n\ndjango.setup()\n\nfrom recommender.models import MovieDescriptions\n\n\ndef dot_product(v1, v2):\n dp = sum(map(operator.mul, v1, v2))\n return dp\n\n\ndef vector_cos(v1, v2):\n prod = dot_product(v1, v2)\n sqrt1 = math.sqrt(dot_product(v1, v1))\n sqrt2 = math.sqrt(dot_product(v2, v2))\n return prod / (sqrt1 * sqrt2)\n\n\ndef cosine_similarity(ldas):\n size = ldas.shape[0]\n similarity_matrix = np.zeros((size,size))\n\n for i in range(ldas.shape[0]):\n\n for j in range(ldas.shape[0]):\n similarity_matrix[i, j] = vector_cos(ldas[i,], ldas[j, ])\n\n return similarity_matrix\n\n\ndef load_data():\n docs = list(MovieDescriptions.objects.all())\n data = [\"{}, {}, {}\".format(d.title, d.genres, d.description) for d in docs]\n\n if len(data) == 0:\n print(\"No descriptions were found, run populate_sample_of_descriptions\")\n return data, docs\n\n\nclass LdaModel(object):\n\n def train(self, data, docs):\n\n NUM_TOPICS = 50\n n_products = len(data)\n self.lda_path = './../lda/'\n if not os.path.exists(self.lda_path):\n os.makedirs(self.lda_path)\n\n dictionary, texts, lda_model = self.build_lda_model(data, docs, NUM_TOPICS)\n\n def tokenize(data):\n tokenizer = RegexpTokenizer(r'\\w+')\n\n return [tokenizer.tokenize(d) for d in data]\n\n\n def build_lda_model(self, data, docs, n_topics=5):\n\n texts = []\n tokenizer = RegexpTokenizer(r'\\w+')\n for data in data:\n raw = data.lower()\n\n tokens = tokenizer.tokenize(raw)\n\n stopped_tokens = self.remove_stopwords(tokens)\n\n stemmed_tokens = stopped_tokens\n #stemmer = PorterStemmer()\n #stemmed_tokens = [stemmer.stem(token) for token in stopped_tokens]\n\n texts.append(stemmed_tokens)\n\n dictionary = corpora.Dictionary(texts)\n\n corpus = [dictionary.doc2bow(text) for text in texts]\n\n lda_model = models.ldamodel.LdaModel(corpus=corpus, id2word=dictionary,\n num_topics=n_topics)\n\n\n\n index = similarities.MatrixSimilarity(corpus)\n\n index.save(self.lda_path + 'index.lda')\n for i in range(len(texts)):\n docs[i].lda_vector = i\n docs[i].save()\n\n self.save_lda_model(lda_model, corpus, dictionary)\n\n return dictionary, texts, lda_model\n\n def save_lda_model(self, lda_model, corpus, dictionary):\n pyLDAvis.save_json(pyLDAvis.gensim.prepare(lda_model, corpus, dictionary), './../static/js/lda.json')\n print(lda_model.print_topics())\n lda_model.save(self.lda_path + 'model.lda')\n\n dictionary.save(self.lda_path + 'dict.lda')\n corpora.MmCorpus.serialize(self.lda_path + 'corpus.mm', corpus)\n\n def remove_stopwords(self, tokenized_data):\n en_stop = get_stop_words('en')\n\n stopped_tokens = [token for token in tokenized_data if token not in en_stop]\n return stopped_tokens\n\nif __name__ == '__main__':\n print(\"Calculating lda model...\")\n\n data, docs = load_data()\n\n lda = LdaModel()\n lda.train(data, docs)\n","repo_name":"maidousi/moviegeek","sub_path":"builder/lda_model_calculator.py","file_name":"lda_model_calculator.py","file_ext":"py","file_size_in_byte":3492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"7902704056","text":"\"\"\"\nYou are given a stream of points on the X-Y plane. Design an algorithm that:\n\n Adds new points from the stream into a data structure. Duplicate points are allowed and should be treated as different points.\n Given a query point, counts the number of ways to choose three points from the data structure such that the three points and the query point form an axis-aligned square with positive area.\n\nAn axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis.\n\nImplement the DetectSquares class:\n\n DetectSquares() Initializes the object with an empty data structure.\n void add(int[] point) Adds a new point point = [x, y] to the data structure.\n int count(int[] point) Counts the number of ways to form axis-aligned squares with point point = [x, y] as described above.\n\n\n\n1, 2\n\n\n4\n\n3 \n\n2 - -\n\n1 - - -\n\n0 1 2 3 4 \n\n\n\ngiven the query point, find points that make a line of 45degree\nremember to check p1.x == p2.x\n\nabs(p1.x - p2.x) == abs(p1.y - p2.y)\n\nif that is true we can check if the other two maching points exist\n\nhave a dict counter for the points, \n\nCheck if \n\n\nO(P) time complexity for the count\nO(1) time for the add\nO(P) space complexity\n\n\n\n\"\"\"\nimport collections\nfrom typing import List, Dict\n\n\nPoint = collections.namedtuple('Point', 'x y')\n\n\nclass DetectSquares:\n\n def __init__(self):\n self.points: Dict[Point, int] = collections.defaultdict(int)\n\n def add(self, point: List[int]) -> None:\n self.points[Point(*point)] += 1\n\n def count(self, point: List[int]) -> int:\n curr: Point = Point(*point)\n result: int = 0\n for x, y in self.points:\n if x == curr.x or abs(x - curr.x) != abs(y - curr.y):\n continue\n result += (\n self.points.get((x, y), 0) * \n self.points.get((curr.x, y), 0) *\n self.points.get((x, curr.y), 0)\n )\n return result\n\n\n\n# Your DetectSquares object will be instantiated and called as such:\n# obj = DetectSquares()\n# obj.add(point)\n# param_2 = obj.count(point)\n","repo_name":"JadielTeofilo/General-Algorithms","sub_path":"src/leetcode/google_list/2013_detect_squares.py","file_name":"2013_detect_squares.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"21197582593","text":"#Variation of equilibrium products mole fractions (mainly CO2 CO and NOx) with different P_c.\r\n\r\nimport cantera as ct\r\nimport numpy as np\r\nimport sys\r\nimport csv\r\n\r\n# Edit these parameters to change the initial temperature, the pressure, and\r\n# the phases in the mixture.\r\n\r\nT = 1000.0\r\nphi = 0.9\r\n\r\n# phases\r\ngas = ct.Solution('JP10.yaml')\r\ncarbon = ct.Solution('graphite.yaml')\r\n\r\n# the phases that will be included in the calculation, and their initial moles\r\nmix_phases = [(gas, 1.0), (carbon, 0.0)]\r\n\r\n# gaseous fuel species\r\nfuel_species = 'C10H16'\r\n\r\n# equivalence ratio range\r\nnpoints = 50\r\nP = np.linspace(0.1, 100, npoints)\r\n\r\nmix = ct.Mixture(mix_phases)\r\n\r\n# create some arrays to hold the data\r\ntad = np.zeros(npoints)\r\nxeq = np.zeros((mix.n_species, npoints))\r\n\r\nxeq_CO = np.zeros(npoints)\r\nxeq_CO2 = np.zeros(npoints)\r\n\r\nfor i in range(npoints):\r\n # set the gas state\r\n gas.set_equivalence_ratio(phi, fuel_species, 'O2:1.0, N2:3.76')\r\n\r\n # create a mixture of 1 mole of gas, and 0 moles of solid carbon.\r\n mix = ct.Mixture(mix_phases)\r\n mix.T = T\r\n mix.P = P[i]\r\n\r\n # equilibrate the mixture adiabatically\r\n mix.equilibrate('HP', solver='gibbs', max_steps=1000)\r\n\r\n tad[i] = mix.T\r\n xeq[:, i] = mix.species_moles\r\n xeq_CO[i] = xeq[11,i]\r\n xeq_CO2[i] = xeq[24,i]\r\n print('At pressure = {0:12.4g}, Xco = {1:12.4g}, Xco2 = {2:12.4g}'.format(P[i], xeq[11,i], xeq[24,i]))\r\n \r\n\r\n# write output CSV file for importing into Excel\r\ncsv_file = 'Molefraction.csv'\r\nwith open(csv_file, 'w', newline='') as outfile:\r\n writer = csv.writer(outfile)\r\n writer.writerow(['P', 'T (K)'] + mix.species_names)\r\n for i in range(npoints):\r\n writer.writerow([P[i], tad[i]] + list(xeq[:, i]))\r\nprint('Output written to {0}'.format(csv_file))\r\n\r\nif '--plot' in sys.argv:\r\n import matplotlib.pyplot as plt \r\n plt.plot(P, xeq_CO)\r\n plt.plot(P, xeq_CO2) \r\n plt.xlabel('pressure')\r\n plt.ylabel('Mole fraction')\r\n plt.legend(['CO','CO2'])\r\n plt.show() \r\n \r\n \r\n","repo_name":"Smiley-2307/molefraciton-variation-with-pressure","sub_path":"moleFraction with pressure.py","file_name":"moleFraction with pressure.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"21844091918","text":"\"\"\" This module contains the configuration variables needed by the app\"\"\"\nimport json\n\n\ndef _json_read_key(data, key):\n \"\"\"\n Read the value of a key\n Args:\n data (str): The value of the parameter\n key (str): The name of the parameter\n Returns:\n data[key]: The value of the key, None if not provided\n \"\"\"\n try:\n return data[key]\n except KeyError:\n return None\n\n\ndef _require_key(value, name):\n \"\"\"\n Check if a key is provided if required to continue\n (Method not currently in use)\n Args:\n value (str): The value of the parameter\n name (str): The name of the parameter\n Raises:\n KeyError: If key/value is not specified in config.json\n \"\"\"\n\n # Currently not required\n if value is None:\n raise KeyError(\"Missing required configuration key: '%s'\" % name)\n\n\nclass Config:\n \"\"\"\n The configuration of the Flask app, can be used to update the app object\n \"\"\"\n\n def __init__(self):\n self.port = None\n self.host = None\n self.cors_origins = None\n\n def from_json(self, data):\n \"\"\"\n Pulls information from config.json. Should be updated as json is modified.\n Args:\n data (str): config.json\n Updates:\n self.port (int): port to run Flask app on\n self.host (str): ip to run Flask app on\n \"\"\"\n data = json.loads(data)\n self.port = _json_read_key(data, \"port\")\n self.host = _json_read_key(data, \"host\")\n self.cors_origins = _json_read_key(data, \"cors_origins\")\n\n # Set port and host to default if not specified\n if self.port is None:\n self.port = 5000\n\n if self.host is None:\n self.host = \"127.0.0.1\"\n\n def get_dict(self):\n \"\"\"\n Returns the parameters for configuration of the app object\n Returns:\n configs (dict): Contains all parameters in config.json\n \"\"\"\n # Require that CORS_DOMAINS has been provided and it can be iterated\n _require_key(self.cors_origins, \"CORS_DOMAINS\")\n if not hasattr(self.cors_origins, \"__iter__\"):\n raise TypeError\n\n return {\n \"PORT\": self.port,\n \"HOST\": self.host,\n \"CORS_ORIGINS\": self.cors_origins\n }\n","repo_name":"DeepNeuron-AI/evaluator-backend","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"15306832299","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom .models import Post, Comment, Like, User\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import View\nfrom django.http import HttpResponseRedirect\nfrom .forms import Regform, PostForm\nimport datetime\n\n\ndef index(request):\n registration_form = Regform\n post_form = PostForm\n\n if request.user.is_authenticated:\n posts = Post.objects.all()\n curr_time = datetime.date.today()\n return render(request, 'Website/index.html', {'posts': posts, 'post_form': post_form, 'curr_time': curr_time})\n\n return render(request, 'Website/index.html', {'reg_form': registration_form})\n\n\nclass register(View):\n form_class = Regform\n\n def get(self, request):\n form = self.form_class(None)\n return render(request, 'Website/index.html', {'form': form})\n\n def post(self, request):\n form = self.form_class(request.POST)\n already_member = True\n\n if form.is_valid():\n user = form.save(commit=False)\n\n firstname = form.cleaned_data['firstname']\n lastname = form.cleaned_data['lastname']\n username = form.cleaned_data['username']\n email = form.cleaned_data['email']\n password = form.cleaned_data['password']\n user.set_password(password)\n\n user.first_name = firstname\n user.last_name = lastname\n user.save()\n\n user = authenticate(username=username, password=password)\n\n login(request, user)\n return redirect('index')\n\n posts = Post.objects.all()\n return render(request, 'Website/index.html', {'already_member': already_member, 'posts': posts})\n\n\n@method_decorator(login_required, name='dispatch')\nclass AddPost(View):\n form_class = PostForm\n\n def get(self, request):\n form = self.form_class(None)\n return render(request, 'Website/index.html', {'form': form})\n\n def post(self, request):\n form = self.form_class(request.POST)\n already_member = True\n\n if form.is_valid():\n post = Post()\n post = form.save(commit=False)\n\n post.user = request.user\n post_content = form.cleaned_data['post_content']\n post.content = post_content\n post.time = datetime.datetime.now()\n post.date = datetime.date.today()\n post.save()\n\n return redirect('index')\n\n posts = Post.objects.all()\n return redirect('index')\n\n\n@login_required\ndef show_profile(request, username):\n posts = Post.objects.all()\n user = User.objects.get(username=username)\n return render(request, 'Website/show_profile.html', {'posts': posts, 'user': user})\n\n\ndef likepost(request, postid):\n current_post = Post.objects.get(pk=postid)\n current_post.like_count = 1 - current_post.like_count\n current_post.save()\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n","repo_name":"abyswp/Social-Network","sub_path":"Website/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"17245246211","text":"# -*- coding: utf-8 -*-\nimport os.path\nfrom urlparse import urlparse\nimport yaml\n\n\nRC_LOCATIONS = (os.path.expanduser(\"~/.py_razor_clientrc\"),\n os.path.join(\"/\", \"etc\", \"py_razor_client\"))\n\n\nclass NoSuchConfigFileException(Exception):\n pass\n\n\nclass InsufficientHostException(Exception):\n pass\n\n\ndef dynamicize_argparser(parser, args):\n \"\"\"Given an ArgumentParser, tries to coerce the ArgumentParser to have\n options for each unknown --longopt it encounters.\n\n This exists to provide a compatibility shim to allow this tool to be used\n in the same manner as the pure-ruby optparse that powers razor-client.\n \"\"\"\n _, unknown_args = parser.parse_known_args(args)\n unknown_longopts = filter_for_longopts(unknown_args)\n\n added_args = []\n\n for opt in unknown_longopts:\n add_result = parser.add_argument(opt)\n dest = add_result.dest\n added_args.append(dest)\n\n return (parser, added_args)\n\n\ndef filter_for_longopts(arglist):\n \"\"\"Given a list of arguments, filter out any that aren't --longopts.\"\"\"\n return filter(lambda x: x.startswith(\"--\"), arglist)\n\n\ndef load_config(config_file=None):\n \"\"\"Loads a configuration from a given file, from ~/.py_razor_clientrc, or\n /etc/py_razor_client if it exists.\n\n Precedence is always given to a config file specified on the command line.\n \"\"\"\n if config_file:\n if not os.path.exists(config_file):\n raise NoSuchConfigFileException()\n else:\n rc_files = filter(os.path.exists, RC_LOCATIONS)\n if rc_files:\n config_file = rc_files[0]\n else:\n config_file = None\n\n if config_file:\n with open(config_file) as f:\n return yaml.load(f.read())\n else:\n return {}\n\n\ndef make_config(args):\n config = vars(args)\n config.update(load_config(args.config))\n\n if config['url']:\n bits = urlparse(config['url'])\n host = bits[1]\n hostname, port = host.split(\":\")\n config.update(hostname=hostname, port=port)\n del config['url']\n\n if not (config['hostname'] and config['port']):\n raise InsufficientHostException()\n\n return config\n","repo_name":"fhats/py_razor_client","sub_path":"py_razor_client/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"27616299293","text":"class Solution:\n def largestRectangleArea(self, heights: list[int]) -> int:\n stack = [] # (index, height)\n max_area = -1\n\n for i, height in enumerate(heights):\n start = i\n while stack and height < stack[-1][1]: \n i_left, h = stack.pop()\n print(i, i_left, h)\n max_area = max(max_area, (i - i_left) * h)\n start = i_left\n stack.append((start, height))\n\n for i_l, h in stack:\n max_area = max(max_area, (i - i_l + 1) * h)\n return max_area","repo_name":"vnagpal25/Leet_Code_Solutions","sub_path":"84.py","file_name":"84.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"33471234749","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport schedule\nimport time\nfrom twilio.rest import Client\n\nclient = Client('ACb89307719aa8043871f9912452ef21c6','2f56bc2c9d8ae27afa3baf74fb46f0cb')\n\nvictim = \"\"\n\ndef job1():\n\tclient.messages.create(from_=\"+12175763259\",to=victim,body=\"NOON\")\n\ndef job2():\n\tclient.messages.create(from_=\"+12175763259\",to=victim,body=\"Midnight\")\n\ninit_msg = \"You are now subscribed to automated texts to assist\" + \\\n \" you in scheduling a lunch and/or dinner date with Steven.\" + \\\n \" You will be reminded twice a day.\" + \\\n \" To stop these texts type \\\"pls stahp.\\\"\" + \\\n \" To schedule a date please type \\\"I am ready to schedule a date.\\\"\" + \\\n \" To report a bug in the software please type \\\"bug: \\\" followed by a description of the bug.\" + \\\n \" For more information please type \\\"information.\\\"\"\n\nclient.messages.create(from_=\"+12175763259\",to=victim,body=init_msg)\n\nschedule.every().day.at(\"12:00\").do(job1)\nschedule.every().day.at(\"00:00\").do(job2)\n\nwhile True:\n\tschedule.run_pending()\n\ttime.sleep(1)\n","repo_name":"sjschmidt93/msgk","sub_path":"sched.py","file_name":"sched.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"26223944439","text":"import random\nimport json\nimport os\nimport sys\nfrom src.parse_args import args\nos.environ['CUDA_VISIBLE_DEVICES'] = '{}'.format(args.gpu)\n\nimport src.common.ops as ops\nimport src.data_processor.data_loader as data_loader\nimport src.data_processor.processor_utils as data_utils\nfrom src.data_processor.data_processor import preprocess\nfrom src.data_processor.vocab_processor import build_vocab\nfrom src.data_processor.schema_graph import SchemaGraph\nfrom src.data_processor.path_utils import get_model_dir, get_checkpoint_path\nfrom src.demos.demos import Text2SQLWrapper\nimport src.eval.eval_tools as eval_tools\nfrom src.eval.wikisql.lib.dbengine import DBEngine\nfrom src.semantic_parser.ensemble_configs import model_dirs as ensemble_model_dirs\nfrom src.semantic_parser.learn_framework import EncoderDecoderLFramework\nfrom src.trans_checker.args import args as cs_args\nimport src.utils.utils as utils\n\nimport torch\n# if not args.data_parallel:\n# torch.cuda.set_device('cuda:{}'.format(args.gpu))\ntorch.manual_seed(args.seed)\ntorch.cuda.manual_seed_all(args.seed)\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# Set model ID\nargs.model_id = utils.model_index[args.model]\nassert(args.model_id is not None)\n\n\ndef train(sp):\n dataset = data_loader.load_processed_data(args)\n train_data = dataset['train']\n print('{} training examples loaded'.format(len(train_data)))\n dev_data = dataset['dev']\n print('{} dev examples loaded'.format(len(dev_data)))\n\n if args.xavier_initialization:\n ops.initialize_module(sp.mdl, 'xavier')\n else:\n raise NotImplementedError\n\n sp.schema_graphs = dataset['schema']\n if args.checkpoint_path is not None:\n sp.load_checkpoint(args.checkpoint_path)\n\n if args.test:\n train_data = train_data + dev_data\n\n sp.run_train(train_data, dev_data)\n\n\ndef inference(sp):\n dataset = data_loader.load_processed_data(args)\n split = 'test' if args.test else 'dev'\n if args.dataset_name == 'wikisql':\n engine_path = os.path.join(args.data_dir, '{}.db'.format(split))\n engine = DBEngine(engine_path)\n else:\n engine = None\n\n def evaluate(examples, out_dict):\n metrics = eval_tools.get_exact_match_metrics(examples, out_dict['pred_decoded'], engine=engine)\n print('Top-1 exact match: {:.3f}'.format(metrics['top_1_em']))\n print('Top-2 exact match: {:.3f}'.format(metrics['top_2_em']))\n print('Top-3 exact match: {:.3f}'.format(metrics['top_3_em']))\n print('Top-5 exact match: {:.3f}'.format(metrics['top_5_em']))\n print('Top-10 exact match: {:.3f}'.format(metrics['top_10_em']))\n if args.dataset_name == 'wikisql':\n print('Top-1 exe match: {:.3f}'.format(metrics['top_1_ex']))\n print('Top-2 exe match: {:.3f}'.format(metrics['top_2_ex']))\n print('Top-3 exe match: {:.3f}'.format(metrics['top_3_ex']))\n print('Top-5 exe match: {:.3f}'.format(metrics['top_5_ex']))\n print('Top-10 exet match: {:.3f}'.format(metrics['top_10_ex']))\n print('Table error: {:.3f}'.format(metrics['table_err']))\n\n examples = dataset[split]\n # random.shuffle(examples)\n sp.schema_graphs = dataset['schema']\n print('{} {} examples loaded'.format(len(examples), split))\n\n if sp.args.use_pred_tables:\n in_table = os.path.join(sp.args.model_dir, 'predicted_tables.txt')\n with open(in_table) as f:\n content = f.readlines()\n assert(len(content) == len(examples))\n for example, line in zip(examples, content):\n pred_tables = set([x.strip()[1:-1] for x in line.strip()[1:-1].split(',')])\n example.leaf_condition_vals_list = pred_tables\n\n sp.load_checkpoint(get_checkpoint_path(args))\n sp.eval()\n\n if sp.args.augment_with_wikisql:\n examples_, examples_wikisql = [], []\n for example in examples:\n if example.dataset_id == data_utils.WIKISQL:\n examples_wikisql.append(example)\n else:\n examples_.append(example)\n examples = examples_\n\n pred_restored_cache = sp.load_pred_restored_cache()\n pred_restored_cache_size = sum(len(v) for v in pred_restored_cache.values())\n # pred_restored_cache = None\n out_dict = sp.inference(examples, restore_clause_order=args.process_sql_in_execution_order,\n pred_restored_cache=pred_restored_cache,\n check_schema_consistency_=args.sql_consistency_check,\n engine=engine, inline_eval=True, verbose=True)\n if args.process_sql_in_execution_order:\n new_pred_restored_cache_size = sum(len(v) for v in out_dict['pred_restored_cache'].values())\n newly_cached_size = new_pred_restored_cache_size - pred_restored_cache_size\n if newly_cached_size > 0:\n sp.save_pred_restored_cache(out_dict['pred_restored_cache'], newly_cached_size)\n\n out_txt = os.path.join(sp.model_dir, 'predictions.{}.{}.{}.txt'.format(args.beam_size, args.bs_alpha, split))\n with open(out_txt, 'w') as o_f:\n assert(len(examples) == len(out_dict['pred_decoded']))\n for i, pred_sql in enumerate(out_dict['pred_decoded']):\n if args.dataset_name == 'wikisql':\n example = examples[i]\n o_f.write('{}\\n'.format(json.dumps(\n {'sql': pred_sql[0], 'table_id': example.db_name})))\n else:\n o_f.write('{}\\n'.format(pred_sql[0]))\n print('Model predictions saved to {}'.format(out_txt))\n\n print('{} set performance'.format(split.upper()))\n evaluate(examples, out_dict)\n if args.augment_with_wikisql:\n wikisql_out_dict = sp.forward(examples_wikisql, verbose=False)\n print('*** WikiSQL ***')\n evaluate(examples_wikisql, wikisql_out_dict)\n\n\ndef ensemble():\n dataset = data_loader.load_processed_data(args)\n split = 'test' if args.test else 'dev'\n dev_examples = dataset[split]\n print('{} dev examples loaded'.format(len(dev_examples)))\n if args.dataset_name == 'wikisql':\n engine_path = os.path.join(args.data_dir, '{}.db'.format(split))\n engine = DBEngine(engine_path)\n else:\n engine = None\n\n sps = [EncoderDecoderLFramework(args) for _ in ensemble_model_dirs]\n for i, model_dir in enumerate(ensemble_model_dirs):\n checkpoint_path = os.path.join(model_dir, 'model-best.16.tar')\n sps[i].schema_graphs = dataset['schema']\n sps[i].load_checkpoint(checkpoint_path)\n sps[i].cuda()\n sps[i].eval()\n\n pred_restored_cache = sps[0].load_pred_restored_cache()\n pred_restored_cache_size = sum(len(v) for v in pred_restored_cache.values())\n\n out_dict = sps[0].inference(dev_examples, restore_clause_order=args.process_sql_in_execution_order,\n pred_restored_cache=pred_restored_cache,\n check_schema_consistency_=args.sql_consistency_check, engine=engine,\n inline_eval=True, model_ensemble=[sp.mdl for sp in sps], verbose=True)\n\n if args.process_sql_in_execution_order:\n new_pred_restored_cache_size = sum(len(v) for v in out_dict['pred_restored_cache'].values())\n newly_cached_size = new_pred_restored_cache_size - pred_restored_cache_size\n if newly_cached_size > 0:\n sps[0].save_pred_restored_cache(out_dict['pred_restored_cache'], newly_cached_size)\n\n out_txt = os.path.join(sps[0].model_dir, 'predictions.ens.{}.{}.{}.{}.txt'.format(\n args.beam_size, args.bs_alpha, split, len(ensemble_model_dirs)))\n with open(out_txt, 'w') as o_f:\n assert(len(dev_examples) == len(out_dict['pred_decoded']))\n for i, pred_sql in enumerate(out_dict['pred_decoded']):\n if args.dataset_name == 'wikisql':\n example = dev_examples[i]\n o_f.write('{}\\n'.format(json.dumps(\n {'sql': pred_sql[0], 'table_id': example.db_name})))\n else:\n o_f.write('{}\\n'.format(pred_sql[0]))\n print('Model predictions saved to {}'.format(out_txt))\n\n print('{} set performance'.format(split.upper()))\n metrics = eval_tools.get_exact_match_metrics(dev_examples, out_dict['pred_decoded'], engine=engine)\n print('Top-1 exact match: {:.3f}'.format(metrics['top_1_em']))\n print('Top-2 exact match: {:.3f}'.format(metrics['top_2_em']))\n print('Top-3 exact match: {:.3f}'.format(metrics['top_3_em']))\n print('Top-5 exact match: {:.3f}'.format(metrics['top_5_em']))\n print('Top-10 exact match: {:.3f}'.format(metrics['top_10_em']))\n\n\ndef error_analysis(sp):\n dataset = data_loader.load_processed_data(args)\n dev_examples = dataset['dev']\n sp.schema_graphs = dataset['schema']\n print('{} dev examples loaded'.format(len(dev_examples)))\n\n if len(ensemble_model_dirs) <= 2:\n print('Needs at least 3 models to perform majority vote')\n sys.exit()\n\n predictions = []\n for model_dir in ensemble_model_dirs:\n pred_file = os.path.join(model_dir, 'predictions.16.txt')\n with open(pred_file) as f:\n predictions.append([x.strip() for x in f.readlines()])\n for i in range(len(predictions)):\n assert(len(dev_examples) == len(predictions[i]))\n \n import collections \n disagree = collections.defaultdict(lambda: collections.defaultdict(list))\n out_txt = 'majority_vote.txt'\n o_f = open(out_txt, 'w')\n for e_id in range(len(dev_examples)):\n example = dev_examples[e_id]\n gt_program_list = example.program_list\n votes = collections.defaultdict(list)\n for i in range(len(predictions)):\n pred_sql = predictions[i][e_id]\n votes[pred_sql].append(i)\n # break ties\n voting_results = sorted(votes.items(), key=lambda x:len(x[1]), reverse=True)\n voted_sql = voting_results[0][0]\n # TODO: the implementation below cheated\n # if len(voting_results) == 1:\n # voted_sql = voting_results[0][0]\n # else:\n # if len(voting_results[0][1]) > len(voting_results[1][1]):\n # voted_sql = voting_results[0][0]\n # else:\n # j = 1\n # while(j < len(voting_results) and len(voting_results[j][1]) == len(voting_results[0][1])):\n # j += 1\n # voting_results = sorted(voting_results[:j], key=lambda x:sum(x[1]))\n # voted_sql = voting_results[0][0]\n o_f.write(voted_sql + '\\n') \n evals = []\n for i in range(len(predictions)):\n eval_results, _, _ = eval_tools.eval_prediction(\n pred=predictions[i][e_id],\n gt_list=gt_program_list,\n dataset_id=example.dataset_id,\n db_name=example.db_name,\n in_execution_order=False\n )\n evals.append(eval_results)\n models_agree = (len(set(evals)) == 1)\n if not models_agree:\n for i in range(len(evals)-1):\n for j in range(1, len(evals)):\n if evals[i] != evals[j]:\n disagree[i][j].append(e_id)\n schema = sp.schema_graphs[example.db_name]\n print('Example {}'.format(e_id+1))\n example.pretty_print(schema)\n for i in range(len(predictions)):\n print('Prediction {} [{}]: {}'.format(i+1, evals[i], predictions[i][e_id]))\n print()\n o_f.close()\n\n for i in range(len(predictions)-1):\n for j in range(i+1, len(predictions)):\n print('Disagree {}, {}: {}'.format(i+1, j+1, len(disagree[i][j])))\n import functools\n disagree_all = functools.reduce(lambda x, y: x & y, [set(l) for l in [disagree[i][j] for i in range(len(disagree)) for j in disagree[i]]])\n print('Disagree all: {}'.format(len(disagree_all)))\n print('Majority voting results saved to {}'.format(out_txt))\n\ndef fine_tune(sp):\n dataset = data_loader.load_processed_data(args)\n fine_tune_data = dataset['fine-tune']\n\n print('{} fine-tuning examples loaded'.format(len(fine_tune_data)))\n dev_data = fine_tune_data\n\n sp.schema_graphs = dataset['schema']\n sp.load_checkpoint(get_checkpoint_path(args))\n\n sp.run_train(fine_tune_data, dev_data)\n\n\ndef process_data():\n \"\"\"\n Data preprocess.\n\n 1. Build vocabulary.\n 2. Vectorize data.\n \"\"\"\n if args.dataset_name == 'spider':\n dataset = data_loader.load_data_spider(args)\n elif args.dataset_name == 'wikisql':\n dataset = data_loader.load_data_wikisql(args)\n else:\n dataset = data_loader.load_data_by_split(args)\n\n # build_vocab(args, dataset, dataset['schema'])\n preprocess(args, dataset, verbose=True)\n\n\ndef demo(args):\n \"\"\"\n Interactive command line demo.\n\n Specify a target database from the Spider dataset and query the database using natural language.\n The output includes:\n 1. if the input question is translated to the SQL query, return the SQL query\n 2. otherwise, return a confusion span in the question that caused the input to be untranslatable.\n \"\"\"\n data_dir = 'data/'\n if args.demo_db is None:\n print('Error: must specify a database name to proceed')\n return\n else:\n db_name = args.demo_db\n db_path = os.path.join(args.db_dir, db_name, '{}.sqlite'.format(db_name))\n schema = SchemaGraph(db_name, db_path=db_path)\n if db_name == 'covid_19':\n in_csv = os.path.join(data_dir, db_name, '{}.csv'.format(db_name))\n in_type = os.path.join(data_dir, db_name, '{}.types'.format(db_name))\n schema.load_data_from_csv_file(in_csv, in_type)\n else:\n # TODO: currently the demo is configured for the Spider dataset.\n import json\n in_json = os.path.join(args.data_dir, 'tables.json')\n with open(in_json) as f:\n tables = json.load(f)\n for table in tables:\n if table['db_id'] == db_name:\n break\n schema.load_data_from_spider_json(table)\n schema.pretty_print()\n\n if args.ensemble_inference:\n t2sql = Text2SQLWrapper(args, cs_args, schema, ensemble_model_dirs=ensemble_model_dirs)\n else:\n t2sql = Text2SQLWrapper(args, cs_args, schema)\n\n sys.stdout.write('Enter a natural language question: ')\n sys.stdout.write('> ')\n sys.stdout.flush()\n text = sys.stdin.readline()\n\n while text:\n output = t2sql.process(text, schema.name)\n translatable = output['translatable']\n sql_query = output['sql_query']\n confusion_span = output['confuse_span']\n replacement_span = output['replace_span']\n print('Translatable: {}'.format(translatable))\n print('SQL: {}'.format(sql_query))\n print('Confusion span: {}'.format(confusion_span))\n print('Replacement span: {}'.format(replacement_span))\n sys.stdout.flush()\n sys.stdout.write('\\nEnter a natural language question: ')\n sys.stdout.write('> ')\n text = sys.stdin.readline()\n\n\ndef run_experiment(args):\n if args.process_data:\n process_data()\n elif args.ensemble_inference and not args.demo:\n get_model_dir(args)\n assert(args.model in ['bridge',\n 'seq2seq',\n 'seq2seq.pg'])\n ensemble()\n else:\n with torch.set_grad_enabled(args.train or args.search_random_seed or args.grid_search or args.fine_tune):\n get_model_dir(args)\n if args.model in ['bridge',\n 'seq2seq',\n 'seq2seq.pg']:\n sp = EncoderDecoderLFramework(args)\n else:\n raise NotImplementedError\n\n sp.cuda()\n if args.train:\n train(sp)\n elif args.inference:\n inference(sp)\n elif args.error_analysis:\n error_analysis(sp)\n elif args.demo:\n demo(args)\n elif args.fine_tune:\n fine_tune(sp)\n else:\n print('No experiment specified. Exit now.')\n sys.exit(1)\n\n\nif __name__ == '__main__':\n run_experiment(args)\n","repo_name":"salesforce/TabularSemanticParsing","sub_path":"src/experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":16250,"program_lang":"python","lang":"en","doc_type":"code","stars":206,"dataset":"github-code","pt":"27"} +{"seq_id":"29144364374","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import HttpResponse\nfrom .models import Organization, Leader, License\nfrom .forms import OrganizationForm, LeaderForm, ContactForm, SocialForm, LicenseForm, CurrentUsersLicenseForm\n\n# ORGANIZATIONS VIEW FUNCTIONS\n# Create your views here.\ndef index(request):\n return render(request, 'base/home.html')\n # return HttpResponse(\"Hello There. You are at the Board Meets Landing Page\")\n\ndef organization_list(request):\n organizations = Organization.objects.all()\n context = {'organizations': organizations}\n return render(request, 'base/organizations_list.html', context)\n # return render(request, 'base/organizations_list.html')\n\n#Counts the number of organizations in Organizations Model\ndef organization_number(request):\n organizations = Organization.objects.all()\n organizations_count = organizations.count()\n return render(request, 'base/home.html', {'organizations_count': organizations_count})\n\n# Logic for displaying organizations details\ndef organization_detail(request, pk):\n organization = get_object_or_404(Organization, pk=pk)\n return render(request, 'base/organization_detail.html', {'organization': organization})\n\n# Adding an Organization\ndef add_organization(request):\n if request.method == \"POST\":\n form = OrganizationForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('organizations_list')\n else:\n form = OrganizationForm()\n return render(request, 'base/add_organization.html', {'form': form})\n \n#Editing Organization Details\ndef edit_organization(request, pk):\n organization = get_object_or_404(Organization, pk=pk)\n\n if request.method == \"POST\":\n form = OrganizationForm(request.POST, instance=organization)\n if form.is_valid():\n form.save()\n return redirect('organization_detail', pk=organization.pk)\n else:\n form = OrganizationForm(instance=organization)\n return render(request, 'base/edit_organization.html', {'form': form})\n\n# DEleting An Organization from the Model\ndef delete_organization(request, pk):\n organization = get_object_or_404(Organization, pk=pk)\n\n if request.method == \"POST\":\n organization.delete()\n return redirect('organizations_list')\n return render(request, 'base/delete_organization.html', {'organization': organization})\n\n\n# ORGANIZATIONS_SOCIAL VIEW FUNCTIONS\ndef organizations_socials(request):\n organizations = Organization.objects.all()\n context = {'organizations': organizations}\n return render(request, 'base/organizations_socials.html', context)\n\n#Edit Socials\ndef edit_socials(request, organization_id):\n organization = get_object_or_404(Organization, id=organization_id)\n\n if request.method == \"POST\":\n form = SocialForm(request.POST, instance=organization)\n if form.is_valid():\n organization = form.save()\n return redirect('organizations_socials')\n else:\n form = SocialForm(instance=organization)\n return render(request, 'base/edit_socials.html', {'form': form, 'organization': organization})\n\n\n# LEADER : ORGANIZATIONS_LEADERS\ndef organizations_names(request):\n organizations = Organization.objects.all()\n context = {'organizations': organizations}\n return render(request, 'base/organization_names.html', context)\n\n\ndef organization_leaders(request, organization_id):\n organization = get_object_or_404(Organization, id=organization_id)\n organization_leaders = Leader.objects.filter(organization=organization)\n\n context = {\n 'organization': organization,\n 'leaders': organization_leaders\n }\n\n return render(request, 'base/organization_leaders.html', context)\n\n#editing a leader\ndef edit_leader(request, organization_id, leader_id):\n leader = get_object_or_404(Leader, id=leader_id)\n\n if request.method == \"POST\":\n form = LeaderForm(request.POST, instance=leader)\n if form.is_valid():\n form.save()\n # Redirect to the leaders page\n return redirect('organization_leaders', organization_id=organization_id)\n else:\n form = LeaderForm(instance=leader)\n\n return render(request, 'base/edit_leader.html', {'form': form, 'leader': leader})\n\ndef delete_leader(request, organization_id, leader_id):\n leader = get_object_or_404(Leader, id=leader_id)\n\n if request.method == \"POST\":\n leader.delete()\n #Redirect\n return redirect('organization_leaders', organization_id=organization_id)\n return render(request, 'base/delete_leader.html', {'leader': leader, 'organization_id': organization_id})\n\n#Add a new leader\ndef add_leader(request, organization_id):\n if request.method == \"POST\":\n form = LeaderForm(request.POST)\n if form.is_valid():\n leader = form.save(commit = False)\n leader.organization_id = organization_id\n leader.save()\n return redirect('organization_leaders', organization_id=organization_id)\n else:\n form = LeaderForm()\n\n return render(request, 'base/add_leader.html', {'form': form, 'organization_id': organization_id})\n\n\n# ORGANIZATION CONTACTS\n# A list of all organizations \n\ndef organizations_contacts(request):\n organizations = Organization.objects.all()\n context = {'organizations': organizations}\n return render(request, 'base/organization_contacts.html', context)\n\n# Adds a new contact on the contacts list\ndef add_contact(request, organization_id):\n organization = get_object_or_404(Organization, id=organization_id)\n\n if request.method == \"POST\":\n form = ContactForm(request.POST)\n if form.is_valid():\n new_contact = form.cleaned_data.get('phone_number')\n existing_contacts = organization.phone_number\n if existing_contacts:\n organization.phone_number = f\"{existing_contacts}, {new_contact}\"\n else:\n organization.phone_number = new_contact\n organization.save()\n return redirect('organizations_contacts')\n else:\n form = ContactForm()\n\n return render(request, 'base/add_contact.html', {'form': form, 'organization': organization})\n\n\ndef edit_contact(request, organization_id):\n organization = get_object_or_404(Organization, id=organization_id)\n\n if request.method == \"POST\":\n form = ContactForm(request.POST)\n if form.is_valid():\n contact = form.cleaned_data.get('phone_number')\n organization.phone_number = contact\n organization.save()\n return redirect('organizations_contacts')\n else:\n form = ContactForm(instance=organization)\n\n return render(request, 'base/edit_contact.html', {'form': form, 'organization': organization})\n\nfrom django.contrib import messages\n\ndef delete_contact(request, organization_id):\n organization = get_object_or_404(Organization, id=organization_id)\n\n if request.method == \"POST\":\n contact_to_delete = request.POST.get('contact')\n existing_contacts = organization.phone_number\n\n if existing_contacts and contact_to_delete in existing_contacts:\n # Remove the contact from the existing contacts\n updated_contacts = existing_contacts.replace(contact_to_delete, '').strip(', ')\n organization.phone_number = updated_contacts\n organization.save()\n messages.success(request, 'Contact deleted successfully.')\n\n return redirect('organizations_contacts')\n\n# LICENSE\ndef license_list(request):\n licenses = License.objects.all()\n return render(request, 'base/license_list.html', {'licenses': licenses})\n\ndef current_users(request):\n licenses = License.objects.all()\n return render(request, 'base/current_users.html', {'licenses':licenses})\n\n#Adding a license\ndef add_license(request):\n \n if request.method == 'POST':\n form = LicenseForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('license_body')\n else:\n form = LicenseForm()\n\n context = {'form': form}\n return render(request, 'base/add_license.html', context)\n\ndef edit_license(request, license_id):\n license = get_object_or_404(License, id=license_id)\n if request.method =='POST':\n form = LicenseForm(request.POST, instance=license)\n if form.is_valid():\n form.save()\n # Redirect to the license page\n return redirect('license_body')\n else:\n form = LicenseForm(instance=license)\n\n return render(request, 'base/edit_license.html', {'form': form, 'license': license})\n\n\ndef delete_license(request, license_id):\n license = get_object_or_404(License, id=license_id)\n if request.method == \"POST\":\n license.delete()\n # Redirect\n return redirect('license_body')\n return render(request, 'base/delete_license.html', {'license': license})\n \n\n#CURRENT USER\n# Retrives a list of Current Users\ndef currentuser_list (request):\n licenses = License.objects.all()\n\n #Extract the required data from each license object\n organizations = [license.organization for license in licenses]\n license_keys = [license.license_key for license in licenses]\n number_of_users = [license.number_of_users for license in licenses]\n\n #Pass the data to the template for rendering\n context = {\n 'organizations': organizations,\n 'license_keys': license_keys,\n 'number_of_users': number_of_users,\n }\n \n return render(request, 'base/edit_currentusers.html', context)\n\ndef edit_currentusers_license(request, license_id):\n license = get_object_or_404(License, id=license_id)\n if request.method =='POST':\n form = CurrentUsersLicenseForm(request.POST, instance=license)\n if form.is_valid():\n form.save()\n # Redirect to the license page\n return redirect('current_users')\n else:\n form = CurrentUsersLicenseForm(instance=license)\n\n return render(request, 'base/edit_currentusers.html', {'form': form, 'license': license})\n\ndef delete_currentusers_license(request, license_id):\n license = get_object_or_404(License, id=license_id)\n if request.method == \"POST\":\n license.delete()\n # Redirect\n return redirect('current_users')\n return render(request, 'base/delete_currentusers.html', {'license': license})\n\n# Counting number of items in a page\ndef count_organizations(request):\n objects = Organization.objects.all()\n\n #Count the number of objects\n object_count = objects.count()\n\n return render(request, 'base/home.html', {'object_count': object_count})","repo_name":"mmbogajemimah/BoardMeets_Demo","sub_path":"boardmeets/base/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"22214451019","text":"import json\n\n# get_all() lets you specify the number of results you want to get\ndef get_all(size: int = 10000) -> dict:\n\tquery = { \\\n\t\t\"query\": {\n\t\t\t\"match_all\": {}\n\t\t},\n\t\t\"size\": size\n\t}\n\treturn query\n\ndef get_most_recent(size: int = 1) -> dict:\n\tquery = { \\\n\t\t\"sort\": [{\"timestamp\": \"desc\"}],\n\t\t\"size\": size\n\t}\n\n\treturn query\n\n# Get index in a determined period of time\n# Date format: \"YYYY-mm-ddTHH:MM:SS.SSSSSS\"\ndef get_within_period(start: str, end: str, size: int = 10000) -> dict:\n\tquery = { \\\n\t\t\"size\": size,\n\t\t\"query\": {\n\t\t\t\"range\": {\n\t\t\t\t\"timestamp\": {\n\t\t\t\t\t\"gte\": start,\n\t\t\t\t\t\"lte\": end\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn query\n\n# Get index until a determined period of time\n# Date format: \"YYYY-mm-ddTHH:MM:SS.SSSSSS\"\ndef get_until(end: str, size: int = 10000) -> dict:\n\tquery = { \\\n\t\t\"size\": size,\n\t\t\"query\": {\n\t\t\t\"range\": {\n\t\t\t\t\"timestamp\": {\n\t\t\t\t\t\"lte\": end\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn query\n\n# Get results that matches the nearest time (before and after)\n# for a given timestamp, or given a period (start and end)\ndef get_nearest_time(start: str, end: str) -> dict:\n\tquery = { \\\n\t\t\"size\": 0,\n\t\t\"aggs\": {\n\t\t\t\"above\": {\n\t\t\t\t\"filter\": {\n\t\t\t\t\t\"range\": {\n\t\t\t\t\t\t\"timestamp\": {\n\t\t\t\t\t\t\t\"gt\": start\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t\"aggs\": {\n\t\t\t\t\t\"TopDocument\": {\n\t\t\t\t\t\t\"terms\": {\n\t\t\t\t\t\t\t\"field\": \"timestamp\",\n\t\t\t\t\t\t\t\"size\": 1,\n\t\t\t\t\t\t\t\"order\": {\n\t\t\t\t\t\t\t\t\"_key\": \"asc\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"aggs\": {\n\t\t\t\t\t\t\t\"documents\": {\n\t\t\t\t\t\t\t\t\"top_hits\": {\n\t\t\t\t\t\t\t\t\t\"size\": 1\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\t\"below\":{\n\t\t\t\t\"filter\": {\n\t\t\t\t\t\"range\": {\n\t\t\t\t\t\t\"timestamp\": {\n\t\t\t\t\t\t\t\"lt\": end\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t\"aggs\": {\n\t\t\t\t\t\"TopDocument\": {\n\t\t\t\t\t\t\"terms\": {\n\t\t\t\t\t\t\t\"field\": \"timestamp\",\n\t\t\t\t\t\t\t\"size\": 1,\n\t\t\t\t\t\t\t\"order\": {\n\t\t\t\t\t\t\t\t\"_key\": \"desc\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"aggs\": {\n\t\t\t\t\t\t\t\"documents\": {\n\t\t\t\t\t\t\t\t\"top_hits\": {\n\t\t\t\t\t\t\t\t\t\"size\": 1\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn query","repo_name":"esmegl/max-pain-package","sub_path":"mp_calc/queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"32272336724","text":"Input = open(\"data/Day 10. input.txt\", \"r\").read().split(\"\\n\")[:-1]\nInput = [list(line) for line in Input]\n\nmatchingDict = {\"(\": \")\", \"[\": \"]\", \"{\": \"}\", \"<\": \">\"}\nscoreDictPart1 = {\")\": 3, \"]\": 57, \"}\": 1197, \">\": 25137}\nscoreDictPart2 = {\")\": 1,\"]\": 2, \"}\": 3, \">\": 4}\nopeningSymbols = [\"(\", \"[\", \"{\", \"<\"]\n\ndef scoreLine(line):\n global errorSum\n openingOrder = []\n\n for char in line:\n if char in openingSymbols:\n openingOrder.append(char)\n continue\n \n lastOpening = openingOrder.pop()\n if matchingDict[lastOpening] != char:\n errorSum = errorSum + scoreDictPart1[char]\n break\n else: \n incompleteScores.append(scoreIncomplete(openingOrder))\n\ndef scoreIncomplete(line):\n line = line[::-1]\n score = 0 \n for char in line:\n score = score*5 + scoreDictPart2[matchingDict[char]]\n return score\n\n# Deel 1/ Deel 2 \nincompleteScores = []\nerrorSum = 0\n\nfor line in Input:\n scoreLine(line)\n\nprint(errorSum)\nprint(sorted(incompleteScores)[len(incompleteScores)//2])\n","repo_name":"Kaysmink/adventOfCode-2021","sub_path":"src/Day 10. Syntax Scoring.py","file_name":"Day 10. Syntax Scoring.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"24487522453","text":"# Lame function that returns a list of beats. \n# Only runs 100 times\ndef current_beat():\n\tmax = 1008\n\tnums = (\"Y\",\"E\",\"K\",\"S\",\"H\",\"A\",\"H\",\"I\")\n\t#nums = (\"S\",\"E\",\"F\",\"I\",\"D\",\"#\",\"E\",\"D\",\"W\",\"A\",\"R\",\"D\",\"#\")\n\t#nums = (\"1\",\"H\",\"E\",\"S\",\"S\")\n\t#nums = (\"C\",\"H\",\"A\",\"M\",\"I\")\n\t#nums = (\"S\",\"H\",\"O\",\"G\",\"H\")\n\t#nums = (\"S\",\"A\",\"Y\",\"R\",\"A\")\n\ti = 0\n\tresult = []\n\twhile len(result) < max:\n\t\tif i >= len(nums): i = 0\n\t\tresult.append(nums[i])\n\t\ti += 1\n\treturn result\n\nprint (current_beat())","repo_name":"semappas/MyPythonCourse","sub_path":"Iterator/yekshahi.py","file_name":"yekshahi.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19538780646","text":"from keras.models import load_model\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\ndef plots(model_name, show=False):\n\n #------ Name and load model ------------------------------\n fig_png_path = '../fig_png/' + model_name + '/'\n model = load_model('../models/'+model_name+'.h5')\n if not os.path.exists(fig_png_path):\n os.makedirs(fig_png_path)\n\n #----- load & prepare data ---------------------------\n traindata = np.load('../Data/traindata.npy')\n testdata = np.load('../Data/testdata.npy')\n valdata = np.load('../Data/valdata.npy')\n\n x_train = traindata[:,1:8]\n y_train = traindata[:,0:1]\n x_test = testdata[:,1:8]\n y_test = testdata[:,0:1]\n x_val = valdata[:,1:8]\n y_val = valdata[:,0:1]\n\n #------ Model evaluation -----------------------------\n predicted_mass_test = model.predict(x_test)\n predicted_mass_train = model.predict(x_train)\n\n np.save('../Data/SVfit_mass', y_test)\n np.save('../Data/siec_mass', predicted_mass_test)\n\n mass_diff_test = y_test - predicted_mass_test\n mass_diff_train = y_train - predicted_mass_train\n mean_sq_test = mass_diff_test**2\n mean_sq_train = mass_diff_train**2\n rel_mass_diff_train = mass_diff_train/y_train\n rel_mass_diff_test = mass_diff_test/y_test\n\n #------ Mass histo -------------------\n plt.hist(predicted_mass_test, bins = 450, range = (0,450), label = 'predicted', alpha = 0.5, color = 'r')\n plt.hist(y_test, bins = 450, range = (0,450), label = 'actual', alpha = 0.3, color = 'b')\n #plt.title('Mass histogram')\n plt.xlabel('Mass')\n plt.ylabel('Count')\n plt.legend()\n plt.savefig(fig_png_path + 'keras_mass.png')\n if(show=='True'):\n plt.show()\n plt.clf()\n\n #------ Mass difference scattered plot (range 0<-->200) -------\n plt.scatter(y_train, mass_diff_train, alpha = 0.25, color = 'r', label = 'train', s = 5)\n plt.scatter(y_test, mass_diff_test, alpha = 1, color = 'b', label = 'test', s = 5)\n plt.xlim(0,200)\n #plt.title('Mass difference')\n plt.xlabel('Actual mass')\n plt.ylabel('Mass difference')\n plt.legend()\n plt.savefig(fig_png_path + 'keras_mass_diff_range.png')\n if(show=='True'):\n plt.show()\n plt.clf()\n\n #--------- Mass difference scattered plot -------------\n plt.scatter(y_train, mass_diff_train, alpha = 0.25, color = 'r', label = 'train', s = 5)\n plt.scatter(y_test, mass_diff_test, alpha = 1, color = 'b', label = 'test', s = 5)\n #plt.title('Mass difference')\n plt.xlabel('Actual mass')\n plt.ylabel('Mass difference')\n plt.legend()\n plt.savefig(fig_png_path + 'keras_mass_diff.png')\n if(show=='True'):\n plt.show()\n plt.clf()\n\n #-------- Squared mass difference histo ----------------\n plt.hist(mean_sq_test, bins = 3000, range = (0,3), label = 'test', alpha = 0.7, color = 'r', log='True')\n #plt.hist(mean_sq_train.T, bins = 100, range = (0,10), label = 'train', alpha = 0.3, color = 'b', log='True')\n #plt.title('Mass difference squared')\n plt.xlabel('Mass difference squared')\n plt.ylabel('Count')\n plt.legend()\n plt.savefig(fig_png_path + 'keras_sq_mass_error.png')\n if(show=='True'):\n plt.show()\n plt.clf()\n\n #--------- Relative mass difference scattered plot -------------\n plt.scatter(y_train, rel_mass_diff_train, alpha = 0.25, color = 'r', label = 'train', s = 5)\n plt.scatter(y_test, rel_mass_diff_test, alpha = 1, color = 'b', label = 'test', s = 5)\n #plt.title('Relative mass difference')\n plt.xlabel('Actual mass')\n plt.ylabel('Relative mass difference')\n plt.legend()\n plt.savefig(fig_png_path + 'keras_relative_mass_diff.png')\n if(show=='True'):\n plt.show()\n plt.clf()\n\n #--------- Relative mass difference scattered plot (range 0<-->200) -------------\n plt.scatter(y_train, rel_mass_diff_train, alpha = 0.25, color = 'r', label = 'train', s = 5)\n plt.scatter(y_test, rel_mass_diff_test, alpha = 1, color = 'b', label = 'test', s = 5)\n plt.xlim(0,200)\n #plt.title('Relative mass difference')\n plt.xlabel('Actual mass')\n plt.ylabel('Relative mass difference')\n plt.legend()\n plt.savefig(fig_png_path + 'keras_relative_mass_diff.png')\n if(show=='True'):\n plt.show()\n plt.clf()\n\n\nif __name__ == '__main__':\n plots('lays_4_epochs_101_init_0', True)\n\n","repo_name":"Rukito/ML_mHfit","sub_path":"MLAnalysis/src/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":4153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"39210982086","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n__author__ = 'ar'\n\nimport os\nimport glob\nimport json\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport nibabel as nib\n\nimport run00_common as comm\n\n#############################################\nif __name__ == '__main__':\n wdir = '../../experimental_data/resize-256x256x64'\n lstPathMsk = sorted(glob.glob('%s/*-msk.nii.gz' % wdir))\n numMsk = len(lstPathMsk)\n matplotlib.interactive(False)\n for ii,fmsk in enumerate(lstPathMsk):\n fmskLungsOut = '%s-lungs.nii.gz' % fmsk\n finfoOut = '%s-info.json' % fmsk\n if os.path.isfile(finfoOut):\n print ('\\t***WARNING*** File [%s] exist, skip...' % finfoOut)\n #\n else:\n print ('[%d/%d] processing: %s' % (ii, numMsk, os.path.basename(fmsk)))\n tdat = nib.load(fmsk)\n timg = comm.niiImagePreTransform(tdat.get_data())\n retMskLungs, retIsOk = comm.makeLungedMask(timg)\n lungInfo = comm.prepareLungSizeInfo(retMskLungs, tdat.header)\n tdatLungs = nib.Nifti1Image(comm.niiImagePostTransform(retMskLungs).astype(tdat.get_data_dtype()), tdat.affine, header=tdat.header)\n nib.save(tdatLungs, fmskLungsOut)\n with open(finfoOut, 'w') as f:\n f.write(json.dumps(lungInfo, indent=4))\n # plt.figure()\n plt.subplot(1,2,1)\n plt.imshow(timg[:,:,timg.shape[-1]/2])\n plt.title('Original mask')\n plt.subplot(1,2,2)\n plt.imshow(retMskLungs[:, :, retMskLungs.shape[-1] / 2])\n plt.title('Divided lungs')\n plt.show(block=False)\n plt.pause(0.1)\n ffigOut = '%s-preview.png' % fmsk\n plt.savefig(ffigOut)\n","repo_name":"gakarak/BTBDB_ImageAnalysisSubPortal","sub_path":"experimental_code/step01_Divide_Segmented_Lungs/run02_morfological_dividing_v2.py","file_name":"run02_morfological_dividing_v2.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"15812307506","text":"#!/usr/bin/env python\n\n\nfrom distutils.core import setup\nimport os\n\n\nlong_description='Please read the documentation on Github.'\nif os.path.exists('README.md'):\n long_description = open('README.md').read()\n\n\nsetup(name='pyMMF',\n version='0.5',\n description='Multimode optical fiber simulation package.',\n author='Sebastien M. Popoff & Pavel Gostev',\n author_email='sebastien.popoff@espci.psl.eu',\n url='https://www.wavefrontshaping.net',\n license = 'MIT',\n packages = ['pyMMF','pyMMF.solvers'],\n long_description=long_description,\n classifiers=[\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 3\",\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Education\",\n \"Topic :: Scientific/Engineering\",\n \"License :: OSI Approved :: MIT License\",\n ],\n install_requires=[\n 'numpy',\n 'matplotlib',\n 'scipy',\n 'numba',\n 'joblib'\n ],\n )\n","repo_name":"wavefrontshaping/pyMMF","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"27"} +{"seq_id":"27389478395","text":"\"\"\"\nInteraction tests for the mopub front-end. Interaction tests\nuse a live browser to test user actions like clicks, entering\nand changing data, and navigation.\n\nThe tests in this module use selenium (http://seleniumhq.org/)\nand assume a running selenium server on localhost. You'll also\nhave to have firefox installed.\n\"\"\"\n\nimport unittest\nimport random\nfrom selenium import webdriver\n\nBROWSER = None\n\nclass InteractionTestCase(unittest.TestCase):\n \"\"\"\n Inheritable base class for testing interaction using selenium.\n Connects to a local selenium server instance before running\n any tests. Provides some common utility methods (login, logout,\n others) that are used in most browser tests.\n \"\"\"\n\n def setUp(self):\n # make the browser a singleton so we can reuse the same firefox process\n global BROWSER\n if BROWSER == None:\n BROWSER = webdriver.Firefox()\n # wait 10 seconds for each page to load\n BROWSER.implicitly_wait(10)\n\n self.browser = BROWSER\n\n def get(self, link):\n \"\"\"\n Shortcut for navigating to a link on our endpoint.\n \"\"\"\n # REFACTOR we should put the endpoint in settings\n page = BROWSER.get(\"http://localhost:8000\" + link)\n return page\n\n def login(self):\n \"\"\"\n Shortcut for logging in to the page. Will log out the current session first.\n \"\"\"\n self.logout()\n self.get(\"/account/login/\")\n email_field = BROWSER.find_element_by_name('username')\n email_field.send_keys(\"test@example.com\")\n password_field = BROWSER.find_element_by_name('password')\n password_field.send_keys(\"test\")\n login_button = BROWSER.find_element_by_id(\"accountForm-submit\")\n login_button.click()\n\n def logout(self):\n \"\"\"\n Shortcut for logging out of a page. Kind of jankity but usually works.\n \"\"\"\n # Try to navigate to '/', which could either be the dashboard page\n # or the account login page depending on whether the user is logged\n # in already. If it finds a logout button it'll click it, otherwise\n # the user is probably not logged in anyway.\n self.get('/')\n try:\n logout_button = BROWSER.find_element_by_id(\"logout-link\")\n logout_button.click()\n except:\n pass\n\n def click(self, id=None, klass=None, xpath=None, name=None):\n \"\"\"\n Shortcut for clicking on something in the page, identifiable by\n one and only one of: id, class, xpath, name.\n \"\"\"\n # REFACTOR allow multiple selectors to be passed in\n if id:\n item = BROWSER.find_element_by_id(id)\n elif klass:\n item = BROWSER.find_element_by_class(klass)\n elif xpath:\n item = BROWSER.find_element_by_xpath(xpath)\n elif name:\n item = BROWSER.find_element_by_name(name)\n else:\n raise Exception('please provide one of: id, class, xpath, name')\n\n item.click()\n\n def send_keys(self, keys, id=None, klass=None, xpath=None, name=None):\n \"\"\"\n Shortcut for typing in to something in the page, identifiable by\n one and only one of: id, class, xpath, name.\n \"\"\"\n if id:\n item = BROWSER.find_element_by_id(id)\n elif klass:\n item = BROWSER.find_element_by_class(klass)\n elif xpath:\n item = BROWSER.find_element_by_xpath(xpath)\n elif name:\n item = BROWSER.find_element_by_name(name)\n else:\n raise Exception('please provide one of: id, class, xpath, name')\n\n item.send_keys(keys)\n\n def select_option(self, select_box_id, option_value):\n \"\"\"\n Shortcut for selecting an option in a select box.\n \"\"\"\n select_box = BROWSER.find_element_by_id(select_box_id)\n select_box.click()\n\n option_xpath = \"//select[@id='\" + select_box_id + \"']\" + \\\n \"//option[@value='\" + option_value + \"']\"\n option = BROWSER.find_element_by_xpath(option_xpath)\n option.click()\n","repo_name":"tasyjean/network-reporting","sub_path":"server/tests/interaction/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"20626909774","text":"from pathlib import Path\n\nfrom genutility.pdf import iter_pdf_text, join_pdfs_in_folder\nfrom genutility.test import MyTestCase, parametrize, print_file_diff\n\n\nclass PdfTest(MyTestCase):\n @parametrize(\n (\"testfiles/pdf/\", \"testtemp/joined.pdf\", \"testfiles/joined.pdf\"),\n )\n def test_join_pdfs_in_folder(self, path, out, truth):\n with self.assertNoRaise():\n join_pdfs_in_folder(Path(path), out, overwrite=True)\n\n try:\n self.assertFilesEqual(out, truth)\n except AssertionError:\n print_file_diff(truth, out, encoding=\"latin1\")\n raise\n\n def test_iter_pdf_text(self):\n truth = [\"Hello World\", \"HELLO WORLD\"]\n result = iter_pdf_text(\"testfiles/joined.pdf\")\n\n self.assertIterEqual(truth, result)\n\n\nif __name__ == \"__main__\":\n import unittest\n\n unittest.main()\n","repo_name":"Dobatymo/genutility","sub_path":"genutility/tests/pdf.py","file_name":"pdf.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"10739532508","text":"import logging\n\nimport numpy as np\nimport pandas as pd\nimport glicko2\n\nfrom sklearn.base import BaseEstimator, ClassifierMixin\n\nfrom skelo.model.base import RatingModel, RatingEstimator\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Glicko2Model(RatingModel):\n \"\"\"\n Dictionary-based implementation of the `Glicko2 rating system `_.\n\n This class creates a dictionary of Glicko2 ratings for each player inserted into the rating system, such\n that each match update will append new ratings for the respective match players, calculated according\n to the Glicko2 update formula.\n\n This model may be used directly, but is primarily intended as a utility class for an Glicko2Estimator.\n \"\"\"\n\n def __init__(self, initial_value=(1500., 350., 0.06), initial_time=0, **kwargs):\n \"\"\"\n Construct a Glicko2 RatingsModel.\n\n Args:\n initial_value (float, float, float): initial default rating and deviation assigned to a new player\n initial_time (int or orderable): the earliest \"time\" value for matches between players.\n \"\"\"\n super().__init__(initial_value=initial_value, initial_time=initial_time)\n\n def evolve_rating(self, r1, r2, label):\n \"\"\"\n Update a Glicko rating based on the outcome of a match.\n \n This is based on the example in the glicko2 package's unit tests,\n available `here `_\n \"\"\"\n rating = glicko2.Player(*r1)\n rating.update_player([r2[0]], [r2[1]], [label])\n updated = (rating.getRating(), rating.getRd(), rating.vol)\n return updated\n\n @staticmethod\n def compute_prob(r1, r2):\n \"\"\"\n Return the probability of a player with rating r1 beating a player with rating r2.\n\n For more background, please see the `Glicko Paper `_\n \"\"\"\n r_diff = (r2[0] - r1[0]) / 400.0\n root_square_std = np.sqrt(r1[1]**2 + r2[1]**2)\n g = glicko2.Player(*r1)._g(r1[1])\n arg = g * root_square_std * r_diff\n prob = 1.0 / (1 + 10**arg)\n return prob\n\n\nclass Glicko2Estimator(RatingEstimator):\n \"\"\"\n A scikit-learn Classifier for creating ratings according to the \n `Glicko2 rating system `_.\n \"\"\"\n RATING_MODEL_CLS = Glicko2Model\n RATING_MODEL_ATTRIBUTES = [\n 'initial_value',\n 'initial_time',\n ]\n\n def __init__(self,\n key1_field=None,\n key2_field=None,\n timestamp_field=None,\n initial_value=(1500., 350., 0.06),\n initial_time=0,\n **kwargs\n ):\n \"\"\"\n Construct a classifier object, without fitting it.\n \n Args:\n key1_field (string): column name of the player1 key, if fit on a pandas DataFrame\n key2_field (string): column name of the player2 key, if fit on a pandas DataFrame\n timestamp_field (string): column name of the timestamp field, if fit on a pandas DataFrame\n \"\"\"\n super().__init__(\n key1_field=key1_field,\n key2_field=key2_field,\n timestamp_field=timestamp_field,\n initial_value=initial_value,\n initial_time=initial_time,\n **kwargs\n )\n","repo_name":"mbhynes/skelo","sub_path":"skelo/model/glicko2.py","file_name":"glicko2.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"27"} +{"seq_id":"6376078030","text":"import json\nimport os\nimport os.path as osp\nfrom typing import Optional, Tuple, Union\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom pylib.utils.DiagonalPreprocessing import DiagonalPreprocessing\nfrom pylib.utils.energy_utils import calculate_D\nfrom sklearn.decomposition import PCA\nfrom torch import Tensor\nfrom torch.nn import Parameter\nfrom torch_geometric.nn.conv import MessagePassing\nfrom torch_geometric.nn.dense.linear import Linear\nfrom torch_geometric.nn.inits import glorot, zeros\nfrom torch_geometric.transforms import BaseTransform, Constant\nfrom torch_geometric.typing import Adj, OptTensor, PairTensor\nfrom torch_geometric.utils import (add_self_loops, degree, remove_self_loops,\n softmax)\nfrom torch_scatter import scatter_max, scatter_mean, scatter_min, scatter_std\nfrom torch_sparse import SparseTensor, matmul, set_diag\n\n\n# node transforms\nclass WeightedLocalDegreeProfile(BaseTransform):\n '''\n Weighted version of Local Degree Profile (LDP) from https://arxiv.org/abs/1811.03508\n Appends WLDP features to feature vector.\n\n Reference code: https://pytorch-geometric.readthedocs.io/en/latest/_modules/\n torch_geometric/transforms/local_degree_profile.html#LocalDegreeProfile\n '''\n def __call__(self, data):\n row, col = data.edge_index\n N = data.num_nodes\n\n # weighted_degree must exist\n deg = data.weighted_degree\n deg_col = deg[col]\n\n min_deg, _ = scatter_min(deg_col, row, dim_size=N)\n min_deg[min_deg > 10000] = 0\n max_deg, _ = scatter_max(deg_col, row, dim_size=N)\n max_deg[max_deg < -10000] = 0\n mean_deg = scatter_mean(deg_col, row, dim_size=N)\n std_deg = scatter_std(deg_col, row, dim_size=N)\n\n x = torch.stack([deg, min_deg, max_deg, mean_deg, std_deg], dim=1)\n\n if data.x is not None:\n data.x = data.x.view(-1, 1) if data.x.dim() == 1 else data.x\n data.x = torch.cat([data.x, x], dim=-1)\n else:\n data.x = x\n\n return data\n\n def __repr__(self) -> str:\n return (f'{self.__class__.__name__}')\n\nclass Degree(BaseTransform):\n '''\n Appends degree features to node feature vector.\n\n Reference code: https://pytorch-geometric.readthedocs.io/en/latest/_modules/\n torch_geometric/transforms/target_indegree.html#TargetIndegree\n '''\n def __init__(self, norm = True, max_val = None, weighted = False,\n split_edges = False, split_val = 0, diag = False):\n '''\n Inputs:\n norm: True to normalize degree by dividing by max_val\n max_val: value for norm, if None uses maximum degree\n weighted: True for weighted degree, False for count\n split_edges: True to divide edges based on split_val\n split_val: split value for split_edges\n diag: TODO\n '''\n self.norm = norm # bool\n self.max = max_val # float\n self.weighted = weighted # bool\n self.split_edges = split_edges # bool\n self.split_val = split_val # float\n self.diag = diag\n # values less than split_val are one type of edge\n # values greater than split_val are second type of edge\n\n def __call__(self, data):\n if self.weighted:\n if self.split_edges:\n if self.diag:\n ypos = torch.clone(data.contact_map_diag)\n yneg = torch.clone(data.contact_map_diag)\n else:\n ypos = torch.clone(data.contact_map)\n yneg = torch.clone(data.contact_map)\n\n ypos[ypos < self.split_val] = 0\n pos_deg = torch.sum(ypos, axis = 1)\n del ypos\n yneg = torch.clone(data.contact_map)\n yneg[yneg > self.split_val] = 0\n neg_deg = torch.sum(yneg, axis = 1)\n del yneg\n else:\n deg = data.weighted_degree\n else:\n if self.split_edges:\n if self.diag:\n pos_deg = degree((data.contact_map_diag > self.split_val).nonzero().t()[0], data.num_nodes)\n neg_deg = degree((data.contact_map_diag < self.split_val).nonzero().t()[0], data.num_nodes)\n else:\n pos_deg = degree((data.contact_map > self.split_val).nonzero().t()[0], data.num_nodes)\n neg_deg = degree((data.contact_map < self.split_val).nonzero().t()[0], data.num_nodes)\n else:\n deg = degree(data.edge_index[0], data.num_nodes)\n # deg = degree((data.contact_map).nonzero().t()[0], data.num_nodes)\n\n\n if self.norm:\n if self.split_edges:\n # print(pos_deg.max())\n # print(neg_deg.max())\n pos_deg /= (pos_deg.max() if self.max is None else self.max)\n neg_deg /= (neg_deg.max() if self.max is None else self.max)\n else:\n deg /= (deg.max() if self.max is None else self.max)\n\n if self.split_edges:\n deg = torch.stack([pos_deg, neg_deg], dim=1)\n else:\n deg = torch.stack([deg], dim=1)\n\n if data.x is not None:\n data.x = data.x.view(-1, 1) if data.x.dim() == 1 else data.x\n data.x = torch.cat([data.x, deg], dim=-1)\n else:\n data.x = deg\n\n return data\n\n def __repr__(self) -> str:\n repr = (f'{self.__class__.__name__}'\n f'(norm={self.norm}')\n\n if self.max is not None:\n repr += f', max={self.max}'\n\n if self.weighted:\n repr += f'weighted={self.weighted}'\n\n repr += f', split_edges={self.split_edges}'\n if self.split_edges:\n repr += f', split_val={self.split_val})'\n else:\n repr += ')'\n\n return repr\n\nclass AdjPCATransform(BaseTransform):\n '''Appends rank k PCA transformation of adjacency matrix to feature vector.'''\n def __init__(self, k = 5, diag = False):\n self.k = k\n self.diag = True\n\n def __call__(self, data,):\n if self.diag:\n input = torch.clone(data.contact_map_diag)\n else:\n input = torch.clone(data.contact_map)\n pca = PCA(n_components = self.k)\n y_trans = pca.fit_transform(input)\n\n y_trans = torch.tensor(y_trans, dtype = torch.float32)\n\n if data.x is not None:\n data.x = data.x.view(-1, 1) if data.x.dim() == 1 else data.x\n data.x = torch.cat([data.x, y_trans], dim=-1)\n else:\n data.x = y_trans\n\n return data\n\n def __repr__(self) -> str:\n return (f'{self.__class__.__name__}(k={self.k}, diag={self.diag})')\n\nclass AdjPCs(BaseTransform):\n '''Appends values from top k PCs of adjacency matrix to feature vector.'''\n def __init__(self, k = 5, normalize = False, sign_net = False):\n self.k = k\n self.normalize = normalize\n self.sign_net = sign_net\n\n def __call__(self, data):\n input = data.contact_map_diag\n # input = torch.nan_to_num(data.contact_map_diag, nan = 1.0)\n pca = PCA(n_components = self.k)\n pca.fit(input)\n\n m = len(input)\n topk_pcs = np.zeros((m, self.k))\n for j in range(self.k):\n pc = pca.components_[j]\n\n if self.normalize:\n min = np.min(pc)\n max = np.max(pc)\n if max > abs(min):\n val = max\n else:\n val = abs(min)\n\n # multiply by scale such that val x scale = 1\n scale = 1/val\n pc *= scale\n\n topk_pcs[:,j] = pc\n\n topk_pcs = torch.tensor(topk_pcs, dtype = torch.float32)\n\n if self.sign_net:\n data.eigen_vectors = topk_pcs.reshape(-1)\n data.eigen_values = torch.tensor(pca.singular_values_[:self.k], dtype = torch.float32)\n else:\n if data.x is not None:\n data.x = data.x.view(-1, 1) if data.x.dim() == 1 else data.x\n data.x = torch.cat([data.x, topk_pcs], dim=-1)\n else:\n data.x = topk_pcs\n\n return data\n\n def __repr__(self) -> str:\n repr = f'{self.__class__.__name__}(k={self.k}, normalize={self.normalize}'\n\n if self.sign_net:\n repr += f', sign_net={self.sign_net})'\n else:\n repr += ')'\n\n return repr\n\nclass AdjTransform(BaseTransform):\n '''Appends rows of adjacency matrix to feature vector.'''\n def __call__(self, data):\n if data.x is not None:\n data.x = data.x.view(-1, 1) if data.x.dim() == 1 else data.x\n data.x = torch.cat([data.x, torch.clone(data.contact_map)], dim=-1)\n else:\n data.x = torch.clone(data.contact_map)\n\n return data\n\n def __repr__(self) -> str:\n return (f'{self.__class__.__name__}')\n\nclass OneHotGeneticPosition(BaseTransform):\n '''Appends one hot encoded genetic position to feature vector.'''\n def __call__(self, data):\n pos = torch.arange(0, data.num_nodes, dtype=torch.long)\n pos = F.one_hot(pos, num_classes=data.num_nodes).to(torch.float)\n\n if data.x is not None:\n data.x = data.x.view(-1, 1) if data.x.dim() == 1 else data.x\n data.x = torch.cat([data.x, pos], dim=-1)\n else:\n data.x = pos\n\n return data\n\n def __repr__(self) -> str:\n return (f'{self.__class__.__name__}')\n\nclass GeneticPosition(BaseTransform):\n '''Appends genetic position to feature vector.'''\n def __init__(self, center = False, norm = False):\n self.center = center # bool\n self.norm = norm # bool\n\n def __call__(self, data):\n pos = torch.arange(0, data.num_nodes, dtype=torch.float32).reshape(data.num_nodes, 1)\n\n if self.center:\n pos -= pos.mean(dim=-2, keepdim=True)\n if self.norm:\n pos /= pos.max()\n\n if data.x is not None:\n data.x = data.x.view(-1, 1) if data.x.dim() == 1 else data.x\n data.x = torch.cat([data.x, pos], dim=-1)\n else:\n data.x = pos\n\n return data\n\n def __repr__(self):\n return (f'{self.__class__.__name__}'\n f'(center={self.center}, norm={self.norm})')\n\nclass NoiseLevel(BaseTransform):\n '''Appends noise level as node feature.'''\n def __init__(self, inverse = False):\n self.inverse = inverse # bool\n\n def __call__(self, data):\n val = data.sweep / 100000\n if self.inverse:\n val = 1/val\n c = torch.full((data.num_nodes, 1), val, dtype=torch.float32)\n\n if data.x is not None:\n data.x = data.x.view(-1, 1) if data.x.dim() == 1 else data.x\n data.x = torch.cat([data.x, c], dim=-1)\n else:\n data.x = c\n\n return data\n\n def __repr__(self):\n return (f'{self.__class__.__name__}(inverse={self.inverse})')\n\nclass GridSize(BaseTransform):\n '''Appends grid size as node feature.'''\n def __init__(self, grid_path=None):\n if grid_path is not None:\n self.grid_file = osp.join(grid_path, 'grid.txt')\n else:\n self.grid_file = None\n\n def __call__(self, data):\n if self.grid_file is not None:\n grid_file = osp.join(data.path, self.grid_file)\n else:\n grid_file = None\n\n config_file = osp.join(data.path, 'config.json')\n if osp.exists(config_file):\n with open(config_file) as f:\n config = json.load(f)\n grid_size = config['grid_size']\n elif grid_file is not None and osp.exists(grid_file):\n grid_size = np.atleast_1d(np.loadtxt(grid_file))[-1]\n else:\n raise Exception(f\"Grid size files not found for {data.path}: {config_file}, {grid_file}\")\n\n pos = torch.full((data.num_nodes, 1), grid_size, dtype=torch.float32)\n\n if data.x is not None:\n data.x = data.x.view(-1, 1) if data.x.dim() == 1 else data.x\n data.x = torch.cat([data.x, pos], dim=-1)\n else:\n data.x = pos\n\n return data\n\n def __repr__(self):\n return (f'{self.__class__.__name__}')\n\n\n# edge transforms\nclass GeneticDistance(BaseTransform):\n '''\n Appends genetic distance to features to edge attr vector.\n\n Based off of https://pytorch-geometric.readthedocs.io/en/latest/\n _modules/torch_geometric/transforms/distance.html\n Note that GeneticDistance doesn't assume data.pos exists while Distance does\n '''\n def __init__(self, norm = False, max_val = None, cat = True,\n split_edges = False, convert_to_attr = False,\n log = False, log10 = False):\n '''\n Inputs:\n norm: True to normalize distances by dividing by max_val\n max_val: value for norm, if None uses maximum distance\n cat: True to concatenate attr, False to overwrite\n split_edges: True if graph has 'positive' and 'negative' edges\n convert_to_attr: True for edge attr, False for edge weight\n log: ln transform\n log10: log10 transform\n '''\n self.norm = norm\n self.max = max_val\n self.cat = cat\n self.split_edges = split_edges # bool\n self.convert_to_attr = convert_to_attr # bool, converts to 2d array\n self.log = log # apply ln transform\n self.log10 = log10 # apply log10 transform\n assert not self.log or not self.log10, \"only one can be True\"\n\n\n def __call__(self, data):\n pos = torch.arange(0, data.num_nodes, dtype=torch.float32).reshape(data.num_nodes, 1)\n\n if self.split_edges:\n # positive\n if 'pos_edge_attr' in data._mapping:\n pseudo = data.pos_edge_attr\n else:\n pseudo = None\n\n row, col = data.pos_edge_index\n dist = torch.norm(pos[col] - pos[row], p=2, dim=-1)\n if self.norm and dist.numel() > 0:\n dist = dist / (data.num_nodes if self.max is None else self.max)\n if self.log:\n dist = np.log(dist)\n elif self.log10:\n dist = np.log10(dist)\n if self.convert_to_attr:\n dist = dist.reshape(-1, 1)\n\n if pseudo is not None and self.cat:\n pseudo = pseudo.view(-1, 1) if pseudo.dim() == 1 else pseudo\n data.pos_edge_attr = torch.cat([pseudo, dist.type_as(pseudo)], dim=-1)\n else:\n data.pos_edge_attr = dist\n\n # negative\n if 'neg_edge_attr' in data._mapping:\n pseudo = data.neg_edge_attr\n else:\n pseudo = None\n row, col = data.neg_edge_index\n dist = torch.norm(pos[col] - pos[row], p=2, dim=-1)\n if self.norm and dist.numel() > 0:\n dist = dist / (dist.max() if self.max is None else self.max)\n if self.log:\n dist = np.log(dist)\n if self.convert_to_attr:\n dist = dist.reshape(-1, 1)\n\n if pseudo is not None and self.cat:\n pseudo = pseudo.view(-1, 1) if pseudo.dim() == 1 else pseudo\n data.neg_edge_attr = torch.cat([pseudo, dist.type_as(pseudo)], dim=-1)\n else:\n data.neg_edge_attr = dist\n\n else:\n (row, col), pseudo = data.edge_index, data.edge_attr\n dist = torch.norm(pos[col] - pos[row], p=2, dim=-1)\n if self.convert_to_attr:\n dist = dist.reshape(-1, 1)\n\n if self.norm and dist.numel() > 0:\n dist = dist / (data.num_nodes if self.max is None else self.max)\n if self.log:\n dist = torch.log(dist)\n elif self.log10:\n dist = torch.log10(dist)\n\n if pseudo is not None and self.cat:\n pseudo = pseudo.view(-1, 1) if pseudo.dim() == 1 else pseudo\n data.edge_attr = torch.cat([pseudo, dist.type_as(pseudo)], dim=-1)\n else:\n data.edge_attr = dist\n\n return data\n\n def __repr__(self) -> str:\n repr = f'{self.__class__.__name__}(norm={self.norm}'\n\n if self.max is not None:\n repr += f', max={self.max}'\n\n if self.log:\n repr += f', log={self.log})'\n else:\n repr += ')'\n\n return repr\n\nclass ContactDistance(BaseTransform):\n '''\n Appends contact map entries to edge attr vector.\n '''\n def __init__(self, norm = False, max_val = None, cat = True, split_edges = False,\n convert_to_attr = False, bonded = False, diag_normalize=False,\n corr = False, rank = None):\n '''\n Inputs:\n norm (bool): True for instant normalization\n max_val (None or int): Normalize by max_val if given, otherwise by true max\n cat (bool): True to concatenate attr, False to overwrite\n split_edges (bool): True if graph has 'positive' and 'negative' edges\n convert_to_attr (bool): True for edge attr, False for edge weight\n bonded (bool): True to use bonded contact map instead of experiment\n '''\n self.norm = norm\n self.max = max_val\n self.cat = cat\n self.split_edges = split_edges\n self.convert_to_attr = convert_to_attr # converts to 2d array,\n # else would be an edge weight\n self.bonded = bonded\n self.diag_norm = diag_normalize\n self.corr = corr\n self.rank = rank\n assert not (self.bonded and self.diag_norm), 'mutually exclusive options'\n assert not (self.bonded and self.corr), 'mutually exclusive options'\n assert not (self.corr and self.diag_norm), 'mutually exclusive options'\n\n def __call__(self, data):\n if self.split_edges:\n assert not self.bonded and not self.diag_norm, 'Not Implemented yet'\n # positive\n if 'pos_edge_attr' in data._mapping:\n pseudo = data.pos_edge_attr\n else:\n pseudo = None\n\n row, col = data.pos_edge_index\n pos_edge_attr = data.contact_map[row, col]\n if self.convert_to_attr:\n pos_edge_attr = pos_edge_attr.reshape(-1, 1)\n if self.norm:\n pos_edge_attr /= (pos_edge_attr.max() if self.max is None else self.max)\n\n if pseudo is not None and self.cat:\n pseudo = pseudo.view(-1, 1) if pseudo.dim() == 1 else pseudo\n data.pos_edge_attr = torch.cat([pseudo, pos_edge_attr.type_as(pseudo)], dim=-1)\n else:\n data.pos_edge_attr = pos_edge_attr\n\n # negative\n if 'neg_edge_attr' in data._mapping:\n pseudo = data.neg_edge_attr\n else:\n pseudo = None\n row, col = data.neg_edge_index\n neg_edge_attr = data.contact_map[row, col]\n if self.convert_to_attr:\n neg_edge_attr = neg_edge_attr.reshape(-1, 1)\n if self.norm:\n neg_edge_attr /= (neg_edge_attr.max() if self.max is None else self.max)\n\n if pseudo is not None and self.cat:\n pseudo = pseudo.view(-1, 1) if pseudo.dim() == 1 else pseudo\n data.neg_edge_attr = torch.cat([pseudo, neg_edge_attr.type_as(pseudo)], dim=-1)\n else:\n data.neg_edge_attr = neg_edge_attr\n\n else:\n (row, col), pseudo = data.edge_index, data.edge_attr\n if self.bonded:\n assert data.contact_map_bonded is not None, \"Can't be None\"\n graph = data.contact_map_bonded\n elif self.diag_norm:\n graph = data.contact_map_diag\n elif self.corr:\n graph = data.contact_map_corr\n else:\n graph = data.contact_map\n\n if self.rank is not None:\n pca = PCA(n_components = self.rank)\n transform = pca.fit_transform(graph)\n graph = pca.inverse_transform(transform)\n graph = torch.tensor(graph, dtype=torch.float32)\n\n edge_attr = graph[row, col]\n if self.convert_to_attr:\n edge_attr = edge_attr.reshape(-1, 1)\n\n if self.norm:\n edge_attr /= (edge_attr.max() if self.max is None else self.max)\n\n if pseudo is not None and self.cat:\n pseudo = pseudo.view(-1, 1) if pseudo.dim() == 1 else pseudo\n data.edge_attr = torch.cat([pseudo, edge_attr.type_as(pseudo)], dim=-1)\n else:\n data.edge_attr = edge_attr\n\n return data\n\n\n def __repr__(self) -> str:\n repr = f'{self.__class__.__name__}(norm={self.norm}'\n\n if self.max is not None:\n repr += f', max={self.max}'\n\n if self.bonded:\n repr += ', bonded=True'\n\n if self.diag_norm:\n repr += ', diag_norm=True'\n\n if self.corr:\n repr += ', corr=True'\n\n if self.rank is not None:\n repr += f', rank={self.rank}'\n\n if self.split_edges:\n repr += f', split_edges={self.split_edges})'\n else:\n repr += ')'\n\n return repr\n\nclass MeanContactDistance(BaseTransform):\n '''\n Appends mean diagonal of contact map to edge attr vector.\n '''\n def __init__(self, norm=False, max_val=None, cat=True,\n convert_to_attr=False, bonded=False,\n bonded_path=None):\n '''\n Inputs:\n norm (bool): True for instant normalization\n max_val (None or int): Normalize by max_val if given, otherwise by true max\n cat (bool): True to concatenate attr, False to overwrite\n split_edges (bool): True if graph has 'positive' and 'negative' edges\n convert_to_attr (bool): True for edge attr, False for edge weight\n bonded (bool): True to use bonded contact map instead of experiment\n '''\n self.norm = norm\n self.max = max_val\n self.cat = cat\n self.convert_to_attr = convert_to_attr # bool, converts to 2d array\n # else would be an edge weight\n self.bonded = bonded\n\n def __call__(self, data):\n if self.bonded:\n assert data.contact_map_bonded is not None, \"Can't be None\"\n mean_per_diagonal = DiagonalPreprocessing.genomic_distance_statistics(data.contact_map_bonded, mode = 'freq')\n mean_per_diagonal[np.isnan(mean_per_diagonal)] = np.nanmin(mean_per_diagonal)\n else:\n mean_per_diagonal = DiagonalPreprocessing.genomic_distance_statistics(data.contact_map, mode = 'freq')\n contact_map = calculate_D(mean_per_diagonal)\n contact_map = torch.tensor(contact_map, dtype = torch.float32)\n\n (row, col), pseudo = data.edge_index, data.edge_attr\n edge_attr = contact_map[row, col]\n if self.convert_to_attr:\n edge_attr = edge_attr.reshape(-1, 1)\n\n if self.norm:\n edge_attr /= (edge_attr.max() if self.max is None else self.max)\n\n if pseudo is not None and self.cat:\n pseudo = pseudo.view(-1, 1) if pseudo.dim() == 1 else pseudo\n data.edge_attr = torch.cat([pseudo, edge_attr.type_as(pseudo)], dim=-1)\n else:\n data.edge_attr = edge_attr\n\n return data\n\n\n def __repr__(self) -> str:\n repr = f'{self.__class__.__name__}(norm={self.norm}'\n\n if self.max is not None:\n repr += f', max={self.max}'\n\n if self.bonded:\n repr += f', bonded={self.bonded})'\n else:\n repr += ')'\n\n return repr\n\nclass DiagonalParameterDistance(BaseTransform):\n '''\n Appends diagonal parameter to features to edge attr vector.\n '''\n def __init__(self, cat = True, split_edges = False, convert_to_attr = False,\n id = None):\n '''\n Inputs:\n cat: True to concatenate attr, False to overwrite\n split_edges: consider 'positive' and 'negative' edges separately\n convert_to_attr: True for edge attr, False for edge weight\n id: ID of trained MLP model\n '''\n self.cat = cat\n self.split_edges = split_edges # bool\n self.convert_to_attr = convert_to_attr # bool, converts to 2d array\n self.mlp_id = id\n\n def __call__(self, data):\n # get D\n if self.mlp_id is None:\n D = calculate_D(data.diag_chi_continuous)\n else:\n assert data.mlp_model_id == self.mlp_id\n D = calculate_D(data.diag_chi_continuous_mlp)\n D = torch.tensor(D, dtype = torch.float32)\n\n if self.split_edges:\n # positive\n if 'pos_edge_attr' in data._mapping:\n pseudo = data.pos_edge_attr\n else:\n pseudo = None\n\n row, col = data.pos_edge_index\n pos_edge_attr = D[row, col]\n if self.convert_to_attr:\n pos_edge_attr = pos_edge_attr.reshape(-1, 1)\n\n if pseudo is not None and self.cat:\n pseudo = pseudo.view(-1, 1) if pseudo.dim() == 1 else pseudo\n data.pos_edge_attr = torch.cat([pseudo, pos_edge_attr.type_as(pseudo)], dim=-1)\n else:\n data.pos_edge_attr = pos_edge_attr\n\n # negative\n if 'neg_edge_attr' in data._mapping:\n pseudo = data.neg_edge_attr\n else:\n pseudo = None\n row, col = data.neg_edge_index\n neg_edge_attr = D[row, col]\n if self.convert_to_attr:\n neg_edge_attr = neg_edge_attr.reshape(-1, 1)\n\n if pseudo is not None and self.cat:\n pseudo = pseudo.view(-1, 1) if pseudo.dim() == 1 else pseudo\n data.neg_edge_attr = torch.cat([pseudo, neg_edge_attr.type_as(pseudo)], dim=-1)\n else:\n data.neg_edge_attr = neg_edge_attr\n\n else:\n (row, col), pseudo = data.edge_index, data.edge_attr\n edge_attr = D[row, col]\n if self.convert_to_attr:\n edge_attr = edge_attr.reshape(-1, 1)\n\n if pseudo is not None and self.cat:\n pseudo = pseudo.view(-1, 1) if pseudo.dim() == 1 else pseudo\n data.edge_attr = torch.cat([pseudo, edge_attr.type_as(pseudo)], dim=-1)\n else:\n data.edge_attr = edge_attr\n\n return data\n\n def __repr__(self) -> str:\n return (f'{self.__class__.__name__}'\n f'(mlp_id={self.mlp_id})')\n\n# message passing\nclass WeightedSignedConv(MessagePassing):\n '''\n Variant of SignedConv that allows for edge weights or edge features.\n Adapted from: https://pytorch-geometric.readthedocs.io/en/latest/_modules/\n torch_geometric/nn/conv/signed_conv.html#SignedConv\n\n Args:\n in_channels (int): Size of each input sample, or :obj:`-1` to derive\n the size from the first input(s) to the forward method.\n out_channels (int): Size of each output sample.\n first_aggr (bool): Denotes which aggregation formula to use.\n bias (bool, optional): If set to :obj:`False`, the layer will not learn\n an additive bias. (default: :obj:`True`)\n edge_dim (int, optional): Edge feature dimensionality (in case\n there are any). (default: :obj:`None`)\n **kwargs (optional): Additional arguments of\n :class:`torch_geometric.nn.conv.MessagePassing`.\n '''\n def __init__(self, in_channels: int, out_channels: int, first_aggr: bool,\n bias: bool = True, edge_dim: int = 0, **kwargs):\n\n kwargs.setdefault('aggr', 'mean')\n super().__init__(**kwargs)\n\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.first_aggr = first_aggr\n self.edge_dim = edge_dim\n\n if first_aggr:\n self.lin_pos_l = Linear(in_channels + self.edge_dim, out_channels, False)\n self.lin_pos_r = Linear(in_channels, out_channels, bias)\n self.lin_neg_l = Linear(in_channels + self.edge_dim, out_channels, False)\n self.lin_neg_r = Linear(in_channels, out_channels, bias)\n else:\n self.lin_pos_l = Linear(2 * (in_channels + self.edge_dim), out_channels, False)\n self.lin_pos_r = Linear(in_channels, out_channels, bias)\n self.lin_neg_l = Linear(2 * (in_channels + self.edge_dim), out_channels, False)\n self.lin_neg_r = Linear(in_channels, out_channels, bias)\n\n self.reset_parameters()\n\n def reset_parameters(self):\n self.lin_pos_l.reset_parameters()\n self.lin_pos_r.reset_parameters()\n self.lin_neg_l.reset_parameters()\n self.lin_neg_r.reset_parameters()\n\n\n def forward(self, x: Union[Tensor, PairTensor], pos_edge_index: Adj,\n neg_edge_index: Adj, pos_edge_attr: OptTensor = None,\n neg_edge_attr: OptTensor = None):\n if isinstance(x, Tensor):\n x: PairTensor = (x, x)\n\n # propagate_type: (x: PairTensor, edge_weight: OptTensor)\n if self.first_aggr:\n out_pos = self.propagate(pos_edge_index, x=x, size=None,\n edge_attr=pos_edge_attr)\n out_pos = self.lin_pos_l(out_pos)\n out_pos += self.lin_pos_r(x[1])\n\n out_neg = self.propagate(neg_edge_index, x=x, size=None,\n edge_attr=neg_edge_attr)\n out_neg = self.lin_neg_l(out_neg)\n out_neg += self.lin_neg_r(x[1])\n\n return torch.cat([out_pos, out_neg], dim=-1)\n\n else:\n F_in = self.in_channels\n\n out_pos1 = self.propagate(pos_edge_index, size=None,\n edge_attr=pos_edge_attr,\n x=(x[0][..., :F_in], x[1][..., :F_in]))\n out_pos2 = self.propagate(neg_edge_index, size=None,\n edge_attr=neg_edge_attr,\n x=(x[0][..., F_in:], x[1][..., F_in:]))\n out_pos = torch.cat([out_pos1, out_pos2], dim=-1)\n out_pos = self.lin_pos_l(out_pos)\n out_pos += self.lin_pos_r(x[1][..., :F_in])\n\n out_neg1 = self.propagate(pos_edge_index, size=None,\n edge_attr=pos_edge_attr,\n x=(x[0][..., F_in:], x[1][..., F_in:]))\n out_neg2 = self.propagate(neg_edge_index, size=None,\n edge_attr=neg_edge_attr,\n x=(x[0][..., :F_in], x[1][..., :F_in]))\n out_neg = torch.cat([out_neg1, out_neg2], dim=-1)\n out_neg = self.lin_neg_l(out_neg)\n out_neg += self.lin_neg_r(x[1][..., F_in:])\n\n return torch.cat([out_pos, out_neg], dim=-1)\n\n\n def message(self, x_j: Tensor, edge_attr: OptTensor) -> Tensor:\n if self.edge_dim == 0:\n # treat edge_attr as a weight if it exists\n result = x_j if edge_attr is None else edge_attr.view(-1, 1) * x_j\n else:\n result = x_j if edge_attr is None else torch.cat((x_j, edge_attr), axis = 1)\n return result\n\n\n def __repr__(self) -> str:\n return (f'{self.__class__.__name__}({self.in_channels}, '\n f'{self.out_channels}, first_aggr={self.first_aggr},'\n f'edge_dim={self.edge_dim})')\n\nclass WeightedGATv2Conv(MessagePassing):\n \"\"\"\n Variant of GATv2Conv that allows for edge features during\n message passing (instead of just as attention coefficients).\n\n Args:\n in_channels (int or tuple): Size of each input sample, or :obj:`-1` to\n derive the size from the first input(s) to the forward method.\n A tuple corresponds to the sizes of source and target\n dimensionalities.\n out_channels (int): Size of each output sample.\n heads (int, optional): Number of multi-head-attentions.\n (default: :obj:`1`)\n concat (bool, optional): If set to :obj:`False`, the multi-head\n attentions are averaged instead of concatenated.\n (default: :obj:`True`)\n negative_slope (float, optional): LeakyReLU angle of the negative\n slope. (default: :obj:`0.2`)\n dropout (float, optional): Dropout probability of the normalized\n attention coefficients which exposes each node to a stochastically\n sampled neighborhood during training. (default: :obj:`0`)\n add_self_loops (bool, optional): If set to :obj:`False`, will not add\n self-loops to the input graph. (default: :obj:`True`)\n edge_dim (int, optional): Edge feature dimensionality (in case\n there are any). (default: :obj:`None`)\n edge_dim_MP (bool, optional): True to use edge features in message passing\n fill_value (float or Tensor or str, optional): The way to generate\n edge features of self-loops (in case :obj:`edge_dim != None`).\n If given as :obj:`float` or :class:`torch.Tensor`, edge features of\n self-loops will be directly given by :obj:`fill_value`.\n If given as :obj:`str`, edge features of self-loops are computed by\n aggregating all features of edges that point to the specific node,\n according to a reduce operation. (:obj:`\"add\"`, :obj:`\"mean\"`,\n :obj:`\"min\"`, :obj:`\"max\"`, :obj:`\"mul\"`). (default: :obj:`\"mean\"`)\n bias (bool, optional): If set to :obj:`False`, the layer will not learn\n an additive bias. (default: :obj:`True`)\n share_weights (bool, optional): If set to :obj:`True`, the same matrix\n will be applied to the source and the target node of every edge.\n (default: :obj:`False`)\n\n **kwargs (optional): Additional arguments of\n :class:`torch_geometric.nn.conv.MessagePassing`.\n \"\"\"\n _alpha: OptTensor\n\n def __init__(\n self,\n in_channels: Union[int, Tuple[int, int]],\n out_channels: int,\n heads: int = 1,\n concat: bool = True,\n negative_slope: float = 0.2,\n dropout: float = 0.0,\n add_self_loops: bool = True,\n edge_dim: Optional[int] = None,\n edge_dim_MP: bool = False,\n fill_value: Union[float, Tensor, str] = 'mean',\n bias: bool = True,\n share_weights: bool = False,\n **kwargs,\n ):\n super().__init__(node_dim=0, **kwargs)\n\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.heads = heads\n self.concat = concat\n self.negative_slope = negative_slope\n self.dropout = dropout\n self.add_self_loops = add_self_loops\n self.edge_dim = edge_dim\n self.edge_dim_MP = edge_dim_MP\n self.fill_value = fill_value\n self.share_weights = share_weights\n\n\n if isinstance(in_channels, int):\n self.lin_l = Linear(in_channels, heads * out_channels, bias=bias,\n weight_initializer='glorot')\n if share_weights:\n self.lin_r = self.lin_l\n else:\n self.lin_r = Linear(in_channels, heads * out_channels,\n bias=bias, weight_initializer='glorot')\n else:\n self.lin_l = Linear(in_channels[0], heads * out_channels,\n bias=bias, weight_initializer='glorot')\n if share_weights:\n self.lin_r = self.lin_l\n else:\n self.lin_r = Linear(in_channels[1], heads * out_channels,\n bias=bias, weight_initializer='glorot')\n\n self.att = Parameter(torch.Tensor(1, heads, out_channels))\n\n if edge_dim is not None:\n # if edge_dim_MP:\n # self.lin_edge_MP = Linear(edge_dim, heads * out_channels, bias=False,\n # weight_initializer='glorot')\n self.lin_edge = Linear(edge_dim, heads * out_channels, bias=False,\n weight_initializer='glorot')\n else:\n self.lin_edge = None\n\n if bias and concat:\n self.bias = Parameter(torch.Tensor(heads * out_channels))\n elif bias and not concat:\n self.bias = Parameter(torch.Tensor(out_channels))\n else:\n self.register_parameter('bias', None)\n\n self._alpha = None\n\n self.reset_parameters()\n\n def reset_parameters(self):\n self.lin_l.reset_parameters()\n self.lin_r.reset_parameters()\n if self.lin_edge is not None:\n self.lin_edge.reset_parameters()\n glorot(self.att)\n zeros(self.bias)\n\n\n def forward(self, x: Union[Tensor, PairTensor], edge_index: Adj,\n edge_attr: OptTensor = None,\n return_attention_weights: bool = None):\n r\"\"\"\n Args:\n return_attention_weights (bool, optional): If set to :obj:`True`,\n will additionally return the tuple\n :obj:`(edge_index, attention_weights)`, holding the computed\n attention weights for each edge. (default: :obj:`None`)\n \"\"\"\n H, C = self.heads, self.out_channels\n\n x_l: OptTensor = None\n x_r: OptTensor = None\n if isinstance(x, Tensor):\n assert x.dim() == 2\n x_l = self.lin_l(x).view(-1, H, C)\n if self.share_weights:\n x_r = x_l\n else:\n x_r = self.lin_r(x).view(-1, H, C)\n else:\n x_l, x_r = x[0], x[1]\n assert x[0].dim() == 2\n x_l = self.lin_l(x_l).view(-1, H, C)\n if x_r is not None:\n x_r = self.lin_r(x_r).view(-1, H, C)\n\n assert x_l is not None\n assert x_r is not None\n\n if self.add_self_loops:\n if isinstance(edge_index, Tensor):\n num_nodes = x_l.size(0)\n if x_r is not None:\n num_nodes = min(num_nodes, x_r.size(0))\n edge_index, edge_attr = remove_self_loops(\n edge_index, edge_attr)\n edge_index, edge_attr = add_self_loops(\n edge_index, edge_attr, fill_value=self.fill_value,\n num_nodes=num_nodes)\n elif isinstance(edge_index, SparseTensor):\n if self.edge_dim is None:\n edge_index = set_diag(edge_index)\n else:\n raise NotImplementedError(\n \"The usage of 'edge_attr' and 'add_self_loops' \"\n \"simultaneously is currently not yet supported for \"\n \"'edge_index' in a 'SparseTensor' form\")\n\n # propagate_type: (x: PairTensor, edge_attr: OptTensor)\n out = self.propagate(edge_index, x=(x_l, x_r), edge_attr=edge_attr,\n size=None)\n\n alpha = self._alpha\n self._alpha = None\n\n if self.concat:\n out = out.view(-1, self.heads * self.out_channels)\n else:\n out = out.mean(dim=1)\n\n if self.bias is not None:\n out += self.bias\n\n if isinstance(return_attention_weights, bool):\n assert alpha is not None\n if isinstance(edge_index, Tensor):\n return out, (edge_index, alpha)\n elif isinstance(edge_index, SparseTensor):\n return out, edge_index.set_value(alpha, layout='coo')\n else:\n return out\n\n\n def message(self, x_j: Tensor, x_i: Tensor, edge_attr: OptTensor,\n index: Tensor, ptr: OptTensor,\n size_i: Optional[int]) -> Tensor:\n x = x_i + x_j\n\n if edge_attr is not None:\n if edge_attr.dim() == 1:\n edge_attr = edge_attr.view(-1, 1)\n\n # if self.edge_dim_MP:\n # assert self.lin_edge_MP is not None\n\n assert self.lin_edge is not None\n edge_attr = self.lin_edge(edge_attr)\n edge_attr = edge_attr.view(-1, self.heads, self.out_channels)\n x += edge_attr\n\n x = F.leaky_relu(x, self.negative_slope)\n alpha = (x * self.att).sum(dim=-1)\n alpha = softmax(alpha, index, ptr, size_i)\n self._alpha = alpha\n alpha = F.dropout(alpha, p=self.dropout, training=self.training)\n\n if self.edge_dim_MP and edge_attr is not None:\n return (x_j + edge_attr) * alpha.unsqueeze(-1)\n else:\n return x_j * alpha.unsqueeze(-1)\n\n def __repr__(self) -> str:\n return (f'{self.__class__.__name__}({self.in_channels}, '\n f'{self.out_channels}, heads={self.heads})')\n","repo_name":"ERSchultz/sequences_to_contact_maps","sub_path":"scripts/neural_nets/pyg_fns.py","file_name":"pyg_fns.py","file_ext":"py","file_size_in_byte":41051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"38914296419","text":"from configparser import ConfigParser\nfrom ipaddress import ip_address\nfrom json import load, dump\nfrom socket import IPPROTO_UDP\nfrom socketserver import BaseRequestHandler\n\nfrom BaseServers import BaseRawServer\nfrom RawPacket import Ethernet, IPv4, UDP, MAC_Address\nfrom . import Packet, Options\nfrom .GarbageCollection import GarbageCollector\nfrom .Pool import Pool\n\ndefaults = ConfigParser()\ndefaults.read(r'Servers/DHCP/config.ini')\n\n\nclass RawHandler(BaseRequestHandler):\n eth = None\n ip = None\n udp = None\n packet = None\n is_dhcp = False\n\n def setup(self):\n self.eth = Ethernet.disassemble(self.request[0])\n self.ip = self.eth.payload\n if self.ip.protocol == IPPROTO_UDP:\n self.udp = self.ip.payload\n if self.udp.destination == self.server.server_port:\n self.is_dhcp = True\n self.packet = Packet.DHCPPacket.disassemble(self.udp.payload)\n return\n\n def handle(self):\n if self.is_dhcp:\n\n packet = None\n\n if Options.DHCPMessageType(1) in self.packet.options:\n packet = self.handle_disco()\n elif Options.DHCPMessageType(3) in self.packet.options:\n packet = self.handle_req()\n elif Options.DHCPMessageType(4) in self.packet.options:\n packet = self.handle_decline()\n elif Options.DHCPMessageType(7) in self.packet.options:\n packet = self.handle_release()\n elif Options.DHCPMessageType(8) in self.packet.options:\n packet = self.handle_inform()\n\n if packet:\n\n # Building UDP Packet\n\n udp = UDP(self.server.server_port, self.server.client_port, packet.build())\n\n # Building IP packet\n\n ip = IPv4(self.server.server_ip, ip_address('255.255.255.255'), udp)\n\n if self.packet.hops:\n packet.hops = self.packet.hops\n packet.giaddr = self.packet.giaddr\n ip.destination = packet.giaddr\n\n elif self.packet.ciaddr._ip:\n # If client has a put a reachable IP address in this field\n # Send to this specific address\n ip.destination = self.packet.ciaddr\n\n # Building Ethernet packet\n\n eth = Ethernet(self.packet.chaddr, self.server.server_address[-1], ip)\n\n if self.server.broadcast or self.packet.broadcast:\n eth.destination = MAC_Address('FF:FF:FF:FF:FF:FF')\n\n eth.calc_checksum()\n self.request[1].send(eth.build())\n\n def handle_disco(self):\n # Building DHCP offer Packet\n\n offer = Packet.DHCPPacket(op=2, xid=self.packet.xid, _chaddr=self.eth.source,\n broadcast=self.packet.broadcast or self.server.broadcast)\n offer.options.append(Options.DHCPMessageType(2))\n offer.options.extend(self.server.server_options.values())\n\n client_hostname = b''\n offer_ip = None\n\n for option in self.packet.options:\n if option.code == Options.ParameterRequestList.code:\n for code in option.data:\n if code in self.server.options:\n offer.options.append(self.server.options[code])\n\n if option.code == Options.RequestedIP.code:\n offer_ip = option.data\n\n if option.code == Options.HostName.code:\n client_hostname = option.data\n\n offer.options.append(Options.End())\n\n offer.siaddr = self.server.server_ip\n offer.yiaddr = self.server.pool.get_ip(self.packet.chaddr, offer_ip)\n\n if offer.yiaddr:\n # If we're offering a valid IP (EG not None), proceed with offer\n self.server.register_offer(offer.chaddr, offer.xid, offer.yiaddr, client_hostname)\n return offer\n\n def handle_req(self):\n\n # Building DHCP acknowledge Packet\n\n ack = Packet.DHCPPacket(op=2, xid=self.packet.xid, _chaddr=self.eth.source,\n broadcast=self.packet.broadcast or self.server.broadcast)\n ack.options.append(Options.DHCPMessageType(5))\n ack.options.extend(self.server.server_options.values())\n\n offer_ip, client_hostname = self.server.offers[(ack.chaddr, ack.xid)]\n req_ip = None\n\n for option in self.packet.options:\n if option.code == Options.ParameterRequestList.code:\n for code in option.data:\n if code in self.server.options:\n ack.options.append(self.server.options[code])\n\n if option.code == Options.RequestedIP.code:\n # If the client didn't request a specific IP in the discover packet\n req_ip = option.data\n\n if option.code == Options.HostName.code:\n # If the client didn't specify a hostname in the discover packet\n client_hostname = option.data\n\n if option.code == Options.DHCPServerID.code:\n if option.data != self.server.server_ip:\n # If the client is trying to request from a server other than us.\n return None\n\n ack.options.append(Options.End())\n\n ack.siaddr = self.server.server_ip\n\n if req_ip and req_ip != offer_ip:\n ack.yiaddr = self.server.pool.get_ip(self.packet.chaddr, offer_ip)\n else:\n ack.yiaddr = offer_ip\n\n if ack.yiaddr:\n self.server.register_client(ack.chaddr, client_hostname, ack.yiaddr)\n\n return ack\n\n def handle_decline(self):\n pass\n\n def handle_release(self):\n pass\n\n def handle_inform(self):\n pass\n\n\nclass RawServer(BaseRawServer):\n clients = dict() # Keys will be a tuple of (MAC address, ClientID). ClientID defaults to b''\n offers = dict() # Keys will be a tuple of (MAC Address, XID).\n\n server_options = dict()\n options = dict() # Keys will be an int being the code of the option.\n\n def __init__(self, interface=defaults.get('optional', 'interface'), **kwargs):\n BaseRawServer.__init__(self, interface, RawHandler)\n\n # Savefile\n self.file = kwargs.get('savefile', defaults.get('optional', 'savefile'))\n\n # Server addressing information\n self.server_ip = ip_address(kwargs.get('server_ip', defaults.get('ip addresses', 'server_ip')))\n self.server_port = kwargs.get('server_port', defaults.getint('numbers', 'server_port'))\n self.client_port = kwargs.get('client_port', defaults.getint('numbers', 'client_port'))\n self.broadcast = kwargs.get('broadcast', defaults.getboolean('optional', 'broadcast'))\n\n # Server IP pool setup\n self.pool = Pool(ip_address(kwargs.get('network', defaults.get('ip addresses', 'network'))),\n ip_address(kwargs.get('mask', defaults.get('ip addresses', 'mask'))))\n\n # Timing information\n self.offer_hold_time = kwargs.get('offer_hold_time', defaults.getint('numbers', 'offer_hold_time'))\n # Default lease time of 8 days\n IPLeaseTime = kwargs.get('ipleasetime', defaults.getint('numbers', 'ipleasetime'))\n # Default renew time of 4 days\n RenewalT1 = kwargs.get('renewalt1', defaults.getint('numbers', 'renewalt1'))\n # Default rebind time of 3 days\n RenewalT2 = kwargs.get('renewalt2', defaults.getint('numbers', 'renewalt2'))\n\n self.register_server_option(Options.Subnet(self.pool.netmask))\n self.register_server_option(Options.BroadcastAddress(self.pool.broadcast))\n self.register_server_option(Options.DHCPServerID(self.server_ip))\n\n self.register_server_option(Options.IPLeaseTime(IPLeaseTime))\n self.register_server_option(Options.RenewalT1(RenewalT1))\n self.register_server_option(Options.RenewalT2(RenewalT2))\n\n self.gb = GarbageCollector()\n\n def register_offer(self, address, xid, offer_ip, client_hostname):\n self.offers[(address, xid)] = (offer_ip, client_hostname)\n self.gb.insert(self.offer_hold_time, self.release_offer, address, xid)\n\n def release_offer(self, address, xid):\n # clear short term reservation of ip address.\n if (address, xid) in self.offers:\n self.pool.add_ip(self.offers.pop((address, xid))[0])\n\n def register_client(self, address, clientid, client_ip):\n self.release_client(address, clientid) # Release previously given IP client may have for reuse\n self.clients[(address, clientid)] = client_ip\n self.gb.insert(self.get(Options.IPLeaseTime), self.release_client, address, clientid, client_ip)\n\n def release_client(self, address, clientid, client_ip=None):\n # clear long term reservation of ip address.\n if (address, clientid) in self.clients:\n if client_ip:\n if self.clients[(address, clientid)] == client_ip:\n # Prevent pre-mature removal of a client that was previously connected to network.\n self.pool.add_ip(self.clients.pop((address, clientid)))\n else:\n # If we're just trying to clear the client from the server.\n self.pool.add_ip(self.clients.pop((address, clientid)))\n\n def register_server_option(self, option):\n # These options always are included in server DHCP packets\n self.server_options[option.code] = option\n\n try:\n try:\n if option.data in self.pool._network:\n # If option data is an ip address, reserve it\n self.pool.reserve(option.__class__.__name__, option.data)\n except AttributeError:\n # Otherwise, try to iterate through the data as a list\n # and if it is an ip address in the network pool\n # reserve it\n for index, addr in enumerate(option.data, start=1):\n if addr not in self.pool._network:\n continue\n self.pool.reserve(f'{option.code}-{index}', addr)\n\n except:\n # option data isn't an IP Address\n pass\n\n def register(self, option):\n # These options are included in server DHCP packets by request of client\n self.options[option.code] = option\n\n try:\n try:\n if option.data in self.pool._network:\n # If option data is an ip address, reserve it\n self.pool.reserve(option.__class__.__name__, option.data)\n except AttributeError:\n # Otherwise, try to iterate through the data as a list\n # and if it is an ip address in the network pool\n # reserve it\n for index, addr in enumerate(option.data, start=1):\n if addr not in self.pool._network:\n continue\n self.pool.reserve(f'{option.__class__.__name__}-{index}', addr)\n\n except:\n # option data isn't an IP Address\n pass\n\n def get(self, option):\n if option.code in self.options:\n return self.options[option.code].data\n\n elif option.code in self.server_options:\n return self.server_options[option.code].data\n\n def reserve(self, mac, ip):\n mac = MAC_Address(mac)\n ip = ip_address(ip)\n self.pool.reserve(mac, ip)\n\n def unreserve(self, mac):\n mac = MAC_Address(mac)\n self.pool.unreserve(mac)\n\n def add_listing(self, mac):\n mac = MAC_Address(mac)\n self.pool.add_listing(mac)\n\n def remove_listing(self, mac):\n mac = MAC_Address(mac)\n self.pool.remove_listing(mac)\n\n def start(self):\n self.gb.start()\n super().start()\n\n def shutdown(self):\n self.save()\n self.gb.shutdown()\n super().shutdown()\n\n def save(self):\n data = dict()\n\n setup = dict()\n setup['server_ip'] = self.server_ip._ip\n setup['server_port'] = self.server_port\n setup['client_port'] = self.client_port\n setup['broadcast'] = self.broadcast\n setup['network'] = self.pool.network._ip\n setup['mask'] = self.pool.netmask._ip\n setup['offer_hold_time'] = self.offer_hold_time\n setup['ipleasetime'] = self.get(Options.IPLeaseTime)\n setup['renewalt1'] = self.get(Options.RenewalT1)\n setup['renewalt2'] = self.get(Options.RenewalT2)\n data['setup_info'] = setup\n\n reservations = dict()\n for address, ip in self.pool.reservations.items():\n try:\n # If we're saving a MAC_Address instance\n reservations[address.address] = ip._ip\n except AttributeError:\n # If we're trying to save something other than a MAC_Address\n continue\n\n data['reservations'] = reservations\n\n listing = list()\n for listing in self.pool.listing:\n listing.append(listing.address)\n data['listings'] = (listing, self.pool.list_mode)\n\n data['server_options'] = [\n list(option.pack()) for option in self.server_options.values()\n ]\n\n data['options'] = [\n list(option.pack()) for option in self.options.values()\n ]\n\n with open(self.file, 'w') as file:\n dump(data, file)\n\n @classmethod\n def load(cls, savefile, **kwargs):\n try:\n with open(savefile, 'r') as file:\n data = load(file)\n\n setup_info = data['setup_info']\n reservations = data['reservations']\n listing, list_mode = data['listings']\n\n server_options_bytes = b''.join([bytes(option_data) for option_data in data['server_options']])\n server_options = Options.BaseOption.unpack(server_options_bytes)\n\n options_bytes = b''.join([bytes(option_data) for option_data in data['options']])\n options = Options.BaseOption.unpack(options_bytes)\n\n setup_info.update(kwargs)\n\n out = cls(savefile=savefile, **setup_info)\n\n for mac, ip in reservations.items():\n out.reserve(mac, ip)\n\n for mac in listing:\n out.add_listing(mac)\n\n out.pool.list_mode = list_mode\n\n for option in server_options:\n out.register_server_option(option)\n\n for option in options:\n out.register(option)\n\n return out\n\n except FileNotFoundError:\n return cls(**kwargs)\n\n except Exception as e:\n print(f'{e.__class__.__name__}: {e}')\n\n def __enter__(self):\n self.start()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.shutdown()\n","repo_name":"ech2901/NetworkProtocols","sub_path":"Services/DHCP/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":14873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"11288986344","text":"import unittest\nfrom pages.exploreportfolio.explore_portfolio import ExplorePortfolio\nfrom utils.teststatus import TestStatus\nimport pytest\n\n@pytest.mark.usefixtures(\"oneTimesetUp\", \"setUp\")\nclass RebalanceTests(unittest.TestCase):\n\n @pytest.fixture(autouse=True)\n def classSetup(self, oneTimesetUp):\n self.ep = ExplorePortfolio(self.driver)\n self.ts = TestStatus(self.driver)\n '''\n Test A\n 1. Navigate to https://sfo-demo.herokuapp.com/model-portfolio\n 2. Select “All Weather Strategy” by clicking on “Explore Investment Ideas”\n 3. In next screen click on button “Customize Portfolio” to make changes to portfolio\n 4. Click on “Customize” button to enable edit controls\n 5. Change slider of “ SPDR S&P 500 ETF TRUST SPY US EQUITY ” to 50%\n 6. Click on “Rebalance” button\n 7. Click on “Invest” button\n 8. On next page” verify that “SPDR…” under “What your portfolio contain ?” to be 50%\n '''\n @pytest.mark.run(order=1)\n def test_rebalanceValidation(self):\n result= self.ep.checkPercenatgeAllocatedAfterCustomizeInvest()\n self.ts.markfinal('test_rebalanceValidation',result, \"test Re-balance Validation FAILED\")","repo_name":"BaraniTharan2410/weinvest-repo","sub_path":"tests/testA/rebalance_tests.py","file_name":"rebalance_tests.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"42712033039","text":"\"\"\"Tests for otter.util.zkpartitioner\"\"\"\n\nfrom kazoo.recipe.partitioner import PartitionState\n\nimport mock\n\nfrom twisted.internet.defer import Deferred\nfrom twisted.internet.task import Clock\nfrom twisted.trial.unittest import SynchronousTestCase\n\nfrom otter.test.utils import mock_log\nfrom otter.util.zkpartitioner import Partitioner\n\n\nclass PartitionerTests(SynchronousTestCase):\n \"\"\"Tests for :obj:`Partitioner`.\"\"\"\n\n def setUp(self):\n self.clock = Clock()\n self.kz_client = mock.Mock(spec=['SetPartitioner'])\n self.kz_partitioner = mock.MagicMock(\n allocating=False,\n release=False,\n failed=False,\n acquired=False)\n self.kz_client.SetPartitioner.return_value = self.kz_partitioner\n self.path = '/the-part-path'\n self.buckets = range(5)\n self.log = mock_log()\n self.time_boundary = 30\n self.buckets_received = []\n self.partitioner = Partitioner(\n self.kz_client, 10, self.path, self.buckets, self.time_boundary,\n self.log, self.buckets_received.append, clock=self.clock)\n\n def test_allocating(self):\n \"\"\"When state is ``allocating``, nothing happens.\"\"\"\n self.kz_partitioner.allocating = True\n self.partitioner.startService()\n self.log.msg.assert_called_with('Partition allocating',\n otter_msg_type='partition-allocating')\n self.assertEqual(self.buckets_received, [])\n\n def test_release(self):\n \"\"\"\n When state is ``release``, the :obj:`SetPartitioner`'s ``release_set``\n method is called.\n \"\"\"\n self.kz_partitioner.release = True\n self.partitioner.startService()\n self.log.msg.assert_called_with('Partition changed. Repartitioning',\n otter_msg_type='partition-released')\n self.kz_partitioner.release_set.assert_called_once_with()\n self.assertEqual(self.buckets_received, [])\n\n def test_failed(self):\n \"\"\"When state is ``failed``, a new partitioner is created.\"\"\"\n self.kz_partitioner.allocating = True\n self.partitioner.startService()\n\n self.kz_partitioner.allocating = False\n self.kz_partitioner.failed = True\n # expect a new SetPartitioner to be created\n new_kz_partition = object()\n self.kz_client.SetPartitioner.return_value = new_kz_partition\n\n self.clock.advance(10)\n\n self.log.msg.assert_called_with('Partition failed. Starting new',\n otter_msg_type='partition-failed')\n # Called once when starting and now again when partition failed\n self.assertEqual(self.kz_client.SetPartitioner.call_args_list,\n [mock.call(self.path,\n set=self.buckets,\n time_boundary=self.time_boundary)] * 2)\n self.assertEqual(self.partitioner.partitioner, new_kz_partition)\n self.assertEqual(self.buckets_received, [])\n\n def test_invalid_state(self):\n \"\"\"\n When none of the expected states are True, the ``finish`` method is\n called on the partitioner and a new partitioner is created.\n \"\"\"\n self.kz_partitioner.allocating = True\n self.partitioner.startService()\n self.kz_partitioner.allocating = False\n self.kz_partitioner.state = 'bad'\n\n # expect a new SetPartitioner to be created\n new_kz_partition = object()\n self.kz_client.SetPartitioner.return_value = new_kz_partition\n\n self.clock.advance(10)\n\n self.log.err.assert_called_with(\n 'Unknown state bad. This cannot happen. Starting new',\n otter_msg_type='partition-invalid-state')\n self.kz_partitioner.finish.assert_called_once_with()\n\n # Called once when starting and now again when got bad state\n self.assertEqual(self.kz_client.SetPartitioner.call_args_list,\n [mock.call(self.path,\n set=self.buckets,\n time_boundary=self.time_boundary)] * 2)\n self.assertEqual(self.partitioner.partitioner, new_kz_partition)\n self.assertEqual(self.buckets_received, [])\n\n def test_acquired(self):\n \"\"\"When state is acquired, our callback is invoked with the buckets.\"\"\"\n self.kz_partitioner.acquired = True\n self.kz_partitioner.__iter__.return_value = iter([2, 3])\n self.partitioner.startService()\n self.log.msg.assert_called_once_with(\n 'Got buckets {buckets}',\n buckets=[2, 3], old_buckets=[], path=self.path,\n otter_msg_type='partition-acquired')\n self.assertEqual(self.buckets_received, [[2, 3]])\n\n def test_repeat(self):\n \"\"\"\n buckets are received every iteration that the partitioner is acquired.\n \"\"\"\n self.kz_partitioner.acquired = True\n self.kz_partitioner.__iter__.return_value = [2, 3]\n self.partitioner.startService()\n self.log.msg.assert_called_once_with(\n 'Got buckets {buckets}',\n buckets=[2, 3], old_buckets=[], path=self.path,\n otter_msg_type='partition-acquired')\n self.clock.advance(10)\n self.clock.advance(10)\n self.assertEqual(self.buckets_received, [[2, 3], [2, 3], [2, 3]])\n\n def test_got_buckets_return(self):\n \"\"\"\n `got_buckets` return value is propogated to timerservice that ensures\n that the service stops after returned deferred is fired\n \"\"\"\n self.kz_partitioner.acquired = True\n self.kz_partitioner.__iter__.return_value = [2, 3]\n self.buckets_got = None\n d = Deferred()\n\n def got_buckets(_buckets):\n self.buckets_got = _buckets\n return d\n\n partitioner = Partitioner(\n self.kz_client, 10, self.path, self.buckets, self.time_boundary,\n self.log, got_buckets, clock=self.clock)\n partitioner.startService()\n self.log.msg.assert_called_once_with(\n 'Got buckets {buckets}',\n buckets=[2, 3], old_buckets=[], path=self.path,\n otter_msg_type='partition-acquired')\n self.assertEqual(self.buckets_got, [2, 3])\n self.clock.advance(10)\n # Stopping service does not complete even after advancing clock\n # since got_buckets deferred has not fired yet\n sd = partitioner.stopService()\n self.assertNoResult(sd)\n # Service stops after deferred is fired\n d.callback(None)\n self.successResultOf(sd)\n\n def test_no_log_spam(self):\n \"\"\"Bucket changes are not logged when the buckets don't change.\"\"\"\n self.kz_partitioner.acquired = True\n self.kz_partitioner.__iter__.return_value = [2, 3]\n self.partitioner.startService()\n self.clock.advance(10)\n self.clock.advance(10)\n self.log.msg.assert_called_once_with(\n 'Got buckets {buckets}',\n buckets=[2, 3], old_buckets=[], path=self.path,\n otter_msg_type='partition-acquired')\n\n def test_log_on_difference(self):\n \"\"\"Bucket changes are logged when the buckets change.\"\"\"\n self.kz_partitioner.acquired = True\n self.kz_partitioner.__iter__.return_value = [2, 3]\n self.partitioner.startService()\n self.log.msg.assert_called_once_with(\n 'Got buckets {buckets}',\n buckets=[2, 3], old_buckets=[], path=self.path,\n otter_msg_type='partition-acquired')\n self.kz_partitioner.__iter__.return_value = [3, 4]\n self.clock.advance(10)\n self.log.msg.assert_called_with(\n 'Got buckets {buckets}',\n buckets=[3, 4], old_buckets=[2, 3], path=self.path,\n otter_msg_type='partition-acquired')\n\n def test_stop_service_not_acquired(self):\n \"\"\"\n stopService() does not stop the allocation (i.e. call finish) if\n it is not acquired.\n \"\"\"\n self.kz_partitioner.allocating = True\n self.partitioner.startService()\n d = self.partitioner.stopService()\n self.assertFalse(self.kz_partitioner.finish.called)\n self.successResultOf(d)\n\n def test_stop_service_acquired(self):\n \"\"\"\n stopService() calls ``finish`` on the partitioner if it is acquired.\n \"\"\"\n self.kz_partitioner.acquired = True\n self.partitioner.startService()\n d = self.partitioner.stopService()\n self.assertIs(self.successResultOf(d),\n self.kz_partitioner.finish.return_value)\n\n def test_stop_service_stops_polling(self):\n \"\"\"\n stopService causes the service to stop checking the partitioner every\n interval.\n \"\"\"\n self.kz_partitioner.allocating = True\n self.partitioner.startService()\n self.kz_partitioner.acquired = True\n self.kz_partitioner.allocating = False\n self.kz_partitioner.__iter__.return_value = iter([2, 3])\n self.partitioner.stopService()\n self.assertEqual(self.partitioner.running, False)\n self.clock.advance(10)\n self.assertEqual(self.buckets_received, [])\n\n def test_reset_path(self):\n \"\"\"``reset_path`` creates a new partitioner at the given path.\"\"\"\n self.partitioner.reset_path('/new_path')\n self.assertEqual(self.partitioner.partitioner_path, '/new_path')\n self.kz_client.SetPartitioner.assert_called_once_with(\n '/new_path',\n set=self.buckets,\n time_boundary=self.time_boundary)\n self.assertEqual(self.partitioner.partitioner,\n self.kz_client.SetPartitioner.return_value)\n\n def test_health_check_not_running(self):\n \"\"\"When the service isn't running, the service is unhealthy.\"\"\"\n self.assertEqual(\n self.successResultOf(self.partitioner.health_check()),\n (False, {'reason': 'Not running'}))\n\n def test_health_check_not_acquired(self):\n \"\"\"When the buckets aren't acquired, the service is unhealthy.\"\"\"\n self.kz_partitioner.allocating = True\n self.partitioner.startService()\n self.assertEqual(\n self.successResultOf(self.partitioner.health_check()),\n (False, {'reason': 'Not acquired'}))\n\n def test_health_check_acquired(self):\n \"\"\"When the buckets are acquired, they're included in the info.\"\"\"\n self.kz_partitioner.acquired = True\n self.partitioner.startService()\n self.kz_partitioner.__iter__.return_value = iter([2, 3])\n self.assertEqual(\n self.successResultOf(self.partitioner.health_check()),\n (True, {'buckets': [2, 3]}))\n\n def test_get_current_buckets(self):\n \"\"\"The current buckets can be retrieved.\"\"\"\n self.kz_partitioner.acquired = True\n self.partitioner.startService()\n self.kz_partitioner.__iter__.return_value = iter([2, 3])\n self.assertEqual(self.partitioner.get_current_buckets(), [2, 3])\n\n def test_get_current_state(self):\n \"\"\"The current state can be retrieved.\"\"\"\n self.kz_partitioner.state = PartitionState.ACQUIRED\n self.partitioner.startService()\n self.assertEqual(self.partitioner.get_current_state(),\n PartitionState.ACQUIRED)\n","repo_name":"rackerlabs/otter","sub_path":"otter/test/util/test_zkpartitioner.py","file_name":"test_zkpartitioner.py","file_ext":"py","file_size_in_byte":11380,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"27"} +{"seq_id":"72325546633","text":"\n# =============================================================================\n# Gradient Boosting Algorithm\n# =============================================================================\n\n# =============================================================================\n# Problem Statement\n# Using the Boston Housing Data, predict the prices using Gradient Boosting (XGBoost)\n# =============================================================================\n\n\n# =============================================================================\n# Preparing the Enviornment\n# =============================================================================\n\nfrom sklearn.datasets import load_boston\nimport pandas as pd\nimport xgboost as xgb\nfrom sklearn.metrics import mean_squared_error\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\n\n# =============================================================================\n# Loading the Data\n# =============================================================================\n\n#import it from scikit-learn \nboston = load_boston()\nprint(boston.keys()) #boston variable itself is a dictionary, so you can check for its keys using the .keys() method.\nprint(boston.data.shape)\nprint(boston.feature_names)\nprint(boston.DESCR)\n\n\n# =============================================================================\n# Exploraotry Data Analysis\n# =============================================================================\n\ndata = pd.DataFrame(boston.data)\ndata.columns = boston.feature_names\ndata.head()\ndata['PRICE'] = boston.target #Dependent Variable\ndata.info()\nstats_df = pd.DataFrame(data.describe())\n\n\n#Separate the target variable and rest of the variables using .iloc to subset the data.\nX, y = data.iloc[:,:-1],data.iloc[:,-1]\n\n#XGBoost supports and gives it acclaimed performance and efficiency gains\ndata_dmatrix = xgb.DMatrix(data=X,label=y)\n\n#Splitting the Data into Train and Test\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=123)\n\n\n#Fitting the XGBoost Model\nxg_reg = xgb.XGBRegressor(objective ='reg:linear', colsample_bytree = 0.3, learning_rate = 0.1,\n max_depth = 5, alpha = 10, n_estimators = 10)\n\n\nxg_reg.fit(X_train,y_train)\n\n# Train Error\npreds_train = xg_reg.predict(X_train)\nrmse_train = np.sqrt(mean_squared_error(y_train, preds_train))\nprint(\"TRAIN RMSE: %f\" % (rmse_train))\n\n#Test Error\npreds = xg_reg.predict(X_test)\nrmse = np.sqrt(mean_squared_error(y_test, preds))\nprint(\"TEST RMSE: %f\" % (rmse))\n\n\n#k-fold Cross Validation using XGBoost \nparams = {\"objective\":\"reg:linear\",'colsample_bytree': 0.3,'learning_rate': 0.1,\n 'max_depth': 5, 'alpha': 10}\n\ncv_results = xgb.cv(dtrain=data_dmatrix, params=params, nfold=3,\n num_boost_round=50,early_stopping_rounds=10,metrics=\"rmse\", as_pandas=True, seed=123)\n\ncv_results.head()\n\n\nprint((cv_results[\"test-rmse-mean\"]).tail(1))\n\n\nxg_reg = xgb.train(params=params, dtrain=data_dmatrix, num_boost_round=50)\n\n\n# =============================================================================\n# Final Model\n# =============================================================================\n\n\nimport matplotlib.pyplot as plt\nxgb.plot_tree(xg_reg, num_trees=15)\nplt.rcParams['figure.figsize']=('70','30')\nplt.show()\n\n\n# =============================================================================\n# Feature Importance \n# =============================================================================\n\nxgb.plot_importance(xg_reg)\nplt.rcParams['figure.figsize'] = [5, 5]\nplt.show()\n","repo_name":"rakshithjm97/Predict_the_prices_using_Gradient_Boosting","sub_path":"Gradient Boosting_v1.py","file_name":"Gradient Boosting_v1.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"71851541511","text":"from fastapi import APIRouter\nfrom fastapi import Depends, Path, Query, status\nfrom fastapi.responses import JSONResponse\nfrom fastapi.encoders import jsonable_encoder\nfrom typing import List\nfrom middlewares.jwt_bearer import JWTBearer\nfrom config.database import Session\nfrom models.movie import Movie as MovieModel\nfrom services.movie import MovieService\nfrom schemas.movie import Movie\n\nmovie_router = APIRouter()\n\n@movie_router.get('/movie',tags=['movie'],response_model=List[Movie], status_code=status.HTTP_200_OK, dependencies=[Depends(JWTBearer())])\ndef get_movies() -> List[Movie]:\n db = Session()\n result = MovieService(db).get_movies()\n return JSONResponse(status_code=status.HTTP_200_OK, content=jsonable_encoder(result))\n\n@movie_router.get('/movie/{id}',tags=['movie'],response_model=Movie, status_code=status.HTTP_200_OK)\ndef get_movie(id:int = Path(ge=1,le=2000)) -> Movie:\n db = Session()\n result = MovieService(db).get_movies(id)\n if not result:\n return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content='No Encontrado')\n else:\n return JSONResponse(status_code=status.HTTP_200_OK, content=jsonable_encoder(result))\n #for item in movies:\n # if item['id'] == id:\n # return JSONResponse(status_code=status.HTTP_200_OK, content=item)\n #return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content=jsonable_encoder(result))\n\n@movie_router.get('/movies/',tags=['movie'], response_model=List[Movie], status_code=status.HTTP_200_OK)\ndef get_movie_by_category(category:str = Query(min_length=5,max_length=15)) -> List[Movie]:\n db = Session()\n result = MovieService(db).get_movies_by_category(category)\n if not result:\n return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content='No Encontrado')\n else:\n return JSONResponse(status_code=status.HTTP_200_OK, content=jsonable_encoder(result))\n #for item in movies:\n # if item['category'] == category:\n # return JSONResponse(status_code=status.HTTP_200_OK, content=item)\n #return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content=[])\n\n@movie_router.post('/movies',tags=['movie'], response_model=dict, status_code=status.HTTP_201_CREATED)\ndef create_movie(movie:Movie) -> dict:\n db = Session()\n MovieService(db).create_movie(movie)\n #movies.append(movie.dict())\n return JSONResponse(status_code=status.HTTP_201_CREATED, content={'message':'Se registro la película'})\n\n@movie_router.put('/movie/{id}',tags=['movie'], response_model=dict, status_code=status.HTTP_200_OK)\ndef update_movie_movies_id(id:int,item:Movie) -> dict:\n \n db = Session()\n result = MovieService(db).get_movies(id)\n if not result:\n return JSONResponse(status_code=status.HTTP_404_NOT_FOUND,content='No de Encontró')\n else:\n MovieService(db).update_movie(id,item)\n return JSONResponse(status_code=status.HTTP_200_OK, content='Se ha modificado')\n \n try:\n index = [movie['id'] for movie in movies].index(id)\n movies[index] = item.dict()\n return JSONResponse(status_code=status.HTTP_200_OK, content={'message':'Se modificado la película'})\n except ValueError:\n return {'error':'Movie not Found'}\n signal = False\n for i in movies:\n if i['id'] == id:\n i['tittle'] = item.tittle\n i['review'] = item.review\n i['year'] = item.year\n i['ranking'] = item.ranking\n i['category'] = item.category\n signal = True\n return signal\n #if signal == False:\n # raise HTTPException(status_code=404,detail='Movie not found')\n\n@movie_router.delete('/movie/{id}',tags=['movie'], response_model=dict, status_code=status.HTTP_200_OK)\ndef delete_movie(id:int) -> dict:\n db = Session()\n result = MovieService(db).get_movies(id)\n if not result:\n return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content=[])\n else:\n MovieService(db).delete_movie(id)\n return JSONResponse(status_code=status.HTTP_200_OK, content={'message':'Se eliminó la película'})\n for item in movies:\n if item['id'] == id:\n movies.remove(item)\n return JSONResponse(status_code=status.HTTP_200_OK, content={'message':'Se eliminó la película'})\n return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content=[])","repo_name":"educhumpitome/movie-api","sub_path":"routers/movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":4370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"7016755326","text":"class Stack:\r\n def __init__(self):\r\n self.top = []\r\n def __str__(self):\r\n return str(self.top)\r\n def isEmpty(self):\r\n return len(self.top) == 0\r\n def push(self,item):\r\n self.top.append(item)\r\n def pop(self): \r\n if not self.isEmpty():\r\n return self.top.pop(-1)\r\n def peek(self):\r\n if not self.isEmpty():\r\n return self.top[-1]\r\n def size(self):\r\n return len(self.top)\r\n def clear(self):\r\n self.top = []\r\n\r\nodd = Stack()\r\neven = Stack()\r\n \r\nfor i in range(10):\r\n if i % 2 == 0:\r\n even.push(i)\r\n else:\r\n odd.push(i)\r\n# print(odd)\r\n# print(even)\r\n\r\n# 괄호 검사 구현\r\ndef checkBrackets(statement):\r\n stack = Stack()\r\n for ch in statement:\r\n if ch in ('{','[','('):\r\n stack.push(ch)\r\n elif ch in ('}',']',')'):\r\n if stack.isEmpty():\r\n return False\r\n else:\r\n left = stack.pop()\r\n if (ch == '}' and left != '{') or (ch == ']' and left != '[') or (ch == '}' and left != '{'):\r\n return False\r\n return stack.isEmpty()\r\n\r\nstr = '{dfdf(dfsad)Df}'\r\n# print(checkBrackets(str))\r\n\r\n# 후위표기 수식의 계산\r\ndef evalPostfix(expr):\r\n s = Stack()\r\n for token in expr:\r\n if token in '+-*/':\r\n val2 = s.pop()\r\n val1 = s.pop()\r\n if token == '+':\r\n s.push(val1+val2)\r\n elif token == '-':\r\n s.push(val1-val2)\r\n elif token == '*':\r\n s.push(val1*val2)\r\n elif token == '/':\r\n s.push(val1/val2)\r\n else:\r\n s.push(float(token))\r\n return s.pop()\r\n\r\nsent = ['8','2','/','3','-','3','2','*','+']\r\n# print(evalPostfix(sent))\r\n\r\n# 중위표기식의 후위 변환 구현\r\ndef precedence(op):\r\n if op == '(' or op == ')':\r\n return 0\r\n elif op == '+' or op == '-':\r\n return 1\r\n elif op == '*' or op == '/':\r\n return 2\r\n else:\r\n return -1\r\n\r\ndef Infix2Postfix(expr):\r\n s = Stack()\r\n output = []\r\n for term in expr:\r\n if term in '(':\r\n s.push('(')\r\n elif term in ')':\r\n while not s.isEmpty():\r\n op = s.pop()\r\n if op == '(':\r\n break\r\n else:\r\n output.append(op)\r\n elif term in '+-*/':\r\n while not s.isEmpty():\r\n op = s.peek()\r\n if precedence(term) <= precedence(op):\r\n output.append(op)\r\n s.pop()\r\n else:\r\n break\r\n s.push(term)\r\n else:\r\n output.append(term)\r\n while not s.isEmpty():\r\n output.append(s.pop()) \r\n return output\r\n\r\ninfix1 = ['8','/','2','-','3','+','(','3','*','2',')']\r\n# print('중위표기식 후위수식 변환\\n',Infix2Postfix(infix1))\r\n# print('계산 결과\\n',evalPostfix(Infix2Postfix(infix1)))\r\n\r\n# P4.1\r\ndef make_reverse(sent):\r\n new_s = Stack()\r\n for i in sent:\r\n new_s.push(i)\r\n\r\n result = ''\r\n for j in range(len(new_s.top)):\r\n s = new_s.pop()\r\n result += s\r\n\r\n return result\r\n\r\n# P4.2\r\ndef find_palindrome(word):\r\n temp = ''\r\n for w in word:\r\n if w.isalpha():\r\n temp += w\r\n \r\n temp = temp.lower()\r\n rev = make_reverse(temp) \r\n s = Stack()\r\n s_rev = Stack()\r\n for i in temp:\r\n s.push(i)\r\n for j in rev:\r\n s_rev.push(j)\r\n flag = True\r\n for i in range(len(temp)):\r\n a = s.pop()\r\n b = s_rev.pop()\r\n if a != b:\r\n flag = False\r\n break\r\n return flag\r\npal_word = 'madam, I\"m Adam'\r\n# print(find_palindrome(pal_word))\r\n\r\n","repo_name":"dongh99/hufs_data_structure","sub_path":"stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":3793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"6257365737","text":"import random\n\nfrom environment import EnvironmentConfig, Environment\nimport math\nimport time\nimport numpy as np\nimport copy\nfrom collections import Counter\nfrom scripts.QL import QLearningAlgorythm\n\n\ndef make_tor(Ys):\n tor = [(0, 0)]\n x = 3\n for y in Ys:\n tor.append((x, y))\n x += 3\n return tor\n\n\ntor1 = make_tor([2, -4, 4, -2, 3, -2, 6, 3, 5, -3])\ntor2 = make_tor([-3, 5, 3, 6, -2, 3, -2, 4, -4, 2])\ntor3 = make_tor([0, 6, -4, -8, -6, 4, -1, -2, 3, 2])\ntor4 = make_tor([-7, 4, 6, 6, -2, 6, 6, 4, 2, 3])\ntor5 = make_tor([2, 2, -4, -7, 8, -7, -6, -6, -4, -3])\nLEARNING_TRACKS = [tor1, tor2, tor3, tor4, tor5]\ntor6 = make_tor([1, 3, 8, -3, 4, 4, 5, -1, 8, -8])\ntor7 = make_tor([-1, -3, 4, -1, 6, -1, -8, 7, -2, 0])\ntor8 = make_tor([-2, 3, 3, 7, -1, -1, -8, -5, 0, -5])\nTESTING_TRACKS = [tor6, tor7, tor8]\n\n\ndef run_epoch(env, qlearning, max_iterations, is_Boltzamann):\n iteration = 0\n total_reward = 0\n env.reset()\n\n velocity, inclination, inclination_ahead, _, _ = env.step(0)\n start_state = [\n round(velocity),\n round(inclination),\n round(inclination_ahead)\n ]\n old_state = start_state\n qlearning.make_Q(old_state)\n\n while True:\n if not is_Boltzamann:\n action = qlearning.make_move_greedy(old_state)\n else:\n action = qlearning.make_move_Boltzmann(state=old_state)\n\n velocity, inclination, inclination_ahead, reward, is_terminal = env.step(\n action)\n total_reward += reward\n\n new_state = [round(velocity), round(inclination),\n round(inclination_ahead)]\n qlearning.make_Q(new_state)\n\n qlearning.default_learning(\n new_state, is_terminal, old_state, action, round(reward, 1))\n old_state = new_state\n\n iteration += 1\n if is_terminal:\n print(\n f\"Reward: {total_reward:.1f},\\tTarget reached in {iteration} iterations.\")\n return True, iteration, total_reward, qlearning\n if iteration > max_iterations:\n print(\n f\"Reward: {total_reward:.1f},\\tIteration limit. Target not reached\")\n return False, iteration, total_reward, qlearning\n\n\ndef run_test(env, qlearning, max_iterations, hive=False):\n iteration = 0\n total_reward = 0\n env.reset()\n velocity, inclination, inclination_ahead, _, _ = env.step(0)\n state = [round(velocity), round(inclination),\n round(inclination_ahead)]\n\n while True:\n if hive is False:\n action = qlearning.make_move_optimal(state)\n else:\n actions = [q.make_move_optimal(state) for q in qlearning]\n counter = Counter(actions)\n max_count = max(counter.values())\n most_common_values = [num for num, count in counter.items() if count == max_count]\n if len(most_common_values) > 1:\n action = random.choice(most_common_values)\n else:\n action = most_common_values[0]\n\n velocity, inclination, inclination_ahead, reward, is_terminal = env.step(\n action)\n total_reward += reward\n\n state = [round(velocity), round(inclination),\n round(inclination_ahead)]\n\n iteration += 1\n if is_terminal:\n print(\n f\"Reward: {total_reward:.1f},\\tTest success: {iteration} iterations.\")\n return True, iteration, total_reward\n if iteration > max_iterations:\n print(f\"Reward: {total_reward:.1f},\\tIteration limit. Test failed\")\n return False, iteration, total_reward\n\n\ndef learn(epochs, config, qlearning, is_Boltzamann=False, track=None):\n start_time = time.time()\n iteration_counts = []\n rewards = []\n success_count = 0\n epoch_max_iterations = 5000\n\n for i in range(epochs):\n if track is None:\n config.points = LEARNING_TRACKS[int(math.floor(i/(epochs/5)))]\n env = Environment(config)\n else:\n config.points = LEARNING_TRACKS[track]\n env = Environment(config)\n\n print(f\"Epoch {i}:\\t\", end=\"\")\n succeeded, iterations, reward, qlearning = run_epoch(\n env, qlearning, epoch_max_iterations, is_Boltzamann)\n iteration_counts.append(iterations)\n rewards.append(reward)\n if succeeded:\n success_count += 1\n\n print(\"Learning finished\")\n print(f'Time: {round(time.time() - start_time, 2)}[s]')\n return success_count, iteration_counts, rewards, qlearning\n\n\ndef test(epochs, config, qlearning, hive=False):\n start_time = time.time()\n\n iteration_counts = []\n rewards = []\n success_count = 0\n epoch_max_iterations = 5000\n\n for i in range(epochs):\n config.points = TESTING_TRACKS[int(math.floor(i / 3))]\n env = Environment(config)\n\n print(f\"Test {i}:\\t\", end=\"\")\n succeeded, iterations, reward = run_test(\n env, qlearning, epoch_max_iterations, hive)\n iteration_counts.append(iterations)\n rewards.append(reward)\n if succeeded:\n success_count += 1\n\n print(\"testing finished\")\n print(f'Time: {round(time.time() - start_time, 2)}[s]')\n return success_count, iteration_counts, rewards\n\n\ndef test_params_E(config): # epsilon zachłanna\n lines = []\n lines.append(f'Gamma, Beta, Epsilon, LearningReached, TestingReached, Best, Worst, Average, Std, BestReward\\n')\n\n gammas = [0.1, 0.5, 0.9] # 0.1, 0.5, 0.9\n betas = [0.1, 0.5, 0.9] # 0.1, 0.5, 0.9\n epsys = [0, 5, 10, 20, 25] # 0, 5, 10, 20, 25\n it = 250\n t = 0\n for eps in epsys:\n for beta in betas:\n for gamma in gammas:\n avg_l_reached, avg_t_reached, avg_t_min, avg_t_max, avg_t_avg, avg_t_std, avg_t_reward = [], [], [], [], [], [], []\n\n for repeat in range(10):\n print(f'{40 * \"#\"}')\n print(f'Testing params: beta: {beta}, gamma: {gamma}, epsilon: {eps}, t: {t}, iter: {it}')\n q = QLearningAlgorythm([-1, 0, 1], gamma=gamma, beta=beta, epsilon=eps, t=t)\n l_reached, l_data, l_reward, q = learn(it, config, q, is_Boltzamann=False) # it=500\n print(f'{25 * \"#\"}')\n t_reached, t_data, t_reward = test(9, config, q)\n print(f'{25 * \"#\"}')\n print(\"Learning data:\")\n print(f\"Reached targets:\\t{l_reached}\")\n print(f\"Best time:\\t{min(l_data)}\")\n print(f\"Avg time: {np.average(l_data)}\")\n print(f\"Best reward:\\t{max(l_reward)}\")\n print(f'{25 * \"#\"}')\n t_min = min(t_data)\n t_max = max(t_data)\n t_avg = np.average(t_data)\n t_std = np.std(t_data)\n print(\"Testing data:\")\n print(f\"Reached targets: {t_reached}\")\n print(f\"Best time: {t_min}\")\n print(f\"Avg time: {t_avg}\")\n print(f\"Best reward:\\t{max(t_reward)}\")\n avg_l_reached.append(l_reached)\n avg_t_reached.append(t_reached)\n avg_t_min.append(t_min)\n avg_t_max.append(t_max)\n avg_t_avg.append(t_avg)\n avg_t_std.append(t_avg)\n avg_t_reward.append(max(t_reward))\n\n lines.append(\n f'{gamma}, {beta}, {eps}, {np.average(avg_l_reached)}, {np.average(avg_t_reached)}, '\n f'{np.average(avg_t_min)}, {np.average(avg_t_max)}, {np.average(avg_t_avg)}, {np.average(avg_t_std)}, '\n f'{np.average(avg_t_reward)}\\n')\n with open('out/QLdata_fulldata_epsilon.csv', 'w') as f:\n for line in lines:\n f.write(line)\n\n\ndef test_params_T(config): # strategia boltzmanna\n lines = []\n lines.append(f'Gamma, Beta, T, LearningReached, TestingReached, Best, Worst, Average, Std, BestReward\\n')\n\n gammas = [0.1, 0.5, 0.9] # 0.1, 0.5, 0.9\n betas = [0.1, 0.5, 0.9] # 0.1, 0.5, 0.9\n t = [0.25, 0.5, 0.75, 1]\n eps = 0\n it = 250\n for t in t:\n for beta in betas:\n for gamma in gammas:\n avg_l_reached, avg_t_reached, avg_t_min, avg_t_max, avg_t_avg, avg_t_std, avg_t_reward = [], [], [], [], [], [], []\n\n for repeat in range(10):\n print(f'{40 * \"#\"}')\n print(f'Testing params: beta: {beta}, gamma: {gamma}, epsilon: {eps}, t: {t}, iter: {it}')\n q = QLearningAlgorythm([-1, 0, 1], gamma=gamma, beta=beta, epsilon=eps, t=t)\n l_reached, l_data, l_reward, q = learn(it, config, q, is_Boltzamann=True) # it=500\n print(f'{25 * \"#\"}')\n t_reached, t_data, t_reward = test(9, config, q)\n print(f'{25 * \"#\"}')\n print(\"Learning data:\")\n print(f\"Reached targets:\\t{l_reached}\")\n print(f\"Best time:\\t{min(l_data)}\")\n print(f\"Avg time: {np.average(l_data)}\")\n print(f\"Best reward:\\t{max(l_reward)}\")\n print(f'{25 * \"#\"}')\n t_min = min(t_data)\n t_max = max(t_data)\n t_avg = np.average(t_data)\n t_std = np.std(t_data)\n print(\"Testing data:\")\n print(f\"Reached targets: {t_reached}\")\n print(f\"Best time: {t_min}\")\n print(f\"Avg time: {t_avg}\")\n print(f\"Best reward:\\t{max(t_reward)}\")\n avg_l_reached.append(l_reached)\n avg_t_reached.append(t_reached)\n avg_t_min.append(t_min)\n avg_t_max.append(t_max)\n avg_t_avg.append(t_avg)\n avg_t_std.append(t_avg)\n avg_t_reward.append(max(t_reward))\n\n lines.append(\n f'{gamma}, {beta}, {t}, {np.average(avg_l_reached)}, {np.average(avg_t_reached)}, '\n f'{np.average(avg_t_min)}, {np.average(avg_t_max)}, {np.average(avg_t_avg)}, {np.average(avg_t_std)}, '\n f'{np.average(avg_t_reward)}\\n')\n with open('out/QLdata_fulldata_T.csv', 'w') as f:\n for line in lines:\n f.write(line)\n\n\ndef test_saturation(config):\n lines = []\n lines.append(f'Iters, LearningReached, TestingReached, Best, Worst, Average, Std, BestReward\\n')\n\n gamma = 0.9\n beta = 0.1\n t = 0.25\n iters = [5, 10, 25, 50, 75, 100, 150, 200, 250, 500, 1000]\n for it in iters:\n avg_l_reached, avg_t_reached, avg_t_min, avg_t_max, avg_t_avg, avg_t_std, avg_t_reward = [], [], [], [], [], [], []\n\n for repeat in range(10):\n print(f'{40 * \"#\"}')\n print(f'Testing params: beta: {beta}, gamma: {gamma}, t: {t}, iter: {it}')\n q = QLearningAlgorythm([-1, 0, 1], gamma=gamma, beta=beta, epsilon=0, t=t)\n l_reached, l_data, l_reward, q = learn(it, config, q, is_Boltzamann=True)\n print(f'{25 * \"#\"}')\n t_reached, t_data, t_reward = test(9, config, q)\n print(f'{25 * \"#\"}')\n print(\"Learning data:\")\n print(f\"Reached targets:\\t{l_reached}\")\n print(f\"Best time:\\t{min(l_data)}\")\n print(f\"Avg time: {np.average(l_data)}\")\n print(f\"Best reward:\\t{max(l_reward)}\")\n print(f'{25 * \"#\"}')\n t_min = min(t_data)\n t_max = max(t_data)\n t_avg = np.average(t_data)\n t_std = np.std(t_data)\n print(\"Testing data:\")\n print(f\"Reached targets: {t_reached}\")\n print(f\"Best time: {t_min}\")\n print(f\"Avg time: {t_avg}\")\n print(f\"Best reward:\\t{max(t_reward)}\")\n avg_l_reached.append(l_reached)\n avg_t_reached.append(t_reached)\n avg_t_min.append(t_min)\n avg_t_max.append(t_max)\n avg_t_avg.append(t_avg)\n avg_t_std.append(t_avg)\n avg_t_reward.append(max(t_reward))\n\n lines.append(\n f'{it}, {np.average(avg_l_reached)}, {np.average(avg_t_reached)}, '\n f'{np.average(avg_t_min)}, {np.average(avg_t_max)}, {np.average(avg_t_avg)}, {np.average(avg_t_std)}, '\n f'{np.average(avg_t_reward)}\\n')\n with open('out/QLdata_fulldata_saturation_150.csv', 'w') as f:\n for line in lines:\n f.write(line)\n\n\ndef test_hive5_vs1(config):\n lines = []\n lines.append(f'SoloLearningReached, SoloTestingReached, SoloBest, SoloWorst, SoloAverage, SoloStd, SoloAverageReward,'\n f' HiveLearningReached, HiveTestingReached, HiveBest, HiveWorst, HiveAverage, HiveStd, HiveAverageReward\\n')\n\n gamma = 0.9\n beta = 0.1\n t = 0.25\n it = 10\n\n SoloLearningReached, SoloTestingReached, SoloTime, SoloBestReward = [], [], [], []\n HiveLearningReached, HiveTestingReached, HiveTime, HiveBestReward = [], [], [], []\n\n for repeat in range(25):\n print(f'{40 * \"#\"}')\n # nauka 5 osobnych agentów\n hive_q = []\n h_l_reached, h_l_data, h_l_reward = [], [], []\n for track_number, truck in enumerate(LEARNING_TRACKS):\n q = QLearningAlgorythm([-1, 0, 1], gamma=gamma, beta=beta, epsilon=0, t=t)\n l_reached, l_data, l_reward, q = learn(it, config, q, is_Boltzamann=True, track=track_number)\n h_l_reached.append(l_reached)\n h_l_data.append(l_data)\n h_l_reward.append(l_reward)\n hive_q.append(q)\n\n # nauka 1 agenta\n solo_q = QLearningAlgorythm([-1, 0, 1], gamma=gamma, beta=beta, epsilon=0, t=t)\n s_l_reached, s_l_data, s_l_reward, solo_q = learn(it*len(LEARNING_TRACKS), config, solo_q, is_Boltzamann=True)\n\n print(f'{25 * \"#\"}')\n s_t_reached, s_t_data, s_t_reward = test(9, config, solo_q)\n h_t_reached, h_t_data, h_t_reward = test(9, config, hive_q, hive=True)\n print(f'{25 * \"#\"}')\n print(\"Learning data:\")\n print(\"Hive data:\")\n HiveLearningReached.append(np.average(h_l_reached))\n print(\"Solo data:\")\n SoloLearningReached.append(s_l_reached)\n\n print(f'{25 * \"#\"}')\n print(\"Testing data:\")\n print(\"Hive data:\")\n HiveTestingReached.append(h_t_reached)\n HiveTime.append(h_t_data)\n HiveBestReward.append(h_t_reward)\n print(\"Solo data:\")\n SoloTestingReached.append(s_t_reached)\n SoloTime.append(s_t_data)\n SoloBestReward.append(s_t_reward)\n\n lines.append(\n f'{np.average(SoloLearningReached)}, {np.average(SoloTestingReached)}, '\n f'{np.average(min(SoloTime))}, {np.average(max(SoloTime))}, {np.average(SoloTime)}, {np.std(SoloTime)}, '\n f'{np.average(SoloBestReward)},'\n f'{np.average(HiveLearningReached)}, {np.average(HiveTestingReached)}, '\n f'{np.average(min(HiveTime))}, {np.average(max(HiveTime))}, {np.average(HiveTime)}, {np.std(HiveTime)}, '\n f'{np.average(HiveBestReward)}'\n f'\\n')\n with open('out/QLdata_fulldata_hive_vs_solo_not_sat.csv', 'w') as f:\n for line in lines:\n f.write(line)\n\n\ndef test_env_impact(config):\n lines = []\n lines.append(f'Number of tracks, LearningReached, TestingReached, '\n f'Best, Worst, Average, Std, AverageReward\\n')\n\n gamma = 0.9\n beta = 0.1\n t = 0.25\n it = 150\n\n for i in range(5):\n LearningReached, TestingReached, Time, BestReward = [], [], [], []\n for repeat in range(10):\n print(f'{40 * \"#\"}')\n\n q = QLearningAlgorythm([-1, 0, 1], gamma=gamma, beta=beta, epsilon=0, t=t)\n l_reached = []\n for j in range(i+1):\n l_reach, l_data, l_reward, q = learn(int(it/(i+1)), config, q, is_Boltzamann=True, track=j)\n l_reached.append(np.average(l_reach))\n\n t_reached, t_data, t_reward = test(9, config, q)\n LearningReached.append(np.average(l_reached))\n TestingReached.append(np.average(t_reached))\n Time.append(t_data)\n BestReward.append(t_reward)\n\n lines.append(\n f'{i+1}, '\n f'{np.average(LearningReached)}, {np.average(TestingReached)}, '\n f'{np.average(min(Time))}, {np.average(max(Time))}, {np.average(Time)}, {np.std(Time)}, '\n f'{np.average(BestReward)}'\n f'\\n')\n with open('out/QLdata_fulldata_env_impact.csv', 'w') as f:\n for line in lines:\n f.write(line)\n\n\ndef learnSoloAgent(config):\n gamma = 0.9\n beta = 0.1\n t = 0.25\n it = 150\n print(f'{40 * \"#\"}')\n\n q = QLearningAlgorythm([-1, 0, 1], gamma=gamma, beta=beta, epsilon=0, t=t)\n l_reached = []\n i = 3\n for j in range(i + 1):\n l_reach, l_data, l_reward, q = learn(int(it / (i + 1)), config, q, is_Boltzamann=True, track=j)\n l_reached.append(np.average(l_reach))\n\n t_reached, t_data, t_reward = test(9, config, q)\n q.save_Q(\"QLKnowledge/bestAgent.json\")\n\n\nif __name__ == \"__main__\":\n config = EnvironmentConfig()\n config.trackLength = 30\n config.cartThrustGain = 16.0\n config.gravity = 9.81\n config.efficiency = 0.995\n\n config.simDeltatime = 0.005\n config.simStepsPerStep = 6\n config.inclinationLookAheadDistance = 1.0\n\n config.positionRewardGain = 1.0\n config.velocityRewardGain = 0.0\n config.timePenaltyGain = 0.1\n config.reversingPenaltyGain = 0.0\n config.overspeedPenaltyGain = 0.0\n config.finishRewardGain = 42.0\n\n config.targetVelocity = 9.0\n config.maxVelocity = 10.0\n\n # test_params_E(config)\n # test_params_T(config)\n # test_saturation(config)\n # test_hive5_vs1(config)\n # test_env_impact(config)\n learnSoloAgent(config)\n","repo_name":"tototmek/UMA","sub_path":"QLearningFULL.py","file_name":"QLearningFULL.py","file_ext":"py","file_size_in_byte":17915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"37084493949","text":"import sys\nimport os\n\nif len(sys.argv) != 2:\n print(\"Invalid usage. Correct: export_urls [source file path]\")\n sys.exit(1)\n\nfile_name = sys.argv[1]\n\nfhand = open(file_name, \"r\")\ncontents = fhand.read()\nfhand.close()\n\nurls = set()\n\nwhile True:\n if contents.find(\"urlForThumbnail\") == -1:\n break\n\n start = contents.find(\"\\\"urlForThumbnail\\\"\")\n start += 19\n\n contents = contents[start:]\n\n end = contents.find(\"\\\"\")\n if (end > 5000 or end == -1):\n continue\n\n url = contents[:end]\n print(url)\n\n urls.add(url + \"\\n\")\n\n contents = contents[end:]\n\nif not os.path.exists(\"./dist\"):\n os.makedirs(\"./dist\")\n\nfhand = open(\"./dist/\" + file_name + \".txt\", \"w\")\nfhand.writelines(urls)\nfhand.close()\n\nprint(\"Succesfully executed. Find decoded files with URLs in dist folder.\")\n","repo_name":"zoltan-antal/vivaldi-restore-urls","sub_path":"export_urls.py","file_name":"export_urls.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"71931084871","text":"from requests import get\n\nURL = \"https://api.tequila.kiwi.com/v2/search\"\n\n\nclass FlightSearch:\n # This class is responsible for talking to the Flight Search API.\n def __init__(\n self,\n fly_from,\n fly_to,\n date_from,\n date_to,\n apikey=\"HCXPvXreO03zkkAEuK67L88jVGqA3mKP\",\n ):\n self.header = {\"apikey\": apikey}\n self.parameters = {\n \"fly_from\": fly_from,\n \"fly_to\": fly_to,\n \"date_from\": date_from,\n \"date_to\": date_to,\n \"curr\":\"IDR\",\n \"limit\":1\n }\n self.result = get(url=URL, headers=self.header, params=self.parameters)\n self.result.raise_for_status()\n self.result = self.result.json()\n","repo_name":"nico-Zero/Python","sub_path":"New_Shit__/Angela_Yu__/Day_39_and Day_40 Flight_search/flight_search_software/flight_search.py","file_name":"flight_search.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"2934712607","text":"import networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom random import randint\n\n\n# - Model NxN board as nodes in a graph.\n# - For each column place a queen and add edges to all squares she can reach.\n# - When placing a queen, she can only go on nodes with 0 edges.\n# Currently randomly choosing a clear square for each column and\n# starting again if we find a column that's in no-mans-land.\n\nN = 8\n\ndef main():\n while(True):\n b = np.arange(N*N).reshape(N,N)\n\n g = nx.Graph()\n g.add_nodes_from(b.ravel())\n\n queens = []\n for icol in range(N):\n col = b[range(N), icol]\n clear_nodes = [n[0] for n in g.degree(col) if n[1]==0]\n if len(clear_nodes) == 0:\n print('Dead End! No solution from here possible!')\n nx.draw(g)\n plt.savefig('graph.png')\n break\n\n n = clear_nodes[randint(0, len(clear_nodes)-1)]\n queens.append(n)\n\n # Add edges from the queen's square to every square she attacks\n g.add_edges_from([(n, i) for i in col]) #column\n row = np.arange(n-(n%N), (n-(n%N))+N)\n g.add_edges_from([(n, i) for i in row]) #row\n # Diagonals\n t = np.where(b == n) #(row,col) index of n\n t_ul = list(zip(range(t[0][0],-1,-1), range(t[1][0],-1,-1))) # up-left\n t_dl = list(zip(range(t[0][0],N), range(t[1][0],-1,-1))) # down-left\n t_ur = list(zip(range(t[0][0],-1,-1), range(t[1][0],N))) # up-right\n t_dr = list(zip(range(t[0][0],N), range(t[1][0],N))) # down-right\n g.add_edges_from([(n,b[i]) for i in t_ul+t_dl+t_ur+t_dr]) # diagonals\n\n\n print(f'queen locations: {queens}')\n #print(b)\n printBoard(b, queens)\n\n if(len(queens) == N):\n break\n\ndef printBoard(board, queens):\n b = np.copy(board)\n for q in queens:\n b[np.where(b==q)] = -1\n b[np.where(b>0)] = 0\n print(f\"{len(queens)}/{N} queens\")\n print(b)\n\n\nif __name__==\"__main__\":\n main()\n","repo_name":"AshyIsMe/nqueens","sub_path":"nqueens/nqueens.py","file_name":"nqueens.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"12150851670","text":"import numpy as np\nfrom typing import Tuple\n\"\"\"**Piotrek's solution**\"\"\"\n\nwith open('input.txt', 'r') as file:\n lines = file.readlines()\nstrings = []\ntemp = []\nfor line in lines:\n if line.startswith('>'):\n temp = ''.join(temp)\n strings.append(temp)\n temp = []\n continue\n else:\n temp.append(line[:-1])\ntemp = ''.join(temp)\nstrings.append(temp)\nstrings.remove('')\nprint(strings)\n\ndef edit_distance(s: str, t: str) -> Tuple[int, np.ndarray]:\n m = len(s) + 1\n n = len(t) + 1\n dynamic_table = np.zeros((m, n))\n for i in range(m):\n for j in range(n):\n if i == 0:\n dynamic_table[i][j] = j\n elif j == 0:\n dynamic_table[i][j] = i\n elif s[i - 1] == t[j - 1]:\n dynamic_table[i][j] = dynamic_table[i - 1][j - 1]\n else:\n dynamic_table[i][j] = 1 + min(dynamic_table[i - 1][j - 1],\n dynamic_table[i][j - 1],\n dynamic_table[i - 1][j])\n return int(dynamic_table[m-1][n-1]), dynamic_table\n\ndef edit_distance2(a: str, b: str) ->int:\n \"\"\"Return the Levenshtein edit distance between two strings *a* and *b*.\"\"\"\n \"\"\" https://dzone.com/articles/the-levenshtein-algorithm-1 \"\"\"\n if a == b:\n return 0\n if len(a) < len(b):\n a, b = b, a\n if not a:\n return len(b)\n previous_row = range(len(b) + 1)\n for i, column1 in enumerate(a):\n current_row = [i + 1]\n for j, column2 in enumerate(b):\n insertions = previous_row[j + 1] + 1\n deletions = current_row[j] + 1\n substitutions = previous_row[j] + (column1 != column2)\n current_row.append(min(insertions, deletions, substitutions))\n previous_row = current_row\n return previous_row[-1]\n\ndef make_best_align_strings(s: str, t: str, dynamic_table: np.ndarray, indel: str = \"-\") -> Tuple[str, str]:\n s_out = \"\"\n t_out = \"\"\n m = len(s)\n n = len(t)\n\n while m > 0 and n > 0:\n options = {\n \"diag\": dynamic_table[m - 1][n - 1],\n \"up\": dynamic_table[m - 1][n],\n \"left\": dynamic_table[m][n - 1]\n }\n move = min(options, key=options.get)\n\n if move == \"diag\":\n s_out += s[m - 1]\n t_out += t[n - 1]\n m -= 1\n n -= 1\n elif move == \"up\":\n s_out += s[m - 1]\n t_out += indel\n m -= 1\n elif move == \"left\":\n s_out += indel\n t_out += t[n - 1]\n n -= 1\n\n return s_out[::-1], t_out[::-1]\n\ndef hamming_distance(s, t):\n counter = 0\n for i in range(len(s)):\n if s[i] != t[i]:\n counter += 1\n return counter\n\ndistance, d_t = edit_distance(strings[0], strings[1])\nprint(distance)\nnew_s, new_t = make_best_align_strings(strings[0], strings[1], d_t)\nprint(new_s)\nprint(new_t)","repo_name":"dushabella/Introduction_to_Bioinformatics","sub_path":"Rosalind/ex22.py","file_name":"ex22.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"26504422585","text":"# -*- coding: utf-8 -*-\nimport sys\nimport imp\nimp.reload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\nimport findspark\nfindspark.init()\n\n'''\n1. Spark SQL 基本操作\n为employee.json创建DataFrame\n并通过Python语句完成如下10个SQL操作\n'''\n\nfrom pyspark import SparkConf\nfrom pyspark.sql import SparkSession\n\n# 创建SparkSession对象\nspark = SparkSession.builder.config(conf=SparkConf()).getOrCreate()\n# 创建一个DataFrame对象\ndf_data = spark.read.json(\"employee.json\")\n\nprint(\"1.查询所有数据:\")\ndf_data.select(\"*\").show() # 查询所有数据\n\nprint(\"2.查询所有数据,并去除重复的数据:\")\n# 逻辑上,年龄,姓名有可能重复,id不能重复\ndf_unique = df_data.drop_duplicates(subset=['id'])\ndf_unique.select(\"*\").show() # 查询所有数据,并去除重复的数据\n\nprint(\"3.查询所有数据,打印时去除id字段:\")\ndf_data.select('name', 'age').show() # 查询所有数据,打印时去除id字段(其实也可从所有中drop掉)\n\nprint(\"4.筛选出age>30的记录:\")\ndf_data.filter(df_data['age'] > 30).show() # 筛选出age>30的记录\n\nprint(\"5.将数据按age分组:\")\ndf_data.groupby('age').count().show() # 将数据按age分组\n\nprint(\"6.将数据按name升序排列\")\ndf_data.sort(df_data['name'].asc()).show() # 将数据按name升序排列\n\nprint(\"7.取出前3行数据\")\ndata = df_data.head(3) # 取出前3行数据\nfor i in data:\n print(i) # 遍历打印前3行数据\nprint(\"\\n\")\n\nprint(\"8.查询所有记录的name列,并为其取别名为username\")\nname = df_data.select('name') # 查询所有记录的name列\nname.withColumnRenamed('name', 'username').show() # 将name列取别名为username\n\nprint(\"9.查询年龄age的平均值\")\ndf_data.agg({'age': 'mean'}).show() # 查询年龄age的平均值\n\nprint(\"10.查询年龄age的最小值。\")\ndf_data.agg({'age': 'min'}).show() # 查询年龄age的最小值。\n","repo_name":"Andytonglove/py_spark","sub_path":"3-spark-SQL/3-SparkSQL.py","file_name":"3-SparkSQL.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"13697945988","text":"__author__ = 'mingyong'\nfrom django.conf.urls import *\nfrom models import Update\n\nurlpatterns = patterns('',\n url(r'^$', 'django.views.generic.list.ListView', {\n 'queryset': Update.objects.all()\n }),\n url(r'^updates-after/(?P\\d+)/$', 'liveBlog.views.updates_after'),\n)\n\n","repo_name":"mingyong0915/mysite","sub_path":"liveBlog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"125516121","text":"\"\"\"\nCreated on May 16, 2015\n\nGreedy solution to Knapsack problem\nSource: Introduction to Computation and Programming Using Python\n\"\"\"\nfrom item import build_items, weight_inverse, value, density\n\n\ndef greedy(items: list, max_weight: float, key_func: callable):\n assert type(items) == list and max_weight >= 0\n items_copy = sorted(items, key=key_func, reverse=True)\n result = []\n totalVal = 0.0\n total_weight = 0.0\n i = 0\n while total_weight < max_weight and i < len(items):\n if (total_weight + items_copy[i].getWeight()) <= max_weight:\n result.append(items_copy[i])\n total_weight += items_copy[i].getWeight()\n totalVal += items_copy[i].getValue()\n i += 1\n return (result, totalVal)\n\n\ndef test_greedy(items: list, constraint: float, get_key: callable):\n taken, val = greedy(items, constraint, get_key)\n print(\"Total value of items taken = %s\" % val)\n for item in taken:\n print(\"\\t % s\" % item)\n\n\ndef test_greedys(max_constraint: float = 20):\n items = build_items()\n print(\"Use greedy by value for knapsack of size %s\" % max_constraint)\n test_greedy(items, max_constraint, value)\n print(\"Use greedy by weight for knapsack of size %s\" % max_constraint)\n test_greedy(items, max_constraint, weight_inverse)\n print(\"Use greedy by density for knapsack of size %s\" % max_constraint)\n test_greedy(items, max_constraint, density)\n\n\nif __name__ == \"__main__\":\n test_greedys()\n","repo_name":"tekrei/DSAlgorithms","sub_path":"python/knapsack/greedy.py","file_name":"greedy.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"27"} +{"seq_id":"18474718867","text":"# -*- coding: utf-8 -*-\nimport copy\n\nimport KBEngine\n\nimport Const\nimport RoomType7Calculator\nfrom KBEDebug import *\nfrom RoomBase import *\nimport json\nimport time\n\n# 准备倒计时时间\n_timeReady = 5\n# 抢庄倒计时时间\n_timeBanker = 5\n# 分牌动画时间\n_create_card_time = 1\n# 押注倒计时时间\n_timeStake = 10\n# 闲家配牌倒计时时间\n_timeOtherMatch = 30\n# ��家配牌倒计时\n_timeMatchBanker = 20\n# 结算时间\n_timeSettlement = 5\n# 选庄家动画时间\nchoice_banker_time = 2\n# 骰子及发牌时间\n_timeDealCard = 8\n# 比牌动画时间\n_time_compare_cards = 8\n# 解散房间倒计时\ntime_disband = 30\n# 牌值 黑红梅方 a,b,c,d\ntotal_cards = ['a8', 'b8', 'c8', 'd8',\n 'a7', 'b7', 'c7', 'd7',\n 'a10', 'b10', 'c10', 'd10',\n 'a6', 'b6', 'c6', 'd6',\n 'a4', 'b4', 'c4', 'd4',\n 'b12', 'd12', 'b2', 'd2',\n 'a9', 'c9', 'a5', 'c5',\n 'a11', 'c11', '99', '100']\n# key 下注上限\nstake_table = {5000: [500, 1000, 2000, 5000], 50000: [5000, 10000, 20000, 50000],\n 300000: [20000, 40000, 80000, 300000]}\n\n# 总结算清理玩家倒计时\nsettlement_clear_players_time = 20\n\n\nclass RoomType7(RoomBase):\n _chapterInfos = {}\n is_manual_disband = False\n disband_from_creator = False\n total_settlement_ed = False\n settlement_count = 0\n started = False\n\n def __init__(self):\n RoomBase.__init__(self)\n self.emptyLocationIndex = list(range(0, 4))\n\n def newChapter(self, maxPlayerCount):\n \"\"\"\n 新牌局\n :param maxPlayerCount:\n :return:\n \"\"\"\n _chapter = {}\n # 房间玩家数量\n _chapter[\"playersCount\"] = 0\n # 最大玩家数量\n _chapter[\"maxPlayerCount\"] = maxPlayerCount\n # 当前轮数\n _chapter[\"currentRound\"] = 0\n # 当前房间状态 0 准备, 1 抢庄, 2 押注, 3 配牌, 4 结算\n _chapter[\"currentState\"] = 0\n # 游戏内玩家\n _chapter[\"playerInGame\"] = {}\n # 游戏外玩家\n _chapter[\"playerOutGame\"] = {}\n # 房间内所有玩家\n _chapter[\"playerInRoom\"] = {}\n # 庄家id\n _chapter[\"banker\"] = -1\n # 庄家位置\n _chapter[\"bankerIndex\"] = -1\n # 轮询是否可以开始牌局计时器\n _chapter[\"mainTimerId\"] = -1\n # 牌局开始倒计时计时器\n _chapter[\"chapterStartTimerId\"] = -1\n # 分牌倒计时\n _chapter[\"createCardTime\"] = -1\n # 选择庄家动画时间\n _chapter[\"choiceBankerTime\"] = -1\n # 发牌倒计时\n _chapter[\"dealCardTime\"] = -1\n # 抢庄计时器\n _chapter[\"bankerTimerId\"] = -1\n # 庄家配牌计时器\n _chapter[\"bankerMatchCardTime\"] = -1\n # 闲家配牌计时器\n _chapter[\"otherMatchCardTime\"] = -1\n # 结算计时器\n _chapter[\"settlementTime\"] = -1\n # 下注计时器\n _chapter[\"stakeTime\"] = -1\n # 抽奖\n _chapter[\"accountLottery\"] = -1\n # 比牌计时器\n _chapter[\"compareCardTime\"] = -1\n # 发牌动画计时器\n _chapter[\"dealCardAnimationTimerId\"] = -1\n # 当前计时时刻点\n _chapter[\"deadline\"] = -1\n # 下注总额\n _chapter[\"stake\"] = {1: 0, 2: 0, 3: 0}\n # 参与抢庄的玩家\n _chapter[\"grabBankerPlayers\"] = []\n # 牌堆牌值\n _chapter[\"cardsZ\"] = []\n _chapter[\"cardsK\"] = []\n _chapter[\"cardsT\"] = []\n _chapter[\"cardsG\"] = []\n # 配牌权值\n _chapter[\"Zweights\"] = []\n _chapter[\"Kweights\"] = []\n _chapter[\"Tweights\"] = []\n _chapter[\"Gweights\"] = []\n # 比牌结果\n _chapter[\"TResult\"] = []\n _chapter[\"KResult\"] = []\n _chapter[\"GResult\"] = []\n # 解散清除玩家倒计时\n _chapter[\"settlementClearPlayers\"] = -1\n # 需要配牌的闲家\n _chapter[\"canMatchCardsPlayers\"] = {}\n # 可以观看配牌的玩家\n _chapter[\"canWatchCardsPlayers\"] = {1: [], 2: [], 3: []}\n # 输赢情况\n _chapter[\"settlementArea\"] = {\"winArea\": [], \"loseArea\": [], \"drawArea\": []}\n self.chapters.append(_chapter)\n self.cn = len(self.chapters) - 1\n self.info['roomId']\n return _chapter\n\n def newPlayer(self, accountEntity):\n \"\"\"\n 新玩家\n :param accountEntity:\n :return:\n \"\"\"\n _chapter = self.chapters[self.cn]\n _player = {}\n # 实体\n _player[\"entity\"] = accountEntity\n # 抢庄 0:没有操作 -1:不抢 1:抢1倍 2:抢2倍 3:抢三倍\n _player[\"grabBanker\"] = -1\n # 玩家押注\n _player[\"stake\"] = {0: 0, 1: 0, 2: 0, 3: 0}\n # 座位\n _player[\"locationIndex\"] = -1\n # 本局金币变化\n _player[\"goldChange\"] = 0\n # 总金币变化\n _player[\"totalGoldChange\"] = 0\n # 准备\n _player[\"ready\"] = False\n # 在线状态\n _player[\"online\"] = True\n # 大赢家扣费\n _player[\"winnerBilling\"] = 0\n # 其余玩家扣费\n _player[\"otherBilling\"] = 0\n # 超额扣费\n _player[\"overBilling\"] = 0\n # 是否已经扣过AA支付的钻石\n _player['AARoomCardConsumed'] = False\n # 金币\n # 钻石场\n if self.info[\"roomType\"] == \"card\":\n _player[\"gold\"] = accountEntity.accountMutableInfo[\"gold\"]\n elif self.info[\"roomType\"] == \"gameCoin\":\n # 比赛分场修改使用比赛分为使用金币\n _player[\"gold\"] = accountEntity.accountMutableInfo[\"gold\"]\n elif self.info['roomType'] == 'normalGameCoin':\n _player[\"gold\"] = accountEntity.accountMutableInfo[\"gold\"]\n _player[\"agreeDisband\"] = False\n return _player\n\n def onEnter(self, accountEntityId):\n \"\"\"\n 有玩家进入,加入到观战玩家列表\n :param accountEntityId:\n :return:\n \"\"\"\n if not RoomBase.onEnter(self, accountEntityId):\n return\n DEBUG_MSG('[Room id %i]------>onEnter accountId %s' % (self.id, accountEntityId))\n _chapter = self.chapters[self.cn]\n _account = KBEngine.entities[accountEntityId]\n _account.viewing_hall = False\n # 存入账户实体列表,相同实体不能重复登入房间\n if _account.id not in self.accountEntities.keys():\n self.accountEntities[_account.id] = _account\n DEBUG_MSG(\"on_enter account_entities:%s\" % self.accountEntities)\n _player = self.newPlayer(_account)\n _currentState = _chapter[\"currentState\"]\n if accountEntityId not in _chapter[\"playerInRoom\"]:\n _chapter[\"playerInRoom\"][accountEntityId] = _player\n self.base.cellToBase({\"func\": \"playersCount\", \"count\": len(_chapter[\"playerInRoom\"])})\n else:\n DEBUG_MSG(\"onEnter-------> account %s on Enter room, but _player already exits\" % accountEntityId)\n return\n _chapter[\"playerOutGame\"][accountEntityId] = _player\n # if _account.info[\"isBot\"] == 1:\n # self.set_seat(accountEntityId, self.emptyLocationIndex[0])\n # self.player_ready(accountEntityId)\n # return\n self.retCurrentChapterState(accountEntityId)\n self.retRoomBaseInfo(accountEntityId)\n # self.retPlayerInRoomInfos()\n # # 如果比赛已经开始不自动坐下\n # if _chapter[\"currentState\"] != 0:\n # return\n # if self.info[\"roomType\"] == \"card\":\n # if _chapter[\"currentState\"] == 0:\n # self.set_seat(accountEntityId, self.emptyLocationIndex[0])\n # elif self.info[\"roomType\"] == \"gold\":\n # # 金币场自动坐下\n # if _chapter[\"currentState\"] == 0:\n # self.set_seat(accountEntityId, self.emptyLocationIndex[0])\n # 如果比赛一开始,观战状态,发送玩家信息\n # if _chapter[\"currentState\"] != 0:\n # self.retPlayerInRoomInfos()\n # 如果比赛已经开始不自动坐下\n if _chapter[\"currentState\"] == 0 and len(self.emptyLocationIndex) != 0:\n if len(_chapter[\"playerInGame\"]) < self.info[\"maxPlayersCount\"]:\n self.set_seat(accountEntityId, self.emptyLocationIndex[0])\n\n # 当玩家掉线\n def onPlayerClientDeath(self, accountEntity):\n DEBUG_MSG(\"RoomType8 onPlayerClientDeath accountId:%s\" % accountEntity)\n chapter = self.chapters[self.cn]\n\n for k, v in chapter[\"playerInGame\"].items():\n if v[\"entity\"] == accountEntity:\n v[\"online\"] = False\n # 总结算或者准备阶段掉线,自动踢出\n if chapter[\"currentState\"] == 0 or chapter[\"currentState\"] == 9:\n self.kick_out(k, player_online=False)\n break\n\n all_offline = True\n for k, v in chapter[\"playerInGame\"].items():\n if v[\"online\"]:\n all_offline = False\n break\n\n if all_offline:\n # self.total_settlement()\n # self.writeToDB()\n for k, v in copy.deepcopy(chapter[\"playerInGame\"]).items():\n self.kick_out(k, player_online=False)\n\n def onLeave(self, accountEntityId, leave_param=None):\n \"\"\"\n 离开房间\n :param accountEntityId:\n :return:\n \"\"\"\n DEBUG_MSG('[Room id %i]------>onLeave accountId %s' % (self.id, accountEntityId))\n _chapter = self.chapters[self.cn]\n _playerInRoom = _chapter[\"playerInRoom\"]\n _playerInGame = _chapter[\"playerInGame\"]\n _playerOutGame = _chapter[\"playerOutGame\"]\n _currentState = _chapter[\"currentState\"]\n if accountEntityId in _playerInGame:\n # if _currentState != 0 and _currentState != 7:\n # self.callClientFunction(accountEntityId, \"Notice\", [\"游戏正在游戏中,请等待游戏结束\"])\n # return\n _player = _playerInGame[accountEntityId]\n\n _playerInGame.pop(accountEntityId)\n _playerInRoom.pop(accountEntityId)\n _locationIndex = _player[\"locationIndex\"]\n if _locationIndex not in self.emptyLocationIndex:\n self.emptyLocationIndex.append(_locationIndex)\n self.emptyLocationIndex.sort()\n if leave_param is None:\n leave_param = {\"inviteRoomInfo\": None}\n leave_param.update({\"result\": 1})\n another_room = {}\n if 'JoinAnotherRoom' in leave_param:\n del leave_param['JoinAnotherRoom']\n another_room = leave_param['inviteRoomInfo']\n del leave_param['inviteRoomInfo']\n self.callClientFunction(accountEntityId, \"LeaveRoomResult\", leave_param)\n if another_room:\n self.callClientFunction(accountEntityId, \"JoinAnotherRoom\", another_room)\n _player[\"entity\"].destroySelf()\n self.retPlayerInRoomInfos()\n DEBUG_MSG('[Room]------>onLeave len(_playerInGame) %s' % (\n len(_playerInGame)))\n self.base.cellToBase({\"func\": \"playersCount\", \"count\": len(_chapter[\"playerInRoom\"])})\n self.base.cellToBase({\"func\": \"seatPlayersCount\", \"count\": len(_chapter[\"playerInGame\"])})\n\n if accountEntityId in _playerOutGame:\n _player = _playerOutGame[accountEntityId]\n\n _playerOutGame.pop(accountEntityId)\n _playerInRoom.pop(accountEntityId)\n if leave_param is None:\n leave_param = {\"inviteRoomInfo\": None}\n leave_param.update({\"result\": 1})\n another_room = {}\n if 'JoinAnotherRoom' in leave_param:\n del leave_param['JoinAnotherRoom']\n another_room = leave_param['inviteRoomInfo']\n del leave_param['inviteRoomInfo']\n self.callClientFunction(accountEntityId, \"LeaveRoomResult\", leave_param)\n if another_room:\n self.callClientFunction(accountEntityId, \"JoinAnotherRoom\", another_room)\n _player[\"entity\"].destroySelf()\n self.retPlayerInRoomInfos()\n DEBUG_MSG('[Room]------>onLeave len(_playerInGame) %s' % (\n len(_playerInGame)))\n self.base.cellToBase({\"func\": \"playersCount\", \"count\": len(_chapter[\"playerInRoom\"])})\n self.base.cellToBase({\"func\": \"seatPlayersCount\", \"count\": len(_chapter[\"playerInGame\"])})\n\n # 从实体列表中移除\n if accountEntityId in self.accountEntities.keys():\n self.accountEntities.pop(accountEntityId)\n DEBUG_MSG(\"onLeave account_entities:%s\" % self.accountEntities)\n self.autoDestroy()\n\n def kick_out(self, accountEntityId, isBot=False, player_online=True):\n \"\"\"\n 离开房间\n :param accountEntityId:\n :return:\n \"\"\"\n DEBUG_MSG('[Room id %i]------>onLeave accountId %s' % (self.id, accountEntityId))\n _chapter = self.chapters[self.cn]\n _playerInRoom = _chapter[\"playerInRoom\"]\n _playerInGame = _chapter[\"playerInGame\"]\n _playerOutGame = _chapter[\"playerOutGame\"]\n _currentState = _chapter[\"currentState\"]\n if accountEntityId in _playerInGame:\n _player = _playerInGame[accountEntityId]\n _playerInGame.pop(accountEntityId)\n _playerInRoom.pop(accountEntityId)\n _locationIndex = _player[\"locationIndex\"]\n if _locationIndex not in self.emptyLocationIndex:\n self.emptyLocationIndex.append(_locationIndex)\n self.emptyLocationIndex.sort()\n if player_online:\n self.callClientFunction(accountEntityId, \"LeaveRoomResult\", {\"result\": 1, \"inviteRoomInfo\": None})\n if player_online:\n _player[\"entity\"].destroySelf()\n self.retPlayerInRoomInfos()\n DEBUG_MSG('[Room]------>onLeave len(_playerInGame) %s' % (\n len(_playerInGame)))\n self.base.cellToBase({\"func\": \"playersCount\", \"count\": len(_chapter[\"playerInRoom\"])})\n self.base.cellToBase({\"func\": \"seatPlayersCount\", \"count\": len(_chapter[\"playerInGame\"])})\n\n if accountEntityId in _playerOutGame:\n _player = _playerOutGame[accountEntityId]\n _playerOutGame.pop(accountEntityId)\n _playerInRoom.pop(accountEntityId)\n self.callClientFunction(accountEntityId, \"LeaveRoomResult\", {\"result\": 1, \"inviteRoomInfo\": None})\n _player[\"entity\"].destroySelf()\n self.retPlayerInRoomInfos()\n self.base.cellToBase({\"func\": \"playersCount\", \"count\": len(_chapter[\"playerInRoom\"])})\n self.base.cellToBase({\"func\": \"seatPlayersCount\", \"count\": len(_chapter[\"playerInGame\"])})\n\n # 从实体列表中移除\n if accountEntityId in self.accountEntities.keys():\n self.accountEntities.pop(accountEntityId)\n DEBUG_MSG(\"onLeave account_entities:%s\" % self.accountEntities)\n self.autoDestroy()\n\n def changeChapterState(self, state):\n \"\"\"\n 改变游戏状态\n :param state:\n :return:\n \"\"\"\n _chapter = self.chapters[self.cn]\n _chapter[\"currentState\"] = state\n self.base.cellToBase({\"func\": \"changeRoomState\", \"roomState\": state})\n if state == 0:\n # 准备\n _args = {\"state\": state, \"Timer\": 0}\n self.callOtherClientsFunction(\"changeChapterState\", _args)\n # 机器人自动准备\n # self.bots_ready()\n # 自动准备\n if self.cn > 0:\n for k, v in _chapter[\"playerInGame\"].items():\n self.player_ready(k)\n _chapter[\"mainTimerId\"] = self.addTimer(1, 0.2, 0)\n elif state == 1:\n # 抢庄\n _args = {\"state\": state, \"Timer\": _timeBanker}\n self.callOtherClientsFunction(\"changeChapterState\", _args)\n elif state == 2:\n # 分牌\n _args = {\"state\": state, \"Timer\": _create_card_time}\n self.callOtherClientsFunction(\"changeChapterState\", _args)\n self.create_card()\n _chapter[\"createCardTime\"] = self.addTimer(_create_card_time, 0, 0)\n _chapter[\"deadline\"] = time.time() + _create_card_time\n elif state == 3:\n # 下注\n _args = {\"state\": state, \"Timer\": _timeStake}\n self.callOtherClientsFunction(\"changeChapterState\", _args)\n # 机器人下注\n # self.bots_set_stake()\n _chapter[\"stakeTime\"] = self.addTimer(_timeStake, 0, 0)\n _chapter[\"deadline\"] = time.time() + _timeStake\n elif state == 4:\n # 发牌\n _args = {\"state\": state, \"Timer\": _timeDealCard}\n self.callOtherClientsFunction(\"changeChapterState\", _args)\n dice1 = random.randint(1, 6)\n dice2 = random.randint(1, 6)\n _args = {\"cardsZ\": _chapter[\"cardsZ\"], \"cardsT\": _chapter[\"cardsT\"],\n \"cardsK\": _chapter[\"cardsK\"], \"cardsG\": _chapter[\"cardsG\"],\n \"diceValue1\": dice1, \"diceValue2\": dice2}\n self.callOtherClientsFunction(\"DealCards\", _args)\n _chapter[\"dealCardTime\"] = self.addTimer(_timeDealCard, 0, 0)\n _chapter[\"deadline\"] = time.time() + _timeDealCard\n elif state == 5:\n # 庄家配牌\n _args = {\"state\": state, \"Timer\": _timeMatchBanker}\n self.callOtherClientsFunction(\"changeChapterState\", _args)\n # 机器人配牌\n # self.bots_match_card()\n _chapter[\"bankerMatchCardTime\"] = self.addTimer(_timeMatchBanker, 0, 0)\n _chapter[\"deadline\"] = time.time() + _timeMatchBanker\n elif state == 6:\n # 闲家配牌\n _args = {\"state\": state, \"Timer\": _timeOtherMatch}\n self.callOtherClientsFunction(\"changeChapterState\", _args)\n player_match_info = self.get_match_cards_player_info()\n _chapter[\"canMatchCardsPlayers\"][1] = player_match_info[0]\n _chapter[\"canMatchCardsPlayers\"][2] = player_match_info[1]\n _chapter[\"canMatchCardsPlayers\"][3] = player_match_info[2]\n match_account = {\n 1: {\"matchPlayer\": player_match_info[0], \"watchPlayers\": _chapter[\"canWatchCardsPlayers\"][1]},\n 2: {\"matchPlayer\": player_match_info[1], \"watchPlayers\": _chapter[\"canWatchCardsPlayers\"][2]},\n 3: {\"matchPlayer\": player_match_info[2], \"watchPlayers\": _chapter[\"canWatchCardsPlayers\"][3]}}\n _args = {\"matchAccount\": match_account}\n self.callOtherClientsFunction(\"OtherPlayerMatchCard\", _args)\n # 机器人配牌\n # self.bots_match_card()\n _chapter[\"otherMatchCardTime\"] = self.addTimer(_timeOtherMatch, 0, 0)\n _chapter[\"deadline\"] = time.time() + _timeOtherMatch\n # 给没人下注的门自动配牌\n self.auto_match_card_in_un_stake()\n elif state == 7:\n # 比牌\n _args = {\"state\": state, \"Timer\": _time_compare_cards}\n self.callOtherClientsFunction(\"changeChapterState\", _args)\n self.compare_cards()\n _chapter[\"compareCardTime\"] = self.addTimer(_time_compare_cards, 0, 0)\n _chapter[\"deadline\"] = time.time() + _time_compare_cards\n elif state == 8:\n # 结算\n _args = {\"state\": state, \"Timer\": _timeSettlement}\n self.callOtherClientsFunction(\"changeChapterState\", _args)\n self.settlement()\n _chapter[\"settlementTime\"] = self.addTimer(_timeSettlement, 0, 0)\n _chapter[\"deadline\"] = time.time() + _timeSettlement\n elif state == 9:\n # 结算\n # 关闭所有计时器\n self.close_all_timer()\n _args = {\"state\": state, \"Timer\": 0}\n self.callOtherClientsFunction(\"changeChapterState\", _args)\n\n def retPlayerInRoomInfos(self, accountId=-1):\n \"\"\"\n 广播房间内所有玩家状态\n :return:\n \"\"\"\n _chapter = self.chapters[self.cn]\n _playerInGameNotEntity = {}\n _playerOutGameNotEntity = {}\n player_in_game_to_base = {}\n\n for k, v in _chapter[\"playerInGame\"].items():\n # 如果是非结算、总结算阶段金币为gold否则为gold+goldChange\n player_gold = 0\n if _chapter[\"currentState\"] < 8:\n player_gold = v[\"gold\"] + v[\"goldChange\"]\n else:\n player_gold = v[\"gold\"]\n _player = {\"gold\": player_gold, \"locationIndex\": int(v[\"locationIndex\"]),\n \"name\": v[\"entity\"].info[\"name\"], \"stake\": v[\"stake\"],\n \"userId\": v[\"entity\"].info[\"userId\"],\n \"ip\": v[\"entity\"].info[\"ip\"],\n 'totalGoldChange': v['totalGoldChange'],\n \"headImageUrl\": v[\"entity\"].info[\"headImageUrl\"], \"ready\": v[\"ready\"]}\n _playerInGameNotEntity[int(k)] = _player\n player_in_game_to_base[int(v[\"locationIndex\"])] = {\"name\": v[\"entity\"].info[\"name\"],\n \"databaseId\": v[\"entity\"].info[\"dataBaseId\"],\n \"headImageUrl\": v[\"entity\"].info[\"headImageUrl\"]}\n for k, v in _chapter[\"playerOutGame\"].items():\n _player = {\"gold\": v[\"gold\"], \"locationIndex\": int(v[\"locationIndex\"]),\n \"name\": v[\"entity\"].info[\"name\"], \"stake\": v[\"stake\"],\n \"userId\": v[\"entity\"].info[\"userId\"],\n \"ip\": v[\"entity\"].info[\"ip\"],\n 'totalGoldChange': v['totalGoldChange'],\n \"headImageUrl\": v[\"entity\"].info[\"headImageUrl\"], \"ready\": v[\"ready\"]}\n _playerOutGameNotEntity[int(k)] = _player\n _args = {\"playerInGame\": _playerInGameNotEntity, \"playerOutGame\": _playerOutGameNotEntity}\n DEBUG_MSG('[Room id %i]------>retPlayerInRoomInfos %s' % (self.id, _args))\n if accountId == -1:\n self.callOtherClientsFunction(\"RetPlayerInRoomInfos\", _args)\n else:\n self.callClientFunction(accountId, \"RetPlayerInRoomInfos\", _args)\n\n tea_house_id = -1\n if self.is_tea_house_room:\n tea_house_id = self.info['teaHouseId']\n self.base.cellToBase({\"func\": \"refreshPlayerInGame\", \"playerInGame\": player_in_game_to_base,\n \"teaHouseId\": tea_house_id})\n\n def get_seat_players(self):\n chapter = self.get_current_chapter()\n _players = chapter[\"playerInGame\"]\n return _players\n\n def get_seat_player_by_entity_id(self, entityId):\n \"\"\"\n 通过实体id获取坐下玩家\n :param entityId:\n :return:\n \"\"\"\n _chapter = self.get_current_chapter()\n for k, v in _chapter['playerInGame'].items():\n if v['entity'].id == entityId:\n return v\n\n def set_seat(self, accountId, locationIndex):\n \"\"\"\n 设置座位\n :param accountId: 设置座位玩家\n :param locationIndex: 座位号0-8\n :return:\n \"\"\"\n DEBUG_MSG('[Room id %i]------>setSeat accountId %s, locationIndex %s ' % (self.id, accountId, locationIndex))\n _chapter = self.chapters[self.cn]\n if accountId not in _chapter[\"playerOutGame\"]:\n return\n for player in _chapter[\"playerInGame\"].values():\n if player[\"locationIndex\"] == locationIndex:\n return\n _chapter[\"playerInGame\"][accountId] = _chapter[\"playerOutGame\"].pop(accountId)\n _chapter[\"playerInGame\"][accountId][\"locationIndex\"] = locationIndex\n if self.cn < 1:\n if len(_chapter[\"playerInGame\"]) == 1:\n _chapter[\"firstMan\"] = accountId\n\n self.emptyLocationIndex.remove(locationIndex)\n self.base.cellToBase({\"func\": \"seatPlayersCount\", \"count\": len(_chapter[\"playerInGame\"])})\n self.retPlayerInRoomInfos()\n # 每人满时,创建新的房间(onRoomEnd为true时插入在当前房间后面)\n if len(_chapter['playerInGame']) == self.info['maxPlayersCount']:\n self.base.cellToBase({\"func\": \"autoCreateRoom\", \"roomInfo\": self.info})\n\n def stand_up(self, accountId, locationIndex):\n \"\"\"\n 站起\n :param accountId: 站起玩家\n :param locationIndex: 座位\n :return:\n \"\"\"\n DEBUG_MSG('[Room id %i]------>standUp accountId %s, locationIndex %s ' % (self.id, accountId, locationIndex))\n _chapter = self.chapters[self.cn]\n if _chapter[\"currentState\"] != 0:\n return\n if accountId not in _chapter[\"playerInGame\"]:\n return\n _chapter[\"playerOutGame\"][accountId] = _chapter[\"playerInGame\"].pop(accountId)\n _chapter[\"playerOutGame\"][accountId][\"locationIndex\"] = -1\n self.emptyLocationIndex.append(locationIndex)\n self.emptyLocationIndex.sort()\n self.retPlayerInRoomInfos()\n\n def chapter_start(self):\n \"\"\"\n 牌局开始\n :return:\n \"\"\"\n DEBUG_MSG('[Room id %i]------>chapterStart ' % self.id)\n self.started = True\n self.info[\"started\"] = True\n _chapter = self.chapters[self.cn]\n _playerInGame = _chapter[\"playerInGame\"]\n # 金币场扣除房费\n if self.is_gold_session_room():\n for k, v in _playerInGame.items():\n v['gold'] -= self.info['roomRate']\n self.set_base_player_gold(k)\n if len(self.get_ready_player()) < 2:\n _args = {\"startGameResult\": False, \"error\": \"准备人数不足\"}\n self.callClientFunction(self.info[\"creatorAccountId\"], \"StartGame\", _args)\n return\n # 通知 base 游戏开始\n if self.cn == 0:\n # 将坐下玩家的DB_ID传入前台\n player_in_game_db_id = []\n for k, v in self.chapters[self.cn][\"playerInGame\"].items():\n player_in_game_db_id.append(v[\"entity\"].info[\"dataBaseId\"])\n self.base.cellToBase(\n {\"func\": \"roomStart\", \"roomInfo\": self.info, \"playerInGameDBID\": player_in_game_db_id})\n # 房间开始,并且人未满时创建新的房间(onRoomEnd为true时插入在当前房间后面)\n if len(_chapter['playerInGame']) < self.info['maxPlayersCount']:\n self.base.cellToBase({\"func\": \"autoCreateRoom\", \"roomInfo\": self.info})\n # _args = {\"startGameResult\": True, \"error\": \"\"}\n # self.callClientFunction(self.info[\"creatorAccountId\"], \"StartGame\", _args)\n self.changeChapterState(1)\n self.set_current_round(self.cn + 1)\n self.banker_type_switch()\n self.base.cellToBase({\"func\": \"newChapter\", \"count\": self.cn + 1})\n\n def player_ready(self, account_id):\n DEBUG_MSG(\"player ready account id:%s\" % account_id)\n chapter = self.chapters[self.cn]\n _player = chapter['playerInGame'][account_id]\n if chapter['currentState'] != 0:\n self.callClientFunction(account_id, 'Notice', ['游戏不在准备阶段,无法准备'])\n return\n if self.is_gold_session_room() and _player['gold'] < self.info['roomRate']:\n return\n chapter[\"playerInGame\"][account_id][\"ready\"] = True\n _args = {\"accountId\": account_id, \"ready\": True}\n self.callOtherClientsFunction(\"Ready\", _args)\n\n def bots_ready(self):\n for k, v in self.get_bots().items():\n if not v[\"ready\"]:\n v[\"ready\"] = True\n _args = {\"accountId\": k, \"ready\": True}\n self.callOtherClientsFunction(\"Ready\", _args)\n\n def get_ready_player(self):\n chapter = self.chapters[self.cn]\n ready_players = []\n for k, v in chapter[\"playerInGame\"].items():\n if v[\"ready\"]:\n ready_players.append(k)\n return ready_players\n\n # 自动给没有下注的门配牌\n def auto_match_card_in_un_stake(self):\n chapter = self.chapters[self.cn]\n # 闲家自动配牌\n # k:门的 index 。v:该门可以配牌的玩家,-1 为没有玩家\n # 遍历可以配牌的门的玩家列表,如果该门没有配并且没有真实玩家可以配牌,系统自动配牌\n for k, v in copy.deepcopy(chapter[\"canMatchCardsPlayers\"]).items():\n cards1, cards2 = [], []\n if k == 3 and v == -1:\n cards1, cards2 = chapter[\"cardsG\"][:2], chapter[\"cardsG\"][2:]\n DEBUG_MSG('[Room]cards1 %s,cards2 %s' % (cards1, cards2))\n elif k == 2 and v == -1:\n cards1, cards2 = chapter[\"cardsT\"][:2], chapter[\"cardsT\"][2:]\n DEBUG_MSG('[Room]cards1 %s,cards2 %s' % (cards1, cards2))\n elif k == 1 and v == -1:\n cards1, cards2 = chapter[\"cardsK\"][:2], chapter[\"cardsK\"][2:]\n DEBUG_MSG('[Room]cards1 %s,cards2 %s' % (cards1, cards2))\n else:\n continue\n self.match_card(v, k, cards1, cards2)\n\n def dealCards(self):\n \"\"\"\n 发牌\n :return:\n \"\"\"\n\n pass\n\n # 抢庄模式\n def banker_type_switch(self):\n \"\"\"\n 设置庄家\n :return:\n \"\"\"\n chapter = self.chapters[self.cn]\n # playerInGame = chapter[\"playerInGame\"]\n # if self.info[\"roomType\"] == \"card\":\n grab_banker_type = self.info[\"grabBankerType\"]\n # 抢庄\n if grab_banker_type == 1:\n # 抢庄倒计时\n args = {\"Timer\": _timeBanker}\n self.callOtherClientsFunction(\"StartGrab\", args)\n chapter[\"bankerTimerId\"] = self.addTimer(_timeBanker, 0, 0)\n chapter[\"deadline\"] = time.time() + _timeBanker\n # 轮庄\n elif grab_banker_type == 2:\n if len(self.chapters) <= 1:\n # 第一个进入的人是第一局的庄家\n first_man = chapter[\"firstMan\"]\n if first_man not in chapter[\"playerInGame\"].keys():\n # 如果第一个人不在房间里,locationIndex 最小的为庄家\n min_index = sys.maxsize\n for k, v in chapter[\"playerInGame\"].items():\n if v[\"locationIndex\"] < min_index:\n min_index = v[\"locationIndex\"]\n for k, v in chapter[\"playerInGame\"].items():\n if v[\"locationIndex\"] == min_index:\n first_man = k\n break\n chapter[\"bankerIndex\"] = self.get_location_with_account_id(first_man)\n self.send_banker_result(first_man)\n self.changeChapterState(2)\n else:\n pre_chapter = self.chapters[self.cn - 1]\n location = pre_chapter[\"bankerIndex\"]\n chapter[\"bankerIndex\"] = self.get_next_location_can_banker(location)\n self.send_banker_result(self.get_account_id_with_location_index(chapter[\"bankerIndex\"]))\n self.changeChapterState(2)\n # elif self.info[\"roomType\"] == \"gold\":\n # if len(self.chapters) <= 1:\n # bot = self.get_a_bots()\n # self.send_banker_result(bot)\n # else:\n # # 抢庄倒计时\n # args = {\"Timer\": _timeBanker}\n # self.callOtherClientsFunction(\"StartGrab\", args)\n # chapter[\"bankerTimerId\"] = self.addTimer(_timeBanker, 0, 0)\n # chapter[\"deadline\"] = time.time() + _timeBanker\n # # 机器人自动抢庄\n # self.bots_grab_banker()\n # 抢庄倒计时\n # args = {\"Timer\": _timeBanker}\n # self.callOtherClientsFunction(\"StartGrab\", args)\n # chapter[\"bankerTimerId\"] = self.addTimer(_timeBanker, 0, 0)\n # chapter[\"deadline\"] = time.time() + _timeBanker\n # 机器人自动抢庄\n # self.bots_grab_banker()\n\n # 发送最终庄家结果\n def send_banker_result(self, banker_account_id):\n chapter = self.chapters[self.cn]\n # 如果已经设置过庄家不再发送消息,防止多次设置\n if chapter[\"banker\"] != -1 and chapter[\"bankerIndex\"] != -1:\n return\n chapter[\"banker\"] = banker_account_id\n chapter[\"bankerIndex\"] = self.get_location_with_account_id(banker_account_id)\n args = {\"banker\": banker_account_id}\n self.callOtherClientsFunction(\"SetBanker\", args)\n # self.changeChapterState(2)\n\n # 玩家抢庄请求处理\n def grab_banker(self, accountId, result):\n \"\"\"\n 抢庄\n :param accountId:\n :return:\n \"\"\"\n DEBUG_MSG('[Room id %i]------>grabBanker, accountId %s' % (self.id, accountId))\n _chapter = self.chapters[self.cn]\n if _chapter['currentState'] != 1:\n self.callClientFunction(accountId, 'Notice', ['游戏不在抢庄阶段,无法抢庄'])\n return\n current_state = _chapter[\"currentState\"]\n grab_banker_type = self.info[\"grabBankerType\"]\n player = _chapter[\"playerInGame\"][accountId]\n player[\"grabBanker\"] = result\n args = {}\n # 抢庄时金币必须大于最小下注的十倍\n if self.have_gold_limit():\n if result == 1 and grab_banker_type == 1 and player[\"gold\"] >= self.info[\"betLimit\"] * 10:\n args = {\"result\": 1}\n # 收集所有抢庄玩家\n _chapter[\"grabBankerPlayers\"].append(accountId)\n else:\n args = {\"result\": 0}\n else:\n if result == 1 and grab_banker_type == 1:\n args = {\"result\": 1}\n # 收集所有抢庄玩家\n _chapter[\"grabBankerPlayers\"].append(accountId)\n else:\n args = {\"result\": 0}\n args[\"accountId\"] = accountId\n self.callOtherClientsFunction(\"GrabBankerResult\", args)\n\n # 未抢庄玩家\n unGrabBankerPlayers = []\n for k, v in _chapter[\"playerInGame\"].items():\n if v[\"grabBanker\"] == -1:\n unGrabBankerPlayers.append(k)\n if len(unGrabBankerPlayers) == 0:\n _chapter[\"bankerTimerId\"] = -1\n self.delTimer(_chapter[\"bankerTimerId\"])\n grab_players = _chapter[\"grabBankerPlayers\"]\n # 如果没有人参与抢庄,随机一个参与比赛的玩家\n if len(grab_players) == 0:\n banker = random.choice(list(_chapter[\"playerInGame\"].keys()))\n # 如果有人抢庄,随机一个参与抢庄的玩家\n else:\n banker = random.choice(grab_players)\n self.send_banker_result(banker)\n _chapter[\"choiceBankerTime\"] = self.addTimer(choice_banker_time, 0, 0)\n _chapter[\"deadline\"] = time.time() + choice_banker_time\n\n # 通过位置获取Id\n def get_account_id_with_location_index(self, location_index):\n \"\"\"\n 通过位置找到 Account_ID\n :param location_index:\n :return:\n \"\"\"\n chapter = self.chapters[self.cn]\n player_in_game = chapter[\"playerInGame\"]\n for k, v in player_in_game.items():\n if v[\"locationIndex\"] == location_index:\n return k\n\n # 通过 id 获取位置\n def get_location_with_account_id(self, account_id):\n chapter = self.chapters[self.cn]\n return chapter[\"playerInGame\"][account_id][\"locationIndex\"]\n\n # 找到一个机器人\n def get_a_bots(self):\n for k, v in self.chapters[self.cn][\"playerInGame\"].items():\n if v[\"entity\"].info[\"isBot\"] == 1:\n return k\n return None\n\n # 获得下个位置\n\n def get_next_location_index(self, location_index):\n current = location_index\n return (current + 1) % self.info[\"maxPlayersCount\"]\n\n # 获取所有闲家\n def get_other_players(self):\n chapter = self.chapters[self.cn]\n other_players = {}\n for k, v in chapter[\"playerInGame\"].items():\n if k != chapter[\"banker\"]:\n other_players[k] = v\n return other_players\n\n # 获取下个有玩家的位置\n def get_next_location_can_banker(self, start_location):\n chapter = self.chapters[self.cn]\n for i in range(0, self.info[\"maxPlayersCount\"]):\n # 获取下个位置\n next = self.get_next_location_index(start_location)\n for k, v in chapter[\"playerInGame\"].items():\n # 如果是比赛分场,有玩家的位置等于下个位置并且该玩家可以当庄家\n if self.have_gold_limit():\n if v[\"locationIndex\"] == next and v[\"gold\"] >= self.info[\"betLimit\"] * 10:\n return next\n else:\n if v[\"locationIndex\"] == next:\n return next\n start_location = next\n return -1\n\n def set_stake(self, accountId, stake, stakeIndex, isBot=False):\n \"\"\"\n 押注\n :param accountId:\n :param stake:\n :return:\n \"\"\"\n DEBUG_MSG('[Room id %i]------>setStake, accountId %s, stake %s ,stakeIndex %s' % (\n self.id, accountId, stake, stakeIndex))\n _chapter = self.chapters[self.cn]\n if _chapter['currentState'] != 3:\n self.callClientFunction(accountId, 'Notice', ['游戏不在下注阶段,无法下注'])\n return\n _playerInGame = _chapter[\"playerInGame\"]\n chapter_total_stake = _chapter[\"stake\"][1] + _chapter[\"stake\"][2] + _chapter[\"stake\"][3]\n\n # 庄家当前货币\n banker_gold = _playerInGame[_chapter[\"banker\"]][\"gold\"] + _playerInGame[_chapter[\"banker\"]][\"goldChange\"]\n # 总下注不能超过庄家总金币\n if stake + chapter_total_stake > banker_gold:\n self.callClientFunction(accountId, \"Notice\", [\"当前总注超过庄家%s,无法下注\" % self.gold_name])\n return\n\n if stake > _playerInGame[accountId][\"gold\"] + _playerInGame[accountId][\"goldChange\"] and not isBot:\n self.callClientFunction(accountId, \"Notice\", [\"%s不足\" % self.gold_name])\n return\n\n _playerInGame[accountId][\"stake\"][int(stakeIndex)] += stake\n _chapter[\"stake\"][int(stakeIndex)] += stake\n # 下注就可以观看配牌\n if accountId not in _chapter[\"canWatchCardsPlayers\"][int(stakeIndex)]:\n _chapter[\"canWatchCardsPlayers\"][int(stakeIndex)].append(accountId)\n _playerInGame[accountId][\"goldChange\"] -= stake\n _args = {\"accountId\": accountId, \"stake\": stake, \"stakeIndex\": int(stakeIndex),\n \"gold\": _playerInGame[accountId][\"gold\"] + _playerInGame[accountId][\"goldChange\"]}\n self.callOtherClientsFunction(\"SetStake\", _args)\n\n def write_chapter_info_to_db(self):\n \"\"\"\n 牌局信息写入库\n :return:\n \"\"\"\n # 至少打一局才写库\n if self.settlement_count < 1:\n return\n _chapter = self.chapters[self.cn]\n _playerInGame = _chapter[\"playerInGame\"]\n _playerData = {}\n _playerInfo = []\n _history_record = {}\n replay_data = {\"chapterInfo\": {}}\n replay_all_chapter_data = {}\n # 如果最后一局未到结算阶段,不计入战绩\n chapter_record_max_count = self.cn + 1 if self.settlement_count == self.cn + 1 else self.cn\n for c in range(0, chapter_record_max_count):\n chapter_info = self.chapters[c]\n chapter_data = []\n # 这一小局除玩家信息外的信息\n replay_single_chapter_data = {\"playerInfo\": {},\n \"cardsZ\": chapter_info[\"cardsZ\"],\n \"cardsT\": chapter_info[\"cardsT\"],\n \"cardsK\": chapter_info[\"cardsK\"],\n \"cardsG\": chapter_info[\"cardsG\"],\n \"TResult\": chapter_info[\"TResult\"],\n \"GResult\": chapter_info[\"GResult\"],\n \"KResult\": chapter_info[\"KResult\"],\n \"cardsTInfo1\": chapter_info[\"Tweights\"][0],\n \"cardsTInfo2\": chapter_info[\"Tweights\"][1],\n \"cardsKInfo1\": chapter_info[\"Kweights\"][0],\n \"cardsKInfo2\": chapter_info[\"Kweights\"][1],\n \"cardsGInfo1\": chapter_info[\"Gweights\"][0],\n \"cardsGInfo2\": chapter_info[\"Gweights\"][1],\n \"cardsZInfo1\": chapter_info[\"Zweights\"][0],\n \"cardsZInfo2\": chapter_info[\"Zweights\"][1],\n \"banker\": chapter_info[\"banker\"]}\n for k, v in chapter_info[\"playerInGame\"].items():\n # 这一小局玩家的输赢和基本信息。作为战绩存储\n player_data = {\"goldChange\": v[\"goldChange\"], \"name\":\n v[\"entity\"].info[\"name\"]}\n\n # 这一小局回放用的玩家信息。回放使用\n replay_player_data = {\"accountId\": k, \"accountName\": v[\"entity\"].info[\"name\"],\n \"stake\": v[\"stake\"],\n \"dataBaseId\": v[\"entity\"].info[\"dataBaseId\"],\n \"locationIndex\": int(v[\"locationIndex\"]),\n \"gold\": v[\"gold\"],\n \"goldChange\": v[\"goldChange\"], \"userId\": v[\"entity\"].info[\"userId\"]}\n #\n replay_single_chapter_data[\"playerInfo\"][k] = replay_player_data\n # 存储这一小局所有玩家战绩\n chapter_data.append(player_data)\n # 存储所有小局回放\n replay_all_chapter_data[c] = replay_single_chapter_data\n # 存储所有小局\n _history_record[c] = chapter_data\n replay_data[\"chapterInfo\"] = replay_all_chapter_data\n # 记录战绩的玩家\n record_players = []\n for k, v in _playerInGame.items():\n _playerData = {\"accountId\": k, \"accountName\": v[\"entity\"].info[\"name\"],\n \"winnerBilling\": v[\"winnerBilling\"], \"overBilling\": v[\"overBilling\"],\n \"otherBilling\": v[\"otherBilling\"],\n \"totalGoldChange\": v[\"totalGoldChange\"], \"userId\": v[\"entity\"].info[\"userId\"]}\n _playerInfo.append(_playerData)\n record_players.append(v[\"entity\"].info[\"userId\"])\n _args = {\"createRoomTime\": int(time.time()), \"roomId\": self.info[\"roomId\"],\n \"maxChapterCount\": self.info[\"maxChapterCount\"],\n \"playerInfo\": _playerInfo, \"historyRecord\": _history_record}\n self._chapterInfos = _args\n self.base.cellToBase({\"func\": \"writeChapterInfo\", \"chapterInfos\": self._chapterInfos})\n # 回放存储玩家信息\n self.chapter_replay = replay_data\n self.base.cellToBase({\"func\": \"writeChapterReplay\", \"chapterReplay\": self.chapter_replay})\n DEBUG_MSG('[Room id %i]------>writeChapterInfoToDB, _chapterInfos %s ' % (self.id, self._chapterInfos))\n if self.is_tea_house_room:\n # 通知base的朋友圈记录该房间\n self.base.cellToBase(\n {\"func\": \"writeTeaHouseRoom\", \"teaHouseId\": self.info[\"teaHouseId\"], \"type\": self.info[\"type\"],\n 'recordPlayers': record_players})\n\n def set_current_round(self, currentRound):\n \"\"\"\n 设置当前轮数\n :param currentRound:\n :return:\n \"\"\"\n DEBUG_MSG('[Room id %i]------>setCurrentRound currentRound %s' % (self.id, currentRound))\n _chapter = self.chapters[self.cn]\n _chapter[\"currentRound\"] = currentRound\n _args = {\"currentRound\": currentRound}\n self.callOtherClientsFunction(\"RetCurrentRound\", _args)\n\n def playerOperation(self, account_entity_id, jsonData):\n \"\"\"\n 玩家操作\n :param account_entity_id:\n :param jsonData:\n :return:\n \"\"\"\n DEBUG_MSG(\n '[Room id %i]------>playerOperation accountId %s ,jsonData %s' % (self.id, account_entity_id, jsonData))\n _py_dic = json.loads(jsonData)\n _func = _py_dic[\"func\"]\n _data = _py_dic[\"args\"]\n _playerInGame = self.chapters[self.cn][\"playerInGame\"]\n if _func == \"GrabBanker\":\n self.grab_banker(account_entity_id, _data[\"result\"])\n elif _func == \"Ready\":\n self.player_ready(account_entity_id)\n elif _func == \"SetStake\":\n self.set_stake(account_entity_id, _data[\"stake\"], _data[\"stakeIndex\"])\n elif _func == \"CheckCardsType\":\n self.check_cards_type(account_entity_id, _data[\"cards\"])\n elif _func == \"MatchCards\":\n self.match_card(account_entity_id, _data[\"matchIndex\"], _data[\"cards1\"], _data[\"cards2\"])\n elif _func == \"LeaveRoom\":\n self.onLeave(account_entity_id, _data)\n elif _func == \"GetCardsType\":\n self.get_cards_type(account_entity_id, _data[\"cards\"])\n elif _func == \"SetSeat\":\n self.set_seat(account_entity_id, _data[\"locationIndex\"])\n elif _func == \"StandUp\":\n self.stand_up(account_entity_id, _data[\"locationIndex\"])\n elif _func == \"Reconnect\":\n self.reconnect(account_entity_id)\n elif _func == \"EmotionChat\":\n self.emotion_chat(account_entity_id, _data[\"index\"], _data[\"type\"])\n elif _func == \"VoiceChat\":\n self.voiceChat(account_entity_id, _data[\"url\"])\n elif _func == \"DisbandRoom\":\n self.disband_room_broadcast(account_entity_id)\n elif _func == \"DisbandRoomOperation\":\n self.response_disband(account_entity_id, _data[\"result\"])\n elif _func == \"TipCardsType\":\n self.tip_cards_type(account_entity_id, _data[\"cards\"])\n elif _func == 'ShareToWX':\n self.share_to_wx(account_entity_id)\n elif _func == 'FreeBlessCount':\n self.free_bless_count(account_entity_id)\n elif _func == \"Bless\":\n self.bless(account_entity_id, _data[\"type\"])\n\n def share_to_wx(self, account_id):\n chapter = self.chapters[self.cn]\n if self.info['roomType'] == 'card':\n title = '纸牌牌九房间号:' + str(self.info[\"roomId\"])\n elif self.info['teaHouseId'] != -1:\n title = '纸牌牌九房间' + ',冠名赛id:' + str(self.info['teaHouseId'])\n else:\n title = '纸牌牌九房间'\n max_chapter = '局数:' + str(self.info['maxChapterCount'])\n min_stake = '最小下注' + str(self.info['betLimit'])\n grab_banker_type = ''\n if self.info['grabBankerType'] == 1:\n grab_banker_type = '抢庄'\n elif self.info['grabBankerType'] == 2:\n grab_banker_type = '轮庄'\n player_count = len(chapter['playerInGame'])\n players = str(player_count) + '缺' + str(self.info['maxPlayersCount'] - player_count)\n con = str('%s %s %s %s' % (players, max_chapter, min_stake, grab_banker_type))\n self.callClientFunction(account_id, 'ShareToWX', {'title': title, 'content': con})\n\n def voiceChat(self, accountId, url):\n \"\"\"\n 语音聊天\n :param accountId:\n :param url:\n :return:\n \"\"\"\n # chapter = self.chapters[self.cn]\n # # 获取当前玩家可以语音的区域\n # can_voice_area = self.get_voice_area(accountId)\n # if len(can_voice_area) != 1:\n # return\n # else:\n # for k, v in chapter[\"playerInGame\"].items():\n # # 如果该玩家下了多门不接收语音\n # if len(self.get_voice_area(k)) != 1:\n # continue\n # # 如果是机器人不接收语音\n # if v[\"entity\"].info[\"isBot\"] == 1:\n # continue\n # if self.get_voice_area(k)[0] == can_voice_area[0]:\n # _args = {\"accountId\": accountId, \"url\": url}\n # self.callClientFunction(k, \"VoiceChat\", _args)\n self.callOtherClientsFunction(\"VoiceChat\", {\"accountId\": accountId, \"url\": url})\n\n def get_voice_area(self, accountId):\n chapter = self.chapters[self.cn]\n\n can_receive_area = []\n if accountId in chapter[\"canWatchCardsPlayers\"][1]:\n can_receive_area.append(1)\n if accountId in chapter[\"canWatchCardsPlayers\"][2]:\n can_receive_area.append(2)\n if accountId in chapter[\"canWatchCardsPlayers\"][3]:\n can_receive_area.append(3)\n # 如果多门下注,不能发送语音\n if len(can_receive_area) != 1:\n return []\n return can_receive_area\n\n def emotion_chat(self, account_id, index, emotion_type):\n \"\"\"\n 表情聊天\n :param emotion_type:\n :param account_id:\n :param index:\n :return:\n \"\"\"\n _args = {\"accountId\": account_id, \"index\": index, \"type\": emotion_type}\n self.callOtherClientsFunction(\"EmotionChat\", _args)\n\n def reconnect(self, accountId):\n \"\"\"\n 请求重连\n :param accountId: 重连玩家\n :return:\n \"\"\"\n DEBUG_MSG('[Room id %i]------>reconnect %s' % (self.id, accountId))\n self.retRoomBaseInfo(accountId)\n self.retPlayerInRoomInfos(accountId)\n self.retChapterInfo(accountId)\n\n def getPlayerInGameCount(self):\n \"\"\"\n 返回游戏内玩家数量\n :return:\n \"\"\"\n _chapter = self.chapters[self.cn]\n _playerInGame = _chapter[\"playerInGame\"]\n return len(_playerInGame)\n\n def onTimer(self, timerHandle, userData):\n \"\"\"\n 计时器回调\n :param timerHandle:\n :param userData:\n :return:\n \"\"\"\n RoomBase.onTimer(self, timerHandle, userData)\n\n chapter = self.chapters[self.cn]\n playerInGame = chapter[\"playerInGame\"]\n if timerHandle == chapter[\"bankerTimerId\"]:\n # 抢庄计时器\n DEBUG_MSG('[Room id %s]------>onTimer bankerTimerId %s' % (self.id, timerHandle))\n chapter[\"bankerTimerId\"] = -1\n self.delTimer(timerHandle)\n grab_players = chapter[\"grabBankerPlayers\"]\n banker = -1\n # 如果没有人参与抢庄,随机一个参与比赛的玩家\n if len(grab_players) == 0:\n banker = random.choice(list(playerInGame.keys()))\n # 如果有人抢庄,随机一个参与抢庄的玩家\n else:\n banker = random.choice(grab_players)\n self.send_banker_result(banker)\n chapter[\"choiceBankerTime\"] = self.addTimer(choice_banker_time, 0, 0)\n chapter[\"deadline\"] = time.time() + choice_banker_time\n elif timerHandle == chapter[\"mainTimerId\"]:\n all_ready = True\n for k, v in chapter[\"playerInGame\"].items():\n if not v[\"ready\"]:\n all_ready = False\n break\n if all_ready and len(chapter[\"playerInGame\"]) >= 2:\n self.delTimer(timerHandle)\n chapter[\"mainTimerId\"] = -1\n self.chapter_start()\n # elif timerHandle == chapter[\"accountLottery\"]:\n # DEBUG_MSG('[Room id %s]------>onTimer accountLottery %s' % (self.id, timerHandle))\n # chapter[\"accountLottery\"] = -1\n # self.Lottery()\n elif timerHandle == chapter[\"choiceBankerTime\"]:\n # 选择庄家动画时间\n DEBUG_MSG('[Room id %s]------>onTimer choiceBankerTime %s' % (self.id, timerHandle))\n chapter[\"choiceBankerTime\"] = -1\n self.delTimer(chapter[\"choiceBankerTime\"])\n self.changeChapterState(2)\n elif timerHandle == chapter[\"createCardTime\"]:\n DEBUG_MSG('[Room id %s]------>onTimer createCardTime %s' % (self.id, timerHandle))\n chapter[\"createCardTime\"] = -1\n self.delTimer(timerHandle)\n self.changeChapterState(3)\n elif timerHandle == chapter[\"stakeTime\"]:\n # 押注计时器\n DEBUG_MSG('[Room id %s]------>onTimer stakeTime %s' % (self.id, timerHandle))\n chapter[\"stakeTime\"] = -1\n self.delTimer(timerHandle)\n self.changeChapterState(4)\n elif timerHandle == chapter[\"dealCardTime\"]:\n # 发牌动画计时器\n DEBUG_MSG('[Room id %s]------>onTimer dealCardTime %s' % (self.id, timerHandle))\n self.delTimer(timerHandle)\n chapter[\"dealCardTime\"] = -1\n self.changeChapterState(5)\n elif timerHandle == chapter[\"bankerMatchCardTime\"]:\n # 庄家配牌计时器\n DEBUG_MSG('[Room id %s]------>onTimer bankerMatchCardTime %s' % (self.id, timerHandle))\n chapter[\"bankerMatchCardTime\"] = -1\n self.delTimer(timerHandle)\n self.match_card(chapter[\"banker\"], 0, chapter[\"cardsZ\"][:2], chapter[\"cardsZ\"][2:])\n elif timerHandle == chapter[\"otherMatchCardTime\"]:\n # 闲家配牌计时器\n DEBUG_MSG('[Room id %s]------>onTimer otherMatchCardTime %s' % (self.id, timerHandle))\n chapter[\"otherMatchCardTime\"] = -1\n self.delTimer(timerHandle)\n DEBUG_MSG('[Room id %s]------>onTimer cardsG %s,cardsT %s,cardsK %s' % (self.id, chapter[\"cardsG\"],\n chapter[\"cardsT\"],\n chapter[\"cardsK\"]))\n\n # 给没有配牌的门自动配牌\n for k, v in copy.deepcopy(chapter[\"canMatchCardsPlayers\"]).items():\n cards1, cards2 = [], []\n if k == 3:\n cards1, cards2 = chapter[\"cardsG\"][:2], chapter[\"cardsG\"][2:]\n DEBUG_MSG('[Room]cards1 %s,cards2 %s' % (cards1, cards2))\n if k == 2:\n cards1, cards2 = chapter[\"cardsT\"][:2], chapter[\"cardsT\"][2:]\n DEBUG_MSG('[Room]cards1 %s,cards2 %s' % (cards1, cards2))\n if k == 1:\n cards1, cards2 = chapter[\"cardsK\"][:2], chapter[\"cardsK\"][2:]\n DEBUG_MSG('[Room]cards1 %s,cards2 %s' % (cards1, cards2))\n self.match_card(v, k, cards1, cards2)\n elif timerHandle == chapter[\"compareCardTime\"]:\n DEBUG_MSG('[Room id %s]------>onTimer compareCardTime %s' % (self.id, timerHandle))\n chapter[\"compareCardTime\"] = -1\n self.delTimer(timerHandle)\n self.changeChapterState(8)\n elif timerHandle == chapter[\"settlementTime\"]:\n DEBUG_MSG('[Room id %s]------>onTimer settlementTime %s' % (self.id, timerHandle))\n # 超过局数总结算\n if self.cn + 1 >= self.info[\"maxChapterCount\"]:\n self.total_settlement()\n self.write_chapter_info_to_db()\n return\n chapter[\"settlementTime\"] = -1\n self.delTimer(timerHandle)\n self.clear_chapter()\n self.changeChapterState(0)\n\n elif timerHandle == chapter[\"settlementClearPlayers\"]:\n chapter[\"settlementClearPlayers\"] = -1\n self.delTimer(chapter[\"settlementClearPlayers\"])\n # 清理玩家\n _playerInGameCopy = chapter[\"playerInGame\"].copy()\n for k, v in _playerInGameCopy.items():\n self.kick_out(k)\n\n def retCurrentChapterState(self, accountEntityId):\n chapter = self.chapters[self.cn]\n self.callClientFunction(accountEntityId, \"CurrentChapterState\", {\"state\": chapter[\"currentState\"]})\n\n # 分牌\n def create_card(self):\n chapter = self.chapters[self.cn]\n cards_temp = copy.deepcopy(total_cards)\n random.shuffle(cards_temp)\n random.shuffle(cards_temp)\n chapter[\"cardsZ\"], chapter[\"cardsK\"] = cards_temp[:4], cards_temp[4:8]\n chapter[\"cardsT\"], chapter[\"cardsG\"] = cards_temp[8:12], cards_temp[12:16]\n args = {\"cardsZ\": chapter[\"cardsZ\"], \"cardsK\": chapter[\"cardsK\"], \"cardsT\": chapter[\"cardsT\"],\n \"cardsG\": chapter[\"cardsG\"]}\n self.callOtherClientsFunction(\"CreateCards\", args)\n\n def check_cards_type(self, accountId, cards):\n RoomType7Calculator.check_cards_type(cards)\n\n def tip_cards_type(self, account_entity_id, cards1):\n card_type_1, number_1 = RoomType7Calculator.get_cards_weights(cards1)\n self.callClientFunction(account_entity_id, \"tipCards\",\n {\"accountId\": account_entity_id, \"type\": card_type_1, \"number\": number_1,\n \"card\": cards1})\n\n def get_match_cards_player_info(self):\n stake_max_1, stake_max_2, stake_max_3 = 0, 0, 0\n chapter = self.chapters[self.cn]\n playerInGame = chapter[\"playerInGame\"]\n notice_player = []\n # 获取每个门的最大下注数\n for k, v in playerInGame.items():\n if k == chapter[\"banker\"]:\n continue\n DEBUG_MSG(\"[Room7]---get_match_cards_player_info---v[stake]%s\" % v[\"stake\"])\n if v[\"stake\"][1] > stake_max_1:\n stake_max_1 = v[\"stake\"][1]\n if v[\"stake\"][2] > stake_max_2:\n stake_max_2 = v[\"stake\"][2]\n if v[\"stake\"][3] > stake_max_3:\n stake_max_3 = v[\"stake\"][3]\n DEBUG_MSG(\"[Room7]---get_match_cards_player_info--stake1max%s,stake2max%s,stake3max%s\" % (\n stake_max_1, stake_max_2, stake_max_3))\n players1, players2, players3 = [], [], []\n for k, v in playerInGame.items():\n if k == chapter[\"banker\"]:\n continue\n if v[\"stake\"][1] == stake_max_1:\n players1.append(k)\n if v[\"stake\"][2] == stake_max_2:\n players2.append(k)\n if v[\"stake\"][3] == stake_max_3:\n players3.append(k)\n\n # 如果没有人下注,自动配牌,可以配牌玩家为-1\n if stake_max_1 == 0:\n players1 = [-1]\n if stake_max_2 == 0:\n players2 = [-1]\n if stake_max_3 == 0:\n players3 = [-1]\n\n DEBUG_MSG(\"[Room7]---get_match_cards_player_info--players1%s,players2%s,players3%s\" % (\n players1, players2, players3))\n\n if len(players1) > 1:\n random.shuffle(players1)\n notice_player.append(players1[0])\n else:\n notice_player.append(players1[0])\n\n if len(players2) > 1:\n random.shuffle(players2)\n notice_player.append(players2[0])\n else:\n notice_player.append(players2[0])\n\n if len(players3) > 1:\n random.shuffle(players3)\n notice_player.append(players3[0])\n else:\n notice_player.append(players3[0])\n\n return notice_player\n\n def get_cards_type(self, accountId, cards):\n cards_type, number = RoomType7Calculator.get_cards_weights(cards)\n args = {\"cards\": cards, \"type\": [cards_type, number]}\n self.callClientFunction(accountId, \"GetCardsType\", args)\n\n def match_card(self, accountId, matchIndex, cards1, cards2):\n DEBUG_MSG(\"[RoomType7]-----matchCard-----accountId%s,matchIndex%s,cards1:%s,cards2:%s\" % (\n accountId, matchIndex, cards1, cards2))\n chapter = self.chapters[self.cn]\n # 庄家配牌\n if chapter[\"currentState\"] == 5:\n if accountId == chapter[\"banker\"] and matchIndex == 0:\n chapter[\"bankerMatchCardTime\"] = -1\n self.delTimer(chapter[\"bankerMatchCardTime\"])\n card_type, number = RoomType7Calculator.get_cards_weights(cards1)\n cards1_weights = [card_type, number]\n card_type, number = RoomType7Calculator.get_cards_weights(cards2)\n cards2_weights = [card_type, number]\n comapre_result = RoomType7Calculator.compare_one_couple_cards(cards1_weights, cards2_weights)\n # 大的放后面\n if comapre_result == 2:\n chapter[\"cardsZ\"] = cards1 + cards2\n chapter[\"Zweights\"] = [cards1_weights, cards2_weights]\n else:\n chapter[\"cardsZ\"] = cards2 + cards1\n chapter[\"Zweights\"] = [cards2_weights, cards1_weights]\n args = {\"accountId\": accountId, \"matchIndex\": matchIndex, \"result\": 1}\n self.callOtherClientsFunction(\"MatchCardsResult\", args)\n self.changeChapterState(6)\n # 闲家配牌\n if chapter[\"currentState\"] == 6 and accountId != chapter[\"banker\"]:\n type, number = RoomType7Calculator.get_cards_weights(cards1)\n cards1_weights = [type, number]\n type, number = RoomType7Calculator.get_cards_weights(cards2)\n cards2_weights = [type, number]\n compare_result = RoomType7Calculator.compare_one_couple_cards(cards1_weights, cards2_weights)\n if compare_result == 1:\n t = cards1\n cards1 = cards2\n cards2 = t\n t_weights = cards1_weights\n cards1_weights = cards2_weights\n cards2_weights = t_weights\n if matchIndex == 1:\n chapter[\"cardsK\"] = cards1 + cards2\n chapter[\"Kweights\"] = [cards1_weights, cards2_weights]\n elif matchIndex == 2:\n chapter[\"cardsT\"] = cards1 + cards2\n chapter[\"Tweights\"] = [cards1_weights, cards2_weights]\n elif matchIndex == 3:\n chapter[\"cardsG\"] = cards1 + cards2\n chapter[\"Gweights\"] = [cards1_weights, cards2_weights]\n\n del chapter[\"canMatchCardsPlayers\"][matchIndex]\n args = {\"accountId\": accountId, \"matchIndex\": matchIndex, \"result\": 1}\n self.callOtherClientsFunction(\"MatchCardsResult\", args)\n if len(chapter[\"canMatchCardsPlayers\"]) == 0:\n chapter[\"otherMatchCardTime\"] = -1\n self.delTimer(chapter[\"otherMatchCardTime\"])\n self.changeChapterState(7)\n\n def compare_cards(self):\n chapter = self.chapters[self.cn]\n DEBUG_MSG(\"[Room7]::compare_cards::Zweights:%s,Tweights:%s,Gweights:%s,Kweights:%s\" % (\n chapter[\"Zweights\"], chapter[\"Tweights\"], chapter[\"Gweights\"], chapter[\"Kweights\"]))\n # 天门\n T = RoomType7Calculator.compare_cards(chapter[\"Zweights\"], chapter[\"Tweights\"], 1)\n # 过门\n G = RoomType7Calculator.compare_cards(chapter[\"Zweights\"], chapter[\"Gweights\"], 1)\n # 坎门\n K = RoomType7Calculator.compare_cards(chapter[\"Zweights\"], chapter[\"Kweights\"], 1)\n chapter[\"TResult\"] = T\n chapter[\"KResult\"] = K\n chapter[\"GResult\"] = G\n # 1:输,2:赢,0:平局\n args = {\"TResult\": T, \"GResult\": G, \"KResult\": K, \"cardsT\": chapter[\"cardsT\"], \"cardsK\": chapter[\"cardsK\"],\n \"cardsG\": chapter[\"cardsG\"], \"cardsZ\": chapter[\"cardsZ\"],\n \"cardsTInfo1\": chapter[\"Tweights\"][0], \"cardsTInfo2\": chapter[\"Tweights\"][1],\n \"cardsKInfo1\": chapter[\"Kweights\"][0], \"cardsKInfo2\": chapter[\"Kweights\"][1],\n \"cardsGInfo1\": chapter[\"Gweights\"][0], \"cardsGInfo2\": chapter[\"Gweights\"][1],\n \"cardsZInfo1\": chapter[\"Zweights\"][0], \"cardsZInfo2\": chapter[\"Zweights\"][1]}\n self.callOtherClientsFunction(\"CompareCardsResult\", args)\n T_results = self.get_total_result(T)\n G_results = self.get_total_result(G)\n K_results = self.get_total_result(K)\n chapter[\"settlementArea\"][G_results].append(3)\n chapter[\"settlementArea\"][T_results].append(2)\n chapter[\"settlementArea\"][K_results].append(1)\n\n def get_total_result(self, couple_result):\n if couple_result[0] == 2 and couple_result[1] == 2:\n return 'winArea'\n elif couple_result[0] == 1 and couple_result[1] == 1:\n return \"loseArea\"\n else:\n return \"drawArea\"\n\n def settlement(self):\n chapter = self.chapters[self.cn]\n banker = chapter[\"banker\"]\n banker_gold = chapter[\"playerInGame\"][banker][\"gold\"]\n # 所有胜利门总注\n win_total_stake = 0\n for area in chapter[\"settlementArea\"][\"winArea\"]:\n win_total_stake += chapter[\"stake\"][area]\n # 结算胜利区域\n for area in chapter[\"settlementArea\"][\"winArea\"]:\n for k, v in chapter[\"playerInGame\"].items():\n if k == banker:\n continue\n # 如果玩家在这个胜场有下注,收回下注并赢得金币\n stake_number = v[\"stake\"][area]\n if stake_number > 0:\n if banker_gold >= win_total_stake:\n win_gold = stake_number\n else:\n # 玩家在所有\n win_gold = stake_number / win_total_stake * banker_gold\n # 收回下注的钱+赢得的钱\n DEBUG_MSG(\"[Room7]::Settlement::id:%s,win_gold:%s,stake_number%s\" % (k, win_gold, stake_number))\n v[\"goldChange\"] += stake_number + win_gold\n chapter[\"playerInGame\"][banker][\"goldChange\"] -= win_gold\n # 结算失败区域\n for area in chapter[\"settlementArea\"][\"loseArea\"]:\n for k, v in chapter[\"playerInGame\"].items():\n if k == banker:\n continue\n # 如果玩家在这个输场有下注,注给庄家\n stake_number = v[\"stake\"][area]\n if stake_number > 0:\n chapter[\"playerInGame\"][banker][\"goldChange\"] += stake_number\n # 结算平局区域\n for area in chapter[\"settlementArea\"][\"drawArea\"]:\n for k, v in chapter[\"playerInGame\"].items():\n if k == banker:\n continue\n stake_number = v[\"stake\"][area]\n # 如果玩家在这个平局场有下注,收回下注\n if stake_number > 0:\n v[\"goldChange\"] += stake_number\n\n args = {\"playerGoldInfo\": {}, \"winArea\": [], \"loseArea\": [], \"drawArea\": []}\n # 修改金币\n for k, v in chapter[\"playerInGame\"].items():\n # 金币场赢钱抽成\n # if self.info[\"roomType\"] == \"gold\":\n # if v[\"goldChange\"] > 0:\n # v[\"goldChange\"] *= 0.95\n v[\"gold\"] += v[\"goldChange\"]\n # 修改玩家金币\n # self.set_player_gold(k, v[\"gold\"])\n DEBUG_MSG(\"[Room7]::Settlement::id:%s,gold change:%s\" % (k, v[\"goldChange\"]))\n v[\"totalGoldChange\"] += v[\"goldChange\"]\n player_gold_info = {\"gold\": v[\"gold\"], \"goldChange\": float(v[\"goldChange\"]),\n 'totalGoldChange': v['totalGoldChange'],\n \"stake\": {1: v[\"stake\"][1], 2: v[\"stake\"][2], 3: v[\"stake\"][3]}}\n args[\"playerGoldInfo\"][k] = player_gold_info\n args[\"winArea\"] = chapter[\"settlementArea\"][\"winArea\"]\n args[\"loseArea\"] = chapter[\"settlementArea\"][\"loseArea\"]\n args[\"drawArea\"] = chapter[\"settlementArea\"][\"drawArea\"]\n self.callOtherClientsFunction(\"settlement\", args)\n chapter[\"settlementTime\"] = self.addTimer(_timeSettlement, 0, 0)\n chapter[\"deadline\"] = time.time() + _timeSettlement\n self.settlement_count += 1\n if self.settlement_count == 1:\n self.base.cellToBase({'func': 'addTodayRoom'})\n # 如果是AA支付,扣除钻石\n if self.info['payType'] == Const.PayType.AA:\n # 需要扣除钻石的玩家\n need_consume_player = []\n # 如果坐下的玩家有没有扣除过AA支付��石的,结算时扣除\n for k, v in chapter['playerInGame'].items():\n if not v['AARoomCardConsumed']:\n need_consume_player.append(v[\"entity\"].info[\"userId\"])\n v['AARoomCardConsumed'] = True\n if len(need_consume_player) != 0:\n self.base.cellToBase({'func': 'AAPayTypeModifyRoomCard', 'needConsumePlayers': need_consume_player})\n\n def clear_chapter(self):\n DEBUG_MSG('[Room id %i]------>chapterRestart ' % self.id)\n _chapter = self.chapters[self.cn]\n _playerInGame = _chapter[\"playerInGame\"]\n _playerInRoom = _chapter[\"playerInRoom\"]\n _playerOutGame = _chapter[\"playerOutGame\"]\n\n _newChapter = self.newChapter(_chapter[\"maxPlayerCount\"])\n # 使用 deepcopy 避免每局战绩的玩家赢钱数相同\n _newChapter[\"playerInGame\"] = copy.deepcopy(_playerInGame)\n _newChapter[\"playerOutGame\"] = copy.deepcopy(_playerOutGame)\n _newChapter[\"playerInRoom\"].update(_newChapter[\"playerInGame\"])\n _newChapter[\"playerInRoom\"].update(_newChapter[\"playerOutGame\"])\n for k, v in _newChapter[\"playerInRoom\"].items():\n v[\"stake\"] = {0: 0, 1: 0, 2: 0, 3: 0}\n v[\"grabBanker\"] = -1\n # 本局金币变化\n v[\"goldChange\"] = 0\n # 准备\n v[\"ready\"] = False\n\n # _playerInGameCopy = _newChapter[\"playerInGame\"].copy()\n # for k, v in _playerInGameCopy.items():\n # # # 金币为零时踢出\n # # if v[\"gold\"] == 0:\n # # self.kick_out(k)\n # # 掉线时踢出\n # if not v[\"online\"]:\n # self.kick_out(k, player_online=False)\n # min_stake = stake_table[self.info[\"betLimit\"]][0]\n # if v[\"gold\"] < min_stake:\n # self.kick_out(k)\n\n def retChapterInfo(self, accountId):\n chapter = self.chapters[self.cn]\n play_in_game = chapter[\"playerInGame\"]\n chapter_info = {}\n chapter_info[\"currentRound\"] = int(chapter[\"currentRound\"])\n chapter_info[\"currentState\"] = int(chapter[\"currentState\"])\n chapter_info[\"deadline\"] = int(chapter[\"deadline\"]) - int(time.time())\n chapter_info[\"banker\"] = int(chapter[\"banker\"])\n chapter_info[\"bankerIndex\"] = int(chapter[\"bankerIndex\"])\n chapter_info[\"stake\"] = chapter[\"stake\"]\n chapter_info[\"cardsZ\"] = chapter[\"cardsZ\"]\n chapter_info[\"cardsK\"] = chapter[\"cardsK\"]\n chapter_info[\"cardsT\"] = chapter[\"cardsT\"]\n chapter_info[\"cardsG\"] = chapter[\"cardsG\"]\n chapter_info[\"canMatchCardsPlayers\"] = chapter[\"canMatchCardsPlayers\"]\n chapter_info[\"canWatchCardsPlayers\"] = chapter[\"canWatchCardsPlayers\"]\n chapter_info[\"settlementArea\"] = chapter[\"settlementArea\"]\n chapter_info[\"TResult\"] = chapter[\"TResult\"]\n chapter_info[\"GResult\"] = chapter[\"GResult\"]\n chapter_info[\"KResult\"] = chapter[\"KResult\"]\n chapter_info[\"started\"] = self.started\n chapter_info[\"disbandSender\"] = self.disband_sender\n chapter_info[\"teaHouseId\"] = self.info[\"teaHouseId\"] if \"teaHouseId\" in self.info.keys() else -1\n chapter_info[\"isDisbanding\"] = self.is_disbanding\n if len(chapter[\"Tweights\"]) != 0:\n chapter_info[\"cardsTInfo1\"] = chapter[\"Tweights\"][0]\n chapter_info[\"cardsTInfo2\"] = chapter[\"Tweights\"][1]\n if len(chapter[\"Kweights\"]) != 0:\n chapter_info[\"cardsKInfo1\"] = chapter[\"Kweights\"][0]\n chapter_info[\"cardsKInfo2\"] = chapter[\"Kweights\"][1]\n if len(chapter[\"Gweights\"]) != 0:\n chapter_info[\"cardsGInfo1\"] = chapter[\"Gweights\"][0]\n chapter_info[\"cardsGInfo2\"] = chapter[\"Gweights\"][1]\n if len(chapter[\"Zweights\"]) != 0:\n chapter_info[\"cardsZInfo1\"] = chapter[\"Zweights\"][0]\n chapter_info[\"cardsZInfo2\"] = chapter[\"Zweights\"][1]\n if len(self.chapters) > 1:\n chapter_info[\"preBanker\"] = self.chapters[self.cn - 1][\"banker\"]\n _playerData = {}\n for k, v in play_in_game.items():\n _playerData[k] = {\"goldChange\": v[\"goldChange\"],\n \"name\": v[\"entity\"].info[\"name\"],\n \"totalGoldChange\": v[\"totalGoldChange\"],\n \"ready\": v[\"ready\"],\n \"locationIndex\": v[\"locationIndex\"],\n \"stake\": v[\"stake\"],\n \"grabBanker\": v[\"grabBanker\"],\n \"gold\": v[\"gold\"] + v[\"goldChange\"],\n \"agreeDisband\": v[\"agreeDisband\"]\n }\n chapter_info[\"playerData\"] = _playerData\n self.callClientFunction(accountId, \"Reconnect\", chapter_info)\n\n # def set_player_gold(self, accountId, gold):\n # \"\"\"\n # 设置玩家金币数量,通知base\n # :param accountId:\n # :param gold:\n # :return:\n # \"\"\"\n # _chapter = self.chapters[self.cn]\n # _playerInRoom = _chapter[\"playerInRoom\"]\n # _player = _playerInRoom[accountId]\n # _player[\"gold\"] = int(gold)\n # _player[\"entity\"].accountMutableInfo[\"goldBean\"] = int(gold)\n # _player[\"entity\"].base.cellToBase({\"func\": \"setAccountMutableInfo\", \"dic\": {\n # \"goldBean\": _player[\"entity\"].accountMutableInfo[\"goldBean\"]}})\n\n # 机器人抢庄\n def bots_grab_banker(self):\n chapter = self.chapters[self.cn]\n for k, v in chapter[\"playerInGame\"].items():\n if v[\"entity\"].info[\"isBot\"] == 1:\n self.grab_banker(k, random.randint(0, 1))\n\n def bots_set_stake(self):\n chapter = self.chapters[self.cn]\n for k, v in chapter[\"playerInGame\"].items():\n if v[\"entity\"].info[\"isBot\"] == 1 and chapter[\"banker\"] != k:\n # 机器人随机下二到五次注\n count = random.randint(3, 8)\n for i in range(1, count):\n stake = random.choice(stake_table[self.info[\"betLimit\"]])\n if self.have_gold_limit() and stake > v[\"gold\"] + v[\"goldChange\"]:\n continue\n self.set_stake(k, stake, random.randint(1, 3), True)\n\n def total_settlement(self):\n if self.total_settlement_ed:\n return\n self.close_all_timer()\n self.changeChapterState(9)\n self.total_settlement_ed = True\n chapter = self.chapters[self.cn]\n\n if self.info[\"roomType\"] == \"gameCoin\" and self.settlement_count > 0:\n self.lottery()\n\n # 找到大赢家\n winner = {}\n max_win = 0\n for k, v in self.chapters[self.cn]['playerInGame'].items():\n if v['totalGoldChange'] >= max_win:\n max_win = v['totalGoldChange']\n\n for k, v in self.chapters[self.cn]['playerInGame'].items():\n if v['totalGoldChange'] == max_win:\n winner[k] = v\n\n all_bill = {}\n for k, v in self.chapters[self.cn]['playerInGame'].items():\n all_bill[k] = {\"userId\": v[\"entity\"].info[\"userId\"], \"todayGameCoinAdd\": 0, 'winner': 1 if k in winner else 0, \"score\": v['totalGoldChange']}\n\n if self.info[\"winnerBilling\"]:\n for k, v in winner.items():\n winnerBillingCount = 0\n for i in range(0, len(self.info[\"winnerBilling\"])):\n if self.info[\"winnerBilling\"][i]['interval'][0] <= v[\"totalGoldChange\"] <= \\\n self.info[\"winnerBilling\"][i]['interval'][1]:\n winnerBillingConsume = self.info[\"winnerBilling\"][i]['consume']\n v[\"totalGoldChange\"] -= winnerBillingConsume\n v[\"gold\"] -= winnerBillingConsume\n v[\"winnerBilling\"] = -winnerBillingConsume\n winnerBillingCount += self.info[\"winnerBilling\"][i]['consume']\n\n self.base.cellToBase({\"func\": \"todayGameBilling\", \"teaHouseId\": self.info[\"teaHouseId\"],\n \"todayGameCoinAdd\": winnerBillingCount,\n \"userId\": v[\"entity\"].info[\"userId\"]})\n all_bill[k][\"todayGameCoinAdd\"] += winnerBillingCount\n\n if self.info['otherBilling']:\n for k, v in chapter['playerInGame'].items():\n # 如果大赢家开启,其他玩家不扣大赢家\n if k in winner and self.info[\"winnerBilling\"]:\n continue\n otherBillingCount = 0\n for i in range(0, len(self.info[\"otherBilling\"])):\n if self.info[\"otherBilling\"][i]['interval'][0] <= v[\"totalGoldChange\"] <= \\\n self.info[\"otherBilling\"][i]['interval'][1]:\n otherBillingConsume = self.info[\"otherBilling\"][i]['consume']\n v[\"totalGoldChange\"] -= otherBillingConsume\n v[\"gold\"] -= otherBillingConsume\n v[\"otherBilling\"] = -otherBillingConsume\n otherBillingCount += self.info[\"otherBilling\"][i]['consume']\n\n self.base.cellToBase({\"func\": \"todayGameBilling\", \"teaHouseId\": self.info[\"teaHouseId\"],\n \"todayGameCoinAdd\": otherBillingCount,\n \"userId\": v[\"entity\"].info[\"userId\"]})\n all_bill[k][\"todayGameCoinAdd\"] += otherBillingCount\n self.base.cellToBase({\"func\": \"todayBillStatic\", \"teaHouseId\": self.info[\"teaHouseId\"], \"bill\": list(all_bill.values())})\n\n player_settlement_info = []\n for k, v in chapter[\"playerInGame\"].items():\n # 同步金币到 base\n if self.info[\"roomType\"] == \"gameCoin\":\n self.set_base_player_game_coin(k)\n else:\n self.set_base_player_gold(k)\n player_settlement_info.append(\n {\"accountId\": k, \"totalGoldChange\": v[\"totalGoldChange\"], \"name\": v[\"entity\"].info[\"name\"],\n \"overBilling\": v[\"overBilling\"], \"otherBilling\": v[\"otherBilling\"],\n \"winnerBilling\": v[\"winnerBilling\"], 'gold': v['gold']})\n\n args = {\"settlementInfo\": player_settlement_info}\n self.callOtherClientsFunction(\"TotalSettlement\", args)\n self.base.cellToBase({\"func\": \"totalSettlementEd\"})\n # 忽略判断,创建一个房间\n self.base.cellToBase({\"func\": \"autoCreateRoom\", \"roomInfo\": self.info, 'ignoreJudge': True, 'onRoomEnd': True})\n # 记录局数\n if self.is_tea_house_room and self.settlement_count >= 1:\n self.set_base_player_chapter_count()\n\n # 总结算清理玩家倒计时\n chapter[\"settlementClearPlayers\"] = self.addTimer(settlement_clear_players_time, 0, 0)\n chapter[\"deadline\"] = time.time() + settlement_clear_players_time\n\n # 群主解散房间\n def tea_house_disband_room_by_creator(self):\n \"\"\"\n 解散房间\n :return:\n \"\"\"\n _chapter = self.chapters[self.cn]\n player_in_game = _chapter[\"playerInGame\"].copy()\n self.disband_from_creator = True\n if not self.started:\n for k, v in player_in_game.items():\n self.kick_out(k)\n else:\n self.autoDestroy()\n return\n\n if self.chapters[self.cn][\"currentState\"] != 9:\n self.total_settlement()\n self.write_chapter_info_to_db()\n\n # 机器人配牌\n def bots_match_card(self):\n chapter = self.chapters[self.cn]\n if chapter[\"currentState\"] == 5:\n for k, v in chapter[\"playerInGame\"].items():\n if v[\"entity\"].info[\"isBot\"] == 1:\n if k == chapter[\"banker\"]:\n self.match_card(k, 0, chapter[\"cardsZ\"][:2], chapter[\"cardsZ\"][2:])\n return\n if chapter[\"currentState\"] == 6:\n match_player = chapter[\"canMatchCardsPlayers\"]\n for k, v in chapter[\"playerInGame\"].items():\n if v[\"entity\"].info[\"isBot\"] == 1:\n if 1 in match_player and k == match_player[1]:\n self.match_card(k, 1, chapter[\"cardsK\"][:2], chapter[\"cardsK\"][2:])\n if 2 in match_player and k == match_player[2]:\n self.match_card(k, 2, chapter[\"cardsT\"][:2], chapter[\"cardsT\"][2:])\n if 3 in match_player and k == match_player[3]:\n self.match_card(k, 3, chapter[\"cardsG\"][:2], chapter[\"cardsG\"][2:])\n return\n\n def get_bots(self):\n chapter = self.chapters[self.cn]\n bots = {}\n for k, v in chapter[\"playerInGame\"].items():\n if v[\"entity\"].info[\"isBot\"] == 1:\n bots[k] = v\n return bots\n\n def close_all_timer(self):\n \"\"\"\n 关闭所有计时器\n :return:\n \"\"\"\n chapter = self.chapters[self.cn]\n chapter[\"bankerTimerId\"] = -1\n self.delTimer(chapter[\"bankerTimerId\"])\n chapter[\"createCardTime\"] = -1\n self.delTimer(chapter[\"createCardTime\"])\n chapter[\"stakeTime\"] = -1\n self.delTimer(chapter[\"stakeTime\"])\n chapter[\"dealCardTime\"] = -1\n self.delTimer(chapter[\"dealCardTime\"])\n chapter[\"bankerMatchCardTime\"] = -1\n self.delTimer(chapter[\"bankerMatchCardTime\"])\n chapter[\"otherMatchCardTime\"] = -1\n self.delTimer(chapter[\"otherMatchCardTime\"])\n chapter[\"compareCardTime\"] = -1\n self.delTimer(chapter[\"compareCardTime\"])\n chapter[\"settlementTime\"] = -1\n self.delTimer(chapter[\"settlementTime\"])\n self.disband_timer = -1\n self.delTimer(self.disband_timer)\n","repo_name":"Bobcatsoap/jy-server","sub_path":"cell/RoomType7.py","file_name":"RoomType7.py","file_ext":"py","file_size_in_byte":82777,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"31294204305","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\n\nfrom flask import json\nfrom six import BytesIO\n\nfrom swagger_server.models.error import Error # noqa: E501\nfrom swagger_server.models.learner_preferences import LearnerPreferences # noqa: E501\nfrom swagger_server.test import BaseTestCase\n\n\nclass TestLearnerPreferencesController(BaseTestCase):\n \"\"\"LearnerPreferencesController integration test stubs\"\"\"\n\n def test_delete_learner_preferences(self):\n \"\"\"Test case for delete_learner_preferences\n\n Deletes a learner's preferences\n \"\"\"\n response = self.client.open(\n '/rui-support/learner-preferences/{keycloakId}'.format(keycloakId='keycloakId_example'),\n method='DELETE',\n content_type='application/ld+json')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n def test_post_learner_preferences(self):\n \"\"\"Test case for post_learner_preferences\n\n Stores a learner's preferences\n \"\"\"\n learnerPreferencesObj = LearnerPreferences()\n response = self.client.open(\n '/rui-support/learner-preferences/{keycloakId}'.format(keycloakId='keycloakId_example'),\n method='POST',\n data=json.dumps(learnerPreferencesObj),\n content_type='application/ld+json')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n def test_update_learner_preferences(self):\n \"\"\"Test case for update_learner_preferences\n\n Updates a learner's preferences\n \"\"\"\n learnerPreferencesObj = LearnerPreferences()\n response = self.client.open(\n '/rui-support/learner-preferences/{keycloakId}'.format(keycloakId='keycloakId_example'),\n method='PATCH',\n data=json.dumps(learnerPreferencesObj),\n content_type='application/ld+json')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n\nif __name__ == '__main__':\n import unittest\n unittest.main()\n","repo_name":"soartech/fluent","sub_path":"services/recommender-ui-support/swagger_server/test/test_learner_preferences_controller.py","file_name":"test_learner_preferences_controller.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"41318597090","text":"\"\"\"\nModule for the newport motors.\n\"\"\"\n\nfrom enum import Enum\nimport logging\nfrom typing import Literal\nimport parse\n\nimport pyvisa\n\n\nclass Motor:\n \"\"\"\n Base class for all the newport motors\n \"\"\"\n\n # The serial config for the newport motors:\n SERIAL_BAUD = 921600\n SERIAL_TERMIN = \"\\r\\n\"\n\n def __init__(self, serial_port: str, resource_manager: pyvisa.ResourceManager):\n self._serial_port = serial_port\n self.open_connection(resource_manager)\n self._verify_valid_connection()\n\n def open_connection(self, resource_manager: pyvisa.ResourceManager):\n \"\"\"\n resource_manager : pyvisa.ResourceManager object (to avoid constructing it many times)\n \"\"\"\n self._connection = resource_manager.open_resource(\n self._serial_port,\n baud_rate=self.SERIAL_BAUD,\n write_termination=self.SERIAL_TERMIN,\n read_termination=self.SERIAL_TERMIN,\n )\n\n def _verify_valid_connection(self):\n raise NotImplementedError()\n\n def write_str(self, str_to_write):\n \"\"\"\n Write a string through serial and do not expect anything to be returned\n\n Parameters:\n -----------\n str_to_write: str\n The string to write to the serial port\n \"\"\"\n self._connection.write(str_to_write)\n\n def query_str(self, str_to_write):\n \"\"\"\n Send a query through serial and return the response\n\n Parameters:\n -----------\n str_to_write: str\n The string to write to the serial port\n\n Returns:\n --------\n return_str: str\n The string returned from the serial port\n \"\"\"\n return_str = self._connection.query(str_to_write).strip()\n return return_str\n\n def set_to_zero(self):\n \"\"\"\n Set the motor to the zero position\n \"\"\"\n raise NotImplementedError()\n\n @classmethod\n def validate_config(cls, config):\n \"\"\"\n Validate the config dictionary for the motor\n \"\"\"\n pass\n\n @staticmethod\n def setup_individual_config():\n raise NotImplementedError()\n\n @staticmethod\n def infer_motor_type(motor_name):\n \"\"\"\n Given the internal name of the motor, attempt to infer the type of the class to instantiate\n\n Parameters:\n -----------\n motor_name: str\n The internal name of the motor\n\n Returns:\n --------\n motor_type: type\n The python type of the motor to instantiate\n \"\"\"\n\n motor_type = None\n ending = motor_name.split(\"_\")[-1]\n if ending.lower() == \"tiptilt\" or ending.lower() == \"m100d\":\n motor_type = M100D\n elif ending.lower() == \"linear\" or ending.lower() == \"ls16p\":\n motor_type = LS16P\n\n if motor_type is None:\n raise KeyError(f\"could not infer motor type from {motor_name}\")\n return motor_type\n\n @staticmethod\n def motor_type_to_string(motor_type):\n \"\"\"\n Convert the motor type to a string\n\n Parameters:\n -----------\n motor_type: type\n The python type of the motor\n\n Returns:\n --------\n motor_str: str\n The string representation of the motor (to use for e.g. saving to a config file)\n \"\"\"\n m = None\n if motor_type == M100D:\n m = \"M100D\"\n elif motor_type == LS16P:\n m = \"LS16P\"\n\n if m is None:\n raise ValueError(f\"Could not find motor from {motor_type}\")\n\n return m\n\n @staticmethod\n def string_to_motor_type(motor_str):\n \"\"\"\n Convert the motor string to a type\n\n Parameters:\n -----------\n motor_str: str\n The string representation of the motor (to use for e.g. saving to a config file)\n\n Returns:\n --------\n motor_type: Motor\n The python type of the motor\n \"\"\"\n m = None\n if motor_str.lower() == \"m100d\":\n m = M100D\n elif motor_str.lower() == \"ls16p\":\n m = LS16P\n\n if m is None:\n raise ValueError(f\"Could not find motor from {motor_str}\")\n\n return m\n\n\nclass M100D(Motor):\n \"\"\"\n A tip tilt motor driver class\n https://www.newport.com.cn/p/CONEX-AG-M100D\n \"\"\"\n\n AXES = Enum(\"AXES\", [\"U\", \"V\"])\n HW_BOUNDS = {AXES.U: [-0.75, 0.75], AXES.V: [-0.75, 0.75]}\n\n def __init__(\n self,\n serial_port,\n resource_manager: pyvisa.ResourceManager,\n orientation: Literal[\"normal\", \"reversed\"] = \"normal\",\n ) -> None:\n \"\"\"\n A class for the tip tile M100D motors\n\n Parameters:\n -----------\n serial_port: str\n The serial port that the motor is connected to\n resource_manager: pyvisa.ResourceManager\n The resource manager that is used to open the serial connection\n orientation: str\n The orientation of the motor. Either \"normal\" or \"reversed\". In the case of reversed, the U and V axes are\n swapped, such that asking a function to move the U axis will actually move the V axis and vice versa.\n This correctly accounts for the flipped sign of the U axis in the reversed orientation.\n \"\"\"\n super().__init__(serial_port, resource_manager)\n\n if orientation not in [\"normal\", \"reverse\"]:\n raise ValueError(\n f\"orientation must be either 'normal' or 'reverse', not {orientation}\"\n )\n self._current_pos = {self.AXES.U: 0.0, self.AXES.V: 0.0}\n # TODO: this needs some thinking about how to implement so that the external interface doesn't notice\n self._is_reversed = orientation == \"reverse\"\n\n def _verify_valid_connection(self):\n \"\"\"\n Verify that the serial connection opened by the class is indeed to to a NEWPORT M100D\n \"\"\"\n id_number = self._connection.query(\"1ID?\").strip()\n assert \"M100D\" in id_number\n\n def _get_axis(self, axis: AXES):\n \"\"\"\n Get the axis and apply the reverse flag if needed\n \"\"\"\n if self._is_reversed:\n if axis == self.AXES.U:\n axis = self.AXES.V\n elif axis == self.AXES.V:\n axis = self.AXES.U\n return axis\n\n def _alter_value(self, axis: AXES, value: float):\n \"\"\"\n if the motor is reversed, then the value for the U axis needs to be flipped\n the function should always be called after _get_axis i.e. the axis should be already changed\n \"\"\"\n if self._is_reversed and axis == self.AXES.U:\n return -value\n return value\n\n @property\n def get_current_pos(self):\n \"\"\"\n Return the current position of the motor in degrees\n \"\"\"\n return [\n self._alter_value(self._get_axis(ax), self._current_pos[self._get_axis(ax)])\n for ax in M100D.AXES\n ]\n\n def set_to_zero(self):\n \"\"\"\n Set all the motor axes positions to zero\n \"\"\"\n for axis in self.AXES:\n self.set_absolute_position(0.0, axis)\n\n def read_pos(self, axis: AXES) -> float:\n \"\"\"\n Read the position of a given axis.\n\n Parameters:\n axis (M100D.AXES) : the axis to read from\n\n Returns:\n position (float) : the position of the axis in degrees\n \"\"\"\n axis = self._get_axis(axis)\n\n return_str = self._connection.query(f\"1TP{axis.name}\").strip()\n subset = parse.parse(\"{}\" + f\"TP{axis.name}\" + \"{}\", return_str)\n\n if subset is not None:\n return self._alter_value(axis, float(subset[1]))\n raise ValueError(f\"Could not parse {return_str}\")\n\n def set_absolute_position(self, value: float, axis: AXES):\n \"\"\"\n Set the absolute position of the motor in a given axis\n\n Parameters:\n value (float) : The new position in degrees\n axis (M100D.AXES) : the axis to set\n \"\"\"\n axis = self._get_axis(axis)\n value = self._alter_value(axis, value)\n str_to_write = f\"1PA{axis.name}{value}\"\n logging.info(f\"sending {str_to_write}\")\n self._connection.write(str_to_write)\n self._current_pos[axis] = value\n\n @classmethod\n def validate_config(cls, config):\n \"\"\"\n Validate the config dictionary for the motor\n \"\"\"\n pass\n if \"orientation\" not in config:\n raise KeyError(\"orientation not in config\")\n\n @staticmethod\n def setup_individual_config():\n inp = input(\"is the motor mounted normally with the text right way up? (Y/N)\")\n orientation = None\n if inp.lower() == \"y\":\n orientation = \"normal\"\n elif inp.lower() == \"n\":\n orientation = \"reverse\"\n\n if orientation is None:\n raise ValueError(f\"invalid input {inp}\")\n return {\"orientation\": orientation}\n\n\nclass LS16P(Motor):\n \"\"\"\n A linear motor driver class\n https://www.newport.com/p/CONEX-SAG-LS16P\n \"\"\"\n\n HW_BOUNDS = [-8.0, 8.0]\n\n def __init__(self, serial_port: str, resource_manager: pyvisa.ResourceManager):\n super().__init__(serial_port, resource_manager)\n self._current_pos = 0.0\n\n def _verify_valid_connection(self):\n \"\"\"\n Verify that the serial connection opened by the class is indeed to to a NEWPORT LS16P\n \"\"\"\n id_number = self._connection.query(\"1ID?\").strip()\n assert \"LS16P\" in id_number\n\n def set_absolute_position(self, value: float):\n \"\"\"\n Set the absolute position of the motor\n\n Parameters:\n value (float) : The new position in mm\n \"\"\"\n str_to_write = f\"1PA{value}\"\n self._connection.write(str_to_write)\n self._current_pos = value\n\n def read_pos(self) -> float:\n \"\"\"\n Set the absolute position of the motor\n\n Returns:\n value (float) : The new position in mm\n \"\"\"\n return_str = self._connection.query(\"1TP\").strip()\n subset = parse.parse(\"{}TP{}\", return_str)\n if subset is not None:\n return float(subset[1])\n raise ValueError(f\"Could not parse {return_str}\")\n\n def set_to_zero(self):\n \"\"\"\n Set the motor to the zero position\n \"\"\"\n self.set_absolute_position(0.0)\n\n @property\n def get_current_pos(self):\n \"\"\"\n Return the software internal position of the motor\n \"\"\"\n return self._current_pos\n\n @staticmethod\n def setup_individual_config():\n return {}\n\n\nif __name__ == \"__main__\":\n import time\n\n # example code:\n # Open a connection to a M100D on ttyUSB0,\n # verify the AXES attributes, read a position and set a position\n tt = M100D(\n \"ASRL/dev/ttyUSB0::INSTR\",\n pyvisa.ResourceManager(visa_library=\"@_py\"),\n orientation=\"normal\",\n )\n # tt = M100D(\n # \"ASRL/dev/ttyUSB1::INSTR\",\n # pyvisa.ResourceManager(visa_library=\"@_py\"),\n # orientation=\"reverse\",\n # )\n print(tt.read_pos(tt.AXES.U), tt.read_pos(tt.AXES.V))\n\n tt.set_absolute_position(0.0, tt.AXES.U)\n tt.set_absolute_position(0.0, tt.AXES.V)\n print(tt.read_pos(tt.AXES.U))\n\n time.sleep(3)\n\n tt.set_absolute_position(0.7, tt.AXES.V)\n # tt.set_absolute_position(0.7, tt.AXES.U)\n\n time.sleep(3)\n print(tt.read_pos(tt.AXES.U), tt.read_pos(tt.AXES.V))\n","repo_name":"ataras2/newport-motors-py","sub_path":"newport_motors/Motors/motor.py","file_name":"motor.py","file_ext":"py","file_size_in_byte":11499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"9532096236","text":"#Handle Frames\n#\n'''\nExample from :https://the-internet.herokuapp.com\n\nFrames are embedded HTML which seats on top over base HTML,\nWe can not directly access to the frames, need to switch from driver to the frame.\n'''\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n# import time\n\n#Step 1:\ndriver = webdriver.Chrome()\n# driver.get(\"https://the-internet.herokuapp.com/windows\")\n\n#Step 2:\n# Open sample url for Frame Example\ndriver.get(\"https://the-internet.herokuapp.com/iframe\")\n\n#Step 3:\n#Switch control from Driver to Frame \ndriver.switch_to.frame(\"mce_0_ifr\")# use frame ID/name .frame\n\n#Step 4:\ndriver.find_element(By.ID,\"tinymce\").clear()\ndriver.find_element(By.ID,\"tinymce\").send_keys(\"I am Abhijit, Testing for frame Automation\")\n\n\n#Switch from frame to normal window back\ndriver.switch_to.default_content() #back to original controll","repo_name":"AbhijitManepatil/Selenium-Scratch-","sub_path":"14.Frames.py","file_name":"14.Frames.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19926818444","text":"# -*- coding: utf-8 -*-\n\nfrom wordgenerator.Weight import WeightNode as Weight\nfrom wordgenerator.Interval import IntervalNode as Interval\nfrom wordgenerator.Sequence import SequenceNode as Sequence\nfrom wordgenerator.Print import Title\nfrom wordgenerator.Generator import Generator\nfrom macro.dice import Pool, PoolSum\n\nd100 = PoolSum(Pool(1,100))\n\ndef DoubleRelance(rel_node) :\n seq = Sequence()\n seq << [\n rel_node,\n rel_node,\n ]\n return seq\n\n################ PROP SPE ARMES & ARMURES\n\nspe_armure = Interval(d100) << [\n [ 1, 3, \"Mimétisme (+2 700 po)\"],\n [ 4, 4, \"Défense légère (bonus de +1)\"],\n [ 5, 7, \"Graisseuse supérieure (+15 000 po)\"],\n [ 8, 13, \"Ombre supérieure (+15 000 po)\"],\n [14, 28, \"Résistance aux énergies (+18 000 po)\"],\n [29, 33, \"Spectrale (bonus de +3)\"],\n [34, 35, \"Invulnérabilité (bonus de +3)\"],\n [36, 40, \"Défense intermédiaire (bonus de +3)\"],\n [41, 42, \"Résistance à la magie (15) (bonus de +3)\"],\n [43, 43, \"Forme animale (bonus de +3)\"],\n [44, 48, \"Graisseuse suprême (+3 750 po)\"],\n [49, 58, \"Ombre suprême (+3 750 po)\"],\n [59, 83, \"Résistance aux énergies supérieure (+42 000 po)\"],\n [84, 88, \"Résistance à la magie (17) (bonus de +4)\"],\n [89, 89, \"Éthérée (+49 000 po)\"],\n [90, 90, \"Contrôle des morts-vivants (+49 000 po)\"],\n [91, 92, \"Défense lourde (bonus de +5)\"],\n [93, 94, \"Résistance à la magie (19) (bonus de +5)\"],\n [95, 99, \"Résistance aux énergies suprême (+66 000 po)\"],\n]# 00 : relance 2 fois\nspe_armure.append(100, 100, DoubleRelance(spe_armure))\n\nspe_bouclier = Interval(d100) << [\n [ 1, 5, \"Interception de projectiles (bonus de +1)\"],\n [ 6, 8, \"Attaque (bonus de +1)\"],\n [ 9, 10, \"Aveuglant (bonus de +1)\"],\n [11, 15, \"Défense légère (bonus de +1)\"],\n [16, 20, \"Antiprojectiles (bonus de +2)\"],\n [21, 25, \"Animé (bonus de +2)\"],\n [26, 41, \"Résistance aux énergies (+18 000 po)\"],\n [42, 46, \"Spectral (bonus de +3)\"],\n [47, 56, \"Défense intermédiaire (bonus de +3)\"],\n [57, 58, \"Résistance à la magie (15) (bonus de +3)\"],\n [59, 59, \"Forme animale (bonus de +3)\"],\n [60, 84, \"Résistance aux énergies supérieure (+42 000 po)\"],\n [85, 86, \"Résistance à la magie (17) (bonus de +4)\"],\n [87, 87, \"Contrôle des morts-vivants (+49 000 po)\"],\n [88, 91, \"Défense lourde (bonus de +5)\"],\n [92, 93, \"Réfléchissant (bonus de +5)\"],\n [94, 94, \"Résistance à la magie (19) (bonus de +5)\"],\n [95, 99, \"Résistance aux énergies suprême (+66 000 po)\"],\n]# 00 : relance 2 fois\nspe_bouclier.append(91, 100, DoubleRelance(spe_bouclier))\n\nspe_cac = Interval(d100) << [\n [ 1, 3, \"Tueuse (bonus de +1)\"],\n [ 4, 6, \"Feu (bonus de +1)\"],\n [ 7, 9, \"Froid (bonus de +1)\"],\n [10, 12, \"Foudre (bonus de +1)\"],\n [13, 15, \"Spectrale (bonus de +1)\"],\n [16, 19, \"Focalisation ki (bonus de +1)\"],\n [20, 21, \"Enchaînement (bonus de +1)\"],\n [22, 24, \"Stockage de sort (bonus de +1)\"],\n [25, 28, \"Lancer (bonus de +1)\"],\n [29, 32, \"Tonnerre (bonus de +1)\"],\n [33, 36, \"Vicieuse (bonus de +1)\"],\n [37, 41, \"Anarchique (bonus de +2)\"],\n [42, 46, \"Axiomatique (bonus de +2)\"],\n [47, 49, \"Destruction (bonus de +2)\"],\n [50, 54, \"Feu intense (bonus de +2)\"],\n [55, 59, \"Froid intense (bonus de +2)\"],\n [60, 64, \"Sainte (bonus de +2)\"],\n [65, 69, \"Foudre intense (bonus de +2)\"],\n [70, 74, \"Impie (bonus de +2)\"],\n [75, 78, \"Sanglante (bonus de +2)\"],\n [79, 83, \"Rapidité (bonus de +3)\"],\n [84, 86, \"Lumière (bonus de +4)\"],\n [87, 88, \"Dansante (bonus de +4)\"],\n [89, 90, \"Vorpale (bonus de +5)\"],\n]# 00 : relance 2 fois\nspe_cac.append(91, 100, DoubleRelance(spe_cac))\n\nspe_dist = Interval(d100) << [\n [ 1, 4, \"Tueuse (bonus de +1)\"],\n [ 5, 8, \"Longue portée (bonus de +1)\"],\n [ 9, 12, \"Feu (bonus de +1)\"],\n [13, 16, \"Froid (bonus de +1)\"],\n [17, 21, \"Boomerang (bonus de +1)\"],\n [22, 25, \"Foudre (bonus de +1)\"],\n [26, 27, \"Traqueuse (bonus de +1)\"],\n [28, 29, \"Tonnerre (bonus de +1)\"],\n [30, 34, \"Anarchique (bonus de +2)\"],\n [35, 39, \"Axiomatique (bonus de +2)\"],\n [40, 49, \"Feu intense (bonus de +2)\"],\n [50, 54, \"Sainte (bonus de +2)\"],\n [55, 64, \"Froid intense (bonus de +2)\"],\n [65, 74, \"Foudre intense (bonus de +2)\"],\n [75, 79, \"Impie (bonus de +2)\"],\n [80, 84, \"Rapidité (bonus de +3)\"],\n [85, 90, \"Lumière (bonus de +4)\"],\n]# 00 : relance 2 fois\nspe_dist.append(91, 100, DoubleRelance(spe_dist))\n\n################ ARMURES & BOUCLIERS\n\nobj_armure_spe = Interval(d100) << [\n [ 1, 10, \"Cuirasse en adamantium (10 200 po)\"],\n [11, 20, \"Harnois nain (16 500 po)\"],\n [21, 32, \"Crevice de la seconde chance (18 900 po)\"],\n [33, 50, \"Armure céleste (22 400 po)\"],\n [51, 60, \"Harnois des profondeurs (24 650po)\"],\n [61, 75, \"Cuirasse de commandement (25 400 po)\"],\n [76, 90, \"Harnois en mithral de vitesse (26 500 po)\"],\n [91, 100, \"Armure démoniaque (52 260 po)\"],\n]\n\nobj_bouclier_spe = Interval(d100) << [\n [ 1, 20, \"Bouclier des arcanes (3 153 po)\"],\n [21, 40, \"Bouclier de la manticore (5 580 po)\"],\n [41, 60, \"Bouclier du lion (9 170 po)\"],\n [61, 90, \"Bouclier ailé (17 257 po)\"],\n [91, 100, \"Bouclier phagocyte (50 170 po)\"],\n]\n\narmor_type = \"NONE\"\ndef setArmor() :\n global armor_type\n armor_type = \"ARMOR\"\ndef setShield() :\n global armor_type\n armor_type = \"SHIELD\"\n\ndef RollArmorProperty() :\n global armor_type\n if armor_type == \"ARMOR\" :\n spe_armure.execute()\n elif armor_type == \"SHIELD\" :\n spe_bouclier.execute()\n else :\n pass #raise ValueError(f\"Not expected value {armor_type}\")\n armor_type = \"NONE\"\n\nobj_bouclier_armure = Weight() << [\n [ 8, Sequence() << [\n \"Bouclier +3 (+9 000po)\",\n setShield]],\n [ 8, Sequence() << [\n \"Armure +3 (+9 000po)\",\n setArmor]],\n [11, Sequence() << [\n \"Bouclier +4 (+16 000po)\",\n setShield]],\n [11, Sequence() << [\n \"Armure +4 (+16 000po)\",\n setArmor]],\n [11, Sequence() << [\n \"Bouclier +5 (+25 000po)\",\n setShield]],\n [ 8, Sequence() << [\n \"Armure +5 (+25 000po)\",\n setArmor]],\n]\n\nobj_bouclier_armure_reroll = Weight()\nobj_bouclier_armure_reroll.children = [c for c in obj_bouclier_armure.children]\n\nobj_bouclier_armure << [\n [ 3, obj_armure_spe],\n [ 3, obj_bouclier_spe],\n # reroll and add a special property\n [37, Sequence() << [\n obj_bouclier_armure_reroll,\n Title(\"Propriété\", RollArmorProperty)]]\n]\n\n################ ARMES CAC & DIST\n\nobj_arme_spe = Interval(d100) << [\n [ 1, 4, \"Dague de l’assassin (10 302 po)\"],\n [ 5, 7, \"Regret du changeant (12 780 po)\"],\n [ 8, 9, \"Trident de domination aquatique (18 650 po)\"],\n [10, 13, \"Épée ardente (20 715 po)\"],\n [14, 17, \"Épée de bonne fortune (0 souhait) (22 060 po)\"],\n [18, 24, \"Épée de précision (22 310 po)\"],\n [25, 31, \"Épée des plans (22 315 po)\"],\n [32, 37, \"Épée des neuf vies (23 057 po)\"],\n [38, 42, \"Arc du long serment (25 600 po)\"],\n [43, 46, \"Épée voleuse de vie (25 715 po)\"],\n [47, 51, \"Masse d’épouvante (38 552 po)\"],\n [52, 57, \"Hache dévitalisante (40 320 po)\"],\n [58, 62, \"Cimeterre des bois (47 315 po)\"],\n [63, 67, \"Rapière d’anémie (50 320 po)\"],\n [68, 73, \"Épée radieuse (50 335 po)\"],\n [74, 79, \"Épée de givre (54 475 po)\"],\n [80, 84, \"Marteau de lancer nain (60 312 po)\"],\n [85, 91, \"Épée de bonne fortune (1 souhait) (62 360 po)\"],\n [92, 95, \"Masse de démolition (75 312 po)\"],\n [96, 97, \"Épée de bonne fortune (2 souhaits) (102 660 po)\"],\n [98, 99, \"Épée de justice (120 630 po)\"],\n [100, 100, \"Épée de bonne fortune (3 souhaits) (142 960 po)\"],\n]\n\nobj_cac_dist = Weight() << [\n [20, \"Arme +3\t(+18 000 po)\"],\n [18, \"Arme +4\t(+32 000 po)\"],\n [11, \"Arme +5\t(+50 000 po)\"],\n]\n\nobj_arme_reroll = Weight()\nobj_arme_reroll.children = [c for c in obj_cac_dist.children]\n\nobj_cac_dist << [\n [14, obj_arme_spe],\n # reroll and add a special property\n [37, Sequence() << [\n obj_arme_reroll,\n Title(\"Propriété Cac\", spe_cac),\n Title(\"Propriété Dist\", spe_dist)]]\n]\n\n################ AUTRES\n\nobj_potion = Weight() << [\n [20, \"Sort de niveau 2 (300 po)\"],\n [80, \"Sort de niveau 3 (750 po)\"],\n]\n\nobj_anneaux = Interval(d100) << [\n [ 3, 7, \"Protection +3 (18 000 po)\"],\n [ 8, 10, \"Stockage de sorts mineurs (18 000 po)\"],\n [11, 15, \"Invisibilité (20 000 po)\"],\n [16, 19, \"Arcanes (premiers) (20 000 po)\"],\n [20, 25, \"Esquive totale (25 000 po)\"],\n [26, 28, \"Rayons X (25 000 po)\"],\n [29, 32, \"Clignotement (27 000 po)\"],\n [33, 39, \"Résistance aux énergies destructives, majeur (28 000 po)\"],\n [40, 49, \"Protection +4 (32 000 po)\"],\n [50, 55, \"Arcanes (deuxièmes) (40 000 po)\"],\n [56, 60, \"Liberté de mouvement (40 000 po)\"],\n [61, 63, \"Résistance aux énergies destructives, suprême (44 000 po)\"],\n [64, 65, \"Protection mutuelle (une paire) (50 000 po)\"],\n [66, 70, \"Protection +5 (50 000 po)\"],\n [71, 74, \"Feu d’étoiles (50 000 po)\"],\n [75, 79, \"Stockage de sorts (50 000 po)\"],\n [80, 83, \"Arcanes (troisièmes) (70 000 po)\"],\n [84, 86, \"Télékinésie (75 000 po)\"],\n [87, 88, \"Régénération (90 000 po)\"],\n [89, 91, \"Renvoi des sorts (100 000 po)\"],\n [92, 93, \"Arcanes (quatrièmes) (100 000 po)\"],\n [94, 94, \"Triple souhait (120 000 po)\"],\n [95, 95, \"Bon génie (125 000 po)\"],\n [96, 96, \"Contrôle des éléments (Air) (200 000 po)\"],\n [97, 97, \"Contrôle des éléments (Terre) (200 000 po)\"],\n [98, 98, \"Contrôle des éléments (Feu) (200 000 po)\"],\n [99, 99, \"Contrôle des éléments (Eau) (200 000 po)\"],\n [100, 100, \"Stockage de sorts supérieur (200 000 po)\"],\n]\n\nobj_sceptre = Interval(d100) << [\n [ 1, 4, \"Oblitération (11 000 po)\"],\n [ 5, 6, \"Métamagie modérée, Extension de portée (11 000 po)\"],\n [ 7, 8, \"Métamagie modérée, Extension de durée (11 000 po)\"],\n [ 9, 10, \"Métamagie modérée, Incantation silencieuse (11 000 po)\"],\n [11, 14, \"Merveilleux (12 000 po)\"],\n [15, 19, \"Python (13 000 po)\"],\n [20, 21, \"Extinction des feux (15 000 po)\"],\n [22, 25, \"Vipère (19 000 po)\"],\n [26, 30, \"Détection de l’hostilité (23 500 po)\"],\n [31, 36, \"Métamagie majeure, Extension de portée (24 500 po)\"],\n [37, 42, \"Métamagie majeure, Extension de durée (24 500 po)\"],\n [43, 48, \"Métamagie majeure, Incantation silencieuse (24 500 po)\"],\n [49, 53, \"Prestance (25 000 po)\"],\n [54, 58, \"Flétrissement (25 000 po)\"],\n [59, 64, \"Métamagie modérée, Extension d'effet (32 500 po)\"],\n [65, 69, \"Orage (33 000 po)\"],\n [70, 73, \"Métamagie mineure, Incantation rapide (35 000 po)\"],\n [74, 77, \"Annulation (37 000 po)\"],\n [78, 80, \"Absorption (50 000 po)\"],\n [81, 84, \"Grand fléau (50 000 po)\"],\n [85, 86, \"Métamagie modérée, Quintessence des sorts (54 000 po)\"],\n [87, 88, \"Suzeraineté (60 000 po)\"],\n [89, 90, \"Sécurité (61 000 po)\"],\n [91, 92, \"Seigneurs de la guerre (70 000 po)\"],\n [93, 94, \"Métamagie majeure, Extension d'effet (73 000 po)\"],\n [95, 96, \"Métamagie modérée, Incantation rapide (75 500 po)\"],\n [97, 98, \"Éternelle vigilance (85 000 po)\"],\n [99, 99, \"Métamagie majeure, Quintessence des sorts (121 500 po)\"],\n [100, 100, \"Métamagie majeure, Incantation rapide (170 000 po)\"],\n]\n\nobj_parchemin = Interval(d100) << [\n [ 1, 5, \"Sort de niveau 4 (700 po)\"],\n [ 6, 50, \"Sort de niveau 5 (1125 po)\"],\n [51, 70, \"Sort de niveau 6 (1650 po)\"],\n [71, 85, \"Sort de niveau 7 (2275 po)\"],\n [86, 95, \"Sort de niveau 8 (3000 po)\"],\n [96, 100, \"Sort de niveau 9 (3825 po)\"],\n]\n\nobj_baton = Interval(d100) << [\n [ 1, 3, \"Envoûtement (17 600 po)\"],\n [ 4, 9, \"Feu (18 950 po)\"],\n [10, 11, \"Grand essaim (22 800 po)\"],\n [12, 13, \"Altération de taille (26 150 po)\"],\n [14, 19, \"Guérison (29 600 po)\"],\n [20, 24, \"Givre (41 400 po)\"],\n [25, 31, \"Clarté (51 500 po)\"],\n [32, 38, \"Défense (62 000 po)\"],\n [39, 45, \"Abjuration (82 000 po)\"],\n [46, 50, \"Invocation (82 000 po)\"],\n [51, 55, \"Divination (82 000 po)\"],\n [56, 60, \"Enchantement (82 000 po)\"],\n [61, 65, \"Évocation (82 000 po)\"],\n [66, 70, \"Illusion (82 000 po)\"],\n [71, 75, \"Nécromancie (82 000 po)\"],\n [76, 80, \"Transmutation (82 000 po)\"],\n [81, 85, \"Pierre et terre (85 800 po)\"],\n [86, 90, \"Forêt profonde (100 400 po)\"],\n [91, 95, \"Vie (109 400 po)\"],\n [96, 98, \"Transport (206 900 po)\"],\n [99, 100, \"Surpuissance (235 000 po)\"],\n]\n\nobj_baguette = Weight() << [\n [60, \"Sort de niveau 2 (4 500 po)\"],\n [40, \"Sort de niveau 3 (11 250 po)\"]\n]\n\nobj_merveilleux = Weight() << [\n [\"Chaînes dimensionnelles (28 000 po)\"],\n [\"Statuette merveilleuse (destrier d’obsidienne) (28 500 po)\"],\n [\"Timbales de panique (30 000 po)\"],\n [\"Pierre ioun (prisme orange) (30 000 po)\"],\n [\"Pierre ioun (prisme vert pâle) (30 000 po)\"],\n [\"Lanterne révélatrice (30 000 po)\"],\n [\"Amulette d’armure naturelle (+4) (32 000 po)\"],\n [\"Amulette d’antidétection (35 000 po)\"],\n [\"Tapis volant (1 50 m x 3 m) (35 000 po)\"],\n [\"Traité de création des golems de fer (35 000 po)\"],\n [\"Ceinturon de force de géant (+6) (36 000 po)\"],\n [\"Ceinturon de dextérité du chat (+6) (36 000 po)\"],\n [\"Ceinturon de constitution de l’ours (+6) (36 000 po)\"],\n [\"Bracelets d’armure (+6) (36 000 po)\"],\n [\"Bandeau de belle allure (+6) (36 000 po)\"],\n [\"Bandeau d’inspiration (+6) (36 000 po)\"],\n [\"Bandeau d’intelligence (+6) (36 000 po)\"],\n [\"Pierre ioun (prisme violet vif) (36 000 po)\"],\n [\"Perle de thaumaturge (sort du 6e niveau) (36 000 po)\"],\n [\"Scarabée de protection (38 000 po)\"],\n [\"Ceinturon de puissance de géant (+4) (40 000 po)\"],\n [\"Bandeau de prouesse mentale (+4) (40 000 po)\"],\n [\"Pierre ioun (ellipsoïde vert et lavande) (40 000 po)\"],\n [\"Anneaux de transport (40 000 po)\"],\n [\"Boule de cristal (42 000 po)\"],\n [\"Traité de création des golems de pierre monumentaux (44 000 po)\"],\n [\"Amulette des poings invincibles (+3) (36 000 po)\"],\n [\"Chapelet de prières (courant) (45 800 po)\"],\n [\"Orbe des tempêtes (48 000 po)\"],\n [\"Bottes de téléportation (49 000 po)\"],\n [\"Bracelets d’armure (+7) (49 000 po)\"],\n [\"Perle de thaumaturge (sort du 7e niveau) (49 000 po)\"],\n [\"Amulette d’armure naturelle (+5) (50 000 po)\"],\n [\"Cape de déplacement (supérieure) (50 000 po)\"],\n [\"Boule de cristal (détection de l’invisibilité) (50 000 po)\"],\n [\"Cor du Valhalla (50 000 po)\"],\n [\"Boule de cristal (détection des pensées) (51 000 po)\"],\n [\"Ailes de vol (54 000 po)\"],\n [\"Cape éthérée (55 000 po)\"],\n [\"Forteresse instantanée (55 000 po)\"],\n [\"Manuel de vitalité (+2) (55 000 po)\"],\n [\"Manuel de remise en forme (+2) (55 000 po)\"],\n [\"Manuel de coordination physique (+2) (55 000 po)\"],\n [\"Traité de perspicacité (+2) (55 000 po)\"],\n [\"Traité d’autorité et d’influence (+2) (55 000 po)\"],\n [\"Traité de compréhension (+2) (55 000 po)\"],\n [\"Yeux de charme (56 000 po)\"],\n [\"Robe étoilée (58 000 po)\"],\n [\"Tapis volant (3 m x 3 m) (60 000 po)\"],\n [\"Crâne des ténèbres (60 000 po)\"],\n [\"Cube de force (62 000 po)\"],\n [\"Ceinturon de la perfection physique (+4) (64 000 po)\"],\n [\"Bracelets d’armure (+8) (64 000 po)\"],\n [\"Bandeau de supériorité mentale (+4) (64 000 po)\"],\n [\"Perle de thaumaturge (sort du 8e niveau) (64 000 po)\"],\n [\"Boule de cristal (télépathie) (70 000 po)\"],\n [\"Cor de dévastation supérieur (70 000 po)\"],\n [\"Perle de thaumaturge (2 sorts) (70 000 po)\"],\n [\"Casque de téléportation (73 500 po)\"],\n [\"Gemme de vision (75 000 po)\"],\n [\"Robe d’archimage (75 000 po)\"],\n [\"Chasuble de la foi (76 000 po)\"],\n [\"Amulette des poings invincibles (+4) (64 000 po)\"],\n [\"Boule de cristal (vision lucide) (80 000 po)\"],\n [\"Perle de thaumaturge (sort du 9e niveau) (81 000 po)\"],\n [\"Puits des mondes (82 000 po)\"],\n [\"Manuel de coordination physique (+3 ) (82 500 po)\"],\n [\"Manuel de remise en forme (+3) (82 500 po)\"],\n [\"Manuel de vitalité (+3) (82 500 po)\"],\n [\"Traité d’autorité et d’influence (+3) (82 500 po)\"],\n [\"Traité de compréhension (+3) (82 500 po)\"],\n [\"Traité de perspicacité (+3) (82 500 po)\"],\n [\"Submersible du crabe (90 000 po)\"],\n [\"Ceinturon de puissance de géant (+6) (90 000 po)\"],\n [\"Bandeau de prouesse mentale (+6) (90 000 po)\"],\n [\"Écharpe de résistance à la magie (90 000 po)\"],\n [\"Miroir d’opposition (92 000 po)\"],\n [\"Chapelet de prières (majeur) (92 500 po)\"],\n [\"Manuel de coordination physique (+4) (110 000 po)\"],\n [\"Manuel de remise en forme (+4) (110 000 po)\"],\n [\"Manuel de vitalité (+4) (110 000 po)\"],\n [\"Traité d’autorité et d’influence (+4) (110 000 po)\"],\n [\"Traité de compréhension (+4) (110 000 po)\"],\n [\"Traité de perspicacité (+4) (110 000 po)\"],\n [\"Amulette des plans (120 000 po)\"],\n [\"Robe de vision totale (120 000 po)\"],\n [\"Amulette des poings invincibles (100 000 po)\"],\n [\"Casque de mille feux (125 000 po)\"],\n [\"Manuel de coordination physique (+5) (137 500 po)\"],\n [\"Manuel de remise en forme (+5) (137 500 po)\"],\n [\"Manuel de vitalité (+5) (137 500 po)\"],\n [\"Traité d’autorité et d’influence (+5) (137 500 po)\"],\n [\"Traité de compréhension (+5) (137 500 po)\"],\n [\"Traité de perspicacité (+5) (137 500 po)\"],\n [\"Ceinturon de la perfection physique (+6) (144 000 po)\"],\n [\"Bandeau de supériorité mentale (+6) (144 000 po)\"],\n [\"Urne du mauvais génie (145 000 po)\"],\n [\"Cube des plans (164 000 po)\"],\n [\"Flasque de fer (170 000 po)\"],\n [\"Miroir d’emprisonnement (200 000 po)\"],\n]\n\n################ ROOT\n\nroot = Weight() << [\n [10, Title(\"Armure\", obj_bouclier_armure)],\n [10, Title(\"Arme\", obj_cac_dist)],\n [ 5, Title(\"Potion\", obj_potion)],\n [10, Title(\"Anneau\", obj_anneaux)],\n [10, Title(\"Sceptre\", obj_sceptre)],\n [10, Title(\"Parchemin\", obj_parchemin)],\n [20, Title(\"Baton\", obj_baton)],\n [ 5, Title(\"Baguette\", obj_baguette)],\n [20, Title(\"Objet Merveilleux\", obj_merveilleux)],\n]\n\ngeneration = Generator(root)\ngeneration.execute()\ngeneration.print_to_console()\n","repo_name":"Ravath/MightyGeneratorPython","sub_path":"generators/pathfinder/puissant.py","file_name":"puissant.py","file_ext":"py","file_size_in_byte":18535,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"7902580316","text":"\"\"\"\"\nGiven a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.\n\nNote: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().\n\n\ns consists of digits, '+', '-', '(', ')', and ' '.\n\nCare about unary operation (-1)\n\n-1 + 2\n\nwe can think of the minus as always applied to the element on the right, and always do additions\n\n\nstacks are usually the way to go\n\nnums: List[int] = [\n-1\n\n\n]\n\n\n\nops: List[str] = [\n\n]\n\nwhen we intert a number we check if there is already an operator, if there is we apply it (if no other number we just apply on the number (op1 * num))\n\n- (1 + 1) - ((3 + 2) - 1)\n\n\nnums: List[int] = [\n-2 | 4\n\n]\n\n\n\nops: List[str] = [\n- \n]\n\nmaybe use recursion when we find an opening parenthesis\n use a start Dict[str, int] {'value': 0} to keep track of where the iteration is\nwhen we see the closing parenthesis we return the value on the stack\n\n\nO(n) time complexity\nO(n) space complexity\n\"\"\"\nimport dataclasses\nfrom typing import List, Dict, Callable\n\n\nOPS: Dict[str, Callable] = {\n '+': lambda x, y: x + y,\n '-': lambda x, y: x - y,\n}\n \n\n@dataclasses.dataclass\nclass Pointer:\n start: int = 0\n\n\nclass Solution:\n def calculate(self, equation: str) -> int:\n return solve(equation, Pointer())\n\n\ndef solve(equation: str, start: Pointer) -> int:\n if start.start >= len(equation):\n return 0\n ops: List[str] = []\n nums: List[int] = []\n while start.start < len(equation):\n curr: str = equation[start.start]\n start.start += 1\n if curr == ' ':\n continue\n if curr in OPS:\n ops.append(curr)\n elif curr == ')':\n return nums[0]\n elif curr == '(':\n apply_number(solve(equation, start), ops, nums)\n else:\n number: int = int(curr)\n while (start.start < len(equation) and \n equation[start.start].isdigit()):\n number *= 10\n number += int(equation[start.start])\n start.start += 1\n apply_number(number, ops, nums)\n return nums[0]\n\n\ndef apply_number(number: int, ops: List[str], nums: List[int]) -> None:\n if not ops:\n nums.append(number)\n return\n left: int = nums.pop() if nums else 0\n nums.append(OPS[ops.pop()](left, number))\n\n","repo_name":"JadielTeofilo/General-Algorithms","sub_path":"src/leetcode/224_basic_calculator.py","file_name":"224_basic_calculator.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"7787370491","text":"#!/usr/bin/env python3\nfrom collections import defaultdict\nimport sys\n\normask = 0\nfmask = 0\n\ndone = 0\nmemory = defaultdict(int)\nfor line in sys.stdin:\n if line.startswith('mask'):\n mstr = line.split()[2]\n ormask = fmask = 0\n for c in mstr:\n ormask = 2 * ormask\n fmask = 2 * fmask + 1\n if c == '1':\n ormask += 1\n elif c == 'X':\n fmask -= 1\n ormask += 1\n else:\n ws = line.replace('[',' ').replace(']',' ').split()\n addr = int(ws[1])\n val = int(ws[3])\n f = fmask\n while True:\n fa = (addr | ormask) & f\n memory[fa] = val\n if f == 2**36-1:\n break\n f = (f + 1) | fmask\n done += 1\nans = sum(v for v in memory.values())\nprint(ans)\n","repo_name":"rgrig/aoc-2020","sub_path":"py/d14.2.py","file_name":"d14.2.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"35144498140","text":"text = \"\"\"Education is not the learning of facts\nbut the training of the mind to think\n\n– Albert Einstein\"\"\"\n\nprepositions = {\"as\", \"but\", \"by\", \"down\", \"for\", \"in\", \"of\", \"on\", \"to\", \"with\"}\n\n \nlstWords=list(text.split())\nsetlst=set(lstWords)\npreps_used=setlst.intersection(prepositions)\nprint(preps_used)","repo_name":"kpverg/pyLEssons","sub_path":"sets/CodingEx.py","file_name":"CodingEx.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"43880179075","text":"import copy\nimport struct\nimport sys\n\n\n##\n# @brief The statistics class used to load and pre-process ROOT-Sim statistics files\n#\n# If you configured ROOT-Sim to produce a statistics file, a binary file will be generated.\n# You can use the facilities offered by this class to efficiently load those statistics.\nclass RSStats:\n def _pattern_unpack(self, ptrn):\n ptrn_size = struct.calcsize(ptrn)\n data_parse = self._data[self._data_idx:ptrn_size + self._data_idx]\n self._data_idx += ptrn_size\n ret = struct.unpack((\">\" if self.big_endian else \"<\") + ptrn, data_parse)\n return ret\n\n def _metric_names_load(self):\n metric_names = []\n n_stats = self._pattern_unpack(\"q\")[0]\n for _ in range(n_stats):\n raw_name_len = self._pattern_unpack(\"B\")[0]\n raw_name = self._pattern_unpack(f\"{raw_name_len}s\")[0]\n metric_name = raw_name.decode(\"utf-8\").rstrip('\\0')\n metric_names.append(metric_name)\n self._metrics[metric_name] = []\n return metric_names\n\n def _threads_unpack(self):\n metrics_len = len(self.metrics)\n n_stats = self._pattern_unpack(\"q\")[0] // (metrics_len * 8)\n t_stats_fmt = str(metrics_len) + \"Q\"\n ret = []\n for _ in range(n_stats):\n ret.append(self._pattern_unpack(t_stats_fmt))\n return ret\n\n def _nodes_stats_load(self):\n nodes_count = self._pattern_unpack(\"q\")[0]\n for _ in range(nodes_count):\n glob_stats = self._pattern_unpack(\"9Q\")\n n_threads = glob_stats[0]\n self.threads_count.append(n_threads)\n n_stats = self._pattern_unpack(\"q\")[0] // 16\n node_stats = []\n for _ in range(n_stats):\n node_stats.append(self._pattern_unpack(\"dQ\"))\n\n threads_stats = []\n for _ in range(n_threads):\n threads_stats.append(self._threads_unpack())\n\n self.all_stats.append((glob_stats, node_stats, threads_stats))\n\n def _truncate_to_last_gvt(self):\n min_gvts = len(self.all_stats[0][1])\n for _, node_stats, threads_stats in self.all_stats:\n min_gvts = min(len(node_stats), min_gvts)\n for t_stats in threads_stats:\n min_gvts = min(len(t_stats), min_gvts)\n\n ret = []\n for glob_stats, node_stats, threads_stats in self.all_stats:\n t_node_stats = node_stats[:min_gvts]\n t_threads_stats = []\n for t_stats in threads_stats:\n t_threads_stats.append(t_stats[:min_gvts])\n ret.append((glob_stats, t_node_stats, t_threads_stats))\n\n self.all_stats = ret\n\n ##\n # @brief Construct a new RSStats object\n # @param self the RSStats instance being constructed\n # @param rs_stats_file the path of the binary statistics file generated by ROOT-Sim\n def __init__(self, rs_stats_file):\n with open(rs_stats_file, 'rb') as f:\n self._data = f.read()\n\n self._data_idx = 0\n self.big_endian = True\n magic_number = self._pattern_unpack(\"H\")[0]\n if magic_number == 61455 or magic_number == 4080:\n self.big_endian = magic_number == 61455\n else:\n raise RuntimeWarning(\"Parsing failed, wrong initial magic number\")\n\n self._metrics = {}\n metric_names = self._metric_names_load()\n\n self.threads_count = []\n self.all_stats = []\n self._nodes_stats_load()\n\n if len(self._data) != self._data_idx:\n raise RuntimeWarning(\"Parsing failed, there's garbage at the end\")\n\n self._gvts = []\n self._truncate_to_last_gvt()\n\n self._global_measures = {\n \"lps\": [],\n \"maximum_resident_set\": [],\n \"node_init_time\": [],\n \"worker_threads_init_time\": [],\n \"processing_time\": [],\n \"worker_threads_fini_time\": [],\n \"node_fini_time\": [],\n \"node_total_time\": [],\n \"node_total_hr_time\": [],\n \"resident_set\": []\n }\n for triple in self.all_stats:\n glob_stats, node_stats, threads_stats = triple\n\n self._global_measures[\"lps\"].append(glob_stats[1])\n self._global_measures[\"maximum_resident_set\"].append(glob_stats[2])\n self._global_measures[\"node_init_time\"].append(glob_stats[3])\n self._global_measures[\"worker_threads_init_time\"].append(glob_stats[4] - glob_stats[3])\n self._global_measures[\"processing_time\"].append(glob_stats[5] - glob_stats[4])\n self._global_measures[\"worker_threads_fini_time\"].append(glob_stats[6] - glob_stats[5])\n self._global_measures[\"node_fini_time\"].append(glob_stats[7] - glob_stats[6])\n self._global_measures[\"node_total_time\"].append(glob_stats[7] - glob_stats[3])\n self._global_measures[\"node_total_hr_time\"].append(glob_stats[8])\n\n mem = []\n for i, (gvt, crs_mem) in enumerate(node_stats):\n if len(self._gvts) <= i:\n self._gvts.append(gvt)\n elif self._gvts[i] != gvt:\n raise RuntimeWarning(\"Parsing failed, inconsistent GVTs across nodes and/or threads\")\n\n mem.append(crs_mem)\n\n self._global_measures[\"resident_set\"].append(mem)\n\n for j, metric_name in enumerate(metric_names):\n metric_n_stat = []\n for t_stat in threads_stats:\n metric_t_stat = []\n for tup in t_stat:\n metric_t_stat.append(tup[j])\n metric_n_stat.append(metric_t_stat)\n\n self._metrics[metric_name].append(metric_n_stat)\n\n ##\n # @brief Get the GVT values\n # @return a list containing the computed GVTs (Global Virtual Times) in ascending order\n @property\n def gvts(self):\n return list(self._gvts)\n\n ##\n # @brief Get the real time values\n # @return a list containing the computed real times in ascending order\n def rts(self, reduction=min):\n real_times = self._metrics[\"gvt real time\"]\n ret = []\n for i in range(len(self._gvts)):\n t = []\n for node_stats in real_times:\n for thread_stats in node_stats:\n t.append(thread_stats[i])\n ret.append(reduction(t))\n return ret\n\n ##\n # @brief Get the thread-specific metric names\n # @return a list containing the metric names that you can use in #thread_metric_get()\n @property\n def metrics(self):\n return list(self._metrics)\n\n ##\n # @brief Get the node-specific statistics\n # @return a dictionary containing node-specific statistics\n # TODO more thorough description of what we have here\n @property\n def nodes_stats(self):\n return self._global_measures\n\n @property\n def nodes_count(self):\n return len(self.threads_count)\n\n ##\n # @brief Get the thread-specific metric values\n # @return a list of values\n # FIXME: much more complicated, explain it!\n # TODO: optionally provide stats normalized by real-time\n def thread_metric_get(self, metric, aggregate_gvts=False, aggregate_threads=False, aggregate_nodes=False):\n if metric not in self._metrics:\n raise RuntimeError(f\"Asked stats for the non-existing thread_metric {metric}\")\n\n if aggregate_nodes:\n aggregate_threads = True\n\n this_stats = copy.deepcopy(self._metrics[metric])\n\n if aggregate_gvts:\n for nstats in this_stats:\n for i, _ in enumerate(nstats):\n nstats[i] = sum(nstats[i])\n\n if aggregate_threads:\n for i, _ in enumerate(this_stats):\n this_stats[i] = sum(this_stats[i])\n\n if aggregate_nodes:\n this_stats = sum(this_stats)\n else:\n if aggregate_threads:\n for i, _ in enumerate(this_stats):\n gvt_stats = [0] * len(self._gvts)\n for rstats in this_stats[i]:\n for j, val in enumerate(rstats):\n gvt_stats[j] += val\n this_stats[i] = gvt_stats\n\n if aggregate_nodes:\n gvt_stats = [0] * len(self._gvts)\n for nstats in this_stats:\n for j, val in enumerate(nstats):\n gvt_stats[j] += val\n this_stats = gvt_stats\n\n return this_stats\n\n\n# Produce a boring textual report\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Please, supply the name of the raw statistics file!\", file=sys.stderr)\n exit(-1)\n\n stats = RSStats(sys.argv[1])\n\n simulation_time = stats.nodes_stats[\"node_total_time\"][0] / 1000000\n hr_ticks_per_second = stats.nodes_stats[\"node_total_hr_time\"][0] / simulation_time\n\n processed_msgs = stats.thread_metric_get(\"processed messages\", aggregate_nodes=True, aggregate_gvts=True)\n anti_msgs = stats.thread_metric_get(\"anti messages\", aggregate_nodes=True, aggregate_gvts=True)\n rollback_msgs = stats.thread_metric_get(\"rolled back messages\", aggregate_nodes=True, aggregate_gvts=True)\n silent_msgs = stats.thread_metric_get(\"silent messages\", aggregate_nodes=True, aggregate_gvts=True)\n rollbacks = stats.thread_metric_get(\"rollbacks\", aggregate_nodes=True, aggregate_gvts=True)\n checkpoints = stats.thread_metric_get(\"checkpoints\", aggregate_nodes=True, aggregate_gvts=True)\n msgs_cost = stats.thread_metric_get(\"processed messages time\", aggregate_nodes=True, aggregate_gvts=True)\n checkpoints_cost = stats.thread_metric_get(\"checkpoints time\", aggregate_nodes=True, aggregate_gvts=True)\n recoveries_cost = stats.thread_metric_get(\"recovery time\", aggregate_nodes=True, aggregate_gvts=True)\n avg_log_size = stats.thread_metric_get(\"checkpoints size\", aggregate_nodes=True, aggregate_gvts=True) / \\\n checkpoints if checkpoints != 0 else 0\n\n avg_msg_cost = 0 if processed_msgs == 0 else msgs_cost / (processed_msgs * hr_ticks_per_second)\n avg_checkpoint_cost = 0 if checkpoints == 0 else checkpoints_cost / (checkpoints * hr_ticks_per_second)\n avg_recovery_cost = 0 if rollbacks == 0 else recoveries_cost / (rollbacks * hr_ticks_per_second)\n\n rollback_freq = 100 * rollbacks / processed_msgs if processed_msgs != 0 else 0\n rollback_len = rollback_msgs / rollbacks if rollbacks != 0 else 0\n efficiency = 100 * (processed_msgs - rollback_msgs) / processed_msgs if processed_msgs else 100\n\n peak_memory_usage = sum(stats.nodes_stats[\"maximum_resident_set\"])\n lps_count = sum(stats.nodes_stats[\"lps\"])\n\n if len(stats.gvts) == 0:\n avg_memory_usage = 0.0\n sim_speed = 0.0\n last_gvt = 0.0\n else:\n avg_memory_usage = sum([sum(t) for t in stats.nodes_stats[\"resident_set\"]]) / len(stats.gvts)\n last_gvt = stats.gvts[-1]\n sim_speed = last_gvt / len(stats.gvts)\n\n out_name = sys.argv[1][:-4] if sys.argv[1].endswith(\".bin\") else sys.argv[1]\n out_name = out_name + \".txt\"\n\n\n def fmt_size(num, is_binary=True):\n div = 1024.0 if is_binary else 1000.0\n post_unit = \"i\" if is_binary else \"\"\n\n if num == 0:\n return \"0\"\n\n if abs(num) < div:\n if abs(num) > 1:\n return f\"{num:3.1f}\"\n num *= div\n for unit in [\"m\", \"u\", \"n\"]:\n if abs(num) > 1:\n return f\"{num:3.1f}{unit}{post_unit}\"\n num *= div\n return f\"{num:3.1f}p{post_unit}\"\n\n num /= div\n for unit in [\"K\", \"M\", \"G\", \"T\", \"P\"]:\n if abs(num) < div:\n return f\"{num:.1f}{unit}{post_unit}\"\n num /= div\n\n return f\"{num:.1f}P{post_unit}\"\n\n\n with open(out_name, \"w+\") as f:\n f.write(f\"TOTAL SIMULATION TIME ..... : {fmt_size(simulation_time, False)}s\\n\")\n f.write(f\"TOTAL KERNELS ............. : {stats.nodes_count}\\n\")\n f.write(f\"TOTAL_THREADS ............. : {sum(stats.threads_count)}\\n\")\n f.write(f\"TOTAL_LPs ................. : {lps_count}\\n\")\n f.write(f\"TOTAL EXECUTED EVENTS ..... : {processed_msgs + silent_msgs}\\n\")\n f.write(f\"TOTAL COMMITTED EVENTS..... : {processed_msgs - rollback_msgs}\\n\")\n f.write(f\"TOTAL REPROCESSED EVENTS... : {rollback_msgs}\\n\")\n f.write(f\"TOTAL SILENT EVENTS........ : {silent_msgs}\\n\")\n f.write(f\"TOTAL ROLLBACKS EXECUTED... : {rollbacks}\\n\")\n f.write(f\"TOTAL ANTIMESSAGES......... : {anti_msgs}\\n\")\n f.write(f\"ROLLBACK FREQUENCY......... : {rollback_freq:.2f}%\\n\")\n f.write(f\"ROLLBACK LENGTH............ : {rollback_len:.2f}\\n\")\n f.write(f\"EFFICIENCY................. : {efficiency:.2f}%\\n\")\n f.write(f\"AVERAGE EVENT COST......... : {fmt_size(avg_msg_cost, False)}s\\n\")\n f.write(f\"AVERAGE CHECKPOINT COST.... : {fmt_size(avg_checkpoint_cost, False)}s\\n\")\n f.write(f\"AVERAGE RECOVERY COST...... : {fmt_size(avg_recovery_cost, False)}s\\n\")\n f.write(f\"AVERAGE LOG SIZE........... : {fmt_size(avg_log_size)}B\\n\")\n f.write(f\"LAST COMMITTED GVT ........ : {last_gvt}\\n\")\n f.write(f\"NUMBER OF GVT REDUCTIONS... : {len(stats.gvts)}\\n\")\n f.write(f\"SIMULATION TIME SPEED...... : {sim_speed}\\n\")\n f.write(f\"AVERAGE MEMORY USAGE....... : {fmt_size(avg_memory_usage)}B\\n\")\n f.write(f\"PEAK MEMORY USAGE.......... : {fmt_size(peak_memory_usage)}B\\n\")\n","repo_name":"ROOT-Sim/core","sub_path":"src/log/parse/rootsim_stats.py","file_name":"rootsim_stats.py","file_ext":"py","file_size_in_byte":13604,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"16078934929","text":"# -*- coding: utf-8 -*-\n\nimport json\nfrom django import forms\nfrom django.forms.utils import flatatt\nfrom django.utils.html import format_html\nfrom django.utils.safestring import mark_safe\n\n\nclass NullCharField(forms.CharField):\n def clean(self, value):\n cleaned = super(NullCharField, self).clean(value)\n return cleaned if len(cleaned) else None\n\n\nclass FullTextArea(forms.CharField):\n widget = forms.Textarea(attrs={'class': 'span12'})\n\n\nclass SearchField(forms.CharField):\n widget = forms.TextInput(attrs={\n 'class': 'search-query',\n 'autocomplete': 'off',\n 'placeholder': '',\n })\n\n\nclass ChoiceField(forms.ChoiceField):\n def __init__(self, *args, **kwargs):\n super(ChoiceField, self).__init__(*args, **kwargs)\n self.widget.attrs['class'] = 'span12'\n\n\nclass TextInput(forms.TextInput):\n def __init__(self, *args, **kwargs):\n super(TextInput, self).__init__(*args, **kwargs)\n self.attrs['class'] = 'span12'\n\n\nclass AutocompleteCharField(forms.CharField):\n widget = forms.TextInput(attrs={\n 'class' : \"input typeahead\",\n 'data-provide' : \"typeahead\"\n })\n\n def __init__(self, values, *args, **kwargs):\n super(AutocompleteCharField, self).__init__(*args, **kwargs)\n\n if not type(values) is str:\n values = json.dumps(list(values))\n\n self.widget.attrs['data-source'] = values\n\n\nclass AutocompleteTextarea(forms.Textarea):\n def __init__(self, rows=8, choices=None):\n super(AutocompleteTextarea, self).__init__()\n self.attrs = {\n 'rows': rows,\n 'class': \"span12 autocomplete\",\n 'data-source': json.dumps(choices)\n }\n\n\nclass BaseForm(forms.Form):\n required_css_class = \"required\"\n\n\nclass BaseModelForm(forms.ModelForm):\n required_css_class = \"required\"\n\n\nclass SearchFieldInput(forms.TextInput):\n\n def render(self, name, value, attrs=None):\n\n field = super(SearchFieldInput, self).render(name, value, attrs)\n final_attrs = self.build_attrs(attrs, name=name)\n\n output = format_html(u'''\n
\n {1}\n \n \n \n
\n ''', flatatt(final_attrs), field)\n\n return mark_safe(output)\n\n\nclass DatepickerInput(forms.DateInput):\n def __init__(self, *args, **kwargs):\n kwargs['format'] = \"%Y-%m-%d\"\n super(DatepickerInput, self).__init__(*args, **kwargs)\n\n def render(self, name, value, attrs=None):\n\n date_format = \"yyyy-MM-dd\"\n\n if \"format\" not in self.attrs:\n attrs['format'] = date_format\n\n if \"data-format\" not in self.attrs:\n attrs['data-format'] = date_format\n\n field = super(DatepickerInput, self).render(name, value, attrs)\n final_attrs = self.build_attrs(attrs, name=name)\n\n output = format_html(u'''\n
\n {1}\n \n \n \n
\n ''', flatatt(final_attrs), field)\n\n return mark_safe(output)\n\n\nclass DateTimePickerInput(forms.DateTimeInput):\n def __init__(self, *args, **kwargs):\n kwargs['format'] = \"%Y-%m-%d %H:%M\"\n super(DateTimePickerInput, self).__init__(*args, **kwargs)\n\n def render(self, name, value, attrs=None):\n\n date_format = \"yyyy-MM-dd hh:mm\"\n\n if \"data-format\" not in self.attrs:\n attrs['data-format'] = date_format\n if \"class\" not in self.attrs:\n attrs['class'] = 'input-medium'\n\n field = super(DateTimePickerInput, self).render(name, value, attrs)\n final_attrs = self.build_attrs(attrs, name=name)\n\n output = format_html(u'''\n
\n {1}\n \n \n \n
\n ''', flatatt(final_attrs), field)\n\n return mark_safe(output)\n","repo_name":"LetsUnlockiPhone/Servo","sub_path":"servo/forms/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4306,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"39666372004","text":"\n\nn=30\ncount = 0\n\nall=1\n\nfor i in range(1, n + 1):\n if i % 5 == 0:\n count += 1\n if i / 5 % 5 ==0:\n count+=1\n all*=i\n\n print(i,all)\nprint(count)","repo_name":"zcfnc/python_study","sub_path":"leetcode/leetcode_172.py","file_name":"leetcode_172.py","file_ext":"py","file_size_in_byte":177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"29544340554","text":"#!/usr/bin/python\n\nimport sys\nimport subprocess\nimport os\nimport re\n\ntask = \"\"\nif len(sys.argv) > 1:\n task = sys.argv[1]\n\n#if len(task) > 0:\n #task = \"*/\" + task\n\nsumed = 0.0\n\nfor root, dirs, files in os.walk(\".\"):\n for name in files:\n if task == name:\n fp = open(os.path.join(root, name), \"r\")\n line = fp.readline()\n while len(line) > 0: \n if \"Elapsed\" in line:\n m = re.match('.* ([\\d.]*) .*', line)\n if m:\n number = float(m.group(1))\n print(\"%.2f + %.2f (%s)\" % (sumed, number, os.path.join(root,name)))\n sumed = sumed + number\n line = fp.readline()\n\n\nprint('%.2f' % sumed)\n","repo_name":"DatGizmo/scripts","sub_path":"getBuildStats.py","file_name":"getBuildStats.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"40621354225","text":"import os\nimport csv\nfrom collections import Counter\n\ndef read_file():\n directory = \"/Users/Luke/Desktop/Python_work/T20_files/\"\n file_name = \"693009.csv\"\n f = open(\"{}ntb_male_csv/\".format(directory) + \"{}\".format(file_name), \"r\")\n csv_f = list(csv.reader(f))\n f.close()\n return csv_f\n\ndef info_grabber(csv_f):\n info_list = []\n info = {}\n #Adding useful information from spreadsheet to info list\n for row in csv_f:\n useless_rows = [\"gender\", \"season\", \"event\", \"city\"]\n if row[0] == \"info\":\n if row[1] not in useless_rows:\n info_list.append([row[1],row[2]])\n elif row[0] == \"ball\":\n break\n info_listed = [val for sublist in info_list for val in sublist]\n info[\"home team\"] = info_listed[1]\n info[\"away team\"] = info_listed[3]\n for i in range(3,len(info_listed)-1):\n if i % 2 == 0:\n info[info_listed[i]] = info_listed[i+1]\n print(info)\n\n #print(info)\n return info\n\ndef match_stats_grabber(csv_f, info):\n \"\"\"column_headings = [\"0 ball\", \"1 Innings\", \"2 Over\", \"3 Batting Team\",\n \"4 On-Strike Batter\", \"5 Off-Strike Batter\", \"6 Bowler\", \"7 Runs\",\n \"8 Extras\", \"9 Wides\", \"10 No-Ball\", \"11 Byes\", \"12 Leg-Byes\",\n \"13 Penalty\", \"14 How out\", \"15 Player Out\"]\"\"\"\n #runs_breakdown = []\n runs = {}\n scorecard = {}\n balls = {}\n how_out = {}\n team_total = {}\n #extras =\n #bowlers_figures =\n runs_dict = {}\n for row in csv_f:\n if row[0] != \"ball\":\n continue\n if row[0] == \"ball\":\n batter = row[4]\n team = row[3]\n if team not in team_total:\n team_total[team] = int(row[7]) + int(row[8])\n elif team in team_total:\n team_total[team] += int(row[7]) + int(row[8])\n if batter not in runs:\n runs[batter] = int(row[7])\n scorecard[batter] = \"{}\".format(row[7])\n elif batter in runs:\n runs[batter] += int(row[7])\n scorecard[batter] += \"{}\".format(row[7])\n else:\n print(\"Error in adding {}'s total\".format(batter))\n break\n #If not a wide, start counting deliveries\n if row[9] == \"\":\n if batter not in balls:\n balls[batter] = 1\n elif batter in balls:\n balls[batter] += 1\n elif batter not in balls:\n balls[batter] = 0\n if row[15] != \"\":\n how_out[batter] = row[14]\n\n###BREAK FOR LOOP###\n # This loop adds creates a breakdown of how they scored their runs and returns\n # an array with the batters name and the breakdown\n team_scores = [score for team,score in team_total.items()]\n\n#Neeed to add code for who batted first / won the toss and therefore if they\n#win do they win by wickets or runs\n#\"\"\" for team,score in team_total.items():\n# if team_scores[0] > team_scores[1]:\n# winning_margin = \"{} won by {} runs\".format(info[\"Home team\"])\n# #print(winning_margin)\"\"\"\n for batter_name,scores in scorecard.items():\n listed_scores = sorted(list(scores))\n breakdown = [[x,listed_scores.count(x)] for x in set(listed_scores)]\n #runs_breakdown.append([batter_name, sorted(breakdown)])\n runs_dict[batter_name] = sorted(breakdown)\n return\n\n\n\n\"\"\"def file_checker():\n \"\"\"\"\"\"Function checks whether file to add data to exists already or not,\n if not, it creates a new file ready\"\"\"\"\"\"\n file_number = 1\n file_check= os.path.isfile(\"{}Match_Files/match{}.csv\".format(directory, file_number))\n if file_check:\n return info_grabber()\n else:\n h = open(\"{}/Match_Files/match{}.csv\".format(directory, file_number), \"x\")\n print(\"else\")\n return info_grabber()\"\"\"\n\n\ndef build_file():\n print(\"hello world\")\n\nif __name__ == \"__main__\":\n x = read_file()\n y = info_grabber(x)\n (match_stats_grabber(x, y))\n","repo_name":"lukewhansford/NatwestT20BlastAnalysis","sub_path":"Cricket_data.py","file_name":"Cricket_data.py","file_ext":"py","file_size_in_byte":4013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7466832536","text":"import pygame\n\nimport game_object\n\n\nPLATFORM_WIDTH = 30\nPLATFORM_HEIGHT = 32\nPLATFORM_COLOUR = (255, 255, 255)\n\nstoppers = []\nplatforms = []\n\n\nclass Platform(game_object.GameObject):\n def __init__(self, x, y):\n super().__init__(x=x, y=y, width=PLATFORM_WIDTH, height=PLATFORM_HEIGHT, colour=PLATFORM_COLOUR)\n self.image = pygame.image.load(\"Platforms images/center.png\").convert_alpha()\n","repo_name":"4rutemu/PythonGame","sub_path":"platform.py","file_name":"platform.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"6924361","text":"from celery import shared_task\nfrom database.orm import Database\n\nfrom services.scraping import Scraping\n\n\n@shared_task()\ndef scraping_site_task() -> None:\n url = 'https://auto.ria.com/uk/search/?lang_id=4&page=0&countpage=100&indexName=auto&custom=1&abroad=2'\n \n database = Database()\n if database.count_cars() > 0:\n database.clear_table()\n \n Scraping(url, database).start_scraping()\n\n\n@shared_task()\ndef create_database_dump_task() -> None:\n database = Database()\n database.dump_database()\n database.clear_table()","repo_name":"Tezlaa/autoria_scraping","sub_path":"src/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"9199991291","text":"from crawlers import *\nimport json\nimport asyncio\nfrom motor.motor_asyncio import AsyncIOMotorClient\nfrom networks.proxy_management import ProxyPool\nimport unicodedata\nimport datetime\nimport multiprocessing\nfrom multiprocessing import Queue\nimport logging\nfrom threading import Thread\nimport time\nimport random\nimport copy\nimport os\nimport redis\nfrom database.mongodb import MongoDatabase\nfrom utilities.utils import save_string_json, extract_key_values, filter_uncasual_slug\n\ndef worker_crawl_app_info(queue, func, identifier, attempt, id_part, num_of_part):\n proxy_pool = ProxyPool(id_part=id_part, num_of_part=num_of_part)\n try:\n crawl_result = func(identifier, proxy_pool)\n queue.put((identifier, crawl_result))\n logging.info(f\"Worker APP: {identifier} completed successfully.\")\n except Exception as e:\n if attempt < 3:\n logging.warn(f\"Worker {identifier} raised an exception: {e}. Retrying...\")\n worker_crawl_app_info(queue, func, identifier, attempt + 1, id_part, num_of_part)\n else:\n logging.warn(f\"Worker {identifier} raised an exception: {e}. Giving up after 3 attempts.\")\n\n result = {}\n queue.put((identifier, result))\n\ndef multi_thread_crawl_app_info(app_slugs, batch_size=50):\n app_dict = dict()\n app_list = list(copy.deepcopy(app_slugs))\n \n while True:\n time.sleep(random.randint(1, 4))\n if len(app_list) == 0:\n break\n\n if len(app_list) < batch_size:\n batch_size = len(app_list)\n\n app_list_batch = app_list[:batch_size]\n app_list = app_list[batch_size:]\n \n queue = Queue()\n for i in range(len(app_list_batch)):\n app_slug = app_list_batch[i]\n t = Thread(target=worker_crawl_app_info, args=(queue, crawl_informaion_app_reviews, app_slug, 1, i, batch_size))\n t.start()\n\n num_of_input = 0\n while True:\n if not queue.empty():\n identifier, crawl_result = queue.get()\n app_dict[identifier] = crawl_result\n num_of_input += 1\n\n if num_of_input == len(app_list_batch):\n break\n \n return app_dict\n\ndef main():\n ALL_CATEGORIES = [\n 'category_finding_products',\n 'category_store_design',\n 'category_selling_products',\n 'category_orders_and_shipping',\n 'category_marketing_and_conversion',\n 'category_store_management'\n ]\n mongodtb = MongoDatabase()\n applications_collection = mongodtb.get_applications_collection()\n tracking_collection = mongodtb.get_tracking_collection()\n\n redis_sv = redis.Redis(host='localhost', port=6379, db=0)\n while True:\n logging.info(\"Waiting for homepage, category crawling..\")\n present_day = str(datetime.datetime.now().strftime(\"%d%m%Y\"))\n try:\n is_categories_running = int(redis_sv.get('categories_running').decode('utf-8'))\n except:\n is_categories_running = 1\n \n if os.path.exists(f\"data/{present_day}\"):\n if os.path.exists(f'data/{present_day}/category_store_management.json'):\n if not os.path.exists(f\"data/{present_day}/applications.json\"):\n if not is_categories_running:\n # redis_sv.delete('app_queue')\n slugs = []\n slug_to_short_desc_dict = {}\n for category in ALL_CATEGORIES:\n with open(f'data/{present_day}/{category}.json') as f:\n category_dict = json.load(f)\n for slug_dict in extract_key_values(category_dict, 'slug'):\n slugs.extend([slug for slug in slug_dict.keys() if not filter_uncasual_slug(slug)])\n slug_to_short_desc_dict.update(slug_dict)\n # slugs.extend([slug_dict for slug_dict in extract_key_values(category_dict, 'slug') if not filter_uncasual_slug(list(slug_dict.keys())[0])])\n\n slugs = list(set(slugs))\n print(f\"Number of slugs: {len(slugs)}\")\n\n app_dict_list = []\n\n crawling_app_time = time.time()\n for slug_app in slugs:\n time.sleep(random.randint(1, 4))\n try:\n app_in_dtb = applications_collection.find_one({\"slug\": slug_app})\n if app_in_dtb['last_updated'] == present_day:\n logging.info(\"App: \" + slug_app + \" already crawled today.\")\n continue\n\n proxy_pool = ProxyPool(id_part=random.randint(0,99), num_of_part=100)\n logging.info(\"Crawling app: \" + slug_app)\n app_dict = crawl_information_app(slug_app, proxy_pool)\n app_dict['slug'] = slug_app\n app_dict['last_updated'] = present_day\n app_dict['short_description'] = slug_to_short_desc_dict[slug_app]\n\n # Push finished app to redis\n redis_sv.lpush('app_queue', slug_app)\n if app_in_dtb is None:\n applications_collection.insert_one(app_dict)\n else:\n applications_collection.update_one({\"slug\": slug_app}, {\"$set\": app_dict})\n except Exception as e:\n logging.info(f\"{e} while crawling: {slug_app}\")\n continue\n\n app_dict_list.append(app_dict)\n\n logging.info(f\"Crawling {len(app_dict_list)} apps took {time.time() - crawling_app_time} seconds.\")\n save_string_json(f'data/{present_day}/applications.json', app_dict_list)\n # tracking_collection.update_one({\"date\": present_day}, {\n # \"$set\": {\"apps\": app_dict_list}\n # })\n time.sleep(1500)\n\nif __name__ == '__main__':\n main()","repo_name":"binhptit/shopify-crawler","sub_path":"src/run_applications.py","file_name":"run_applications.py","file_ext":"py","file_size_in_byte":6382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7827475279","text":"from SiemplifyUtils import output_handler\n# Imports\nfrom SiemplifyAction import SiemplifyAction\nfrom ZendeskManager import ZendeskManager\n\n\n@output_handler\ndef main():\n siemplify = SiemplifyAction()\n conf = siemplify.get_configuration(\"Zendesk\")\n user_email = conf['User Email Address']\n api_token = conf['Api Token']\n server_address = conf['Server Address']\n zendesk = ZendeskManager(user_email, api_token, server_address)\n\n ticket_id = siemplify.parameters['Ticket ID']\n macro_name = siemplify.parameters['Macro Title']\n ticket_data = zendesk.apply_macro_on_ticket(ticket_id, macro_name)\n\n if ticket_data:\n output_message = \"Successfully apply macro {0} on ticket #{1}\".format(macro_name, str(ticket_id))\n result_value = 'true'\n else:\n output_message = 'There was a problem applying macro {0} om ticket #{1}.'.format(macro_name, str(ticket_id))\n result_value = 'false'\n\n siemplify.end(output_message, result_value)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"chronicle/tip-marketplace","sub_path":"Integrations/Zendesk/ActionsScripts/ApplyMacrosOnTicket.py","file_name":"ApplyMacrosOnTicket.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"983133520","text":"\"\"\"\nListen for sensors one or more channels and store received messages.\n\"\"\"\n\nimport re\nimport sqlite3\nimport io\nimport time\nimport subprocess\nimport logging\nfrom ctypes import c_ubyte\n\nimport serial\nfrom smbus2 import SMBusWrapper\n\nBUSNUM = 1\nDEVICE_ADDR = 0x10\nI2C_READ_DELAY = 0.005\nI2C_WRITE_DELAY = 0.075\nLOOP_DELAY = 0.1\n\nlogging.basicConfig()\nlog = logging.getLogger()\nlog.setLevel(logging.INFO)\n\nclass I2CError(Exception):\n pass\n\nclass ChecksumError(Exception):\n pass\n\ndef i2c_write_int(busnum, address, number):\n time.sleep(I2C_WRITE_DELAY)\n try:\n assert number<=255\n with SMBusWrapper(busnum) as bus:\n bus.write_byte(address, c_ubyte(number))\n\n return True\n\n except IOError:\n log.error('Error writing to I2C device: {:d}, value: {}'.format(\n address, number))\n raise I2CError()\n\n except:\n raise\n\ndef i2c_read_array(busnum, address, size):\n time.sleep(I2C_READ_DELAY)\n with SMBusWrapper(busnum) as bus:\n arr = bus.read_i2c_block_data(address, 0, size)\n\n return arr\n\ndef i2c_read_string(busnum, address, nbytes):\n \"\"\"\n Return character data read from I2C.\n \"\"\"\n buff = []\n try:\n with SMBusWrapper(busnum) as bus:\n for i in range(nbytes+2):\n time.sleep(I2C_READ_DELAY)\n c = bus.read_byte(address)\n buff.append(c)\n\n except IOError:\n log.debug('Error reading string. device: {:d}'.format(address))\n raise I2CError()\n\n except:\n raise\n\n log.debug(buff)\n\n buff_checksum = buff[-2]<<8 | buff[-1]\n local_checksum = sum(buff[:-2])\n if buff_checksum!=local_checksum:\n log.error('Checksums do not match, buff: {}, local: {}'.format(\n buff_checksum, local_checksum))\n raise ChecksumError()\n\n s = ''.join([chr(v) for v in buff[:-2]])\n return s\n\ndef i2c_read_int(busnum, addr):\n try:\n with SMBusWrapper(busnum) as bus:\n time.sleep(I2C_READ_DELAY)\n data = bus.read_byte(addr)\n return int(data)\n\n except IOError:\n log.debug('Error reading int. device: :d{}'.format(addr))\n raise I2CError()\n\n except:\n raise\n\ndef listen_i2c(busnum, address, db):\n \"\"\"\n \"\"\"\n\n dbconn = sqlite3.connect(db)\n\n while True:\n time.sleep(LOOP_DELAY)\n try:\n if not i2c_write_int(busnum, address, 1):\n continue\n log.debug('Sent - 1')\n\n nbytes = i2c_read_int(busnum, address)\n if not nbytes:\n continue\n\n elif not nbytes>0:\n log.debug('Nothing to read - {}'.format(nbytes))\n continue\n\n # Signal the next transmit should be the message\n log.debug('Signal ready to read.')\n if not (i2c_write_int(busnum, address, 2)):\n continue\n\n log.debug('Read {} bytes'.format(nbytes))\n nretrys = 0\n while 1:\n try:\n msg = i2c_read_string(busnum, address, nbytes)\n\n except (I2CError, ChecksumError):\n msg = None\n\n except:\n raise\n\n if not msg is None:\n break\n #continue\n\n if nretrys<5:\n log.debug('Retry read - {}'.format(nretrys))\n # Signal to restart the current message\n i2c_write_int(busnum, address, 4)\n nretrys += 1\n\n else:\n log.warn('Error reading message.')\n break\n\n # Signal to advance the message queue\n #bus.write_byte(address, 3)\n i2c_write_int(busnum, address, 3)\n\n log.info('Packet: {}'.format(msg))\n\n data = parse_packet(msg)\n if not data:\n log.info('Bad packet: {}'.format(msg))\n continue\n\n net_id = data['net_id']\n unit_id = get_unit_id(net_id, dbconn)\n\n m = 'Net ID: {}, Unit: {}, Msg: {}'\n log.debug(m.format(net_id, unit_id, msg))\n\n insert_message(msg, unit_id, dbconn)\n\n except (KeyboardInterrupt, SystemExit):\n print('Exiting!')\n dbconn.close()\n raise\n\n except I2CError:\n log.error('I2C Error')\n #i2c_write_int(busnum, address, 0)\n continue\n\n except:\n dbconn.close()\n raise\n\n # Note: We will never get here if all exceptions re-raise\n dbconn.close()\n\ndef parse_packet(packet):\n fld_xref = {\n 'U':'net_id'\n , 'T':'temperature'\n , 'H':'humidity'\n , 'V':'volts'\n , 'C':'seq_num'\n }\n\n data = {}\n\n try:\n rx_seq, rx_time, packet = packet.split(',')\n data['rx_seq'] = rx_seq\n data['rx_time'] = rx_time\n\n except:\n raise IOError('Unexpected data structure. {}'.format(packet))\n\n flds = packet.split(';')\n for fld in flds:\n abv, value = fld.split(':')\n data[fld_xref[abv]] = value\n\n# unit_pat = re.compile('U:([0-9]{4});')\n# s = re.search(unit_pat, packet)\n# if not s:\n# return None\n#\n# data['net_id'] = s.groups()[0]\n\n return data\n\n# TODO: This needs to run in it's own thread or process.\ndef listen_serial(port, db, **kwargs):\n \"\"\"\n Listen on a serial port for sensor data packets.\n\n Args:\n port: Serial port to listen on.\n db: SQLite database to post data to.\n\n Addtional keyword arguments are passed to serial.Serial for\n port configuration.\n \"\"\"\n\n unit_pat = re.compile('U:([0-9]{4});')\n\n dbconn = sqlite3.connect(db)\n tty = serial.Serial(port\n , baudrate=9600\n , bytesize=serial.EIGHTBITS\n , parity=serial.PARITY_NONE\n , stopbits=serial.STOPBITS_ONE\n , timeout=1)\n sio = io.TextIOWrapper(io.BufferedRWPair(tty, tty), newline='\\r\\n')\n tty.reset_input_buffer()\n\n while True:\n try:\n msg = sio.readline().strip()\n # msg = sio.readline().decode('utf-8').strip()\n# s = re.search(unit_pat, msg)\n b = tty.read(size=2)\n print(b)\n# net_id = s.groups()[0]\n# unit_id = get_unit_id(net_id, dbconn)\n\n# print(net_id, unit_id, msg)\n# insert_message(msg, unit_id, dbconn)\n\n except (KeyboardInterrupt, SystemExit):\n print('Exiting!')\n dbconn.close()\n tty.close()\n raise\n\n except:\n dbconn.close()\n tty.close()\n raise\n\n # Note: We will never get here if all exceptions re-raise\n dbconn.close()\n tty.close()\n\ndef insert_message(msg, unit_id, conn):\n \"\"\"\n Insert a message into the database.\n \"\"\"\n sql = \"\"\"\n insert into messages\n (unit_id, message_string)\n values('{unit_id}','{msg}')\n \"\"\"\n try:\n conn.execute(sql.format(**locals()))\n log.debug('Messages stored to DB, {}'.format(msg))\n\n except:\n log.error('Error inserting message {} for unit {}'.format(msg, unit_id))\n conn.rollback()\n\n conn.commit()\n\ndef get_unit_id(net_id, conn):\n \"\"\"\n Return the unit_id matching a net_id\n \"\"\"\n\n sql = \"\"\"select unit_id from units where net_id='{}'\"\"\".format(net_id)\n cur = conn.cursor()\n try:\n cur.execute(sql)\n unit_id = cur.fetchone()[0]\n\n except:\n sql = \"\"\"insert into units (net_id) values('{}')\"\"\".format(net_id)\n cur.execute(sql)\n cur.close()\n conn.commit()\n unit_id = get_unit_id(net_id, conn)\n\n return unit_id\n\ndef init_db(path):\n \"\"\"\n Initialize the database schema.\n \"\"\"\n\n conn = sqlite3.connect(path)\n\n try:\n conn.execute('drop table messages')\n conn.execute('drop table units')\n\n except:\n pass\n\n units_sql = \"\"\"\n create table units (\n unit_id text primary key default (lower(hex(randomblob(16))))\n , net_id varchar(10) not null\n , label varchar(30)\n , loc_name varchar(30)\n , loc_point varchar(100)\n )\n \"\"\"\n conn.execute(units_sql)\n\n messages_sql = \"\"\"\n create table messages (\n message_id text primary key default (lower(hex(randomblob(16))))\n , unit_id text not null\n , insert_timestamp real default CURRENT_TIMESTAMP\n , message_string text not null\n , foreign key (message_id)\n references units(unit_id)\n on delete cascade\n )\n \"\"\"\n\n conn.execute(messages_sql)\n\n conn.close()\n\nif __name__=='__main__':\n db = '/home/pi/rfnetx/pyrfnetx/rfnetx_data.sqlite'\n init_db(db)\n\n listen_i2c(BUSNUM, DEVICE_ADDR, db)\n\n","repo_name":"tharen/rfnetwx","sub_path":"pyrfnetx/rfreceive.py","file_name":"rfreceive.py","file_ext":"py","file_size_in_byte":8910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"32141960348","text":"import csv\nimport json\nimport os\n\n\n# Diese Methode kann JSON und CSV Dateien lesen und als Liste zurückgeben.\ndef read(path, type):\n try:\n list_of_dicts = []\n if type == \"csv\":\n with open(path, \"r\", newline='', encoding=\"utf8\") as file:\n reader = csv.DictReader(file)\n for v in reader:\n list_of_dicts.append(v)\n return list_of_dicts\n elif type == \"json\":\n with open(path) as file:\n list_of_dicts = json.load(file)\n return list_of_dicts\n except IOError:\n print('An error occured trying to read the file.')\n\n\ndef write(path, list_of_dicts):\n try:\n with open(path, \"w\", newline='', encoding=\"utf8\") as file:\n fieldnames=['Anrede', 'Name', 'Vorname', 'Straße', 'Hausnummer', 'PLZ', 'Stadt', 'Telefon', 'Mobil', 'Email']\n writer = csv.DictWriter(file, fieldnames, extrasaction='ignore')\n writer.writeheader()\n writer.writerows(list_of_dicts)\n\n except IOError:\n print('An error occured trying to write the file.')\n\n\ndef open_file(path):\n os.system(\"open \" + path)\n\n\ndef get_all_csv_and_json():\n # Liste mit sämtlichen Dateien ertsellen, die sich im selben Ordner befinden.\n dir_list = os.listdir('.')\n new_list = []\n # Jeden Dateinamen mit der Endung '.csv' oder '.json' der Liste new_list hinzufügen.\n for file in dir_list:\n if file.find(\".csv\") > -1 or file.find(\".json\") > -1:\n new_list.append(file)\n\n index = 0\n for file in new_list:\n index = index + 1\n print(str(index) + \": \" + file)\n return new_list\n\n","repo_name":"MaxBotta/Vertiefung_Programmierung","sub_path":"Max/Adressbuch/crud.py","file_name":"crud.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"13513686048","text":"\"\"\"analysis of results using signed distance functions to crop the segments to a certain geometry\"\"\"\nimport sys; sys.path.append(\"../..\"); sys.path.append(\"../../src/\")\n\nimport plantbox as pb\nimport visualisation.vtk_plot as vp\nimport numpy as np\nimport matplotlib.pyplot as plt\n\npath = \"../../modelparameter/structural/rootsystem/\"\nname = \"Zea_mays_5_Leitner_2014\" # Zea_mays_1_Leitner_2010, Brassica_napus_a_Leitner_2010\n\nplant = pb.Plant()\nplant.readParameters(path + name + \".xml\")\nplant.setGeometry(pb.SDF_PlantContainer(10, 10, 200, True))\nplant.initialize()\nplant.simulate(120)\nplant.write(\"results/topics_postprocessing2.vtp\")\n\nr, depth, layers = 5, 100., 100 # Soil core analysis\nsoilcolumn = pb.SDF_PlantContainer(r, r, depth, False) # in the center of the root\nsoilcolumn2 = pb.SDF_RotateTranslate(soilcolumn, 0, 0, pb.Vector3d(10, 0, 0)) # shift for 10 cm\n\ngeom = soilcolumn # pick one geometry for further analysis\n\nz_ = np.linspace(0, -1 * depth, layers)\nfig, axes = plt.subplots(nrows = 1, ncols = 3, figsize = (16, 8))\nfor a in axes:\n a.set_xlabel('RLD (cm/cm^3)') # layer size is 1 cm\n a.set_ylabel('Depth (cm)')\n\n# Make a root length distribution\nlayerVolume = depth / layers * 20 * 20\ntimes = [120, 60, 30, 10]\nana = pb.SegmentAnalyser(plant)\nana.cropDomain(20, 20, depth) # ana.mapPeriodic(20, 20)\naxes[0].set_title('All roots in 20*20*100')\nrl_ = []\nfor t in times:\n ana.filter(\"creationTime\", 0, t)\n rl_.append(ana.distribution(\"length\", 0., -depth, layers, True))\n axes[0].plot(np.array(rl_[-1]) / layerVolume, z_, label = \"{:g} days\".format(t))\naxes[0].legend() # [\"10 days\", \"30 days\", \"60 days\", \"120 days\"]\n\n# Make a root length distribution along the soil core\nlayerVolume = depth / layers * r * r * np.pi\nana = pb.SegmentAnalyser(plant)\nana.crop(geom)\nana.pack()\nana_vis = pb.SegmentAnalyser(ana)\naxes[1].set_title('Soil core (over time)')\nrl_ = []\nfor t in times:\n ana.filter(\"creationTime\", 0, t)\n rl_.append(ana.distribution(\"length\", 0., -depth, layers, True))\n axes[1].plot(np.array(rl_[-1]) / layerVolume, z_, label = \"{:g} days\".format(t))\naxes[1].legend()\n\n# distributions per root type\nana = pb.SegmentAnalyser(plant)\nana.crop(geom)\nana.pack()\naxes[2].set_title('Soil core (per subType)')\nrl_ = []\nfor i in range(1, 5):\n a = pb.SegmentAnalyser(ana) # copy\n a.filter(\"subType\", i)\n rl_.append(a.distribution(\"length\", 0., -depth, layers, True))\n\naxes[2].plot((np.array(rl_[0]) + np.array(rl_[3])) / layerVolume, z_)\naxes[2].plot(np.array(rl_[1]) / layerVolume, z_)\naxes[2].plot(np.array(rl_[2]) / layerVolume, z_)\naxes[2].legend([\"basal roots\", \"first order roots\", \"second order roots\"])\n\nfig.subplots_adjust()\nplt.savefig(\"results/topics_postprocessing2.png\")\nplt.show()\n\nvp.plot_roots(ana_vis, \"subType\")\n","repo_name":"Plant-Root-Soil-Interactions-Modelling/CPlantBox","sub_path":"tutorial/examples/topics_postprocessing2.py","file_name":"topics_postprocessing2.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"20"} +{"seq_id":"43988607452","text":"# coding=utf-8\n\"\"\"\n将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。\n本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。\n\"\"\"\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution(object):\n def sortedArrayToBST(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: TreeNode\n \"\"\"\n if not nums:\n return None\n m = len(nums) / 2\n root = TreeNode(nums[m])\n l = nums[:m]\n r = nums[m+1:]\n root.left = self.sortedArrayToBST(l)\n root.right = self.sortedArrayToBST(r)\n return root","repo_name":"Winterdirge/Leetcode","sub_path":"Python/108.ConvertSortedArrayToBinarySearchTree.py","file_name":"108.ConvertSortedArrayToBinarySearchTree.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"72707926768","text":"import os\n\nfrom twitchio.ext import commands\n\n\nclass Multipov(commands.Cog):\n def __init__(self, bot: commands.Bot):\n self.bot = bot\n self.multipov_channels = {\n x.name: [] for x in self.bot.connected_channels\n }\n\n @commands.command(name=\"multipov\", aliases=[])\n async def multipov(self, ctx: commands.bot.Context):\n \"\"\"Renvoie le lien multipov. Ex: !multipov\"\"\"\n channels = '/'.join(self.multipov_channels[ctx.author.channel.name])\n await ctx.send(f'https://kadgar.net/live/{ctx.author.channel.name}/{channels}')\n\n @commands.command(name=\"multiadd\", aliases=[])\n async def multiadd(self, ctx: commands.bot.Context, *channels):\n \"\"\"Ajoute un streamer au lien multipov. Requiert privilege modérateur.\n Ex: !multiadd leix34\n \"\"\"\n if ctx.author.is_mod:\n for channel in channels:\n self.multipov_channels[ctx.author.channel.name].append(channel)\n await ctx.send('Multi mis à jour SeemsGood')\n\n @commands.command(name=\"multiset\", aliases=[])\n async def multiset(self, ctx: commands.bot.Context, *channels):\n \"\"\"Regle le lien multipov sur les chaines choisies. Requiert privilege\n modérateur.\n Ex: !multiset chaine1 chaine2 ...\n \"\"\"\n if ctx.author.is_mod:\n self.multipov_channels[ctx.author.channel.name] = []\n for channel in channels:\n self.multipov_channels[ctx.author.channel.name].append(channel)\n await ctx.send('Multi mis à jour SeemsGood')\n\n @commands.command(name=\"multireset\", aliases=[])\n async def multireset(self, ctx: commands.bot.Context):\n \"\"\"Réinitialise le lien multipov. Requiert privilege modérateur.\n Ex: !multireset\"\"\"\n if ctx.author.is_mod:\n self.multipov_channels[ctx.author.channel.name] = []\n await ctx.send('Multi a été reset SwiftRage')\n\n\ndef prepare(bot: commands.Bot):\n bot.add_cog(Multipov(bot))\n","repo_name":"leochely/LeixBot","sub_path":"cogs/multipov.py","file_name":"multipov.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"30170281809","text":"#!/usr/bin/env python3\nimport numpy as np\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\n\nimport tensorflow as tf\n# example from https://www.tensorflow.org/lite/convert\n\n# Create a model using high-level tf.keras.* APIs\nmodel = tf.keras.models.Sequential([\n #tf.keras.layers.ReLU(input_shape=[1])\n tf.keras.layers.Dense(units=256, input_shape=[256], use_bias=False),\n #tf.keras.layers.Dense(units=0x20, input_shape=[1], use_bias=False),\n #tf.keras.layers.Conv2D(filters=16, kernel_size=3, input_shape=[1,16,16,16])\n #tf.keras.layers.Rescaling(4, input_shape=[1])\n #tf.keras.layers.Dense(units=1, input_shape=[1], use_bias=False),\n #tf.keras.layers.Dense(units=16, activation='relu'),\n #tf.keras.layers.Dense(units=1)\n])\n#model.compile(optimizer='sgd', loss='mean_squared_error') # compile the model\n#model.fit(x=[-1, 0, 1], y=[-3, -1, 1], epochs=5) # train the model\n# (to generate a SavedModel) tf.saved_model.save(model, \"saved_model_keras_dir\")\n\ndef representative_dataset():\n for i in range(256):\n #data = np.random.rand(1, 1)\n #data = np.zeros([1,16,16,16]) + i\n data = np.zeros([1,256]) + i\n yield [data.astype(np.float32)]\n\n\"\"\"\n# Convert the model.\nroot = tf.train.Checkpoint()\n#root.f = tf.function(lambda g_input: tf.nn.relu(g_input))\nroot.f = tf.function(lambda g_input: g_input*2) #+10)\n#root.f = tf.function(lambda x: tf.nn.relu(x)-1)\ninput_data = tf.constant(1., shape=[0x20])\nto_save = root.f.get_concrete_function(input_data)\nprint(to_save)\n\"\"\"\n\n#print(to_save(tf.ones(1)*2))\n#exit(-1)\n\n#converter = tf.lite.TFLiteConverter.from_concrete_functions([to_save])\nconverter = tf.lite.TFLiteConverter.from_keras_model(model)\nconverter.optimizations = [tf.lite.Optimize.DEFAULT]\nconverter.representative_dataset = representative_dataset\n\nconverter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\nconverter.inference_input_type = tf.uint8 # or tf.uint8\nconverter.inference_output_type = tf.uint8 # or tf.uint8\ntflite_model = converter.convert()\n\n# Save the model.\nwith open('model.tflite', 'wb') as f:\n f.write(tflite_model)\n\n# Compile it\nos.system(\"./docker.sh\")\n","repo_name":"geohot/edgetpuxray","sub_path":"compile/generate_model.py","file_name":"generate_model.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","stars":69,"dataset":"github-code","pt":"20"} +{"seq_id":"21872032529","text":"# coding: utf-8\n\nimport six\n\nfrom huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization\n\n\nclass TermAssignmentHeader:\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n sensitive_list = []\n\n openapi_types = {\n 'confidence': 'int',\n 'steward': 'str',\n 'source': 'str',\n 'status': 'str',\n 'create_user': 'str',\n 'expression': 'str',\n 'display_text': 'str',\n 'term_guid': 'str',\n 'relation_guid': 'str'\n }\n\n attribute_map = {\n 'confidence': 'confidence',\n 'steward': 'steward',\n 'source': 'source',\n 'status': 'status',\n 'create_user': 'create_user',\n 'expression': 'expression',\n 'display_text': 'display_text',\n 'term_guid': 'term_guid',\n 'relation_guid': 'relation_guid'\n }\n\n def __init__(self, confidence=None, steward=None, source=None, status=None, create_user=None, expression=None, display_text=None, term_guid=None, relation_guid=None):\n \"\"\"TermAssignmentHeader\n\n The model defined in huaweicloud sdk\n\n :param confidence: 信任id\n :type confidence: int\n :param steward: 管理员\n :type steward: str\n :param source: 来源\n :type source: str\n :param status: 状态 枚举值:DISCOVERED、PROPOSED、IMPORTED、VALIDATED、DEPRECATED、OBSOLETE、OTHER\n :type status: str\n :param create_user: 创建人\n :type create_user: str\n :param expression: 表达式\n :type expression: str\n :param display_text: 展示信息\n :type display_text: str\n :param term_guid: 标签guid\n :type term_guid: str\n :param relation_guid: 关联guid\n :type relation_guid: str\n \"\"\"\n \n \n\n self._confidence = None\n self._steward = None\n self._source = None\n self._status = None\n self._create_user = None\n self._expression = None\n self._display_text = None\n self._term_guid = None\n self._relation_guid = None\n self.discriminator = None\n\n if confidence is not None:\n self.confidence = confidence\n if steward is not None:\n self.steward = steward\n if source is not None:\n self.source = source\n if status is not None:\n self.status = status\n if create_user is not None:\n self.create_user = create_user\n if expression is not None:\n self.expression = expression\n if display_text is not None:\n self.display_text = display_text\n if term_guid is not None:\n self.term_guid = term_guid\n if relation_guid is not None:\n self.relation_guid = relation_guid\n\n @property\n def confidence(self):\n \"\"\"Gets the confidence of this TermAssignmentHeader.\n\n 信任id\n\n :return: The confidence of this TermAssignmentHeader.\n :rtype: int\n \"\"\"\n return self._confidence\n\n @confidence.setter\n def confidence(self, confidence):\n \"\"\"Sets the confidence of this TermAssignmentHeader.\n\n 信任id\n\n :param confidence: The confidence of this TermAssignmentHeader.\n :type confidence: int\n \"\"\"\n self._confidence = confidence\n\n @property\n def steward(self):\n \"\"\"Gets the steward of this TermAssignmentHeader.\n\n 管理员\n\n :return: The steward of this TermAssignmentHeader.\n :rtype: str\n \"\"\"\n return self._steward\n\n @steward.setter\n def steward(self, steward):\n \"\"\"Sets the steward of this TermAssignmentHeader.\n\n 管理员\n\n :param steward: The steward of this TermAssignmentHeader.\n :type steward: str\n \"\"\"\n self._steward = steward\n\n @property\n def source(self):\n \"\"\"Gets the source of this TermAssignmentHeader.\n\n 来源\n\n :return: The source of this TermAssignmentHeader.\n :rtype: str\n \"\"\"\n return self._source\n\n @source.setter\n def source(self, source):\n \"\"\"Sets the source of this TermAssignmentHeader.\n\n 来源\n\n :param source: The source of this TermAssignmentHeader.\n :type source: str\n \"\"\"\n self._source = source\n\n @property\n def status(self):\n \"\"\"Gets the status of this TermAssignmentHeader.\n\n 状态 枚举值:DISCOVERED、PROPOSED、IMPORTED、VALIDATED、DEPRECATED、OBSOLETE、OTHER\n\n :return: The status of this TermAssignmentHeader.\n :rtype: str\n \"\"\"\n return self._status\n\n @status.setter\n def status(self, status):\n \"\"\"Sets the status of this TermAssignmentHeader.\n\n 状态 枚举值:DISCOVERED、PROPOSED、IMPORTED、VALIDATED、DEPRECATED、OBSOLETE、OTHER\n\n :param status: The status of this TermAssignmentHeader.\n :type status: str\n \"\"\"\n self._status = status\n\n @property\n def create_user(self):\n \"\"\"Gets the create_user of this TermAssignmentHeader.\n\n 创建人\n\n :return: The create_user of this TermAssignmentHeader.\n :rtype: str\n \"\"\"\n return self._create_user\n\n @create_user.setter\n def create_user(self, create_user):\n \"\"\"Sets the create_user of this TermAssignmentHeader.\n\n 创建人\n\n :param create_user: The create_user of this TermAssignmentHeader.\n :type create_user: str\n \"\"\"\n self._create_user = create_user\n\n @property\n def expression(self):\n \"\"\"Gets the expression of this TermAssignmentHeader.\n\n 表达式\n\n :return: The expression of this TermAssignmentHeader.\n :rtype: str\n \"\"\"\n return self._expression\n\n @expression.setter\n def expression(self, expression):\n \"\"\"Sets the expression of this TermAssignmentHeader.\n\n 表达式\n\n :param expression: The expression of this TermAssignmentHeader.\n :type expression: str\n \"\"\"\n self._expression = expression\n\n @property\n def display_text(self):\n \"\"\"Gets the display_text of this TermAssignmentHeader.\n\n 展示信息\n\n :return: The display_text of this TermAssignmentHeader.\n :rtype: str\n \"\"\"\n return self._display_text\n\n @display_text.setter\n def display_text(self, display_text):\n \"\"\"Sets the display_text of this TermAssignmentHeader.\n\n 展示信息\n\n :param display_text: The display_text of this TermAssignmentHeader.\n :type display_text: str\n \"\"\"\n self._display_text = display_text\n\n @property\n def term_guid(self):\n \"\"\"Gets the term_guid of this TermAssignmentHeader.\n\n 标签guid\n\n :return: The term_guid of this TermAssignmentHeader.\n :rtype: str\n \"\"\"\n return self._term_guid\n\n @term_guid.setter\n def term_guid(self, term_guid):\n \"\"\"Sets the term_guid of this TermAssignmentHeader.\n\n 标签guid\n\n :param term_guid: The term_guid of this TermAssignmentHeader.\n :type term_guid: str\n \"\"\"\n self._term_guid = term_guid\n\n @property\n def relation_guid(self):\n \"\"\"Gets the relation_guid of this TermAssignmentHeader.\n\n 关联guid\n\n :return: The relation_guid of this TermAssignmentHeader.\n :rtype: str\n \"\"\"\n return self._relation_guid\n\n @relation_guid.setter\n def relation_guid(self, relation_guid):\n \"\"\"Sets the relation_guid of this TermAssignmentHeader.\n\n 关联guid\n\n :param relation_guid: The relation_guid of this TermAssignmentHeader.\n :type relation_guid: str\n \"\"\"\n self._relation_guid = relation_guid\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n if attr in self.sensitive_list:\n result[attr] = \"****\"\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n import simplejson as json\n if six.PY2:\n import sys\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)\n\n def __repr__(self):\n \"\"\"For `print`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, TermAssignmentHeader):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","repo_name":"huaweicloud/huaweicloud-sdk-python-v3","sub_path":"huaweicloud-sdk-dataartsstudio/huaweicloudsdkdataartsstudio/v1/model/term_assignment_header.py","file_name":"term_assignment_header.py","file_ext":"py","file_size_in_byte":9641,"program_lang":"python","lang":"en","doc_type":"code","stars":104,"dataset":"github-code","pt":"20"} +{"seq_id":"10284814576","text":"''' extract package data from README and write as a packages file '''\n\nimport re\n\nfrom bs4 import BeautifulSoup\nimport markdown\n\nwith open('README.md') as readme:\n md = readme.read()\nhtml = markdown.markdown(md)\nsoup = BeautifulSoup(html, 'html.parser')\ntable = soup.find('table', {'id': 'packages'})\n\ndef handle_cell(packages, subject, cell):\n # for some reason markdown doesn't parse links in table cells properly,\n # so we do it by regexp:\n links = re.findall('\\[(.*?)\\]',cell.text)\n if len(links) == 0:\n return\n packages.append('# %s' % subject.text)\n packages += links\n packages.append('')\n\n\nguide, extra = ['### packages from Meteor guide ###\\n'], ['### extra packages ###\\n']\nfor row in table.find_all('tr')[1:]:\n subject, guide_cell, extra_cell = row.find_all('td')\n if subject.text.lower() == 'out of the box':\n next\n handle_cell(guide, subject, guide_cell)\n handle_cell(extra, subject, extra_cell)\n\nwith open('packages', 'w') as out:\n out.write('\\n'.join(guide + extra))","repo_name":"otech-nl/meteor-packages","sub_path":"packages.py","file_name":"packages.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72547205809","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 1 17:01:42 2019\n\n@author: Jie Zhang,微信公众号【EasyShu】,本代码源自《Python数据可视化之美》\n\"\"\"\n\nimport matplotlib.pyplot as plt \nimport numpy as np\nimport pandas as pd\n\ndf=pd.DataFrame(dict(group=[\"Manufacturing\",\"Transportationm warehousing\",\"Education services, healt care,social assistance\",\n \"Construction\",\"Information\",\"Retail trade\",\"Professional and business services\",\n \"Finance, insurace,real estate, rental, leasing\"],\n price=[1.08,0.74,0.73,0.66,0.55,0.54,0.356,0.28]))\n\ndf=df.sort_values(by=[\"price\"],ascending=True)\nx_label=np.array(df['group'])\ny=np.array(df['price'])\nx_value=np.arange(len(x_label))\nheight=0.45\n\nfig=plt.figure(figsize=(5,5))\nplt.xticks([])\nplt.yticks([])\nax = plt.gca() #获取整个表格边框\nax.spines['top'].set_color('none') #设置上‘脊梁’为无色\nax.spines['right'].set_color('none') #设置右‘脊梁’为无色\nax.spines['left'].set_color('none') #设置左‘脊梁’为无色\nax.spines['bottom'].set_color('none') #设置下‘脊梁’为无色\nplt.barh(x_value,color='#0099DC',height=height,width=y,align=\"center\")\nfor a,b,label in zip(y,x_value,x_label): #给条形图加标签,需要使用for循环\n plt.text(0, b+0.45, s=label, ha='left', va= 'center',fontsize=13,family='sans-serif')\n plt.text(a+0.01, b, s=\"$\"+ str(round(a,2)), ha='left', va= 'center',fontsize=13.5,family='Arial',weight=\"bold\")\n\nplt.text(0,1.3,s='Economic Engine',transform=ax.transAxes,weight='bold',size=20,family='Arial')\nplt.text(0,1.05,s=\"Manufacturing has a big impact on the U.S.\\neconomy's health. Everay dollar of value added\\nin these areas generates the following amounts\\nof additional transsactions: \",\n transform=ax.transAxes,weight='light',size=14,family='sans-serif')\nplt.text(0,-0.05,s='Source: Daniel J. Meckstroth.MAPI Foundtation;U.S. Bureau\\nof Economic Analysis',transform=ax.transAxes,weight='light',size=10,family='sans-serif')\n#plt.savefig('商业图表_条形图.pdf',bbox_inches='tight', pad_inches=0.3)\nplt.show()\n","repo_name":"gzsailor/Easy-Shu-Beautiful-Visualization-with-python","sub_path":"第11章 数据可视化案例/11.1_ 商业图表绘制示例/图11-1-5 Y轴标签省去的条形图绘制过程.py","file_name":"图11-1-5 Y轴标签省去的条形图绘制过程.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"20"} +{"seq_id":"39923008532","text":"\nimport discord\nfrom discord.ext import commands\nfrom discord.utils import get\nfrom replit import db\n\nclass Jobs(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n \n @commands.command(name='job', help='See your job title')\n async def seeJob(self, ctx):\n if \"jobs\" in db.keys():\n jobs = db[\"jobs\"]\n active_jobs = []\n roles = ctx.author.roles[1:]\n for r in roles:\n if r.name in jobs:\n active_jobs.append(r.name)\n if active_jobs:\n await ctx.send(f\"```\\n{ctx.author.display_name}\\'s Jobs:\\n\" + \"\\n\".join(active_jobs) + \"\\n```\")\n else:\n await ctx.send(\"Looks like you\\'re unemployed. We don't give handouts so get a job!\")\n\n @commands.command(name='job-set', help='Start a new job')\n async def giveRole(self,ctx, role_name):\n role = get(ctx.message.guild.roles, name=role_name)\n if 'jobs' in db.keys() and role:\n jobs = db['jobs']\n if role.name in jobs:\n await ctx.author.add_roles(role)\n await ctx.send(f\"Hey {ctx.author.display_name} you are now a {role}\")\n else:\n await ctx.send(f\"Hmmm, doesn't look like {role_name} is on the job list\")\n\n @commands.command(name='job-quit', help='Quit your job')\n async def quitRole(self,ctx, role_name):\n role = get(ctx.message.guild.roles, name=role_name)\n if 'jobs' in db.keys() and role:\n jobs = db['jobs']\n if jobs:\n active_jobs = []\n roles = ctx.author.roles[1:]\n for r in roles:\n if r.name in jobs:\n active_jobs.append(r.name)\n if role.name in active_jobs:\n await ctx.author.remove_roles(role)\n await ctx.send(f\"You are no longer employed as a {role.name}\")\n else:\n await ctx.send(\"You can't quit a job you don't have silly\")\n\n else:\n await ctx.send(f\"Hmmm, doesn't look like {role_name} is on the job list\")\n else:\n await ctx.send(f\"Hmmm, doesn't look like {role_name} is on the job list\")\n\n @commands.command(name='job-list', help='See a list of all job titles')\n async def seeRoles(self,ctx):\n if 'jobs' in db.keys():\n jobs = db['jobs']\n if jobs:\n await ctx.send(\"```\\nJob List:\\n\" + \"\\n\".join(jobs) + \"\\n```\")\n else:\n await ctx.send(\"There are no jobs on the job list. Maybe we should add some\")\n\n @commands.command(name='job-add', help='Add new Job titles for town members (ADMIN)')\n @commands.has_role(\"Admin\")\n async def addRoles(self,ctx,job):\n if 'jobs' in db.keys():\n jobs = db['jobs']\n if job in jobs:\n await ctx.send(f\"{job} is already on the job list\")\n return\n jobs.append(job)\n db['jobs'] = jobs\n await ctx.guild.create_role(name=job)\n await ctx.send(f\"I added a new role for the {job} job!\")\n else:\n db['jobs'] = [job]\n await ctx.guild.create_role(name=job)\n await ctx.send(f\"I added a new role for the {job} job!\")\n \n\n @commands.command(name='job-remove', help='Delete an existing job (ADMIN)')\n @commands.has_role(\"Admin\")\n async def delRoles(self,ctx,job):\n if 'jobs' in db.keys():\n jobs = db['jobs']\n if jobs == []:\n await ctx.send(\"There are no jobs... so you can't delete that... Silly Goose\")\n role = get(ctx.message.guild.roles, name=job)\n if job in jobs:\n del jobs[jobs.index(job)]\n db['jobs'] = jobs\n if role:\n await role.delete()\n await ctx.send(f\"{job} was removed from the job list\")\n else:\n await ctx.send(f\"{job} is not on the job list\")\n else:\n await ctx.send(\"There are no jobs... so you can't delete that... Silly Goose\")\n\nclass Profile(commands.Cog):\n\n def __init__(self,bot):\n self.bot = bot\n\n def _getProfile(self, user: discord.Member):\n if \"jobs\" in db.keys():\n jobs = db[\"jobs\"]\n active_jobs = []\n job_status = ''\n roles = user.roles[1:]\n for r in roles:\n if r.name in jobs:\n active_jobs.append(r.name)\n if active_jobs:\n job_status = ', '.join(active_jobs)\n else:\n job_status = 'unemployed'\n name = user.display_name\n return \"```\\nUser Profle:\\n\" + \"\\nName: \"+ name + \"\\nJobs: \" + job_status + \"\\n```\"\n return\n\n \n\nclass Info(commands.Cog):\n\n def __init__(self,bot):\n self.bot = bot\n \n @commands.command(name='commands', help='Sends server plugin commands link')\n async def comInfo(self,ctx):\n link = \"https://github.com/catch441/Ultimate_Economy/wiki\"\n await ctx.send(link)\n ","repo_name":"neu-ma-tic/test9475","sub_path":"364138aa-b06a-4035-a8b4-5cb5c0c5d23c/economy.py","file_name":"economy.py","file_ext":"py","file_size_in_byte":4493,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"72196797490","text":"import os, requests, sys, pytz\nfrom datetime import datetime\nfrom django.core.management.base import BaseCommand, CommandError\nfrom ...models import Organization\nfrom ...tasks import persist_organization_events\nfrom django.utils import timezone\n\n\nclass Command(BaseCommand):\n help = 'Sync from eventbrite, please make sure to add the argument, Eg: sync_eventbrite events'\n\n def add_arguments(self, parser):\n parser.add_argument('entity', type=str)\n parser.add_argument(\n '--override',\n action='store_true',\n help='Delete and add again',\n )\n parser.add_argument('--limit',\n action='store',\n dest='limit',\n type=int,\n default=0,\n help='How many to import')\n\n def handle(self, *args, **options):\n if 'entity' not in options:\n return self.stderr.write(self.style.ERROR('Entity argument not provided'))\n\n try:\n func = getattr(self, options['entity'])\n func(options)\n except:\n return self.stderr.write(self.style.ERROR(f'Sync method for `{options[\"entity\"]}` no Found!'))\n\n def events(self, options):\n now = timezone.now()\n orgs = Organization.objects.all()\n count = 0\n for org in orgs:\n if not org.eventbrite_key or not org.eventbrite_id:\n org.sync_status = 'ERROR'\n org.sync_desc = 'Missing eventbrite key or id'\n org.save()\n self.stderr.write(self.style.ERROR(f'Organization {str(org)} is missing evenbrite key or ID'))\n else:\n org.sync_status = 'PENDING'\n org.sync_desc = 'Running sync_eventbrite command at ' + str(now)\n org.save()\n persist_organization_events.delay({'org_id': org.id})\n count = count + 1\n\n self.stdout.write(self.style.SUCCESS(f'Enqueued {count} of {len(orgs)} for sync events'))\n","repo_name":"breatheco-de/apiv2","sub_path":"breathecode/events/management/commands/sync_eventbrite.py","file_name":"sync_eventbrite.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"20"} +{"seq_id":"37619405594","text":"import os, re, sys, time, datetime, traceback\nimport urlparse, urllib, urllib2, socket, json\nimport xbmc, xbmcgui, xbmcplugin, xbmcaddon\n\nfrom simplecache import SimpleCache\nfrom bs4 import BeautifulSoup\n\n# Plugin Info\nADDON_ID = 'plugin.video.skynews'\nREAL_SETTINGS = xbmcaddon.Addon(id=ADDON_ID)\nADDON_NAME = REAL_SETTINGS.getAddonInfo('name')\nSETTINGS_LOC = REAL_SETTINGS.getAddonInfo('profile')\nADDON_PATH = REAL_SETTINGS.getAddonInfo('path').decode('utf-8')\nADDON_VERSION = REAL_SETTINGS.getAddonInfo('version')\nICON = REAL_SETTINGS.getAddonInfo('icon')\nFANART = REAL_SETTINGS.getAddonInfo('fanart')\nLANGUAGE = REAL_SETTINGS.getLocalizedString\n\n## GLOBALS ##\nTIMEOUT = 15\nCONTENT_TYPE = 'files'\nDEBUG = REAL_SETTINGS.getSetting('Enable_Debugging') == 'true'\nLIVEURL = 'http://news.sky.com/watch-live'\nYTURL = 'plugin://plugin.video.youtube/play/?video_id='\n\ndef log(msg, level=xbmc.LOGDEBUG):\n if DEBUG == False and level != xbmc.LOGERROR: return\n if level == xbmc.LOGERROR: msg += ' ,' + traceback.format_exc()\n xbmc.log(ADDON_ID + '-' + ADDON_VERSION + '-' + msg, level)\n \ndef getParams():\n return dict(urlparse.parse_qsl(sys.argv[2][1:]))\n \nsocket.setdefaulttimeout(TIMEOUT)\nclass Sky(object):\n def __init__(self):\n log('__init__')\n self.cache = SimpleCache()\n\n \n def openURL(self, url):\n log('openURL, url = ' + str(url))\n try:\n cacheResponse = self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)\n if not cacheResponse:\n request = urllib2.Request(url)\n request.add_header('User-Agent','Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)')\n response = urllib2.urlopen(request, timeout=TIMEOUT).read()\n self.cache.set(ADDON_NAME + '.openURL, url = %s'%url, response, expiration=datetime.timedelta(hours=6))\n return self.cache.get(ADDON_NAME + '.openURL, url = %s'%url)\n except Exception as e: log(\"openURL Failed! \" + str(e), xbmc.LOGERROR)\n xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30001), ICON, 4000)\n return ''\n \n\n def buildMainMenu(self):\n self.addLink(LANGUAGE(30002),'',0)\n self.addYoutube(LANGUAGE(30003),'plugin://plugin.video.youtube/user/skynews/')\n \n \n def buildLiveLink(self):\n try:\n link = 'http:' + BeautifulSoup(self.openURL(LIVEURL), \"html.parser\")('div', {'class': 'video-embed'})[0].find('iframe').get('src')\n print(self.resolveYoutube(link))\n self.playVideo(LANGUAGE(30004),self.resolveYoutube(link))\n except: self.playVideo(LANGUAGE(30004),YTURL + 'XOacA3RYrXk')\n \n def resolveYoutube(self, link):\n if len(re.findall('http[s]?://www.youtube.com/watch', link)) > 0: return YTURL + link.split('/watch?v=')[1]\n elif len(re.findall('http[s]?://www.youtube.com/embed', link)) > 0: return YTURL + link.split('/embed/')[1].split('?autoplay=1')[0]\n elif len(re.findall('http[s]?://youtu.be/', link)) > 0: return YTURL + link.split('/youtu.be/')[1] \n\n \n def playVideo(self, name, url, liz=None):\n log('playVideo')\n if not liz: liz = xbmcgui.ListItem(name, path=url)\n xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)\n\n\n def addYoutube(self, title, url):\n liz=xbmcgui.ListItem(title)\n liz.setProperty('IsPlayable', 'false')\n liz.setInfo(type=\"Video\", infoLabels={\"label\":title,\"title\":title} )\n liz.setArt({'thumb':ICON,'fanart':FANART})\n xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz,isFolder=True)\n\n \n def addLink(self, name, u, mode, infoList=False, infoArt=False, total=0):\n name = name.encode(\"utf-8\")\n log('addLink, name = ' + name)\n liz=xbmcgui.ListItem(name)\n liz.setProperty('IsPlayable', 'true')\n if infoList == False: liz.setInfo(type=\"Video\", infoLabels={\"mediatype\":\"video\",\"label\":name,\"title\":name,\"genre\":\"News\"})\n else: liz.setInfo(type=\"Video\", infoLabels=infoList) \n if infoArt == False: liz.setArt({'thumb':ICON,'fanart':FANART})\n else: liz.setArt(infoArt)\n u=sys.argv[0]+\"?url=\"+urllib.quote_plus(u)+\"&mode=\"+str(mode)+\"&name=\"+urllib.quote_plus(name)\n xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,totalItems=total)\n\nparams=getParams()\ntry: url=urllib.unquote_plus(params[\"url\"])\nexcept: url=None\ntry: name=urllib.unquote_plus(params[\"name\"])\nexcept: name=None\ntry: mode=int(params[\"mode\"])\nexcept: mode=None\nlog(\"Mode: \"+str(mode))\nlog(\"URL : \"+str(url))\nlog(\"Name: \"+str(name))\n\nif mode==None: Sky().buildMainMenu()\nelif mode == 0: Sky().buildLiveLink()\nelif mode == 9: Sky().playVideo(name, url)\n\nxbmcplugin.setContent(int(sys.argv[1]) , CONTENT_TYPE)\nxbmcplugin.addSortMethod(int(sys.argv[1]) , xbmcplugin.SORT_METHOD_UNSORTED)\nxbmcplugin.addSortMethod(int(sys.argv[1]) , xbmcplugin.SORT_METHOD_NONE)\nxbmcplugin.addSortMethod(int(sys.argv[1]) , xbmcplugin.SORT_METHOD_LABEL)\nxbmcplugin.addSortMethod(int(sys.argv[1]) , xbmcplugin.SORT_METHOD_TITLE)\nxbmcplugin.endOfDirectory(int(sys.argv[1]), cacheToDisc=True)","repo_name":"sandmans/KODI_Addons","sub_path":"plugin.video.skynews/resources/lib/skynews.py","file_name":"skynews.py","file_ext":"py","file_size_in_byte":5262,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"11755216913","text":"#!/usr/bin/python3 \n \nimport requests\nfrom webdav3.client import Client\nfrom subprocess import Popen\n\n\nip = '10.10.10.15'\nshell = 'shell.txt'\nlport = '443'\n\noptions = {\n 'webdav_hostname': \"http://\"+ip\n}\nclient = Client(options)\nclient.upload(remote_path=shell, local_path=shell)\n\nclient.move(remote_path_from=shell, remote_path_to=\"shell.aspx\")\ncmd = \"terminator -T \\'Catch the Shell\\' -e \\'nc -nvl \"+ lport+'\\''\nPopen(cmd ,shell=True)\n\ncallbackurl = 'http://'+ip+'/'+\"shell.aspx\"\nr2 = requests.get(callbackurl)\n\n","repo_name":"dfclin073/exploits","sub_path":"granny.py","file_name":"granny.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7822711289","text":"from SiemplifyAction import SiemplifyAction\nfrom SiemplifyUtils import output_handler\n\n\n@output_handler\ndef main():\n siemplify = SiemplifyAction()\n priority = siemplify.parameters[\"Alert Priority\"]\n\n request_dict = {\"caseId\": siemplify.case_id,\n \"alertIdentifier\": siemplify.current_alert.identifier,\n \"alertName\": siemplify.current_alert.name,\n \"priority\": priority\n }\n\n # noinspection PyBroadException\n try:\n address = u\"{0}/{1}\".format(siemplify.API_ROOT, \"external/v1/sdk/UpdateAlertPriority\")\n response = siemplify.session.post(address, json=request_dict)\n siemplify.validate_siemplify_error(response)\n output_message = u\"The alert priority was set to {}\".format(priority)\n is_success = \"true\"\n except Exception as _:\n output_message = (\"This method is supported only in Siemplify versions 5.6 and above, \"\n \"please make sure your Siemplify version id 5.6 or higher and try again\")\n siemplify.LOGGER.info(output_message)\n is_success = \"false\"\n\n siemplify.end(output_message, is_success)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"chronicle/tip-marketplace","sub_path":"Integrations/Siemplify/ActionsScripts/ChangeAlertPriority.py","file_name":"ChangeAlertPriority.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"5275512805","text":"#!/usr/bin/env python3\n\n################################################################################################\n#\n# GlacierScript: Part of the Glacier Protocol (http://glacierprotocol.org)\n#\n# GlacierScript is designed specifically for use in the context of executing the broader Glacier\n# Protocol, a step-by-step procedure for high-security cold storage of Bitcoin. It is not\n# intended to be used as standalone software.\n#\n# GlacierScript primarily replaces tasks that users would otherwise be doing manually, such as\n# typing things on the command line, copying-and-pasting strings, and hand-editing JSON. It\n# mostly consists of print statements, user input, string & JSON manipulation, and command-line\n# wrappers around Bitcoin Core and other applications (e.g. those involved in reading and writing\n# QR codes.)\n#\n# GlacierScript avoids cryptographic and other security-sensitive operations as much as possible.\n#\n# GlacierScript depends on the following command-line applications:\n# - Bitcoin Core (http://bitcoincore.org)\n# - qrencode (QR code writer: http://packages.ubuntu.com/xenial/qrencode)\n# - zbarimg (QR code reader: http://packages.ubuntu.com/xenial/zbar-tools)\n#\n################################################################################################\n\n# standard Python libraries\nimport argparse\nfrom collections import OrderedDict\nfrom decimal import Decimal\nfrom hashlib import sha256, md5\nimport json\nimport os\nimport shlex\nimport subprocess\nimport sys\nimport time\n\n# Taken from https://github.com/keis/base58\nfrom base58 import b58encode_check\n\nSATOSHI_PLACES = Decimal(\"0.00000001\")\n\nverbose_mode = 0\n\n################################################################################################\n#\n# Minor helper functions\n#\n################################################################################################\n\ndef hash_sha256(s):\n \"\"\"A thin wrapper around the hashlib SHA256 library to provide a more functional interface\"\"\"\n m = sha256()\n m.update(s.encode('ascii'))\n return m.hexdigest()\n\n\ndef hash_md5(s):\n \"\"\"A thin wrapper around the hashlib md5 library to provide a more functional interface\"\"\"\n m = md5()\n m.update(s.encode('ascii'))\n return m.hexdigest()\n\n\ndef satoshi_to_btc(satoshi):\n \"\"\"\n Converts a value in satoshi to a value in BTC\n outputs => Decimal\n\n satoshi: \n \"\"\"\n value = Decimal(satoshi) / Decimal(100000000)\n return value.quantize(SATOSHI_PLACES)\n\n\ndef btc_to_satoshi(btc):\n \"\"\"\n Converts a value in BTC to satoshi\n outputs => \n\n btc: or \n \"\"\"\n value = btc * 100000000\n return int(value)\n\n\n################################################################################################\n#\n# Subprocess helper functions\n#\n################################################################################################\n\ndef verbose(content):\n if verbose_mode: print(content)\n\n\ndef run_subprocess(exe, *args):\n \"\"\"\n Run a subprocess (bitcoind or bitcoin-cli)\n Returns => (command, return code, output)\n\n exe: executable file name (e.g. bitcoin-cli)\n args: arguments to exe\n \"\"\"\n cmd_list = [exe] + cli_args + list(args)\n verbose(\"bitcoin cli call:\\n {0}\\n\".format(\" \".join(shlex.quote(x) for x in cmd_list)))\n with subprocess.Popen(cmd_list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1) as pipe:\n output, _ = pipe.communicate()\n output = output.decode('ascii')\n retcode = pipe.returncode\n verbose(\"bitcoin cli call return code: {0} output:\\n {1}\\n\".format(retcode, output))\n return (cmd_list, retcode, output)\n\n\ndef bitcoin_cli_call(*args):\n \"\"\"\n Run `bitcoin-cli`, return OS return code\n \"\"\"\n _, retcode, _ = run_subprocess(\"bitcoin-cli\", *args)\n return retcode\n\n\ndef bitcoin_cli_checkoutput(*args):\n \"\"\"\n Run `bitcoin-cli`, fail if OS return code nonzero, return output\n \"\"\"\n cmd_list, retcode, output = run_subprocess(\"bitcoin-cli\", *args)\n if retcode != 0: raise subprocess.CalledProcessError(retcode, cmd_list, output=output)\n return output\n\n\ndef bitcoin_cli_json(*args):\n \"\"\"\n Run `bitcoin-cli`, parse output as JSON\n \"\"\"\n return json.loads(bitcoin_cli_checkoutput(*args))\n\n\ndef bitcoind_call(*args):\n \"\"\"\n Run `bitcoind`, return OS return code\n \"\"\"\n _, retcode, _ = run_subprocess(\"bitcoind\", *args)\n return retcode\n\n\n################################################################################################\n#\n# Read & validate random data from the user\n#\n################################################################################################\n\ndef validate_rng_seed(seed, min_length):\n \"\"\"\n Validates random hexadecimal seed\n returns => \n\n seed: hex string to be validated\n min_length: number of characters required. > 0\n \"\"\"\n\n if len(seed) < min_length:\n print(\"Error: Computer entropy must be at least {0} characters long\".format(min_length))\n return False\n\n if len(seed) % 2 != 0:\n print(\"Error: Computer entropy must contain an even number of characters.\")\n return False\n\n try:\n int(seed, 16)\n except ValueError:\n print(\"Error: Illegal character. Computer entropy must be composed of hexadecimal characters only (0-9, a-f).\")\n return False\n\n return True\n\n\ndef read_rng_seed_interactive(min_length):\n \"\"\"\n Reads random seed (of at least min_length hexadecimal characters) from standard input\n returns => string\n\n min_length: minimum number of bytes in the seed.\n \"\"\"\n\n char_length = min_length * 2\n\n def ask_for_rng_seed(length):\n print(\"Enter at least {0} characters of computer entropy. Spaces are OK, and will be ignored:\".format(length))\n\n ask_for_rng_seed(char_length)\n seed = input()\n seed = unchunk(seed)\n\n while not validate_rng_seed(seed, char_length):\n ask_for_rng_seed(char_length)\n seed = input()\n seed = unchunk(seed)\n\n return seed\n\n\ndef validate_dice_seed(dice, min_length):\n \"\"\"\n Validates dice data (i.e. ensures all digits are between 1 and 6).\n returns => \n\n dice: representing list of dice rolls (e.g. \"5261435236...\")\n \"\"\"\n\n if len(dice) < min_length:\n print(\"Error: You must provide at least {0} dice rolls\".format(min_length))\n return False\n\n for die in dice:\n try:\n i = int(die)\n if i < 1 or i > 6:\n print(\"Error: Dice rolls must be between 1 and 6.\")\n return False\n except ValueError:\n print(\"Error: Dice rolls must be numbers between 1 and 6\")\n return False\n\n return True\n\n\ndef read_dice_seed_interactive(min_length):\n \"\"\"\n Reads min_length dice rolls from standard input, as a string of consecutive integers\n Returns a string representing the dice rolls\n returns => \n\n min_length: number of dice rolls required. > 0.\n \"\"\"\n\n def ask_for_dice_seed(x):\n print(\"Enter {0} dice rolls (example: 62543 16325 21341...) Spaces are OK, and will be ignored:\".format(x))\n\n ask_for_dice_seed(min_length)\n dice = input()\n dice = unchunk(dice)\n\n while not validate_dice_seed(dice, min_length):\n ask_for_dice_seed(min_length)\n dice = input()\n dice = unchunk(dice)\n\n return dice\n\n\n################################################################################################\n#\n# private key generation\n#\n################################################################################################\n\ndef xor_hex_strings(str1, str2):\n \"\"\"\n Return xor of two hex strings.\n An XOR of two pieces of data will be as random as the input with the most randomness.\n We can thus combine two entropy sources in this way as a safeguard against one source being\n compromised in some way.\n For details, see http://crypto.stackexchange.com/a/17660\n\n returns => in hex format\n \"\"\"\n if len(str1) != len(str2):\n raise Exception(\"tried to xor strings of unequal length\")\n str1_dec = int(str1, 16)\n str2_dec = int(str2, 16)\n\n xored = str1_dec ^ str2_dec\n\n return \"{:0{}x}\".format(xored, len(str1))\n\n\ndef hex_private_key_to_WIF_private_key(hex_key):\n \"\"\"\n Converts a raw 256-bit hex private key to WIF format\n returns => in hex format\n \"\"\"\n hex_key_with_prefix = wif_prefix + hex_key + \"01\"\n wif_key = b58encode_check(bytes.fromhex(hex_key_with_prefix))\n return wif_key.decode('ascii')\n\n\n################################################################################################\n#\n# Bitcoin helper functions\n#\n################################################################################################\n\ndef ensure_bitcoind_running():\n \"\"\"\n Start bitcoind (if it's not already running) and ensure it's functioning properly\n \"\"\"\n # start bitcoind. If another bitcoind process is already running, this will just print an error\n # message (to /dev/null) and exit.\n #\n # -connect=0.0.0.0 because we're doing local operations only (and have no network connection anyway)\n bitcoind_call(\"-daemon\", \"-connect=0.0.0.0\")\n\n # verify bitcoind started up and is functioning correctly\n times = 0\n while times <= 20:\n times += 1\n if bitcoin_cli_call(\"getnetworkinfo\") == 0:\n return\n time.sleep(0.5)\n\n raise Exception(\"Timeout while starting bitcoin server\")\n\ndef require_minimum_bitcoind_version(min_version):\n \"\"\"\n Fail if the bitcoind version in use is older than required\n - required minimum version in format of getnetworkinfo, i.e. 150100 for v0.15.1\n \"\"\"\n networkinfo = bitcoin_cli_json(\"getnetworkinfo\")\n\n if int(networkinfo[\"version\"]) < min_version:\n print(\"ERROR: Your bitcoind version is too old. You have {}, I need {} or newer. Exiting...\".format(networkinfo[\"version\"], min_version))\n sys.exit()\n\ndef get_address_for_wif_privkey(privkey):\n \"\"\"A method for retrieving the address associated with a private key from bitcoin core\n - a bitcoin private key in WIF format\"\"\"\n\n # Bitcoin Core doesn't have an RPC for \"get the addresses associated w/this private key\"\n # just \"get the addresses associated with this label\"\n # where \"label\" corresponds to an arbitrary tag we can associate with each private key\n # so, we'll generate a unique \"label\" to attach to this private key.\n\n label = hash_sha256(privkey)\n\n ensure_bitcoind_running()\n bitcoin_cli_call(\"importprivkey\", privkey, label)\n addresses = bitcoin_cli_json(\"getaddressesbylabel\", label)\n\n # getaddressesbylabel returns multiple addresses associated with\n # this one privkey; since we use it only for communicating the\n # pubkey to addmultisigaddress, it doesn't matter which one we\n # choose; they are all associated with the same pubkey.\n\n return next(iter(addresses))\n\n\ndef addmultisigaddress(m, addresses_or_pubkeys, address_type='p2sh-segwit'):\n \"\"\"\n Call `bitcoin-cli addmultisigaddress`\n returns => JSON response from bitcoin-cli\n\n m: number of multisig keys required for withdrawal\n addresses_or_pubkeys: List either addresses or hex pubkeys for each of the N keys\n \"\"\"\n address_string = json.dumps(addresses_or_pubkeys)\n return bitcoin_cli_json(\"addmultisigaddress\", str(m), address_string, \"\", address_type)\n\ndef get_utxos(tx, address):\n \"\"\"\n Given a transaction, find all the outputs that were sent to an address\n returns => List list of UTXOs in bitcoin core format\n\n tx - in bitcoin core format\n address - \n \"\"\"\n utxos = []\n\n for output in tx[\"vout\"]:\n if \"addresses\" not in output[\"scriptPubKey\"]:\n # In Bitcoin Core versions older than v0.16, native segwit outputs have no address decoded\n continue\n out_addresses = output[\"scriptPubKey\"][\"addresses\"]\n amount_btc = output[\"value\"]\n if address in out_addresses:\n utxos.append(output)\n\n return utxos\n\n\ndef create_unsigned_transaction(source_address, destinations, redeem_script, input_txs):\n \"\"\"\n Returns a hex string representing an unsigned bitcoin transaction\n returns => \n\n source_address: input_txs will be filtered for utxos to this source address\n destinations: {address : amount} dictionary mapping destination addresses to amount in BTC\n redeem_script: \n input_txs: List List of input transactions in dictionary form (bitcoind decoded format)\n \"\"\"\n ensure_bitcoind_running()\n\n # prune destination addresses sent 0 btc\n destinations = OrderedDict((key, val) for key, val in destinations.items() if val != '0')\n\n # For each UTXO used as input, we need the txid and vout index to generate a transaction\n inputs = []\n for tx in input_txs:\n utxos = get_utxos(tx, source_address)\n txid = tx[\"txid\"]\n\n for utxo in utxos:\n inputs.append(OrderedDict([\n (\"txid\", txid),\n (\"vout\", int(utxo[\"n\"]))\n ]))\n\n tx_unsigned_hex = bitcoin_cli_checkoutput(\n \"createrawtransaction\",\n json.dumps(inputs),\n json.dumps(destinations)).strip()\n\n return tx_unsigned_hex\n\n\ndef sign_transaction(source_address, keys, redeem_script, unsigned_hex, input_txs):\n \"\"\"\n Creates a signed transaction\n output => dictionary {\"hex\": transaction , \"complete\": }\n\n source_address: input_txs will be filtered for utxos to this source address\n keys: List The private keys you wish to sign with\n redeem_script: \n unsigned_hex: The unsigned transaction, in hex format\n input_txs: List A list of input transactions to use (bitcoind decoded format)\n \"\"\"\n\n # For each UTXO used as input, we need the txid, vout index, scriptPubKey, amount, and redeemScript\n # to generate a signature\n inputs = []\n for tx in input_txs:\n utxos = get_utxos(tx, source_address)\n txid = tx[\"txid\"]\n for utxo in utxos:\n inputs.append({\n \"txid\": txid,\n \"vout\": int(utxo[\"n\"]),\n \"amount\": utxo[\"value\"],\n \"scriptPubKey\": utxo[\"scriptPubKey\"][\"hex\"],\n \"redeemScript\": redeem_script\n })\n\n signed_tx = bitcoin_cli_json(\n \"signrawtransactionwithkey\",\n unsigned_hex, json.dumps(keys), json.dumps(inputs))\n return signed_tx\n\n\ndef get_fee_interactive(source_address, keys, destinations, redeem_script, input_txs):\n \"\"\"\n Returns a recommended transaction fee, given market fee data provided by the user interactively\n Because fees tend to be a function of transaction size, we build the transaction in order to\n recomend a fee.\n return => fee value\n\n Parameters:\n source_address: input_txs will be filtered for utxos to this source address\n keys: A list of signing keys\n destinations: {address : amount} dictionary mapping destination addresses to amount in BTC\n redeem_script: String\n input_txs: List List of input transactions in dictionary form (bitcoind decoded format)\n fee_basis_satoshis_per_byte: optional basis for fee calculation\n \"\"\"\n\n MAX_FEE = .005 # in btc. hardcoded limit to protect against user typos\n\n ensure_bitcoind_running()\n\n approve = False\n while not approve:\n print(\"\\nEnter fee rate.\")\n fee_basis_satoshis_per_byte = int(input(\"Satoshis per vbyte: \"))\n\n unsigned_tx = create_unsigned_transaction(\n source_address, destinations, redeem_script, input_txs)\n\n signed_tx = sign_transaction(source_address, keys,\n redeem_script, unsigned_tx, input_txs)\n\n decoded_tx = bitcoin_cli_json(\"decoderawtransaction\", signed_tx[\"hex\"])\n size = decoded_tx[\"vsize\"]\n\n fee = size * fee_basis_satoshis_per_byte\n fee = satoshi_to_btc(fee)\n\n if fee > MAX_FEE:\n print(\"Calculated fee ({}) is too high. Must be under {}\".format(fee, MAX_FEE))\n else:\n print(\"\\nBased on the provided rate, the fee will be {} bitcoin.\".format(fee))\n confirm = yes_no_interactive()\n\n if confirm:\n approve = True\n else:\n print(\"\\nFee calculation aborted. Starting over...\")\n\n return fee\n\n\n################################################################################################\n#\n# QR code helper functions\n#\n################################################################################################\n\ndef write_and_verify_qr_code(name, filename, data):\n \"\"\"\n Write a QR code and then read it back to try and detect any tricksy malware tampering with it.\n\n name: short description of the data\n filename: filename for storing the QR code\n data: the data to be encoded\n \"\"\"\n\n subprocess.call(\"qrencode -o {0} {1}\".format(filename, data), shell=True)\n check = subprocess.check_output(\n \"zbarimg --set '*.enable=0' --set 'qr.enable=1' --quiet --raw {}\".format(filename), shell=True)\n\n if check.decode('ascii').strip() != data:\n print(\"********************************************************************\")\n print(\"WARNING: {} QR code could not be verified properly. This could be a sign of a security breach.\".format(name))\n print(\"********************************************************************\")\n\n print(\"QR code for {0} written to {1}\".format(name, filename))\n\n\n################################################################################################\n#\n# User sanity checking\n#\n################################################################################################\n\ndef yes_no_interactive():\n def confirm_prompt():\n return input(\"Confirm? (y/n): \")\n\n confirm = confirm_prompt()\n\n while True:\n if confirm.upper() == \"Y\":\n return True\n if confirm.upper() == \"N\":\n return False\n else:\n print(\"You must enter y (for yes) or n (for no).\")\n confirm = confirm_prompt()\n\ndef safety_checklist():\n\n checks = [\n \"Are you running this on a computer WITHOUT a network connection of any kind?\",\n \"Have the wireless cards in this computer been physically removed?\",\n \"Are you running on battery power?\",\n \"Are you running on an operating system booted from a USB drive?\",\n \"Is your screen hidden from view of windows, cameras, and other people?\",\n \"Are smartphones and all other nearby devices turned off and in a Faraday bag?\"]\n\n for check in checks:\n answer = input(check + \" (y/n)?\")\n if answer.upper() != \"Y\":\n print(\"\\n Safety check failed. Exiting.\")\n sys.exit()\n\n\n################################################################################################\n#\n# Main \"entropy\" function\n#\n################################################################################################\n\n\ndef unchunk(string):\n \"\"\"\n Remove spaces in string\n \"\"\"\n return string.replace(\" \", \"\")\n\n\ndef chunk_string(string, length):\n \"\"\"\n Splits a string into chunks of [length] characters, for easy human readability\n Source: https://stackoverflow.com/a/18854817/11031317\n \"\"\"\n return (string[0+i:length+i] for i in range(0, len(string), length))\n\n\ndef entropy(n, length):\n \"\"\"\n Generate n random strings for the user from /dev/random\n \"\"\"\n safety_checklist()\n\n print(\"\\n\\n\")\n print(\"Making {} random data strings....\".format(n))\n print(\"If strings don't appear right away, please continually move your mouse cursor. These movements generate entropy which is used to create random data.\\n\")\n\n idx = 0\n while idx < n:\n seed = subprocess.check_output(\n \"xxd -l {} -p /dev/random\".format(length), shell=True)\n idx += 1\n seed = seed.decode('ascii').replace('\\n', '')\n print(\"Computer entropy #{0}: {1}\".format(idx, \" \".join(chunk_string(seed, 4))))\n\n\n################################################################################################\n#\n# Main \"deposit\" function\n#\n################################################################################################\n\ndef deposit_interactive(m, n, dice_seed_length=62, rng_seed_length=20):\n \"\"\"\n Generate data for a new cold storage address (private keys, address, redemption script)\n m: number of multisig keys required for withdrawal\n n: total number of multisig keys\n dice_seed_length: minimum number of dice rolls required\n rng_seed_length: minimum length of random seed required\n \"\"\"\n\n safety_checklist()\n ensure_bitcoind_running()\n require_minimum_bitcoind_version(170000) # getaddressesbylabel API new in v0.17.0\n\n print(\"\\n\")\n print(\"Creating {0}-of-{1} cold storage address.\\n\".format(m, n))\n\n keys = []\n\n while len(keys) < n:\n index = len(keys) + 1\n print(\"\\nCreating private key #{}\".format(index))\n\n dice_seed_string = read_dice_seed_interactive(dice_seed_length)\n dice_seed_hash = hash_sha256(dice_seed_string)\n\n rng_seed_string = read_rng_seed_interactive(rng_seed_length)\n rng_seed_hash = hash_sha256(rng_seed_string)\n\n # back to hex string\n hex_private_key = xor_hex_strings(dice_seed_hash, rng_seed_hash)\n WIF_private_key = hex_private_key_to_WIF_private_key(hex_private_key)\n keys.append(WIF_private_key)\n\n print(\"Private keys created.\")\n print(\"Generating {0}-of-{1} cold storage address...\\n\".format(m, n))\n\n addresses = [get_address_for_wif_privkey(key) for key in keys]\n results = addmultisigaddress(m, addresses)\n\n print(\"Private keys:\")\n for idx, key in enumerate(keys):\n print(\"Key #{0}: {1}\".format(idx + 1, key))\n\n print(\"\\nCold storage address:\")\n print(\"{}\".format(results[\"address\"]))\n\n print(\"\\nRedemption script:\")\n print(\"{}\".format(results[\"redeemScript\"]))\n print(\"\")\n\n write_and_verify_qr_code(\"cold storage address\", \"address.png\", results[\"address\"])\n write_and_verify_qr_code(\"redemption script\", \"redemption.png\",\n results[\"redeemScript\"])\n\n\n################################################################################################\n#\n# Main \"withdraw\" function\n#\n################################################################################################\n\ndef withdraw_interactive():\n \"\"\"\n Construct and sign a transaction to withdaw funds from cold storage\n All data required for transaction construction is input at the terminal\n \"\"\"\n\n safety_checklist()\n ensure_bitcoind_running()\n require_minimum_bitcoind_version(170000) # signrawtransaction API changed in v0.17.0\n\n approve = False\n\n while not approve:\n addresses = OrderedDict()\n\n print(\"\\nYou will need to enter several pieces of information to create a withdrawal transaction.\")\n print(\"\\n\\n*** PLEASE BE SURE TO ENTER THE CORRECT DESTINATION ADDRESS ***\\n\")\n\n source_address = input(\"\\nSource cold storage address: \")\n addresses[source_address] = 0\n\n redeem_script = input(\"\\nRedemption script for source cold storage address: \")\n\n dest_address = input(\"\\nDestination address: \")\n addresses[dest_address] = 0\n\n num_tx = int(input(\"\\nHow many unspent transactions will you be using for this withdrawal? \"))\n\n txs = []\n utxos = []\n utxo_sum = Decimal(0).quantize(SATOSHI_PLACES)\n\n while len(txs) < num_tx:\n print(\"\\nPlease paste raw transaction #{} (hexadecimal format) with unspent outputs at the source address\".format(len(txs) + 1))\n print(\"OR\")\n print(\"input a filename located in the current directory which contains the raw transaction data\")\n print(\"(If the transaction data is over ~4000 characters long, you _must_ use a file.):\")\n\n hex_tx = input()\n if os.path.isfile(hex_tx):\n hex_tx = open(hex_tx).read().strip()\n\n tx = bitcoin_cli_json(\"decoderawtransaction\", hex_tx)\n txs.append(tx)\n utxos += get_utxos(tx, source_address)\n\n if len(utxos) == 0:\n print(\"\\nTransaction data not found for source address: {}\".format(source_address))\n sys.exit()\n else:\n print(\"\\nTransaction data found for source address.\")\n\n for utxo in utxos:\n value = Decimal(utxo[\"value\"]).quantize(SATOSHI_PLACES)\n utxo_sum += value\n\n print(\"TOTAL unspent amount for this raw transaction: {} BTC\".format(utxo_sum))\n\n print(\"\\nHow many private keys will you be signing this transaction with? \")\n key_count = int(input(\"#: \"))\n\n keys = []\n while len(keys) < key_count:\n key = input(\"Key #{0}: \".format(len(keys) + 1))\n keys.append(key)\n\n ###### fees, amount, and change #######\n\n input_amount = utxo_sum\n fee = get_fee_interactive(\n source_address, keys, addresses, redeem_script, txs)\n # Got this far\n if fee > input_amount:\n print(\"ERROR: Your fee is greater than the sum of your unspent transactions. Try using larger unspent transactions. Exiting...\")\n sys.exit()\n\n print(\"\\nPlease enter the decimal amount (in bitcoin) to withdraw to the destination address.\")\n print(\"\\nExample: For 2.3 bitcoins, enter \\\"2.3\\\".\")\n print(\"\\nAfter a fee of {0}, you have {1} bitcoins available to withdraw.\".format(fee, input_amount - fee))\n print(\"\\n*** Technical note for experienced Bitcoin users: If the withdrawal amount & fee are cumulatively less than the total amount of the unspent transactions, the remainder will be sent back to the same cold storage address as change. ***\\n\")\n withdrawal_amount = input(\n \"Amount to send to {0} (leave blank to withdraw all funds stored in these unspent transactions): \".format(dest_address))\n if withdrawal_amount == \"\":\n withdrawal_amount = input_amount - fee\n else:\n withdrawal_amount = Decimal(withdrawal_amount).quantize(SATOSHI_PLACES)\n\n if fee + withdrawal_amount > input_amount:\n print(\"Error: fee + withdrawal amount greater than total amount available from unspent transactions\")\n raise Exception(\"Output values greater than input value\")\n\n change_amount = input_amount - withdrawal_amount - fee\n\n # less than a satoshi due to weird floating point imprecision\n if change_amount < 1e-8:\n change_amount = 0\n\n if change_amount > 0:\n print(\"{0} being returned to cold storage address address {1}.\".format(change_amount, source_address))\n\n addresses[dest_address] = str(withdrawal_amount)\n addresses[source_address] = str(change_amount)\n\n # check data\n print(\"\\nIs this data correct?\")\n print(\"*** WARNING: Incorrect data may lead to loss of funds ***\\n\")\n\n print(\"{0} BTC in unspent supplied transactions\".format(input_amount))\n for address, value in addresses.items():\n if address == source_address:\n print(\"{0} BTC going back to cold storage address {1}\".format(value, address))\n else:\n print(\"{0} BTC going to destination address {1}\".format(value, address))\n print(\"Fee amount: {0}\".format(fee))\n print(\"\\nSigning with private keys: \")\n for key in keys:\n print(\"{}\".format(key))\n\n print(\"\\n\")\n confirm = yes_no_interactive()\n\n if confirm:\n approve = True\n else:\n print(\"\\nProcess aborted. Starting over....\")\n\n #### Calculate Transaction ####\n print(\"\\nCalculating transaction...\\n\")\n\n unsigned_tx = create_unsigned_transaction(\n source_address, addresses, redeem_script, txs)\n\n signed_tx = sign_transaction(source_address, keys,\n redeem_script, unsigned_tx, txs)\n\n print(\"\\nSufficient private keys to execute transaction?\")\n print(signed_tx[\"complete\"])\n\n print(\"\\nRaw signed transaction (hex):\")\n print(signed_tx[\"hex\"])\n\n print(\"\\nTransaction fingerprint (md5):\")\n print(hash_md5(signed_tx[\"hex\"]))\n\n write_and_verify_qr_code(\"transaction\", \"transaction.png\", signed_tx[\"hex\"])\n\n\n################################################################################################\n#\n# main function\n#\n# Show help, or execute one of the three main routines: entropy, deposit, withdraw\n#\n################################################################################################\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('program', choices=[\n 'entropy', 'create-deposit-data', 'create-withdrawal-data'])\n\n parser.add_argument(\"--num-keys\", type=int,\n help=\"The number of keys to create random entropy for\", default=1)\n parser.add_argument(\"-d\", \"--dice\", type=int,\n help=\"The minimum number of dice rolls to use for entropy when generating private keys (default: 62)\", default=62)\n parser.add_argument(\"-r\", \"--rng\", type=int,\n help=\"Minimum number of 8-bit bytes to use for computer entropy when generating private keys (default: 20)\", default=20)\n parser.add_argument(\n \"-m\", type=int, help=\"Number of signing keys required in an m-of-n multisig address creation (default m-of-n = 1-of-2)\", default=1)\n parser.add_argument(\n \"-n\", type=int, help=\"Number of total keys required in an m-of-n multisig address creation (default m-of-n = 1-of-2)\", default=2)\n parser.add_argument('--testnet', type=int, help=argparse.SUPPRESS)\n parser.add_argument('-v', '--verbose', action='store_true', help='increase output verbosity')\n args = parser.parse_args()\n\n verbose_mode = args.verbose\n\n global cli_args, wif_prefix\n cli_args = [\"-testnet\", \"-rpcport={}\".format(args.testnet), \"-datadir=bitcoin-test-data\"] if args.testnet else []\n wif_prefix = \"EF\" if args.testnet else \"80\"\n\n if args.program == \"entropy\":\n entropy(args.num_keys, args.rng)\n\n if args.program == \"create-deposit-data\":\n deposit_interactive(args.m, args.n, args.dice, args.rng)\n\n if args.program == \"create-withdrawal-data\":\n withdraw_interactive()\n","repo_name":"GlacierProtocol/GlacierProtocol","sub_path":"glacierscript.py","file_name":"glacierscript.py","file_ext":"py","file_size_in_byte":30761,"program_lang":"python","lang":"en","doc_type":"code","stars":145,"dataset":"github-code","pt":"20"} +{"seq_id":"74405090610","text":"from os import mkdir as os_mkdir\nfrom os import listdir as os_listdir\nfrom os.path import exists as os_path_exists\nfrom os import remove as os_remove\nfrom cv2 import imread as cv2_imread\nfrom cv2 import hconcat as cv2_hconcat\nfrom cv2 import vconcat as cv2_vconcat\nfrom cv2 import imwrite as cv2_imwrite\nfrom Game import Game\nfrom Levels import Levels\nfrom pyautogui import size as pyautogui_size\nimport matplotlib.pyplot as plt\nfrom Levels_colors_list import Levels_colors_list \n\ndef divisor_closest_to_sqrt(n):\n from numpy import ceil, sqrt\n d = 1\n for k in range(1, int(ceil(sqrt(n))) + 1):\n if n % k == 0:\n d = k\n return min(n // d, d)\n\nif __name__ == \"__main__\":\n \n racine = __file__\n racine = racine.split('\\\\')\n del racine[-1]\n racine.append('images')\n racine = '/'.join(racine)\n if not os_path_exists(racine):\n os_mkdir(racine)\n for file in os_listdir(racine):\n file = racine + '/' + file\n if 'level' in file:\n os_remove(file)\n\n # TOTAL_SIZE = pyautogui_size()\n # Game(save_image=1, time_between_level_changing=0, show_help=0).play()\n # TOTAL_SIZE = [1920, 1055]\n game_color = Levels_colors_list.FROM_HUE(hu=0, sa=0, li=0.4)\n game_color = None\n # Game(is_fullscreen=0, save_image=1, game_color=game_color).play()\n # Game(is_fullscreen=1, save_image=1, game_color=game_color).play()\n\n if not os_path_exists('images'):\n os_mkdir('images')\n\n if not os_path_exists('images/concat'):\n os_mkdir('images/concat')\n \n n_levels = Levels.number_of_levels\n n = divisor_closest_to_sqrt(n_levels)\n m = n_levels // n\n for size in [[1920, 1200],\n [1920, 1080],\n [1366, 768]]: # [1346, 668], [1920, 1001], [1920, 1055],\n try:\n WIDTH, HEIGHT = size\n string = \"WIDTH_{}_HEIGHT_{}\".format(WIDTH, HEIGHT)\n dico = {}\n for file in os_listdir(racine):\n if string in file and not \"HELP\" in file:# and not \"concat\" in file:\n k = int(file.split('_')[1])\n dico[k] = '/'.join([racine, file])\n file_list = []\n for k in sorted(dico.keys()):\n file_list.append(dico[k])\n \n assert m >= n, f'~ {m} <= {n}'\n # assert m * n == len(file_list), \"\"\"{0}, {1}, {2}\"\"\".format(m, n, len(file_list))\n l_img_h = []\n for i in range(m):\n l = file_list[n * i:n * i + n]\n if len(l) == 1:\n l_img_h.append(l[0])\n else:\n l = [cv2_imread(file) for file in l]\n im_h = cv2_hconcat(l)\n l_img_h.append(im_h)\n img = cv2_vconcat(l_img_h)\n plt.imshow(img)\n plt.close()\n filename = r'images/concat/concat_levels_{}.jpg'.format(string)\n cv2_imwrite(filename, img)\n print(filename)\n \n WIDTH, HEIGHT = size\n string = \"WIDTH_{}_HEIGHT_{}\".format(WIDTH, HEIGHT)\n dico = {}\n for file in os_listdir(racine):\n if string in file and \"HELP\" in file and not \"concat\" in file:\n k = int(file.split('_')[2])\n dico[k] = '/'.join([racine, file])\n file_list = []\n for k in sorted(dico.keys()):\n file_list.append(dico[k])\n \n # assert m <= n\n assert m * n == len(file_list)\n l_img_h = []\n for i in range(m):\n l = file_list[n * i:n * i + n]\n if len(l) == 1:\n l_img_h.append(l[0])\n else:\n l = [cv2_imread(file) for file in l]\n im_h = cv2_hconcat(l)\n l_img_h.append(im_h)\n img_h = cv2_vconcat(l_img_h)\n plt.imshow(img_h)\n plt.close()\n filename = r'images/concat/concat_levels_HELP_{}.jpg'.format(string)\n cv2_imwrite(filename, img_h)\n except TypeError:\n pass\n \n n_levels = len(Levels.levels_list)\n lx = [i for i in range(n_levels, n_levels+30)]\n ly = []\n for i in lx:\n a = divisor_closest_to_sqrt(i)\n b = i//a\n a, b = min(a, b), max(a, b)\n ly.append(a/b)\n plt.plot(lx, ly)\n plt.scatter(lx, ly)\n plt.grid(True)","repo_name":"Zackary-Vanche/logic_gates_mazes","sub_path":"src/image_fusion.py","file_name":"image_fusion.py","file_ext":"py","file_size_in_byte":4413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25288351534","text":"import pytest\n\nfrom influxdb import InfluxDBClient\n\n\nINFLUX_URI = '127.0.0.1'\nINFLUX_PORT = 8086\nINFLUX_DBNAME = 'acceptation_test'\n\n\n@pytest.fixture()\ndef influx_database(influxdb_content):\n \"\"\"\n connect to a local influx database (localhost:8086) and store data contained in the list influxdb_content\n after test end, delete the data\n \"\"\"\n client = InfluxDBClient(host=INFLUX_URI, port=INFLUX_PORT)\n _delete_db(client, INFLUX_DBNAME)\n _init_db(client, influxdb_content)\n yield client\n _delete_db(client, INFLUX_DBNAME)\n\n\ndef _init_db(client, content):\n\n if content != []:\n client.create_database(INFLUX_DBNAME)\n client.switch_database(INFLUX_DBNAME)\n client.write_points(content)\n\n\ndef _delete_db(client, db_name):\n client.drop_database(db_name)\n client.close()\n\n\ndef get_all_reports(client, db_name):\n \"\"\"\n get all points stored in the database during test execution\n \"\"\"\n client.switch_database(db_name)\n result = client.query('SELECT * FROM \"power_consumption\"')\n return list(result.get_points())\n","repo_name":"powerapi-ng/powerapi","sub_path":"tests/utils/db/influx.py","file_name":"influx.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":146,"dataset":"github-code","pt":"20"} +{"seq_id":"31438232046","text":"from setuptools import setup\nfrom setuptools.command.install import install\nfrom distutils.version import LooseVersion\nimport os\nimport shutil\nimport warnings\nfrom distutils.util import strtobool\nimport sys\n\n\n# Utility function to read the README file.\n# Used for the long_description. It's nice, because now 1) we have a top level\n# README file and 2) it's easier to type in the README file than to put a raw\n# string in below ...\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\ndependencies = [\n \"appdirs\",\n \"prettytable\",\n \"simpleyaml\",\n \"numpy\",\n \"scipy\",\n \"pandas\",\n \"joblib\"\n]\n\n# Detect if pygtk is already available. Only add it to the\n# dependency list if it can't be imported. This avoids a failure\n# state on Ubuntu where pip can't see that pygtk is already installed,\n# then tries (and fails) to build it, preventing installation.\ntry:\n import pygtk\nexcept ImportError:\n dependencies.append(\"pygtk\")\n\n# Detect if matplotlib >= 1.4 is already available. This is similar to the \n# pygtk issue - pip doesn't see the OS version and overwrites it with \n# a version that doesn't have GTK support.\ntry:\n import matplotlib\n\n # We don't want to overwrite any native matplotlib, \n # however, we should issue a warning if there is an old version.\n\n if LooseVersion(matplotlib.__version__) < LooseVersion(\"1.4\"):\n warnings.warn(\"Detected matplotlib {}. Superplot requires \"\n \"version 1.4 or greater. Please upgrade manually.\".format(\n matplotlib.__version__\n )\n )\nexcept ImportError:\n # No version available - add to deps\n warnings.warn(\"matplotlib not detected. Please install matplotlib version 1.4 or \"\n \"greater. Note that superplot requires a version of matplotlib with \"\n \"GTK backend support.\")\n\nsetup(\n setup_requires=[\"setuptools_git\", \"appdirs\"],\n\n install_requires=dependencies,\n\n packages=[\n \"superplot\",\n \"superplot.plotlib\",\n \"superplot.plotlib.styles\",\n \"superplot.statslib\"\n ],\n include_package_data=True,\n\n name=\"superplot\",\n version=\"2.0.4\",\n author=\"Andrew Fowlie, Michael Bardsley\",\n author_email=\"mhbar3@student.monash.edu\",\n license=\"GPL v2\",\n url=\"https://github.com/michaelhb/superplot\",\n\n description=\"Python GUI for plotting SuperPy/SuperBayes/MultiNest/BAYES-X results\",\n long_description=read(\"README.rst\"),\n\n entry_points={\n 'gui_scripts': [\n 'superplot_gui = superplot.super_gui:main',\n 'superplot_summary = superplot.summary:main',\n 'superplot_cli = superplot.super_command:main',\n 'superplot_create_home_dir = superplot.create_home_dir:main'\n ]\n }\n)\n","repo_name":"michaelhb/superplot","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"37604605128","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport re\nimport json\nimport os \nimport pandas as pd\nimport flask\nfrom flask import Flask\nfrom flask import request\n#for the search_text function\nfrom difflib import get_close_matches \nfrom py_openthesaurus import OpenThesaurusWeb\nopen_thesaurus = OpenThesaurusWeb()\nimport logging\nimport requests\n\napp = Flask(__name__)\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\n#Defining class for the rows (Accounts) in excel\nclass Account: #account_line\n def __init__(self, id, desc, searchTerms, negativeTerms, amount, duration, usage, stage2_logic, category,stage3_result):\n self.id = id\n self.desc = desc\n self.searchTerms = searchTerms\n self.negativeTerms = negativeTerms\n self.amount = amount\n self.duration = duration\n self.usage = usage\n self.stage2_logic = stage2_logic\n self.category = category\n self.stage3_result = stage3_result\n\n def toJSON(self):\n return json.dumps(self, default=lambda o: o.__dict__, indent=4)\n\n#Defining class for the variables in excel\nclass Amount:\n def __init__(self, id):\n self.id = id\n\n def toJSON(self):\n return json.dumps(self, default=lambda o: o.__dict__,\n sort_keys=True, indent=4)\n\nclass Duration:\n def __init__(self, id):\n self.id = id\n\n def toJSON(self):\n return json.dumps(self, default=lambda o: o.__dict__,\n sort_keys=True, indent=4)\n\nclass Usage:\n def __init__(self, id):\n self.id = id\n\n\n# Getting excel data into the predefined objects\ndef getExcelData():\n thisFolder = os.path.dirname(os.path.abspath(__file__))\n my_file = os.path.join(thisFolder, 'Datei.xlsx')\n excel_import = pd.read_excel(\n my_file, dtype=str)\n #excel_import = pd.read_excel(\n # \"C:\\\\Users\\\\cts\\\\Horváth & Partner GmbH\\\\IFUA-IDEX.TAN.T55170 - 02_Munka\\\\01_Projektmunka_IFUA\\\\Datei.xlsx\", dtype=str)\n listOfAccounts = []\n for index, row in excel_import.iterrows():\n searchTerms = [\"\"] if pd.isnull(\n row.iloc[2]) else row.iloc[2].replace(\" \", \"\").split(\",\")\n negativeTerms = [\"\"] if pd.isnull(\n row.iloc[3]) else row.iloc[3].replace(\" \", \"\").split(\",\")\n amount = Amount(re.split(\",|\\.\", row.iloc[4]))\n duration = Duration(re.split(\",|\\.\", row.iloc[5]))\n usage = Usage(row.iloc[6])\n stage2_logic=[\"\"] if pd.isnull(\n row.iloc[8]) else row.iloc[8].replace(\" \", \"\").split(\",\")\n listOfAccounts.append(\n Account(\n row.iloc[0],\n row.iloc[1],\n searchTerms,\n negativeTerms,\n amount,\n duration,\n usage,\n stage2_logic, # stage 2 logic id\n row.iloc[9], #übergeordnete kategories\n row.iloc[7] # stage3_result\n ))\n return listOfAccounts\n\n#TODO fv-t magat bepakolni az account_list helyett?\naccount_list = getExcelData()\n\n#Filtering for amount,duration, usage, categories\ndef amountSearch(results, amount):\n newResults = []\n for account in results:\n ids = account.amount.id\n for acc_amount in ids:\n if(str(acc_amount) == amount or str(acc_amount)==\"0\"):\n newResults.append(account)\n return newResults\n\ndef durationSearch(results, duration):\n newResults = []\n for account in results:\n ids = account.duration.id\n for acc_duration in ids:\n if(str(acc_duration) == duration):\n newResults.append(account)\n return newResults\n\ndef usageSearch(results, usage):\n newResults = []\n for account in results:\n if(str(account.usage.id) == usage): \n newResults.append(account)\n return newResults\n\n# TODO: above functions can be simplified by leaving out a for loop like this - using dictionaries instead-> faster!!!\n\ndef categorySearch(results, category):\n newResults = []\n for account in results:\n if(str(account.category) == category): \n newResults.append(account)\n return newResults\n\n### Stage 2: Amount, Duration, Usage question and answer dictionaries\n\n#Question logic\ndef questionLogic(results):\n l_temp = []\n for account in results:\n l_temp.append(account.stage2_logic)\n if len(set([''.join(lst) for lst in l_temp]))==1: # converting list to string to be able to get the distinct list values\n newResults=l_temp[0]\n else:\n newResults=['Amount', 'Usage','Duration'] \n # TODO:default question and order - beletenni hogy ha nincs usage a leszurt excelbe akk a default se legyen usage\n return newResults\n\n#Importing additional excel sheets (id-text dictionaries) \n#amount\n#xlsx = pd.ExcelFile('C:\\\\Users\\\\cts\\\\Horváth & Partner GmbH\\\\IFUA-IDEX.TAN.T55170 - 02_Munka\\\\01_Projektmunka_IFUA\\\\Datei.xlsx')\nthisFolder = os.path.dirname(os.path.abspath(__file__))\nmy_file = os.path.join(thisFolder, 'Datei.xlsx')\nxlsx = pd.ExcelFile(my_file)\n#xlsx = pd.ExcelFile('C:\\\\Users\\\\hdo\\\\Horváth & Partner GmbH\\HP SAP S4 ACCOUNT IDENTIFIER FEJLESZTES NP - IFUA-IDEX.TAN.T55170 - 02_Munka\\\\01_Projektmunka_IFUA\\\\Datei.xlsx')\ndf = xlsx.parse(xlsx.sheet_names[1])\nd_amount=df.set_index('ID').T.to_dict('records')[0]\n#duration\ndf = xlsx.parse(xlsx.sheet_names[2])\nd_duration=df.set_index('ID').T.to_dict('records')[0]\n#usage\ndf = xlsx.parse(xlsx.sheet_names[3])\nd_usage=df.set_index('ID').T.to_dict('records')[0]\n#übergeordnete category\ndf = xlsx.parse(xlsx.sheet_names[4])\nd_category=df.set_index('ID').T.to_dict('records')[0]\n\n#Dictionary for übergeordnete categories \nd_cats={\"id\": \"c1\",\n \"text\": \"Bitte wählen Sie eine Kategorie:\",\n \"answers\": [\n {\n \"id\": \"c1\",\n \"text\": d_category[\"c1\"]\n },\n {\n \"id\": \"c2\",\n \"text\": d_category[\"c2\"]\n },\n {\n \"id\": \"c3\",\n \"text\": d_category[\"c3\"]\n },\n {\n \"id\": \"c4\",\n \"text\": d_category[\"c4\"]\n },\n {\n \"id\": \"c5\",\n \"text\": d_category[\"c5\"]\n },\n {\n \"id\": \"c6\",\n \"text\": d_category[\"c6\"]\n },\n {\n \"id\": \"c7\",\n \"text\": d_category[\"c7\"]\n },\n {\n \"id\": \"c8\",\n \"text\": d_category[\"c8\"]\n },\n {\n \"id\": \"c9\",\n \"text\": d_category[\"c9\"]\n },\n {\n \"id\": \"c10\",\n \"text\": d_category[\"c10\"]\n },\n {\n \"id\": \"c11\",\n \"text\": d_category[\"c11\"]\n },\n {\n \"id\": \"c12\",\n \"text\": d_category[\"c12\"]\n }\n ],\n \"infobox\":None\n}\n\n#All potential answers to stage2 questions\n#Answers for Amount and Duration questions\nd_answers={1: {\n \"id\": 0,\n \"text\": \"na\",\n \"question\":\"Amount\"\n },\n 2: {\n \"id\": 1,\n \"text\": \"<10\",\n \"question\":\"Amount\"\n },\n 3: {\n \"id\": 2,\n \"text\": \"10,01-59,99\",\n \"question\":\"Amount\"\n },\n 4: {\n \"id\": 3,\n \"text\": \"60-249,99\",\n \"question\":\"Amount\"\n },\n 5: {\n \"id\": 4,\n \"text\": \">250\",\n \"question\":\"Amount\"\n },\n 6: {\n \"id\": 0,\n \"text\": \"na\",\n \"question\":\"Duration\"\n },\n 7: {\n \"id\": 1,\n \"text\": \"< 1 Jahr\",\n \"question\":\"Duration\"\n },\n 8: {\n \"id\": 2,\n \"text\": \"> 1 Jahr\",\n \"question\":\"Duration\"\n }\n }\n\n#Adding answers for Usage questions to the d_answers dictionary\nfor i in range(1,len(d_usage)+1):\n d_answers[8+i]={\n \"id\": i,\n \"text\": d_usage[i],\n \"question\":\"Usage\"\n }\n#d_answers id-s: 1 to 98\n\n### Reversed dicts per question type to get the api_ids for the answers\n#Amount\nexcel_ids=[]\nfor l in range(1,6):\n excel_ids.append(d_answers[l][\"id\"])\napi_ids=[]\nfor l in range(1,6):\n api_ids.append(l)\nd_amount_id=dict(zip(excel_ids,api_ids))\n#Duration\nexcel_ids=[]\nfor l in range(6,9):\n excel_ids.append(d_answers[l][\"id\"])\napi_ids=[]\nfor l in range(6,9):\n api_ids.append(l)\nd_duration_id=dict(zip(excel_ids,api_ids))\n#Usage\nexcel_ids=[]\nfor l in range(9,99):\n excel_ids.append(d_answers[l][\"id\"])\napi_ids=[]\nfor l in range(9,99):\n api_ids.append(l)\nd_usage_id=dict(zip(excel_ids,api_ids))\n\n#Function for getting available answers for Amount,Duration,Usage quesstions\ndef create_answers(results):\n #Amount\n # list of available amount ids\n l_amount=[]\n for i in range(len(results)):\n l_amount.extend(results[i].amount.id)\n l_amount=list(set(l_amount))\n \n # if there is a 0 (na) then all the answers should be shown\n if \"0\" in l_amount:\n l_amount=[\"1\",\"2\",\"3\",\"4\"]\n \n #list of dictionaries of available amount ids\n l_answers_amount=[]\n for i in range(len(l_amount)): \n s={\n \"id\": d_amount_id[int(l_amount[i])], #api id for l_amount[i]\n \"text\": d_amount[int(l_amount[i])] \n }\n l_answers_amount.append(s)\n \n #Duration\n l_duration=[]\n for i in range(len(results)):\n l_duration.extend(results[i].duration.id)\n l_duration=list(set(l_duration))\n\n # if there is a 0 (na) then all the answers should be shown\n if \"0\" in l_duration:\n l_duration=[\"1\",\"2\"]\n\n l_answers_duration=[]\n for i in range(len(l_duration)): \n s={\n \"id\": d_duration_id[int(l_duration[i])], \n \"text\": d_duration[int(l_duration[i])] \n }\n l_answers_duration.append(s)\n \n #Usage\n l_usage=[]\n for i in range(len(results)):\n l_usage.append(results[i].usage.id) #append instead of extend, because there are only 1 id there, with extend it doesnt work\n l_usage=list(set(l_usage))\n\n l_answers_usage=[]\n for i in range(len(l_usage)): \n s={\n \"id\": d_usage_id[int(l_usage[i])], \n \"text\": d_usage[int(l_usage[i])] \n }\n l_answers_usage.append(s)\n\n #Getting rid of the nan answer for each question\n for i, d in enumerate(l_answers_duration):\n if pd.isna(d['text']):\n l_answers_duration.pop(i)\n break\n\n for i, d in enumerate(l_answers_amount):\n if pd.isna(d['text']):\n l_answers_amount.pop(i)\n break\n\n for i, d in enumerate(l_answers_usage):\n if pd.isna(d['text']):\n l_answers_usage.pop(i)\n break\n \n # ordering answer dictionaries:\n l_answers_amount=sorted(l_answers_amount, key = lambda i: i['id'])\n l_answers_duration=sorted(l_answers_duration, key = lambda i: i['id'])\n l_answers_usage=sorted(l_answers_usage, key = lambda i: i['id'])\n \n # d_questions dictionary with the questions and the potential answers\n d_questions={\n \"Amount\": {\n \"id\": 1,\n \"text\": \"Betrag:\",\n \"answers\": l_answers_amount,\n \"infobox\":\"Bitte Betrag in NETTO EUR pro Einheit (bspw. sonstige Betriebsaufw., Büromaterial) oder pro Person (bspw. bei Bewirtung, Geschenken) angeben. Die Beträge müssen sich auf Positionen in einer Banf, Bestellung oder Angebot beziehen; nicht der Rechnungsbetrag.\"\n },\n \"Duration\": {\n \"id\": 2,\n \"text\": \"Nutzungsdauer:\",\n \"answers\":l_answers_duration,\n \"infobox\":\"Geben Sie an, über welchen Zeitraum Sie Ihren gewünschten Bedarf voraussichtlich nutzen und er dem Unternehmen zur Verfügung steht.\"\n },\n \"Usage\": {\n \"id\": 3,\n \"text\": \"Verwendungszweck:\",\n \"answers\": l_answers_usage,\n \"infobox\":\"Wählen Sie für Ihren Bedarf den dazu passenden Verwendungszweck aus. Bsp.: Bedarf: 'Verschenken von Modellauto' -> Verwendungszweck: 'Empfänger: Mitarbeiter (für Bewirtung & Geschenke)'\"\n }\n }\n return d_questions\n\n### Stage 3 - Instandhaltung: linked lists for decision trees\n\n#Defining Question and Answer class for the decision trees\nclass Question:\n def __init__(self, id, text, answers, infobox):\n self.id = id\n self.text =text\n self.answers = answers\n self.infobox = infobox\n\nclass Answer:\n def __init__(self, id, text, next_question,question,account_name): # account is egy plusz objektum\n self.id = id\n self.text = text\n self.next_question = next_question\n self.question=question\n self.account_name = account_name\n\n#Question objects\n#When beside Amount, Duration, Usage more questions or answers are used, these id-s should be changed as well\n#Instandhaltung decision tree\nq1=Question(4,\"Handelt es sich um eine reine Instandhaltungsmaßnahme?\",[{\"id\":101,\"text\":\"Ja\"},{\"id\":102,\"text\":\"Nein\"}], \"Die Instandhaltung ist die Gesamtheit der Maßnahmen zur Bewahrung des Soll-Zustandes sowie zur Festlegung und Beurteilung des Ist-Zustandes. Solche Maßnahmen sind: (1) Inspektion (Feststellung und Beurteilung des Ist-Zustandes), (2) Wartung / Reparatur (Bewahrung des Soll-Zustandes), (3) Instandsetzung (Wiederherstellung des Soll-Zustandes).\")\nq2=Question(5,\"Findet ein Austausch von bereits vorhandenen Gegenständen statt?\",[{\"id\":103,\"text\":\"Ja\"},{\"id\":104,\"text\":\"Nein\"}], \"Beispiele für den Austausch von bereits vorhandenen Gegenständen: (1) Austausch eines zerbrochenen Fensters am Firmengebäude, (2) Ölwechsel bei einem Kran, (3) Wartung einer Fertigungsmaschine, (4) Überwachung einer Produktionsanlage durch Messtechnik, (5) Reparatur der Sanitäranlagen im Firmengebäude\")\nq3=Question(6,\"Wird durch die Maßnahme ein über dem einst vorhandenen Standard liegender Zustand erreicht (Standardhebung)?\",[{\"id\":105,\"text\":\"Ja\"},{\"id\":106,\"text\":\"Nein\"}], \"Indizien für die Standarderhebung: (1) ein Gebäude wird in zeitl. Nähe zum Erwerb im Ganzen und von Grund auf modernisiert, (2) hohe Aufw. für die Sanierung der zentralen Ausstattungsmerk. werden getätigt, (3) aufgrund dieser Baumaßnahme wird der Mietzins erheblich erhöht.\")\n#Werkvertrag/Dienstvertrag (WVDV) decision tree\nq4=Question(7,\"Handelt es sich um einen materiellen oder immateriellen Bedarf?\",[{\"id\":107,\"text\":\"Materiell\"},{\"id\":108,\"text\":\"Immateriell\"}], \"Materiell: Sache oder ein Gegenstand, der körperlich existiert (z.B. Gabelstapler, Schrauber). Immateriell: nicht körperlich greifbar (z.B. Dienstleistung, Lizenz)\")\nq5=Question(8,\"Ist ein konkretes Arbeitsergebnis Gegenstand des Vertrags?\",[{\"id\":109,\"text\":\"Ja\"},{\"id\":110,\"text\":\"Nein\"},{\"id\":111,\"text\":\"Nicht bekannt\"}],\"Ein konkretes Arbeitsergebnis liegt vor, wenn die Verpflichtung zur Herstellung eines Werks / eines Ergebnisses (z.B. Reparaturvertrag, Erstellung von Gutachten) erfüllt ist.\")\nq6=Question(9,\"Können alle Fragen in der Infobox bejaht werden?\",[{\"id\":112,\"text\":\"Ja\"},{\"id\":113,\"text\":\"Nein\"}], \"Das Unternehmen... (1) ...verfügt über fundiertes Know How (2) ...definiert Meilensteine (3) ...trägt/stellt die Projektverantwortung /-leiter (4) ...übernimmt Vorgaben und Überwachung (5) ...trägt die wesentlichen Chancen und Risiken (6) ...kann den Ausgang der Entwicklung beeinflussen (7) ...trägt das Produktrisiko\")\n#Sachgesamtheit / Aktivierung decision tree\nq7=Question(10,\"Gehört der Bedarf zu einer bestehenden / neuen Sachanlage? \",[{\"id\":114,\"text\":\"Ja\"},{\"id\":115,\"text\":\"Nein\"}], \"Sachanlagen sind körperlich und greifbar (materiell), z.B. Laptop, Maschinen, Tisch\")\nq8=Question(11,\"Ist die Anlagenummer bekannt?\",[{\"id\":116,\"text\":\"Ja\"},{\"id\":117,\"text\":\"Nein\"}], \"Geben Sie, falls der Bedarf zu einer bestehenden Anlage gehört, die entsprechende Anlagennummer an.\")\nq9=Question(12,\"Handelt es sich bei Ihrem Bedarf um einen Gegenstand, der nicht selbstständig genutzt werden kann? (z.B. Dockingstation)\",[{\"id\":118,\"text\":\"Ja\"},{\"id\":119,\"text\":\"Nein\"}], \"Die selbständige Nutzung eines Gegenstandes setzt voraus, dass sie unabhängig von anderen Wirtschaftsgütern genutzt werden kann, bspw. Drucker.\")\n#Einkauf/Vertrieb decision tree\nq10=Question(13,\"Handelt es um Transportkosten mit Bezug auf den Vertrieb? (Ausgangsfracht)\",[{\"id\":120,\"text\":\"Ja\"},{\"id\":121,\"text\":\"Nein\"}], \"Zu den Transportkosten im Rahmen des Vertriebs gehören Waren, die an den Kunden ausgeliefert werden.\")\nq11=Question(14,\"Handelt es sich um Versandkosten für ...?\",[{\"id\":122,\"text\":\"Fahrzeuge\"},{\"id\":123,\"text\":\"Ersatzteile\"},{\"id\":124,\"text\":\"Sonstiges\"},{\"id\":125,\"text\":\"Nein\"}], None)\nq12=Question(15,\"Gehören die Transportkosten zu einer bestehenden / neuen Sachanlage?\",[{\"id\":126,\"text\":\"Ja\"},{\"id\":127,\"text\":\"Nein\"}], \"Sachanlagen sind körperlich und greifbar (materiell), z.B. Laptop, Maschinen, Tisch\")\nq13=Question(16,\"Ist die Anlagenummer bekannt?\",[{\"id\":128,\"text\":\"Ja\"},{\"id\":129,\"text\":\"Nein\"}], \"Geben Sie, falls der Bedarf zu einer bestehenden Anlage gehört, die entsprechende Anlagennummer an.\")\nq14=Question(17,\"Handelt es sich um Logistikkosten eines Serienlieferanten?)\",[{\"id\":130,\"text\":\"Ja\"},{\"id\":131,\"text\":\"Nein\"}], \"Zu den Serienlieferanten gehören bspw. Bosch und Mahle.\")\nq15=Question(18,\"Weitere Spezifikation:\",[{\"id\":132,\"text\":\"Verpackung und Versand Material im Werk\"},{\"id\":133,\"text\":\"Eingangstransportkosten\"},\n {\"id\":134,\"text\":\"Ungeplante Bezugsnebenkosten\"},{\"id\":135,\"text\":\"Zölle\"},\n {\"id\":136,\"text\":\"See- / Frachtkosten\"},{\"id\":137,\"text\":\"Inboundkosten (WE, Verpackung, Einlagerung, Retouren) des Logistikdienstleisters PLOG\"}], None)\n\n#Answer objects\n#When besoide Amount, Duration, Usage more questions or answers are used, these id-s should be changed as well\n#Instandhaltung decision tree\na1=Answer(101,\"Ja\",next_question=q2,question=q1,account_name=None)\na2=Answer(102,\"Nein\",next_question=None,question=q1,account_name=\"Invest-Dummy-Konto\")\na3=Answer(103,\"Ja\",next_question=q3,question=q2,account_name=None)\na4=Answer(104,\"Nein\",next_question=None,question=q2,account_name=\"Invest-Dummy-Konto\")\na5=Answer(105,\"Ja\",next_question=None,question=q3,account_name=\"Invest-Dummy-Konto\")\na6=Answer(106,\"Nein\",next_question=None,question=q3,account_name=\"Aufwandskonto\")\n#Werkvertrag/Dienstvertrag (WVDV) decision tree\na7=Answer(107,\"Materiell\",next_question=None,question=q4,account_name=\"Invest-Dummy-Konto\")\na8=Answer(108,\"Immateriell\",next_question=q5,question=q4,account_name=None)\na9=Answer(109,\"Ja\",next_question=q6,question=q5,account_name=None)\na10=Answer(110,\"Nein\",next_question=None,question=q5,account_name=\"Aufwandskonto\")\na11=Answer(111,\"Nicht bekannt\",next_question=None,question=q5,account_name=\"Invest-Dummy-Konto\")\na12=Answer(112,\"Ja\",next_question=None,question=q6,account_name=\"Aufwandskonto\")\na13=Answer(113,\"Nein\",next_question=None,question=q6,account_name=\"Invest-Dummy-Konto\")\n#Sachgesamtheit / Aktivierung decision tree\na14=Answer(114,\"Ja\",next_question=q8,question=q7,account_name=None)\na15=Answer(115,\"Nein\",next_question=q9,question=q7,account_name=None)\na16=Answer(116,\"Ja\",next_question=None,question=q8,account_name=\"Invest-Dummy-Konto\")\na17=Answer(117,\"Nein\",next_question=None,question=q8,account_name=\"Invest-Dummy-Konto\")\na18=Answer(118,\"Ja\",next_question=None,question=q9,account_name=\"Invest-Dummy-Konto\")\na19=Answer(119,\"Nein\",next_question=None,question=q9,account_name=\"Aufwandskonto\")\n#Einkauf/Vertrieb decision tree\na20=Answer(120,\"Ja\",next_question=q11,question=q10,account_name=None)\na21=Answer(121,\"Nein\",next_question=q12,question=q10,account_name=None)\na22=Answer(122,\"Fahrezeuge\",next_question=None,question=q11,account_name=\"Specific account\")\na23=Answer(123,\"Ersatzteile\",next_question=None,question=q11,account_name=\"Specific account\")\na24=Answer(124,\"Sonstiges\",next_question=None,question=q11,account_name=\"Specific account\")\na25=Answer(125,\"Nein\",next_question=None,question=q11,account_name=\"Specific account\")\na26=Answer(126,\"Ja\",next_question=q13,question=q12,account_name=None)\na27=Answer(127,\"Nein\",next_question=q14,question=q12,account_name=None)\na28=Answer(128,\"Ja\",next_question=None,question=q13,account_name=\"Invest-Dummy-Konto\")\na29=Answer(129,\"Nein\",next_question=None,question=q13,account_name=\"Invest-Dummy-Konto\")\na30=Answer(130,\"Ja\",next_question=None,question=q14,account_name=\"Specific account\")\na31=Answer(131,\"Nein\",next_question=q15,question=q14,account_name=\"Aufwandskonto\")\na32=Answer(132,\"Verpackung und Versand Material im Werk\",next_question=None,question=q15,account_name=\"Specific account\")\na33=Answer(133,\"Eingangstransportkosten\",next_question=None,question=q15,account_name=\"Specific account\")\na34=Answer(134,\"Ungeplante Bezugsnebenkosten\",next_question=None,question=q15,account_name=\"Specific account\")\na35=Answer(135,\"Zölle\",next_question=None,question=q15,account_name=\"Specific account\")\na36=Answer(136,\"See- / Frachtkosten\",next_question=None,question=q15,account_name=\"Specific account\")\na37=Answer(137,\"Inboundkosten (WE, Verpackung, Einlagerung, Retouren) des Logistikdienstleisters PLOG\",next_question=None,question=q15,account_name=\"Specific account\")\n\n#Decision tree dictionary\nd_tree={ a1.id:a1,\n a2.id:a2,\n a3.id:a3,\n a4.id:a4,\n a5.id:a5,\n a6.id:a6,\n a7.id:a7,\n a8.id:a8,\n a9.id:a9,\n a10.id:a10,\n a11.id:a11,\n a12.id:a12,\n a13.id:a13,\n a14.id:a14,\n a15.id:a15,\n a16.id:a16,\n a17.id:a17,\n a18.id:a18,\n a19.id:a19,\n a20.id:a20,\n a21.id:a21,\n a22.id:a22,\n a23.id:a23,\n a24.id:a24,\n a25.id:a25,\n a26.id:a26,\n a27.id:a27,\n a28.id:a28,\n a29.id:a29,\n a30.id:a30,\n a31.id:a31,\n a32.id:a32,\n a33.id:a33,\n a34.id:a34,\n a35.id:a35,\n a36.id:a36,\n a37.id:a37\n }\n#Search function with text search (synonyms, positive-negative keywords), categories, amount, duration, usage\ndef search_text(accounts, search_value, category=None, amount=None, duration=None, usage=None): \n search_value_list = search_value.strip().split(\" \")\n results = []\n synonyms = []\n \n #Dealing with no text in textbox\n if search_value_list[0]==\"\": # if there is now text, it shouldnt find anything\n results=[]\n else:\n # searching for synonyms at open thesaurus\n for value in search_value_list:\n params = {\"q\":value, \"format\":\"application/json\"}\n r = requests.get('https://www.openthesaurus.de/synonyme/search', params=params)\n response = json.loads(r.text)\n synonyms_each = []\n for cat in response.get(\"synsets\"):\n for synonym in cat.get(\"terms\"):\n synonyms_each.append(synonym.get(\"term\"))\n synonyms.extend(synonyms_each)\n \n for index, account in enumerate(accounts): # the index and enumerate stuff porbably just counts the loop numbers\n matches = 0\n negative_matches = 0\n \n # get_close_values is used to make the search case insensitive and more robust. With different cutoff values the closeness of the results can be set.\n for value in search_value_list: \n if len(get_close_matches(value.casefold(), map(str.casefold, account.searchTerms), cutoff=0.84)) > 0: \n matches += 1\n # if any synonym of the search term is in the list then we get a match\n for value in search_value_list:\n if any(item.casefold() in map(str.casefold, synonyms) for item in map(str.casefold, account.searchTerms)):\n matches += 1\n \n # if the searched term (robust search) or a synonym is in the negative keyword list then dont append to result\n for value in search_value_list: \n if len(get_close_matches(value.casefold(), map(str.casefold, account.negativeTerms), cutoff=0.84)) > 0: \n negative_matches += 1\n for value in search_value_list: \n if any(item.casefold() in map(str.casefold, synonyms) in synonyms for item in map(str.casefold, account.negativeTerms)):\n negative_matches += 1\n \n #if at least one found word in keyword list and no negative matches then append to result! \n if matches > 0 and negative_matches==0: \n results.append(account)\n \n if(category != None):\n results = categorySearch(accounts, category) # when we have category, then we have to search from the given results and not from the text filtered accounts, becouse it is empty\n if(amount != None):\n results = amountSearch(results, amount) # using the predefined functions for amount, duration and usage search; only searching in the results that has been filtered above\n if(duration != None):\n results = durationSearch(results, duration) # only searching in the results that has been filtered above\n if(usage != None):\n results = usageSearch(results, usage) # only searching in the results that has been filtered above\n return results\n\n# #Search function with text search (synonyms, positive-negative keywords), categories,amount,duration,usage\n# def search_text(accounts, search_value, category=None, amount=None, duration=None, usage=None): \n# search_value_list = search_value.split(\" \")\n# results = []\n# synonyms = []\n\n# # searching for synonyms at open thesaurus\n# for value in search_value_list:\n# synonyms.extend(open_thesaurus.get_synonyms(value)) \n\n# for index, account in enumerate(accounts): # the index and enumerate stuff porbably just counts the loop numbers\n# matches = 0\n# negative_matches = 0\n\n# # get_close_values is used to make the search case insensitive and more robust. With different cutoff values the closeness of the results can be set.\n# for value in search_value_list: \n# if len(get_close_matches(value, account.searchTerms, cutoff=0.8)) > 0: \n# matches += 1\n# # if any synonym of the search term is in the list then we get a match\n# for value in search_value_list:\n# if any(item in synonyms for item in account.searchTerms): \n# matches += 1\n\n# # if the searched term (robust search) or a synonym is in the negative keyword list then dont append to result\n# for value in search_value_list: \n# if len(get_close_matches(value, account.negativeTerms, cutoff=0.8)) > 0: \n# negative_matches += 1\n# for value in search_value_list: \n# if any(item in synonyms for item in account.negativeTerms):\n# negative_matches += 1\n \n# #if at least one found word in keyword list and no negative matches then append to result! \n# if matches > 0 and negative_matches==0: \n# results.append(account)\n \n# if(category != None):\n# results = categorySearch(accounts, category) # when we have category, then we have to search from the given results and not from the text filtered accounts, becouse it is empty\n# if(amount != None):\n# results = amountSearch(results, amount) # using the predefined functions for amount, duration and usage search; only searching in the results that has been filtered above\n# if(duration != None):\n# results = durationSearch(results, duration) # only searching in the results that has been filtered above\n# if(usage != None):\n# results = usageSearch(results, usage) # only searching in the results that has been filtered above\n# return results\n\n# stage3 logic function for 1. post request\ndef stage3(results,content,filters):\n\n if results[0].stage3_result==\"Account ID\":\n dict2={ \"sid\":content[\"sid\"],\n \"result\": {\"text\":results[0].desc,\"id\":results[0].id, \"is_asset_number\":False},\n \"cat_list\": None,\n \"question\": None,\n \"filter\": filters\n }\n response=json.dumps(dict2, indent=4,ensure_ascii=False)\n \n if results[0].stage3_result==\"Dummy\":\n dict2={ \"sid\":content[\"sid\"],\n \"result\": {\"text\":\"Invest-Dummy-Konto\", \"id\":999910, \"is_asset_number\":False},\n \"cat_list\": None,\n \"question\": None,\n \"filter\": filters\n }\n response=json.dumps(dict2, indent=4,ensure_ascii=False)\n \n elif results[0].stage3_result==\"Entscheidungsbaum (Instandhaltung)\":\n dict2={\n \"sid\": content[\"sid\"],\n \"result\": None,\n \"cat_list\": None,\n \"question\": {\n \"id\": q1.id,\n \"text\": q1.text,\n \"answers\": q1.answers,\n \"infobox\":q1.infobox},\n \"filter\": filters\n }\n response=json.dumps(dict2, indent=4,ensure_ascii=False) \n elif results[0].stage3_result==\"Entscheidungsbaum (WVDV)\":\n dict2={\n \"sid\": content[\"sid\"],\n \"result\": None,\n \"cat_list\": None,\n \"question\": {\n \"id\": q4.id,\n \"text\": q4.text,\n \"answers\": q4.answers,\n \"infobox\":q4.infobox},\n \"filter\": filters\n }\n response=json.dumps(dict2, indent=4,ensure_ascii=False) \n elif results[0].stage3_result==\"Entscheidungsbaum (Sachgesamtheit)\":\n dict2={\n \"sid\": content[\"sid\"],\n \"result\": None,\n \"cat_list\": None,\n \"question\": {\n \"id\": q7.id,\n \"text\": q7.text,\n \"answers\": q7.answers,\n \"infobox\":q7.infobox},\n \"filter\": filters\n }\n response=json.dumps(dict2, indent=4,ensure_ascii=False) \n\n elif results[0].stage3_result==\"Entscheidungsbaum (Einkauf/Vertrieb)\":\n dict2={\n \"sid\": content[\"sid\"],\n \"result\": None,\n \"cat_list\": None,\n \"question\": {\n \"id\": q10.id,\n \"text\": q10.text,\n \"answers\": q10.answers,\n \"infobox\":q10.infobox},\n \"filter\": filters\n }\n response=json.dumps(dict2, indent=4,ensure_ascii=False) \n return response\n\n# stage3 logic function for 2. post request\ndef stage3_2(results,content,filters):\n\n if results[0].stage3_result==\"Account ID\":\n dict2={ \"sid\":content[\"sid\"],\n \"result\": {\"text\":results[0].desc,\"id\":results[0].id, \"is_asset_number\":False},\n \"question\": None,\n \"filter\": filters\n }\n response=json.dumps(dict2, indent=4,ensure_ascii=False)\n \n elif results[0].stage3_result==\"Dummy\":\n dict2={ \"sid\":content[\"sid\"],\n \"result\": {\"text\":\"Invest-Dummy-Konto\", \"id\":999910, \"is_asset_number\":False},\n \"question\": None,\n \"filter\": filters\n }\n response=json.dumps(dict2, indent=4,ensure_ascii=False)\n \n elif results[0].stage3_result==\"Entscheidungsbaum (Instandhaltung)\":\n dict2={\n \"sid\": content[\"sid\"],\n \"result\": None,\n \"question\": {\n \"id\": q1.id,\n \"text\": q1.text,\n \"answers\": q1.answers,\n \"infobox\":q1.infobox},\n \"filter\": filters\n }\n response=json.dumps(dict2, indent=4,ensure_ascii=False) \n elif results[0].stage3_result==\"Entscheidungsbaum (WVDV)\":\n dict2={\n \"sid\": content[\"sid\"],\n \"result\": None,\n \"question\": {\n \"id\": q4.id,\n \"text\": q4.text,\n \"answers\": q4.answers,\n \"infobox\":q4.infobox},\n \"filter\": filters\n }\n response=json.dumps(dict2, indent=4,ensure_ascii=False) \n elif results[0].stage3_result==\"Entscheidungsbaum (Sachgesamtheit)\":\n dict2={\n \"sid\": content[\"sid\"],\n \"result\": None,\n \"question\": {\n \"id\": q7.id,\n \"text\": q7.text,\n \"answers\": q7.answers,\n \"infobox\":q7.infobox},\n \"filter\": filters\n }\n response=json.dumps(dict2, indent=4,ensure_ascii=False) \n\n elif results[0].stage3_result==\"Entscheidungsbaum (Einkauf/Vertrieb)\":\n dict2={\n \"sid\": content[\"sid\"],\n \"result\": None,\n \"question\": {\n \"id\": q10.id,\n \"text\": q10.text,\n \"answers\": q10.answers,\n \"infobox\":q10.infobox},\n \"filter\": filters\n }\n response=json.dumps(dict2, indent=4,ensure_ascii=False) \n return response\n\n@app.route('/api/search', methods=['POST'])\n\ndef search():\n \"\"\" Requires this request json: {\"sid\":\"GUID\",\"text\":\"user input\"} \"\"\"\n content = request.get_json()\n results=search_text(account_list,str(content['text'])) \n filters={\"search_text\": content['text']}\n #3 options from here: 0 result, 1 result, several result\n if len(results)==0:\n dict1={ \"sid\":content[\"sid\"],\n \"result\": None,\n \"question\": d_cats,\n \"filter\": filters\n }\n response=json.dumps(dict1, indent=4,ensure_ascii=False)\n elif len(results)==1:\n response=stage3(results,content,filters)\n \n elif len(results)>1:\n #print(questionLogic(results))\n dict3={ \"sid\":content[\"sid\"],\n \"result\": None,\n \"question\": create_answers(results)[questionLogic(results)[0]], # get the json of the first question from the d_question dict\n \"filter\": filters\n }\n response=json.dumps(dict3, indent=4,ensure_ascii=False)\n return response\n\n@app.route('/api/questions', methods=['POST'])\n\ndef questions():\n \"\"\" Requires this request json: {\n \"sid\":\"GUID\",\n \"answer_id\": c3,\n \"filter\":{\n \"search_text\": \"tasche\",\n ...}} \"\"\" \n \n content = request.get_json()\n \n ##Checking what is already in the filter properties\n #category\n try: \n Category=str({v: k for k, v in d_category.items()}[content[\"filter\"][\"Category\"]]) # inverting dictionary, we need the id\n except: \n Category=None\n #amount\n try: \n Amount=str({v: k for k, v in d_amount.items()}[content[\"filter\"][\"Amount\"]])\n except: \n Amount=None\n #duration\n try: \n Duration=str({v: k for k, v in d_duration.items()}[content[\"filter\"][\"Duration\"]])\n except: \n Duration=None\n #usage\n try: \n Usage=str({v: k for k, v in d_usage.items()}[content[\"filter\"][\"Usage\"]])\n except: \n Usage=None\n \n \n #app.logger.info(str(content[\"filter\"]))\n #app.logger.info(content[\"filter\"][\"Amount\"])\n \n # Search function, parameters coming from the filter property\n results=search_text(account_list,str(content[\"filter\"][\"search_text\"]),category=Category,amount=Amount,duration=Duration,usage=Usage)\n #Übergeordnete categories branch\n if content[\"answer_id\"] in ['c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10', 'c11', 'c12']:\n results=categorySearch(account_list,str(content[\"answer_id\"]))\n dict1={\n \"sid\": content[\"sid\"],\n \"result\": None,\n \"question\": create_answers(results)[questionLogic(results)[0]],\n \"filter\": {\n \"search_text\": content[\"filter\"][\"search_text\"],\n \"Category\": d_category[content[\"answer_id\"]] \n }\n } \n response=json.dumps(dict1, indent=4,ensure_ascii=False)\n\n #stage2 logic\n elif content[\"answer_id\"] != None and int(content[\"answer_id\"])<=98: \n\n str_question=d_answers[int(content[\"answer_id\"])][\"question\"] #to which question I have the answer\n l_question_logic=questionLogic(results) # question order\n question_nr=l_question_logic.index(str_question) # the index of the question that I have the answer\n #print(str_question) \n #print(str(d_answers[int(content[\"answer_id\"])][\"id\"])) \n #filtering based on the answer, it is not in the search_text function, because it only works with the filter property\n if str_question == \"Amount\":\n results = amountSearch(results, str(d_answers[int(content[\"answer_id\"])][\"id\"])) \n elif (str_question == \"Duration\") : \n results = durationSearch(results, str(d_answers[int(content[\"answer_id\"])][\"id\"]))\n elif str_question == \"Usage\":\n results = usageSearch(results, str(d_answers[int(content[\"answer_id\"])][\"id\"])) \n \n #print(len(results))\n #print(results)\n \n #print(l_question_logic)\n \n #print(question_nr)\n #Adding to the existing filter, the new question-answer pair\n filters=str(content[\"filter\"]).strip(\"}\")+\",'\"+str(str_question)+\"':'\"+str(d_answers[int(content[\"answer_id\"])][\"text\"])+\"'}\"\n filters=filters.replace(\"'\",\"\\\"\")\n filtero=json.loads(filters)\n # if there is 1 result-> stage3 logic\n if len(results)==1: \n response=stage3_2(results,content,filtero)\n \n elif len(results)>1: # if there is >1 results\n #if the next question is null or we already asked the 3 questions, then decision tree\n if question_nr==3 or l_question_logic[question_nr+1]==\"Null\":\n response=\"After usage question, there will be only one result, this branch shouldnt exist\"\n \n else:\n next_question=create_answers(results)[l_question_logic[question_nr+1]] # next question \n #print(next_question)\n #print(l_question_logic[question_nr+1])\n dict3={\n \"sid\": content[\"sid\"],\n \"result\": None,\n \"question\": next_question,\n \"filter\": filtero\n }\n response=json.dumps(dict3, indent=4,ensure_ascii=False)\n elif len(results)<1: \n response=\"Error: 0 in results!\"\n\n elif int(content[\"answer_id\"])>100: #Decision tree\n \n filters2=str(content[\"filter\"]).strip(\"}\")+\",'\"+d_tree[int(content[\"answer_id\"])].question.text+\"':'\"+str(d_tree[int(content[\"answer_id\"])].text)+\"'}\"\n filters2=filters2.replace(\"'\",\"\\\"\")\n filtero2=json.loads(filters2)\n if d_tree[int(content[\"answer_id\"])].next_question is not None:\n dict4={\n \"sid\": content[\"sid\"],\n \"result\": None,\n \"question\": {\n \"id\": d_tree[int(content[\"answer_id\"])].next_question.id,\n \"text\": d_tree[int(content[\"answer_id\"])].next_question.text, \n \"answers\": d_tree[int(content[\"answer_id\"])].next_question.answers,\n \"infobox\": d_tree[int(content[\"answer_id\"])].next_question.infobox},\n \"filter\": filtero2\n }\n response=json.dumps(dict4, indent=4,ensure_ascii=False)\n else:\n if d_tree[int(content[\"answer_id\"])].account_name==\"Invest-Dummy-Konto\":\n #there are 2 Asset number questions, when the Account is Invest-Dummy-Konto\n if d_tree[int(content[\"answer_id\"])].id in [128,116]:\n dict5={\n \"sid\": content[\"sid\"],\n \"result\": {\"text\":d_tree[int(content[\"answer_id\"])].account_name, \"id\":999910, \"is_asset_number\":True}, \n \"question\": None,\n \"filter\": filtero2\n }\n response=json.dumps(dict5, indent=4,ensure_ascii=False)\n else:\n dict5={\n \"sid\": content[\"sid\"],\n \"result\": {\"text\":d_tree[int(content[\"answer_id\"])].account_name, \"id\":999910, \"is_asset_number\":False}, #id of Invest-dummy-Konto\n \"question\": None,\n \"filter\": filtero2\n }\n response=json.dumps(dict5, indent=4,ensure_ascii=False)\n \n elif d_tree[int(content[\"answer_id\"])].account_name==\"Specific account\":\n if d_tree[int(content[\"answer_id\"])].id==122:\n dict5={\n \"sid\": content[\"sid\"],\n \"result\": {\"text\":\"Versandkosten Fahrzeuge\", \"id\":691000, \"is_asset_number\":False}, \n \"question\": None,\n \"filter\": filtero2\n }\n response=json.dumps(dict5, indent=4,ensure_ascii=False)\n elif d_tree[int(content[\"answer_id\"])].id==123:\n dict5={\n \"sid\": content[\"sid\"],\n \"result\": {\"text\":\"Versandkosten Ersatzteile\", \"id\":691100, \"is_asset_number\":False}, \n \"question\": None,\n \"filter\": filtero2\n }\n response=json.dumps(dict5, indent=4,ensure_ascii=False)\n elif d_tree[int(content[\"answer_id\"])].id==124:\n dict5={\n \"sid\": content[\"sid\"],\n \"result\": {\"text\":\"Versandkosten sonstige\", \"id\":691200, \"is_asset_number\":False}, \n \"question\": None,\n \"filter\": filtero2\n }\n response=json.dumps(dict5, indent=4,ensure_ascii=False)\n elif d_tree[int(content[\"answer_id\"])].id==125:\n dict5={\n \"sid\": content[\"sid\"],\n \"result\": {\"text\":\"Kundenkulanz Sonderthemen\", \"id\":691210, \"is_asset_number\":False}, \n \"question\": None,\n \"filter\": filtero2\n }\n response=json.dumps(dict5, indent=4,ensure_ascii=False)\n elif d_tree[int(content[\"answer_id\"])].id==130:\n dict5={\n \"sid\": content[\"sid\"],\n \"result\": {\"text\":\"Verpackungskosten der Lieferanten\", \"id\":604400, \"is_asset_number\":False}, \n \"question\": None,\n \"filter\": filtero2\n }\n response=json.dumps(dict5, indent=4,ensure_ascii=False)\n elif d_tree[int(content[\"answer_id\"])].id==132:\n dict5={\n \"sid\": content[\"sid\"],\n \"result\": {\"text\":\"Verpackung und Versand Material im Werk\", \"id\":604000, \"is_asset_number\":False}, \n \"question\": None,\n \"filter\": filtero2\n }\n response=json.dumps(dict5, indent=4,ensure_ascii=False)\n elif d_tree[int(content[\"answer_id\"])].id==133:\n dict5={\n \"sid\": content[\"sid\"],\n \"result\": {\"text\":\"Eingangstransportkosten\", \"id\":691300, \"is_asset_number\":False}, \n \"question\": None,\n \"filter\": filtero2\n }\n response=json.dumps(dict5, indent=4,ensure_ascii=False)\n elif d_tree[int(content[\"answer_id\"])].id==134:\n dict5={\n \"sid\": content[\"sid\"],\n \"result\": {\"text\":\"Ungeplante Bezugsnebenkosten\", \"id\":691310, \"is_asset_number\":False}, \n \"question\": None,\n \"filter\": filtero2\n }\n response=json.dumps(dict5, indent=4,ensure_ascii=False)\n elif d_tree[int(content[\"answer_id\"])].id==135:\n dict5={\n \"sid\": content[\"sid\"],\n \"result\": {\"text\":\"Zölle\", \"id\":691350, \"is_asset_number\":False}, \n \"question\": None,\n \"filter\": filtero2\n }\n response=json.dumps(dict5, indent=4,ensure_ascii=False)\n elif d_tree[int(content[\"answer_id\"])].id==136:\n dict5={\n \"sid\": content[\"sid\"],\n \"result\": {\"text\":\"See- / Frachtkosten\", \"id\":6604300, \"is_asset_number\":False}, \n \"question\": None,\n \"filter\": filtero2\n }\n response=json.dumps(dict5, indent=4,ensure_ascii=False)\n elif d_tree[int(content[\"answer_id\"])].id==137:\n dict5={\n \"sid\": content[\"sid\"],\n \"result\": {\"text\":\"Inboundkosten (WE, Verpackung, Einlagerung, Retouren) des Logistikdienstleisters PLOG\", \"id\":604310, \"is_asset_number\":False}, \n \"question\": None,\n \"filter\": filtero2\n }\n response=json.dumps(dict5, indent=4,ensure_ascii=False)\n else: # this branch is Aufwandskonto\n dict5={\n \"sid\": content[\"sid\"],\n \"result\": {\"text\":results[0].desc,\"id\":results[0].id, \"is_asset_number\":False},\n \"question\": None,\n \"filter\": filtero2\n }\n response=json.dumps(dict5, indent=4,ensure_ascii=False)\n\n return response\n\n@app.route('/api/asset', methods=['POST'])\n\ndef asset():\n \"\"\" Requires this request json: {\n \"sid\":\"GUID\",\n \"text\": \"123456\",\n \"filter\":{\n \"search_text\": \"tasche\",\n ...}} \"\"\" \n \n #content = request.get_json()\n response = flask.Response()\n response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n return response\n \nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5000)\n\n#TODO: \n# a questionLogic fv-ben a defaultba ne legyen olyan, amit nem lehet kérdezni! meg kell nézni, hogy milyen question logicok vannak és ami abba van, azt jelenítsae csak meg.\n# lementés egy táblába, \n\n#komment\n\n\n\n","repo_name":"IFUA/sea","sub_path":"SEA_v5.py","file_name":"SEA_v5.py","file_ext":"py","file_size_in_byte":47016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"34383862925","text":"from mock import patch\n\nimport mock\n\nfrom .test_helper import raises\n\nfrom kiwi.package_manager.dnf import PackageManagerDnf\nfrom kiwi.exceptions import KiwiRequestError\n\n\nclass TestPackageManagerDnf(object):\n def setup(self):\n repository = mock.Mock()\n repository.root_dir = 'root-dir'\n\n root_bind = mock.Mock()\n root_bind.move_to_root = mock.Mock(\n return_value=['root-moved-arguments']\n )\n repository.root_bind = root_bind\n\n repository.runtime_config = mock.Mock(\n return_value={\n 'dnf_args': ['-c', 'dnf.conf', '-y'],\n 'command_env': ['env']\n }\n )\n self.manager = PackageManagerDnf(repository)\n\n def test_request_package(self):\n self.manager.request_package('name')\n assert self.manager.package_requests == ['name']\n\n def test_request_collection(self):\n self.manager.request_collection('name')\n assert self.manager.collection_requests == ['\"name\"']\n\n def test_request_product(self):\n self.manager.request_product('name')\n assert self.manager.product_requests == []\n\n def test_request_package_exclusion(self):\n self.manager.request_package_exclusion('name')\n assert self.manager.exclude_requests == ['name']\n\n @patch('kiwi.command.Command.call')\n @patch('kiwi.command.Command.run')\n def test_process_install_requests_bootstrap(self, mock_run, mock_call):\n self.manager.request_package('vim')\n self.manager.request_collection('collection')\n self.manager.process_install_requests_bootstrap()\n mock_run.assert_called_once_with(\n ['dnf', '-c', 'dnf.conf', '-y', 'makecache']\n )\n mock_call.assert_called_once_with(\n [\n 'bash', '-c',\n 'dnf -c dnf.conf -y --installroot root-dir install vim && ' +\n 'dnf -c dnf.conf -y --installroot root-dir group install ' +\n '\"collection\"'\n ], ['env']\n )\n\n @patch('kiwi.command.Command.call')\n @patch('kiwi.command.Command.run')\n def test_process_install_requests(self, mock_run, mock_call):\n self.manager.request_package('vim')\n self.manager.request_collection('collection')\n self.manager.request_package_exclusion('skipme')\n self.manager.process_install_requests()\n self.manager.root_bind.move_to_root(\n self.manager.dnf_args\n )\n mock_run.assert_called_once_with(\n ['chroot', 'root-dir', 'rpm', '--rebuilddb']\n )\n mock_call.assert_called_once_with(\n [\n 'bash', '-c',\n 'chroot root-dir dnf root-moved-arguments --exclude=skipme install vim && ' +\n 'chroot root-dir dnf root-moved-arguments --exclude=skipme group install ' +\n '\"collection\"'\n ], ['env']\n )\n\n @patch('kiwi.command.Command.call')\n @patch('kiwi.command.Command.run')\n def test_process_delete_requests_force(self, mock_run, mock_call):\n self.manager.request_package('vim')\n self.manager.process_delete_requests()\n mock_call.assert_called_once_with(\n [\n 'chroot', 'root-dir', 'rpm', '-e',\n '--nodeps', '--allmatches', '--noscripts', 'vim'\n ],\n [\n 'env'\n ]\n )\n\n @patch('kiwi.command.Command.run')\n @patch('kiwi.command.Command.call')\n @raises(KiwiRequestError)\n def test_process_delete_requests_package_missing(\n self, mock_call, mock_run\n ):\n mock_run.side_effect = Exception\n self.manager.request_package('vim')\n self.manager.process_delete_requests()\n mock_run.assert_called_once_with(\n ['chroot', 'root-dir', 'rpm', '-q', 'vim']\n )\n\n @patch('kiwi.command.Command.call')\n def test_update(self, mock_call):\n self.manager.update()\n self.manager.root_bind.move_to_root(\n self.manager.dnf_args\n )\n mock_call.assert_called_once_with(\n [\n 'chroot', 'root-dir', 'dnf',\n 'root-moved-arguments', 'upgrade'\n ], ['env']\n )\n\n def test_process_only_required(self):\n self.manager.process_only_required()\n assert self.manager.custom_args == ['--setopt=install_weak_deps=False']\n\n def test_process_plus_recommended(self):\n self.manager.process_only_required()\n assert self.manager.custom_args == ['--setopt=install_weak_deps=False']\n self.manager.process_plus_recommended()\n assert '--setopt=install_weak_deps=False' not in self.manager.custom_args\n\n def test_match_package_installed(self):\n assert self.manager.match_package_installed('foo', 'Installing : foo')\n\n def test_match_package_deleted(self):\n assert self.manager.match_package_deleted('foo', 'Removing: foo')\n\n @patch('kiwi.command.Command.run')\n def test_database_consistent(self, mock_command):\n assert self.manager.database_consistent() is True\n mock_command.assert_called_once_with(\n ['chroot', 'root-dir', 'rpmdb', '--initdb']\n )\n\n @patch('kiwi.command.Command.run')\n def test_database_not_consistent(self, mock_command):\n mock_command.side_effect = Exception\n assert self.manager.database_consistent() is False\n\n def test_dump_reload_package_database(self):\n self.manager.dump_reload_package_database()\n","repo_name":"myrr2k/kiwi","sub_path":"test/unit/package_manager_dnf_test.py","file_name":"package_manager_dnf_test.py","file_ext":"py","file_size_in_byte":5516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"39142268312","text":"from tkinter import *\n\nfrom data.constants import *\n\n\nclass ChooseRunmode(Frame):\n\tdef __init__(self, root, controller):\n\t\tsuper(ChooseRunmode, self).__init__(master=root)\n\t\tself.pack(expand=True, fill=BOTH)\n\n\t\tself.controller = controller\n\t\tself.root = root\n\n\t\tself.runmode_selection = IntVar()\n\t\tself.runmode_selection.set(value=0)\n\n\t\tself.final_only = IntVar()\n\t\tself.final_only.set(value=0)\n\n\t\tself.viewer = Frame(self)\n\t\tself.labels = LABELS[\"RunmodeFrame\"]\n\n\t\tself.prompt_frame = Frame(self.viewer)\n\t\tself.prompt_label = Label(self.prompt_frame,\n\t\t\t\t\t\t\t\t text=self.labels[\"Instruct\"][0],\n\t\t\t\t\t\t\t\t font=self.controller.font)\n\t\tself.prompt_label.pack(side=TOP, anchor=W, fill=None, expand=True)\n\n\t\tfor i in range(len(self.labels[\"Runmodes\"])):\n\t\t\tradio = Radiobutton(master=self.prompt_frame,\n\t\t\t\t\t\t\t\tfont=self.controller.font,\n\t\t\t\t\t\t\t\tvariable=self.runmode_selection,\n\t\t\t\t\t\t\t\ttext=self.labels[\"Runmodes\"][i],\n\t\t\t\t\t\t\t\tvalue=i)\n\t\t\tradio.pack(side=TOP, anchor=W, fill=None, expand=True)\n\n\t\tself.prompt_frame.pack(side=TOP, anchor=N, fill=X, expand=True)\n\n\t\tself.final_only_frame = Frame(self.viewer)\n\t\tself.final_only_checkbox = Checkbutton(master=self.final_only_frame,\n\t\t\t\t\t\t\t\t\t\t\t variable=self.final_only,\n\t\t\t\t\t\t\t\t\t\t\t text=\"Exclude draft genomes\",\n\t\t\t\t\t\t\t\t\t\t\t font=self.controller.font)\n\t\tself.final_only_checkbox.pack(side=TOP, anchor=NW, fill=None,\n\t\t\t\t\t\t\t\t\t expand=True)\n\t\tself.final_only_frame.pack(side=TOP, anchor=N, fill=X, expand=True)\n\n\t\tself.button_frame = Frame(self.viewer)\n\t\tself.next_button = Button(self.button_frame, text=\"Next\",\n\t\t\t\t\t\t\t\t font=self.controller.font,\n\t\t\t\t\t\t\t\t command=self.next)\n\t\tself.next_button.pack(side=BOTTOM, anchor=SE, fill=None, expand=True)\n\t\tself.button_frame.pack(side=TOP, anchor=N, fill=BOTH, expand=True)\n\n\t\tself.viewer.pack(side=TOP, anchor=CENTER, fill=BOTH, expand=True)\n\n\tdef next(self):\n\t\trunmode = self.runmode_selection.get()\n\t\tprint(\"Runmode selected: {}\".format(runmode))\n\t\tself.controller.runmode = self.runmode_selection.get()\n\t\tself.controller.exclude_draft = self.final_only.get()\n\t\tself.controller.redraw_window(frame=2)\n","repo_name":"chg60/phamnexus","sub_path":"ui/frames/ChooseRunmode.py","file_name":"ChooseRunmode.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"22230539673","text":"\"\"\"\nProgram Name: series_analysis_wrapper.py\nContact(s): George McCabe\nAbstract: Builds command for and runs SeriesAnalysis. Optionally produce plots\n and animated gifs of the output\nHistory Log: Initial version\nUsage:\nParameters: None\nInput Files:\nOutput Files:\nCondition codes: 0 for success, 1 for failure\n\"\"\"\n\nimport os\n\n# handle if module can't be loaded to run wrapper\nWRAPPER_CANNOT_RUN = False\nEXCEPTION_ERR = ''\ntry:\n import netCDF4\nexcept Exception as err_msg:\n WRAPPER_CANNOT_RUN = True\n EXCEPTION_ERR = err_msg\n\nfrom ..util import met_util as util\nfrom ..util import do_string_sub, parse_template\nfrom ..util import get_lead_sequence, get_lead_sequence_groups, set_input_dict\nfrom ..util import ti_get_hours_from_lead, ti_get_seconds_from_lead\nfrom ..util import ti_get_lead_string\nfrom .plot_data_plane_wrapper import PlotDataPlaneWrapper\nfrom . import RuntimeFreqWrapper\n\nclass SeriesAnalysisWrapper(RuntimeFreqWrapper):\n \"\"\"! Performs series analysis with filtering options\n \"\"\"\n\n WRAPPER_ENV_VAR_KEYS = [\n 'METPLUS_MODEL',\n 'METPLUS_OBTYPE',\n 'METPLUS_DESC',\n 'METPLUS_REGRID_DICT',\n 'METPLUS_CAT_THRESH',\n 'METPLUS_FCST_FILE_TYPE',\n 'METPLUS_FCST_FIELD',\n 'METPLUS_OBS_FILE_TYPE',\n 'METPLUS_OBS_FIELD',\n 'METPLUS_CLIMO_MEAN_DICT',\n 'METPLUS_CLIMO_STDEV_DICT',\n 'METPLUS_BLOCK_SIZE',\n 'METPLUS_VLD_THRESH',\n 'METPLUS_CTS_LIST',\n 'METPLUS_STAT_LIST',\n ]\n\n # handle deprecated env vars used pre v4.0.0\n DEPRECATED_WRAPPER_ENV_VAR_KEYS = [\n 'CLIMO_MEAN_FILE',\n 'CLIMO_STDEV_FILE',\n ]\n\n def __init__(self, config, instance=None, config_overrides={}):\n self.app_name = 'series_analysis'\n self.app_path = os.path.join(config.getdir('MET_BIN_DIR', ''),\n self.app_name)\n\n super().__init__(config,\n instance=instance,\n config_overrides=config_overrides)\n\n if self.c_dict['GENERATE_PLOTS']:\n self.plot_data_plane = self.plot_data_plane_init()\n\n if WRAPPER_CANNOT_RUN:\n self.log_error(\"There was a problem importing modules: \"\n f\"{EXCEPTION_ERR}\\n\")\n\n self.logger.debug(\"Initialized SeriesAnalysisWrapper\")\n\n def create_c_dict(self):\n \"\"\"! Populate c_dict dictionary with values from METplusConfig \"\"\"\n c_dict = super().create_c_dict()\n c_dict['VERBOSITY'] = (\n self.config.getstr('config',\n 'LOG_SERIES_ANALYSIS_VERBOSITY',\n c_dict['VERBOSITY'])\n )\n\n self.set_met_config_string(self.env_var_dict,\n 'MODEL',\n 'model',\n 'METPLUS_MODEL')\n self.set_met_config_string(self.env_var_dict,\n 'OBTYPE',\n 'obtype',\n 'METPLUS_OBTYPE')\n\n # handle old format of MODEL and OBTYPE\n c_dict['MODEL'] = self.config.getstr('config', 'MODEL', 'WRF')\n c_dict['OBTYPE'] = self.config.getstr('config', 'OBTYPE', 'ANALYS')\n\n self.handle_description()\n\n self.handle_regrid(c_dict)\n\n self.set_met_config_list(self.env_var_dict,\n 'SERIES_ANALYSIS_CAT_THRESH',\n 'cat_thresh',\n 'METPLUS_CAT_THRESH',\n remove_quotes=True)\n\n self.set_met_config_float(self.env_var_dict,\n 'SERIES_ANALYSIS_VLD_THRESH',\n 'vld_thresh',\n 'METPLUS_VLD_THRESH')\n\n self.set_met_config_string(self.env_var_dict,\n 'SERIES_ANALYSIS_BLOCK_SIZE',\n 'block_size',\n 'METPLUS_BLOCK_SIZE',\n remove_quotes=True)\n\n # get stat list to loop over\n c_dict['STAT_LIST'] = util.getlist(\n self.config.getstr('config',\n 'SERIES_ANALYSIS_STAT_LIST',\n '')\n )\n if not c_dict['STAT_LIST']:\n self.log_error(\"Must set SERIES_ANALYSIS_STAT_LIST to run.\")\n\n # set stat list to set output_stats.cnt in MET config file\n self.set_met_config_list(self.env_var_dict,\n 'SERIES_ANALYSIS_STAT_LIST',\n 'cnt',\n 'METPLUS_STAT_LIST')\n\n # set cts list to set output_stats.cts in MET config file\n self.set_met_config_list(self.env_var_dict,\n 'SERIES_ANALYSIS_CTS_LIST',\n 'cts',\n 'METPLUS_CTS_LIST')\n\n c_dict['PAIRED'] = self.config.getbool('config',\n 'SERIES_ANALYSIS_IS_PAIRED',\n False)\n\n # get input dir, template, and datatype for FCST, OBS, and BOTH\n for data_type in ('FCST', 'OBS', 'BOTH'):\n c_dict[f'{data_type}_INPUT_DIR'] = (\n self.config.getdir(f'{data_type}_SERIES_ANALYSIS_INPUT_DIR', '')\n )\n c_dict[f'{data_type}_INPUT_TEMPLATE'] = (\n self.config.getraw('filename_templates',\n f'{data_type}_SERIES_ANALYSIS_INPUT_TEMPLATE',\n '')\n )\n\n c_dict[f'{data_type}_INPUT_DATATYPE'] = (\n self.config.getstr('config',\n f'{data_type}_SERIES_ANALYSIS_INPUT_DATATYPE',\n '')\n )\n\n # initialize list path to None for each type\n c_dict[f'{data_type}_LIST_PATH'] = None\n\n # if BOTH is set, neither FCST or OBS can be set\n c_dict['USING_BOTH'] = False\n if c_dict['BOTH_INPUT_TEMPLATE']:\n if c_dict['FCST_INPUT_TEMPLATE'] or c_dict['OBS_INPUT_TEMPLATE']:\n self.log_error(\"Cannot set FCST_SERIES_ANALYSIS_INPUT_TEMPLATE\"\n \" or OBS_SERIES_ANALYSIS_INPUT_TEMPLATE if \"\n \"BOTH_SERIES_ANALYSIS_INPUT_TEMPLATE is set.\")\n\n c_dict['USING_BOTH'] = True\n\n # set *_WINDOW_* variables for BOTH\n # used in CommandBuilder.find_data function)\n self.handle_file_window_variables(c_dict, dtypes=['BOTH'])\n\n # if BOTH is not set, both FCST or OBS must be set\n else:\n if (not c_dict['FCST_INPUT_TEMPLATE'] or\n not c_dict['OBS_INPUT_TEMPLATE']):\n self.log_error(\"Must either set \"\n \"BOTH_SERIES_ANALYSIS_INPUT_TEMPLATE or both \"\n \"FCST_SERIES_ANALYSIS_INPUT_TEMPLATE and \"\n \"OBS_SERIES_ANALYSIS_INPUT_TEMPLATE to run \"\n \"SeriesAnalysis wrapper.\")\n\n # set *_WINDOW_* variables for FCST and OBS\n self.handle_file_window_variables(c_dict, dtypes=['FCST', 'OBS'])\n\n c_dict['TC_STAT_INPUT_DIR'] = (\n self.config.getdir('SERIES_ANALYSIS_TC_STAT_INPUT_DIR', '')\n )\n\n c_dict['TC_STAT_INPUT_TEMPLATE'] = (\n self.config.getraw('config',\n 'SERIES_ANALYSIS_TC_STAT_INPUT_TEMPLATE')\n )\n\n c_dict['OUTPUT_DIR'] = self.config.getdir('SERIES_ANALYSIS_OUTPUT_DIR',\n '')\n c_dict['OUTPUT_TEMPLATE'] = (\n self.config.getraw('config',\n 'SERIES_ANALYSIS_OUTPUT_TEMPLATE')\n )\n if not c_dict['OUTPUT_DIR']:\n self.log_error(\"Must set SERIES_ANALYSIS_OUTPUT_DIR to run.\")\n\n c_dict['CONFIG_FILE'] = (\n self.config.getraw('config',\n 'SERIES_ANALYSIS_CONFIG_FILE')\n )\n if not c_dict['CONFIG_FILE']:\n self.log_error(\"SERIES_ANALYSIS_CONFIG_FILE must be set\")\n\n c_dict['BACKGROUND_MAP'] = (\n self.config.getbool('config',\n 'SERIES_ANALYSIS_BACKGROUND_MAP',\n False)\n )\n\n c_dict['VAR_LIST_TEMP'] = util.parse_var_list(self.config,\n met_tool=self.app_name)\n if not c_dict['VAR_LIST_TEMP']:\n self.log_error(\"No fields specified. Please set \"\n \"[FCST/OBS]_VAR_[NAME/LEVELS]\")\n\n c_dict['GENERATE_PLOTS'] = (\n self.config.getbool('config',\n 'SERIES_ANALYSIS_GENERATE_PLOTS',\n False)\n )\n\n c_dict['GENERATE_ANIMATIONS'] = (\n self.config.getbool('config',\n 'SERIES_ANALYSIS_GENERATE_ANIMATIONS',\n False)\n )\n\n c_dict['CONVERT_EXE'] = self.config.getexe('CONVERT')\n if c_dict['GENERATE_ANIMATIONS'] and not c_dict['CONVERT_EXE']:\n self.log_error(\"[exe] CONVERT must be set correctly if \"\n \"SERIES_ANALYSIS_GENERATE_ANIMATIONS is True\")\n\n c_dict['PNG_FILES'] = {}\n\n c_dict['RUN_ONCE_PER_STORM_ID'] = (\n self.config.getbool('config',\n 'SERIES_ANALYSIS_RUN_ONCE_PER_STORM_ID',\n False)\n )\n if (c_dict['RUN_ONCE_PER_STORM_ID'] and\n not c_dict['TC_STAT_INPUT_TEMPLATE']):\n self.log_error(\"Must set SERIES_ANALYSIS_TC_STAT_INPUT_TEMPLATE \"\n \"if SERIES_ANALYSIS_RUN_ONCE_PER_STORM_ID is True\")\n\n # get climatology config variables\n self.handle_climo_dict()\n\n # if no forecast lead sequence is specified,\n # use wildcard (*) so all leads are used\n c_dict['WILDCARD_LEAD_IF_EMPTY'] = True\n\n # allow multiple files so wildcards can be used to get input files\n c_dict['ALLOW_MULTIPLE_FILES'] = True\n\n return c_dict\n\n def plot_data_plane_init(self):\n \"\"\"! Set values to allow successful initialization of\n PlotDataPlane wrapper\n\n @returns instance of PlotDataPlaneWrapper\n \"\"\"\n plot_overrides = {'PLOT_DATA_PLANE_INPUT_TEMPLATE': 'template',\n 'PLOT_DATA_PLANE_OUTPUT_TEMPLATE': 'template',\n 'PLOT_DATA_PLANE_FIELD_NAME': 'field_name',\n 'PLOT_DATA_PLANE_CONVERT_TO_IMAGE': True,\n }\n\n if not self.c_dict['BACKGROUND_MAP']:\n plot_overrides['PLOT_DATA_PLANE_FIELD_EXTRA'] = (\n \"map_data={ source=[];}\"\n )\n\n pdp_wrapper = PlotDataPlaneWrapper(self.config,\n config_overrides=plot_overrides)\n return pdp_wrapper\n\n def clear(self):\n \"\"\"! Call parent's clear function and clear additional values \"\"\"\n super().clear()\n for data_type in ('FCST', 'OBS', 'BOTH'):\n self.c_dict[f'{data_type}_LIST_PATH'] = None\n\n def run_all_times(self):\n \"\"\"! Process all run times defined for this wrapper \"\"\"\n super().run_all_times()\n\n if self.c_dict['GENERATE_ANIMATIONS']:\n self.generate_animations()\n\n return self.all_commands\n\n def run_once_per_lead(self, custom):\n \"\"\"! Run once per forecast lead\n\n @param value of current CUSTOM_LOOP_LIST iteration\n @returns True if all runs were successful, False otherwise\n \"\"\"\n self.logger.debug(\"Running once for forecast lead time\")\n success = True\n\n lead_groups = get_lead_sequence_groups(self.config)\n if not lead_groups:\n lead_seq = get_lead_sequence(self.config,\n input_dict=None,\n wildcard_if_empty=True)\n for index, lead in enumerate(lead_seq):\n lead_hours = ti_get_hours_from_lead(lead)\n\n # if cannot get lead hours, use index of forecast lead\n # hours cannot be computed from months or years without\n # knowing the valid time\n if lead_hours is None:\n lead_hours = index\n else:\n lead_hours = f\"F{str(lead_hours).zfill(3)}\"\n\n lead_groups[f'series_{lead_hours}'] = [lead]\n\n for lead_group in lead_groups.items():\n # create input dict and only set 'now' item\n # create a new dictionary each iteration in case the function\n # that it is passed into modifies it\n input_dict = set_input_dict(loop_time=None,\n config=self.config,\n use_init=None,\n instance=self.instance,\n custom=custom)\n\n input_dict['init'] = '*'\n input_dict['valid'] = '*'\n lead_hours = [ti_get_lead_string(item, plural=False) for\n item in lead_group[1]]\n\n self.logger.debug(f\"Processing {lead_group[0]} - forecast leads: \"\n f\"{', '.join(lead_hours)}\")\n if not self.run_at_time_once(input_dict, lead_group):\n success = False\n\n return success\n\n def run_at_time_once(self, time_info, lead_group=None):\n \"\"\"! Attempt to build series_analysis command for run time\n\n @param time_info dictionary containing time information\n @param lead_group (optional) dictionary where key is label and\n value is a list of forecast leads to process.\n @returns True on success, False otherwise\n \"\"\"\n self.logger.debug(\"Starting SeriesAnalysis\")\n\n # if running for each storm ID, get list of storms\n storm_list = self.get_storm_list(time_info)\n if not storm_list:\n return False\n\n # perform string substitution on var list\n self.c_dict['VAR_LIST'] = (\n util.sub_var_list(self.c_dict['VAR_LIST_TEMP'],\n time_info)\n )\n\n # loop over storm list and process for each\n # this loop will execute once if not filtering by storm ID\n for storm_id in storm_list:\n # Create FCST and OBS ASCII files\n fcst_path, obs_path = (\n self.create_ascii_storm_files_list(time_info,\n storm_id,\n lead_group)\n )\n if not fcst_path or not obs_path:\n self.log_error('No ASCII file lists were created. Skipping.')\n continue\n\n # Build up the arguments to and then run the MET tool series_analysis.\n if not self.build_and_run_series_request(time_info,\n fcst_path,\n obs_path):\n continue\n\n if self.c_dict['GENERATE_PLOTS']:\n self.generate_plots(fcst_path,\n time_info,\n storm_id)\n else:\n self.logger.debug(\"Skip plotting output. Change \"\n \"SERIES_ANALYSIS_GENERATE_PLOTS to True to \"\n \"run this step.\")\n\n self.logger.debug(\"Finished series analysis\")\n return True\n\n def get_storm_list(self, time_info):\n \"\"\"! Find the .tcst filter file for the current run time and get the\n list of storm IDs that are found in the file.\n\n @param time_info dictionary containing time information\n @returns A list of all the storms ids that correspond to the\n current init time or None if filter file does not exist\n \"\"\"\n if not self.c_dict['RUN_ONCE_PER_STORM_ID']:\n return ['*']\n\n # Retrieve filter files, first create the filename\n # by piecing together the out_dir_base with the cur_init.\n filter_template = os.path.join(self.c_dict['TC_STAT_INPUT_DIR'],\n self.c_dict['TC_STAT_INPUT_TEMPLATE'])\n filter_file = do_string_sub(filter_template, **time_info)\n self.logger.debug(f\"Getting storms from filter file: {filter_file}\")\n if not os.path.exists(filter_file):\n self.log_error(f\"Filter file does not exist: {filter_file}\")\n return None\n\n # Now that we have the filter filename for the init time, let's\n # extract all the storm ids in this filter file.\n storm_list = util.get_storm_ids(filter_file, self.logger)\n if not storm_list:\n # No storms for this init time, check next init time in list\n self.logger.debug(\"No storms found for current runtime\")\n return None\n\n return storm_list\n\n def get_files_from_time(self, time_info):\n \"\"\"! Create dictionary containing time information (key time_info) and\n any relevant files for that runtime. The parent implementation of\n this function creates a dictionary and adds the time_info to it.\n This wrapper gets all files for the current runtime and adds it to\n the dictionary with keys 'fcst' and 'obs'\n\n @param time_info dictionary containing time information\n @returns dictionary containing time_info dict and any relevant\n files with a key representing a description of that file\n \"\"\"\n file_dict_list = []\n # get all storm IDs\n storm_list = self.get_storm_list(time_info)\n if not storm_list:\n return None\n\n for storm_id in storm_list:\n time_info['storm_id'] = storm_id\n file_dict = super().get_files_from_time(time_info)\n if self.c_dict['USING_BOTH']:\n fcst_files = self.find_input_files(time_info, 'BOTH')\n obs_files = fcst_files\n else:\n fcst_files = self.find_input_files(time_info, 'FCST')\n obs_files = self.find_input_files(time_info, 'OBS')\n\n if fcst_files is None or obs_files is None:\n return None\n\n file_dict['fcst'] = fcst_files\n file_dict['obs'] = obs_files\n file_dict_list.append(file_dict)\n\n return file_dict_list\n\n def find_input_files(self, time_info, data_type):\n \"\"\"! Loop over list of input templates and find files for each\n\n @param time_info time dictionary to use for string substitution\n @returns Input file list if all files were found, None if not.\n \"\"\"\n input_files = self.find_data(time_info,\n return_list=True,\n data_type=data_type)\n return input_files\n\n def subset_input_files(self, time_info):\n \"\"\"! Obtain a subset of input files from the c_dict ALL_FILES based on\n the time information for the current run.\n\n @param time_info dictionary containing time information\n @returns the path to a ascii file containing the list of files\n or None if could not find any files\n \"\"\"\n fcst_files = []\n obs_files = []\n for file_dict in self.c_dict['ALL_FILES']:\n # compare time information for each input file\n # add file to list of files to use if it matches\n if not self.compare_time_info(time_info, file_dict['time_info']):\n continue\n\n fcst_files.extend(file_dict['fcst'])\n obs_files.extend(file_dict['obs'])\n\n return fcst_files, obs_files\n\n def compare_time_info(self, runtime, filetime):\n \"\"\"! Call parents implementation then if the current run time and file\n time may potentially still not match, use storm_id to check\n\n @param runtime dictionary containing time information for current\n runtime\n @param filetime dictionary containing time information for file\n that is being evaluated\n @returns True if the file should be processed in the current\n run or False if not\n \"\"\"\n if not super().compare_time_info(runtime, filetime):\n return False\n\n # compare storm_id\n if runtime['storm_id'] == '*':\n return True\n\n return bool(filetime['storm_id'] == runtime['storm_id'])\n\n def create_ascii_storm_files_list(self, time_info, storm_id, lead_group):\n \"\"\"! Creates the list of ASCII files that contain the storm id and init\n times. The list is used to create an ASCII file which will be\n used as the option to the -obs or -fcst flag to the MET\n series_analysis tool.\n\n @param time_info dictionary containing time information\n @param storm_id storm ID to process\n @param lead_group dictionary where key is label and value is a\n list of forecast leads to process. If no label was defined, the\n key will match the format \"NoLabel_\" and if no lead groups\n are defined, the dictionary should be replaced with None\n \"\"\"\n time_info['storm_id'] = storm_id\n all_fcst_files = []\n all_obs_files = []\n if not lead_group:\n fcst_files, obs_files = self.subset_input_files(time_info)\n if not fcst_files or not obs_files:\n return None, None\n all_fcst_files.extend(fcst_files)\n all_obs_files.extend(obs_files)\n label = ''\n leads = None\n else:\n label = lead_group[0]\n leads = lead_group[1]\n for lead in leads:\n time_info['lead'] = lead\n fcst_files, obs_files = self.subset_input_files(time_info)\n if fcst_files and obs_files:\n all_fcst_files.extend(fcst_files)\n all_obs_files.extend(obs_files)\n\n # skip if no files were found\n if not all_fcst_files or not all_obs_files:\n return None, None\n\n output_dir = self.get_output_dir(time_info, storm_id, label)\n\n if not self.check_python_embedding():\n return None, None\n\n # create forecast (or both) file list\n if self.c_dict['USING_BOTH']:\n data_type = 'BOTH'\n else:\n data_type = 'FCST'\n fcst_ascii_filename = self.get_ascii_filename(data_type,\n storm_id,\n leads)\n self.write_list_file(fcst_ascii_filename,\n all_fcst_files,\n output_dir=output_dir)\n\n fcst_path = os.path.join(output_dir, fcst_ascii_filename)\n\n if self.c_dict['USING_BOTH']:\n return fcst_path, fcst_path\n\n # create analysis file list\n obs_ascii_filename = self.get_ascii_filename('OBS',\n storm_id,\n leads)\n self.write_list_file(obs_ascii_filename,\n all_obs_files,\n output_dir=output_dir)\n\n obs_path = os.path.join(output_dir, obs_ascii_filename)\n\n return fcst_path, obs_path\n\n def check_python_embedding(self):\n \"\"\"! Check if any of the field names contain a Python embedding script.\n See CommandBuilder.check_for_python_embedding for more info.\n\n @returns False if something is not configured correctly or True\n \"\"\"\n for var_info in self.c_dict['VAR_LIST']:\n if self.c_dict['USING_BOTH']:\n if not self.check_for_python_embedding('BOTH', var_info):\n return False\n else:\n if not self.check_for_python_embedding('FCST', var_info):\n return False\n if not self.check_for_python_embedding('OBS', var_info):\n return False\n\n return True\n\n @staticmethod\n def get_ascii_filename(data_type, storm_id, leads=None):\n \"\"\"! Build filename for ASCII file list file\n\n @param data_type FCST, OBS, or BOTH\n @param storm_id current storm ID or wildcard character\n @param leads list of forecast leads to use add the forecast hour\n string to the filename or the minimum and maximum forecast hour\n strings if there are more than one lead\n @returns string containing filename to use\n \"\"\"\n prefix = f\"{data_type}_FILES\"\n\n # of storm ID is set (not wildcard), then add it to filename\n if storm_id == '*':\n filename = ''\n else:\n filename = f\"_{storm_id}\"\n\n # add forecast leads if specified\n if leads is not None:\n lead_hours_list = []\n for lead in leads:\n lead_hours = ti_get_hours_from_lead(lead)\n if lead_hours is None:\n lead_hours = ti_get_lead_string(lead,\n letter_only=True)\n lead_hours_list.append(lead_hours)\n\n # get first forecast lead, convert to hours, and add to filename\n lead_hours = min(lead_hours_list)\n\n lead_str = str(lead_hours).zfill(3)\n filename += f\"_F{lead_str}\"\n\n # if list of forecast leads, get min and max and add them to name\n if len(lead_hours_list) > 1:\n max_lead_hours = max(lead_hours_list)\n max_lead_str = str(max_lead_hours).zfill(3)\n filename += f\"_to_F{max_lead_str}\"\n\n ascii_filename = f\"{prefix}{filename}\"\n return ascii_filename\n\n def get_output_dir(self, time_info, storm_id, label):\n \"\"\"! Determine directory that will contain output data from the\n OUTPUT_DIR and OUTPUT_TEMPLATE. This will include any\n subdirectories specified in the filename template.\n\n @param time_info dictionary containing time information for\n current run\n @param storm_id storm ID to process\n @param label label defined for forecast lead groups to identify\n them\n @returns path to output directory with filename templates\n substituted with the information for the current run\n \"\"\"\n output_dir_template = os.path.join(self.c_dict['OUTPUT_DIR'],\n self.c_dict['OUTPUT_TEMPLATE'])\n output_dir_template = os.path.dirname(output_dir_template)\n if storm_id == '*':\n storm_id_out = 'all_storms'\n else:\n storm_id_out = storm_id\n\n # get output directory including storm ID and label\n time_info['storm_id'] = storm_id_out\n time_info['label'] = label\n output_dir = do_string_sub(output_dir_template,\n **time_info)\n return output_dir\n\n def build_and_run_series_request(self, time_info, fcst_path, obs_path):\n \"\"\"! Build up the -obs, -fcst, -out necessary for running the\n series_analysis MET tool, then invoke series_analysis.\n\n @param time_info dictionary containing time information for\n current run\n @param storm_id storm ID to process\n @returns True if all runs succeeded, False if there was a problem\n with any of the runs\n \"\"\"\n success = True\n\n num, beg, end = self.get_fcst_file_info(fcst_path)\n if num is None:\n self.logger.debug(\"Could not get fcst_beg and fcst_end values. \"\n \"Those values cannot be used in filename \"\n \"templates\")\n\n time_info['fcst_beg'] = beg\n time_info['fcst_end'] = end\n\n # build the command and run series_analysis for each variable\n for var_info in self.c_dict['VAR_LIST']:\n if self.c_dict['USING_BOTH']:\n self.c_dict['BOTH_LIST_PATH'] = fcst_path\n else:\n self.c_dict['FCST_LIST_PATH'] = fcst_path\n self.c_dict['OBS_LIST_PATH'] = obs_path\n self.add_field_info_to_time_info(time_info, var_info)\n\n # get formatted field dictionary to pass into the MET config file\n fcst_field, obs_field = self.get_formatted_fields(var_info)\n\n self.format_field('FCST', fcst_field)\n self.format_field('OBS', obs_field)\n\n self.set_environment_variables(time_info)\n\n self.set_command_line_arguments(time_info)\n\n self.find_and_check_output_file(time_info)\n\n if not self.build():\n success = False\n\n self.clear()\n\n return success\n\n def set_environment_variables(self, time_info):\n \"\"\"! Set the env variables based on settings in the METplus config\n files.\n\n @param time_info dictionary containing time information\n @param fcst_field formatted forecast field information\n @param obs_field formatted observation field information\n \"\"\"\n self.logger.info('Setting env variables from config file...')\n\n # Set all the environment variables that are needed by the\n # MET config file.\n # Set up the environment variable to be used in the Series Analysis\n self.add_env_var(\"FCST_FILE_TYPE\", self.c_dict.get('FCST_FILE_TYPE',\n ''))\n self.add_env_var(\"OBS_FILE_TYPE\", self.c_dict.get('OBS_FILE_TYPE',\n ''))\n\n self.add_env_var(\"FCST_FIELD\",\n self.c_dict.get('FCST_FIELD', ''))\n self.add_env_var(\"OBS_FIELD\",\n self.c_dict.get('OBS_FIELD', ''))\n\n # set old env var settings for backwards compatibility\n self.add_env_var('MODEL', self.c_dict.get('MODEL', ''))\n self.add_env_var(\"OBTYPE\", self.c_dict.get('OBTYPE', ''))\n self.add_env_var('REGRID_TO_GRID',\n self.c_dict.get('REGRID_TO_GRID', ''))\n\n # format old stat list\n stat_list = self.c_dict.get('STAT_LIST')\n if not stat_list:\n stat_list = \"[]\"\n else:\n stat_list = '\",\"'.join(stat_list)\n stat_list = f'[\"{stat_list}\"]'\n self.add_env_var('STAT_LIST', stat_list)\n\n super().set_environment_variables(time_info)\n\n def set_command_line_arguments(self, time_info):\n \"\"\"! Set arguments that will be passed into the MET command\n\n @param time_info dictionary containing time information\n \"\"\"\n # add input data format if set\n if self.c_dict['PAIRED']:\n self.args.append(\" -paired\")\n\n # add config file - passing through do_string_sub\n # to get custom string if set\n config_file = do_string_sub(self.c_dict['CONFIG_FILE'],\n **time_info)\n self.args.append(f\" -config {config_file}\")\n\n def get_command(self):\n \"\"\"! Build command to run\n\n @returns string of the command that will be called\n \"\"\"\n cmd = self.app_path\n\n if self.c_dict['USING_BOTH']:\n cmd += f\" -both {self.c_dict['BOTH_LIST_PATH']}\"\n else:\n cmd += f\" -fcst {self.c_dict['FCST_LIST_PATH']}\"\n cmd += f\" -obs {self.c_dict['OBS_LIST_PATH']}\"\n\n # add output path\n cmd += f' -out {self.get_output_path()}'\n\n # add arguments\n cmd += ''.join(self.args)\n\n # add verbosity\n cmd += ' -v ' + self.c_dict['VERBOSITY']\n return cmd\n\n def generate_plots(self, fcst_path, time_info, storm_id):\n \"\"\"! Generate the plots from the series_analysis output.\n\n @param time_info dictionary containing time information\n @param storm_id storm ID to process\n \"\"\"\n output_dir = os.path.dirname(fcst_path)\n output_filename = os.path.basename(self.c_dict['OUTPUT_TEMPLATE'])\n output_template = os.path.join(output_dir, output_filename)\n\n for var_info in self.c_dict['VAR_LIST']:\n name = var_info['fcst_name']\n level = var_info['fcst_level']\n self.add_field_info_to_time_info(time_info, var_info)\n\n # change wildcard storm ID to all_storms\n if storm_id == '*':\n time_info['storm_id'] = 'all_storms'\n else:\n time_info['storm_id'] = storm_id\n\n # get the output directory where the series_analysis output\n # was written. Plots will be written to the same directory\n plot_input = do_string_sub(output_template,\n **time_info)\n\n # Get the number of forecast tile files and the name of the\n # first and last in the list to be used in the -title\n num, beg, end = self.get_fcst_file_info(fcst_path)\n if num is None:\n self.log_error(\"Could not get any forecast lead info \"\n f\"from {fcst_path}\")\n self.logger.debug(f\"Skipping plot for {storm_id}\")\n continue\n\n _, nseries = self.get_netcdf_min_max(plot_input,\n 'series_cnt_TOTAL')\n nseries_str = '' if nseries is None else f\" (N = {nseries})\"\n time_info['nseries'] = nseries_str\n\n # Assemble the input file, output file, field string, and title\n for cur_stat in self.c_dict['STAT_LIST']:\n key = f\"{name}_{level}_{cur_stat}\"\n if self.c_dict['PNG_FILES'].get(key) is None:\n self.c_dict['PNG_FILES'][key] = []\n\n min_value, max_value = (\n self.get_netcdf_min_max(plot_input,\n f'series_cnt_{cur_stat}')\n )\n range_min_max = f\"{min_value} {max_value}\"\n\n plot_output = (f\"{os.path.splitext(plot_input)[0]}_\"\n f\"{cur_stat}.ps\")\n\n time_info['num_leads'] = num\n time_info['fcst_beg'] = beg\n time_info['fcst_end'] = end\n time_info['stat'] = cur_stat\n self.plot_data_plane.c_dict['INPUT_TEMPLATE'] = plot_input\n self.plot_data_plane.c_dict['OUTPUT_TEMPLATE'] = plot_output\n self.plot_data_plane.c_dict['FIELD_NAME'] = f\"series_cnt_{cur_stat}\"\n self.plot_data_plane.c_dict['FIELD_LEVEL'] = level\n self.plot_data_plane.c_dict['RANGE_MIN_MAX'] = range_min_max\n self.plot_data_plane.run_at_time_once(time_info)\n self.all_commands.extend(self.plot_data_plane.all_commands)\n self.plot_data_plane.all_commands.clear()\n\n png_filename = f\"{os.path.splitext(plot_output)[0]}.png\"\n self.c_dict['PNG_FILES'][key].append(png_filename)\n\n def generate_animations(self):\n \"\"\"! Use ImageMagick convert to create an animated gif from the png\n images generated from the current run\n \"\"\"\n success = True\n\n convert_exe = self.c_dict.get('CONVERT_EXE')\n if not convert_exe:\n self.log_error(\"[exe] CONVERT not set correctly. Cannot generate\"\n \"image file.\")\n return False\n\n animate_dir = os.path.join(self.c_dict['OUTPUT_DIR'],\n 'series_animate')\n if not os.path.exists(animate_dir):\n os.makedirs(animate_dir)\n\n for group, files in self.c_dict['PNG_FILES'].items():\n # write list of files to a text file\n list_file = f'series_animate_{group}_files.txt'\n self.write_list_file(list_file,\n files,\n output_dir=animate_dir)\n\n gif_file = f'series_animate_{group}.gif'\n gif_filepath = os.path.join(animate_dir, gif_file)\n convert_command = (f\"{convert_exe} -dispose Background -delay 100 \"\n f\"{' '.join(files)} {gif_filepath}\")\n if not self.run_command(convert_command):\n success = False\n\n return success\n\n def get_fcst_file_info(self, fcst_path):\n \"\"\"! Get the number of all the gridded forecast n x m tile\n files. Determine the filename of the\n first and last files. This information is used to create\n the title value to the -title opt in plot_data_plane.\n\n @param fcst_path path to forecast ascii list file to process\n @returns num, beg, end: A tuple representing the number of\n forecast tile files, and the first and last file. If info cannot\n be parsed, return (None, None, None)\n \"\"\"\n # read the file but skip the first line because it contains 'file_list'\n with open(fcst_path, 'r') as file_handle:\n files_of_interest = file_handle.readlines()\n\n if len(files_of_interest) < 2:\n self.log_error(f\"No files found in file list: {fcst_path}\")\n return None, None, None\n\n files_of_interest = files_of_interest[1:]\n num = str(len(files_of_interest))\n\n if self.c_dict['USING_BOTH']:\n input_dir = self.c_dict['BOTH_INPUT_DIR']\n input_template = self.c_dict['BOTH_INPUT_TEMPLATE']\n else:\n input_dir = self.c_dict['FCST_INPUT_DIR']\n input_template = self.c_dict['FCST_INPUT_TEMPLATE']\n\n full_template = os.path.join(input_dir, input_template)\n\n smallest_fcst = 99999999\n largest_fcst = -99999999\n beg = None\n end = None\n for filepath in files_of_interest:\n filepath = filepath.strip()\n file_time_info = parse_template(full_template,\n filepath,\n self.logger)\n if not file_time_info:\n continue\n lead = ti_get_seconds_from_lead(file_time_info.get('lead'),\n file_time_info.get('valid'))\n if lead < smallest_fcst:\n smallest_fcst = lead\n beg = str(ti_get_hours_from_lead(lead)).zfill(3)\n if lead > largest_fcst:\n largest_fcst = lead\n end = str(ti_get_hours_from_lead(lead)).zfill(3)\n\n if beg is None or end is None:\n return None, None, None\n\n return num, beg, end\n\n @staticmethod\n def get_netcdf_min_max(filepath, variable_name):\n \"\"\"! Determine the min and max for all lead times for each\n statistic and variable pairing.\n\n @param filepath NetCDF file to inspect\n @param variable_name name of variable to read\n @returns tuple containing the minimum and maximum values or\n None, None if something went wrong\n \"\"\"\n try:\n nc_var = netCDF4.Dataset(filepath).variables[variable_name]\n min_value = nc_var[:].min()\n max_value = nc_var[:].max()\n return min_value, max_value\n except (FileNotFoundError, KeyError):\n return None, None\n\n def get_formatted_fields(self, var_info):\n \"\"\"! Get forecast and observation field information for var_info and\n format it so it can be passed into the MET config file\n\n @param var_info dictionary containing info to format\n @returns tuple containing strings of the formatted forecast and\n observation information or None, None if something went wrong\n \"\"\"\n # get field info field a single field to pass to the MET config file\n fcst_field_list = self.get_field_info(v_level=var_info['fcst_level'],\n v_thresh=var_info['fcst_thresh'],\n v_name=var_info['fcst_name'],\n v_extra=var_info['fcst_extra'],\n d_type='FCST')\n\n obs_field_list = self.get_field_info(v_level=var_info['obs_level'],\n v_thresh=var_info['obs_thresh'],\n v_name=var_info['obs_name'],\n v_extra=var_info['obs_extra'],\n d_type='OBS')\n\n if fcst_field_list is None or obs_field_list is None:\n return None, None\n\n fcst_fields = ','.join(fcst_field_list)\n obs_fields = ','.join(obs_field_list)\n\n return fcst_fields, obs_fields\n","repo_name":"Ho-ChunHuang-NOAA/EMC_AQM_Verification","sub_path":"metplus/wrappers/series_analysis_wrapper.py","file_name":"series_analysis_wrapper.py","file_ext":"py","file_size_in_byte":41569,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"10552149379","text":"from django.shortcuts import get_object_or_404, render\nfrom books.models import Book,Category\nfrom django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\n# Create your views here.\ndef home(request,category_slug=None):\n # books = Book.objects.all().filter(is_available=True)\n\n if category_slug is not None:\n book_category = get_object_or_404(Category, slug=category_slug)\n books = Book.objects.filter(category=book_category, is_available=True)\n paginator = Paginator(books, 4)\n page = request.GET.get('page')\n paged_products = paginator.get_page(page)\n \n else:\n books = Book.objects.all().filter(is_available=True)\n paginator = Paginator(books, 4)\n page = request.GET.get('page')\n paged_products = paginator.get_page(page)\n \n\n\n context = {\n 'books':paged_products,\n }\n return render(request, 'home.html', context)\n\n\n","repo_name":"masum2617/Bookshop_Django","sub_path":"bookshop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"30691606491","text":"#Soma dos dígitos de um inteiro\n\nnumero = input(\"Digite um número inteiro: \")\nseq = len(numero)\nnumero1 = int(numero)\nsoma = 0\n\nwhile seq >= 0:\n#Para achar o dígito\n d = numero1%10\n i = numero1//10\n numero1 = i\n soma = soma + d\n seq = seq - 1\n \nprint(soma)\n","repo_name":"laismenezes-br/python_coursera","sub_path":"soma_digitos.py","file_name":"soma_digitos.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"34241295615","text":"def solution(s):\n arr = [[] for _ in range(len(s) + 1)]\n arr_len = [[] for _ in range(len(s) + 1)]\n cnt = []\n for i in range(1, len(s) + 1):\n if len(s) % i == 0:\n k = len(s) // i\n else:\n k = len(s) // i + 1\n for j in range(k):\n arr[i].append(s[j * i:(j + 1) * i])\n\n for i, ar in enumerate(arr):\n idx = 0\n tmp = ''\n for _ in range(len(ar)):\n letter = ar[idx]\n if idx != len(ar) - 1 and ar[idx] == ar[idx + 1]:\n if not arr_len[i]:\n arr_len[i].append(ar[idx])\n else:\n if arr_len[i][-1] != ar[idx] or tmp != ar[idx]:\n arr_len[i].append(ar[idx])\n del ar[idx]\n idx -= 1\n tmp = letter\n idx += 1\n\n for i in range(len(s) + 1):\n if not arr[i]:\n continue\n if len(s) % i == 0:\n cnt.append(len(arr[i]) * len(arr[i][0]) + len(arr_len[i]))\n else:\n cnt.append((len(arr[i]) - 1) * len(arr[i][0]) + len(arr_len[i]) + len(arr[i][-1]))\n answer = min(cnt)\n return answer\n\n\nS = \"abcabcdede\"\nprint(solution(S))\n","repo_name":"raeyoungii/baekjoon","sub_path":"프로그래머스/2020 카카오 채용/문자열 압축_1.py","file_name":"문자열 압축_1.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"35439620676","text":"import sys\nimport os\nimport getopt\n\ndef usage():\n sys.stderr.write(\"Usage: icalendar-response.py -r {accept|tentative|decline} -s responder@email [-i input-file] [-o output-file]\\n\")\n status = -1\n if hasattr(os, \"EX_USAGE\"):\n status = os.EX_USAGE\n sys.exit(status)\n\ndef error(msg, fatal = False):\n if fatal:\n template = \"Fatal error: {msg}.\\n\"\n else:\n template = \"Error: {msg}.\\n\"\n sys.stderr.write(template.format(msg=msg))\n status = -1\n if hasattr(os, \"EX_SOFTWARE\"):\n status = os.EX_SOFTWARE\n if fatal:\n sys.exit(status)\n\ndef parseArgs():\n response = None\n sender = None\n infile = None\n outfile = None\n try:\n opts, unparsed = getopt.getopt(sys.argv[1:], \"r:s:i:o:\")\n except getopt.GetoptError:\n usage()\n if len(unparsed) != 0:\n usage()\n seenOptions = []\n for option, value in opts:\n if option in seenOptions:\n usage()\n seenOptions.append(option)\n for option, value in opts:\n if option == \"-r\":\n response = value\n if option == \"-s\":\n sender = value\n if option == \"-i\" and value != \"-\":\n infile = value\n if option == \"-o\" and value != '-':\n outfile = value\n if response is None or sender is None:\n usage()\n if response not in [\"accept\", \"tentative\", \"decline\"]:\n usage()\n return response, sender, infile, outfile\n\ndef readInput(infile = None):\n if infile is not None:\n f = open(infile, \"r\", encoding=\"utf-8\")\n else:\n f = sys.stdin\n ret = \"\"\n while True:\n buff = f.read()\n if len(buff) == 0:\n break\n ret += buff\n if infile is not None:\n f.close()\n return ret\n\ndef writeOutput(output, outfile = None):\n if outfile is not None:\n f = open(outfile, \"w\", encoding=\"utf-8\")\n else:\n f = sys.stdout\n if f.write(output) != len(output): # I d'ont know how this could happen\n error(\"unusual write error\", fatal = True)\n if outfile is not None:\n f.close()\n\ndef generateResponse(invite, response, sender):\n template = \"\"\"BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:piotrcki/icalendar-reply\nMETHOD:REPLY\nBEGIN:VEVENT\n{uid}\n{dtstart}\n{dtend}\nATTENDEE;PARTSTAT={status}:mailto:{sender}\nEND:VEVENT\nEND:VCALENDAR\n\"\"\".replace(\"\\n\", \"\\r\\n\")\n status = {\"accept\" : \"ACCEPTED\",\n \"tentative\" : \"TENTATIVE\",\n \"decline\" : \"DECLINED\"}[response]\n lines = invite.splitlines()\n for prefix in [\"UID:\", \"DTSTART;TZID=\", \"DTEND;TZID=\"]:\n count = 0\n for line in lines:\n if line.upper().find(prefix) == 0:\n count += 1\n if prefix == \"UID:\":\n uid = line\n if prefix == \"DTSTART;TZID=\":\n dtstart = line\n if prefix == \"DTEND;TZID=\":\n dtend = line\n if count != 1:\n print(\"debug {} {}\".format(prefix, count))\n error(\"unexepected inpur format\", fatal = True)\n return template.format(uid = uid, dtstart = dtstart, dtend = dtend,\n sender = sender, status = status)\n\n\nif __name__ == \"__main__\":\n response, sender, infile, outfile = parseArgs()\n invite = readInput(infile)\n output = generateResponse(invite, response, sender)\n writeOutput(output, outfile)\n","repo_name":"piotrcki/icalendar-reply","sub_path":"icalendar-reply.py","file_name":"icalendar-reply.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73122214128","text":"import json\n\nimport pytest\n\nfrom app.domains.users.repositories import UserModel\nfrom tests.conftest import truncate_tables, test_engine\nfrom tests.helpers.model_factories import ReactionModelFactory, UserModelFactory\nfrom tests.helpers.randoms import get_random_string\nfrom tests.helpers.user_creator import create_random_users\n\n\n@pytest.mark.parametrize('anyio_backend', ['asyncio'])\nclass TestUserApi:\n def setup_class(self):\n self.user: UserModel = UserModelFactory(test_engine).build()\n self.other_user: UserModel = UserModelFactory(test_engine).build(**{\n \"slack_id\": get_random_string(20),\n \"username\": \"test-new-user\",\n \"avatar_url\": \"yoyo\",\n \"department\": \"gag-team\"\n })\n\n def teardown_class(self):\n truncate_tables([\"users\", \"reactions\"])\n\n @pytest.mark.asyncio\n async def test_get_users(self, db, anyio_backend, test_client):\n create_random_users(10)\n response = await test_client.get(\"/users/\")\n assert response.status_code == 200\n data = json.loads(response.text)\n assert len(data) == 12 # self.user + self.other_user\n\n @pytest.mark.asyncio\n async def test_create_users(self, db, anyio_backend, test_client):\n payload = {\n \"slack_id\": get_random_string(20),\n \"name\": \"jay\",\n \"avatar_url\": \"url\",\n \"department\": \"gag-team\"\n }\n response = await test_client.post(\"/users/\", json=payload)\n assert response.status_code == 200\n data = json.loads(response.text)\n assert data[\"slack_id\"] == payload[\"slack_id\"]\n assert data[\"username\"] == payload[\"name\"]\n assert data[\"avatar_url\"] == payload[\"avatar_url\"]\n assert data[\"department\"] == payload[\"department\"]\n\n @pytest.mark.asyncio\n async def test_create_exists_users(self, db, anyio_backend, test_client):\n payload = {\n \"slack_id\": self.user.slack_id,\n \"name\": \"jay\",\n \"avatar_url\": \"url\",\n \"department\": \"gag-team\"\n }\n response = await test_client.post(\"/users/\", json=payload)\n assert response.status_code == 400\n\n @pytest.mark.asyncio\n async def test_get_reactions(self, db, anyio_backend, test_client):\n truncate_tables([\"reactions\"])\n\n emoji = get_random_string(5)\n ReactionModelFactory(db).build(\n to_user_id=self.user.id,\n from_user_id=self.other_user.id,\n emoji=emoji\n )\n ReactionModelFactory(db).build(\n to_user_id=self.user.id,\n from_user_id=self.other_user.id,\n emoji='other-emoji'\n )\n ReactionModelFactory(db).build(\n to_user_id=self.user.id,\n from_user_id=self.other_user.id,\n emoji=emoji,\n year=1991,\n month=9\n )\n ReactionModelFactory(db).build(\n to_user_id=self.user.id,\n from_user_id=self.other_user.id,\n emoji=emoji,\n year=1991,\n month=8\n )\n\n response = await test_client.get(f\"/users/{self.user.id}/reactions/\")\n assert response.status_code == 200\n data = json.loads(response.text)\n assert data[0][\"username\"] == self.other_user.username\n assert len(data[0][\"emoji_infos\"]) == 2\n assert data[0][\"emoji_infos\"][0][\"emoji\"] == emoji\n assert data[0][\"emoji_infos\"][0][\"count\"] == 3\n assert data[0][\"emoji_infos\"][1][\"emoji\"] == 'other-emoji'\n assert data[0][\"emoji_infos\"][1][\"count\"] == 1\n\n response = await test_client.get(f\"/users/{self.user.id}/reactions/\", params={\"year\": 1991, \"month\": 9})\n assert response.status_code == 200\n data = json.loads(response.text)\n assert data[0][\"username\"] == self.other_user.username\n assert len(data[0][\"emoji_infos\"]) == 1\n assert data[0][\"emoji_infos\"][0][\"emoji\"] == emoji\n assert data[0][\"emoji_infos\"][0][\"count\"] == 1\n\n @pytest.mark.asyncio\n async def test_get_my_reaction(self, db, anyio_backend, mock_allowed_emoji, test_client):\n truncate_tables([\"reactions\"])\n for _ in range(0, 5):\n ReactionModelFactory(db).build(\n to_user_id=self.user.id,\n from_user_id=self.other_user.id,\n emoji=\"heart\"\n )\n response = await test_client.get(f\"/users/{self.user.slack_id}/my_reaction/\")\n assert response.status_code == 200\n data = json.loads(response.text)\n assert data[\"❤️\"] == 5\n","repo_name":"JAY-Chan9yu/heymoji","sub_path":"tests/e2e/test_users.py","file_name":"test_users.py","file_ext":"py","file_size_in_byte":4582,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"20"} +{"seq_id":"31666045638","text":"from constants import GRAPH_SIZE\n\ndef gen_min_max(data_loc, out_loc):\n data = []\n\n with open(data_loc) as data_file:\n for row in data_file:\n num_list = list(map(int, row.split(' ')))\n data.append(num_list)\n\n\n def get_cycle_permutations(key):\n if GRAPH_SIZE == 2:\n return [[key[0], key[1]], [key[1], key[0]]]\n elif GRAPH_SIZE == 4:\n l1 = [key[0], key[1], key[2], key[3]]\n l2 = [key[1], key[2], key[3], key[0]]\n l3 = [key[2], key[3], key[0], key[1]]\n l4 = [key[3], key[0], key[1], key[2]]\n return [l1, l2, l3, l4]\n else:\n raise Exception(\"min_max_throughput: unsupported graph size\")\n\n def update_dictionary(dictionary, key, value):\n all_keys = get_cycle_permutations(key)\n inserted = False\n for key in all_keys:\n str_key = ','.join(map(str, key))\n if str_key in dictionary.keys():\n inserted = True\n if value not in dictionary.get(str_key, []):\n dictionary.setdefault(str_key, []).append(value)\n if inserted:\n break\n\n if not inserted:\n str_key = ','.join(map(str, key))\n if value not in dictionary.get(str_key, []):\n dictionary.setdefault(str_key, []).append(value)\n\n\n all_permutations = {}\n for sublist in data:\n res = sublist[-1:][0]\n sublist = sublist[:-1]\n update_dictionary(all_permutations, sublist, res)\n\n with open(out_loc, 'w') as out_data_file:\n for k, v in all_permutations.items():\n line = f\"{k}: {v}\\n\"\n out_data_file.write(line)\n\n\n \n","repo_name":"JachymPutta/kiterml","sub_path":"generation/gen_min_max_throughut.py","file_name":"gen_min_max_throughut.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17113331248","text":"import json\nimport requests\nimport numpy as np\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\ndef get_cid_from_mass(mass, tol=0.5):\n min_mass = mass - tol\n max_mass = mass + tol\n \n url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pccompound&term={}[MIMass]:{}[MIMass]&retmode=json&retmax=100000'.format(min_mass, max_mass)\n res = requests.get(url)\n string = res.content.decode(encoding='gbk')\n dicts = json.loads(string)\n cids = dicts['esearchresult']['idlist']\n \n idstring = ''\n smiles = []\n inchikey = []\n all_cids = []\n \n for i, cid in enumerate(cids):\n idstring += ',' + str(cid)\n if ((i%100==99) or (i==len(cids)-1)):\n url_i = \"http://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/\" + idstring[1:(len(idstring))] + \"/property/InChIKey,CanonicalSMILES/JSON\"\n res_i = requests.get(url_i, timeout=999)\n soup_i = BeautifulSoup(res_i.content, \"html.parser\")\n str_i = str(soup_i)\n properties_i = json.loads(str_i)['PropertyTable']['Properties']\n idstring = ''\n for properties_ij in properties_i:\n smiles_ij = properties_ij['CanonicalSMILES']\n if smiles_ij not in smiles:\n smiles.append(smiles_ij)\n inchikey.append(properties_ij['InChIKey'])\n all_cids.append(str(properties_ij['CID']))\n else:\n wh = np.where(np.array(smiles)==smiles_ij)[0][0]\n all_cids[wh] = all_cids[wh] + ', ' + str(properties_ij['CID'])\n \n result = pd.DataFrame({'InChIKey': inchikey, 'SMILES': smiles, 'PubChem': all_cids})\n return result","repo_name":"hcji/pubchem-service-scripts","sub_path":"search_compounds_via_mass.py","file_name":"search_compounds_via_mass.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"22607736946","text":"from django.http import JsonResponse\nfrom rest_framework import views\nfrom django.contrib.auth.hashers import PBKDF2PasswordHasher\nimport logging\nfrom django.db.models import F,Q\nfrom django.db.models import Count, Sum\nfrom django.contrib.auth import authenticate\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django_cron import CronJobBase, Schedule\nfrom .models import User, Shops, Items, Client, OrderTemplate, OrderItemStack, Schedule, Order, OrderList\n\nimport jwt,json\nfrom datetime import datetime, date\n\nfrom rest_framework import exceptions\nfrom rest_framework.authentication import get_authorization_header\nfrom rest_framework.authtoken.models import Token\n\nclass UserView(views.APIView):\n def post(self, request, userId=0):\n if userId == 0:\n try:\n user = User(\n name=request.data['name'],\n phone=request.data['phone'],\n role=request.data['role'],\n shop_id=Shops.objects.filter(id=request.data['shopId']).get(),\n )\n\n user.save()\n\n return JsonResponse({'status': True,'id': user.id, 'message': 'New user added successfully'}, status=200)\n \n except Exception as e:\n return JsonResponse({'message' : str(e),'status': False},status=200) \n else:\n try:\n user = User.objects.filter(id=userId).update(\n name=request.data['name'],\n phone=request.data['phone'],\n role=request.data['role'],\n shop_id=Shops.objects.filter(id=request.data['shopId']).get(),\n )\n\n return JsonResponse({'status': True,'id': id, 'message': 'Information updated successfully'}, status=200)\n except Exception as e:\n return JsonResponse({'message' : str(e),'status': False},status=200)\n\n def get(self, request, userId=0):\n if userId==0:\n users = User.objects.all()\n else:\n users = User.objects.filter(id=userId)\n result = []\n\n for user in users:\n status=True\n if user.is_active == 0:\n status=False\n\n result.append({\n 'id':user.id,\n 'name': user.name,\n 'phone': user.phone,\n 'role': user.role,\n 'shop_id':user.shop_id_id,\n 'status': status\n }) \n return JsonResponse(result, safe=False, status=200)\n\nclass ShopView(views.APIView):\n def post(self, request, shopId=0):\n if shopId == 0:\n try:\n shop=Shops(\n branch=request.data['branch'],\n address=request.data['address']\n )\n\n shop.save()\n\n return JsonResponse({'status': True,'id': shop.id, 'message': 'New shop added successfully'}, status=200)\n except Exception as e:\n return JsonResponse({'message' : str(e),'status': False},status=200)\n else:\n try:\n shop = Shops.objects.filter(id=shopId).update(\n branch=request.data['branch'],\n address=request.data['address']\n )\n\n return JsonResponse({'status': True,'id': id, 'message': 'Information updated successfully'}, status=200)\n except Exception as e:\n return JsonResponse({'message' : str(e),'status': False},status=200)\n \n def get(self, request, shopId=0):\n if shopId==0:\n shops = Shops.objects.all()\n else:\n shops = Shops.objects.filter(id=shopId)\n result = []\n\n for shop in shops:\n status=True\n if shop.is_active == 0:\n status=False\n\n result.append({\n 'id':shop.id,\n 'branch': shop.branch,\n 'address': shop.address,\n 'status': status\n }) \n return JsonResponse(result, safe=False, status=200)\n\nclass ItemView(views.APIView):\n def post(self, request, idemId=0):\n if idemId==0:\n try:\n item = Items(\n name = request.data['item_name'],\n shop_id = Shops.objects.filter(id=request.data['shopId']).get(),\n price = request.data['price']\n )\n item.save()\n\n return JsonResponse({'status':True, 'id': item.id, 'message': 'Item added successfully'}, status=200)\n except Exception as e:\n return JsonResponse({'message': str(e), 'status':False},status=200)\n else:\n try:\n item = Items.objects.filter(id=itemId).update(\n name = request.data['item_name'],\n shop_id = Shops.objects.filter(id=request.data['shopId']).get(),\n price = request.data['price']\n )\n return JsonResponse({'status':True, 'id': items.id, 'message': 'Item updated successfully'}, status=200)\n except Exception as e:\n return JsonResponse({'message': str(e), 'status': False,}, status=200)\n def get(self, request, itemId=0):\n if itemId==0:\n items = Items.objects.all()\n else:\n items = Items.objects.filter(id=itemId)\n result = []\n\n for item in items:\n status= True\n if item.is_active ==0:\n status=False\n result.append({\n 'id':item.id, \n 'item_name':item.name,\n 'shop_id':item.shop_id_id,\n 'price':item.price \n })\n return JsonResponse(result, safe= False, status=200)\n\nclass ClientView(views.APIView):\n def post(self, request, clientId=0):\n if clientId == 0:\n try:\n client = Client(\n name = request.data['name'],\n phone = request.data['phone'],\n contact_person_name = request.data['contact_name'],\n address = request.data['address'],\n shop_id = Shops.objects.filter(id=request.data['shopId']).get(),\n )\n\n client.save()\n\n order_temp = OrderTemplate(\n client_id = Client.objects.filter(id=client.id).get(),\n )\n\n order_temp.save()\n\n items = json.loads(request.data['items'])\n\n for item in items:\n data = OrderItemStack(\n order_temp_id = OrderTemplate.objects.filter(id=order_temp.id).get(),\n item_id = Items.objects.filter(id=item['item_id']).get(),\n quantity = item['quantity'],\n )\n data.save()\n\n dates = json.loads(request.data['dates'])\n\n for date in dates:\n schedule = Schedule(\n client_id = Client.objects.filter(id=client.id).get(),\n user_id = User.objects.filter(id=request.data['user_id']).get(),\n morning_time = request.data['morning_time'],\n evening_time = request.data['evening_time'],\n morning_schedule = request.data['morning_schedule'],\n evening_schedule = request.data['evening_schedule'],\n date = date['date'],\n order_template_id = OrderTemplate.objects.filter(id=order_temp.id).get(),\n )\n schedule.save()\n\n return JsonResponse({'status':True, 'id': client.id,'order_temp_id': order_temp.id, 'message': 'Client and the respective orders added successfully'}, status=200)\n except Exception as e:\n return JsonResponse({'message': str(e), 'status':False},status=200)\n \n def get(self, request, clientId=0):\n try:\n if clientId==0:\n clients = Client.objects.all()\n else:\n clients = Client.objects.filter(id=clientId)\n\n details = []\n \n for client in clients:\n items = []\n orders = []\n order_temps = OrderTemplate.objects.filter(client_id=client.id)\n for order_temp in order_temps:\n item = OrderItemStack.objects.filter(order_temp_id=order_temp.id)\n for i in item:\n items.append({\n 'item_id': i.item_id.id,\n 'item_name': i.item_id.name,\n 'quantity': i.quantity,\n })\n orders.append({\n 'order_temp_id': order_temp.id, \n 'items': items,\n })\n \n details.append({\n 'id': client.id,\n 'name': client.name,\n 'phone': client.phone,\n 'contact_person_name': client.contact_person_name,\n 'address': client.address,\n 'shop_branch': client.shop_id.branch,\n 'orders': orders,\n })\n\n return JsonResponse(details, safe=False, status=200)\n except Exception as e:\n return JsonResponse({'message' : str(e),'status': False},status=200)\n\ndef generate_daily_order():\n try:\n print(\"Updating Today's Order\")\n todayDate = date.today()\n schedules = Schedule.objects.filter(date=todayDate),\n for schedule in schedules:\n price = 0,\n items = OrderItemStack.objects.filter(order_temp_id=schedule.order_template_id.id)\n for item in items:\n price = price + (item.item_id.price*item.quantity)\n if schedule.morning_schedule == 1:\n order = Order(\n client_id = schedule.client_id.id,\n user_id = schedule.user_id.id,\n otp = 0,\n delivery_status = 0,\n user_phone = schedule.user_id.phone,\n client_phone = schedule.client_id.phone,\n date = schedule.date,\n time = schedule.morning_time,\n order_temp_id = schedule.order_template_id.id,\n price = price,\n )\n order.save()\n for i in items:\n order_list = OrderList(\n order_id = Order.objects.filter(id=order.id).get(),\n item_id = i.item_id.id,\n quantity = i.quantity,\n price = (i.item_id.price)*(i.quantity),\n )\n order_list.save()\n if schedule.evening_schedule == 1:\n order = Order(\n client_id = schedule.client_id,\n user_id = schedule.user_id,\n otp = 0,\n delivery_status = 0,\n user_phone = schedule.user_id.phone,\n client_phone = schedule.client_id.phone,\n date = schedule.date,\n time = schedule.evening_time,\n order_temp_id = schedule.order_template_id,\n price = price,\n )\n order.save()\n for i in items:\n order_list = OrderList(\n order_id = Order.objects.filter(id=order.id).get(),\n item_id = i.item_id.id,\n quantity = i.quantity,\n price = (i.item_id.price)*(i.quantity),\n )\n order_list.save()\n except Exception as e:\n print(\"Failed to generate daily order\"+str(e))","repo_name":"kragh-dev/coffee_order","sub_path":"order_manager/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"14603623118","text":"#WAP to Sum of digit.\r\nno=int(input(\"Enter any num:\"))\r\nm=no\r\nsum=0\r\nre=0\r\nwhile no!=0:\r\n re=no%10 \r\n sum=sum+re\r\n no=no//10\r\nprint(\"The sum of {} is {}.\".format(m,sum))\r\n","repo_name":"vtcbca/204-python-basic-21bca54","sub_path":"Solution 9.py","file_name":"Solution 9.py","file_ext":"py","file_size_in_byte":183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"2429438833","text":"#!/usr/bin/env python\nimport numpy as np\nimport math\n\n'''\nSelectionSort(A)\n For i = 1 to n do\n\tSort[i] = Find-Minimum from A\n\tDelete-Minimum from A Return(Sort)\n Return(Sort)\n'''\n\ndef SelectionSort(data):\n dup = data[:]\n sort = []\n while len(dup) > 0:\n min_ = min(dup)\n sort.append(min_)\n dup.remove(min_)\n\n return sort\n\n#data = np.random.randint(low=0, high=100, size=(10,)).tolist()\n#print(data)\n#print(SelectionSort(data))\n\n######################################################\n'''\nHeap Sort, parent is always smaller and greater than children\nHeap is always implemented with array, eg\n2,6,4,10,8,12,11\nimagine heap is a tree like structure, deep or broad search through\na heap, output is not sorted\nheap array like implement has too import features:\n 1. parent_index = child_index / 2\n 2. left_child_index = parent_index * 2\n'''\n\nclass Heap:\n def __init__(self):\n self.elements = []\n # a place holder, so index start with 1\n self.elements.append(-1)\n self.count = 0\n\n def parent(self, idx):\n if idx == 1:\n return -1\n else:\n return int(idx / 2)\n\n def left_child(self, idx):\n if idx * 2 <= self.count:\n return idx * 2\n else:\n return -1\n\n def insert(self, item):\n self.elements.append(item)\n self.count += 1\n self.bubble_up(self.count)\n\n def bubble_up(self, idx):\n if self.parent(idx) == -1:\n return\n\n if self.elements[self.parent(idx)] > self.elements[idx]:\n self.elements[self.parent(idx)], self.elements[idx] = self.elements[idx], self.elements[self.parent(idx)]\n self.bubble_up(self.parent(idx))\n\n def make_heap(self, data):\n for d in data:\n self.insert(d)\n\n def print(self):\n for i in range(1, self.count + 1):\n print(self.elements[i],)\n\n def empty(self):\n return (self.count == 0)\n\n def pop(self):\n if self.empty():\n return None\n min_ = self.elements[1]\n self.elements[1] = self.elements[self.count]\n self.count -= 1\n self.elements.pop(-1)\n self.bubble_down(1)\n\n return min_\n\n def bubble_down(self, idx):\n c = self.left_child(idx)\n if c < 0:\n return\n if c + 1 <= self.count and self.elements[c] > self.elements[c + 1]:\n min_idx = c + 1\n else:\n min_idx = c\n\n if self.elements[idx] > self.elements[min_idx]:\n self.elements[idx], self.elements[min_idx] = self.elements[min_idx], self.elements[idx]\n self.bubble_down(min_idx)\n\ndef HeapSort(data):\n heap = Heap()\n heap.make_heap(data)\n\n sort = []\n while not heap.empty():\n sort.append(heap.pop())\n\n return sort\n\n#data = np.random.randint(low=0, high=100, size=(10,)).tolist()\n#print(data)\n#print(HeapSort(data))\n\n#################################################\n\n'''\nInsertionSort(A)\n A[0] = −∞\n for i = 2 to n do\n j=i\n while (A[j] < A[j − 1]) do\n swap(A[j], A[j − 1])\n j=j−1\n'''\n\n################################################\n\n'''\nMergeSort(data, low, high):\n if low < hign:\n middel = (low + high) / 2\n MergeSort(data, low, middle)\n MergeSort(data, middle + 1, high)\n Merge(data, low, midel, high)\n'''\n\n##############################################\n\n'''\nQuickSort(data, low, high):\n if high > low:\n p = partition(data, low, high)\n QuickSort(data, low, p - 1)\n QuickSort(data, p + 1, high)\n\npartition每次找pivot,比pivot小的在pivot的左边,比pivot大的在pivot右边\nquick sort因为不需要多余的存储空间,操作简单,所以实际上要比heap sort和\nmerge sort要快\n'''\n\n############################################\n\n\n","repo_name":"thelostpeace/algorithms","sub_path":"sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"28877233779","text":"import unittest as ut\nimport unittest_decorators as utx\n\nimport pathlib\nimport tempfile\nimport contextlib\nimport numpy as np\n\nwith contextlib.suppress(ImportError):\n import vtk\n import vtk.util.numpy_support\n\nimport espressomd\nimport espressomd.lb\nif espressomd.has_features('LB_BOUNDARIES'):\n import espressomd.lbboundaries\n import espressomd.shapes\n\n\nclass TestLBWrite:\n system = espressomd.System(box_l=[10, 11, 12])\n system.time_step = 0.01\n system.cell_system.skin = 0.4\n\n def tearDown(self):\n self.system.actors.clear()\n self.system.thermostat.turn_off()\n\n def set_lbf(self):\n # setup LB system\n lbf = self.lb_class(\n kT=1, agrid=1.0, dens=1.0, visc=1.0, tau=0.1, seed=42,\n ext_force_density=[0, 0.03, 0])\n self.system.actors.add(lbf)\n if espressomd.has_features('LB_BOUNDARIES'):\n self.system.lbboundaries.add(espressomd.lbboundaries.LBBoundary(\n shape=espressomd.shapes.Wall(normal=[1, 0, 0], dist=1.5)))\n self.system.lbboundaries.add(espressomd.lbboundaries.LBBoundary(\n shape=espressomd.shapes.Wall(normal=[-1, 0, 0], dist=-8.5)))\n return lbf\n\n def parse_vtk(self, filepath, name, shape):\n reader = vtk.vtkStructuredPointsReader()\n reader.SetFileName(str(filepath))\n reader.ReadAllVectorsOn()\n reader.ReadAllScalarsOn()\n reader.Update()\n\n data = reader.GetOutput()\n points = data.GetPointData()\n\n return vtk.util.numpy_support.vtk_to_numpy(\n points.GetArray(name)).reshape(shape, order='F')\n\n def test_vtk(self):\n '''\n Check VTK files.\n '''\n\n with tempfile.TemporaryDirectory() as tmp_directory:\n path_vtk_root = pathlib.Path(tmp_directory)\n path_vtk_boundary = path_vtk_root / 'boundary.vtk'\n path_vtk_velocity = path_vtk_root / 'velocity.vtk'\n path_vtk_velocity_bb = path_vtk_root / 'velocity_bb.vtk'\n path_vtk_skip = path_vtk_root / 'skip.vtk'\n path_vtk_invalid = path_vtk_root / 'non_existent_folder' / 'file'\n\n shape = [10, 11, 12]\n lbf = self.set_lbf()\n self.system.integrator.run(100)\n\n # write VTK files\n with self.assertRaises(RuntimeError):\n lbf.write_vtk_velocity(str(path_vtk_invalid))\n with self.assertRaises(RuntimeError):\n lbf.write_vtk_boundary(str(path_vtk_invalid))\n lbf.write_vtk_boundary(str(path_vtk_boundary))\n lbf.write_vtk_velocity(str(path_vtk_velocity))\n with self.assertRaises(ValueError):\n lbf.write_vtk_velocity(str(path_vtk_skip), 3 * [0], None)\n with self.assertRaises(ValueError):\n lbf.write_vtk_velocity(str(path_vtk_skip), None, 3 * [0])\n with self.assertRaises(RuntimeError):\n lbf.write_vtk_velocity(str(path_vtk_skip), [-2, 1, 1], 3 * [1])\n with self.assertRaises(RuntimeError):\n lbf.write_vtk_velocity(str(path_vtk_skip), 3 * [0], [1, 2, 16])\n with self.assertRaises(ValueError):\n lbf.write_vtk_velocity(str(path_vtk_skip), [1, 1], 3 * [1])\n with self.assertRaises(ValueError):\n lbf.write_vtk_velocity(\n str(path_vtk_skip), 3 * [1], np.array([2, 3]))\n bb1, bb2 = ([1, 2, 3], [9, 10, 11])\n lbf.write_vtk_velocity(str(path_vtk_velocity_bb), bb1, bb2)\n\n # check VTK values match node values\n node_velocity = np.zeros(shape + [3])\n node_boundary = np.zeros(shape, dtype=int)\n for i in range(shape[0]):\n for j in range(shape[1]):\n for k in range(shape[2]):\n node = lbf[i, j, k]\n node_velocity[i, j, k] = node.velocity\n node_boundary[i, j, k] = node.boundary\n node_velocity_bb = node_velocity[bb1[0]:bb2[0],\n bb1[1]:bb2[1],\n bb1[2]:bb2[2]]\n\n vtk_velocity = self.parse_vtk(path_vtk_velocity, 'velocity',\n node_velocity.shape)\n np.testing.assert_allclose(vtk_velocity, node_velocity, atol=5e-7)\n\n vtk_velocity_bb = self.parse_vtk(path_vtk_velocity_bb, 'velocity',\n node_velocity_bb.shape)\n np.testing.assert_allclose(\n vtk_velocity_bb, node_velocity_bb, atol=5e-7)\n\n vtk_boundary = self.parse_vtk(path_vtk_boundary, 'boundary', shape)\n np.testing.assert_equal(vtk_boundary, node_boundary.astype(int))\n\n def test_print(self):\n '''\n Check data files.\n '''\n\n with tempfile.TemporaryDirectory() as tmp_directory:\n path_dat_root = pathlib.Path(tmp_directory)\n path_dat_boundary = path_dat_root / 'boundary.vtk'\n path_dat_velocity = path_dat_root / 'velocity.vtk'\n path_dat_invalid = path_dat_root / 'non_existent_folder' / 'file'\n\n shape = [10, 11, 12]\n lbf = self.set_lbf()\n self.system.integrator.run(100)\n\n # write data files\n with self.assertRaises(RuntimeError):\n lbf.write_velocity(str(path_dat_invalid))\n with self.assertRaises(RuntimeError):\n lbf.write_boundary(str(path_dat_invalid))\n lbf.write_boundary(str(path_dat_boundary))\n lbf.write_velocity(str(path_dat_velocity))\n\n # check data values match node values\n node_velocity = np.zeros(shape + [3])\n node_boundary = np.zeros(shape, dtype=int)\n for i in range(shape[0]):\n for j in range(shape[1]):\n for k in range(shape[2]):\n node = lbf[i, j, k]\n node_velocity[i, j, k] = node.velocity\n node_boundary[i, j, k] = node.boundary\n\n ref_coord = np.array([\n np.tile(np.arange(shape[0]), shape[1] * shape[2]),\n np.tile(np.repeat(np.arange(shape[1]), shape[0]), shape[2]),\n np.repeat(np.arange(shape[2]), shape[0] * shape[1])]).T\n\n dat_velocity = np.loadtxt(path_dat_velocity)\n dat_coord = (dat_velocity[:, 0:3] - 0.5).astype(int)\n np.testing.assert_equal(dat_coord, ref_coord)\n dat_vel = dat_velocity[:, 3:]\n ref_vel = np.swapaxes(node_velocity, 0, 2).reshape((-1, 3))\n np.testing.assert_allclose(dat_vel, ref_vel, atol=5e-7)\n\n dat_boundary = np.loadtxt(path_dat_boundary)\n dat_coord = (dat_boundary[:, 0:3] - 0.5).astype(int)\n np.testing.assert_equal(dat_coord, ref_coord)\n dat_bound = dat_boundary[:, 3].astype(int)\n ref_bound = np.swapaxes(node_boundary, 0, 2).reshape(-1)\n if isinstance(lbf, espressomd.lb.LBFluid):\n ref_bound = (ref_bound != 0).astype(int)\n np.testing.assert_equal(dat_bound, ref_bound)\n\n\n@utx.skipIfMissingModules(\"vtk\")\nclass TestLBWriteCPU(TestLBWrite, ut.TestCase):\n\n def setUp(self):\n self.lb_class = espressomd.lb.LBFluid\n\n\n@utx.skipIfMissingGPU()\n@utx.skipIfMissingModules(\"vtk\")\nclass TestLBWriteGPU(TestLBWrite, ut.TestCase):\n\n def setUp(self):\n self.lb_class = espressomd.lb.LBFluidGPU\n\n\nif __name__ == '__main__':\n ut.main()\n","repo_name":"1234somesh/espresso","sub_path":"testsuite/python/lb_vtk.py","file_name":"lb_vtk.py","file_ext":"py","file_size_in_byte":7566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"535197402","text":"from fuzzywuzzy import fuzz,process\ndef reger(matcher, cor):\n text_lin = cor.split('\\n')\n #lin_sel for the fuzzy selected in the line\n lin_sel = process.extractOne(matcher, text_lin)\n print(lin_sel[0])\n lin_tokens = lin_sel[0].split(' ')\n print(lin_tokens)\n print(matcher.split(' '))\n for word in matcher.split(' '):\n token = process.extractOne(word, lin_tokens)\n print(token)\n lin_tokens.remove(token[0])\n# print(lin_tokens)\n out=' '.join(lin_tokens)\n# print('out '+out)\n return out\n\n\ndef reger_find(matcher, cor):\n out = ''\n text_lin = cor.split('\\n')\n #lin_sel for the fuzzy selected in the line\n lin_sel = process.extractOne(matcher, text_lin)\n print(lin_sel[0])\n lin_tokens = lin_sel[0].split(' ')\n print(lin_tokens)\n\n print(matcher.split(' '))\n for word in matcher.split(' '):\n token = process.extractOne(word, lin_tokens)\n print(out)\n out = out +' ' + token[0]\n \n# print('out '+out)\n return out\n\n\n\ndef initiate(query_string, corpus, mode):\n if mode ==0:\n text = reger(query_string, corpus)\n else :\n query_string.lstrip()\n query_string.rstrip()\n text = reger_find(query_string, corpus)\n\n\n\n print(text)\n text = text.lstrip()\n text = text.rstrip()\n if ':'in text or '-' in text:\n print('removing')\n text = text.strip(':')\n text = text.strip('-')\n text = text.strip(':')\n \n return text\n","repo_name":"amansheaven/EY_FileClaims","sub_path":"app/static/ocr/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"1848678595","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 12 20:08:23 2017\n\n@author: danjr\n\"\"\"\n\nimport fluids2d.piv as piv\nimport matplotlib.pyplot as plt\nimport pickle\nimport numpy as np\nimport scipy.ndimage\nfrom fluids2d.masking import MovingRectMasks\nimport fluids2d.geometry\nimport pims\nfrom fluids2d.piv import PIVDataProcessing\nimport pandas as pd\nimport fluids2d.spectra as spectra\n\nparent_folder = r'C:\\Users\\Luc Deike\\data_comp3_C\\180228\\\\'\ncine_name = r'piv_4x4_center_sunbathing_on100_off400_fps1000'\ncase_name = cine_name\n\nneed2rotate = False\n\nvmin = -0.2\nvmax = 0.2\n\n'''\nLoad the data and make the scalers\n'''\n\np = pickle.load(open(parent_folder+case_name+'.pkl'))\np.parent_folder = parent_folder\np.name_for_save = case_name\np.associate_flowfield()\ndt = p.dt_frames\n\nif need2rotate:\n p.data.ff=piv.rotate_data_90(p.data.ff)\n p.data.ff=piv.rotate_data_90(p.data.ff)\n p.data.ff=piv.rotate_data_90(p.data.ff)\nff = p.data.ff\n\ng_orig = fluids2d.geometry.GeometryScaler(dx=p.dx,im_shape=(2048,2048),origin_pos=(-1024,-1024),origin_units='pix')\n#g_orig = fluids2d.geometry.GeometryScaler(dx=p.dx,im_shape=(512,512),origin_pos=(-400,-50),origin_units='pix')\ng = fluids2d.geometry.create_piv_scaler(p,g_orig)\n\n'''\nFilter the velocity field\n'''\nff=piv.clip_flowfield(ff,5)\n\n\nstart_frames = np.arange(0,5000,10)\n\nx = [[np.random.uniform(-0.05,0.05)] for _ in start_frames]\ny = [[np.random.uniform(-0.05,0.05)] for _ in start_frames]\n\nframes_after_drop = np.arange(0,1000)\nfor fi,f in enumerate(frames_after_drop):\n \n for si,s in enumerate(start_frames):\n \n [loc_y,loc_x] = g.get_coords([y[si][-1],x[si][-1]])\n \n if loc_y==g.im_shape[0] or loc_y==0 or loc_x==g.im_shape[1] or loc_y==0:\n u = np.nan\n v = np.nan\n \n else:\n u = ff[f+s,loc_y,loc_x,0]\n v = ff[f+s,loc_y,loc_x,1]\n \n y[si].append(y[si][-1]+dt*v)\n x[si].append(x[si][-1]+dt*u)\n \nfig = plt.figure()\nax = fig.add_subplot(111)\n\n[ax.plot(X,Y,alpha=0.2) for X,Y in zip(x,y)]\nax.set_xlabel('x [m]')\nax.set_ylabel('y [m]')\nfig.tight_layout()\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n\n[ax.plot(np.array(X)-X[0],np.array(Y)-Y[0]) for X,Y in zip(x,y)]\n\n\nmean_displacement_list = []\nlags_list = []\nautocorr_lags_list = []\nautocorr_corr_list = []\nfor bi,(x_vec,y_vec) in enumerate(zip(x,y)):\n \n \n x_vec = np.array(x_vec)\n y_vec = np.array(y_vec)\n \n print(bi)\n lags = np.arange(0,min(len(x_vec),1000)-2,1)\n mean_displacement = np.zeros(np.shape(lags))\n \n for li,lag in enumerate(lags):\n mean_displacement[li] = np.sqrt(np.nanmean((x_vec[0:len(x_vec)-lag]-x_vec[lag:len(x_vec)])**2 + (y_vec[0:len(x_vec)-lag]-y_vec[lag:len(x_vec)])**2))\n \n lags_list.append(lags)\n mean_displacement_list.append(mean_displacement)\n \n u = np.gradient(np.array(x_vec))/dt\n C,lags = spectra.autocorr(u,i_lags=np.arange(len(lags)),dt=dt)\n autocorr_lags_list.append(lags)\n autocorr_corr_list.append(C)\n \n \nfig = plt.figure()\nax = fig.add_subplot(111)\nurms = 0.1\n[ax.loglog(l*dt,md**2/urms**2,alpha=0.2) for l,md in zip(lags_list,mean_displacement_list)]\nax.plot([.01,.1],[10**-2,10**0],'--',color='k',alpha=0.5)\nax.set_xlabel('lag [s]')\nax.set_ylabel('MSD / u_rms [s^2]')\nfig.tight_layout()\n\nfig = plt.figure()\nax_c = fig.add_subplot(111)\n[ax_c.plot(l,c,alpha=0.1) for l,c in zip(autocorr_lags_list,autocorr_corr_list)]\n\nfig = plt.figure()\nax_c = fig.add_subplot(111)\n[ax_c.plot(l,np.cumsum(c)*(l[1]-l[0]),alpha=0.1) for l,c in zip(autocorr_lags_list,autocorr_corr_list)]\nax_c.set_xlabel('lag [s]')\nax_c.set_ylabel('integral of lagrangian autocorrelation [s]')\nfig.tight_layout()\n\n\n\n\n\n\n\n\n#\n#x_bins = np.arange(-0.08,0.08,.005)\n#y_bins = np.arange(-0.08,0.08,.005)\n#X,Y = np.meshgrid(x_bins,y_bins)\n#\n#counts = np.zeros(np.shape(X))\n#counts_norm = np.zeros(np.shape(X))\n#end_y = np.zeros(np.shape(X))\n#\n#r_df = pd.DataFrame(index=frames_after_drop)\n#\n#ci = -1\n#for x_vec,y_vec in zip(x,y):\n# ci = ci+1\n# for xi,yi in zip(x_vec,y_vec):\n# if ~np.isnan(xi) and ~np.isnan(yi):\n# \n# ind_y = np.digitize(yi,y_bins)\n# ind_x = np.digitize(xi,x_bins)\n# counts[ind_y,ind_x] = counts[ind_y,ind_x]+1\n# \n# ind_y_norm = np.digitize(yi-y_vec[0],y_bins)\n# ind_x_norm = np.digitize(xi-x_vec[0],x_bins)\n# counts_norm[ind_y_norm,ind_x_norm] = counts_norm[ind_y_norm,ind_x_norm]+1\n# \n# if ~np.isnan(x_vec[0]) and ~np.isnan(y_vec[0]):\n# \n# ind_start_y = np.digitize(y_vec[0],y_bins)\n# ind_start_x = np.digitize(x_vec[0],x_bins) \n# y_no_nans = [i for i in y_vec if ~np.isnan(i)] \n# end_y[ind_start_y,ind_start_x] = end_y[ind_start_y,ind_start_x] + y_no_nans[-1]\n# \n# r_vec = np.sqrt((np.array(x_vec)-x_vec[0])**2+(np.array(y_vec)-y_vec[0])**2)\n# r_df[ci] = r_vec[0:-1]\n# \n#fig=plt.figure()\n#ax=fig.add_subplot(111)\n#ax.imshow(counts,vmin=0,vmax=10000,extent=g.im_extent,origin='lower')\n#\n#fig=plt.figure()\n#ax=fig.add_subplot(111)\n#ax.imshow(counts_norm,vmin=0,vmax=10000,extent=g.im_extent,origin='lower')\n#\n#fig=plt.figure()\n#ax=fig.add_subplot(111)\n#ax.imshow(end_y,extent=g.im_extent,origin='lower')\n#\n##r_df.index = r_df.index*dt\n#r_mean = r_df.mean(axis=1)\n#\n#fig = plt.figure()\n#ax = fig.add_subplot(111)\n#\n#ax.plot(r_mean,color='k',lw=2)\n#ax.plot(r_mean+r_df.std(axis=1),color='gray')\n#ax.plot(r_mean-r_df.std(axis=1),color='gray')\n#\n#ax.set_xlabel('time [s]')\n#ax.set_ylabel('distance traveled [m]')\n#\n","repo_name":"Erismena/Study_Surface","sub_path":"scripts/piv_to_trajectories.py","file_name":"piv_to_trajectories.py","file_ext":"py","file_size_in_byte":5597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"45214440281","text":"#!/usr/bin/env python\n\nfrom __future__ import unicode_literals\n\n# Allow direct execution\nimport os\nimport sys\nimport unittest\nsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom yt_dlp.postprocessor import (\n FFmpegThumbnailsConvertorPP,\n MetadataFromFieldPP,\n MetadataFromTitlePP,\n)\n\n\nclass TestMetadataFromField(unittest.TestCase):\n def test_format_to_regex(self):\n pp = MetadataFromFieldPP(None, ['title:%(title)s - %(artist)s'])\n self.assertEqual(pp._data[0]['regex'], r'(?P.+)\\ \\-\\ (?P<artist>.+)')\n\n def test_field_to_outtmpl(self):\n pp = MetadataFromFieldPP(None, ['title:%(title)s : %(artist)s'])\n self.assertEqual(pp._data[0]['tmpl'], '%(title)s')\n\n def test_in_out_seperation(self):\n pp = MetadataFromFieldPP(None, ['%(title)s \\\\: %(artist)s:%(title)s : %(artist)s'])\n self.assertEqual(pp._data[0]['in'], '%(title)s : %(artist)s')\n self.assertEqual(pp._data[0]['out'], '%(title)s : %(artist)s')\n\n\nclass TestMetadataFromTitle(unittest.TestCase):\n def test_format_to_regex(self):\n pp = MetadataFromTitlePP(None, '%(title)s - %(artist)s')\n self.assertEqual(pp._titleregex, r'(?P<title>.+)\\ \\-\\ (?P<artist>.+)')\n\n\nclass TestConvertThumbnail(unittest.TestCase):\n def test_escaping(self):\n pp = FFmpegThumbnailsConvertorPP()\n if not pp.available:\n print('Skipping: ffmpeg not found')\n return\n\n file = 'test/testdata/thumbnails/foo %d bar/foo_%d.{}'\n tests = (('webp', 'png'), ('png', 'jpg'))\n\n for inp, out in tests:\n out_file = file.format(out)\n if os.path.exists(out_file):\n os.remove(out_file)\n pp.convert_thumbnail(file.format(inp), out)\n assert os.path.exists(out_file)\n\n for _, out in tests:\n os.remove(file.format(out))\n","repo_name":"SpartanJohn-117/yt-dlp","sub_path":"test/test_postprocessors.py","file_name":"test_postprocessors.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"476837771","text":"def getinput():\n file = open(\"input.txt\", \"r\")\n lines = file.read().splitlines()\n patterns = []\n for line in lines:\n l = line.split(\" | \")\n patterns.append([l[0].split(), l[1].split()])\n return patterns\n\ndef one():\n patterns = getinput()\n\n s = {2, 3, 4, 7}\n count = 0\n for pattern in patterns:\n for c in pattern[1]:\n if len(c) in s:\n count += 1\n return count\n\nprint(one())\n\nm = {\n 2: 1,\n 4: 4,\n 3: 7,\n 7: 8\n}\n\ndef two():\n patterns = getinput()\n\n total = 0\n for pattern in patterns:\n d = {}\n for word in pattern[0]:\n size = len(word)\n if size in m:\n d[m[size]] = ''.join(sorted(word))\n\n for word in pattern[0]:\n size = len(word)\n if size == 6 and any(c not in word for c in d[1]):\n d[6] = ''.join(sorted(word))\n break\n\n for word in pattern[0]:\n size = len(word)\n ordered = ''.join(sorted(word))\n if size == 6 and any(c not in word for c in d[4]) and ordered not in d.values():\n d[0] = ordered\n break\n\n for word in pattern[0]:\n size = len(word)\n ordered = ''.join(sorted(word))\n if size == 6 and ordered not in d.values():\n d[9] = ''.join(sorted(word))\n break\n\n for word in pattern[0]:\n size = len(word)\n if size == 5 and all(c in d[6] for c in word):\n d[5] = ''.join(sorted(word))\n break\n\n for word in pattern[0]:\n size = len(word)\n ordered = ''.join(sorted(word))\n if size == 5 and all(c in d[9] for c in word) and ordered not in d.values():\n d[3] = ''.join(sorted(word))\n break\n\n for word in pattern[0]:\n size = len(word)\n ordered = ''.join(sorted(word))\n if size == 5 and ordered not in d.values():\n d[2] = ''.join(sorted(word))\n break\n\n inv_d = {v: k for k, v in d.items()}\n mid = 0\n for word in pattern[1]:\n ordered = ''.join(sorted(word))\n mid = mid * 10 + inv_d[ordered]\n total += mid\n return total\n\nprint(two())","repo_name":"TsarkFC/advent","sub_path":"2021/08.py","file_name":"08.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"45200261467","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Aug 20 21:58:08 2022\r\n\r\n@author: priya\r\n\"\"\"\r\n\r\ndef isSubstring(s1,s2):\r\n lens1 = len(s1)\r\n lens2 = len(s2)\r\n if lens1>=lens2:\r\n if s2 in s1:\r\n return True\r\n return False\r\n else:\r\n if s1 in s2:\r\n return True\r\n return False\r\n \r\ndef strRotation(s1,s2):\r\n if len(s1) != len(s2):\r\n return False\r\n sc1 = s1 + s1 + s1\r\n sc2 = s2 + s2\r\n return isSubstring(sc1,sc2)\r\n\r\nprint(strRotation(\"Priyam\",\"iyaPrm\"))","repo_name":"raopriyam/Leetcode-CTCI-Python","sub_path":"strRotation.py","file_name":"strRotation.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"10714641519","text":"import random\nimport time\nimport pprint\n\nclass Game(object):\n def __init__(self, piece):\n self.piece = piece\n self.board = {0: \"-\", 1: \"-\", 2: \"-\", 3: \"-\", 4: \"-\", 5: \"-\", 6: \"-\", 7: \"-\", 8: \"-\", 9: \"-\"}\n self.playerOne = 1\n self.playerTwo = 2\n \n def playerMove(self):\n if \"-\" not in self.board.values():\n user_input = input(\"The game is a tie! Would you like to play again?\")\n if user_input == \"Y\" or user_input == \"Yes\":\n print(\"lets play again\")\n self.board = {0: \"-\", 1: \"-\", 2: \"-\", 3: \"-\", 4: \"-\", 5: \"-\", 6: \"-\", 7: \"-\", 8: \"-\", 9: \"-\"}\n # self.playerMove()\n else:\n print(\"Thanks for playing! Quitting the game.\")\n return\n return\n \n # self.playerInput()\n \n\n \n\n def playerInput(self):\n position = self.setPosition(self.playerOne)\n print(\"Position = \" + str(position))\n if self.board[position] == \"-\":\n self.board[position] = self.piece\n print(self.board)\n self.playerMove()\n else:\n print(\"That position already has a piece. Please choose another.\")\n print(self.board)\n # self.playerMove()\n self.playerInput()\n self.playerMove()\n self.playerTwoTurn()\n \n\n def playerTwoTurn(self):\n position = self.setPosition(self.playerTwo)\n if self.piece == \"X\":\n playerTwoPiece = \"O\"\n else:\n playerTwoPiece = \"X\"\n if self.board[position] == \"-\":\n self.board[position] = playerTwoPiece\n print(self.board)\n self.playerMove()\n else:\n print(\"That position already has a piece. Please choose another.\")\n print(self.board)\n self.playerTwoTurn()\n self.playerMove()\n self.playerInput()\n\n def setPosition(self, player):\n positionInput = int(input(\"Player \" + str(player) + \" please choose a spot: \"))\n return positionInput\n \n\n \n\ngame1 = Game(\"O\")\ngame1.playerInput()\n\n # playerChoice = input(\"Starting the first round. Who will be Player 1? \")\n # if self.player == 1:\n # self.playerTwo = 2\n # else:\n # self.playerTwo = 1\n # print(self.playerTwo)","repo_name":"acolbert1/TicTactoe","sub_path":"TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"12701854813","text":"###############################################################################\n# RaxML - Use muscle alignment and the model chosen by modeltest to build\n# the best tree. Slower than fasttree, possible higher quality.\n# SACCHARIS 2.0 author: Alexander Fraser, https://github.com/AlexSCFraser\n# Original author for SACCHARIS 1.0: Dallas Thomas\n# License: GPL v3\n###############################################################################\n# Built in libraries\nimport atexit\nimport glob\nimport os\nimport subprocess\nimport sys\nfrom logging import Logger, getLogger\nfrom math import ceil\n\nfrom saccharis.utils.Formatting import convert_path_wsl\n# Internal Imports\nfrom saccharis.utils.PipelineErrors import PipelineException\n\n\ndef main(muscle_input_file: str | os.PathLike, amino_model: str, output_dir: str | os.PathLike,\n raxml_version: str, num_seqs: int, threads: int = 4, force_update: bool = False,\n user_run: int = None, logger: Logger = getLogger()):\n if user_run:\n rax_tree = f\"RAxML_bipartitions.{user_run:05d}.A1\"\n else:\n rax_tree = \"RAxML_bipartitions.A1\"\n bootstrap = 100\n\n # Calculate an optimal number of threads to use\n opt_thr = ceil(num_seqs / 300) # optimal thread num = # seqs / 300 rounded up\n # todo: QUESTION: why do we do this? alignments of smaller groups still seem faster with more threads\n\n # Now set threads used to the lower value of $opt_thr and $threads\n # todo: should we up the thread count above 16? Why is it limited to 16 threads anyway?\n if threads < opt_thr:\n opt_thr = threads\n elif threads >= 16:\n opt_thr = 16\n elif opt_thr == 1:\n opt_thr = 2 # raxML pthread version requires at least two threads\n\n file_output_path = os.path.join(output_dir, rax_tree)\n\n if os.path.isfile(file_output_path) and not force_update:\n msg = \"\\n\\nRAxML has built this tree before, loading tree data from previous run.\\n\\n\"\n print(msg)\n logger.debug(msg)\n return file_output_path\n else:\n\n # check for partial run files and delete them here\n files_to_delete = glob.glob(os.path.join(output_dir, '*.A1'))\n for file_path in files_to_delete:\n try:\n os.remove(file_path)\n logger.info(f\"Deleted {file_path}\")\n except OSError as e:\n logger.info(f\"Error deleting {file_path}: {e}\")\n\n print(\"Building best tree - using RAxML\\n\")\n # thread_arg = \"\" if opt_thr == 1 else f\"-T {opt_thr} \"\n extension = f\"UserRun{user_run:05d}.A1\" if user_run else \"A1\"\n command = f\"{raxml_version} -f a -T {opt_thr} -p 0111 -s {muscle_input_file} -n {extension} \" \\\n f\"-m {amino_model} -x 0123 -# {bootstrap}\"\n\n# if ($opt_thr == 1) {\n # $cmd1 = f\"{raxml_version} -f a -p 0111 -s $muscle -n A1 -m $tree -x 0123 -# $bootstrap; \";\n # } else {\n # $cmd1 = \"$raxml -f a -T $opt_thr -p 0111 -s $muscle -n A1 -m $tree -x 0123 -# $bootstrap; \";\n # }\n # &run_cmd($cmd1, $cmd2);\n\n msg = f\"Running command: {command}\"\n logger.info(msg)\n # subprocess.run(command, shell=True, cwd=output_dir, check=True)\n main_proc = subprocess.Popen(command, shell=True, cwd=output_dir)\n atexit.register(main_proc.kill)\n main_proc.wait()\n atexit.unregister(main_proc.kill)\n if main_proc.returncode != 0:\n msg = f\"raxml tree building process failed to return properly. Return code: {main_proc.returncode}\"\n logger.error(msg)\n raise PipelineException(msg)\n\n msg = \"RaxML has finished\\n\\n\"\n print(msg)\n logger.debug(msg)\n return file_output_path\n\n\ndef build_tree_raxml_ng(muscle_input_file: str | os.PathLike, amino_model: str, output_dir: str | os.PathLike,\n num_seqs: int, threads: int = 4, force_update: bool = False,\n user_run: int = None, logger: Logger = getLogger(), bootstraps: int = 100):\n if user_run:\n # todo: update these prefixes to be more informative? Is this redudant?\n rax_tree = f\"RAxML-NG_output.U{user_run:05d}\"\n else:\n rax_tree = \"RAxML-NG_output\"\n\n initial_seed = 111\n file_output_prefix = os.path.join(output_dir, rax_tree)\n\n if sys.platform.startswith(\"win\"):\n command = [\"wsl\"]\n muscle_input_path = convert_path_wsl(muscle_input_file)\n file_output_path = convert_path_wsl(file_output_prefix)\n validity_args = [\"wsl\"]\n else:\n command = []\n muscle_input_path = muscle_input_file\n file_output_path = file_output_prefix\n validity_args = []\n\n validity_args += [\"raxml-ng\", \"--parse\", \"--seed\", str(initial_seed), \"--msa\", muscle_input_path, \"--model\", amino_model, \"--prefix\", file_output_path]\n try:\n valid_result = subprocess.run(validity_args, capture_output=True, encoding=\"utf-8\", check=True)\n logger.info(valid_result.stdout)\n except FileNotFoundError as err:\n logger.error(err)\n msg = \"raxml-ng not found, check that it's available via PATH variable.\"\n logger.error(msg)\n raise PipelineException(msg) from err\n\n optimal_threads = threads\n can_run = False\n for line in valid_result.stdout.split('\\n'):\n if line.__contains__(\"Recommended number of threads\"):\n optimal_threads = int(line.split(' ')[-1])\n elif line.__contains__(\"Alignment can be successfully read\"):\n can_run = True\n\n if not can_run:\n logger.error(valid_result.stdout)\n logger.error(\"RAxML-NG cannot read MSA.\")\n raise PipelineException(\"RAxML-NG cannot read MSA.\")\n run_threads = min(optimal_threads, threads)\n\n # todo: add outgroup option --outgroup [csv list]\n command += [\"raxml-ng\", \"--all\", \"--threads\", f\"auto{'{' + str(run_threads) + '}'}\", \"--seed\", str(initial_seed),\n \"--msa\", muscle_input_path, \"--prefix\", file_output_path, \"--model\", amino_model,\n \"--bs-trees\", str(bootstraps)]\n\n if force_update:\n command += [\"--redo\"]\n\n msg = f\"Running command: {command}\"\n logger.info(msg)\n\n try:\n assert(os.path.isfile(muscle_input_file))\n assert(os.path.isdir(output_dir))\n main_proc = subprocess.Popen(command, cwd=output_dir)\n atexit.register(main_proc.kill)\n main_proc.wait()\n atexit.unregister(main_proc.kill)\n if main_proc.returncode != 0:\n msg = f\"raxml-ng tree building process failed to return properly. Return code: {main_proc.returncode}\"\n logger.error(msg)\n raise PipelineException(msg)\n\n except FileNotFoundError as err:\n logger.error(err)\n msg = \"raxml-ng not found, check that it's available via PATH variable.\"\n logger.error(msg)\n raise PipelineException(msg) from err\n\n # todo: check if bootstraps converged and then run until they converge. This may take large amounts of compute and\n # should be an optional feature. Will have to recompute best tree with support, so maybe just do this\n # earlier instead of running with --all?\n # see https://github.com/amkozlov/raxml-ng/wiki/Tutorial#bootstrapping\n # bsconverge_args = [\"raxml-ng\", \"--bsconverge\", \"--bs-trees\", f\"{file_output_path}.raxml.bootstraps\",\n # \"--prefix\", f\"{file_output_path}\", \"--seed\", \"2\", \"--threads\", \"2\", \"--bs-cutoff\", \"0.01\"]\n # if sys.platform.startswith(\"win\"):\n # bsconverge_args.insert(0, \"wsl\")\n # bsconverge_result = subprocess.run(bsconverge_args, capture_output=True, encoding=\"utf-8\", check=True)\n\n msg = \"RaxML-NG has finished\\n\\n\"\n print(msg)\n logger.debug(msg)\n\n best_tree_with_support_path = os.path.join(f\"{file_output_prefix}.raxml.support\")\n return best_tree_with_support_path\n\n\nif __name__ == \"__main__\":\n test_family = \"PL9\"\n test_mode = \"CHARACTERIZED\"\n group = os.path.join(os.getcwd(), \"../../output\", test_family, test_mode)\n muscle_input = os.path.join(group, \"muscle\", \"PL9_CHARACTERIZED.muscle_aln_mod.phyi\")\n raxml_folder = os.path.join(group, \"raxml\")\n if not os.path.isdir(raxml_folder):\n os.mkdir(raxml_folder, 0o755)\n main(muscle_input, \"PROTGAMMAIWAG\", raxml_folder, \"raxmlHPC-PTHREADS-AVX\", 13, threads=8)\n","repo_name":"saccharis/SACCHARIS_2","sub_path":"src/saccharis/RAxML_Build.py","file_name":"RAxML_Build.py","file_ext":"py","file_size_in_byte":8332,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"11010501166","text":"import matplotlib.pyplot as plt\nimport csv\nimport sys\nimport pandas as pd\n\ninputsize = []\nruntime = []\nlang = []\n\nwith open(sys.argv[1],'r') as csvfile:\n plots = csv.reader(csvfile, delimiter=',')\n for row in plots:\n inputsize.append(float(row[1]))\n runtime.append(float(row[2]))\n lang.append(str(row[0]))\n\ndf = pd.DataFrame(dict(x=inputsize, y=runtime, label=lang))\nlangs = df.groupby('label')\n\nwith plt.xkcd():\n fig, ax = plt.subplots()\n ax.set_title(sys.argv[1].replace(\".csv\", \"\").upper())\n ax.set_xscale('log')\n ax.set_yscale('log')\n ax.set_xlabel('Input Size')\n ax.set_ylabel('Run Time (sec)')\n ax.margins(0.05) # Optional, just adds 5% padding to the autoscaling\n for name, lang in langs:\n ax.plot(lang.x, lang.y, marker='o', linestyle='', ms=6, alpha=0.7, label=name)\n ax.legend()\n plt.show()","repo_name":"rbreeze/CSCI551-final-project","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"2833256332","text":"import math\nimport sys\n\nm,n=map(int,sys.stdin.readline().split())\n\nfor i in range(m,n+1):\n error=0\n for j in range(2,int(i**1/2)+1):\n if i%j==0:\n error=1\n break\n if i != 1 and error==0:\n print(i)\n\n#에라토스테네스의 체 기억하기.\n'''\n에라토스테네스의 체란 소수를 판별하는 알고리즘.\n\nm,n=map(int,input().split())\n\nfor i in range(m,n+1):\n if i==1:#1은 소수가 아니므로 제외\n continue\n for j in range(2,int(i**0.5)+1):\n if i%j==0: #약수가 존재하므로 소수가 아님\n break #더이상 검사할 필요가 없으므로 멈춤\n else:\n print(i)\n\n'''","repo_name":"thisishwan2/Algorithm","sub_path":"baekjoon/python/소수판정/1929.py","file_name":"1929.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"28950210701","text":"import sys\nfrom itertools import permutations as pm\ninput = sys.stdin.readline\n\nn = int(input())\narr = list(input().split())\n\nmin_val = 9998979695949393\nfor case in list(pm(arr, n)):\n\tstring = \"\"\n\tfor i in range(n):\n\t\tif string != \"\" and string[-1] == case[i][0]:\n\t\t\tstring += case[i][1]\n\t\telse:\n\t\t\tstring += case[i]\n\t\n\tif min_val > int(string):\n\t\tmin_val = int(string)\n\t\nprint(min_val)","repo_name":"Hyes-y/algorithm","sub_path":"goorm/week05/03_수이어붙이기.py","file_name":"03_수이어붙이기.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"43090325136","text":"from typing import Optional, Tuple, Union\n\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nfrom models import tf_layers as layers\n\nImageNetBlockType = Tuple[int, int, int, int]\nCifarBlockType = Tuple[int, int, int]\nTensorType = Union[tf.Tensor, np.ndarray, tf.placeholder]\n\n\n# This function is taken from the original tf repo.\n# It ensures that all layers have a channel number that is divisible by 8\n# It can be seen here:\n# https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py\n\n\ndef _make_divisible(v, divisor, min_value=None):\n if min_value is None:\n min_value = divisor\n new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)\n # Make sure that round down does not go down by more than 10%.\n if new_v < 0.9 * v:\n new_v += divisor\n return new_v\n\n\nclass MobileNetV2(object):\n \"\"\"Base class for MobileNetV2 architecture.\"\"\"\n\n def __init__(self, num_classes: int, image_width: int, image_height: int,\n image_channels: Optional[int] = 3, weights: Optional[str] = 'imagenet',\n alpha: Optional[int] = 1.0) -> None:\n\n \"\"\"Initialize mobilenet model.\n\n Args:\n num_classes: Number of target classes.\n image_width: Input image width.\n image_height: Input image height.\n image_channels: Input image number of channels.\n weights: Inizialize with imagenet weights.\n alpha: controls network width\n \"\"\"\n self.alpha = alpha\n self.num_classes = num_classes\n # Network is setup for NHWC\n self.input_shape = [image_height, image_width, image_channels]\n self.weights = weights\n\n def build_model(self, img_input: TensorType) -> TensorType:\n \"\"\"Build graph using img_input as input.\n\n Args:\n img_input: 4D Image input tensor of shape (batch, height, width, channels)\n\n Returns:\n `Tensor` holding output probabilities per class, shape (batch, num_classes)\n \"\"\"\n filters = _make_divisible(32 * self.alpha, 8)\n\n # Conv 1 block\n x = layers.zero_padding(img_input, padding=((0, 1), (0, 1)), name='Conv1_pad')\n x = layers.conv(x, filters_out=filters, kernel_size=3, padding='valid', add_bias=False, stride=2, name='Conv1')\n x = layers.norm(x, axis=-1, epsilon=1e-3, momentum=0.999, name='bn_Conv1')\n x = layers.relu(x, name='Conv1_relu', max_value=tf.constant(6, tf.float16))\n\n # Depthwise separable convolutions\n x = self._inverted_res_block(x, filters=16, alpha=self.alpha, stride=1,\n expansion=1, block_id=0)\n\n x = self._inverted_res_block(x, filters=24, alpha=self.alpha, stride=2,\n expansion=6, block_id=1)\n x = self._inverted_res_block(x, filters=24, alpha=self.alpha, stride=1,\n expansion=6, block_id=2)\n\n x = self._inverted_res_block(x, filters=32, alpha=self.alpha, stride=2,\n expansion=6, block_id=3)\n x = self._inverted_res_block(x, filters=32, alpha=self.alpha, stride=1,\n expansion=6, block_id=4)\n x = self._inverted_res_block(x, filters=32, alpha=self.alpha, stride=1,\n expansion=6, block_id=5)\n\n x = self._inverted_res_block(x, filters=64, alpha=self.alpha, stride=2,\n expansion=6, block_id=6)\n x = self._inverted_res_block(x, filters=64, alpha=self.alpha, stride=1,\n expansion=6, block_id=7)\n x = self._inverted_res_block(x, filters=64, alpha=self.alpha, stride=1,\n expansion=6, block_id=8)\n x = self._inverted_res_block(x, filters=64, alpha=self.alpha, stride=1,\n expansion=6, block_id=9)\n\n x = self._inverted_res_block(x, filters=96, alpha=self.alpha, stride=1,\n expansion=6, block_id=10)\n x = self._inverted_res_block(x, filters=96, alpha=self.alpha, stride=1,\n expansion=6, block_id=11)\n x = self._inverted_res_block(x, filters=96, alpha=self.alpha, stride=1,\n expansion=6, block_id=12)\n\n x = self._inverted_res_block(x, filters=160, alpha=self.alpha, stride=2,\n expansion=6, block_id=13)\n x = self._inverted_res_block(x, filters=160, alpha=self.alpha, stride=1,\n expansion=6, block_id=14)\n x = self._inverted_res_block(x, filters=160, alpha=self.alpha, stride=1,\n expansion=6, block_id=15)\n\n x = self._inverted_res_block(x, filters=320, alpha=self.alpha, stride=1,\n expansion=6, block_id=16)\n\n # no alpha applied to last conv as stated in the paper:\n # if the width multiplier is greater than 1 we\n # increase the number of output channels\n if self.alpha > 1.0:\n last_block_filters = _make_divisible(1280 * self.alpha, 8)\n else:\n last_block_filters = 1280\n\n x = layers.conv(x, filters_out=last_block_filters,\n kernel_size=1,\n add_bias=False,\n name='Conv_1')\n x = layers.norm(x, epsilon=1e-3,\n momentum=0.999,\n name='Conv_1_bn')\n x = layers.relu(x, max_value=tf.constant(6, tf.float16), name='out_relu')\n\n # Include top\n x = layers.global_avg_pool(x)\n x = layers.fully_connected(x, self.num_classes, name='Logits')\n x = layers.softmax(x, name='act_softmax')\n return x\n\n def __call__(self, img_input: TensorType) -> TensorType:\n \"\"\"Build graph using img_input as input.\"\"\"\n return self.build_model(img_input)\n\n @staticmethod\n def _inverted_res_block(inputs, expansion, stride, alpha, filters, block_id):\n in_channels = inputs.get_shape()[-1]\n pointwise_conv_filters = int(filters * alpha)\n pointwise_filters = _make_divisible(pointwise_conv_filters, 8)\n x = inputs\n prefix = 'block_{}_'.format(block_id)\n\n if block_id:\n # Expand\n x = layers.conv(x, filters_out=expansion * in_channels,\n kernel_size=1,\n padding='same',\n add_bias=False,\n name=prefix + 'expand')\n x = layers.norm(x, epsilon=1e-3,\n momentum=0.999,\n name=prefix + 'expand_BN')\n x = layers.relu(x, max_value=tf.constant(6, tf.float16), name=prefix + 'expand_relu')\n else:\n prefix = 'expanded_conv_'\n\n # Depthwise\n if stride == 2:\n x = layers.zero_padding(x, padding=((0, 1), (0, 1)),\n name=prefix + 'pad')\n x = layers.depthwise_conv(x, kernel_size=3,\n stride=stride,\n add_bias=False,\n padding='same' if stride == 1 else 'valid',\n name=prefix + 'depthwise')\n x = layers.norm(x, epsilon=1e-3,\n momentum=0.999,\n name=prefix + 'depthwise_BN')\n\n x = layers.relu(x, max_value=tf.constant(6, tf.float16), name=prefix + 'depthwise_relu')\n\n # Project\n x = layers.conv(x, filters_out=pointwise_filters,\n kernel_size=1,\n padding='same',\n add_bias=False,\n name=prefix + 'project')\n x = layers.norm(x,\n epsilon=1e-3, momentum=0.999, name=prefix + 'project_BN')\n\n if in_channels == pointwise_filters and stride == 1:\n return x + inputs\n return x\n","repo_name":"TrellixVulnTeam/examples_HB8S","sub_path":"applications/tensorflow/cnns/inference/models/official_keras/mobilenetv2_base.py","file_name":"mobilenetv2_base.py","file_ext":"py","file_size_in_byte":8131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"71802669833","text":"import itertools\nimport random\nimport math\nfrom abc import ABC, abstractmethod\nimport sympy.ntheory as sym\nimport tensorflow as tf\nfrom keras.engine.keras_tensor import KerasTensor\nfrom networkx import DiGraph\n\n# valid_node_types = [\"Conv2D\", \"Dense\", \"Flatten\", \"MaxPooling2D\", \"ReLU\", \"BatchNormalization\"]\nvalid_node_types = [\"Dense\", \"ReLU\", \"BatchNormalization\", \"MaxPooling2D\", \"Conv2D\"]\ndense_max_power_two = 10\nmax_conv2d_power = 8\nconv2d_kernel_sizes = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]\nmax_pooling_size = [(2, 2), (3, 3)]\n\n\nclass TensorNode(ABC):\n id_iter = itertools.count()\n\n def __init__(self):\n self.id = next(TensorNode.id_iter)\n self.label = self.get_label()\n self.is_branch_root = False\n self.saved_layers = None\n self.can_mutate = False\n self.input_shape = [] # TensorShape (batch, rows, columns, channels)\n self.output_shape = None\n\n def __eq__(self, other):\n return self.id == other.id\n\n def __call__(self, all_nodes: dict, graph: DiGraph) -> KerasTensor:\n if self.saved_layers is not None:\n return self.saved_layers\n else:\n self.reset()\n layers_so_far = self._call_parents(all_nodes, graph)\n\n for parent in self.get_parents(all_nodes, graph):\n self.input_shape.append(parent.output_shape)\n\n layers_so_far = self.fix_input(layers_so_far)\n layers_so_far = self._build(layers_so_far)\n self.output_shape = layers_so_far.shape\n\n if self.is_branch_root:\n self.saved_layers = layers_so_far\n\n return layers_so_far\n\n def get_parents(self, all_nodes: dict, graph: DiGraph) -> list:\n parents_ids = graph.predecessors(self.id)\n parents = []\n for p_id in parents_ids:\n parents.append(all_nodes[p_id])\n return parents\n\n # def get_children(self):\n # return self.graph.successors(self.id)\n\n def reset(self):\n self.input_shape = []\n self.output_shape = None\n self.saved_layers = None\n\n @abstractmethod\n def _build(self, layers_so_far) -> KerasTensor:\n raise NotImplementedError\n\n def _call_parents(self, all_nodes: dict, graph: DiGraph) -> KerasTensor:\n parents = self.get_parents(all_nodes, graph)\n if len(parents) > 0:\n return (parents[0])(all_nodes, graph)\n else:\n return None\n\n def mutate(self):\n pass\n\n def fix_input(self, layers_so_far):\n return layers_so_far\n\n @staticmethod\n @abstractmethod\n def create_random():\n raise NotImplementedError\n\n def get_label(self) -> str:\n label = str(type(self)).split('.')[-1]\n label = label.split('\\'')[0]\n return label\n\n\nclass InputNode(TensorNode):\n def __init__(self, input_shape: tuple):\n super().__init__()\n self.input_shape.append(input_shape)\n self.is_branch_root = True\n\n def _build(self, layers_so_far):\n return tf.keras.Input(shape=self.input_shape[0])\n\n def reset(self):\n self.output_shape = None\n self.saved_layers = None\n\n @staticmethod\n def create_random():\n raise NotImplementedError(\"Input Node can't be created randomly\")\n\n\nclass FlattenNode(TensorNode):\n def _build(self, layers_so_far: KerasTensor):\n return tf.keras.layers.Flatten()(layers_so_far)\n\n @staticmethod\n def create_random():\n return FlattenNode()\n\n\nclass AdditionNode(TensorNode):\n\n def _call_parents(self, all_nodes: dict, graph: DiGraph) -> tuple:\n parents = self.get_parents(all_nodes, graph)\n return parents[0](all_nodes, graph), parents[1](all_nodes, graph)\n\n def _build(self, layers_so_far: tuple) -> KerasTensor:\n main_branch, adder_branch = layers_so_far\n return tf.keras.layers.add([main_branch, adder_branch])\n\n @staticmethod\n def create_random():\n return AdditionNode()\n\n def fix_input(self, layers_so_far: tuple) -> tuple:\n main_branch, adder_branch = layers_so_far\n main_shape = (self.input_shape[0])\n adder_shape = (self.input_shape[1])\n\n if main_shape[1:] != adder_shape[1:]:\n adder_branch = tf.keras.layers.Flatten()(adder_branch)\n if main_shape.rank == 2: # dense shape\n units = main_shape[1] # main_shape[0] will be None\n adder_branch = tf.keras.layers.Dense(units)(adder_branch)\n elif main_shape.rank == 4: # Conv2D shape\n units = main_shape[3] # num of filters\n adder_branch = tf.keras.layers.Dense(units)(adder_branch)\n ones = tf.ones(main_shape[1:])\n tf.expand_dims(ones, 0)\n adder_branch = tf.keras.layers.multiply([ones, adder_branch])\n else:\n main_branch = tf.keras.layers.Flatten()(main_branch)\n main_shape = main_branch.shape\n units = main_shape[1]\n adder_branch = tf.keras.layers.Dense(units)(adder_branch)\n\n return main_branch, adder_branch\n\n\nclass DenseNode(TensorNode):\n def __init__(self, num_units: int, activation='relu'):\n super().__init__()\n self.num_units = num_units\n self.activation = activation\n self.can_mutate = True\n\n def _build(self, layers_so_far: KerasTensor) -> KerasTensor:\n return tf.keras.layers.Dense(self.num_units,\n activation=self.activation)(layers_so_far)\n\n @staticmethod\n def create_random():\n random_power = random.randint(0, dense_max_power_two)\n units = 2 ** random_power\n return DenseNode(units)\n\n def mutate(self):\n random_power = random.randint(0, dense_max_power_two)\n units = 2 ** random_power\n self.num_units = units\n\n\nclass Conv2dNode(TensorNode):\n def __init__(self, filters, kernel_size, padding='same'):\n super().__init__()\n self.filters = filters\n self.kernel_size = kernel_size\n self.activation = 'relu'\n self.padding = padding\n self.can_mutate = True\n\n def _build(self, layers_so_far: KerasTensor) -> KerasTensor:\n print(\"Shape (build): \" + str(layers_so_far.shape))\n return tf.keras.layers.Conv2D(self.filters, self.kernel_size,\n activation=self.activation,\n padding=self.padding)(layers_so_far)\n\n @staticmethod\n def create_random():\n random_power = random.randint(0, max_conv2d_power)\n filters = 2 ** random_power\n kernel_size = random.choice(conv2d_kernel_sizes)\n return Conv2dNode(filters, kernel_size)\n\n def mutate(self):\n random_power = random.randint(0, max_conv2d_power)\n filters = 2 ** random_power\n kernel_size = random.choice(conv2d_kernel_sizes)\n\n self.filters = filters\n self.kernel_size = kernel_size\n\n def fix_input(self, layers_so_far: KerasTensor) -> KerasTensor:\n return reshape_1D_to_2D(layers_so_far)\n\n\nclass ReluNode(TensorNode):\n def _build(self, layers_so_far: KerasTensor) -> KerasTensor:\n return tf.keras.layers.ReLU()(layers_so_far)\n\n @staticmethod\n def create_random():\n return ReluNode()\n\n\nclass BatchNormNode(TensorNode):\n def _build(self, layers_so_far: KerasTensor) -> KerasTensor:\n return tf.keras.layers.BatchNormalization()(layers_so_far)\n\n @staticmethod\n def create_random():\n return BatchNormNode()\n\n\nclass OutputNode(TensorNode):\n def __init__(self, num_outputs):\n super().__init__()\n self.num_outputs = num_outputs\n\n def _build(self, layers_so_far) -> KerasTensor:\n layers_so_far = tf.keras.layers.Flatten()(layers_so_far)\n layers_so_far = tf.keras.layers.Dense(self.num_outputs, activation=None)(layers_so_far)\n return layers_so_far\n\n @staticmethod\n def create_random():\n raise NotImplementedError(\"Output Node can't be created randomly\")\n\n\nclass MaxPool2DNode(TensorNode):\n def __init__(self, pool_size=(2, 2), padding=\"valid\"):\n super().__init__()\n self.pool_size = pool_size\n self.padding = padding\n self.can_mutate = True\n\n def _build(self, layers_so_far: KerasTensor) -> KerasTensor:\n print(\"Shape (build): \" + str(layers_so_far.shape))\n return tf.keras.layers.MaxPooling2D(self.pool_size,\n padding=self.padding)(layers_so_far)\n\n @staticmethod\n def create_random():\n pool_size = random.choice(max_pooling_size)\n return MaxPool2DNode(pool_size=pool_size)\n\n def mutate(self):\n pool_size = random.choice(max_pooling_size)\n self.pool_size = pool_size\n\n def fix_input(self, layers_so_far: KerasTensor) -> KerasTensor:\n return reshape_1D_to_2D(layers_so_far)\n\n\ndef create(node_type: str) -> TensorNode:\n if node_type == \"Conv2D\":\n return Conv2dNode.create_random()\n elif node_type == \"Dense\":\n return DenseNode.create_random()\n elif node_type == \"Flatten\":\n return FlattenNode()\n elif node_type == \"MaxPooling2D\":\n return MaxPool2DNode.create_random()\n elif node_type == \"ReLU\":\n return ReluNode.create_random()\n elif node_type == \"add\":\n return AdditionNode.create_random()\n elif node_type == \"BatchNormalization\":\n return BatchNormNode.create_random()\n else:\n raise ValueError(\"Unsupported node type: \" + str(node_type))\n\n\ndef evaluate_square_shapes(n) -> tuple:\n sqrt = int(math.sqrt(n)) - 1\n\n while sqrt >= 5:\n square = sqrt ** 2\n channels = n // square\n\n if (square * channels) == n:\n return sqrt, sqrt, channels\n\n sqrt -= 1\n return None\n\n\ndef is_square_rgb(n):\n if (n % 3) == 0:\n n = n // 3\n return sym.primetest.is_square(n)\n else:\n return False\n\n\ndef shape_from_primes(n) -> tuple:\n prime_dict = sym.factorint(n)\n prime_list = []\n\n for prime, repeat in prime_dict.items():\n for rep in range(repeat):\n prime_list.append(prime)\n\n if len(prime_list) == 2:\n return prime_list[0], prime_list[1], 1\n\n while len(prime_list) > 3:\n prime_list.sort(reverse=True)\n composite = prime_list[-1] * prime_list[-2]\n prime_list.pop(-1)\n prime_list.pop(-1)\n prime_list.append(composite)\n\n return prime_list[0], prime_list[1], prime_list[2]\n\n\ndef reshape_1D_to_2D(layers_so_far: KerasTensor) -> KerasTensor:\n if layers_so_far.shape.rank != 2:\n raise ValueError(\"reshape_1D_to_2D only accepts KerasTensors of rank 2 (batch_size, dim1)\")\n\n n = layers_so_far.shape[1]\n\n if sym.isprime(n):\n target_shape = (1, 1, n)\n\n elif sym.primetest.is_square(n):\n sqrt = int(math.sqrt(n))\n target_shape = (sqrt, sqrt, 1)\n\n elif is_square_rgb(n):\n n = n / 3\n sqrt = int(math.sqrt(n))\n target_shape = (sqrt, sqrt, 3)\n\n else:\n target_shape = evaluate_square_shapes(n)\n if target_shape is None:\n target_shape = shape_from_primes(n)\n\n return tf.keras.layers.Reshape(target_shape)(layers_so_far)\n","repo_name":"cactusWhiskey/chessEvo","sub_path":"evolution/tensor_node.py","file_name":"tensor_node.py","file_ext":"py","file_size_in_byte":11212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"21052370931","text":"# -*- coding: utf-8 -*-\n\n#实验效果:控制I2C RGB彩色LCD1602液晶屏幕\n#接线:使用windows或linux电脑连接一块arduino主控板,LCD1602接到I2C口SCL SDA\nimport sys\nimport time\nfrom pinpong.board import Board\nfrom pinpong.libs.dfrobot_rgb1602 import RGB1602 #从libs导入rgb1602库\n\nBoard(\"xugu\").begin()\n\nlcd = RGB1602()\n\nprint(\"I2C RGB1602 TEST...\")\n\nlcd.set_rgb(0,50,0); #设置RGB值\n\nlcd.print(\"PinPong\") #显示 \"PinPong\"\n\nlcd.set_cursor(1,1) #设置光标位置\nlcd.print(1234) #显示数字\n\nwhile True:\n time.sleep(1)\n lcd.scroll_left() #滚动显示\n","repo_name":"milkv-duo/duo-buildroot-sdk","sub_path":"buildroot-2021.05/package/python-pinpong/pinpong/examples/xugu/3-03-rgb1602.py","file_name":"3-03-rgb1602.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"zh","doc_type":"code","stars":174,"dataset":"github-code","pt":"27"} +{"seq_id":"31014412024","text":"import re\nimport requests\n\nwith open('a4.txt','r')as f:\n content = f.read()\n\n\n# <title data-vue-meta=\"true\">【凌】触摸天空☁_哔哩哔哩 (゜-゜)つロ 干杯~-bilibili\ng = re.search(r'(.*?)', content)\n\n# \"baseUrl\":\"http://upos-hz-mirrorcosu.acgvideo.com/upgcxcode/21/56/99945621/99945621-1-30015.m4s?\ng2 = re.search(r'\"(?:base)?[U,u]rl\".*?/(\\d*?)-',content)\n\n# print(g.groups()[0])\nprint(g2.groups()[0])","repo_name":"OliverChao/bili-dl","sub_path":"TestFile/Extract/get_single_by_re.py","file_name":"get_single_by_re.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"36148371252","text":"# sum contact maps in each cluster to get overall frequency matrix and plot imshow and bar graph\n\nimport os\nimport pickle\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import zscore\nimport matplotlib.pyplot as plt\nimport cluster_contact_maps\nfrom cluster_contact_maps import ClusterContactMaps\nfrom generate_contact_map_list_object import ContactMap\n\n\ndef load_pickle_object(pickle_fpath):\n \"\"\"\n opens the pickled object!\n Caution: You have to import the class(es) into current python script in order to load the object\n First import the python script: import python_script\n then import the class: from python_script import class(es)\n :param pickle_file_path: pickle object path\n :return: object\n \"\"\"\n with open(pickle_fpath, 'rb') as pk_file:\n obj = pickle.load(pk_file)\n return obj\n\ndef plot_imshow(array, seq_xaxis, seq_yaxis, fname, dirpath):\n # plt.figure(figsize=(8,10))\n plt.imshow(array, origin='lower')\n plt.xticks(np.arange(0, len([x for x in seq_xaxis])), seq_xaxis)\n plt.yticks(np.arange(0, len([x for x in seq_yaxis]), 2), seq_yaxis)\n plt.colorbar()\n plt.savefig(os.path.join(dirpath, fname))\n plt.close()\n\ndef plot_bar_graph(array, seq, fname, dirpath, color='red'):\n ind = np.arange(1, len(array)+1)\n plt.bar(ind, array, width=1, color=color)\n plt.xticks(ind, seq)\n plt.savefig(os.path.join(dirpath, fname))\n plt.close()\n\n\ndef write_zscore_output(resseq, zscore_arr, fname, dirpath):\n outlines = ''\n header = '{},{},{}\\n'.format('residue_num', 'residue', 'zscore')\n outlines += header\n for ind, (resid, zscore) in enumerate(zip(resseq, zscore_arr)):\n line = '{},{},{}\\n'.format(ind+1, resid, zscore)\n outlines += line\n\n with open(os.path.join(dirpath, fname), 'w') as zscore_out:\n zscore_out.write(outlines)\n zscore_out.close()\n\n print('test')\n\n\ndef write_zscore_for_pairs(z_score_pairs, ind_1, ind_2, res_sq_1, res_sq_2, outid, dirpath):\n\n output_string = ''\n header = 'res1_num,res2_num,res1_,res2_,zscore\\n'\n output_string += header\n\n for ind, (res1num, res2num, zscore_) in enumerate(zip(ind_1, ind_2, z_score_pairs)):\n\n res1_ = res_sq_1[res1num]\n res2_ = res_sq_2[res2num]\n\n line = '{},{},{},{},{}\\n'.format(res1num, res2num, res1_, res2_, zscore_)\n\n output_string += line\n\n\n out_name = 'pair_zscore_'+ outid + '.csv'\n with open(os.path.join(dirpath, out_name), 'w') as outfile:\n outfile.write(output_string)\n outfile.close()\n\ndef construct_grid(wh, wv, data):\n wv_unique = np.unique(wv)\n wh_unique = np.unique(wh)\n data_grid = np.zeros(shape=(len(wv_unique), len(wh_unique)))\n ind_new = 0\n for ind, (wv_, wh_) in enumerate(zip(wv, wh)):\n for i, wv_un in enumerate(wv_unique):\n for j, wh_un in enumerate(wh_unique):\n if wv_un == wv_:\n if wh_un == wh_:\n data_grid[i, j] = data[ind_new]\n ind_new += 1\n\n data_grid[data_grid == 0] = 'nan'\n return data_grid\n\ndef plot_zscore_imhow(zscoremat, cmap, distcutoff, xaxis, yaxis, dirpath):\n y_ticks = np.arange(0, len(yaxis), 2)\n y_tick_labels = []\n for ind in y_ticks:\n y_tick_labels.append(yaxis[ind])\n plt.imshow(zscoremat, origin=('lower', 'lower'), aspect='auto', cmap=cmap)\n plt.xticks(np.arange(0, len(xaxis), 1), xaxis)\n plt.yticks(y_ticks, y_tick_labels)\n plt.colorbar()\n plt.savefig(os.path.join(dirpath, 'pair_zscore_imshow_dist_cut_off_'+str(distcutoff)+'.pdf'))\n plt.close()\n\n\ndef z_score_for_pairs(sum_ct, resseq1, resseq2, dirpath, outid, image_type):\n\n ind_1 = []\n ind_2 = []\n sum_ct_arr = []\n for ind1 in range(len(sum_ct[0,:])):\n for ind2 in range(len(sum_ct[:, 0])):\n ind_1.append(ind1)\n ind_2.append(ind2)\n sum_ct_val = sum_ct[ind2, ind1]\n sum_ct_arr.append(sum_ct_val)\n\n sum_ct_arr = np.array(sum_ct_arr)\n z_score_pairs = zscore(sum_ct_arr)\n sort_ind = np.argsort(z_score_pairs)\n z_score_pair_sort = z_score_pairs[sort_ind[::-1]]\n ind_1_sort = np.array(ind_1)[sort_ind[::-1]]\n ind_2_sort = np.array(ind_2)[sort_ind[::-1]]\n\n write_zscore_for_pairs(z_score_pair_sort, ind_1_sort, ind_2_sort, resseq1, resseq2, outid, dirpath)\n\n z_score_sq_mat = construct_grid(ind_1_sort, ind_2_sort, z_score_pair_sort)\n\n z_score_mat_masked = np.ma.masked_where(z_score_sq_mat <= 2, z_score_sq_mat)\n # mask_array = np.ma.array(z_score_mat, mask=np.where(z_score_mat <=2))\n cmap = plt.cm.get_cmap('PuBu')\n cmap.set_bad(color='white')\n\n plot_zscore_imhow(z_score_mat_masked, cmap, distcutoff=outid, xaxis=resseq1, yaxis=resseq2, dirpath=dirpath)\n\n # z_score_sq_mat = z_score_pairs.reshape(len(sum_ct[0,:]), len(sum_ct[:,0]))\n\n # plot_imshow(z_score_sq_mat, resseq1, resseq2, 'pair_zscore_imshow_'+outid + image_type, dirpath)\n\n return z_score_sq_mat\n\n\n\n\n\n print('heho')\n\n\n\n\ndef total_contacts_for_cluster(contact_map_obj, resseq1, resseq2, dirpath, outid, image_type='.png'):\n \"\"\"\n\n :param contact_map_obj:\n :param resseq1:\n :param resseq2:\n :param dirpath:\n :param image_type:\n :return:\n \"\"\"\n\n sum_ct = np.sum(contact_map_obj.contact_mat, axis=0)\n\n z_score_for_pairs(sum_ct, resseq1, resseq2, dirpath, outid, image_type)\n\n plot_imshow(sum_ct, resseq1, resseq2, 'total_contacts_cluster_'+outid+image_type, dirpath)\n\n ct_dataframe = pd.DataFrame(sum_ct)\n ct_dataframe.to_csv(os.path.join(dirpath, 'total_contacts_cluster_' + outid + '.csv'))\n\n mol1_freq = np.sum(sum_ct, axis=0)\n mol2_freq = np.sum(sum_ct, axis=1)\n\n # plot_bar_graph(mol1_freq, resseq1, 'mol1_total_contacts_cluster_' + outid + image_type, dirpath, color='blue')\n # plot_bar_graph(mol2_freq, resseq2, 'mol2_total_contacts_cluster_' + outid + image_type, dirpath, color='red')\n\n mol1_zscore = zscore(mol1_freq)\n mol2_zscore = zscore(mol2_freq)\n\n write_zscore_output(resseq1, mol1_zscore, 'mol1_zscore_cluster_' + outid + '.csv', dirpath)\n write_zscore_output(resseq2, mol2_zscore, 'mol2_zscore_cluster_' + outid + '.csv', dirpath)\n\n # plot_bar_graph(mol1_zscore, resseq1, 'mol1_total_contacts_zscore_cluster_' + outid + image_type, dirpath,\n # color='blue')\n # plot_bar_graph(mol2_zscore, resseq2, 'mol2_total_contacts_zscore_cluster_' + outid + image_type, dirpath,\n # color='red')\n\n\n\n\ndef total_contacts_for_cluster_using_combined_cluster_ct_object(cluster_ct_object, resseq1, resseq2, dirpath, image_type='.png'):\n\n\n for index, cluster_ct in enumerate(cluster_ct_object.cluster_contact_maps):\n\n sum_ct = np.sum(cluster_ct, axis=0)\n\n plot_imshow(sum_ct, resseq1, resseq2, 'total_contacts_cluster_'+str(index)+image_type, dirpath)\n\n z_score_for_pairs(sum_ct, resseq1, resseq2, dirpath, outid='clust_'+str(index), image_type=image_type)\n\n ct_dataframe = pd.DataFrame(sum_ct)\n ct_dataframe.to_csv(os.path.join(dirpath, 'total_contacts_cluster_' + str(index) + '.csv'))\n\n mol1_freq = np.sum(sum_ct, axis=0)\n mol2_freq = np.sum(sum_ct, axis=1)\n\n plot_bar_graph(mol1_freq, resseq1, 'mol1_total_contacts_cluster_'+str(index)+image_type, dirpath, color='blue')\n plot_bar_graph(mol2_freq, resseq2, 'mol2_total_contacts_cluster_' + str(index) + image_type, dirpath, color='red')\n\n mol1_zscore = zscore(mol1_freq)\n mol2_zscore = zscore(mol2_freq)\n\n write_zscore_output(resseq1, mol1_zscore, 'mol1_zscore_cluster_'+str(index)+'.csv', dirpath)\n write_zscore_output(resseq2, mol2_zscore, 'mol2_zscore_cluster_' + str(index) + '.csv', dirpath)\n\n plot_bar_graph(mol1_zscore, resseq1, 'mol1_total_contacts_zscore_cluster_' + str(index) + image_type, dirpath, color='blue')\n plot_bar_graph(mol2_zscore, resseq2, 'mol2_total_contacts_zscore_cluster_' + str(index) + image_type, dirpath, color='red')\n\n\n\nif __name__=='__main__':\n ## for serf ab interaction analysis\n dirpath = r\"C:\\Users\\sugyan\\Documents\\MembraneMDfiles\\serf_ab_models\\cluster_5\"\n cluster_ct_obj_fname = \"cluster_contact_mat_5.obj\"\n mol1_res = 'DAEFRHDSGYEVHHQKLVFFAEDVGSNKGAIIGLMVGGVV'\n mol2_res = 'MARGNQRDLARQKNLKKQKDMAKNQKKSGDPKKRMESDAEILRQKQAAADARREAEKLEK'\n cluster_ct_obj = load_pickle_object(os.path.join(dirpath, cluster_ct_obj_fname))\n total_contacts_for_cluster_using_combined_cluster_ct_object(cluster_ct_obj, mol1_res, mol2_res, dirpath)\n\n #for single cluster object analysis\n # dirpath = r\"C:\\Users\\sugyan\\Documents\\MembraneMDfiles\\Serf_tmp_model\\Replica_Exchange_Analysis_mod\\rmsd_mat\\cluster_manual_7\"\n # cluster_ct_obj_fname = \"contact_mat_clust_7_[5, 10].obj\"\n # mol1_res = 'MARGNQRDLARQKNLKKQKDMAKNQKKSGDPKKRMESDAEILRQKQAAADARREAEKLEKLKAEKTRR'\n # mol2_res = mol1_res\n # clust_ct_obj = load_pickle_object(os.path.join(dirpath, cluster_ct_obj_fname))\n # total_contacts_for_cluster(clust_ct_obj, mol1_res, mol2_res, dirpath, outid='cluster_man_7_[5, 10]', image_type='.pdf')\n\n\n","repo_name":"sugyandixit/MISC_Modeling_Analysis","sub_path":"cluster_ct_map_sum_report.py","file_name":"cluster_ct_map_sum_report.py","file_ext":"py","file_size_in_byte":9104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"2093587365","text":"\n\n# Helper file for preconfig generator\n\ndef extra_info(orch, nepk, hostname):\n yaml_text = \"\" \n# info = orch.get(\"/appliance/extraInfo/\" + nepk).json()\n info = orch.get(\"/appliance/extraInfo/\" + nepk + \"?source=context_menu_id\").json() \n yaml_text += \"applianceInfo: \\n\"\n yaml_text += \" hostname: \" + hostname + \"\\n\"\n yaml_text += \" location:\\n\"\n yaml_text += \" address: \" + info['location']['address'] + \"\\n\"\n yaml_text += \" address2: \" + info['location']['address2'] + \"\\n\"\n yaml_text += \" city: \" + info['location']['city'] + \"\\n\"\n yaml_text += \" state: \" + info['location']['state'] + \"\\n\"\n yaml_text += \" zipCode: \" + info['location']['zipCode'] + \"\\n\"\n yaml_text += \" country: \" + info['location']['country'] + \"\\n\"\n yaml_text += \" contact:\\n\"\n yaml_text += \" name: \" + info['contact']['name'] + \"\\n\"\n yaml_text += \" email: \" + info['contact']['email'] + \"\\n\"\n yaml_text += \" phoneNumber: \" + info['contact']['phoneNumber'] + \"\\n\"\n return yaml_text\n\ndef deployment(orch, nepk, labels, zones):\n yaml_text = \"\"\n dhcp_yaml_text = \"\"\n dhcpInfo = False\n#RBAC may need the ?source=menu_deployment_id\n dep = orch.get(\"/appliance/rest/\" + nepk + \"/deployment?source=menu_deployment_id\").json()\n\n firewallMode = [\"all\", \"harden\", \"stateful\", \"statefulsnat\"]\n yaml_text += \"\\ndeploymentInfo: \\n\"\n yaml_text += \" deploymentMode: inline-router \\n\"\n yaml_text += \" totalOutboundBandwidth: \" + str(dep['sysConfig']['maxBW']) + \"\\n\"\n yaml_text += \" totalInboundBandwidth: \" + str(dep['sysConfig']['maxInBW']) + \"\\n\"\n yaml_text += \" shapeInboundTraffic: \"\n if(dep['sysConfig']['maxInBWEnabled']):\n yaml_text += \"true \\n\"\n else:\n yaml_text += \"false \\n\"\n\n yaml_text += \"\\n deploymentInterfaces: \\n\"\n for ifs in range(len(dep['modeIfs'])):\n for ips in range(len(dep['modeIfs'][ifs]['applianceIPs'])):\n \n ### Add an interface, check if it is tagged\n yaml_text += \"\\n - interfaceName: \" + dep['modeIfs'][ifs]['ifName']\n intName = dep['modeIfs'][ifs]['ifName']\n if(\"vlan\" in dep['modeIfs'][ifs]['applianceIPs'][ips].keys()):\n yaml_text += \".\" + str(dep['modeIfs'][ifs]['applianceIPs'][ips]['vlan']) + \" \\n\"\n intName += \".\" + str(dep['modeIfs'][ifs]['applianceIPs'][ips]['vlan'])\n else:\n yaml_text += \" \\n\"\n \n yaml_text += \" interfaceComment: \" + dep['modeIfs'][ifs]['applianceIPs'][ips]['comment'] + \"\\n\"\n if(dep['modeIfs'][ifs]['applianceIPs'][ips]['zone']):\n yaml_text += \" zone: \" + zones[str(dep['modeIfs'][ifs]['applianceIPs'][ips]['zone'])]['name'] + \"\\n\"\n \n ### Check for dhcp address, else set IP address/mask/nh\n if(dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcp']):\n yaml_text += \" ipAddressMask: \\n\"\n else:\n yaml_text += \" ipAddressMask: \" + dep['modeIfs'][ifs]['applianceIPs'][ips]['ip'] + \"/\" + str(dep['modeIfs'][ifs]['applianceIPs'][ips]['mask']) + \"\\n\"\n if(dep['modeIfs'][ifs]['applianceIPs'][ips]['wanNexthop'] != \"0.0.0.0\"):\n yaml_text += \" nextHop: \" + dep['modeIfs'][ifs]['applianceIPs'][ips]['wanNexthop'] + \"\\n\"\n \n \n ### Check if this is wan/lan, add info accordingly\n if(dep['modeIfs'][ifs]['applianceIPs'][ips]['lanSide']):\n yaml_text += \" interfaceType: lan \\n\"\n if(dep['modeIfs'][ifs]['applianceIPs'][ips]['label']):\n yaml_text += \" interfaceLabel: \" + labels['lan'][dep['modeIfs'][ifs]['applianceIPs'][ips]['label']]['name'] + \"\\n\"\n\n #If lan side, check DHCP settings - this may add too many \"dhcpInfo:\" lines\n if((\"dhcpd\" in dep['modeIfs'][ifs]['applianceIPs'][ips].keys()) and (dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['type'] == \"server\")):\n #if(dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['type'] == \"server\"):\n if(not dhcpInfo):\n dhcp_yaml_text += \" dhcpInfo: \\n\"\n dhcpInfo = True\n dhcp_yaml_text += \" - dhcpInterfaceName: \" + intName + \"\\n\"\n dhcp_yaml_text += \" dhcpType: server \\n\"\n dhcp_yaml_text += \" dhcpAddressMask: \" + dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['server']['prefix'] + \"\\n\"\n dhcp_yaml_text += \" startIpAddress: \" + dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['server']['ipStart'] + \"\\n\"\n dhcp_yaml_text += \" endIpAddress: \" + dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['server']['ipEnd'] + \"\\n\"\n try:\n dhcp_yaml_text += \" gatewayIpAddress: \" + dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['server']['gw'][0] + \"\\n\"\n except IndexError:\n print(\"There is no gateway for this DHCP Scope.\")\n if(len(dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['server']['dns'])):\n dhcp_yaml_text += \" dnsServers: \\n\"\n for i in range(len(dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['server']['dns'])):\n dhcp_yaml_text += \" - \" + dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['server']['dns'][i] + \"\\n\"\n if(len(dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['server']['ntpd'])):\n dhcp_yaml_text += \" ntpServers: \\n\"\n for i in range(len(dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['server']['ntpd'])):\n dhcp_yaml_text += \" - \" + dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['server']['ntpd'][i] + \"\\n\"\n # dhcp_yaml_text += \" netbiosNameServers: \\n\"\n # for(i in range(len(dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['ntpd']):\n # dhcp_yaml_text += \" - 192.168.0.0\n # dhcp_yaml_text += \" netbiosNodeType: B\n # dhcp_yaml_text += \" maximumLease: 24\n # dhcp_yaml_text += \" defaultLease: 24\n # dhcp_yaml_text += \" options:\n # dhcp_yaml_text += \" - option: 1\n # dhcp_yaml_text += \" value: 255.255.255.0\n # dhcp_yaml_text += \" staticIpAssignments:\n # dhcp_yaml_text += \" - hostname: google\n # dhcp_yaml_text += \" macAddress: 00:25:96:FF:FE:12\n # dhcp_yaml_text += \" ipAddress: 198.168.0.7\n\n\n elif((\"dhcpd\" in dep['modeIfs'][ifs]['applianceIPs'][ips].keys()) and (dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['type'] == \"relay\")):\n if(not dhcpInfo):\n dhcp_yaml_text += \" dhcpInfo: \\n\"\n dhcpInfo = True\n dhcp_yaml_text += \" - dhcpInterfaceName: \" + intName + \"\\n\"\n dhcp_yaml_text += \" dhcpType: relay \\n\"\n dhcp_yaml_text += \" dhcpProxyServers: \\n\"\n for i in range(len(dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['relay']['dhcpserver'])):\n dhcp_yaml_text += \" - \" + dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['relay']['dhcpserver'][i] + \"\\n\"\n if(dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['relay']['option82']):\n dhcp_yaml_text += \" enableOptions82: \" + str(dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['relay']['option82']) + \"\\n\"\n dhcp_yaml_text += \" options82Policy: \" + dep['modeIfs'][ifs]['applianceIPs'][ips]['dhcpd']['relay']['option82_policy'] + \"\\n\"\n\n else:\n if(dep['modeIfs'][ifs]['applianceIPs'][ips]['label']):\n yaml_text += \" interfaceLabel: \" + labels['wan'][dep['modeIfs'][ifs]['applianceIPs'][ips]['label']]['name'] + \"\\n\"\n yaml_text += \" interfaceType: wan \\n\"\n yaml_text += \" outboundMaxBandwidth: \" + str(dep['modeIfs'][ifs]['applianceIPs'][ips]['maxBW']['outbound']) + \"\\n\"\n yaml_text += \" inboundMaxBandwidth: \" + str(dep['modeIfs'][ifs]['applianceIPs'][ips]['maxBW']['outbound']) + \"\\n\"\n yaml_text += \" firewallMode: \" + firewallMode[dep['modeIfs'][ifs]['applianceIPs'][ips]['harden']] + \"\\n\"\n yaml_text += \" behindNat: \" + dep['modeIfs'][ifs]['applianceIPs'][ips]['behindNAT'] + \"\\n\"\n\n\n return yaml_text, dhcp_yaml_text\n\ndef routes(orch, nepk):\n yaml_text = \"\" \n sys = orch.get(\"/appliance/rest/\" + nepk + \"/system\").json()\n yaml_text += \"\\nlocalRoutes: \\n\" \n yaml_text += \" useSharedSubnetInfo: \" + str(sys['auto_subnet']['self']).lower() + \"\\n\"\n yaml_text += \" advertiseLocalLanSubnets: \" + str(sys['auto_subnet']['add_local_lan']).lower() + \"\\n\"\n yaml_text += \" advertiseLocalWanSubnets: \" + str(sys['auto_subnet']['add_local_wan']).lower() + \"\\n\"\n yaml_text += \" localMetric: \" + str(sys['auto_subnet']['add_local_metric']) + \"\\n\"\n yaml_text += \" localCommunities: \\n\"\n\n try:\n sub3 = orch.get(\"/appliance/rest/\" + nepk + \"/subnets3/configured\").json()\n if(\"prefix\" in sub3.keys()):\n yaml_text += \"\\n routes: \\n\"\n for i in sub3['prefix']:\n #Is there a better way to do the nhop manipulation? probably\n nhop = str(list(sub3['prefix'][i]['nhop']))[2:-2]\n int = str(list(sub3['prefix'][i]['nhop'][nhop]['interface']))[2:-2]\n \n yaml_text += \" - routeIpSubnet: \" + i + \"\\n\"\n yaml_text += \" nextHop: \" + nhop + \"\\n\"\n # yaml_text += \" interfaceName: \" + int + \"\\n\"\n yaml_text += \" metric: \" + str(sub3['prefix'][i]['nhop'][nhop]['interface'][int]['metric']) + \"\\n\"\n yaml_text += \" advertise: \" + str(sub3['prefix'][i]['advert']).lower() + \"\\n\"\n yaml_text += \" advertiseToBgp: \" + str(sub3['prefix'][i]['advert_bgp']).lower() + \"\\n\"\n yaml_text += \" advertiseToOspf: \" + str(sub3['prefix'][i]['advert_ospf']).lower() + \"\\n\"\n yaml_text += \" tag: \" + str(sub3['prefix'][i]['nhop'][nhop]['interface'][int]['dir']) + \"\\n\"\n yaml_text += \" comment: \" + str(sub3['prefix'][i]['nhop'][nhop]['interface'][int]['comment']) + \"\\n\"\n except:\n print(\"Uhoh\")\n\n return yaml_text\n\ndef loopback(orch, nepk, labels, zones):\n yaml_text = \"\"\n loopback = orch.get(\"/appliance/rest/\" + nepk + \"/virtualif/loopback?source=menu_deployment_id\").json()\n user_def_loopback = False\n loop_text = \"\"\n if(loopback):\n for int in loopback:\n if(not loopback[int]['gms_marked']):\n user_def_loopback = True\n loop_text += \" - interfaceId: \" + int + \"\\n\"\n loop_text += \" adminStatus: \"\n if(loopback[int]['admin']):\n loop_text += \"Up\\n\"\n else:\n loop_text += \"Down\\n\"\n loop_text += \" ipAddressMask: \" + loopback[int]['ipaddr'] + \"/\" + str(loopback[int]['nmask']) + \"\\n\"\n if(loopback[int]['zone']):\n loop_text += \" zone: \" + zones[str(loopback[int]['zone'])]['name'] + \"\\n\"\n loop_int = loopback[int]['label']\n if(loop_int):\n loop_text += \" interfaceLabel: \" + labels['lan'][loop_int]['name'] + \"\\n\\n\"\n\n if(user_def_loopback):\n yaml_text += \"\\nloopbackInterface:\\n\"\n yaml_text += \" loopbacks:\\n\"\n yaml_text += loop_text\n\n return yaml_text\n\n\ndef bgp(orch, nepk):\n yaml_text = \"\"\n bgp = orch.get(\"/appliance/rest/\" + nepk + \"/bgp/config/system?source=menu_deployment_id\").json()\n bgp_neigh = orch.get(\"/appliance/rest/\" + nepk + \"/bgp/config/neighbor?source=menu_deployment_id\").json()\n if(bgp['enable']):\n yaml_text += \"\\nbgpSystemConfig: \\n\"\n yaml_text += \" enable: true \\n\"\n yaml_text += \" asn: \" + str(bgp['asn']) + \"\\n\"\n yaml_text += \" routerId: \" + bgp['rtr_id'] + \"\\n\"\n yaml_text += \" enableGracefulRestart: \" + str(bgp['graceful_restart_en']).lower() + \"\\n\"\n yaml_text += \" maxRestartTime: \" + str(bgp['max_restart_time']) + \"\\n\"\n yaml_text += \" maxStalePathTime: \" + str(bgp['stale_path_time']) + \"\\n\"\n #yaml_text += \" redistToSilverPeak: false\" + bgp['asn'] + \"\\n\"\n yaml_text += \" propagateAsPath: \" + str(bgp['remote_as_path_advertise']).lower() + \"\\n\"\n yaml_text += \" redistOspfToBgp: \" + str(bgp['redist_ospf']).lower() + \"\\n\"\n yaml_text += \" filterTag: \" + str(bgp['redist_ospf_filter']) + \"\\n\"\n\n # if(bgp_neigh):\n # yaml_text += \" neighbors: \\n\"\n # for i in range(len(list(bgp_neigh))):\n \n # yaml_text += \" - peerIpAddress: \" + list(bgp_neigh)[i] + \"\\n\"\n # yaml_text += \" enableImports: \" + str(bgp_neigh[list(bgp_neigh)[i]]['import_rtes']).lower() + \"\\n\"\n # yaml_text += \" peerAsn: \" + str(bgp_neigh[list(bgp_neigh)[i]]['remote_as']) + \"\\n\"\n # #yaml_text += \" peerType: \" + bgp_neigh[list(bgp_neigh)[i]]['type'] + \"\\n\"\n # yaml_text += \" enableNeighbor: \" + str(bgp_neigh[list(bgp_neigh)[i]]['enable']).lower() + \"\\n\"\n # #yaml_text += \" localPreference: \" + str(bgp_neigh[list(bgp_neigh)[i]]['loc_pref']) + \"\\n\"\n # yaml_text += \" med: \" + str(bgp_neigh[list(bgp_neigh)[i]]['med']) + \"\\n\"\n # yaml_text += \" asPrependCount: \" + str(bgp_neigh[list(bgp_neigh)[i]]['as_prepend']) + \"\\n\"\n # yaml_text += \" nextHopSelf: \" + str(bgp_neigh[list(bgp_neigh)[i]]['next_hop_self']).lower() + \"\\n\"\n # if(\"lcl_interface\" in bgp_neigh[list(bgp_neigh)[i]].keys()):\n # yaml_text += \" sourceIpInterface: \" + bgp_neigh[list(bgp_neigh)[i]]['lcl_interface'] + \"\\n\"\n # yaml_text += \" inputMetric: \" + str(bgp_neigh[list(bgp_neigh)[i]]['in_med']) + \"\\n\" #???\n # yaml_text += \" keepAlive: \" + str(bgp_neigh[list(bgp_neigh)[i]]['ka']) + \"\\n\"\n # yaml_text += \" holdTime: \" + str(bgp_neigh[list(bgp_neigh)[i]]['hold']) + \"\\n\"\n #yaml_text += \" password:\n #yaml_text += localConfigured: true\n # yaml_text += learnViaSubnetSharing: true\n # yaml_text += learnFromBgpBranch: true\n # yaml_text += learnFromBgpBranchTransit: true\n # yaml_text += learnFromBgpPeRouter: true\n # yaml_text += remoteBgp: true\n # yaml_text += remoteBgpBranchTransit: true\n # yaml_text += learnFromLocalOspf: true\n # yaml_text += learnFromRemoteOspf: true\n\n\n return yaml_text\n\n\ndef templates(orch, nepk):\n yaml_text = \"\"\n templates = orch.get(\"/template/applianceAssociation/\" + nepk + \"?source=menu_deployment_id\").json()\n yaml_text += \"\\ntemplateGroups: \\n\"\n yaml_text += \" groups: \\n\"\n for i in range(len(templates['templateIds'])):\n yaml_text += \" - \" + templates['templateIds'][i] + \"\\n\"\n\n return yaml_text\n\ndef bio(orch, nepk):\n yaml_text = \"\"\n bio = orch.get(\"/gms/overlays/association\").json()\n bio_config = orch.get(\"/gms/overlays/config\").json()\n bio_dict = {}\n for i in range(len(bio_config)):\n bio_dict[str(bio_config[i]['id'])] = bio_config[i]['name']\n\n yaml_text += \"\\nbusinessIntentOverlays:\\n\"\n yaml_text += \" overlays:\\n\"\n for i in bio:\n if nepk in bio[i]:\n yaml_text += \" - \" + bio_dict[i] + \"\\n\"\n return yaml_text\n\ndef inbound_port_forwarding(orch, nepk):\n yaml_text = \"\"\n ipf = orch.get(\"/portForwarding/\" + nepk + \"?source=menu_deployment_id\").json()\n if(ipf):\n yaml_text += \"\\ninboundPortForwarding:\\n\"\n yaml_text += \" portForwardingRules:\\n\"\n\n for i in ipf:\n if(not i['gms_marked']):\n yaml_text += \" - sourceIpSubnet: \" + i['srcSubnet'] + \"\\n\"\n yaml_text += \" destinationIpSubnet: \" + i['destSubnet'] + \"\\n\"\n yaml_text += \" translate: true\\n\" #always true? Unsure of the different use cases\n yaml_text += \" destinationPortRange: \" + i['destPort'] + \"\\n\"\n yaml_text += \" destinationProtocol: \" + i['protocol'] + \"\\n\"\n yaml_text += \" translateIp: \" + i['targetIp'] + \"\\n\"\n yaml_text += \" translatePortRange: \" + i['targetPort'] + \"\\n\"\n yaml_text += \" comment: \" + i['comment'] + \"\\n\"\n\n\n return yaml_text\n\n\n\n\n\n\n\n","repo_name":"craigsanford/preconfig_gen","sub_path":"preconf.py","file_name":"preconf.py","file_ext":"py","file_size_in_byte":17225,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"16846222559","text":"def solution(numbers):\n answer = ''\n numbers = list(map(str, numbers))\n number = list(map(lambda x: (x * 4)[:4], numbers))\n temp = []\n for idx, n in enumerate(number):\n temp.append((n, len(numbers[idx])))\n temp.sort(key=lambda x: x[0], reverse=True)\n\n for n, length in temp:\n answer += n[:length]\n\n if answer[0] == '0':\n answer = '0'\n\n return answer","repo_name":"yyoongs/CodingTest-Practice","sub_path":"프로그래머스/코테 고득점 KIT/정렬/가장 큰 수/가장 큰 수.py","file_name":"가장 큰 수.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"26708001866","text":"\"\"\"\n :author: pk13055, shreygupta2809\n :brief: convenience functions for strategy help\n\"\"\"\nfrom datetime import datetime, timedelta\nimport hashlib\nimport json\nimport os\nimport uuid\n\nfrom aio_pika import connect, IncomingMessage, ExchangeType, Message, DeliveryMode\nimport asyncio\n\nfrom .encoder import EnhancedJSONDecoder, EnhancedJSONEncoder\nfrom .enums import Stage, StrategyType\n\n\nclass Strategy:\n \"\"\"Base class for strategy creation\"\"\"\n\n def __init__(\n self,\n stage: Stage,\n loop: asyncio.AbstractEventLoop = asyncio.get_event_loop(),\n params: dict = None,\n ):\n self.name = params[\"name\"]\n self.strategy_type = StrategyType(params[\"strategy_type\"].lower())\n self.loop = loop\n self.stage = Stage[stage]\n self.asset = params[\"asset\"]\n self.asset_class = params[\"asset_class\"]\n self.asset_type = params[\"asset_type\"]\n self.inPosition: bool = False\n self.DATABASE_URI: str = os.getenv(\n \"DATABASE_URI\", \"postgresql://postgres@localhost/test\"\n )\n self.RABBIT_URI: str = os.getenv(\"RABBIT_URI\", \"amqp://guest:guest@localhost/\")\n self.sigGenerated: bool = False\n\n self.versionID = hashlib.md5(\n json.dumps(params, sort_keys=True).encode(\"utf-8\")\n ).hexdigest()\n # TODO: Generate Strategy ID using proper methods from config\n self.strategyID = uuid.uuid4().hex\n\n self.start_date = params[\"start_date\"]\n self.end_date = params[\"end_date\"]\n if self.stage == Stage.BACKTEST:\n if self.start_date == \"\" and self.end_date != \"\":\n self.end_date = datetime.strptime(self.end_date, \"%Y/%m/%d\")\n self.start_date = datetime.strptime(\n self.end_date, \"%Y/%m/%d\"\n ) - timedelta(2)\n\n elif self.start_date != \"\" and self.end_date == \"\":\n self.start_date = datetime.strptime(self.start_date, \"%Y/%m/%d\")\n self.end_date = self.start_date + timedelta(2)\n\n elif self.start_date == \"\" and self.end_date == \"\":\n self.end_date = datetime.today()\n self.start_date = datetime.today() - timedelta(2)\n\n else:\n self.start_date = datetime.strptime(self.start_date, \"%Y/%m/%d\")\n self.end_date = datetime.strptime(self.end_date, \"%Y/%m/%d\")\n\n self.start_date = self.start_date.date()\n self.end_date = self.end_date.date()\n\n async def run(self) -> None:\n \"\"\"The main strategy run function which executes the strategy\"\"\"\n await self.create_exchanges()\n await self.bind_queues()\n\n if self.stage == Stage.BACKTEST:\n publish_data = {\n \"date_interval\": [self.start_date, self.end_date],\n \"asset\": self.asset,\n \"frequency\": \"1m\",\n \"asset_type\": self.asset_type,\n \"versionID\": self.versionID,\n }\n asyncio.ensure_future(\n self.exchange.publish(\n Message(\n json.dumps(publish_data, cls=EnhancedJSONEncoder).encode(),\n delivery_mode=DeliveryMode.PERSISTENT,\n ),\n routing_key=f\"{self.asset_class}.meta.{self.strategyID}.requests.{self.versionID}\",\n ),\n loop=self.loop,\n )\n\n async def create_exchanges(self) -> None:\n \"\"\"Creates the Exchanges, Pool and Topics necessary for execution\"\"\"\n self.connection = await connect(self.RABBIT_URI, loop=self.loop)\n channel = await self.connection.channel()\n if self.stage == Stage.LIVE:\n self.ohlc_topic = (\n f\"{self.asset_class}.tickers.{self.asset_type}.ohlc.1m.{self.asset}\"\n )\n self.tick_topic = (\n f\"{self.asset_class}.tickers.{self.asset_type}.tick.{self.asset}\"\n )\n self.exchange_name = \"tickers\"\n elif self.stage == Stage.BACKTEST:\n self.ohlc_topic = f\"{self.asset_class}.tickers.{self.asset_type}.ohlc.1m.{self.asset}.{self.versionID}\"\n self.tick_topic = f\"{self.asset_class}.tickers.{self.asset_type}.tick.{self.asset}.{self.versionID}\"\n self.exchange_name = \"database\"\n\n self.exchange = await channel.declare_exchange(\n self.exchange_name, ExchangeType.TOPIC\n )\n\n async def bind_queues(self) -> None:\n \"\"\"Binds the Queues to the Exchange for Necessary Topics\"\"\"\n channel = await self.connection.channel()\n await channel.set_qos(prefetch_count=1)\n\n self.topics = [self.ohlc_topic]\n if self.stage != Stage.BACKTEST:\n self.topics.append(self.tick_topic)\n\n for topic in self.topics:\n queue = await channel.declare_queue()\n await queue.bind(self.exchange, topic)\n await queue.consume(self.on_message)\n\n async def on_message(self, message: IncomingMessage, *args, **kwargs) -> None:\n \"\"\"Callback function which routes message to necessary function\"\"\"\n async with message.process():\n data = json.loads(message.body, cls=EnhancedJSONDecoder)\n if \".tick.\" in message.routing_key:\n await self.on_tick(data)\n elif \".ohlc.\" in message.routing_key:\n await self.on_candle(data)\n\n async def on_tick(self, data: dict) -> None:\n \"\"\"Process data every tick\"\"\"\n if self.sigGenerated and not self.inPosition:\n if self.checkEntry(data):\n self.inPosition = True\n self.sigGenerated = False\n elif self.inPosition:\n if self.checkExit(data):\n self.inPosition = False\n\n async def on_candle(self, data: dict) -> None:\n \"\"\"Process data every candle\"\"\"\n if self.stage == Stage.LIVE:\n self.genSig(data)\n elif self.stage == Stage.BACKTEST:\n data = list({frozenset(item.items()): item for item in data}.values())\n sorted_data = sorted(data, key=lambda k: k[\"t\"])\n self.backtest(sorted_data)\n\n def checkEntry(self, data: dict) -> None:\n \"\"\"Checks entry after signal is generated\"\"\"\n raise NotImplementedError\n\n def checkExit(self, data: dict) -> None:\n \"\"\"Checks exit\"\"\"\n raise NotImplementedError\n\n def genSig(self, data: dict) -> None:\n \"\"\"Generates trade signals\"\"\"\n raise NotImplementedError\n\n def backtest(self, data: dict) -> None:\n \"\"\"Backtests the strategy on past ohlc data\"\"\"\n raise NotImplementedError\n","repo_name":"Synalytica/btc-futures","sub_path":"utils/strategy_helpers.py","file_name":"strategy_helpers.py","file_ext":"py","file_size_in_byte":6675,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"33236002327","text":"\"\"\"\nReplaces the audio of a video file with an external audio file, and syncronises\nthe audio file with the original video file audio.\n\"\"\"\nfrom moviepy.audio.io.AudioFileClip import AudioFileClip\nfrom moviepy.editor import VideoFileClip\nimport numpy as np\nfrom scipy import signal\n\naudio_fn = \"blackbird.wav\"\nvideo_fn = \"blackbird.mp4\"\nout_fn = None # \"out.mp4\"\n\n\ndef calculate_time_offset(a, b, fs):\n \"\"\"\n Calculates the time offset of two signals by performing a cross correlation\n analysis. Assumes both signals have the same sampling frequency.\n args:\n a (1D array): first signal.\n b (1D array): second signal.\n fs (float): Sampling frequency of signals.\n returns:\n offset (float): The time offset in seconds. Positive offset means a lags\n behind b.\n max_corr (float): The Pearson correlation coefficient of the two signals\n at the optimal time offset.\n \"\"\"\n a = np.reshape(a, (-1))\n b = np.reshape(b, (-1))\n corr = signal.correlate(a - a.mean(), b - b.mean(), mode=\"full\")\n corr /= len(b) * a.std() * b.std()\n\n lag = np.arange(0, len(corr)) - (len(b) - 1)\n\n offset = lag[corr.argmax()]\n max_corr = corr.max()\n return offset / fs, max_corr\n\n\ndef AVsync(audio_fn, video_fn, offset=None, verbose=False):\n audio = AudioFileClip(audio_fn)\n video = VideoFileClip(video_fn)\n\n if offset is None:\n x1 = audio.to_soundarray()\n x2 = video.audio.to_soundarray()\n offset, corr = calculate_time_offset(x1[:, 0], x2[:, 0], fs=44100)\n if verbose:\n print(f\"Offset: {offset:2.3f}s\\nCorrelation: {corr*100:2.2f}%\")\n\n if offset > 0:\n video_out = video.set_audio(audio.subclip(offset))\n else:\n video_out = video.subclip(-offset).set_audio(audio)\n\n return video_out\n\n\nif __name__ == \"__main__\":\n\n video_out = AVsync(audio_fn, video_fn, verbose=True)\n if out_fn:\n video_out.write_videofile(out_fn)\n","repo_name":"jaimeliew1/AVsync","sub_path":"avsync/avsync.py","file_name":"avsync.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"34005154208","text":"\"\"\"\nEvent\n---------\nA class to hold data from particular events in the rain gage network as well as information \nabout the network. This class is the transpose of a temporal slice or aggregation of the \nRain object. So the columns are dates and the rows are rain gage locations. \n\n\"\"\"\nfrom common import *\n\nclass Event:\n '''\n Base class for Event files\n ''' \n def __init__(self, df, ll_cols=None):\n '''\n Initialize intance of Event class\n \n Parameters\n ----------\n df : Dataframe object with rain gage locations as the index. The columns must include \n lat and lon as well as the times of interest.\n \n '''\n df = df[df.lat > -200]\n if ll_cols is not None:\n self.ll_cols = ll_cols\n else:\n self.ll_cols = [col for col in df.columns if col in ('RG','lat','lon','X','Y','start_date','station_name')]\n \n self.data_cols = [col for col in df.columns if col not in self.ll_cols]\n self.df = df.dropna(how='all', subset=self.data_cols)\n self.data_cols = [col for col in self.df.columns if col not in self.ll_cols]\n self.ll = self.df[self.ll_cols]\n \n def set_ll(self):\n \"\"\"\n Add projected distances in catrtesian coordinates given lat and lon\n \n Parameters\n ----------\n self : lat and lon in columns\n\n Returns\n -------\n self.ll : similar to ll, but also with projected euclidian locations.\n \"\"\"\n self.ll['Y'] = self.ll['lat']*110.574\n self.ll['X'] = self.ll['lon']*111.320*(self.ll['lat']*pi/180).apply(cos)\n self.ll_cols = self.ll.columns\n self.df.insert(2, 'X',self.ll.X)\n self.df.insert(3, 'Y',self.ll.Y)\n\n def __get_latlon(self, latlon):\n if latlon:\n x,y = self.df['lon'], self.df['lat']\n else:\n try:\n x,y = self.df['X'], self.df['Y']\n except:\n x,y = self.df['x'], self.df['y'] \n return x, y\n \n def map_rain(self, save_path='./', title='', sharec=False, save=False, cmap='gist_earth_r', s=100,\n top_to_bottom=False, hide_title=False, ncols=None, nrows=None, figsize=None, \n ax=None, latlon=True, cartopy=False,\n basemap=False, shpfile=None, POT=[], locs=[], colors=[], **basemap_kwargs):\n \"\"\"\n Map rainfall at each gage location\n\n Parameters\n ----------\n self : Event object with at least one data column\n\n kwargs\n ----------\n \n save_path : Path to which output should be saved - must include trailing slash\n title : Plot title\n sharec : bool to represent whether the plots should share a colorbar or tuple of min,max values\n save : bool to determine whether plot should be saved\n cmap : colormap - default 'gist_eart_r'\n s : int size of points - default 100\n top_to_bottom : bool to orient the subplots vertically rather than horizontally\n hide_title : bool to not have a title over the whole figure\n figsize : as in matplotlib\n tooltips: bool include labels of on scroll over the points\n ax : axes object onto which the map should plot\n latlon : bool plot against lat and lon rather than euclidian distances - default True\n basemap : bool include underlaying county boundaries\n shpfile : str shapefile for the watersheds in the area\n POT : list times of peak over threshold incidents\n locs : list GAGE_IDs of the watersheds of interest\n colors: list colors to use for watersheds of interest\n\n **basemap_kwargs\n\n Returns\n -------\n fig : map of rain intensity at each location\n \"\"\"\n if len(title) == 0:\n hide_title=True\n df = self.df\n x, y = self.__get_latlon(latlon)\n cols = self.data_cols\n map_kwargs = {'cmap':cmap, 's':s}\n if ncols or nrows:\n try: \n nrows = int(np.ceil(len(cols)/float(ncols)))\n except:\n ncols = int(np.ceil(len(cols)/float(nrows)))\n elif len(cols) == 1:\n ncols = 1\n nrows = 1\n else:\n ncols = 2\n nrows = int(np.ceil(len(cols)/float(ncols)))\n if top_to_bottom:\n nrows, ncols = ncols, nrows\n if cartopy:\n fig = plt.figure(figsize=figsize)\n axes = np.array(range(len(cols)))\n axes_list = []\n elif figsize:\n fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex='row', sharey='row')\n elif ax is None:\n fig, axes = plt.subplots(nrows, ncols, figsize=(ncols*8, 5*nrows), sharex='row', sharey='row')\n\n if sharec:\n try:\n vmin, vmax = sharec\n except:\n vmax = min(100, df[cols].max().max())\n vmin = max(0, df[cols].min().min())\n map_kwargs.update({'vmin':vmin, 'vmax':vmax})\n if not hide_title: \n fig.suptitle(title, fontsize=18)\n fig.subplots_adjust(top=.85, hspace=.3, wspace=0.1)\n return_ax = False\n if not cartopy and ax is not None:\n axes = ax\n return_ax = True\n try:\n axes = axes.reshape(-1)\n except:\n axes = list(axes)\n for col, ax in zip(cols, axes):\n if basemap:\n a = self.__include_basemap(ax, shpfile, POT, locs, colors, **basemap_kwargs)\n map_kwargs.update({'latlon': latlon})\n if cartopy:\n a = self.__include_cartopy(ax, nrows, ncols, **basemap_kwargs)\n axes_list.append(a)\n else:\n a = ax\n scat = a.scatter(x=x.values, y=y.values, c=df[col].values, **map_kwargs)\n a.set_title(col)\n if return_ax:\n return scat\n if not sharec:\n fig.colorbar(scat, ax=a)\n if sharec and not cartopy:\n fig.colorbar(scat, ax=list(axes), fraction=.05)\n elif sharec and cartopy:\n fig.colorbar(scat, ax=axes_list, fraction=.05)\n if save:\n plt.savefig(save_path+title+'.png')\n\n\n def movie(self, vmin=None, vmax=None, cmap='gist_earth_r', s=100, latlon=True, basemap=False,\n shpfile=None, POT=[], locs=[], colors=[], **basemap_kwargs):\n \"\"\"\n Make a movie of rainfall maps using JSAnimation (always share a colormap)\n\n Parameters\n ----------\n self : Event object with at least one data column\n\n kwargs\n ----------\n vmin : min value for colormap\n vmax : max value for colormap\n cmap : colormap - default 'gist_eart_r'\n s : int size of points - default 100\n latlon : bool plot against lat and lon rather than euclidian distances - default True\n basemap : bool include underlaying county boundaries\n shpfile : str shapefile for the watersheds in the area\n POT : list times of peak over threshold incidents\n locs : list GAGE_IDs of the watersheds of interest\n colors: list colors to use for watersheds of interest\n\n **basemap_kwargs\n\n Returns\n -------\n animation : animation of maps (breaks on matplotlib > 1.4.3)\n \"\"\" \n df = self.df\n x, y = self.__get_latlon(latlon)\n cols = self.data_cols\n\n if not vmin:\n vmin = max(0, df[cols].min().min())\n if not vmax:\n vmax = df[cols].max().max()\n map_kwargs = {'x':x.values, 'y':y.values, 'cmap':cmap, 'vmin':vmin, 'vmax':vmax, 's':s}\n \n fig, ax = plt.subplots(1,1,figsize=(10,6))\n if basemap:\n a = self.__include_basemap(ax, shpfile, POT, locs, colors, **basemap_kwargs)\n map_kwargs.update({'latlon': latlon})\n else:\n a = ax\n\n sc = a.scatter(c=y.values*0, **map_kwargs)\n fig.colorbar(sc)\n\n def animate(i):\n ax.set_title(cols[i])\n scat = a.scatter(c=df[cols[i]].values, **map_kwargs)\n\n return animation.FuncAnimation(fig, animate, frames=len(cols), interval=300, blit=True)\n\n \n def detrend(self, latlon=True, plot=False, drop_zeros=True):\n \"\"\"\n Generate a dataframe containing values linearly detrended in space\n\n Parameters\n ----------\n self : Event object with at least one data column\n\n kwargs\n ----------\n latlon : bool detrend with respect to lat and lon rather than euclidian distances - default True\n plot : bool plot the detrending - default False\n drop_zeros : bool drop all the zeros from the detrended dataset - default True\n\n Returns\n -------\n self.res : Dataframe of means plus residuals for each time and location\n \"\"\"\n import statsmodels.formula.api as sm\n \n df = self.df\n x, y = self.__get_latlon(latlon)\n cols = self.data_cols\n\n res = self.ll\n for col in cols:\n foo = pd.DataFrame(x).join((y, df[col])).dropna(how='any')\n foo.columns = ['lon', 'lat', 'col']\n result = sm.ols(formula=\"col ~ lon + lat\", data=foo).fit()\n fit = result.params['Intercept'] + result.params['lon']*foo.lon +result.params['lat']*foo.lat\n if plot:\n fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12,4))\n for l, ax in zip(['lon', 'lat'], axes):\n ax.scatter(x=foo[l], y=foo.col)\n ax.scatter(foo[l], fit, c='r')\n ax.set_ylabel('Rain Rate (mm/hr)')\n ax.set_xlabel(l)\n ax.set_title('Trend in ' + l)\n res = res.join(pd.DataFrame({col: df[col]-fit + df[col].mean()}))\n if drop_zeros:\n zeros = [col for col in cols if res[col].mean()==0]\n res = res.drop(zeros, axis=1)\n self.res = res\n\n def variogram(self, i=0, plot_v=True, **kwargs):\n \"\"\"\n Generate a variogram\n\n Parameters\n ----------\n\t\tself : Event object with at least one data column\n i : int data column index number (defaults to 0)\n\t\tplot_v : bool generate a plot of the variogram\n\n **kwargs (target_np, alpha, tol_hor, max_bnd, last_max)\n\n Returns\n -------\n v : Dataframe containing output from r-variogram function\n \"\"\"\n from rpy2.robjects import pandas2ri\n pandas2ri.activate()\n rfuncs = import_r_tools()\n \n if 'X' not in self.ll_cols:\n self.set_ll()\n \n df = self.df\n cols = self.data_cols\n \n r_df = df.loc[:,['X', 'Y', cols[i]]].dropna(how='any')\n v = pandas2ri.ri2py(rfuncs.get_iSVG(r_df, 3, **kwargs))\n if plot_v:\n v.plot(x='dist', y='gamma', marker = 'o', figsize=(8,4))\n return v\n\n def krige(self, i=0, v=None, step=1, res=True, plot_v=False, plot_k=True, animated=False, **plot_kwargs):\n \"\"\"\n Krige the dataframe with a single data column or a column index number\n\n Parameters\n -------\n\t\tself : Event object with at least one data column\n\t\t\n\t\tkwargs\n\t\t-------\n i : int data column index number (defaults to 0)\n v : variogram to use in determining sill and range\n step : grid interval to krige on (in km)\n\t\tres : bool detrend points before computing kriged values - default True\n\t\tplot_v : bool plot variogram - default False\n\t\tplot_k : bool plot kriged values - default True\n\t\tanimated : bool return axis for animation - default False\n\n **plot_kwargs (cmap, s, latlon, basemap, shpfile, POT, locs, colors)\n\n Returns\n -------\n k : Dataframe containing output from r-krige function\n \"\"\"\n from rpy2.robjects import pandas2ri\n pandas2ri.activate()\n rfuncs = import_r_tools()\n \n if 'X' not in self.ll_cols:\n self.set_ll()\n \n if res:\n if not hasattr(self, 'res'):\n self.detrend()\n df = self.res\n else:\n df = self.df\n cols = self.data_cols\n \n r_df = df.loc[:,['X', 'Y', cols[i]]].dropna(how='any')\n if not v:\n v = pandas2ri.ri2py(rfuncs.get_variogram(r_df))\n\n model = 'Sph'\n psill = r_df.var()[cols[i]]\n for j in range(len(v)):\n if v.gamma[j] > psill:\n rng = v.dist[j]\n break\n k = pandas2ri.ri2py(rfuncs.get_krige(r_df, psill, model, rng, step=step))\n k['lat'] = k.y/110.574\n k['lon'] = k.x/(111.320*(k['lat']*pi/180).apply(cos))\n self.k = k\n if plot_k and animated:\n return self.plot_krige(i, k, rng, step=step, res=res, animated=animated, **plot_kwargs)\n elif plot_k and not animated:\n self.plot_krige(i, k, rng, step=step, res=res, animated=animated, **plot_kwargs)\n else:\n return k\n\n def plot_krige(self, i, k, rng, step=1, res=True, animated=False,\n ax=None, cmap='gist_earth_r', vmin=None, vmax=None, latlon=False,\n basemap=False, shpfile=None, POT=[], locs=[], colors=[], **basemap_kwargs):\n \"\"\"\n\t\tPlot the kriged values for data column i\n\t\t\n\t\tParameters\n\t\t------\n\t\tself : Event object with at least one data column\n\t\ti : int data column index number (defaults to 0)\n k : Dataframe containing output from r-krige function\n\t\trng : distance in km for which kriged values are good predictors\n\t\t\n\t\tkwargs \n\t\t------\n\t\tstep : distance in km between grid cells on which to compute kriged values - default 1\n\t\tres : bool detrend points before computing kriged values - default True\n\t\tanimated : bool return axis for animation - default False\n\t\tax : axes object onto which the map should plot\n\t\tcmap : colormap - default 'gist_eart_r'\n\t\ts : int size of points - default 100\n\t\tlatlon : bool plot against lat and lon rather than euclidian distances - default True\n\t\tbasemap : bool include underlaying county boundaries\n\t\tshpfile : str shapefile for the watersheds in the area\n\t\tPOT : list times of peak over threshold incidents\n\t\tlocs : list GAGE_IDs of the watersheds of interest\n\t\tcolors: list colors to use for watersheds of interest\n\t\t\n\t\t**basemap_kwargs (any kwarg that goes into the Basemap)\n\t\t\n\t\tReturns\n -------\n fig : plot of output from r-krige function\n \"\"\"\n\n if res:\n if not hasattr(self, 'res'):\n self.detrend() \n df = self.res\n else:\n df = self.df\n cols = self.data_cols\n map_kwargs = {'cmap':cmap}\n \n if not ax:\n fig, ax = plt.subplots(figsize=(10,6))\n if not vmin:\n vmin = max(0, df[cols[i]].min())\n if not vmax:\n vmax = df[cols[i]].max()\n map_kwargs.update({'vmin':vmin, 'vmax':vmax})\n \n if basemap:\n latlon=True\n a = self.__include_basemap(ax, shpfile, POT, locs, colors, **basemap_kwargs)\n map_kwargs.update({'latlon': latlon, 'alpha':0.7})\n else:\n a = ax\n if latlon:\n a.scatter(k.lon.values, k.lat.values, c=k['var1.pred'].values, marker='s', edgecolors='none', s=step*300, **map_kwargs)\n scat = a.scatter(df.lon.values, df.lat.values, c=df[cols[i]].values, edgecolors='1', **map_kwargs)\n if not basemap:\n a.set_xlim(min(df.lon), max(df.lon))\n a.set_ylim(min(df.lat), max(df.lat))\n else:\n a.scatter(k.x, k.y, c=k['var1.pred'].values, marker='s', edgecolors='none', s=step*300, **map_kwargs)\n scat = a.scatter(df.X, df.Y, c=df[cols[i]].values, edgecolors='1', **map_kwargs)\n a.set_xlim(min(df.X), max(df.X))\n a.set_ylim(min(df.Y), max(df.Y))\n plt.title('{t} (range={dts}km)'.format(t=cols[i], dts=round(rng)))\n if animated:\n return scat\n plt.colorbar(scat)\n\n def get_SVG(self, **kwargs):\n \"\"\"\n Generate a panel of variograms from a dataframe\n\n Parameters\n ----------\n\t\tself : Event object with at least one data column\n\t\t\n **kwargs (target_np, alpha, tol_hor, max_bnd, last_max)\n\n Returns\n -------\n SVGs : panel of variograms with the date_times as the items\n \"\"\"\n df = self.df\n cols = self.data_cols\n \n d = {}\n for col in cols:\n d.update({col: variogram(df, df.axes[1].get_loc(col), **kwargs)})\n SVGs = pd.Panel(d)\n self.SVGs\n\n def combine_SVGs(self):\n \"\"\"\n Wrapper for get_SVG to create a consolidated dataframe of dist vs gamma\n\t\t\n\t\tParameters\n\t\t-------\n\t\tself : Event object with at least one data column\n\t\t\n Returns\n -------\n combined_SVG : dataframe of dist vs gamma\n \"\"\"\n SVGs = self.SVGs\n k = 0\n for i in SVGs.items:\n s = SVGs[i,:,'gamma']\n s.set_axis(0, SVGs[i,:,'dist'])\n s.name = i\n k += 1\n if k == 1:\n a = pd.DataFrame(s)\n else:\n a = a.join(s)\n combined_SVG = a\n self.combined_SVG\n\n def __include_cartopy(self, n, nrows, ncols, shpfile='../../data/CHARLOTTE/Maps/county.shp', \n extent=None, proj=None):\n import cartopy.crs as ccrs\n import cartopy.io.shapereader as shpreader\n import cartopy.feature as cfeature\n \n if proj is None:\n proj=ccrs.PlateCarree()\n if extent is None:\n extent = [self.ll.lon.min()-.01, self.ll.lon.max()+.01, \n self.ll.lat.min()-.01, self.ll.lat.max()+.01]\n ax = plt.subplot(nrows, ncols, n+1, projection=proj)\n #ax = plt.axes(projection=proj)\n #TODO: add other geometries (basins and whatever) maybe using dicts?\n\n counties = list(shpreader.Reader(shpfile).geometries())\n ax.add_geometries(counties, proj, edgecolor='gray', facecolor='None')\n ax.set_extent(extent, proj)\n\n return ax\n\n def __include_basemap(self, ax, shpfile, POT, locs, colors, resolution='i', projection='tmerc', **basemap_kwargs):\n from mpl_toolkits.basemap import Basemap\n from matplotlib.patches import Polygon\n\n if 'llcrnrlon' not in basemap_kwargs.keys():\n basemap_kwargs.update({'llcrnrlon': self.ll.lon.min()-.01})\n if 'llcrnrlat' not in basemap_kwargs.keys():\n basemap_kwargs.update({'llcrnrlat': self.ll.lat.min()-.01})\n if 'urcrnrlon' not in basemap_kwargs.keys():\n basemap_kwargs.update({'urcrnrlon': self.ll.lon.max()+.01})\n if 'urcrnrlat' not in basemap_kwargs.keys():\n basemap_kwargs.update({'urcrnrlat': self.ll.lat.max()+.01})\n if projection == 'tmerc':\n if 'lat_0' not in basemap_kwargs.keys():\n basemap_kwargs.update({'lat_0': (self.ll.lat.min()+self.ll.lat.max())/2.})\n if 'lon_0' not in basemap_kwargs.keys():\n basemap_kwargs.update({'lon_0': (self.ll.lon.min()+self.ll.lon.max())/2.})\n\n map = Basemap(ax=ax, resolution=resolution, projection=projection, **basemap_kwargs)\n \n parallels = np.arange(basemap_kwargs['llcrnrlat'], basemap_kwargs['urcrnrlat'],.1)\n map.drawparallels(parallels,labels=[True,False,False,False])\n \n meridians = np.arange(basemap_kwargs['llcrnrlon'], basemap_kwargs['urcrnrlon'],.1)\n map.drawmeridians(meridians,labels=[False,False,False,True])\n map.drawcounties()\n\n if shpfile is not None:\n map.readshapefile(shpfile, 'watersheds')\n\n w_names = []\n for shape_dict in map.watersheds_info:\n w_names.append(shape_dict['GAGE_ID'])\n\n for loc, c in zip(locs, colors):\n seg = map.watersheds[w_names.index(loc)]\n poly = Polygon(seg, facecolor=c,edgecolor=c, alpha=.5)\n ax.add_patch(poly)\n return map \n","repo_name":"jsignell/rain-gage-tools","sub_path":"rain/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":20177,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"22157624680","text":"class Node:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\ndef print_tree(node, level=0):\n if node is not None:\n print_tree(node.right, level+1)\n print(' ' * 4 * level + '->', node.value)\n print_tree(node.left, level+1)\n\ndef insere_direita(node, value):\n if node.right is None:\n node.right = Node(value)\n else:\n insere_direita(node.right, value)\n\ndef insere_esquerda(node, value):\n if node.left is None:\n node.left = Node(value)\n else:\n insere_esquerda(node.left, value)\n\n\n\nroot = Node(6)\nroot.left = Node(2)\nroot.right = Node(8)\nroot.left.left = Node(1)\nroot.left.right = Node(4)\nroot.right.left = Node(7)\nroot.right.right = Node(9)\n\nprint_tree(root)\n","repo_name":"ed1rac/AulasEstruturasDados","sub_path":"UNP/ref/C/Arvores/trees/arvore_visualizando.py","file_name":"arvore_visualizando.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"27"} +{"seq_id":"72160260873","text":"#!/usr/bin/env python\n\n\"\"\"\nPredicting digits in the mnist dataset using feedforward neural network. \nParameters:\n infile: str \n outfile: str \n split: float \n epochs: int \n\nUsage:\n nn-mnist.py --epochs \nExample:\n $ python nn-mnist.py --epochs 10\n\"\"\"\n\n# import dependencies \nimport sys,os\nimport numpy as np\nsys.path.append(os.path.join(\"..\"))\nimport argparse\nimport pandas as pd\n\nimport utils.classifier_utils as clf_util\n\n# Import sklearn metrics\nfrom sklearn import metrics\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom utils.neuralnetwork import NeuralNetwork\n#from utils.neuralnetwork import plot_train_hist\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split\n\n\n# define main function\ndef main():\n print(\"\\nInitialising analysis...\")\n \n # initialise argumentparser\n ap = argparse.ArgumentParser()\n \n # define arguments\n ap.add_argument(\"-i\", \n \"--infile\", \n required=False, \n type = str, \n help=\"Input filename\",\n default=\"mnist_784\")\n ap.add_argument(\"-s\", \n \"--split\", \n required=False,\n type=float,\n help=\"Train/test split\", \n default=0.2)\n ap.add_argument(\"-o\", \n \"--outfile\", \n required=False, \n type = str,\n help=\"Output csv filename\", \n default = \"metrics_nn.csv\")\n ap.add_argument(\"-e\", \n \"--epochs\", \n required=False, \n type = int, \n help=\"Number of epochs\",\n default = 1000)\n\n\n\n # parse arguments to args\n args = vars(ap.parse_args())\n \n # fetch args\n input_name = args[\"infile\"]\n split_value = args[\"split\"]\n n_epochs = args[\"epochs\"]\n\n \n print(\"\\nFetching data...\")\n \n # fetch data \n digits = datasets.load_digits()\n \n # convert to floats\n data = digits.data.astype(\"float\")\n \n # perform min-max regularization\n data = (data - data.min())/(data.max() - data.min())\n \n # create train/test split \n X_train, X_test, y_train, y_test = train_test_split(data, \n digits.target,\n test_size = args[\"split\"])\n \n # scaling the input features\n X_train_scaled = (X_train - X_train.min())/(X_train.max() - X_train.min())\n X_test_scaled = (X_test - X_test.min())/(X_test.max() - X_test.min())\n \n # convert labels from integers to vectors\n y_train = LabelBinarizer().fit_transform(y_train)\n y_test = LabelBinarizer().fit_transform(y_test)\n \n \n print(\"\\nTraining network...\")\n\n # train neural network\n nn = NeuralNetwork([X_train.shape[1], 20, 15, 10]) # no. of input features, hiddenlayer1, hiddenlayer2, no. of output features\n nn.fit(X_train, y_train, epochs = n_epochs)\n \n # save fitted model \n model_fit = nn.fit(X_train, y_train, epochs = n_epochs)\n \n # calculate predictions for the test set and print in terminal\n predictions = nn.predict(X_test_scaled)\n predictions = predictions.argmax(axis=1)\n print(\"\\nCalculated performance metrics: \")\n print(metrics.classification_report(y_test.argmax(axis=1), predictions))\n \n # create df for storing metrics\n df = pd.DataFrame(metrics.classification_report(y_test.argmax(axis=1), \n predictions, \n output_dict=True)).transpose().round(decimals=2)\n\n # save classification report \n df.to_csv(os.path.join(\"..\", \"output\", args[\"outfile\"]), index = True)\n\n \n# define behaviour from command line \nif __name__==\"__main__\":\n main()\n \n \n \n \n \n \n \n \n","repo_name":"AstridSlet/visual_exam","sub_path":"assignment_4/src/nn-mnist.py","file_name":"nn-mnist.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"16138160760","text":"import argparse\nimport logging\nimport os\nimport random\nimport shutil\nimport sys\nimport time\n\nimport numpy as np\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom tensorboardX import SummaryWriter\nfrom torch.nn import BCEWithLogitsLoss\nfrom torch.nn.modules.loss import CrossEntropyLoss\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\nfrom torchvision.utils import make_grid\nfrom tqdm import tqdm\n\nfrom dataloaders import utils\nfrom networks.net_factory import net_factory\nfrom dataloaders.la_heart import *\nfrom utils import losses, metrics, ramps, test_patch\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--root_path', type=str,\n default='./', help='Name of Experiment')\nparser.add_argument('--dataset_name', type=str,\n default='Prostate', help='dataset_name')\nparser.add_argument('--model_name', type=str,\n default='CPS', help='model_name') \nparser.add_argument('--model_type', type=str,\n default='vnet', help='model_type') \nparser.add_argument('--max_iterations', type=int,\n default=12000, help='maximum epoch number to train')\nparser.add_argument('--batch_size', type=int, default=4,\n help='batch_size per gpu')\nparser.add_argument('--deterministic', type=int, default=1,\n help='whether use deterministic training')\nparser.add_argument('--base_lr', type=float, default=0.01,\n help='segmentation network learning rate')\nparser.add_argument('--seed', type=int, default=1337, help='random seed')\n\n# label and unlabel\nparser.add_argument('--labeled_bs', type=int, default=2,\n help='labeled_batch_size per gpu')\nparser.add_argument('--labeled_num', type=int, default=32,\n help='labeled data')\n\n# costs\nparser.add_argument('--ema_decay', type=float, default=0.99, help='ema_decay')\nparser.add_argument('--consistency_type', type=str,\n default=\"mse\", help='consistency_type')\nparser.add_argument('--consistency', type=float,\n default=0.1, help='consistency')\nparser.add_argument('--consistency_rampup', type=float,\n default=40.0, help='consistency_rampup')\nargs = parser.parse_args()\n\ndef get_current_consistency_weight(epoch):\n # Consistency ramp-up from https://arxiv.org/abs/1610.02242\n return args.consistency * ramps.sigmoid_rampup(epoch, args.consistency_rampup)\n\n\ndef update_ema_variables(model, ema_model, alpha, global_step):\n # Use the true average until the exponential average is more correct\n alpha = min(1 - 1 / (global_step + 1), alpha)\n for ema_param, param in zip(ema_model.parameters(), model.parameters()):\n ema_param.data.mul_(alpha).add_(1 - alpha, param.data)\n\n\ndef kaiming_normal_init_weight(model):\n for m in model.modules():\n if isinstance(m, nn.Conv3d):\n torch.nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm3d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n return model\n\n\ndef xavier_normal_init_weight(model):\n for m in model.modules():\n if isinstance(m, nn.Conv3d):\n torch.nn.init.xavier_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm3d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n return model\n\n\ndef train(args, snapshot_path):\n base_lr = args.base_lr\n batch_size = args.batch_size\n max_iterations = args.max_iterations\n num_classes = 2\n if args.dataset_name == \"LA\":\n args.patch_size = (112, 112, 80)\n args.root_path = args.root_path + 'datasets/LA'\n args.max_samples = 100\n elif args.dataset_name == \"Pancreas\":\n args.patch_size = (96, 96, 96)\n args.root_path = args.root_path + 'datasets/Pancreas-CT'\n args.max_samples = 60\n elif args.dataset_name == \"BraTS\":\n args.patch_size = (96, 96, 96)\n args.root_path = args.root_path + 'datasets/BraTS'\n args.max_samples = 250\n elif args.dataset_name == \"Prostate\":\n args.patch_size = (112, 112, 80)\n args.root_path = args.root_path + 'datasets/Prostate'\n args.max_samples = 160\n train_data_path = args.root_path\n\n def create_model(ema=False):\n # Network definition\n net = net_factory(net_type=args.model_type, in_chns=1, class_num=num_classes)\n model = net.cuda()\n if ema:\n for param in model.parameters():\n param.detach_() # 参数冻结\n return model\n\n net1 = create_model()\n net2 = create_model()\n model1 = kaiming_normal_init_weight(net1)\n model2 = xavier_normal_init_weight(net2)\n model1.train()\n model2.train()\n\n # Create Dataset\n if args.dataset_name == \"LA\":\n db_train = LA(base_dir=train_data_path,\n split='train',\n transform=transforms.Compose([\n RandomRotFlip(),\n RandomCrop(args.patch_size),\n ToTensor(),\n ]))\n elif args.dataset_name == \"Pancreas\":\n db_train = Pancreas(base_dir=train_data_path,\n split='train',\n transform=transforms.Compose([\n RandomCrop(args.patch_size),\n ToTensor(),\n ]))\n elif args.dataset_name == \"BraTS\":\n db_train = BraTS(base_dir=train_data_path,\n split='train',\n transform=transforms.Compose([\n RandomCrop(args.patch_size),\n ToTensorBra(),\n ]))\n elif args.dataset_name == \"Prostate\":\n db_train = Prostate(base_dir=train_data_path,\n split='train',\n transform=transforms.Compose([\n RandomCrop(args.patch_size),\n ToTensor(),\n ]))\n\n def worker_init_fn(worker_id):\n random.seed(args.seed + worker_id)\n\n labeled_idxs = list(range(0, args.labeled_num))\n unlabeled_idxs = list(range(args.labeled_num, args.max_samples))\n batch_sampler = TwoStreamBatchSampler(\n labeled_idxs, unlabeled_idxs, batch_size, batch_size - args.labeled_bs)\n\n trainloader = DataLoader(db_train, batch_sampler=batch_sampler,\n num_workers=4, pin_memory=True, worker_init_fn=worker_init_fn)\n\n optimizer1 = optim.SGD(model1.parameters(), lr=base_lr,\n momentum=0.9, weight_decay=0.0001)\n optimizer2 = optim.SGD(model2.parameters(), lr=base_lr,\n momentum=0.9, weight_decay=0.0001)\n best_performance1 = 0.0\n best_performance2 = 0.0\n iter_num = 0\n ce_loss = CrossEntropyLoss()\n dice_loss = losses.DiceLoss(num_classes)\n\n writer = SummaryWriter(snapshot_path + '/log')\n logging.info(\"{} iterations per epoch\".format(len(trainloader)))\n\n max_epoch = max_iterations // len(trainloader) + 1\n iterator = tqdm(range(max_epoch), ncols=70)\n for epoch_num in iterator:\n for i_batch, sampled_batch in enumerate(trainloader):\n\n volume_batch, label_batch = sampled_batch['image'], sampled_batch['label']\n volume_batch, label_batch = volume_batch.cuda(), label_batch.cuda()\n\n outputs1 = model1(volume_batch)\n outputs_soft1 = torch.softmax(outputs1, dim=1)\n\n outputs2 = model2(volume_batch)\n outputs_soft2 = torch.softmax(outputs2, dim=1)\n consistency_weight = get_current_consistency_weight(iter_num // 150)\n\n loss1 = 0.5 * (ce_loss(outputs1[:args.labeled_bs],\n label_batch[:][:args.labeled_bs].long()) + dice_loss(\n outputs_soft1[:args.labeled_bs], label_batch[:args.labeled_bs].unsqueeze(1)))\n loss2 = 0.5 * (ce_loss(outputs2[:args.labeled_bs],\n label_batch[:][:args.labeled_bs].long()) + dice_loss(\n outputs_soft2[:args.labeled_bs], label_batch[:args.labeled_bs].unsqueeze(1)))\n\n pseudo_outputs1 = torch.argmax(outputs_soft1[args.labeled_bs:].detach(), dim=1, keepdim=False)\n pseudo_outputs2 = torch.argmax(outputs_soft2[args.labeled_bs:].detach(), dim=1, keepdim=False)\n\n pseudo_supervision1 = ce_loss(outputs1[args.labeled_bs:], pseudo_outputs2)\n pseudo_supervision2 = ce_loss(outputs2[args.labeled_bs:], pseudo_outputs1)\n\n model1_loss = loss1 + consistency_weight * pseudo_supervision1\n model2_loss = loss2 + consistency_weight * pseudo_supervision2\n\n loss = model1_loss + model2_loss\n\n optimizer1.zero_grad()\n optimizer2.zero_grad()\n\n loss.backward()\n\n optimizer1.step()\n optimizer2.step()\n\n iter_num = iter_num + 1\n # 更新学习率\n # lr_ = base_lr * (1.0 - iter_num / max_iterations) ** 0.9\n # for param_group1 in optimizer1.param_groups:\n # param_group1['lr'] = lr_\n # for param_group2 in optimizer2.param_groups:\n # param_group2['lr'] = lr_\n\n # writer.add_scalar('lr', lr_, iter_num)\n writer.add_scalar(\n 'consistency_weight/consistency_weight', consistency_weight, iter_num)\n writer.add_scalar('loss/model1_loss',\n model1_loss, iter_num)\n writer.add_scalar('loss/model2_loss',\n model2_loss, iter_num)\n logging.info(\n 'iteration %d : model1 loss : %f model2 loss : %f' % (iter_num, model1_loss.item(), model2_loss.item()))\n\n # if iter_num % 50 == 0:\n # image = volume_batch[0, 0:1, :, :, 20:61:10].permute(\n # 3, 0, 1, 2).repeat(1, 3, 1, 1)\n # grid_image = make_grid(image, 5, normalize=True)\n # writer.add_image('train/Image', grid_image, iter_num)\n\n # image = outputs_soft1[0, 0:1, :, :, 20:61:10].permute(\n # 3, 0, 1, 2).repeat(1, 3, 1, 1)\n # grid_image = make_grid(image, 5, normalize=False)\n # writer.add_image('train/Model1_Predicted_label',\n # grid_image, iter_num)\n\n # image = outputs_soft2[0, 0:1, :, :, 20:61:10].permute(\n # 3, 0, 1, 2).repeat(1, 3, 1, 1)\n # grid_image = make_grid(image, 5, normalize=False)\n # writer.add_image('train/Model2_Predicted_label',\n # grid_image, iter_num)\n\n # image = label_batch[0, :, :, 20:61:10].unsqueeze(\n # 0).permute(3, 0, 1, 2).repeat(1, 3, 1, 1)\n # grid_image = make_grid(image, 5, normalize=False)\n # writer.add_image('train/Groundtruth_label',\n # grid_image, iter_num)\n\n # if iter_num % 20 == 0:\n if iter_num > 800 and iter_num % 200 == 0:\n # 测试并保存模型一\n model1.eval()\n if args.dataset_name == \"LA\":\n dice_sample1 = test_patch.var_all_case(model1, num_classes=num_classes, patch_size=args.patch_size,\n stride_xy=18, stride_z=4, dataset_name='LA')\n elif args.dataset_name == \"Pancreas\":\n dice_sample1 = test_patch.var_all_case(model1, num_classes=num_classes, patch_size=args.patch_size,\n stride_xy=16, stride_z=16, dataset_name='Pancreas')\n elif args.dataset_name == \"BraTS\":\n dice_sample1 = test_patch.var_all_case(model1, num_classes=num_classes, patch_size=args.patch_size,\n stride_xy=64, stride_z=64, dataset_name='BraTS')\n elif args.dataset_name == \"Prostate\":\n dice_sample1 = test_patch.var_all_case(model1, num_classes=num_classes, patch_size=args.patch_size,\n stride_xy=18, stride_z=4, dataset_name='Prostate')\n\n if dice_sample1 > best_performance1:\n best_performance1 = dice_sample1\n save_mode_path = os.path.join(snapshot_path, 'model1_iter_{}_dice_{}.pth'.format(iter_num, best_performance1))\n save_best_path = os.path.join(snapshot_path, '{}_best_model1.pth'.format(args.model_name))\n torch.save(model1.state_dict(), save_mode_path)\n torch.save(model1.state_dict(), save_best_path)\n logging.info(\"save best model1 to {}\".format(save_mode_path))\n writer.add_scalar('Var_dice/Dice', dice_sample1, iter_num)\n writer.add_scalar('Var_dice/Best_dice', best_performance1, iter_num)\n model1.train()\n\n # 测试并保存模型二\n model2.eval()\n if args.dataset_name == \"LA\":\n dice_sample2 = test_patch.var_all_case(model2, num_classes=num_classes, patch_size=args.patch_size,\n stride_xy=18, stride_z=4, dataset_name='LA')\n elif args.dataset_name == \"Pancreas\":\n dice_sample2 = test_patch.var_all_case(model2, num_classes=num_classes, patch_size=args.patch_size,\n stride_xy=16, stride_z=16, dataset_name='Pancreas')\n elif args.dataset_name == \"BraTS\":\n dice_sample2 = test_patch.var_all_case(model2, num_classes=num_classes, patch_size=args.patch_size,\n stride_xy=64, stride_z=64, dataset_name='BraTS')\n elif args.dataset_name == \"Prostate\":\n dice_sample2 = test_patch.var_all_case(model2, num_classes=num_classes, patch_size=args.patch_size,\n stride_xy=18, stride_z=4, dataset_name='Prostate')\n if dice_sample2 > best_performance2:\n best_performance2 = dice_sample2\n save_mode_path = os.path.join(snapshot_path, 'model2_iter_{}_dice_{}.pth'.format(iter_num, best_performance2))\n save_best_path = os.path.join(snapshot_path, '{}_best_model2.pth'.format(args.model_name))\n torch.save(model2.state_dict(), save_mode_path)\n torch.save(model2.state_dict(), save_best_path)\n logging.info(\"save best model2 to {}\".format(save_mode_path))\n writer.add_scalar('Var_dice/Dice', dice_sample2, iter_num)\n writer.add_scalar('Var_dice/Best_dice', best_performance2, iter_num)\n model2.train()\n\n if iter_num % 3000 == 0:\n save_mode_path = os.path.join(\n snapshot_path, 'model1_iter_' + str(iter_num) + '.pth')\n torch.save(model1.state_dict(), save_mode_path)\n logging.info(\"save model1 to {}\".format(save_mode_path))\n\n save_mode_path = os.path.join(\n snapshot_path, 'model2_iter_' + str(iter_num) + '.pth')\n torch.save(model2.state_dict(), save_mode_path)\n logging.info(\"save model2 to {}\".format(save_mode_path))\n\n if iter_num >= max_iterations:\n break\n time1 = time.time()\n if iter_num >= max_iterations:\n iterator.close()\n break\n writer.close()\n\n\nif __name__ == \"__main__\":\n if not args.deterministic:\n cudnn.benchmark = True\n cudnn.deterministic = False\n else:\n cudnn.benchmark = False\n cudnn.deterministic = True\n\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n torch.cuda.manual_seed(args.seed)\n\n snapshot_path = \"model/{}_{}/{}\".format(args.dataset_name, args.labeled_num, args.model_name)\n if not os.path.exists(snapshot_path):\n os.makedirs(snapshot_path)\n\n logging.basicConfig(filename=snapshot_path+\"/log.txt\", level=logging.INFO,\n format='[%(asctime)s.%(msecs)03d] %(message)s', datefmt='%H:%M:%S')\n logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))\n logging.info(str(args))\n train(args, snapshot_path)","repo_name":"Fyw1988/SemiSeg","sub_path":"train_CPS.py","file_name":"train_CPS.py","file_ext":"py","file_size_in_byte":16790,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"26158962110","text":"from rest_framework import viewsets\nfrom rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly\nfrom .models import Teacher\nfrom .serializers import TeacherListSerializer, TeacherSerializer\n\n\nclass TeacherView(viewsets.ModelViewSet):\n permission_classes = [DjangoModelPermissionsOrAnonReadOnly]\n queryset = Teacher.objects.all()\n serializer_class = TeacherSerializer\n lookup_field = 'slug'\n list_serializer_class = TeacherListSerializer\n\n def get_serializer_class(self):\n if self.action == 'list':\n if hasattr(self, 'list_serializer_class'):\n return self.list_serializer_class\n\n return super(TeacherView, self).get_serializer_class()\n","repo_name":"hsb-tonmoy/engmedapp-django","sub_path":"teacher_db/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"34202401048","text":"import numpy as np\nfrom layer import Layer\nclass ConvolutionLayer(Layer):\n\t'''\n\tFor two demensional convolution\n\t'''\n\tdef __init__(self,filters,kernel,stride,pad,activator):\n\t\tsuper(ConvolutionLayer,self).__init__()\n\t\tself.filters=filters\n\t\t#kernel:[kernel_h,kernel_w],values of kernel size \n\t\t#should be odd,in order to make padding simple\n\t\tself.kernel=kernel\n\t\t#stride:[stride_h,stride_w]\n\t\tself.stride=stride\n\t\t#padding:'same','valid'\n\t\tself.pad=pad\n\t\tself.activator=activator\n\t\tself.__kernels=np.random.randn(self.filters,self.kernel[0],self.kernel[1])\n\t\tself.__bias=np.random.randn(self.filters)\n\tdef get_patch(self,data,i,j):\n\t\tsi=i*self.stride[0]\n\t\tsj=j*self.stride[1]\n\t\treturn data[:,si:si+self.kernel[0],sj:sj+self.kernel[1]]\n\tdef conv2D(self,_input,kernel,output,bi):\n\t\t[oh,ow]=output.shape\n\t\tfor i in range(oh):\n\t\t\tfor j in range(ow):\n\t\t\t\toutput[i,j]=np.sum(self.get_patch(_input,i,j)*kernel)+bi\n\tdef padding(self,_input):\n\t\t[m,ic,ih,iw]=_input.shape\n\t\tpad_h=(self.kernel[0]-1)/2\n\t\tpad_w=(self.kernel[1]-1)/2\n\t\tif self.pad=='same':\n\t\t\tpad_output=np.zeros((m,ic,ih+pad_h*2,iw+pad_w*2))\n\t\t\tpad_output[:,:,pad_h:pad_h+ih,pad_w:pad_w+iw]=_input\n\t\t\treturn pad_output\n\t\telif self.pad=='valid':\n\t\t\treturn _input\n\t\telse:\n\t\t\traise Exception('Only \\'same\\' and \\'valid\\' are implemented.')\n\tdef forward(self,_input):\n\t\t#m:number of input samples\n\t\t#ic:input channel\n\t\t#ih:input height\n\t\t#iw:input width\n\t\t[m,ic,ih,iw]=_input.shape\n\t\tself.__input=self.padding(_input)\n\t\t[pm,pc,ph,pw]=self.__input.shape\n\t\t#calculate output size\n\t\toh=(ph-self.kernel[0])//self.stride[0]+1\n\t\tow=(pw-self.kernel[1])//self.stride[1]+1\n\t\tself.__unactivate_output=np.zeros((m,self.filters,oh,ow))\n\t\t#forward propagation\n\t\tfor item in range(m):\n\t\t\tfor nf in range(self.filters):\n\t\t\t\tself.conv2D(self.__input[item,:,:,:],self.__kernels[nf],self.__unactivate_output[item,nf,:,:],self.__bias[nf])\n\t\treturn self._activation(self.activator,self.__unactivate_output)\n\tdef flip_w(self,w):\n\t\treturn np.fliplr(np.flipud(w))\n\tdef expand(self,feature_map):\n\t\t[m,fc,fh,fw]=feature_map.shape\n\t\t[pm,pc,ph,pw]=self.__input.shape\n\t\teh=ph-self.kernel[0]+1\n\t\tew=pw-self.kernel[1]+1\n\t\texpand_feature=np.zeros((m,fc,eh,ew))\n\t\tfor i in range(fh):\n\t\t\tfor j in range(fw):\n\t\t\t\texpand_feature[:,:,i*self.stride[0],j*self.stride[1]]=feature_map[:,:,i,j]\n\t\treturn expand_feature\n\tdef back(self,error,learning_rate):\n\t\t#calculate delta^(l)\n\t\terror=error*self._activation_prime(self.activator,self.__unactivate_output)\n\t\t#back to stride[1,1]\n\t\terror=self.expand(error)\n\t\t[em,echannel,eh,ew]=error.shape\n\t\t#calculate gradient\n\t\tgradient_w=np.zeros((self.filters,self.kernel[0],self.kernel[1]))\n\t\tgradient_b=np.zeros(self.filters)\n\t\tfor n in range(self.filters):\n\t\t\tfor i in range(self.kernel[0]):\n\t\t\t\tfor j in range(self.kernel[1]):\n\t\t\t\t\tgradient_w[n,i,j]=np.sum(self.__input[:,:,i:i+eh,j:j+eh]*error[:,n,:,:])\n\t\t\tgradient_b[n]=np.sum(error[:,n,:,:])\n\t\t#calculate back error\n\t\t[im,ichannel,ih,iw]=self.__input.shape\n\t\tback_error=np.zeros(self.__input.shape)\n\t\t#padding inorder to get same size of input array\n\t\terror=self.padding(error)\n\t\tpad_error=self.padding(error)\n\t\tsh=self.stride[0]\n\t\tsw=self.stride[1]\n\t\tself.stride[0]=self.stride[1]=1\n\t\tfor item in range(em):\n\t\t\tfor ic in range(ichannel):\n\t\t\t\tfor ec in range(echannel):\n\t\t\t\t\tself.conv2D(pad_error[item,:,:,:],self.flip_w(self.__kernels[ec,:,:]),back_error[item,ic,:,:],0)\n\t\tself.stride[0]=sh\n\t\tself.stride[1]=sw\n\t\t#update\n\t\tself.__kernels-=learning_rate*gradient_w\n\t\tself.__bias-=learning_rate*gradient_b\n\t\treturn back_error\n","repo_name":"Leeying1235/deep-learning","sub_path":"src/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":3531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"17680060503","text":"from datetime import datetime, timedelta\r\nimport math\r\nimport time\r\nimport os\r\nfrom types import NoneType\r\n\r\n\r\ndef cls():\r\n #Funktion för att rensa konsollen\r\n os.system('cls' if os.name=='nt' else 'clear')\r\n \r\ndef round_down_to_nearest_half_int(num):\r\n #Funktion som senare kommer avrunda timmarna till halvor (exempel:'1,5', '1.0' '8,5')\r\n #Använder math.floor för att avrunda timmarna nedåt\r\n return math.floor(num * 2) / 2\r\n\r\ndef get_wage():\r\n #Funktion som ber användaren om deras timlön\r\n while True:\r\n try:\r\n hourly_wage = int(input(\"\\nWhat is your hourly wage?: \"))\r\n return hourly_wage\r\n except ValueError:\r\n print(\"\\nInvalid amount\")\r\n\r\ndef get_weekday():\r\n #Funktion som redogör viken dag det är\r\n weekdays_dict = {\r\n 1: \"Monday\",\r\n 2: \"Tuesday\",\r\n 3: \"Wednesday\",\r\n 4: \"Thursday\",\r\n 5: \"Friday\",\r\n 6: \"Saturday\",\r\n 7: \"Sunday\"\r\n }\r\n day = 0\r\n while day < 1 or day > 7:\r\n try:\r\n day = int(input(\"\\nWhat day is it? ('Monday' = 1,), (1-7): \"))\r\n except ValueError:\r\n print(\"\\nEnter a number\")\r\n for i in weekdays_dict:\r\n if i == day:\r\n weekday = weekdays_dict[day]\r\n return weekday\r\n\r\ndef get_hours():\r\n #Få ut differensen mellan arbetstimmarna\r\n while True:\r\n try:\r\n start_time = input(\"Enter time for start of workday.('00:00'): \")\r\n end_time = input(\"\\nEnter time for end of workday.('00:00'): \")\r\n time_format = '%H:%M'\r\n diff = timedelta\r\n #Om man jobbar skriver att man jobbar över 24:00\r\n if start_time > end_time:\r\n print(\"You can't overlap workdays. Program will restart in 3 seconds...\")\r\n time.sleep(3)\r\n cls()\r\n break\r\n #Differensen mellan sluttiden och starttiden\r\n else: \r\n diff = datetime.strptime(end_time, time_format) - datetime.strptime(start_time, time_format)\r\n #Vi får ut differensen i sekunder och omvandlar till timmar\r\n hour_diff = diff.total_seconds() / 3600\r\n #Om man jobbar över 12 timmar \r\n if hour_diff > 12:\r\n hour_diff = 12\r\n print(\"\\nYou will not recieve additional payment for work over 12 hours.\")\r\n return hour_diff\r\n except ValueError:\r\n #datetime tillåter inte 24:00 utan bara 00:00....\r\n if end_time == \"24:00\":\r\n print(\"You can only be paid till 23:59\\n\")\r\n else:\r\n print(\"\\nInvalid time\")\r\n except AttributeError:\r\n print(\"You can only be paid till 23:59\\n\")\r\n else:\r\n return round_down_to_nearest_half_int(hour_diff)\r\n \r\ndef get_payment():\r\n work_hours = get_hours()\r\n while type(work_hours) == NoneType:\r\n work_hours = get_hours()\r\n hourly_wage = get_wage()\r\n weekday = get_weekday()\r\n hardship_time = work_hours - 8\r\n hourly_multiplier = 1\r\n \r\n #Räkna ut ob om det är helg\r\n if weekday == \"Saturday\" or weekday == \"Sunday\":\r\n hourly_multiplier = 2\r\n \r\n #Räkna ut ob för arbete över 8 timmar. OBS inte på helger\r\n if work_hours > 8 and hourly_multiplier != 2:\r\n hourly_multiplier = 1.5\r\n payment = hourly_wage * 8 + (hourly_wage * hourly_multiplier * hardship_time)\r\n else:\r\n payment = hourly_wage * work_hours * hourly_multiplier\r\n \r\n print(f\"\\nYou are being paid for {work_hours} hours on a {weekday} with a hourly wage\"\\\r\n f\" of {hourly_wage} kr.\\n\\nYour salary for the day is: {payment} kr.\")\r\n\r\nget_payment()","repo_name":"mildrikk/python","sub_path":"Inlämningsuppgift_3.py","file_name":"Inlämningsuppgift_3.py","file_ext":"py","file_size_in_byte":3807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"44238667220","text":"from __future__ import annotations\nimport sqlite3\nfrom typing import Optional, Dict, Any, List, Tuple, Union\nfrom toolkit.fileutils import Fileutils\n\n\nclass DatabaseHandler:\n def __init__(self, db_name: str) -> None:\n mtime = Fileutils().get_file_mtime(db_name)\n self.connection = sqlite3.connect(db_name)\n self.cursor = self.connection.cursor()\n if mtime == \"file_not_found\":\n self.create_table(\"spread\",\n [\"id INTEGER PRIMARY KEY\",\n \"name TEXT\", \"capital INTEGER\",\n \"mtm INTEGER\", \"tp INTEGER\",\n \"sl INTEGER\", \"max_mtm INTEGER\",\n \"trail_after INTEGER\",\n \"trail_at INTEGER\", \"status INTEGER\",\n \"created_at DATETIME DEFAULT CURRENT_TIMESTAMP\"])\n self.create_table(\"items\",\n [\"id INTEGER PRIMARY KEY\",\n \"spread_id TEXT\", \"symbol TEXT\",\n \"exchange TEXT\", \"entry REAL\",\n \"side INTEGER\", \"quantity INTEGER\",\n \"mtm INTEGER\", \"ltp REAL\"])\n self.create_table(\"user\",\n [\"id INTEGER PRIMARY KEY\",\n \"broker_id TEXT\",\n \"user TEXT\"])\n self.create_table(\"spread_user\",\n [\"id INTEGER PRIMARY KEY\",\n \"spread_id INTEGER\",\n \"broker_id TEXT\"])\n\n def disconnect(self) -> None:\n try:\n if self.connection:\n self.connection.close()\n except sqlite3.Error as e:\n print(f\"Error disconnecting from the database: {e}\")\n\n def execute_query(self,\n query: str,\n params: Optional[Tuple[Any, Any]] = None\n ) -> None:\n try:\n if self.cursor:\n if params:\n self.cursor.execute(query, params)\n\n else:\n self.cursor.execute(query)\n\n self.connection.commit()\n except sqlite3.Error as e:\n print(f\"Error executing query: {e}\")\n\n def fetch_data(\n self, query: str,\n params: Optional[Tuple[Any, ...]] = None\n ) -> List[Dict[str, Any]]:\n try:\n if self.cursor:\n if params:\n self.cursor.execute(query, params)\n else:\n self.cursor.execute(query)\n\n # Get the column names from the cursor description\n column_names = [column[0]\n for column in self.cursor.description]\n\n # Fetch rows and convert each row into a dictionary\n rows = self.cursor.fetchall()\n result = [dict(zip(column_names, row)) for row in rows]\n return result\n except sqlite3.Error as e:\n print(f\"Error fetching data: {e}\")\n return []\n\n def create_table(self, table_name: str, columns: List[str]) -> None:\n try:\n query = f\"CREATE TABLE IF NOT EXISTS {table_name} \\\n ({', '.join(columns)})\"\n self.execute_query(query)\n except sqlite3.Error as e:\n print(f\"Error creating table: {e}\")\n\n def insert_data(self, table_name: str, data: Dict[str, Any]) -> None:\n try:\n columns = ', '.join(data.keys())\n placeholders = ', '.join(['?'] * len(data))\n query = f\"INSERT INTO {table_name} ({columns}) \\\n VALUES ({placeholders})\"\n self.execute_query(query, tuple(data.values()))\n except sqlite3.Error as e:\n print(f\"Error inserting data: {e}\")\n\n def update_data(self, table_name: str, item_id: Union[int, str], data: Dict[str, Any]):\n try:\n if isinstance(data, dict):\n set_values = \", \".join(f\"{key} = ?\" for key in data.keys())\n query = f\"UPDATE {table_name} SET {set_values} WHERE id = ?\"\n params = list(data.values()) + [item_id]\n self.execute_query(query, params)\n else:\n raise ValueError(\"Data must be a dictionary\")\n except sqlite3.Error as e:\n print(f\"Error updating data: {e}\")\n except Exception as e:\n print(f\"value error {e}\")\n\n def drop_table(self, table_name: str) -> None:\n try:\n query = f\"DROP TABLE IF EXISTS {table_name}\"\n self.execute_query(query)\n except sqlite3.Error as e:\n print(f\"Error dropping table: {e}\")\n\n\nif __name__ == \"__main__\":\n # Create an instance of the DatabaseHandler\n handler = DatabaseHandler(\"../../../../spread.db\")\n # Before creating the triggers, set the recursive_triggers pragma to ON\n handler.drop_table(\"spread\")\n handler.drop_table(\"items\")\n handler.drop_table(\"user\")\n handler.drop_table(\"spread_user\")\n\n \"\"\"\n create tables\n \"\"\"\n handler.create_table(\"spread\",\n [\"id INTEGER PRIMARY KEY\",\n \"name TEXT\", \"capital INTEGER\",\n \"mtm INTEGER\", \"tp INTEGER\",\n \"sl INTEGER\", \"max_mtm INTEGER\",\n \"trail_after INTEGER\",\n \"trail_at INTEGER\", \"status INTEGER\",\n \"created_at DATETIME DEFAULT CURRENT_TIMESTAMP\"])\n # Create the \"items\" table\n handler.create_table(\"items\", [\"id INTEGER PRIMARY KEY\", \"token TEXT\",\n \"spread_id INTEGER\", \"symbol TEXT\",\n \"exchange TEXT\", \"entry REAL\",\n \"side INTEGER\", \"quantity INTEGER\",\n \"mtm INTEGER\", \"ltp REAL\"])\n handler.create_table(\"user\",\n [\"id INTEGER PRIMARY KEY\",\n \"broker_id TEXT\",\n \"user TEXT\"])\n handler.create_table(\"spread_user\",\n [\"id INTEGER PRIMARY KEY\",\n \"spread_id INTEGER\",\n \"broker_id TEXT\"])\n spread_data_1 = {\n \"name\": \"First Spread\",\n \"capital\": -176,\n \"mtm\": 0,\n \"tp\": 80,\n \"sl\": 50,\n \"max_mtm\": 0,\n \"trail_after\": 50,\n \"trail_at\": 40,\n \"status\": 1}\n handler.insert_data(\"spread\", spread_data_1)\n \"\"\"\n items_data_1 = {\n \"spread_id\": 1,\n \"token\": \"73311\",\n \"symbol\": \"HINDALCO31AUG23440PE\",\n \"exchange\": \"NFO\",\n \"entry\": 0.5,\n \"side\": -1,\n \"quantity\": 1,\n \"mtm\": 0.5,\n \"ltp\": 0.5\n }\n items_data_2 = {\n \"spread_id\": 1,\n \"token\": \"73310\",\n \"symbol\": \"HINDALCO31AUG23445CE\",\n \"exchange\": \"NFO\",\n \"entry\": 176,\n \"side\": -1,\n \"quantity\": 1,\n \"mtm\": 0,\n \"ltp\": 176\n }\n handler.insert_data(\"items\", items_data_1)\n handler.insert_data(\"items\", items_data_2)\n \"\"\"\n query = \"\"\"\n SELECT items.*\n FROM items\n INNER JOIN spread ON items.spread_id = spread.id\n \"\"\"\n items = handler.fetch_data(query, )\n\n for item in items:\n print(item)\n\n \"\"\"\n UPDATE\n updated_item_1 = {\n \"exchange\": \"NFO\",\n \"token\": \"127900\",\n \"ltp\": 120 # Updated ltp value\n }\n updated_item_2 = {\n \"exchange\": \"NFO\",\n \"token\": \"127901\",\n \"ltp\": 130 # Updated ltp value\n }\n # Update the row, excluding the 'mtm' field\n # query = \"\"\"\n # UPDATE items\n # SET ltp = :ltp\n # WHERE exchange = :exchange and token = :token\n # \"\"\"\n \"\"\"\n handler.execute_query(query, updated_item_1)\n handler.execute_query(query, updated_item_2)\n \"\"\"\n # Fetch the updated data from the \"items\" table\n query = \"SELECT * FROM items\"\n updated_items = handler.fetch_data(query, )\n\n query = \"\"\"\n SELECT spread.*\n FROM spread\n where status >= 0\n \"\"\"\n spreads = handler.fetch_data(query, )\n\n # Insert Users\n users_data = [\n {\"broker_id\": \"A1079542\", \"user\": \"AnjuAgrawal\"},\n {\"broker_id\": \"K583959\", \"user\": \"KALPANAKATH\"},\n {\"broker_id\": \"PETT1665\", \"user\": \"MAHESHKAATH\"},\n {\"broker_id\": \"S1521310\", \"user\": \"SANDEEPAWAL\"},\n {\"broker_id\": \"DESV1032\", \"user\": \"HARSHITBONI\"},\n {\"broker_id\": \"P824460\", \"user\": \"Priyankarya\"},\n {\"broker_id\": \"PETT1707\", \"user\": \"SANDEEPAHUF\"},\n {\"broker_id\": \"R1001548\", \"user\": \"RaghavAgwal\"},\n {\"broker_id\": \"D537510\", \"user\": \"DoyalKayyal\"},\n ]\n for user_data in users_data:\n query = \"INSERT INTO user (broker_id, user) VALUES (?, ?)\"\n params = (user_data[\"broker_id\"], user_data[\"user\"])\n handler.execute_query(query, params)\n\n # Create Spread User table\n handler.create_table(\"spread_user\",\n [\"id INTEGER PRIMARY KEY\",\n \"spread_id INTEGER\",\n \"broker_id TEXT\"])\n\n # Print the retrieved items\n for spread in spreads:\n print(spread)\n # Print the updated item\n for item in updated_items:\n print(item)\n # Disconnect from the database\n handler.disconnect()\n","repo_name":"pannet1/dealer-web","sub_path":"dealer_web/sqlite/database_handler.py","file_name":"database_handler.py","file_ext":"py","file_size_in_byte":9454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"26714788657","text":"from django import forms\nfrom .models import Article\nfrom django.core.exceptions import ValidationError\n\nclass ArticleForm(forms.ModelForm):\n class Meta:\n model = Article\n fields = ['title', 'content']\n def clean_title(self):\n title = self.cleaned_data['title']\n if '*' in title:\n raise ValidationError('*은 제목에 들어갈 수 없습니다.')\n return title","repo_name":"tnpfldyd/TIL","sub_path":"django/20221004/articles/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"18864244318","text":"# import tkinter as tk\n# from tkinter import ttk\n\n# # Fungsi yang akan dijalankan saat tombol diklik\n# def button_click():\n# print(\"Tombol diklik\")\n\n# # Membuat instance Tkinter\n# root = tk.Tk()\n\n# # Mengatur gaya dan desain kustom\n# style = ttk.Style()\n# style.configure('TButton', background='green', foreground='red', font=('Arial', 12, 'bold'))\n\n# # Membuat tombol dengan gaya kustom\n# button = ttk.Button(root, text=\"Tombol\", style='TButton', command=button_click)\n# button.pack(padx=10, pady=5)\n\n# # Menjalankan aplikasi Tkinter\n# root.mainloop()\n\n# import tkinter as tk\n\n# # Membuat instance Tkinter\n# root = tk.Tk()\n\n# # Mengatur warna latar belakang jendela\n# root.configure(background='green')\n\n# # Menjalankan aplikasi Tkinter\n# root.mainloop()\n\n# import tkinter as tk\n\n# # Membuat instance Tkinter\n# root = tk.Tk()\n\n# # Membuat frame untuk konten\n# content_frame = tk.Frame(root)\n# content_frame.pack(side=\"left\", fill=\"both\", expand=True)\n\n# # Mengatur warna latar belakang content_frame\n# content_frame.configure(background='green')\n\n# # Menjalankan aplikasi Tkinter\n# root.mainloop()\n# Import the library\nfrom tkinter import *\nfrom tkinter import filedialog\n\n# Create an instance of window\nwin=Tk()\n\n# Set the geometry of the window\nwin.geometry(\"700x350\")\n\n# Create a frame widget\nframe=Frame(win, width=300, height=300)\nframe.grid(row=0, column=0, sticky=\"NW\")\n\n# Create a label widget\nlabel=Label(win, text=\"I am inside a Frame\", font='Arial 17 bold')\nlabel.place(relx=0.5, rely=0.5, anchor=CENTER)\n\nwin.mainloop()","repo_name":"matlbert/skripsi","sub_path":"tes.py","file_name":"tes.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"5066992319","text":"#\r\n# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).\r\n# All rights reserved.\r\n# This component and the accompanying materials are made available\r\n# under the terms of \"Eclipse Public License v1.0\"\r\n# which accompanies this distribution, and is available\r\n# at the URL \"http://www.eclipse.org/legal/epl-v10.html\".\r\n#\r\n# Initial Contributors:\r\n# Nokia Corporation - initial contribution.\r\n#\r\n# Contributors:\r\n#\r\n# Description: \r\n#\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n import nose\r\n setuptools_incompat = ('report', 'prepareTest',\r\n 'prepareTestLoader', 'prepareTestRunner',\r\n 'setOutputStream')\r\n\r\n plugins = nose.plugins.manager.RestrictedPluginManager(exclude=setuptools_incompat)\r\n allfiles = nose.config.all_config_files() + ['nose_unittests.cfg']\r\n conf = nose.config.Config(files=allfiles,\r\n plugins=plugins)\r\n conf.configure(argv=['collector'])\r\n nose.main(config=conf)\r\n\r\n","repo_name":"SymbianSource/oss.FCL.sftools.depl.swconfigmdw","sub_path":"configurationengine/source/cone/runtests.py","file_name":"runtests.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"29234326126","text":"import os\nimport numpy as np\nimport pandas as pd\n\nfrom ConfLearning.recovery.gen_design_sim import GenDesign\nfrom pathlib import Path\n\ngen_data = True\nuse_10 = False\nndatasets = 500\n\nif not os.path.exists('../plot/data/para_experiment'):\n os.makedirs('../plot/data/para_experiment')\n\npath_save = os.path.join(Path.cwd(), '../plot/data/para_experiment/')\n\nif gen_data == True:\n\n GenDesign.factor = 10 if use_10 else 1\n genDesign = GenDesign()\n\n for n in np.arange(ndatasets):\n print(f'n {n + 1} / {ndatasets}')\n\n np.random.seed(n)\n experiment = genDesign.generate()\n\n if use_10:\n experiment.to_pickle(os.path.join(path_save, \"experimental_sim_\" + str(n) + \"_10.pkl\"), protocol=4)\n else:\n experiment.to_pickle(os.path.join(path_save, \"experimental_sim_\" + str(n) + \".pkl\"), protocol=4)\n\n\nnblocks = 110 if use_10 else 11\nnphases = 3\nntrials = 18\nnbandits = 5\n\nstim_left = np.full((ndatasets, nblocks, nphases, ntrials), np.nan, float)\nstim_right = np.full((ndatasets, nblocks, nphases, ntrials), np.nan, float)\n\nhistory_constraint = np.full((ndatasets, nblocks, nphases, ntrials), np.nan, bool)\ncorrect_value = np.full((ndatasets, nblocks, nphases, ntrials), np.nan, float)\n\n\nclass ExtractData:\n\n def __init__(self):\n\n self.data = None\n self.df = None\n\n self.stim_l = np.full((nblocks, nphases, ntrials), np.nan, float)\n self.stim_r = np.full((nblocks, nphases, ntrials), np.nan, float)\n\n self.history_con = np.full((nblocks, nphases, ntrials), np.nan, bool)\n self.correct_val = np.full((nblocks, nphases, ntrials), np.nan, float)\n\n def extract_data(self, dataset):\n \"\"\"loops through dataframe to extract relevant arrays for subsequent fitting\"\"\"\n\n self.data = dataset\n\n for one, b in enumerate(self.data.block.unique()):\n for two, p in enumerate(self.data[(self.data.block == b) & (~self.data[~self.data.phase.isna()].phase.isna())].phase.unique()):\n for three, t in enumerate(self.data[(self.data.block == b) & (self.data[~self.data.phase.isna()].phase == p) & self.data.type_choice_obs].trial_phase.astype(int).values):\n\n self.df = self.data[(self.data.block == b) & (self.data.phase == p) & (self.data.trial_phase == t)]\n\n self.stim_l[b, p, t] = self.df.stimulus_left.values[0]\n self.stim_r[b, p, t] = self.df.stimulus_right.values[0]\n\n self.history_con[b, p, t] = self.df.pre_equalshown_secondlasttrial.values[0]\n self.correct_val[b, p, t] = self.df.type_choice.values[0]\n\n return self.stim_l, self.stim_r, self.history_con, self.correct_val\n\n\nif __name__ == '__main__':\n\n data = ExtractData()\n\n for i in np.arange(0, ndatasets):\n\n print(f'i {i + 1} / {ndatasets}')\n\n if use_10:\n matrix = pd.read_pickle(os.path.join(path_save, 'experimental_sim_' + str(i) + '_10.pkl'))\n else:\n matrix = pd.read_pickle(os.path.join(path_save, 'experimental_sim_' + str(i) + '.pkl'))\n\n stim_left[i, :], stim_right[i, :], history_constraint[i, :], correct_value[i, :] = data.extract_data(matrix)\n\n variables = ['stim_left', 'stim_right', 'history_constraint', 'correct_value']\n\n for v, var in enumerate(variables):\n if use_10:\n np.save(os.path.join(path_save, f'{var}_10'), eval(var))\n else:\n np.save(os.path.join(path_save, f'{var}'), eval(var))\n","repo_name":"eptas/ConfLearning","sub_path":"revision2/gen_data.py","file_name":"gen_data.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"33961584098","text":"class Solution:\n def countPrimes(self, n: int):\n if n < 2:\n return 0\n strikes = [1] * n\n strikes[0] = 0\n strikes[1] = 0\n for i in range(2, int(n**0.5)+1):\n if strikes[i] != 0:\n strikes[i*i:n:i] = [0] * ((n-1-i*i)//i + 1)\n\n return sum(strikes)\n","repo_name":"aishuo07/DSA-Practice","sub_path":"count-primes/count-primes.py","file_name":"count-primes.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"780377690","text":"#!/usr/bin/env python3\n\"\"\" qtpyt is the a python package for quantum transport simulations.\"\"\"\nDOCLINES = (__doc__ or \"\").split(\"\\n\")\n\nimport os\nimport sys\n\nimport pkg_resources\n\nif sys.version_info[:2] < (3, 7):\n raise RuntimeError(\"Python version >= 3.7 required.\")\n\nfrom distutils.command.build_ext import build_ext\n\nfrom setuptools import Extension, find_packages, setup\n\nmacros = [(\"NPY_NO_DEPRECATED_API\", \"0\")]\n\nextensions = []\n\ntry:\n import Cython\n\n USE_CYTHON = True\nexcept:\n USE_CYTHON = False\n\nsuffix = \".pyx\" if USE_CYTHON else \".c\"\n\nif USE_CYTHON:\n from Cython.Build import cythonize\n\next_cython = {\n \"qtpyt.surface._recursive\": {},\n}\n\nextra_compile_args = [\"-fopenmp\", \"-march=native\", \"-O3\"] # , \"-ffast-math\"]\nextra_link_args = [\"-fopenmp\"]\n\nnp_incl = pkg_resources.resource_filename(\"numpy\", \"core/include\")\n\nfor ext_name, ext_dict in ext_cython.items():\n\n source = ext_name.replace(\".\", os.path.sep) + suffix\n ext = Extension(\n ext_name,\n sources=[source] + ext_dict.get(\"sources\", []),\n include_dirs=[np_incl] + ext_dict.get(\"include\", []),\n define_macros=macros + ext_dict.get(\"macros\", []),\n extra_compile_args=extra_compile_args,\n extra_link_args=extra_link_args,\n )\n\n if USE_CYTHON:\n extensions += cythonize(ext, quiet=False)\n\n else:\n extensions.append(ext)\n\nNAME = \"qtpyt\"\nVERSION = \"0.5.3\"\nURL = \"https://gitlab.ethz.ch/ggandus/qtpyt.git\"\n\nAUTHOR = \"Guido Gandus\"\nEMAIL = \"gandusgui@gmail.com\"\n\nLICENSE = \"MIT License\"\n\n\ndef readme():\n if not os.path.exists(\"README.md\"):\n return \"\"\n return open(\"README.md\", \"r\").read()\n\n\nrequires = {\n \"python_requires\": \">= \" + \"3.7\",\n \"install_requires\": [\n \"setuptools\",\n \"numpy >= \" + \"1.21\" + \",<1.22\",\n \"scipy\",\n \"numba >= \" + \"0.55\",\n \"ase\",\n ],\n \"setup_requires\": [\"numpy >= \" + \"1.21\",],\n}\n\nmetadata = dict(\n name=\"qtpyt\",\n description=DOCLINES[0],\n long_description=readme(),\n url=\"https://gitlab.ethz.ch/ggandus/qtpyt.git\",\n author=AUTHOR,\n author_email=EMAIL,\n license=LICENSE,\n platforms=\"any\",\n test_suite=\"pytest\",\n version=VERSION,\n cmdclass={\"build_ext\": build_ext},\n zip_safe=False,\n packages=find_packages(include=[\"qtpyt\", \"qtpyt.*\", \"qttools\", \"qttools.*\"]),\n entry_points={\"console_scripts\": [\"qt-cp2k = qttools.cp2k.prepare_kpts:main\"]},\n ext_modules=extensions,\n **requires\n)\n\n\nif __name__ == \"__main__\":\n setup(**metadata)\n","repo_name":"gandusgui/qtpyt","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"27845134909","text":"\nimport socket\n\nclass Node:\n buffer = 1024\n def __init__(self, conn):\n self.conn = conn\n self.ok = b'@ROK#'\n \n def save(self):\n started = True\n self.data = []\n tmp = self.conn.recv(self.buffer)\n while tmp != b'DONE':\n self.data.append(tmp)\n if started:\n self.conn.send(b'@SOK#')\n started = False\n else:\n self.conn.send(self.ok)\n tmp = self.conn.recv(self.buffer)\n\n def save_blue(self):\n self.data = []\n tmp = self.conn.recv(self.buffer)\n while tmp != b'done\\r\\n':\n self.data.append(tmp)\n self.conn.send(self.ok)\n tmp = self.conn.recv(self.buffer)\n\n def pars_filedata(self):\n try:\n return self.data[1:]\n except IndexError:\n return None\n\n def command(self):\n return self.data[0].decode(\"euc-kr\")\n\n def getData(self):\n return [x.decode(\"euc-kr\") for x in self.data[1:]]\n\n def sendData(self, data):\n datas = [data[i:i+self.buffer] for i in range(0, len(data), self.buffer)]\n for i in datas:\n #i = b'@' + i + b'#'\n self.conn.send(i)\n self.conn.recv(self.buffer)\n self.conn.send(b'@DONE#')\n\n def sendIMG(self, data):\n datas = [data[i:i+self.buffer - 7] for i in range(0, len(data), self.buffer - 7)]\n for i in datas:\n i = b'@IMG' + i + b'###'\n self.conn.send(i)\n x = self.conn.recv(self.buffer)\n self.conn.send(b'@DONE#')\n","repo_name":"Roharui/Coloring_Server","sub_path":"node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"7905106306","text":"import pyodbc\nimport pandas as pd\n\n\ndef dados_conexao(DriveDoBancoDeDados, host, database, user_server, pwd):\n dados_conexao = (\n f\"Driver={DriveDoBancoDeDados};\"\n f\"Server={host};\"\n f\"Database={database};\"\n f\"UID={user_server};\"\n f\"PWD={pwd}\"\n )\n return dados_conexao\n# Informações necessarias para conectar no banco de dados.\n\n\nconexao_banco_de_dados = pyodbc.connect(dados_conexao('SQL SERVER Native Client 11.0',\n host='samu', database='TO-DO', user_server='sa', pwd='sa270212'))\n# Conexão com banco de dados\n\ncursor = conexao_banco_de_dados.cursor()\n# Cursor responsavel por executar query\n\n\nclass GrupoConexao:\n\n def cria_tabela_sql(nome_tabela):\n sql_criacao_tabela = f\"\"\"\n CREATE TABLE [{nome_tabela}](\n [ID] INT IDENTITY NOT NULL,\n [DESCRICAO] NVARCHAR(30) NOT NULL,\n [PRIORIDADE] NVARCHAR(10) NOT NULL,\n [STATUS] CHAR(2) NOT NULL,\n [DT_INICIO] NVARCHAR(30) NOT NULL,\n [DT_FIM] NVARCHAR(30)\n )\n \"\"\"\n return sql_criacao_tabela\n\n def ler_tabela_sql(nome_tabela):\n tabela = pd.read_sql(\n f'SELECT * FROM [{nome_tabela}]', conexao_banco_de_dados)\n return print(tabela)\n\n def excluir_tabela_sql(nome_tabela):\n sql_excluir_tabela = f\"\"\"\n USE [TO-DO]\n DROP TABLE [{nome_tabela}]\n \"\"\"\n return sql_excluir_tabela\n\n def executa_query_sql(nome_metodo):\n cursor.execute(nome_metodo)\n cursor.commit()\n\n\nclass ArgumentosGrupoSQL:\n # \n def adicionar_tarefa(nome_tabela, descricao, prioridade, status, dt_inicio, dt_fim):\n sql_adiciona_tarefa = f\"\"\"\n INSERT INTO [{nome_tabela}] VALUES ('{descricao}', '{prioridade}', '{status}', '{dt_inicio}', '{dt_fim}')\n \"\"\"\n return sql_adiciona_tarefa\n\n def complete_tarefa(nome_tabela, id_tarefa, data_fim):\n sql_complete_tarefa = f\"\"\"\n USE [TO-DO]\n UPDATE [{nome_tabela}]\n SET [STATUS] = 'OK'\n WHERE [ID] = {id_tarefa}\n\n USE [TO-DO]\n UPDATE [{nome_tabela}]\n SET [DT_FIM] = '{data_fim}'\n WHERE [ID] = {id_tarefa}\n \"\"\"\n return sql_complete_tarefa\n\n def deleta_tarefa(nome_tabela, id_tarefa):\n sql_deleta_tarefa = f\"\"\"\n DELETE [{nome_tabela}] WHERE [ID] = {id_tarefa}\n \"\"\"\n return sql_deleta_tarefa\n\n def ler_tarefas(nome_tabela):\n tabela = pd.read_sql(\n f'SELECT * FROM [{nome_tabela}]', conexao_banco_de_dados)\n return print(f'\\033[1;37m{tabela}')\n\n def alterar_tarefa(nome_tabela, coluna, descricao, id_tarefa):\n sql_altera_tarefa = f\"\"\"\n USE [TO-DO]\n UPDATE [{nome_tabela}]\n SET [{coluna}] = '{descricao}'\n WHERE [ID] = {id_tarefa}\n \"\"\"\n return sql_altera_tarefa\n\n def read_tabelas():\n tabela = pd.read_sql(\n f'SELECT TABLE_NAME FROM information_schema.tables', conexao_banco_de_dados)\n return print(f'\\033[1;37m{tabela}')\n\n\ndef validando_tabela_existente(nome_tabela):\n sql_verificando_existencia_tabela = f\"\"\"\n SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_NAME = '{nome_tabela}';\n \"\"\"\n cursor.execute(sql_verificando_existencia_tabela)\n rows = cursor.fetchall()\n return rows\n\n\ndef valida_se_existe_task_na_tabela(nome_tabela, id):\n sql_valida_existencia_task = f\"\"\"\n SELECT ID FROM {nome_tabela} WHERE ID = {id}\n \"\"\"\n cursor.execute(sql_valida_existencia_task)\n rows = cursor.fetchall()\n return rows\n","repo_name":"SamuelFLM/CrudTaskPython","sub_path":"src/conexao.py","file_name":"conexao.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"33089418924","text":"\n# 导包\nfrom appium import webdriver\nfrom time import sleep\nimport base64\n\n# 前置代码、\n# server 启动参数\nfrom selenium.webdriver.support.wait import WebDriverWait\n\ndesired_caps = {}\n# 设备信息\ndesired_caps['platformName'] = 'Android'\ndesired_caps['platformVersion'] = '5.1'\ndesired_caps['deviceName'] = '192.168.56.101:5555'\n# app信息\ndesired_caps['appPackage'] = 'com.android.settings'\ndesired_caps['appActivity'] = '.Settings'\n# 解决中文\ndesired_caps['unicodeKeyboard'] = True\ndesired_caps['resetKeyboard'] = True\n\ndriver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\n\n\"\"\"\n 1.打开设置\n 2.点击搜索按钮\n 3.输入内容abc\n 4.删除已输入abc\n\"\"\"\n# 点击搜索按钮\n# el = driver.find_element_by_id(\"com.android.settings:id/search\")\n\n# 获取 搜索按钮的 name值 注意:name在android中不是元素的属性\n# 使用name:返回 content-desc 或 text 文本值\n# txt = el.get_attribute(\"name\")\n# print(\"使用name获取的值为:\", txt)\n\n\n# 使用 text 获取蓝牙元素文本\n# result = driver.find_element_by_xpath(\"//*[contains(@text, '蓝牙')]\").get_attribute(\"text\")\n# print(\"使用text获取的文本值为:\", result)\n\n# 使用 className 获取蓝牙 class属性值 注意:获取class属性时,使用的是className\n# result = driver.find_element_by_xpath(\"//*[contains(@text, '蓝牙')]\").get_attribute(\"className\")\n# print(\"使用class获取的文本值为:\", result)\n\n\n# 使用 resourceId 获取蓝牙 resource-id属性值 注意:获取resource-id属性时,使用的是resourceId\nresult = driver.find_element_by_xpath(\"//*[contains(@text, '蓝牙')]\").get_attribute(\"resourceId\")\nprint(\"使用resource-id获取的文本值为:\", result)\n\n\n\nsleep(3)\ndriver.quit()\n\n\n\n\n\n\n\n\n","repo_name":"zzx15107104463/APP_automation","sub_path":"day01/scripts/test16_get_attribute.py","file_name":"test16_get_attribute.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"74163617671","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('my_profile//', views.profile_page, name='profile'),\n path('profile//orders/', views.my_orders, name='my-orders'),\n path('order_history//', views.order_history, name='order-history'),\n path('profile//wishlist/', views.my_wishlist, name='my-wishlist'),\n path('profile/wishlist_add//',\n views.wishlist_add, name='wishlist-add'),\n]\n","repo_name":"Dayana-N/Book-Heaven-PP5","sub_path":"profiles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"2634398317","text":"x=input(\"Enter the first number:\")\ny=input(\"Enter the second number:\")\nx=int(x)\ny=int(y)\nprint(\"a=x+y\\nb=x-y\\nc=x/y\\nd=x*y\")\ns=input(\"Your Choice:\")\nif s=='a':\n print(\"Sum is:\",x+y)\nelif s=='b':\n print(\"Answer is:\",x-y)\nelif s=='c':\n print(\"Answer is:\",x/y)\nelif s=='d':\n print(\"Answer is:\",x*y)\n","repo_name":"1906539/Pythoncode","sub_path":"menudriven.py","file_name":"menudriven.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"25961502578","text":"from PySide6.QtCore import *\r\nfrom PySide6.QtGui import *\r\nfrom PySide6.QtWidgets import *\r\n\r\n\r\nclass Ui_application_pages(object):\r\n def setupUi(self, application_pages):\r\n if not application_pages.objectName():\r\n application_pages.setObjectName(u\"application_pages\")\r\n application_pages.resize(1400, 960)\r\n \r\n #Page 1\r\n self.page_1 = QWidget()\r\n self.page_1.setObjectName(u\"page_1\")\r\n \r\n self.main_layout_1 = QVBoxLayout(self.page_1)\r\n self.main_layout_1.setObjectName(u\"main_layout_1\")\r\n \r\n self.frame = QFrame(self.page_1)\r\n self.frame.setObjectName(u\"frame\")\r\n self.frame.setMinimumSize(QSize(1400, 960))\r\n self.frame.setMaximumSize(QSize(1400, 960))\r\n\r\n self.sub_layout_1 = QHBoxLayout(self.frame)\r\n self.sub_layout_1.setAlignment(Qt.AlignCenter)\r\n\r\n self.btn_1 = QPushButton(\"Game start\")\r\n self.btn_1.setObjectName(u\"btn_1\")\r\n self.btn_1.setMinimumSize(QSize(200, 80))\r\n self.btn_1.setMaximumSize(QSize(200, 80))\r\n self.sub_layout_1.addWidget(self.btn_1)\r\n\r\n application_pages.addWidget(self.page_1)\r\n\r\n\r\n #Page 2\r\n self.page_2 = QWidget()\r\n self.page_2.setObjectName(u\"page_2\")\r\n\r\n self.main_layout_2 = QVBoxLayout(self.page_2)\r\n self.main_layout_2.setObjectName(u\"main_layout_2\")\r\n \r\n self.frame_2 = QFrame(self.page_2)\r\n self.frame_2.setObjectName(u\"frame_2\")\r\n self.frame_2.setMinimumSize(QSize(1400, 960))\r\n self.frame_2.setMaximumSize(QSize(1400, 960))\r\n\r\n self.sub_layout_2 = QVBoxLayout(self.frame_2)\r\n self.sub_layout_2.setAlignment(Qt.AlignCenter)\r\n\r\n self.label_1 = QLabel()\r\n self.label_1.setObjectName(u\"label_1\")\r\n self.label_1.setFixedSize(640, 480)\r\n self.sub_layout_2.addWidget(self.label_1)\r\n\r\n self.btn_2 = QPushButton(\"Card_Load\")\r\n self.btn_2.setObjectName(u\"btn_2\")\r\n self.btn_2.setFixedSize(200, 100)\r\n self.sub_layout_2.addWidget(self.btn_2)\r\n \r\n self.btn_3 = QPushButton(\"Next\")\r\n self.btn_3.setObjectName(u\"btn_3\")\r\n self.btn_3.setFixedSize(200, 100)\r\n self.sub_layout_2.addWidget(self.btn_3)\r\n\r\n application_pages.addWidget(self.page_2)\r\n\r\n \r\n #Page 3\r\n self.page_3 = QWidget()\r\n self.page_3.setObjectName(u\"page_3\")\r\n\r\n self.main_layout_3 = QVBoxLayout(self.page_3)\r\n self.main_layout_3.setObjectName(u\"main_layout_3\")\r\n \r\n self.frame_3 = QFrame(self.page_3)\r\n self.frame_3.setObjectName(u\"frame_3\")\r\n self.frame_3.setMinimumSize(QSize(1400, 960))\r\n self.frame_3.setMaximumSize(QSize(1400, 960))\r\n\r\n self.sub_layout_3 = QHBoxLayout(self.frame_3)\r\n self.sub_layout_3.setAlignment(Qt.AlignCenter)\r\n\r\n self.label_2 = QLabel()\r\n self.label_2.setObjectName(u\"label_2\")\r\n self.label_2.setFixedSize(640, 480)\r\n self.sub_layout_3.addWidget(self.label_2)\r\n\r\n self.btn_4 = QPushButton(\"Start\")\r\n self.btn_4.setObjectName(u\"btn_4\")\r\n self.btn_4.setFixedSize(200, 100)\r\n self.sub_layout_3.addWidget(self.btn_4)\r\n\r\n application_pages.addWidget(self.page_3)\r\n\r\n self.retranslateUi(application_pages)\r\n\r\n QMetaObject.connectSlotsByName(application_pages)\r\n\r\n def retranslateUi(self, application_pages):\r\n application_pages.setWindowTitle(QCoreApplication.translate(\"application_pages\", u\"StackedWidget\", None))","repo_name":"ohkingtaek/digit_span","sub_path":"src/gui/ui_application_page.py","file_name":"ui_application_page.py","file_ext":"py","file_size_in_byte":3559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"22671398630","text":"############################################### \r\n# Import Modules\r\n###############################################\r\nimport numpy as np\r\nimport pandas as pd\r\nimport datetime as dt\r\nfrom datetime import datetime, timedelta\r\nimport sqlalchemy\r\nfrom sqlalchemy.ext.automap import automap_base\r\nfrom sqlalchemy.orm import Session\r\nfrom sqlalchemy import create_engine, func\r\n\r\nfrom flask import Flask, jsonify, render_template, flash, request\r\nfrom wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField\r\n\r\n#################################################\r\n# Database Setup\r\n#################################################\r\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\r\n\r\n# reflect an existing database into a new model\r\nBase = automap_base()\r\n# reflect the tables\r\nBase.prepare(engine, reflect=True)\r\n\r\n# Save reference to the table\r\nMeasurement = Base.classes.measurement\r\nStation = Base.classes.station\r\n\r\n# Create an app, being sure to pass __name__\r\napp = Flask(__name__)\r\n\r\n# Create a Secret Key\r\napp.config['Secret Key'] = '6d2808e6627a23651c546c7b78b7c02f'\r\n#################################################\r\n\r\n# 1. Define what to do when a user hits the index route\r\n@app.route(\"/\")\r\ndef home():\r\n print(\"Server received request for 'Home' page...\")\r\n return '''Welcome to my app! \r\n
Available Routes: \r\n
1) /api/v1.0/precipitation\r\n
2) /api/v1.0/stations\r\n
3) /api/v1.0/tobs\r\n
4) /api/v1.0/<start> \r\n
5) /api/v1.0/<start>/<end>'''\r\n\r\n\r\n# 2. Define what to do when a user hits the /api/v1.0/precipitation route\r\n@app.route(\"/api/v1.0/precipitation\")\r\ndef precipitation():\r\n #Create session\r\n session= Session(engine)\r\n\r\n #Query Measurement Table\r\n precipt = session.query(Measurement.date, Measurement.prcp).all()\r\n\r\n #Close session\r\n session.close()\r\n\r\n # Create a dictionary from the row data and append to a list of all_passengers\r\n all_precipt = []\r\n for date, prcp in precipt:\r\n prcp_dict = {}\r\n prcp_dict[\"date\"] = date\r\n prcp_dict[\"prcp\"] = prcp\r\n all_precipt.append(prcp_dict)\r\n\r\n return jsonify(all_precipt)\r\n\r\n# 3. Define what to do when a user hits the /api/v1.0/stations route\r\n@app.route(\"/api/v1.0/stations\")\r\ndef stations():\r\n #Create session\r\n session= Session(engine)\r\n\r\n #Query all station\r\n station = session.query(Station.station).all()\r\n\r\n #Close session\r\n session.close()\r\n\r\n #Convert list of tuples into normal list\r\n all_stations = list(np.ravel(station))\r\n\r\n return jsonify(all_stations)\r\n\r\n# 4. Define what to do when a user hits the /api/v1.0/tobs route\r\n@app.route(\"/api/v1.0/tobs\")\r\ndef tobs():\r\n #Create session\r\n session= Session(engine)\r\n \r\n #Query for the dates and temperature observations from a year from the last data point\r\n obj = session.query(Measurement).order_by(Measurement.date.desc()).first()\r\n dates = [obj.date] \r\n l = [d.date() for d in pd.to_datetime(dates)]\r\n past_year= l[0] - timedelta(days = 365)\r\n temp = session.query(Measurement.date, Measurement.tobs).filter(Measurement.date >= past_year).all()\r\n\r\n #Close session\r\n session.close()\r\n\r\n #Convert list of tuples into normal list\r\n all_temp = list(np.ravel(temp))\r\n return jsonify(all_temp)\r\n\r\n# 5. Define what to do when a user hits the /api/v1.0/ route\r\n\r\n@app.route(\"/api/v1.0/\")\r\ndef departure(start):\r\n\r\n #Create session\r\n session= Session(engine)\r\n\r\n #Reformat Start Date\r\n start_date = datetime.strptime(start, '%Y-%m-%d')\r\n\r\n result = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\r\n filter(Measurement.date >= start_date).all()\r\n \r\n #Close session\r\n session.close() \r\n \r\n return jsonify(result)\r\n \r\n# 6. Define what to do when a user hits the /api/v1.0// route\r\n@app.route(\"/api/v1.0//\")\r\ndef departure_arrival(start, end):\r\n\r\n #Create session\r\n session= Session(engine)\r\n\r\n #Reformat Start Date and End Date\r\n start_date = datetime.strptime(start, '%Y-%m-%d')\r\n end_date = datetime.strptime(end, '%Y-%m-%d')\r\n\r\n result = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\r\n filter(and_(Measurement.date >= start_date, Measurement.date <= end_date)).all()\r\n\r\n #Close session\r\n session.close()\r\n \r\n return jsonify(result)\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n","repo_name":"ssundar80/sqlalchemy-challenge","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"13018753266","text":"import math\n\ninputfile = \"input-day3.txt\"\ninputdata = []\ngrid = []\nintersections = []\ntesting = False\n\n#########################################\n#########################################\n\ndef ReadInput():\n\ttesting = False\n\tfile = open(inputfile, \"r\") \n\tfor line in file:\n\t\tinputdata.append(line)\n\tfile.close()\n\n#########################################\n#########################################\n\ndef SetTestData1():\n\ttesting = True\n\tinputdata.clear()\n\tinputdata.append(\"R75,D30,R83,U83,L12,D49,R71,U7,L72\")\n\tinputdata.append(\"U62,R66,U55,R34,D71,R55,D58,R83\")\n\t# answer = 159\n\ndef SetTestData2():\n\ttesting = True\n\tinputdata.clear()\n\tinputdata.append(\"R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51\")\n\tinputdata.append(\"U98,R91,D20,R16,D67,R40,U7,R15,U6,R7\")\n\t# answer = 135\n\n#########################################\n#########################################\n\ndef ManhattanDistance(x1, y1, x2, y2):\n\treturn abs(x1 - x2) + abs(y1 - y2)\n\n# for real\ngridsizex = 17000\ngridsizey = 13000\nstartx = 4200 # int(gridsize / 2)\nstarty = 1900 # int(gridsize / 2)\n\nif testing:\n\t# for testing\n\tgridsizex = 1000\n\tgridsizey = 1000\n\tstartx = 100 # int(gridsize / 2)\n\tstarty = 100 # int(gridsize / 2)\n\n\ndef InitGrid():\n\tgrid.clear()\n\tfor x in range(0, gridsizex):\n\t\tgrid.append([0 for y in range(0, gridsizey)])\n\t# print(grid)\n\ndef LayWireRight(dist, x, y, val):\n\tfor i in range(0, dist):\n\t\tx += 1\n\t\tif x >= gridsizex:\n\t\t\tprint(\"Grid too small: %d,%d\" % (x, y))\n\t\tgrid[x][y] |= val\n\n\treturn x, y\n\ndef LayWireLeft(dist, x, y, val):\n\tfor i in range(0, dist):\n\t\tx -= 1\n\t\tif x < 0:\n\t\t\tprint(\"Grid too small: %d,%d\" % (x, y))\n\t\tgrid[x][y] |= val\n\n\treturn x, y\n\ndef LayWireUp(dist, x, y, val):\n\tfor i in range(0, dist):\n\t\ty += 1\n\t\tif y >= gridsizey:\n\t\t\tprint(\"Grid too small: %d,%d\" % (x, y))\n\t\tgrid[x][y] |= val\n\n\treturn x, y\n\ndef LayWireDown(dist, x, y, val):\n\tfor i in range(0, dist):\n\t\ty -= 1\n\t\tif y < 0:\n\t\t\tprint(\"Grid too small: %d,%d\" % (x, y))\n\t\tgrid[x][y] |= val\n\n\treturn x, y\n\ndef LayWire(wire, val):\n\tprint(wire)\n\tposx = startx\n\tposy = starty\n\n\tlargestx = 0\n\tlargesty = 0\n\n\tsmallestx = gridsizex\n\tsmallesty = gridsizey\n\n\tfor part in wire.split(','):\n\t\t# print(part)\n\t\tif part[0] == \"R\":\n\t\t\tposx, posy = LayWireRight(int(part[1:]), posx, posy, val)\n\t\telif part[0] == \"L\":\n\t\t\tposx, posy = LayWireLeft(int(part[1:]), posx, posy, val)\n\t\telif part[0] == \"U\":\n\t\t\tposx, posy = LayWireUp(int(part[1:]), posx, posy, val)\n\t\telif part[0] == \"D\":\n\t\t\tposx, posy = LayWireDown(int(part[1:]), posx, posy, val)\n\t\telse:\n\t\t\tprint(\"Invalid code: \", part)\n\n\t\tif posx > largestx:\n\t\t\tlargestx = posx\n\t\tif posy > largesty:\n\t\t\tlargesty = posy\n\n\t\tif posx < smallestx:\n\t\t\tsmallestx = posx\n\t\tif posy < smallesty:\n\t\t\tsmallesty = posy\n\n\tprint(\"Largest = %d, %d\" % (largestx, largesty))\n\tprint(\"Smallest = %d, %d\" % (smallestx, smallesty))\n\ndef MoveTo(dist, x, y, goalx, goaly, dx, dy):\n\tsteps = 0\n\tfor i in range(0, dist):\n\t\tx += dx\n\t\ty += dy\n\t\tsteps += 1\n\t\tif x == goalx and y == goaly:\n\t\t\tbreak\n\n\treturn x, y, steps\n\n\ndef CountStepsTo(goalx, goaly, wire):\n\tposx = startx\n\tposy = starty\n\ttotalsteps = 0\n\tfor part in wire.split(','):\n\t\t# print(part)\n\t\tsteps = 0\n\t\tif part[0] == \"R\":\n\t\t\tposx, posy, steps = MoveTo(int(part[1:]), posx, posy, goalx, goaly, 1, 0)\n\t\telif part[0] == \"L\":\n\t\t\tposx, posy, steps = MoveTo(int(part[1:]), posx, posy, goalx, goaly, -1, 0)\n\t\telif part[0] == \"U\":\n\t\t\tposx, posy, steps = MoveTo(int(part[1:]), posx, posy, goalx, goaly, 0, 1)\n\t\telif part[0] == \"D\":\n\t\t\tposx, posy, steps = MoveTo(int(part[1:]), posx, posy, goalx, goaly, 0, -1)\n\t\telse:\n\t\t\tprint(\"Invalid code: \", part)\n\t\ttotalsteps += steps\n\t\tif posx == goalx and posy == goaly:\n\t\t\tbreak\n\treturn totalsteps\n\n#########################################\n#########################################\n\ndef PartA():\n\tprint(\"Part A\")\n\tInitGrid()\n\tLayWire(inputdata[0], 1)\n\tLayWire(inputdata[1], 2)\n\n\tsmallest_distance = 100000\n\tfor x in range(0, gridsizex):\n\t\tfor y in range(0, gridsizey):\n\t\t\tif grid[x][y] == 3:\n\t\t\t\tprint(\"Intersection at %d,%d\" % (x, y))\n\t\t\t\tintersections.append([x, y])\n\t\t\t\tdistance = ManhattanDistance(startx, starty, x, y)\n\t\t\t\tif distance > 0 and distance < smallest_distance:\n\t\t\t\t\tsmallest_distance = distance\n\t# print(grid)\n\tprint(\"Answer:\", smallest_distance)\n\n#########################################\n#########################################\n\ndef PartB():\n\tprint(\"Part B\")\n\n\tsmallest = 10000000\n\tfor i in intersections:\n\t\tsteps1 = CountStepsTo(i[0], i[1], inputdata[0])\n\t\tsteps2 = CountStepsTo(i[0], i[1], inputdata[1])\n\n\t\tif steps1 + steps2 < smallest:\n\t\t\tsmallest = steps1 + steps2\n\n\tprint(\"Answer:\", smallest)\n\n#########################################\n#########################################\n\nif __name__ == \"__main__\":\n\tprint(\"Day 3\")\n\tReadInput()\n\t# SetTestData1()\n\t# SetTestData2()\n\tPartA()\n\tPartB()\n","repo_name":"DeShrike/AdventOfCode2019","sub_path":"day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":4769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"15539164822","text":"print(\"The Stick in the Pile Game\")\r\nplayer2 = str(input(\"What's your name? : \"))\r\nsticks = int(input(\"How many sticks in the pile? : \"))\r\nMax_take = int(input(\"The maximum amount that can be took: \"))\r\nimport random\r\nwhile sticks > 0 :\r\n print(\"There are \" + str(sticks) + \" sticks in the pile \")\r\n\r\n#player1 (AI)\r\n\r\n if sticks % Max_take+1 == Max_take:\r\n take1 = 1\r\n sticks -= take1\r\n print(\"I take \" + str(take1) + \" stick, there are \" + str(sticks) + \" sticks in the pile. \")\r\n else:\r\n take1 = random.randint(1, Max_take)\r\n sticks -= take1\r\n print(\"I take \" + str(take1) + \" stick, there are \" + str(sticks) + \" sticks in the pile. \")\r\n if sticks <= 0:\r\n print(\"chiAI takes the last stick,\")\r\n print(player2,\" WON \")\r\n break\r\n#player2 (people)\r\n\r\n take2 = int(input(\"How many you will take: \"))\r\n if take2 <= Max_take:\r\n sticks -= take2\r\n else: \r\n print(\"No! you can't take more less than 1 stick!\")\r\n take2 = int(input(\"How many you will take: \"))\r\n sticks -= take2\r\n if sticks== 0:\r\n print(player2, \"takes the last stick,\")\r\n print(\"I WON (Python won) \")\r\n break\r\n\r\n\r\n\r\n ","repo_name":"nattanan13/-nattanan","sub_path":"640631119__Nattanan_sticks vs AI.py","file_name":"640631119__Nattanan_sticks vs AI.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"22091192527","text":"\"\"\"\nstanCode Breakout Project\nAdapted from Eric Roberts's Breakout by\nSonja Johnson-Yu, Kylie Jue, Nick Bowman,\nand Jerry Liao.\n\nFile: breakout.py\nName: 黃元品\n\"\"\"\n\nfrom campy.gui.events.timer import pause\nfrom breakoutgraphics import BreakoutGraphics\n\nFRAME_RATE = 1000 / 120 # 120 frames per second\nNUM_LIVES = 3\t\t\t# Number of attempts\n\n\ndef main():\n graphics = BreakoutGraphics()\n\n dx = graphics.get_dx()\n dy = graphics.get_dy()\n life = NUM_LIVES\n\n # Add animation loop here!\n while True:\n pause(FRAME_RATE)\n if graphics.is_start: # check if the mouse already clicked to start the game\n graphics.ball.move(dx, dy)\n if graphics.ball.x + graphics.ball_diameter >= graphics.window.width or graphics.ball.x <= 0:\n graphics.prior_collide_obj = 'wall'\n dx = -dx\n elif graphics.ball.y <= 0:\n graphics.prior_collide_obj = 'wall'\n dy = -dy\n elif graphics.ball.y >= graphics.window.height:\n graphics.prior_collide_obj = 'wall'\n life -= 1\n graphics.reset_ball()\n\n if graphics.check_remove(): # if collide sth. then bounce and decide remove or not\n dy = -dy\n\n if graphics.get_brick_count() == 0: # win condition\n graphics.win()\n break\n\n if life == 0: # lose condition\n graphics.gameover()\n break\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"tommy73594/stanCode_Projects","sub_path":"SC101_Assignment2/breakout.py","file_name":"breakout.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"31786614186","text":"from sqlalchemy import create_engine, Column, MetaData\n\nfrom clickhouse_sqlalchemy import (\n Table, make_session, get_declarative_base, types, engines\n)\nfrom clickhouse import *\n\n\nmetric__extrema_balance = ('CREATE TABLE IF NOT EXISTS cti.metric__extrema_balance '\n '( '\n 'MaxBalance SimpleAggregateFunction(max, Float64), '\n 'MinBalance SimpleAggregateFunction(min, Float64), '\n 'Server String, '\n 'Login UInt64 '\n ') '\n 'ENGINE = AggregatingMergeTree() '\n 'ORDER BY (Login, Server) ')\n\nmetric__extrema_balance_mv = ('CREATE MATERIALIZED VIEW cti.metric__extrema_balance_mv TO cti.metric__extrema_balance '\n 'AS SELECT ' \n 'max(TotalBalance) as MaxBalance, min(TotalBalance) as MinBalance, Server as Server, Login as Login '\n 'FROM cti.mt_account_balance_table ' \n 'GROUP BY Login, Server ')\n\n\n","repo_name":"hoangnguyennhu/clickhouse_init","sub_path":"table/extrema_balance.py","file_name":"extrema_balance.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70339793991","text":"#\n# Entities being reported on.\n#\n# At the moment this maps mostly to tables in the local database, but it\n# doesn't have to - in the case of the instances table there are a number\n# of things we may derive from the same data source, though they're mostly\n# aggregates of some sort or another.\n#\n# We can't really make each object map to an actual physical-ish entity,\n# because that would be quite wasteful both in live memory and processing.\n# What we can probably do is make each class a mapping tool from the\n# source(es) to the data store. Thus when you say \"extract\" that would pull\n# in all the source data in bulk, and when you say \"load\" it would put it\n# all in the data store. The actual live object would keep the source data\n# in memory while it was working, but wouldn't try to map each chunk to an\n# in-memory object.\n\nfrom datetime import datetime\nfrom datetime import timedelta\nimport logging\nimport pickle\n\nfrom reporting_pollster.common.config import Config\nfrom reporting_pollster.common.DB import DB\nfrom reporting_pollster import entities\n\n\nclass TableNotFound(Exception):\n \"\"\"A handler for the requested table was not found\n \"\"\"\n def __init__(self, table):\n self.table = table\n\n\nclass TableDependencyError(Exception):\n \"\"\"A dependency error was encountered\n \"\"\"\n def __init__(self, msg):\n self.msg = msg\n\n\nclass Entity(object):\n \"\"\"Top level generic - all entities inherit from this\n\n Required methods raise NotImplementedError()\n \"\"\"\n\n metadata_query = (\n \"select last_update from metadata \"\n \"where table_name = %s limit 1\"\n )\n # The class level data cache\n _cache = {}\n\n def __init__(self, args):\n self.args = args\n self.dbs = Config.get_dbs()\n self.data = []\n self.dry_run = not self.args.full_run\n self.last_update = None\n self.this_update_start = None\n self.last_update_window = args.last_update_window\n self.extract_time = timedelta()\n self.transform_time = timedelta()\n self.load_time = timedelta()\n\n # We can't simply use parameters here because you can't specify the\n # table name as a parameter - it has to be a plain token in the SQL.\n # Since we're directly manipulating the SQL string, we may as well\n # drop the quoted table name into the values tuple as well . . .\n #\n # Adding support for manually setting the last update timestamp.\n self.metadata_update_template = (\n \"insert into metadata (table_name, last_update, row_count) \"\n \"values ('{table}', %(last_update)s, \"\n \" (select count(*) from {table})) \"\n \"on duplicate key update last_update=%(last_update)s, \"\n \"row_count=(select count(*) from {table})\"\n )\n\n @classmethod\n def from_table_name(cls, table, args):\n \"\"\"Get an entity object given the table name\"\"\"\n entity = None\n for i in dir(entities.entities):\n entity = getattr(entities.entities, i)\n try:\n t = getattr(entity, 'table')\n if t == table:\n # break here rather than return, so that the actual object\n # instantiation isn't wrapped in a try: block\n break\n except AttributeError:\n pass\n\n if not entity:\n raise TableNotFound(table)\n\n return entity(args)\n\n @classmethod\n def get_table_names(cls, user_tables=None):\n # we resolve dependencies using the following algorithm, based on\n # Kahn's topological sort algorithm with warts to support a\n # user-supplied subset of the full depdency list, and the creation of a\n # full consistent ordering rather than an ordered collection of sets:\n #\n # 1) build a map of all supported tables and their dependencies\n #\n # 2) build a list containing the intersection of the set of supported\n # tables with the set of requested tables, filtering out requested\n # tables that aren't in the supported table list\n #\n # 3) for each requested table, add that table's dependencies to the\n # list of required tables\n #\n # 4) repeat step 3 until the required list doesn't change between\n # iterations (this resolves chained dependencies)\n #\n # 5) build a new dependency map including only the required tables\n # (i.e. requested tables and their dependencies)\n #\n # 6) sort the list of required tables based on the length of each\n # table's dependency list\n #\n # 7) remove the first table from the list, verify that it has an empty\n # dependency list, and append it to the output list. If the first entry\n # in the list has dependencies this indicates that there are circular\n # dependencies.\n #\n # 8) remove the selected table from all entries in the dependency map\n #\n # 9) sort the remainder of the required tables list again based on the\n # updated dependency map. This avoids a situation where we resolve all\n # the dependencies of entries further back on the list, but leave\n # entries with dependencies ahead of them - sorting the list here pulls\n # all the indepdenent entries to the front of the list, ensuring that\n # the only way step 7 can fail is if there are genuine circular\n # dependencies.\n #\n # 10) repeat steps 7 through 9 until the required tables list is empty\n #\n # 11) raise an error if no entries can be found with an empty\n # dependency list (this indicates a circular dependency chain)\n #\n # Note that at least one table must be independent - have no\n # dependencies - otherwise this algorithm can't proceed.\n #\n # By default no dependencies are defined for a table - each\n # Entity-based class has to override the Entity level definition to\n # specify dependencies.\n #\n # Why bother with this? Because with data caching during runs the\n # inter-table dependencies keep getting more complex, and devoting the\n # effort to come up with a general solution /now/ means that in future\n # all we have to do is specify data dependencies and it'll be dealt\n # with automagically.\n\n # the dependency map\n dependencies = {}\n\n # build the set of all supported tables and their dependencies\n tables = set()\n for i in dir(entities.entities):\n entity = getattr(entities.entities, i)\n try:\n table = getattr(entity, 'table')\n dependencies[table] = entity._get_dependencies()\n tables.add(table)\n except AttributeError:\n pass\n\n # if the user has specified a list of tables we take the intersection\n # of the supported tables and their requested list (to make sure\n # they're not asking for invalid tables)\n if user_tables:\n user_tables = set(user_tables)\n tables = user_tables & tables\n # add in any missing dependencies\n required_tmp = tables\n required = set()\n while required != required_tmp:\n required = required_tmp\n for table in required:\n required_tmp = required_tmp | dependencies[table]\n # remove tables that aren't being processed from the dependency map\n for table in dependencies.keys():\n if table not in required:\n del dependencies[table]\n required = [t for t in required]\n # alphabetically sort, so that we have a consistent base\n required.sort()\n # then sort based on dependency count\n required.sort(key=lambda x: len(dependencies[x]))\n # finally run the basic topological sort\n resolved = []\n while len(required) > 0:\n table = required.pop(0)\n if len(dependencies[table]) > 0:\n raise TableDependencyError(\n \"Circular table dependencies found. \"\n )\n resolved.append(table)\n for t in dependencies.keys():\n dependencies[t] = dependencies[t] - set([table])\n required.sort(key=lambda x: len(dependencies[x]))\n\n return resolved\n\n # Note: this will be overridden in any class that needs to declare\n # dependencies\n @classmethod\n def _get_dependencies(cls):\n return set()\n\n @classmethod\n def _cache_data(cls, key, data):\n \"\"\"Stash some data in a class-level cache so that it can be re-used by\n other Entity object instantiations. This is used to support derived\n updates across multiple Entity object instantiations within a single\n run.\n \"\"\"\n # the implementation is stupid simple . . .\n cls._cache[key] = data\n\n @classmethod\n def _get_cached_data(cls, key):\n \"\"\"Retrieve data cached by another (or potentially this) Entity object\n instantiation.\n \"\"\"\n return cls._cache[key]\n\n @classmethod\n def drop_cached_data(cls):\n \"\"\"Drop any cached data.\n \"\"\"\n cls._cache = {}\n\n def dup_record(self, record):\n \"\"\"Trivial utility method.\n Probably doesn't seem important, but it avoids any confusion between\n the return type of the database query (which may simply emulate a dict\n type) and a \"real\" dict\n \"\"\"\n t = {}\n for key in record.keys():\n t[key] = record[key]\n return t\n\n def _format_query(self, qname):\n \"\"\"This is designed to handle the case where the database name is\n non-standard. Database names in the relevant queries need to be\n converted to format string entities like '{nova}' or '{keystone}' for\n this to work.\n\n Note that placeholders in the actual queries use either %s style\n formatting, or %(name)s style - while these are both valid python\n string formatting codes, they're in the queries because that's what\n the mysql connector uses. The \"\".format() method is used here because\n it doesn't clash with query placeholders.\n \"\"\"\n return self.queries[qname].format(**self.dbs)\n\n def _extract_all(self):\n logging.info(\"Extracting data for table %s\", self.table)\n cursor = DB.remote_cursor()\n cursor.execute(self._format_query('query'))\n self.db_data = cursor.fetchall()\n logging.debug(\"Rows returned: %d\", cursor.rowcount)\n\n def _extract_dry_run(self):\n logging.info(\"Extracting data for %s table\", self.table)\n logging.debug(\"Query: %s\", self._format_query('query'))\n\n def _extract_all_last_update(self):\n logging.info(\"Extracting data for %s table (last_update)\", self.table)\n query = self._format_query('query_last_update')\n cursor = DB.remote_cursor()\n cursor.execute(query, {'last_update': self.last_update})\n self.db_data = cursor.fetchall()\n logging.debug(\"Rows returned: %d\", cursor.rowcount)\n\n def _extract_dry_run_last_update(self):\n logging.info(\"Extracting data for %s table (last update)\", self.table)\n query = self._format_query('query_last_update')\n logging.debug(\"Query: %s\", query % {'last_update': self.last_update})\n\n def _extract_no_last_update(self):\n \"\"\"Can be used when no last_update is available for this entity\n \"\"\"\n if self.dry_run:\n self._extract_dry_run()\n else:\n self._extract_all()\n\n def _extract_with_last_update(self):\n \"\"\"Can be used when a last_update value is meaningfull for this entity\n \"\"\"\n self.last_update = self.get_last_update()\n if 'force_update' in self.args:\n self.last_update = False\n method_name = \"_extract_all\"\n if self.dry_run:\n method_name = \"_extract_dry_run\"\n\n if self.last_update:\n method_name = method_name + \"_last_update\"\n\n # yey reflection\n method = getattr(self, method_name)\n method()\n\n def extract(self):\n \"\"\"Extract, from whatever sources are necessary, the data that this\n entity requires\n\n This may make use of one of the utility functions above.\n \"\"\"\n raise NotImplementedError()\n\n def transform(self):\n \"\"\"Transform the data loaded via extract() into the format to be loaded\n using load()\n \"\"\"\n raise NotImplementedError()\n\n def _load_dry_run(self):\n logging.info(\"Loading data for %s table\", self.table)\n logging.debug(\"Query: %s\", self._format_query('update'))\n\n # Note: we really need to give some consideration to the use of\n # transactions - right now we only have one case where the entity code\n # uses a transaction above this level, but it's hard to know what other\n # cases may come up as the processing gets more sophisticated. For now\n # we're going to assume that the high level wrappers (load, _load_simple)\n # have complete ownership of the transaction, but the lower stuff\n # (_load_many and _run_sql_cursor) don't. Hence the user needs to make\n # sure they handle transactions and commits themselves.\n def _load(self):\n logging.info(\"Loading data for %s table\", self.table)\n cursor = DB.local_cursor()\n # necessary because it's entirely possible for a last_update query to\n # return no data\n if len(self.data) > 0:\n cursor.executemany(self._format_query('update'),\n self.data)\n DB.local().commit()\n logging.debug(\"Rows updated: %d\", cursor.rowcount)\n self.set_last_update()\n\n def _load_simple(self):\n if self.dry_run:\n self._load_dry_run()\n else:\n self._load()\n\n # Note: this is a low-level function that doesn't do any commits - the\n # caller is expected to handle database consistency\n def _load_many(self, qname, data):\n q = self._format_query(qname)\n if self.dry_run:\n logging.debug(\"Special query: %s\", q)\n else:\n cursor = DB.local_cursor()\n cursor.executemany(q, data)\n logging.debug(\"Rows updated: %d\", cursor.rowcount)\n\n # seems a bit silly, but this captures the dry_run and debug logic\n #\n # Note: since we don't own the cursor we don't do any cursor-specific\n # debugging output or commits\n def _run_sql_cursor(self, cursor, qname):\n q = self._format_query(qname)\n if self.dry_run:\n logging.debug(\"Generic query: %s\", q)\n else:\n cursor.execute(q)\n\n def load(self):\n \"\"\"Load data about this entity into the data store.\n \"\"\"\n raise NotImplementedError()\n\n def _get_timing(self):\n msg = (\n \"Process timing (%s):\" % (self.table) +\n \"\\textract: %f\" % (self.extract_time.total_seconds()) +\n \"\\ttransform: %f\" % (self.transform_time.total_seconds()) +\n \"\\tload: %f\" % (self.load_time.total_seconds())\n )\n return msg\n\n def process(self):\n \"\"\"Wrapper for the extract/load loop\n \"\"\"\n logging.debug(\"Processing table %s\", self.table)\n self.this_update_start = datetime.now()\n self.extract()\n self.transform()\n self.load()\n\n logging.debug(self._get_timing())\n\n def _get_default_last_update(self, args):\n last_update = None\n if 'last_updated' in args:\n last_update = datetime.strptime(args.last_updated, \"%Y%m%d\")\n if 'last_day' in args:\n logging.debug(\"Update for last day\")\n last_update = datetime.now() - timedelta(days=1)\n if 'last_week' in args:\n logging.debug(\"Update for last week\")\n last_update = datetime.now() - timedelta(weeks=1)\n if 'last_month' in args:\n logging.debug(\"Update for last month\")\n last_update = datetime.now() - timedelta(days=30)\n return last_update\n\n def _get_last_update(self, table):\n \"\"\"Get the time that the data was updated most recently, so that we can\n process only the updated data.\n \"\"\"\n cursor = DB.local_cursor()\n cursor.execute(self.metadata_query, (table, ))\n row = cursor.fetchone()\n res = None\n if row:\n res = row['last_update']\n res = res - timedelta(seconds=self.last_update_window)\n return res\n\n def get_last_update(self, table=None):\n if not table:\n table = self.table\n last_update = self._get_default_last_update(self.args)\n if not last_update:\n last_update = self._get_last_update(table)\n if not last_update:\n logging.debug(\"No last update value available\")\n else:\n logging.debug(\"Last update: %s\", last_update.isoformat())\n return last_update\n\n def set_last_update(self, table=None, last_update=None):\n \"\"\"Set the last_update field for the given table\n \"\"\"\n if not table:\n table = self.table\n if self.dry_run:\n logging.debug(\"Setting last update on table %s\", table)\n return\n # the user can specify a different last update time, otherwise we use\n # the start point of the processing loop for this entity\n if not last_update:\n last_update = self.this_update_start\n\n cursor = DB.local_cursor(dictionary=False)\n query = self.metadata_update_template.format(**{'table': table})\n cursor.execute(query, {'last_update': last_update})\n DB.local().commit()\n\n @staticmethod\n def _begin(conn):\n \"\"\"Older versions of pymysql don't support a begin() or\n start_transaction(), so we wrap that functionality here\n \"\"\"\n try:\n conn.begin()\n except AttributeError:\n pass\n\n\nclass Aggregate(Entity):\n \"\"\"Aggregate entity, which is used by OpenStack as part of its scheduling\n logic. This pulls its data from the APIs.\n \"\"\"\n\n # this seems a bit silly, but it allows us to use the load_simple method.\n queries = {\n 'update': (\n \"replace into aggregate (id, availability_zone, name, created, \"\n \"deleted, active) values (%(id)s, %(availability_zone)s, \"\n \"%(name)s, %(created)s, %(deleted)s, %(active)s)\"\n ),\n 'aggregate_host_cleanup': (\n \"delete from aggregate_host\"\n ),\n 'aggregate_host': (\n \"replace into aggregate_host (id, availability_zone, host, active)\"\n \" values (%(id)s, %(availability_zone)s, %(host)s, 1)\"\n ),\n 'clear_active': (\n \"update aggregate_host set active=0\"\n ),\n 'hypervisor_az_update': (\n \"update hypervisor set availability_zone = %(availability_zone)s \"\n \"where host = %(host)s\"\n ),\n }\n\n table = \"aggregate\"\n\n def __init__(self, args):\n super(Aggregate, self).__init__(args)\n self.api_data = []\n self.agg_data = []\n self.agg_host_data = []\n self.hypervisor_az_data = {}\n self.data = []\n self.novaclient = Config.get_nova_client()\n\n def new_agg_record(self):\n return {\n 'id': None,\n 'availability_zone': None,\n 'name': None,\n 'created': None,\n 'deleted': None,\n 'active': None,\n }\n\n def new_agg_host_record(self):\n return {\n 'id': None,\n 'availability_zone': None,\n 'host': None,\n }\n\n def extract(self):\n start = datetime.now()\n # NeCTAR requires hypervisors details from the API\n if not self.dry_run:\n self.api_data = self.novaclient.aggregates.list()\n else:\n logging.info(\"Extracting API data for the aggregate table\")\n self.extract_time = datetime.now() - start\n\n def transform(self):\n start = datetime.now()\n # We have two separate pieces of data here: the aggregate itself, and\n # the list of hosts assigned to each aggregate. We're dealing with them\n # in the same place because the data all comes from one API query.\n for aggregate in self.api_data:\n agg = self.new_agg_record()\n # Newton and above moves aggregates out of the cells to the top\n # level, meaning the aggregate ID format changes from a string\n # (with routing information) to a globally unique integer. This\n # makes for a break in the information contained in the\n # aggregate/aggregate_host tables, but the result will be a little\n # more meaningful (currently the 'availability_zone' field is\n # actually the cell name rather than the actual availability zone).\n #\n # Note that this code is the canonical source of the hypervisor->AZ\n # mapping, and hence updates the hypervisor table in addition to\n # the aggregate and aggregate_host tables.\n if type(aggregate.id) == int:\n id = aggregate.id\n az = aggregate.availability_zone\n else:\n id = aggregate.id.split('!', 1)[1]\n (az, id) = id.split('@')\n agg['id'] = id\n agg['availability_zone'] = az\n agg['name'] = aggregate.name\n agg['created'] = aggregate.created_at\n agg['deleted'] = aggregate.deleted_at\n agg['active'] = not aggregate.deleted\n self.agg_data.append(agg)\n\n # this is meaningless if an aggregate has no availability_zone\n # specified\n if az:\n for host in aggregate.hosts:\n hname = host.split('.')[0]\n h = self.new_agg_host_record()\n h['id'] = id\n h['availability_zone'] = az\n h['host'] = hname\n self.agg_host_data.append(h)\n\n self.hypervisor_az_data[hname] = az\n\n self.data = self.agg_data\n Entity._cache_data('hypervisor_az', self.hypervisor_az_data)\n self.transform_time = datetime.now() - start\n\n def load(self):\n start = datetime.now()\n\n # the aggregate table is simple to deal with.\n self._load_simple()\n\n # the aggregate_host table is a pretty simple many to many mapping\n # (hosts can be in more than one aggregate). This is the authoritative\n # method of determining the availability zone that hypervisors are\n # members of.\n #\n # Because there's no temporal data associated with any of this we're\n # adding our own - a simple 'last_seen' timestamp which will allow\n # users of this data to figure out which entries are current and which\n # are historical (and at the same time they'll be able to track the\n # history of the data).\n #\n # Note that there's a window here where the hypervisor table and the\n # aggregate table can get out of sync - we've cached the hypervisor/AZ\n # mapping /now/, but if there are changes between now and when the\n # hypervisor queries happen they can be out of sync. There's no way to\n # avoid this, though, outside of wrapping /everything/ in a big\n # transaction, which I'd really like to avoid.\n self._run_sql_cursor(DB.local_cursor(), 'clear_active')\n self._load_many('aggregate_host', self.agg_host_data)\n self.set_last_update(table='aggregate_host') # commits transaction\n\n self.load_time = datetime.now() - start\n\n\nclass Hypervisor(Entity):\n \"\"\"Hypervisor entity. This uses the hypervisor table locally, and gets its\n source data from the Nova APIs.\n \"\"\"\n\n queries = {\n 'query': (\n \"select id, 'nova' as availability_zone, hypervisor_hostname, \"\n \"host_ip, vcpus, memory_mb, local_gb from {nova}.compute_nodes\"\n ),\n 'query_last_update': (\n \"select id, 'nova' as availability_zone, hypervisor_hostname, \"\n \"host_ip, vcpus, memory_mb, local_gb from {nova}.compute_nodes \"\n \"where ifnull(deleted_at, now()) > %(last_update)s \"\n \" or updated_at > %(last_update)s\"\n ),\n 'update': (\n \"replace into hypervisor \"\n \"(id, availability_zone, host, hostname, ip_address, cpus, \"\n \"memory, local_storage, last_seen, active) \"\n \"values (%(id)s, %(availability_zone)s, %(host)s, %(hostname)s, \"\n \"%(ip_address)s, %(cpus)s, %(memory)s, %(local_storage)s, null, 1)\"\n ),\n 'clear_active': (\n \"update hypervisor set active=0\"\n ),\n }\n\n table = \"hypervisor\"\n\n def __init__(self, args):\n super(Hypervisor, self).__init__(args)\n self.db_data = []\n self.api_data = []\n self.data = []\n self.novaclient = Config.get_nova_client()\n self.hypervisor_az_data = {}\n\n # PUll all the data from whatever sources we need, and assemble them here\n #\n # Right now this is entirely the database.\n\n @classmethod\n def _get_dependencies(cls):\n return set(['aggregate'])\n\n def new_record(self):\n return {\n 'id': None,\n 'availability_zone': None,\n 'host': None,\n 'hostname': None,\n 'ip_address': None,\n 'cpus': None,\n 'memory': None,\n 'local_storage': None\n }\n\n def extract(self):\n start = datetime.now()\n # NeCTAR requires hypervisors details from the API\n if not self.dry_run:\n self.api_data = self.novaclient.hypervisors.list()\n else:\n logging.info(\"Extracting API data for the hypervisor table\")\n try:\n self.hypervisor_az_data = Entity._get_cached_data(\"hypervisor_az\")\n except KeyError:\n pass\n self.extract_time = datetime.now() - start\n\n # ded simple until we have more than one data source\n def transform(self):\n start = datetime.now()\n for hypervisor in self.api_data:\n r = self.new_record()\n # here the availability zone is actually the cell name, for\n # historical reasons. With the change to Newton, this will become\n # the actual availability zone, with this table updated by the\n # aggregate update process (which is the canonical source of the\n # hypervisor->aggregate->AZ mapping). This update makes use of the\n # host part of the hypervisor_hostname field, which is used by nova\n # as the key in the host aggregate relationship.\n (cell, hid) = hypervisor.id.split('!', 1)[1].split('@')\n hname = hypervisor.hypervisor_hostname.split('.')[0]\n try:\n az = self.hypervisor_az_data[hname]\n except KeyError:\n # use the cell name - this provides some historical consistency\n az = cell\n r['id'] = int(hid)\n r['availability_zone'] = az\n r['host'] = hname\n r['hostname'] = hypervisor.hypervisor_hostname\n r['ip_address'] = hypervisor.host_ip\n r['cpus'] = hypervisor.vcpus\n r['memory'] = hypervisor.memory_mb\n r['local_storage'] = hypervisor.local_gb\n self.data.append(r)\n self.transform_time = datetime.now() - start\n\n def load(self):\n start = datetime.now()\n self._run_sql_cursor(DB.local_cursor(), 'clear_active')\n self._load_simple() # commits transaction\n self.load_time = datetime.now() - start\n\n\nclass Project(Entity):\n \"\"\"Project entity, using the project table locally and the keystone.project\n table remotely. Also the allocations database, and probably the keystone\n apis too.\n \"\"\"\n queries = {\n 'query': (\n \"select distinct kp.id as id, kp.name as display_name, \"\n \"kp.description as description, kp.enabled as enabled, \"\n \"kp.name like 'pt-%' as personal, \"\n \"false as has_instances, \"\n \"i.hard_limit as quota_instances, c.hard_limit as quota_vcpus, \"\n \"r.hard_limit as quota_memory, \"\n \"g.total_limit as quota_volume_total, \"\n \"s.total_limit as quota_snapshots, \"\n \"v.total_limit as quota_volume_count \"\n \"from {keystone}.project as kp left outer join \"\n \"( select * from {nova}.quotas where deleted = 0 \"\n \"and resource = 'ram' ) \"\n \"as r on kp.id = r.project_id left outer join \"\n \"( select * from {nova}.quotas where deleted = 0 \"\n \"and resource = 'instances' ) \"\n \"as i on kp.id = i.project_id left outer join \"\n \"( select * from {nova}.quotas where deleted = 0 \"\n \"and resource = 'cores' ) \"\n \"as c on kp.id = c.project_id left outer join \"\n \"( select project_id, \"\n \"sum(if(hard_limit>=0,hard_limit,0)) as total_limit \"\n \"from {cinder}.quotas where deleted = 0 \"\n \"and resource like 'gigabytes%' \"\n \"group by project_id ) \"\n \"as g on kp.id = g.project_id left outer join \"\n \"( select project_id, \"\n \"sum(if(hard_limit>=0,hard_limit,0)) as total_limit \"\n \"from {cinder}.quotas where deleted = 0 \"\n \"and resource like 'volumes%' \"\n \"group by project_id ) \"\n \"as v on kp.id = v.project_id left outer join \"\n \"( select project_id, \"\n \"sum(if(hard_limit>=0,hard_limit,0)) as total_limit \"\n \"from {cinder}.quotas where deleted = 0 \"\n \"and resource like 'snapshots%' \"\n \"group by project_id ) \"\n \"as s on kp.id = s.project_id\"\n ),\n 'update': (\n \"replace into project \"\n \"(id, display_name, organisation, description, enabled, personal, \"\n \"has_instances, quota_instances, quota_vcpus, quota_memory, \"\n \"quota_volume_total, quota_snapshot, quota_volume_count) \"\n \"values (%(id)s, %(display_name)s, %(organisation)s, \"\n \"%(description)s, %(enabled)s, %(personal)s, %(has_instances)s, \"\n \"%(quota_instances)s, %(quota_vcpus)s, %(quota_memory)s, \"\n \"%(quota_volume_total)s, %(quota_snapshots)s, \"\n \"%(quota_volume_count)s)\"\n ),\n 'tenant_owner': (\n \"select ka.target_id as tenant, ka.actor_id as user, \"\n \"rc.shibboleth_attributes as shib_attr \"\n \"from {keystone}.assignment as ka join {rcshibboleth}.user as rc \"\n \"on ka.actor_id = rc.user_id \"\n \"where ka.type = 'UserProject' and ka.role_id = \"\n \"(select id from {keystone}.role where name = 'TenantManager')\"\n ),\n 'tenant_member': (\n \"select ka.target_id as tenant, ka.actor_id as user, \"\n \"rc.shibboleth_attributes as shib_attr \"\n \"from {keystone}.assignment as ka join {rcshibboleth}.user as rc \"\n \"on ka.actor_id = rc.user_id \"\n \"where ka.type = 'UserProject' and ka.role_id = \"\n \"(select id from {keystone}.role where name = 'Member')\"\n ),\n }\n\n table = \"project\"\n\n def __init__(self, args):\n super(Project, self).__init__(args)\n self.db_data = []\n self.tenant_owner_data = []\n self.tenant_member_data = []\n self.has_instance_data = {}\n\n # XXX: this dependency has the potential to result in nasty interactions!\n # Running a forced update of the project table (which is a small task on\n # its own, and meaningless given it has no last_update support) will now\n # result in doing a forced update of the instance table, which is hellishly\n # painful! It's not a likely scenario, but it's currently a possibility -\n # at present this is just a case of caveat emptor, but in future some kind\n # of sanity checking of arguments may be necessary.\n @classmethod\n def _get_dependencies(cls):\n return set(['instance'])\n\n def new_record(self):\n return {\n 'id': None,\n 'display_name': None,\n 'organisation': None,\n 'description': None,\n 'enabled': None,\n 'personal': None,\n 'has_instances': False,\n 'quota_instances': None,\n 'quota_vcpus': None,\n 'quota_memory': None,\n 'quota_volume_total': None,\n 'quota_volume_count': None,\n 'quota_snapshot': None,\n }\n\n def extract(self):\n start = datetime.now()\n self._extract_no_last_update()\n cursor = DB.remote_cursor()\n cursor.execute(self._format_query('tenant_owner'))\n self.tenant_owner_data = cursor.fetchall()\n cursor.execute(self._format_query('tenant_member'))\n self.tenant_member_data = cursor.fetchall()\n try:\n self.has_instance_data = Entity._get_cached_data('has_instance')\n except KeyError:\n pass\n self.extract_time = datetime.now() - start\n\n def transform(self):\n start = datetime.now()\n # we have the data we pulled from the project database, but we now\n # need to merge in the tenant owner data. We iterate over the database\n # results and pull in the tenant owner info and organisation stuff . .\n #\n # This is nowhere near perfect - there are a lot of logical holes. But\n # we want this approximation for the moment.\n\n def new_tenant_owner():\n return {\n 'tenant': None,\n 'user': None,\n 'shib_attr': None,\n }\n\n # convert the raw database result set into something we can query\n # by tenant id\n def tenant_role_to_dict(data):\n tdict = {}\n for t in data:\n id = t['tenant']\n shib_attr = pickle.loads(t['shib_attr'])\n to = new_tenant_owner()\n to['tenant'] = id\n to['user'] = t['user']\n to['shib_attr'] = shib_attr\n tdict[id] = to\n return tdict\n\n # Build the tenant owner dict\n tod = tenant_role_to_dict(self.tenant_owner_data)\n # and since we need to get useful information for personal trials . . .\n tmd = tenant_role_to_dict(self.tenant_member_data)\n\n # now we walk the main result set and fill it out in full\n self.data = []\n for tenant in self.db_data:\n t = self.new_record()\n for key in tenant.keys():\n t[key] = tenant[key]\n # personal trials do not have a TenantManager - leave these null\n try:\n shib_attr = tod[tenant['id']]['shib_attr']\n except KeyError:\n try:\n shib_attr = tmd[tenant['id']]['shib_attr']\n except KeyError:\n self.data.append(t)\n continue\n # this is a bit nasty, but it does two things: firstly, it picks\n # up the two useful shibboleth attributes that we can use here\n # namely 'organisation' and 'homeorganisation', of which\n # organisation is the more useful since it's an actual name rather\n # than a domain, and the sorted keys mean organisation overrides\n # homeorganisation; and secondly it picks up the stupid stupid\n # misspelling that's used by some organisations: they spelled it\n # 'orginisation'. Stupid. I picked a substring that would match\n # for US spellings, too, though I don't know if that's an issue\n # here.\n keys = shib_attr.keys()\n keys.sort()\n for k in keys:\n if ('organi' in k or 'orgini' in k) and 'type' not in k:\n t['organisation'] = shib_attr[k]\n # there are still some cases where there's no organisation set,\n # even with all that. In those cases we use the email domain\n if not t['organisation']:\n t['organisation'] = shib_attr['mail'].split('@')[1]\n # default is set to False in the new_record() method\n #\n # Note: this will always work correctly because the instance update\n # pulls in all active instances, not just the ones that have been\n # updated recently.\n if t['id'] in self.has_instance_data:\n t['has_instances'] = True\n self.data.append(t)\n\n self.transform_time = datetime.now() - start\n\n def load(self):\n start = datetime.now()\n self._load_simple()\n self.load_time = datetime.now() - start\n\n\nclass User(Entity):\n \"\"\"User entity, using the user table locally and the keystone.user table\n remotely, along with the rcshibboleth.user table.\n \"\"\"\n queries = {\n 'query': (\n \"select ku.id as id, ru.displayname as name, ru.email as email, \"\n \"ku.default_project_id as default_project, ku.enabled as enabled \"\n \"from \"\n \"{keystone}.user as ku join {rcshibboleth}.user as ru \"\n \"on ku.id = ru.user_id\"\n ),\n 'update': (\n \"replace into user \"\n \"(id, name, email, default_project, enabled) \"\n \"values (%(id)s, %(name)s, %(email)s, %(default_project)s, \"\n \"%(enabled)s)\"\n ),\n }\n\n table = \"user\"\n\n def __init__(self, args):\n super(User, self).__init__(args)\n self.db_data = []\n\n def extract(self):\n start = datetime.now()\n self._extract_no_last_update()\n self.extract_time = datetime.now() - start\n\n def transform(self):\n start = datetime.now()\n self.data = self.db_data\n self.transform_time = datetime.now() - start\n\n def load(self):\n start = datetime.now()\n self._load_simple()\n self.load_time = datetime.now() - start\n\n\nclass Role(Entity):\n \"\"\"Roles map between users and entities. This is a subset of the full range\n of mappings listed in keystone.roles, filtered to include only the\n user/project relations.\n \"\"\"\n\n queries = {\n 'query': (\n \"select kr.name as role, ka.actor_id as user, \"\n \"ka.target_id as project \"\n \"from {keystone}.assignment as ka join {keystone}.role as kr \"\n \"on ka.role_id = kr.id \"\n \"where ka.type = 'UserProject' \"\n \"AND EXISTS(select * from {keystone}.user ku \"\n \"WHERE ku.id = ka.actor_id) \"\n \"AND EXISTS(select * from {keystone}.project kp \"\n \"WHERE kp.id = ka.target_id)\"\n ),\n 'update': (\n \"replace into role \"\n \"(role, user, project) \"\n \"values (%(role)s, %(user)s, %(project)s)\"\n ),\n }\n\n table = \"role\"\n\n def __init__(self, args):\n super(Role, self).__init__(args)\n self.db_data = []\n\n def extract(self):\n start = datetime.now()\n self._extract_no_last_update()\n self.extract_time = datetime.now() - start\n\n def transform(self):\n start = datetime.now()\n self.data = self.db_data\n self.transform_time = datetime.now() - start\n\n def load(self):\n start = datetime.now()\n self._load_simple()\n self.load_time = datetime.now() - start\n\n\nclass Flavour(Entity):\n \"\"\"Flavour entity, using the flavour table locally and the nova.instance_types\n table remotely.\n \"\"\"\n\n queries = {\n 'query': (\n \"select id, flavorid as uuid, name, vcpus, memory_mb as memory, \"\n \"root_gb as root, ephemeral_gb as ephemeral, is_public as public, \"\n \"not deleted as active \"\n \"from {nova}.instance_types\"\n ),\n 'query_last_update': (\n \"select id, flavorid as uuid, name, vcpus, memory_mb as memory, \"\n \"root_gb as root, ephemeral_gb as ephemeral, is_public as public, \"\n \"not deleted as active \"\n \"from {nova}.instance_types \"\n \"where ifnull(deleted_at, now()) > %(last_update)s \"\n \" or updated_at > %(last_update)s\"\n ),\n 'update': (\n \"replace into flavour \"\n \"(id, uuid, name, vcpus, memory, root, ephemeral, public, active) \"\n \"values (%(id)s, %(uuid)s, %(name)s, %(vcpus)s, %(memory)s, \"\n \"%(root)s, %(ephemeral)s, %(public)s, %(active)s)\"\n ),\n }\n\n table = \"flavour\"\n\n def __init__(self, args):\n super(Flavour, self).__init__(args)\n self.db_data = []\n\n def extract(self):\n start = datetime.now()\n self._extract_with_last_update()\n self.extract_time = datetime.now() - start\n\n def transform(self):\n start = datetime.now()\n self.data = self.db_data\n self.transform_time = datetime.now() - start\n\n def load(self):\n start = datetime.now()\n self._load_simple()\n self.load_time = datetime.now() - start\n\n\nclass Instance(Entity):\n \"\"\"Instance entity, using the instance table locally and the nova.instances\n table remotely.\n \"\"\"\n queries = {\n 'query': (\n \"select project_id, uuid as id, display_name as name, vcpus, \"\n \"memory_mb as memory, root_gb as root, ephemeral_gb as ephemeral, \"\n \"instance_type_id as flavour, user_id as created_by, \"\n \"created_at as created, deleted_at as deleted, \"\n \"if(deleted<>0,false,true) as active, host as hypervisor, \"\n \"availability_zone, cell_name \"\n \"from {nova}.instances order by created_at\"\n ),\n 'query_last_update': (\n \"select project_id, uuid as id, display_name as name, vcpus, \"\n \"memory_mb as memory, root_gb as root, ephemeral_gb as ephemeral, \"\n \"instance_type_id as flavour, user_id as created_by, \"\n \"created_at as created, deleted_at as deleted, \"\n \"if(deleted<>0,false,true) as active, host as hypervisor, \"\n \"availability_zone, cell_name \"\n \"from {nova}.instances \"\n \"where ifnull(deleted_at, now()) > %(last_update)s \"\n \" or updated_at > %(last_update)s \"\n \"order by created_at\"\n ),\n 'update': (\n \"replace into instance \"\n \"(project_id, id, name, vcpus, memory, root, ephemeral, flavour, \"\n \"created_by, created, deleted, active, hypervisor, \"\n \"availability_zone, cell_name) \"\n \"values (%(project_id)s, %(id)s, %(name)s, %(vcpus)s, %(memory)s, \"\n \"%(root)s, %(ephemeral)s, %(flavour)s, %(created_by)s, \"\n \"%(created)s, %(deleted)s, %(active)s, %(hypervisor)s, \"\n \"%(availability_zone)s, %(cell_name)s)\"\n ),\n 'hist_agg': (\n \"replace into historical_usage \"\n \"(day, vcpus, memory, local_storage) \"\n \"values (%(day)s, %(vcpus)s, %(memory)s, %(local_storage)s)\"\n ),\n }\n\n table = \"instance\"\n\n def __init__(self, args):\n super(Instance, self).__init__(args)\n self.db_data = []\n self.hist_agg_data = []\n self.has_instance_data = {}\n self.hypervisor_az_data = {}\n\n @classmethod\n def _get_dependencies(cls):\n return set(['aggregate'])\n\n def extract(self):\n start = datetime.now()\n self._extract_with_last_update()\n try:\n self.hypervisor_az_data = Entity._get_cached_data(\"hypervisor_az\")\n except KeyError:\n pass\n self.extract_time = datetime.now() - start\n\n def new_hist_agg(self, date):\n return {\n 'day': date,\n 'vcpus': 0,\n 'memory': 0,\n 'local_storage': 0\n }\n\n def transform(self):\n # we do quite a lot of work here within a big loop because we only want\n # to traverse the (potentially very large) instances dataset once.\n start = datetime.now()\n\n # the data should be ordered by created_at, so we start by taking the\n # created_at value and use that as the starting point.\n def date_to_day(date):\n return datetime(date.year,\n date.month,\n date.day)\n hist_agg = {}\n if len(self.db_data) > 0:\n # create a list of records to be added to the historical_usate\n # table\n #\n # How to handle a partial update? Well, we need to make sure that\n # we don't put a partial day's update in, which means we need to\n # have all the data for the state of things from the last_update\n # time point forwards, rather than just the instances that have\n # been updated. So we need to change the last_updated query to\n # return all instances that were active at that point. That would\n # mean where created_at < last_update and deleted_at > last_update\n #\n # we already have a last update value\n if not self.last_update:\n orig_day = date_to_day(self.db_data[0]['created'])\n else:\n orig_day = date_to_day(self.last_update)\n # generate our storage dictionary, starting from the start date\n # we determined above\n day = orig_day\n while day < date_to_day(datetime.now()):\n hist_agg[day.strftime(\"%s\")] = self.new_hist_agg(day)\n day = day + timedelta(1)\n # Iterate over the list of instances, and update the\n # historical usage records for each one.\n for instance in self.db_data:\n # here we start from the created date, and then if that's\n # before the start date we found above we use that start date\n # instead\n day = date_to_day(instance['created'])\n if day < orig_day:\n day = orig_day\n deleted = date_to_day(datetime.now())\n if instance['deleted']:\n deleted = date_to_day(instance['deleted'])\n while day < deleted:\n key = day.strftime(\"%s\")\n hist_agg[key]['vcpus'] += instance['vcpus']\n hist_agg[key]['memory'] += instance['memory']\n hist_agg[key]['local_storage'] += (instance['root'] +\n instance['ephemeral'])\n day = day + timedelta(1)\n\n # update the project has_instance data for this instance\n self.has_instance_data[instance['project_id']] = True\n\n # and make sure that the instance's availability_zone is set\n # correctly\n instance['availability_zone'] = None\n try:\n az = self.hypervisor_az_data[instance['hypervisor']]\n instance['availability_zone'] = az\n except KeyError:\n logging.info(\n \"Hypervisor %s not found in any availability zone\",\n instance['hypervisor']\n )\n pass\n keys = hist_agg.keys()\n keys.sort()\n for key in keys:\n self.hist_agg_data.append(hist_agg[key])\n self.data = self.db_data\n Entity._cache_data('has_instance', self.has_instance_data)\n self.transform_time = datetime.now() - start\n\n def _load_hist_agg(self):\n logging.debug(\"Loading data for historical_usage table\")\n # necessary because it's entirely possible for a last_update query to\n # return no data\n if len(self.hist_agg_data) > 0 or self.dry_run:\n self._load_many('hist_agg', self.hist_agg_data)\n DB.local().commit()\n # note that we never /use/ this to determine whether to update or\n # not, this is for informational purposes only\n self.set_last_update(table=\"historical_usage\")\n\n def load(self):\n start = datetime.now()\n # comment out for sanity while testing\n self._load_simple()\n self._load_hist_agg()\n self.load_time = datetime.now() - start\n\n\nclass Volume(Entity):\n \"\"\"Volume entity, using the volume table locally and the cinder.volumes table\n remotely.\n \"\"\"\n queries = {\n 'query': (\n \"select distinct v.id, v.project_id, v.display_name, v.size, \"\n \"v.created_at as created, v.deleted_at as deleted, \"\n \"if(v.attach_status='attached',true,false) as attached, \"\n \"a.instance_uuid, v.availability_zone, not v.deleted as active \"\n \"from {cinder}.volumes as v left join \"\n \"{cinder}.volume_attachment as a \"\n \"on v.id = a.volume_id and a.deleted = 0\"\n ),\n 'query_last_update': (\n \"select distinct v.id, v.project_id, v.display_name, v.size, \"\n \"v.created_at as created, v.deleted_at as deleted, \"\n \"if(v.attach_status='attached',true,false) as attached, \"\n \"a.instance_uuid, v.availability_zone, not v.deleted as active \"\n \"from {cinder}.volumes as v left join \"\n \"{cinder}.volume_attachment as a \"\n \"on v.id = a.volume_id and a.deleted = 0 \"\n \"where ifnull(v.deleted_at, now()) > %(last_update)s \"\n \" or v.updated_at > %(last_update)s\"\n ),\n 'update': (\n \"replace into volume \"\n \"(id, project_id, display_name, size, created, deleted, attached, \"\n \"instance_uuid, availability_zone, active) \"\n \"values (%(id)s, %(project_id)s, %(display_name)s, %(size)s, \"\n \"%(created)s, %(deleted)s, %(attached)s, %(instance_uuid)s, \"\n \"%(availability_zone)s, %(active)s)\"\n ),\n }\n\n table = \"volume\"\n\n def __init__(self, args):\n super(Volume, self).__init__(args)\n self.db_data = []\n\n def extract(self):\n start = datetime.now()\n self._extract_with_last_update()\n self.extract_time = datetime.now() - start\n\n def transform(self):\n start = datetime.now()\n self.data = self.db_data\n self.transform_time = datetime.now() - start\n\n def load(self):\n start = datetime.now()\n self._load_simple()\n self.load_time = datetime.now() - start\n\n\nclass Image(Entity):\n \"\"\"Image entity, using the image table locally and the glance.image table\n remotely.\n \"\"\"\n queries = {\n 'query': (\n \"select id, owner as project_id, name, size, status, \"\n \"is_public as public, created_at as created, \"\n \"deleted_at as deleted, not deleted as active \"\n \"from {glance}.images\"\n ),\n 'query_last_update': (\n \"select id, owner as project_id, name, size, status, \"\n \"is_public as public, created_at as created, \"\n \"deleted_at as deleted, not deleted as active \"\n \"from {glance}.images \"\n \"where ifnull(deleted_at, now()) > %(last_update)s \"\n \" or updated_at > %(last_update)s\"\n ),\n 'update': (\n \"replace into image \"\n \"(id, project_id, name, size, status, public, created, deleted, \"\n \"active) values (%(id)s, %(project_id)s, %(name)s, %(size)s, \"\n \"%(status)s, %(public)s, %(created)s, %(deleted)s, %(active)s)\"\n ),\n }\n\n table = \"image\"\n\n def __init__(self, args):\n super(Image, self).__init__(args)\n self.db_data = []\n\n def extract(self):\n start = datetime.now()\n self._extract_with_last_update()\n self.extract_time = datetime.now() - start\n\n def transform(self):\n start = datetime.now()\n self.data = self.db_data\n self.transform_time = datetime.now() - start\n\n def load(self):\n start = datetime.now()\n self._load_simple()\n self.load_time = datetime.now() - start\n\n\nclass Allocation(Entity):\n \"\"\"Allocation data, using the allocation table locally and the\n dashboard.rcallocation_allocationrequest table remotely.\n \"\"\"\n queries = {\n 'query': (\n \"SELECT ra.id, project_id, project_name, \"\n \" contact_email, approver_email, \"\n \" ci.email as chief_investigator, status, start_date, end_date, \"\n \" modified_time, \"\n \" field_of_research_1, for_percentage_1, \"\n \" field_of_research_2, for_percentage_2, \"\n \" field_of_research_3, for_percentage_3, \"\n \" funding_national_percent as funding_national, \"\n \" funding_node \"\n \"FROM {dashboard}.rcallocation_allocationrequest as ra \"\n \"LEFT JOIN {dashboard}.rcallocation_chiefinvestigator as ci \"\n \"ON ra.id = ci.allocation_id \"\n \"WHERE \"\n \" parent_request_id is null and status in ('A', 'X', 'J') \"\n \"ORDER BY modified_time; \"\n ),\n 'query_last_update': (\n \"SELECT ra.id, project_id, project_name, \"\n \" contact_email, approver_email, \"\n \" ci.email as chief_investigator, status, start_date, end_date, \"\n \" modified_time, \"\n \" field_of_research_1, for_percentage_1, \"\n \" field_of_research_2, for_percentage_2, \"\n \" field_of_research_3, for_percentage_3, \"\n \" funding_national_percent as funding_national, \"\n \" funding_node \"\n \"FROM {dashboard}.rcallocation_allocationrequest as ra \"\n \"LEFT JOIN {dashboard}.rcallocation_chiefinvestigator as ci \"\n \"ON ra.id = ci.allocation_id \"\n \"WHERE \"\n \" parent_request_id is null and status in ('A', 'X', 'J') \"\n \" AND modified_time >= %(last_update)s \"\n \"ORDER BY modified_time; \"\n ),\n 'update': (\n \"REPLACE INTO allocation \"\n \"(id, project_id, project_name, contact_email, approver_email, \"\n \" chief_investigator, status, start_date, end_date, \"\n \" modified_time, \"\n \" field_of_research_1, for_percentage_1, \"\n \" field_of_research_2, for_percentage_2, \"\n \" field_of_research_3, for_percentage_3, \"\n \" funding_national, funding_node ) \"\n \"VALUES (%(id)s, %(project_id)s, %(project_name)s, \"\n \" %(contact_email)s, %(approver_email)s, %(chief_investigator)s, \"\n \" %(status)s, %(start_date)s, %(end_date)s, \"\n \" %(modified_time)s, \"\n \" %(field_of_research_1)s, %(for_percentage_1)s, \"\n \" %(field_of_research_2)s, %(for_percentage_2)s, \"\n \" %(field_of_research_3)s, %(for_percentage_3)s, \"\n \" %(funding_national)s, %(funding_node)s)\"\n ),\n 'tenant_allocation_id': (\n \"select id as project_id, \"\n \"replace(replace(substring(extra, \"\n \" locate('allocation_id', extra)+16, 5), \"\n \" '\\\"', \"\n \" ''), \"\n \" '}}', \"\n \" '') as allocation_id \"\n \"from {keystone}.project where name not like 'pt-%' \"\n \"and extra like '%allocation_id%'\"\n ),\n }\n\n table = \"allocation\"\n\n def __init__(self, args):\n super(Allocation, self).__init__(args)\n self.db_data = []\n self.tenant_allocation_data = []\n\n def extract(self):\n start = datetime.now()\n self._extract_with_last_update()\n cursor = DB.remote_cursor()\n cursor.execute(self._format_query('tenant_allocation_id'))\n self.tenant_allocation_data = cursor.fetchall()\n self.extract_time = datetime.now() - start\n\n def transform(self):\n start = datetime.now()\n # create a dict keyed on the project_id\n project_alloc = {}\n for t in self.tenant_allocation_data:\n project_alloc[t['project_id']] = t['allocation_id']\n # and on allocation_id\n allocs_by_id = {}\n for t in self.db_data:\n allocs_by_id[t['id']] = t\n # go through the raw data and look for duplicates\n alloc_dict = {}\n alloc_null_tenant = []\n for alloc in self.db_data:\n project_id = alloc['project_id']\n # deal with null tenant_uuids\n if not project_id or project_id == \"\":\n alloc['project_id'] = None\n alloc_null_tenant.append(self.dup_record(alloc))\n elif project_id not in alloc_dict:\n alloc_dict[project_id] = self.dup_record(alloc)\n else:\n # duplicated project_id - de-dup using the keystone\n # data\n try:\n alloc_id = project_alloc[project_id]\n alloc = self.dup_record(allocs_by_id[alloc_id])\n alloc_dict[project_id] = alloc\n except KeyError:\n # the project has duplicate alloctaion records\n # but no allocation_id in keystone - this should\n # be logged as a bogus allocation\n # Note: this should not happen, as manual verification\n # of the allocations data has shown that all\n # duplicated project_ids have an allocation_id in\n # keystone\n logging.info(\"Bogus allocation id %s for project %s\",\n alloc['id'], project_id)\n\n # now pull it into the final data table\n self.data = []\n keys = alloc_dict.keys()\n keys.sort()\n for k in keys:\n self.data.append(alloc_dict[k])\n for a in alloc_null_tenant:\n self.data.append(a)\n self.transform_time = datetime.now() - start\n\n def load(self):\n start = datetime.now()\n self._load_simple()\n self.load_time = datetime.now() - start\n","repo_name":"NeCTAR-RC/reporting-pollster","sub_path":"reporting_pollster/entities/entities.py","file_name":"entities.py","file_ext":"py","file_size_in_byte":58472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"11600421279","text":"budget_film = float(input())\ncount_statist = int(input())\nprice_clothes = float(input())\ndecor = budget_film * 0.10\ntotal_price_clothes = count_statist * price_clothes\nif count_statist > 150:\n total_price_clothes *= 0.90\ntotal_price = decor + total_price_clothes\ndifferent = abs(budget_film - total_price)\nif total_price > budget_film:\n print('Not enough money!')\n print(f'Wingard needs {different:.2f} leva more.')\nelse:\n print('Action!')\n print(f'Wingard starts filming with {different:.2f} leva left.')","repo_name":"petrova91/SoftUni---Courses","sub_path":"programming_basic_2022/exam_6_7_april_2019/godzilla_vs_kong.py","file_name":"godzilla_vs_kong.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"41537310129","text":"import os\nimport ntpath\nimport posixpath\n\nfrom sqlalchemy import Column, Integer, BigInteger, String, DateTime, Boolean\nfrom sqlalchemy import func, asc\nfrom sqlalchemy.schema import ForeignKey, UniqueConstraint\nfrom sqlalchemy.orm import reconstructor, relationship, backref\nfrom sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound\n\nimport akiri.framework.sqlalchemy as meta\n\nfrom mixin import BaseDictMixin\nfrom util import sizestr, is_ip, hostname_only\n\nclass Agent(meta.Base, BaseDictMixin):\n # pylint: disable=too-many-instance-attributes\n __tablename__ = 'agent'\n\n agentid = Column(BigInteger, unique=True, nullable=False,\n autoincrement=True, primary_key=True)\n conn_id = Column(BigInteger)\n envid = Column(BigInteger, ForeignKey(\"environment.envid\"))\n uuid = Column(String, unique=True, index=True)\n displayname = Column(String)\n display_order = Column(Integer)\n enabled = Column(Boolean, default=True, nullable=False)\n hostname = Column(String)\n fqdn = Column(String)\n agent_type = Column(String)\n version = Column(String)\n ip_address = Column(String)\n peername = Column(String)\n listen_port = Column(Integer)\n username = Column(String)\n password = Column(String)\n os_version = Column(String)\n installed_memory = Column(BigInteger)\n processor_type = Column(String)\n processor_count = Column(Integer)\n bitness = Column(Integer)\n install_dir = Column(String, nullable=False)\n data_dir = Column(String)\n tableau_install_dir = Column(String)\n tableau_data_dir = Column(String)\n tableau_data_size = Column(BigInteger)\n creation_time = Column(DateTime, server_default=func.now())\n modification_time = Column(DateTime, server_default=func.now(), \\\n onupdate=func.current_timestamp())\n last_connection_time = Column(DateTime, server_default=func.now())\n last_disconnect_time = Column(DateTime)\n UniqueConstraint('envid', 'displayname')\n\n def __init__(self, *args, **kwargs):\n super(Agent, self).__init__(*args, **kwargs)\n self.reconstruct()\n self.path = None\n self.server = None\n self.connection = None\n self.odbc = None\n self.firewall = None\n self.filemanager = None\n self.static_hostname = False\n\n @reconstructor\n def reconstruct(self):\n \"\"\" Basically __init__ for sqlalchemy \"\"\"\n self.server = None\n self.connection = None\n self.odbc = None\n self.firewall = None\n self.filemanager = None\n self.static_hostname = False\n\n def __getattr__(self, name):\n if name == 'iswin':\n if 'microsoft' in self.os_version.lower():\n return True\n else:\n return False\n if name == 'path':\n if 'microsoft' in self.os_version.lower():\n return ntpath\n else:\n return posixpath\n raise AttributeError(name)\n\n def connected(self):\n if not self.last_disconnect_time or \\\n self.last_disconnect_time < self.last_connection_time:\n return True # connected\n else:\n return False # not connected\n\n @classmethod\n def get_by_id(cls, agentid):\n try:\n entry = meta.Session.query(Agent).\\\n filter(Agent.agentid == agentid).one()\n except NoResultFound:\n return None\n return entry\n\n @classmethod\n def get_by_uuid(cls, envid, uuid):\n try:\n entry = meta.Session.query(Agent).\\\n filter(Agent.envid == envid).\\\n filter(Agent.uuid == uuid).one()\n except NoResultFound:\n return None\n return entry\n\n @classmethod\n def get_agentid_from_host(cls, envid, host, enabled_agents_only=True):\n \"\"\" Given a hostname, fully qualified domain name or IP address,\n return an agentid. If no agentid is found, return None.\n Hostname is treated as case insensitive.\n Note: Only enabled agents are checked.\"\"\"\n\n session = meta.Session()\n query = session.query(Agent).\\\n filter(Agent.envid == envid)\n\n if is_ip(host):\n query = query.filter(Agent.ip_address == host)\n if enabled_agents_only:\n query = query.filter(Agent.enabled == True)\n try:\n entry = query.one()\n return entry.agentid\n except NoResultFound:\n return None\n except MultipleResultsFound:\n # FIXME: log error\n pass\n return None\n\n hostname = hostname_only(host).upper()\n\n query = query.filter(func.upper(Agent.hostname) == hostname)\n if enabled_agents_only:\n query = query.filter(Agent.enabled == True)\n try:\n entry = query.one()\n return entry.agentid\n except NoResultFound:\n return None\n except MultipleResultsFound:\n # FIXME: log error\n return None\n\n @classmethod\n def display_order_by_envid(cls, envid):\n \"\"\"Returns a list of agent uuids, sorted by display_order.\"\"\"\n agent_entries = meta.Session.query(Agent).\\\n filter(Agent.envid == envid).\\\n order_by(Agent.display_order).\\\n all()\n\n agents_sorted = [entry.uuid for entry in agent_entries]\n return agents_sorted\n\n @classmethod\n def get_agentstatusentry_by_volid(cls, volid):\n vol_entry = AgentVolumesEntry.get_vol_entry_by_volid(volid)\n if not vol_entry:\n return False\n\n return meta.Session.query(Agent).\\\n filter(Agent.agentid == vol_entry.agentid).\\\n one()\n\n def todict(self, pretty=False, exclude=None):\n if exclude is None:\n exclude = []\n d = super(Agent, self).todict(pretty=pretty, exclude=exclude)\n if not 'displayname' in d:\n # We may need the displayname to exist for events, even\n # before the agent has a displayname.\n if 'hostname' in d:\n d['displayname'] = d['hostname']\n else:\n d['displayname'] = d['uuid']\n if 'username' in d:\n del d['username']\n if 'password' in d:\n del d['password']\n if pretty:\n fmt = \"%(value).0f%(symbol)s\"\n d['installed-memory-readable'] = \\\n sizestr(self.installed_memory, fmt=fmt)\n return d\n\n @classmethod\n def build(cls, envid, aconn):\n \"\"\"Create an agent from a new connection.\"\"\"\n body = aconn.auth\n session = meta.Session()\n\n uuid = body['uuid']\n\n entry = Agent.get_by_uuid(envid, uuid)\n if entry:\n # Make a copy of the object\n entry = session.merge(entry)\n # but points at the same aconn...\n else:\n entry = Agent(envid=envid, uuid=uuid)\n session.add(entry)\n\n entry.conn_id = aconn.conn_id\n entry.version = body['version']\n entry.os_version = body['os-version']\n entry.processor_type = body['processor-type']\n entry.processor_count = body['processor-count']\n entry.installed_memory = body['installed-memory']\n entry.hostname = body['hostname']\n entry.fqdn = body['fqdn']\n entry.ip_address = body['ip-address']\n entry.peername = aconn.peername\n entry.listen_port = body['listen-port']\n\n if 'static-hostname' in body:\n entry.static_hostname = bool(body['static-hostname'])\n else:\n entry.static_hostname = False\n\n # Note: Do not set agent_type here since 1) We need to know\n # what the agent_type was in the case where the row existed, and\n # 2) the agent_type isn't known yet at the time we are called anyway.\n entry.username = u'palette'# fixme\n entry.password = u'tableau2014'\n\n entry.install_dir = body['install-dir']\n\n # FIXME: make required when all agents are updated.\n if 'os-bitness' in body:\n entry.bitness = body['os-bitness']\n\n entry.last_connection_time = func.now()\n session.commit()\n\n if entry.iswin:\n entry.path = ntpath\n parts = body['data-dir'].split(':')\n entry.data_dir = ntpath.join(parts[0].upper() + ':', parts[1])\n else:\n entry.path = posixpath\n entry.data_dir = body['data-dir']\n return entry\n\n def find_space(self, needed):\n \"\"\" Find an AgentVolumesEntry with sufficient available space. \"\"\"\n entry = AgentVolumesEntry.has_available_space(self.agentid, needed)\n if not entry:\n return None\n return entry\n\nclass AgentVolumesEntry(meta.Base, BaseDictMixin):\n __tablename__ = \"agent_volumes\"\n\n volid = Column(Integer, unique=True, nullable=False, primary_key=True)\n\n agentid = Column(BigInteger,\n ForeignKey(\"agent.agentid\", ondelete='CASCADE'),\n nullable=False)\n\n name = Column(String)\n path = Column(String)\n vol_type = Column(String)\n label = Column(String)\n drive_format = Column(String)\n\n size = Column(BigInteger)\n available_space = Column(BigInteger)\n\n # Last notification about disk low or high watermark:\n # \"r\" (red), \"y\" (yellow) or null.\n watermark_notified_color = Column(String(1))\n\n system = Column(Boolean) # The OS/system is installed on this volume\n\n archive = Column(Boolean)\n archive_limit = Column(BigInteger)\n\n active = Column(Boolean)\n\n priority = Column(BigInteger)\n\n agent = relationship('Agent',\n backref=backref('volumes',\n order_by='AgentVolumesEntry.name')\n )\n UniqueConstraint('agentid', 'name')\n\n def full_path(self):\n \"\"\" This is the full path of this volume is that OS format. \"\"\"\n return self.name + \":\" + self.path\n\n def todict(self, pretty=False, exclude=None):\n d = super(AgentVolumesEntry, self).todict(pretty=pretty)\n if not self.size is None and not self.available_space is None:\n d['used'] = self.size - self.available_space\n if not pretty:\n return d\n if 'size' in d:\n d['size-readable'] = sizestr(d['size'])\n if 'available-space' in d:\n d['available-readable'] = sizestr(d['available-space'])\n if 'used' in d:\n d['used-readable'] = sizestr(d['used'])\n return d\n\n @classmethod\n def build(cls, agent, volume, install_data_dir):\n # pylint: disable=multiple-statements\n name = None; path = None; vol_type = None; label = None\n drive_format = None; archive = False; archive_limit = None\n size = None; available_space = None\n\n if volume.has_key(\"name\"):\n name = volume['name']\n if agent.iswin:\n name = volume['name'].upper()\n\n if volume.has_key('path'):\n path = volume['path']\n\n if volume.has_key(\"size\"):\n size = volume['size']\n\n if volume.has_key(\"type\"):\n vol_type = volume['type']\n if agent.iswin and vol_type == 'Fixed':\n archive = True\n path = install_data_dir\n elif not agent.iswin and volume['type'][:7] == '/dev/sd' and \\\n name != None and \\\n os.path.commonprefix([agent.data_dir, name]) == name:\n # The data-dir is on the entry's mount point so it is\n # the \"archive\" entry.\n archive = True\n path = install_data_dir\n\n if archive == True:\n if size:\n archive_limit = size # fixme: can't use whole disk\n\n if volume.has_key(\"label\"):\n label = volume['label']\n\n if volume.has_key(\"drive-format\"):\n drive_format = volume['drive-format']\n\n if volume.has_key('available-space'):\n available_space = volume['available-space']\n\n return AgentVolumesEntry(agentid=agent.agentid, name=name, path=path,\n vol_type=vol_type, label=label, drive_format=drive_format,\n archive=archive, archive_limit=archive_limit, size=size,\n available_space=available_space, active=True)\n\n @classmethod\n def has_available_space(cls, agentid, min_needed):\n \"\"\"Searches for a volume on the agent that has\n the requested disk space for archiving. If found, returns\n the volume entry. If not, returns None.\"\"\"\n\n return meta.Session.query(AgentVolumesEntry).\\\n filter(AgentVolumesEntry.agentid == agentid).\\\n filter(AgentVolumesEntry.vol_type == \"Fixed\").\\\n filter(AgentVolumesEntry.archive == True).\\\n filter(AgentVolumesEntry.active == True).\\\n filter(AgentVolumesEntry.available_space >= min_needed).\\\n filter(AgentVolumesEntry.size - \\\n AgentVolumesEntry.available_space +\n min_needed < AgentVolumesEntry.archive_limit).\\\n order_by(AgentVolumesEntry.priority.desc()).\\\n first() # for now, choosen any one - no particular order.\n\n @classmethod\n def get_vol_entry_by_agentid_vol_name(cls, agentid, vol_name):\n # pylint: disable=invalid-name\n try:\n return meta.Session.query(AgentVolumesEntry).\\\n filter(AgentVolumesEntry.agentid == agentid).\\\n filter(AgentVolumesEntry.name == vol_name).\\\n one()\n except NoResultFound:\n return None\n\n @classmethod\n def get_vol_entry_by_volid(cls, volid):\n # pylint: disable=invalid-name\n try:\n return meta.Session.query(AgentVolumesEntry).\\\n filter(AgentVolumesEntry.volid == volid).\\\n one()\n except NoResultFound:\n return None\n get_by_id = get_vol_entry_by_volid\n\n @classmethod\n def get_vol_entry_with_agent_by_volid(cls, volid):\n # pylint: disable=invalid-name\n try:\n return meta.Session.query(AgentVolumesEntry).\\\n filter(AgentVolumesEntry.volid == volid).\\\n join('agent').\\\n filter_by(agentid=AgentVolumesEntry.agentid).\\\n one()\n except NoResultFound:\n return None\n\n @classmethod\n def get_vol_archive_entries_by_agentid(cls, agentid):\n # pylint: disable=invalid-name\n return meta.Session.query(AgentVolumesEntry).\\\n filter(AgentVolumesEntry.archive == True).\\\n filter(AgentVolumesEntry.agentid == agentid).\\\n order_by(AgentVolumesEntry.name.desc()).\\\n all()\n\n @classmethod\n def get_archives_by_envid(cls, envid, enabled_agents_only=True):\n query = meta.Session.query(AgentVolumesEntry).\\\n filter_by(archive=True).\\\n join('agent').\\\n filter_by(envid=envid)\n\n if enabled_agents_only:\n query = query.filter_by(enabled=True)\n\n return query.order_by(asc('agent.display_order'), asc('name')).\\\n all()\n","repo_name":"palette-software/palette","sub_path":"controller/controller/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":15336,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"72523494471","text":"from crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Field, Submit, Div\n\nfrom django import forms\nfrom django.utils.translation import gettext_lazy as _\nfrom .models import ContactInfo\n\n\nclass ContactInfoForm(forms.ModelForm):\n class Meta:\n model = ContactInfo\n fields = (\"title\", \"first_name\", \"last_name\", \"country\", \"phone_number\")\n labels = {\n 'first_name': _('First Name'),\n 'last_name': _('Last Name'),\n 'phone_number': _('Phone Number'),\n }\n\n def __init__(self, contact_info, *args, **kwargs):\n\n super().__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.form_id = 'contact-form'\n self.helper.layout = Layout(\n Div(\n Div('title', css_class='col-md-2'),\n Div(Field('first_name', placeholder='Enter your first name'), css_class='col-md-5'),\n Div(Field('last_name', placeholder='Enter your last name'), css_class='col-md-5'),\n css_class='form-row'\n ),\n Div(\n Div('country', css_class='col-md-6'),\n Div(Field('phone_number', placeholder='Phone / WhatsApp number'), css_class='col-md-6'),\n css_class='form-row')\n )\n\n if contact_info:\n self.fields['title'].initial = contact_info.title\n self.fields['first_name'].initial = contact_info.first_name\n self.fields['last_name'].initial = contact_info.last_name\n self.fields['country'].initial = contact_info.country\n self.fields['phone_number'].initial = contact_info.phone_number\n \n","repo_name":"dhita-irma/travel-booking","sub_path":"booking/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"17521522745","text":"\"\"\"\nChange power and amplitude distribution across frequencies.\n\nNote that functions from this module rely on `scipy.signal.firwin2` and so\nactual output is not always equal to the desired output. That being said,\nthe module can not be used for tasks that require high precision (e.g., narrow\nnotch filter), but it can be used for tasks where general proximity is enough\n(e.g., imitation of resonating body).\n\nAuthor: Nikolay Lysenko\n\"\"\"\n\n\nfrom typing import List\n\nimport numpy as np\nfrom scipy.signal import convolve, firwin2\n\nfrom sinethesizer.utils.misc import mix_with_original_sound\n\n\ndef equalize_with_absolute_frequencies(\n sound: np.ndarray, event: 'sinethesizer.synth.core.Event',\n breakpoint_frequencies: List[float], gains: List[float],\n **kwargs\n) -> np.ndarray:\n \"\"\"\n Change power and amplitude distribution across frequencies.\n\n :param sound:\n sound to be modified\n :param event:\n parameters of sound event for which this function is called\n :param breakpoint_frequencies:\n frequencies (in Hz) that correspond to breaks in frequency response of equalizer\n :param gains:\n relative gains at corresponding breakpoint frequencies; a gain at an intermediate frequency\n is linearly interpolated\n :return:\n sound with altered frequency balance\n \"\"\"\n nyquist_frequency = 0.5 * event.frame_rate\n breakpoint_frequencies = [min(x / nyquist_frequency, 1) for x in breakpoint_frequencies]\n gains = [x for x in gains] # Copy it to prevent modifying original list.\n if breakpoint_frequencies[0] != 0:\n breakpoint_frequencies.insert(0, 0)\n gains.insert(0, gains[0])\n if breakpoint_frequencies[-1] != 1:\n breakpoint_frequencies.append(1)\n gains.append(gains[-1])\n # `fir_size` is odd, because else there are constraints on `gains`.\n fir_size = 2 * int(round(event.frame_rate / 100)) + 1\n fir = firwin2(fir_size, breakpoint_frequencies, gains, **kwargs)\n sound = np.vstack((\n convolve(sound[0, :], fir, mode='same'),\n convolve(sound[1, :], fir, mode='same'),\n ))\n return sound\n\n\ndef equalize_with_relative_frequencies(\n sound: np.ndarray, event: 'sinethesizer.synth.core.Event',\n breakpoint_frequencies_ratios: List[float], gains: List[float],\n **kwargs\n) -> np.ndarray:\n \"\"\"\n Change power and amplitude distribution across frequencies.\n\n :param sound:\n sound to be modified\n :param event:\n parameters of sound event for which this function is called\n :param breakpoint_frequencies_ratios:\n frequencies (represented as ratios to fundamental frequency) that correspond to breaks in\n frequency response of equalizer\n :param gains:\n relative gains at corresponding breakpoint frequencies; a gain at an intermediate frequency\n is linearly interpolated\n :return:\n sound with altered frequency balance\n \"\"\"\n fundamental_frequency = event.frequency\n breakpoint_frequencies = [x * fundamental_frequency for x in breakpoint_frequencies_ratios]\n sound = equalize_with_absolute_frequencies(\n sound, event, breakpoint_frequencies, gains, **kwargs\n )\n return sound\n\n\n@mix_with_original_sound\ndef apply_equalizer(\n sound: np.ndarray, event: 'sinethesizer.synth.core.Event',\n kind: str = 'absolute', *args, **kwargs\n) -> np.ndarray:\n \"\"\"\n Change power and amplitude distribution across frequencies.\n\n :param sound:\n sound to be modified\n :param event:\n parameters of sound event for which this function is called\n :param kind:\n kind of filter; supported values are 'absolute' and 'relative'\n :return:\n sound with altered frequency balance\n \"\"\"\n if kind == 'absolute':\n sound = equalize_with_absolute_frequencies(sound, event, *args, **kwargs)\n elif kind == 'relative':\n sound = equalize_with_relative_frequencies(sound, event, *args, **kwargs)\n else:\n raise ValueError(f\"Supported kinds are 'absolute' and 'relative', but found: {kind}\")\n return sound\n","repo_name":"Nikolay-Lysenko/sinethesizer","sub_path":"sinethesizer/effects/equalizer.py","file_name":"equalizer.py","file_ext":"py","file_size_in_byte":4108,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"27"} +{"seq_id":"24446384468","text":"import matplotlib.pyplot as plt \nimport numpy as np\nfrom pyts.transformation import ShapeletTransform\nfrom pyts.datasets import load_gunpoint\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.svm import LinearSVC\nfrom pyts.transformation import ShapeletTransform\n\nX = [[0, 2, 3, 4, 3, 2, 1],\n [0, 1, 3, 4, 3, 4, 5],\n [2, 1, 0, 2, 1, 5, 4],\n [1, 2, 2, 1, 0, 3, 5]]\ny = [0, 0, 1, 1]\nst = ShapeletTransform(n_shapelets=2, window_sizes=[3])\nX_new = st.fit_transform(X, y)\nX_new.shape\n\n# output \n(4, 2)\n\n# 搭建分类模型\nX_train, X_test, y_train, y_test = load_gunpoint(return_X_y=True)\nshapelet = ShapeletTransform(window_sizes=np.arange(10, 130, 3), random_state=42)\nsvc = LinearSVC()\nclf = make_pipeline(shapelet, svc)\nclf.fit(X_train, y_train)\nclf.score(X_test, y_test)\n\n# output\n# 0.9666666666666667\n\n# 可视化数据集\nplt.plot(X_test[0])\nplt.plot(X_test[1])\nplt.plot(X_test[2])\nplt.plot(X_test[3])\n\n# 预测\nclf.predict([X_test[0],X_test[1],X_test[2],X_test[3]])","repo_name":"NameIsAlreadyTakenY/Multi-Layer-Attention-Model-With-Dynamic-Community-Aware","sub_path":"shapelet.py","file_name":"shapelet.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18386847425","text":"from rediscluster import StrictRedisCluster\n\nstartup_nodes = [\n {\"host\": \"127.0.0.1\", \"port\": \"7000\"},\n {\"host\": \"127.0.0.1\", \"port\": \"7001\"},\n {\"host\": \"127.0.0.1\", \"port\": \"7002\"},\n]\n\ncluster = StrictRedisCluster(startup_nodes=startup_nodes,decode_responses=True)\n\n\ncluster.set('name','xiaoming')\n\nprint(cluster.get('name'))\n\n\n","repo_name":"tjhlp/FlaskProject","sub_path":"FlaskTest/day_06/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"16422983154","text":"import regex\nimport os\n\n# internal - meaning inside the bill for parts of the bill\n# or internal meaning inside of any bill?\n\n# regulation id?\n\n\n# don't count references like this:\n\n# W ustawie z dnia 30 czerwca 1970 r. o Inspekcji Skupu i Przetwórstwa Artykułów\n# Rolnych (Dz.U. z 2000 r. Nr 23, poz. 293 i Nr 89, poz. 991) w art. 3 w ust. 1 w\n# pkt 1 dodaje się lit. e) w brzmieniu:\n# \" e) domów składowych,\".\n\n\n# TODO: case to consider:\n# 8) w art. 8:\n# a) ust. 1\n# otrzymuje brzmienie:\n# (...)\n# b) w ust. 1a:\n# – pkt 2 i 3\n\n\ndef make_range(article):\n arts_range = []\n match = regex.findall(r'(?P\\d*)(?P\\p{L}*)-(?P\\d*)(?P\\p{L}*)', article)\n sn, sl, en, el = match[0]\n for i in range(int(sn), int(en) + 1):\n if sl and el:\n for j in range(ord(sl), ord(el) + 1):\n arts_range.append(str(i)+chr(j))\n else:\n arts_range.append(str(i))\n return arts_range\n\n\ndef parse_prefix_numbers(prefix, art_text):\n final_articles = []\n art_text = regex.sub(prefix, '', art_text)\n art_text = regex.sub('\\s(?:i|oraz)\\s', ', ', art_text)\n articles = regex.split(', ', art_text)\n for article in articles:\n if '-' in article:\n final_articles += make_range(article)\n else:\n final_articles.append(article)\n\n return final_articles\n\n\ndef parse_articles_only(articles):\n references = {}\n for art, ust in articles:\n # for art. X only\n arts = parse_prefix_numbers(r'art\\. ', art)\n if not ust:\n for a in arts:\n id = 'art. ' + a\n if id in references:\n n = references[id]\n references[id] = n + 1\n else:\n references[id] = 1\n return references\n\n\ndef parse_paragraphs(paragraphs):\n references = {}\n last_art = ''\n for art_ref, art, par in paragraphs:\n if art_ref:\n last_art = parse_prefix_numbers(r'art\\. ', art_ref)[-1]\n article = 'art. ' + parse_prefix_numbers(r'art\\. ', art)[-1]\n pars = parse_prefix_numbers(r'ust\\. ', par)\n if not art:\n article = regex.sub(r'A', 'a', last_art)\n\n id = article\n if id:\n id = id + ', '\n for p in pars:\n p_id = id + 'ust. ' + p\n if p_id in references:\n n = references[p_id]\n references[p_id] = n + 1\n else:\n references[p_id] = 1\n return references\n\n\ndef merge_references(rankings):\n final = {}\n for ranking in rankings:\n for id, value in ranking.items():\n if id in final:\n last_value = final[id]\n final[id] = last_value + value\n else:\n final[id] = value\n return final\n\n\ndef find_references(filepath):\n print(filepath)\n\n with open(filepath, 'r') as bill_file:\n bill = bill_file.read()\n bill = regex.sub(r'[\\t\\p{Zs}\\xA0\\n]+', ' ', bill) # remove redundant spaces\n\n # PROBLEM: with citations -> it is not that simple -> how to distinguish which \" should end the citation?\n # there are internal \"\" as well.\n\n # remove citations\n # test_citation = 'AAAAadsd „bbbbbb” \"Cccc\" ajjasjdsahs'\n # bill = regex.sub(r'(?:„\\X*?”|\"\\X*?\")', '', bill)\n\n # Articles may be 'Art. D+L*'\n\n # find fragments starting with 'Art. X' (until next Art or $?)\n sentences = regex.findall(\n r\"(?P(?:^|)Art\\.\"\n r\"\\X*?)(?=Art\\.|$)\"\n # r\")\"\n r\"\",\n bill)\n # 'Po ust. 2 dodaje się ust. 2a w brzmieniu:')\n\n parts = []\n # find the fragments with these references\n for sentence in sentences:\n\n part = regex.findall(\n r\"(?:^|\\.)\"\n r\"(?P(?!r\\.|poz.)\\X*\"\n r\"(?:art\\.|ust\\.)\\X*)\"\n # r\"(?P(?:,)\\X*)\"\n r\"\",\n sentence\n )\n if not part:\n # print(\"\\n***\\nSENT\", sentence)\n # print()\n pass\n else:\n parts.append(part[0])\n\n rankings = []\n for fragment in parts:\n\n test_sentence = 'Art. 2. Bart. 1, art: 200a, 20bb. W art. 100-103 w ust. 300, 200 i 10 byyyy,' \\\n ' art. 400, 20. W art. 23 i 40, art. 30.' \\\n ' Art. 3. W art. 500: 18) ust. 1, 502-505 i 60, bo ust. 70-78. W art. 90 i 91, art. 100.'\n # art. X (, X i X-X)\n\n # saves ust if it follows\n # finds both if art. (X) ust. (X)\n art = regex.findall(\n r\"(?P\\bart(?:\\.|:)\" # art. lub art:\n # r\"(?:(?P\\bArt\\.\\s\\d+(?:\\p{L}|))\\X*?)?(?P\\bart\\.\"\n r\"(?:\"\n r\"(?:,\\s|\\s|\\si\\s|-|\\soraz\\s)\"\n r\"\\d+(?:\\p{L}*|)\"\n r\")+\"\n r\")(?:(?::\\s\\d+\\)|:\\s\\p{L}+\\))|:|)\" # ': a) ' lub ': 19) lub '' lub ': '\n r\"(?:\\s(?:w\\s|)\" # 'ust.' lub 'w ust.' lub ': '\n r\"(?P\\bust(?:\\.|:)\"\n r\"(?:\"\n r\"(?:,\\s|\\s|\\si\\s|-|\\soraz\\s)\"\n r\"\\d+(?:\\p{L}*|)\"\n r\")+)\"\n # r\"(?=,\\s\\p{L}|\\.|$|:)(?\\bArt\\.\\s\\d+(?:\\p{L}|))\\X*?)?(?:(?P\\bart(?:\\.|:)\"\n r\"(?:\"\n r\"(?:,\\s|\\s|\\si\\s|-|\\soraz\\s)\"\n r\"\\d+(?:\\p{L}*|)\"\n r\")+\"\n r\")(?:(?::\\s\\d+\\)|:\\s\\p{L}+\\))|:|)\\s)*(?:w\\s|)\"\n r\"(?P\\bust(?:\\.|:)\"\n r\"(?:\"\n r\"(?:,\\s|\\s|\\si\\s|-|\\soraz\\s)\"\n r\"\\d+(?:\\p{L}*|)\"\n r\")+\"\n r\")\",\n # test_sentence\n fragment\n )\n\n result = parse_articles_only(art)\n result.update(parse_paragraphs(ust))\n\n # ordered = sorted(result.items(), key=lambda x: x[1], reverse=True)\n # for r in ordered:\n # print(r)\n\n # print(ordered)\n rankings.append(result)\n\n ranking = merge_references(rankings)\n print(\"*** RANKING ***\")\n ordered = sorted(ranking.items(), key=lambda x: x[1], reverse=True)\n for r in ordered:\n print(\"{} - {}\".format(r[1], r[0]))\n print()\n return ranking\n\n\ndef main():\n dir_path = 'ustawy'\n all_references = []\n\n n = 0\n for filename in os.listdir(dir_path):\n if n < 2000:\n all_references.append(find_references('{}/{}'.format(dir_path, filename)))\n n = n + 1\n\n # ranking = merge_references(all_references)\n # ordered = sorted(ranking.items(), key=lambda x: x[1], reverse=True)\n # for r in ordered:\n # print(r)\n\n # for testing:\n # filename = '2000_136.txt'\n # all_references.append(find_references('{}/{}'.format(dir_path, filename)))\n\n # print(\"*** RANKING ***\")\n # aggregated = aggregate_rankings(all_references)\n # print_ranking(aggregated)\n\nmain()\n","repo_name":"katabana/NLP","sub_path":"1-regexp/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":7307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"40650255646","text":"import adv_common as common\n\n@common.elapsed_time_factory()\ndef process_contents(contents):\n # print(contents)\n result = 0\n horizontal_position = 0\n depth = 0\n aim = 0\n for pair in contents:\n direction, value = pair.split()\n value = int(value)\n if direction == 'forward':\n horizontal_position += value\n depth += (aim * value)\n elif direction == 'down':\n aim += value\n elif direction == 'up':\n aim -= value\n result = horizontal_position * depth\n return result\n\nif __name__ == \"__main__\":\n contents = common.read_input()\n result = process_contents(contents)\n common.print_result(result, 2015547716)","repo_name":"HectorBravo/adventofcode","sub_path":"2021/py/day_2_2.py","file_name":"day_2_2.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"16086797900","text":"# 2'. Напишите программу, которая найдёт произведение пар чисел списка. Парой считаем первый и последний элемент, второй и предпоследний и т.д.\nls1 = [1, 2, 3, 4, 5]\nls2 = [1, 2, 3, 4]\ndef Summa_par(ls):\n res = []\n if len(ls)%2==0:\n for i in range(int(len(ls)/2)):\n res.append(ls[i]*ls[len(ls) - i - 1])\n print(\"Новый список из произведений пар: \", res)\n else:\n k = int(len(ls)/2)\n for i in range(int(len(ls)/2)):\n res.append(ls[i]*ls[len(ls) - i - 1])\n res.append(ls[k]**2)\n print(\"Новый список из произведений пар: \", res)\n\nSumma_par(ls1)\nSumma_par(ls2)","repo_name":"Romka678/Python","sub_path":"HomeWork№3/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"37278730878","text":"def sequence(phrase):\n seq = list()\n map = [\n [2, [['A', 'a'], ['B', 'b'], ['C', 'c']]], \n [3, [['D', 'd'], ['E', 'e'], ['F','f']]],\n [4, [['G', 'g'], ['H', 'h'], ['I', 'i']]],\n [5, [['J', 'j'], ['K', 'k'], ['L', 'l']]],\n [6, [['M', 'm'], ['N', 'n'], ['O', 'o']]],\n [7, [['P', 'p'], ['Q', 'q'], ['R', 'r'], ['S', 's']]],\n [8, [['T', 't'], ['U', 'u'], ['V', 'v']]],\n [9, [['W', 'w'], ['X', 'x'], ['Y', 'y'], ['Z', 'z']]]\n ]\n\n for i in range(len(phrase)) :\n isLower = True if ord(phrase[i]) >= 97 else False\n\n if 48 <= ord(phrase[i]) <= 57 or phrase[i] == '#' or phrase[i] == '*' :\n seq.append(phrase[i])\n elif phrase[i] == ' ' :\n seq.append('0')\n elif phrase[i-1] == phrase[i] :\n seq.append('p')\n else :\n idx = getIdx(map, phrase[i]) +2\n cnt = getCount(map, phrase[i], idx, isLower)\n\n for j in range(cnt) :\n seq.append(chr(48+idx))\n\n s = \"\"\n for i in range(len(seq)) :\n s += str(seq[i])\n return s\n\ndef getIdx(map, target) :\n idx = 0\n for i in range(len(map)) :\n for j in range(len(map[i][1])) :\n if target in map[i][1][j] :\n idx = i \n break\n return idx \n\ndef getCount(seq, target, idx, lower) :\n cnt = 0\n l_idx = 1 if lower else 0\n for k in range(len(seq[idx-2][1])) :\n cnt += 1\n if ord(seq[idx-2][1][k][l_idx]) == ord(target) :\n break\n return 1 if cnt == 0 else cnt","repo_name":"Roktar/codewars","sub_path":"lang/python/D%/dumbphone_keypads.py","file_name":"dumbphone_keypads.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"22278464868","text":"class UppercaseTuple(tuple):\n\n def __new__(cls, iterable):\n upper_iterable = (element.upper() for element in iterable)\n return super().__new__(cls, upper_iterable)\n\n # Error: tuples are immutable, even in init\n # def __init__(self, iterable):\n # print(f'init {iterable}')\n # for i, arg in enumerate(iterable):\n # self[i] = arg.upper()\n\n\nif __name__ == \"__main__\":\n\n print(\"UPPERCASE TUPLE EXAMPLE\")\n print(UppercaseTuple([\"hi\", \"there\"]))\n","repo_name":"thesaintraphael/python-stuff","sub_path":"classes/__new__ vs __init__/immutable_uppercase_tuple_example.py","file_name":"immutable_uppercase_tuple_example.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"32925318079","text":"from django.views.generic.create_update import update_object, delete_object\nfrom django.views.generic.list_detail import object_list\nfrom django.template import RequestContext\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.humanize.templatetags.humanize import ordinal\nfrom django.core.urlresolvers import reverse\nfrom django.db.models import Q\n\nfrom timesheet.timer.forms import ActivityForm\nfrom timesheet.timer.models import Activity\nimport datetime\n\n# TODO: Can I retreive this through the URL resolution methods?\ndef _get_current_time_string():\n current_time = datetime.datetime.now()\n\n return current_time.strftime('%A, %B ') + ordinal(current_time.strftime('%d')) + current_time.strftime(' %I:%M:%S %p')\n\n@login_required(login_url='/account/login/')\ndef activity_list(request, *args, **kwargs):\n if 'template_name' not in kwargs:\n kwargs['template_name'] = 'timesheet/list.html'\n\n if 'queryset' not in kwargs:\n kwargs['queryset'] = Activity.objects.today().filter(delegate=request.user)\n\n if 'template_object_name' not in kwargs:\n kwargs['template_object_name'] = 'activity'\n\n return object_list(request, *args, **kwargs)\n\n@login_required(login_url='/account/login/')\ndef create_activity(request, *args, **kwargs):\n if request.user.has_perm('timer.add_activity') is not True:\n raise Http404()\n\n if request.method == 'POST':\n form = ActivityForm(request.POST)\n\n form.instance.delegate = request.user\n\n if form.is_valid():\n form.save()\n\n return HttpResponseRedirect(reverse('timesheet-activity-list'))\n else:\n form = ActivityForm(request.POST)\n else:\n form = ActivityForm()\n\n extra_context = {\n 'current_time': _get_current_time_string,\n 'todays_activities': Activity.objects.today().filter(delegate = request.user),\n 'form': form,\n }\n\n return render_to_response('timesheet/create.html', extra_context, context_instance=RequestContext(request))\n\n@login_required(login_url='/account/login/')\ndef update_activity(request, *args, **kwargs):\n if request.user.has_perm('timer.change_activity') is not True:\n raise Http404()\n\n if 'template_name' not in kwargs:\n kwargs['template_name'] = 'timesheet/update.html'\n\n if 'form_class' not in kwargs:\n kwargs['form_class'] = ActivityForm\n\n if 'post_save_redirect' not in kwargs:\n kwargs['post_save_redirect'] = reverse('timesheet-activity-list')\n\n return update_object(request, *args, **kwargs)\n\n@login_required(login_url='/account/login/')\ndef delete_activity(request, *args, **kwargs):\n if request.user.has_perm('timer.delete_activity') is not True:\n raise Http404()\n\n if 'template_name' not in kwargs:\n kwargs['template_name'] = 'timesheet/delete.html'\n\n if 'post_delete_redirect' not in kwargs:\n kwargs['post_delete_redirect'] = reverse('timesheet-activity-list')\n\n if 'model' not in kwargs:\n kwargs['model'] = Activity\n\n return delete_object(request, *args, **kwargs)\n\n@login_required(login_url='/account/login/')\ndef activity_timer(request, *args, **kwargs):\n if request.method == 'POST':\n try:\n this_activity = Activity.objects.get(delegate=request.user, finished_original=None)\n this_activity.finished_original = datetime.datetime.now()\n\n except Activity.DoesNotExist:\n this_activity = Activity()\n this_activity.started_original = datetime.datetime.now()\n\n if this_activity.delegate is None:\n this_activity.delegate = request.user\n\n this_activity.save()\n\n # Delete activities that don't consist of at least 15 minutes. TODO: Verify that we want this.\n if this_activity.started == this_activity.finished:\n this_activity.delete()\n\n return HttpResponseRedirect('/')\n\n try:\n this_activity = Activity.objects.get(delegate=request.user, finished_original=None)\n clock_in = False\n\n except Activity.DoesNotExist:\n clock_in = True\n\n template_data = {\n 'current_time': _get_current_time_string,\n 'todays_activities': Activity.objects.today().filter(delegate = request.user),\n 'clock_in': clock_in\n }\n\n return render_to_response('timesheet/activity_timer.html', template_data,\n context_instance=RequestContext(request))\n\n","repo_name":"Mention-xx/Mention1","sub_path":"src/timesheet/timer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4513,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"23504023486","text":"\"\"\"Main Mathser logic.\"\"\"\n\nDELIMITER = \"==========\"\n\n\ndef get_questions() -> list[str]:\n \"\"\"Get questions from a source file.\n\n Returns:\n The content of the source file as a list.\n \"\"\"\n with open(\"assets/questions.txt\", \"r\") as file:\n content = file.read()\n return list(\n filter(\n lambda question: question not in [\"\", \"\\n\"],\n content.split(DELIMITER),\n )\n )\n\n\ndef parse_questions(questions: list[str]) -> dict[str, str]:\n \"\"\"Parse questions from a string.\n\n Args:\n questions: The string containing the questions\n\n Returns:\n A list of questions\n \"\"\"\n parsed_questions = {}\n return parsed_questions\n\n\nif __name__ == \"__main__\":\n # get the content\n content = get_questions()\n # split the content into questions\n parsed_questions = parse_questions(content)\n # print the questions\n for question in parsed_questions:\n print(question)\n","repo_name":"strickvl/maths_questioner","sub_path":"src/mathser.py","file_name":"mathser.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"40629279025","text":"import json\nimport subprocess\nimport signal\nimport argparse\nimport threading\nimport time\nimport numpy as np\nimport math\nimport os\n\nparser = argparse.ArgumentParser(description='Run a hindsight-grpc benchmark')\nparser.add_argument(\"out\", metavar=\"DIR\", type=str, help=\"Output directory for process logs and results\")\nparser.add_argument(\"--benchmark\", metavar=\"BENCHMARK\", type=str, default=\"two\", help=\"Name of the benchmark to run. Currently supported benchmarks: one two four. Default two\")\nparser.add_argument(\"--tmp\", metavar=\"DIR\", type=str, default=\"\", help='Output directory for temporary output (primarily, collector traces). If not specified then we wont write traces to disk')\nparser.add_argument(\"--hindsight\", metavar=\"PATH\", type=str, default=\"~/hindsight\", help='Path to hindsight directory. Default ~/hindsight')\nparser.add_argument(\"--ot_collector\", metavar=\"PATH\", type=str, default=\"~/otel46/otelcontribcol_linux_amd64\", help='Path to opentelemetry collector binary. Default ~/otel46/otelcontribcol_linux_amd64')\nparser.add_argument(\"--server_concurrency\", metavar=\"NUM\", type=int, default=8, help='Value to use for server --concurrency parameter. Default 8')\nparser.add_argument(\"--server_rate\", metavar=\"NUM\", type=int, default=10, help='Network bandwidth limit for hindsight agents. Default 10')\nparser.add_argument(\"--nocompute\", action='store_true', help='Set servers to -nocompute mode. Default false')\nparser.add_argument(\"--tracing\", metavar=\"TRACER\", type=str, default=\"none\", help='Tracer to use for server --tracing parameter. Valid options come from the ./server binary -- none hindsight ot-jaeger etc. Default none')\nparser.add_argument('-c', \"--clients\", metavar=\"NUM\", type=int, default=1, help='Number of concurrent clients for client --concurrency parameter. Default 1.')\nparser.add_argument('-r', \"--requests\", metavar=\"NUM\", type=int, default=1, help='Number of requests to configure for client --requests parameter. Default 1')\nparser.add_argument(\"--openloop\", action='store_true', help='Sets clients to -openloop mode. Default false.')\nparser.add_argument('-s', \"--sampling\", metavar=\"NUM\", type=str, default=\"\", help='Sampling / trigger percentage to use. With opentelemetry this sets head-sampling probability. With hindsight this sets trigger percentage. Default 0')\nparser.add_argument(\"--silent\", action='store_true', help='By default we will prompt before proceeding with the experiment. Set this to disable.')\nparser.add_argument('-d', \"--duration\", metavar=\"NUM\", type=int, default=30, help='Benchmark duration in seconds. Default 30')\n\n\nclass Benchmark:\n \n def __init__(self, name, topology, gateways):\n self.name = name\n self.topology = topology\n self.gateways = gateways\n self.addresses_filename = \"../config/%s_addresses.json\" % topology\n self.topology_filename = \"../config/%s_topology.json\" % topology\n self.otel_config_filename = \"../config/sample_otel_collector_config.yaml\"\n self.files = []\n self.processes = []\n \n def load(self):\n with open(self.addresses_filename, \"r\") as f:\n data = json.load(f)\n self.services = dict()\n for service in data[\"addresses\"]:\n self.services[service[\"name\"]] = service\n \n def summarize(self, args):\n print(\"Benchmark %s:\" % (self.name, ))\n print(\" Writing output to %s\" % args.out)\n if args.tmp == \"\":\n print(\" Not writing temporary output\")\n else:\n print(\" Writing temporary output to %s\" % args.tmp)\n\n tracing = \"tracing=%s\" % args.tracing\n if args.tracing==\"hindsight\" or args.tracing==\"ot-hindsight\":\n if args.sampling == \"\":\n tracing = \"tracing=%s, no triggers\" % args.tracing\n else:\n tracing = \"tracing=%s, trigger=%s\" % (args.tracing, args.sampling)\n elif args.tracing.startswith(\"ot-\"):\n if args.sampling == \"\":\n tracing = \"tracing=%s, no sampling\" % args.tracing\n else:\n tracing = \"tracing=%s, head-sampling=%s\" % (args.tracing, args.sampling)\n \n if args.nocompute:\n print(\" Servers: %d, concurrency=%d, %s\" % (len(self.services), args.server_concurrency, tracing))\n else:\n print(\" Servers: %d nocompute, concurrency=%d, %s\" % (len(self.services), args.server_concurrency, tracing))\n \n if args.openloop:\n print(\" Clients: %d openloop, %d r/s (%d r/s total)\" % (args.clients, args.requests, args.requests * args.clients))\n else:\n print(\" Clients: %d closedloop, concurrency %d (%d total)\" % (args.clients, args.requests, args.requests * args.clients))\n \n if args.tracing == \"hindsight\" or args.tracing==\"ot-hindsight\":\n print(\" Hindsight Agents: %d; 1 collector; 1 coordinator\" % len(self.services))\n elif args.tracing == \"ot-jaeger\":\n print(\" OpenTelemetry Collectors: 1\")\n \n print(\"Benchmark duration: %ds\" % args.duration)\n \n\n\n \n def reset_shm(self, args):\n files = [\"complete_queue\", \"triggers_queue\", \"pool\", \"breadcrumbs_queue\", \"available_queue\"]\n for service in self.services:\n for file in files:\n cmd = [\"rm\", \"-v\", \"/dev/shm/%s__%s\" % (service, file)]\n child = subprocess.Popen(cmd)\n child.wait()\n print(\"Reset shm\")\n \n def mkdirs(self, args):\n mkdirs = False\n if not os.path.isdir(args.out):\n print(\"out dir %s does not exist.\" % args.out)\n mkdirs = True\n if args.tmp != \"\":\n if not os.path.isdir(args.tmp):\n print(\"tmp dir %s does not exist.\" % args.tmp)\n mkdirs = True\n if mkdirs and not args.silent:\n print(\"Press to create it or CTRL-C to abort\")\n input()\n \n if not os.path.isdir(args.out):\n os.makedirs(args.out)\n if args.tmp != \"\" and not os.path.isdir(args.tmp):\n os.makedirs(args.tmp)\n \n def get_cpu_usage(self, args):\n pids = \",\".join([str(p.pid) for p in self.processes])\n cmd_args = [\"ps\"]\n cmd_args += [\"--ppid\", pids]\n cmd_args += [\"-p\", pids]\n cmd_args += [\"-o\", \"%cpu,%mem,cmd\"]\n print(\" \".join(cmd_args))\n output = \"%s/cpu.out\" % args.out\n with open(output, \"w\") as f:\n child = subprocess.Popen(cmd_args, stdout=f, stderr=f)\n child.wait()\n\n\n def stop(self, args):\n for p in self.processes:\n try:\n os.killpg(os.getpgid(p.pid), signal.SIGINT)\n except Exception as e:\n print(str(e)) \n for p in self.processes:\n p.wait()\n for f in self.files:\n try:\n f.close()\n except Exception as e:\n print(str(e))\n self.processes = []\n self.files = []\n \n def run_client(self, args):\n cmd_args = [\"./client\"]\n cmd_args += [\"--addresses=%s\" % self.addresses_filename]\n cmd_args += [\"--topology=%s\" % self.topology_filename]\n cmd_args += [\"--concurrency=%d\" % args.clients]\n cmd_args += [\"--requests=%d\" % args.requests]\n if args.sampling != \"\" and args.tracing.startswith(\"ot-\"):\n cmd_args += [\"--sampling=%s\" % args.sampling]\n if args.openloop:\n cmd_args += [\"--openloop\"]\n cmd_args += self.gateways\n\n cmd = [str(v) for v in cmd_args]\n print(\" \".join(cmd))\n \n output = \"%s/client.out\" % args.out\n f = open(output, \"w\")\n self.files.append(f)\n\n p = subprocess.Popen(cmd, stdout=f, stderr=f, cwd=\"../build\", preexec_fn=os.setsid)\n self.processes.append(p)\n \n def run_servers(self, args):\n trigger_installed = False\n for servicename, service in self.services.items():\n cmd_args = [\"./server\"]\n cmd_args += [\"--addresses=%s\" % self.addresses_filename]\n cmd_args += [\"--topology=%s\" % self.topology_filename]\n cmd_args += [\"--concurrency=%d\" % args.server_concurrency]\n if args.sampling != \"\" and (args.tracing == \"hindsight\" or args.tracing == \"ot-hindsight\") and not trigger_installed:\n cmd_args += [\"--trigger=7:%s\" % args.sampling]\n trigger_installed = True # only fire the trigger at one server\n if args.tracing == \"ot-jaeger\":\n cmd_args += [\"--otel_host=localhost\"]\n cmd_args += [\"--otel_port=6833\"] # all servers should be able to use same OT port\n if args.nocompute:\n cmd_args += [\"--nocompute\"]\n cmd_args += [\"--tracing=%s\" % args.tracing]\n cmd_args += [service[\"name\"]]\n\n cmd = [str(v) for v in cmd_args]\n print(\" \".join(cmd))\n \n output = \"%s/%s.out\" % (args.out, servicename)\n f = open(output, \"w\")\n self.files.append(f)\n\n p = subprocess.Popen(cmd, stdout=f, stderr=f, cwd=\"../build\", preexec_fn=os.setsid)\n self.processes.append(p)\n\n def run_agents(self, args):\n if args.tracing != \"hindsight\" and args.tracing != \"ot-hindsight\":\n return []\n\n for servicename, service in self.services.items():\n cmd_args = [\"go\", \"run\", \"cmd/agent2/main.go\"]\n cmd_args += [\"-serv\", service[\"name\"]]\n cmd_args += [\"-host\", service[\"hostname\"]]\n cmd_args += [\"-port\", service[\"agent_port\"]]\n cmd_args += [\"-lc\", \"localhost:5252\"]\n cmd_args += [\"-r\", \"localhost:5253\"]\n cmd_args += [\"-rate\", args.server_rate]\n\n cmd = [str(v) for v in cmd_args]\n print(\" \".join(cmd))\n\n output = \"%s/agent_%s.out\" % (args.out, servicename)\n f = open(output, \"w\")\n self.files.append(f)\n\n p = subprocess.Popen(cmd, stdout=f, stderr=f, cwd=\"%s/agent\" % args.hindsight, preexec_fn=os.setsid)\n self.processes.append(p)\n\n def run_backends(self, args):\n if args.tracing == \"hindsight\" or args.tracing == \"ot-hindsight\":\n cmd_args = [\n \"go\", \"run\", \"cmd/collector/main.go\",\n \"-port\", \"5253\"\n ]\n if args.tmp != \"\":\n cmd_args += [\"-out\", \"%s/collector.out\" % args.tmp]\n\n cmd = [str(v) for v in cmd_args]\n print(\" \".join(cmd))\n\n output = \"%s/hindsight_collector.out\" % args.out\n f = open(output, \"w\")\n self.files.append(f)\n\n p = subprocess.Popen(cmd, stdout=f, stderr=f, cwd=\"%s/agent\" % args.hindsight, preexec_fn=os.setsid)\n self.processes.append(p)\n\n\n if args.tracing == \"hindsight\" or args.tracing == \"ot-hindsight\":\n cmd_args = [\n \"go\", \"run\", \"cmd/coordinator/main.go\",\n \"-port\", \"5252\"\n ]\n if args.tmp != \"\":\n cmd_args += [\"-out\", \"%s/coordinator.out\" % args.tmp]\n\n cmd = [str(v) for v in cmd_args]\n print(\" \".join(cmd))\n\n output = \"%s/hindsight_coordinator.out\" % args.out\n f = open(output, \"w\")\n self.files.append(f)\n\n p = subprocess.Popen(cmd, stdout=f, stderr=f, cwd=\"%s/agent\" % args.hindsight, preexec_fn=os.setsid)\n self.processes.append(p)\n \n if args.tracing == \"ot-jaeger\":\n cmd_args = [\n args.ot_collector,\n \"--config\", \"%s/%s\" % (os.getcwd(), self.otel_config_filename)\n ]\n\n cmd = [str(v) for v in cmd_args]\n print(\" \".join(cmd))\n\n output = \"%s/opentelemetry_collector.out\" % args.out\n f = open(output, \"w\")\n self.files.append(f)\n\n p = subprocess.Popen(cmd, stdout=f, stderr=f, cwd=args.tmp, preexec_fn=os.setsid)\n self.processes.append(p)\n \n def process_traces(self, args):\n if args.tmp == \"\":\n return\n\n cmd_args = [\"./process\"]\n cmd_args += [\"%s/collector.out\" % args.tmp]\n\n cmd = [str(v) for v in cmd_args]\n print(\" \".join(cmd))\n \n output = \"%s/process.out\" % args.out\n f = open(output, \"w\")\n self.files.append(f)\n\n p = subprocess.Popen(cmd, stdout=f, stderr=f, cwd=\"../build\")\n p.wait()\n \n\n\nbenchmarks = dict([\n (\"one\", Benchmark(\"one\", \"single_server\", [\"service1\"])),\n (\"two\", Benchmark(\"two\", \"two\", [\"service1\"])),\n (\"four\", Benchmark(\"four\", \"four\", [\"service1\"])),\n (\"ten\", Benchmark(\"ten\", \"ten\", [\"service1\"]))\n])\n\n\ndef run(args):\n valid_tracers = [\n \"none\", \"hindsight\", \"ot-noop\", \"ot-stdout\", \n \"ot-local\", \"ot-jaeger\", \"ot-hindsight\"]\n if args.tracing not in valid_tracers:\n print(\"Unknown tracer %s\" % args.tracing)\n print(\"Expected one of: %s\" % valid_tracers)\n exit(1)\n \n if args.benchmark not in benchmarks:\n print(\"Unknown benchmark %s\" % args.benchmark)\n print(\"Expected one of: %s\" % list(benchmarks.keys()))\n exit(1)\n\n if args.tracing == \"ot-jaeger\" and args.tmp == \"\":\n print(\"Cannot run ot-jaeger tracing without setting --tmp directory\")\n exit(1)\n \n benchmark = benchmarks[args.benchmark]\n benchmark.load()\n benchmark.summarize(args)\n\n if not args.silent:\n print(\"Proceed with benchmark %s? Press to continue or CTRL-C to abort\" % args.benchmark)\n input()\n\n benchmark.reset_shm(args)\n benchmark.mkdirs(args)\n\n exit_flag = threading.Event()\n\n def signal_handler(sig, frame):\n print(\"Killing experiment processes...\")\n exit_flag.set()\n signal.signal(signal.SIGINT, signal_handler)\n\n\n print(\"Running for %d seconds\" % args.duration)\n benchmark.run_servers(args)\n benchmark.run_backends(args)\n time.sleep(5)\n benchmark.run_agents(args)\n benchmark.run_client(args)\n \n\n exit_flag.wait(args.duration)\n\n print(\"Stopping benchmark...\")\n benchmark.get_cpu_usage(args)\n benchmark.stop(args)\n benchmark.process_traces(args)\n\nif __name__ == '__main__':\n args = parser.parse_args()\n args.tmp = os.path.expanduser(args.tmp)\n args.out = os.path.expanduser(args.out)\n args.hindsight = os.path.expanduser(args.hindsight)\n args.ot_collector = os.path.expanduser(args.ot_collector)\n exit(run(args))\n","repo_name":"vishwanath1306/microbricks-copy","sub_path":"benchmark/run_benchmark.py","file_name":"run_benchmark.py","file_ext":"py","file_size_in_byte":14554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"74702870790","text":"#!/usr/bin/env python\nimport os\nfrom RouToolPa.Tools.Abstract import Tool\n\n\nclass Bowtie2(Tool):\n def __init__(self, path=\"\", max_threads=4):\n Tool.__init__(self, \"bowtie2\", path=path, max_threads=max_threads)\n\n def index(self, reference, index_name):\n options = \"%s %s\" % (reference, index_name)\n self.execute(options, cmd=\"bowtie2-build\")\n\n def align(self,\n bowtie2_index,\n forward_reads_list=None,\n reverse_reads_list=None,\n unpaired_reads_list=None,\n quality_score=\"phred33\",\n alignment_mode=\"very-sensitive\",\n find_discordant_alignments=True,\n find_separated_alignments=True,\n max_insert_size=None,\n output_prefix=\"alignment\",\n output_format=\"bam\",\n read_group_name=\"reads\",\n PU=\"x\",\n SM=\"sample\",\n platform=\"Illumina\",\n LB=\"x\",\n mark_duplicates=True,\n sort_by_coordinate=False,\n sort_by_name=False,\n max_per_sorting_thread_memory=None,\n softclipping_penalty=None, local_alignment=False):\n\n options = \" -p %i\" % self.threads\n options += \" --local\" if local_alignment else \"\"\n options += \" --%s\" % alignment_mode\n options += \" --%s\" % quality_score\n options += \" -x %s\" % bowtie2_index\n options += \" -X %i\" % max_insert_size if max_insert_size else \"\"\n options += \" --rg-id %s\" % read_group_name\n options += \" --rg \\'PU:%s\tSM:%s\tPL:%s\tLB:%s\\'\" % (PU, SM, platform, LB)\n options += \" --no-discordant\" if not find_discordant_alignments else \"\"\n options += \" --no-mixed\" if not find_separated_alignments else \"\"\n options += \" -1 %s -2 %s\" % (forward_reads_list if isinstance(forward_reads_list, str) else \",\".join(forward_reads_list),\n reverse_reads_list if isinstance(reverse_reads_list, str) else\",\".join(reverse_reads_list)) \\\n if forward_reads_list and reverse_reads_list else \"\"\n\n options += \" -U %s\" % ( unpaired_reads_list if isinstance(unpaired_reads_list, str) else \",\".join(unpaired_reads_list)) if unpaired_reads_list else \"\"\n options += \" 2>%s.stats\" % output_prefix\n if sort_by_coordinate or sort_by_name:\n if sort_by_coordinate and sort_by_name:\n raise ValueError(\"Sorting by both coordinate and read name was requested\")\n options += \" | samtools view -b | samtools sort\"\n if sort_by_name:\n options += \" -n\"\n options += \" -@ %i\" % self.threads\n options += \" -m %s\" % max_per_sorting_thread_memory if max_per_sorting_thread_memory else self.max_per_thread_memory\n options += \" -O %s\" % output_format.upper()\n\n if mark_duplicates:\n options += \" | samtools fixmate\"\n options += \" -@ %i\" % self.threads\n options += \" -m - - \"\n\n options += \" | samtools sort\"\n options += \" -@ %i\" % self.threads\n options += \" -m %s\" % max_per_sorting_thread_memory if max_per_sorting_thread_memory else self.max_per_thread_memory\n\n options += \" | samtools markdup\"\n options += \" -@ %i\" % self.threads\n options += \" - %s.%s\" % (output_prefix, output_format)\n else:\n options += \" > %s.%s\" % (output_prefix, output_format)\n\n self.execute(options)\n\n","repo_name":"mahajrod/RouToolPa","sub_path":"RouToolPa/Tools/Alignment/Bowtie2.py","file_name":"Bowtie2.py","file_ext":"py","file_size_in_byte":3513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"30792936253","text":"\"\"\"\nClass Config Helper\n@author Irfan Andriansyah \n\"\"\"\nimport os\nfrom configparser import ConfigParser\n\n\nclass ConfigHelper:\n \"\"\"\n Config Helper Helper\n \"\"\"\n\n config: ConfigParser\n\n def __init__(self, filename: str):\n \"\"\"\n Constructor\n :param filename: str\n \"\"\"\n self.set_config(filename)\n\n def set_config(self, filename: str):\n \"\"\"\n initial config based on filename\n :param filename: str\n \"\"\"\n try:\n self.config = ConfigParser()\n self.config.read(\n os.path.join(\n os.path.dirname(\n os.path.dirname(\n os.path.dirname(\n os.path.dirname(os.path.abspath(__file__))\n )\n )\n ), filename\n )\n )\n except Exception as err:\n raise Exception(err)\n\n def get(self, section: str, key: str) -> str:\n \"\"\"\n Get object config based on key and section in config files\n :param section: str\n :param key: str\n \"\"\"\n try:\n return self.config.get(section, key)\n except Exception as err:\n raise Exception(err)\n","repo_name":"mochnurhalimizd/Match-V1","sub_path":"app/utils/config/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"7902235996","text":"\"\"\"\nGiven a 2D integer matrix A of size N x M.\n\nFrom A[i][j] you can move to A[i+1][j], if A[i+1][j] > A[i][j], or can move to A[i][j+1] if A[i][j+1] > A[i][j].\n\nThe task is to find and output the longest path length if we start from (0, 0).\n\nNOTE:\n\nIf there doesn't exist a path return -1.\n\n\n A = [ [1, 2, 3, 4]\n [2, 2, 3, 4]\n [3, 2, 3, 4]\n [4, 5, 6, 7]\n ]\n\nat each step we can choose to go right or down\nmax(solve(down), solve(right))\npass on a visited \nremove curr from visited at the end\n\n\n\n\n\n\"\"\"\nimport collections\nfrom typing import List, Set, Tuple\n\n\nMatrix = List[List[int]]\nPair = collections.namedtuple('Pair', 'row col')\nCache = Set[Pair]\n\n\nclass Solution:\n\t# @param A : list of list of integers\n\t# @return an integer\n\tdef solve(self, matrix: Matrix) -> int:\n\t\tif not matrix or not matrix[0]:\n\t\t\treturn -1\n\t\tvisited: Cache = set()\n\t\treturn self.get_max_path(matrix, Pair(0, 0), visited)\n\n\tdef get_max_path(self, matrix: Matrix, position: Pair, \n\t\t\t\t\t visited: Cache) -> int:\n\t\tif position in visited:\n\t\t\treturn 0\n\t\tvisited.add(position)\n\t\tdown: Pair = Pair(position.row + 1, position.col)\n\t\tright: Pair = Pair(position.row, position.col + 1)\n\t\tmax_path: int = 0\n\t\tif self.is_valid(position, down, matrix):\n\t\t\tmax_path = self.get_max_path(matrix, down, visited)\n\t\tif self.is_valid(position, right, matrix):\n\t\t\tmax_path = max(max_path, self.get_max_path(matrix, right, visited))\n\t\tvisited.discard(position)\n\t\treturn max_path+1\n\t\t\n\tdef is_valid(self, position: Pair, other: Pair, matrix: Matrix) -> bool:\n\t\tif self.out_bounds(position, matrix) or self.out_bounds(other, matrix):\n\t\t\treturn False\n\t\treturn matrix[position.row][position.col] < matrix[other.row][other.col]\n\n\tdef out_bounds(self, position: Pair, matrix: Matrix) -> bool:\n\t\treturn (position.col < 0 or position.row < 0 or \n\t\t\t\tposition.col > len(matrix[0]) or \n\t\t\t\tposition.row > len(matrix))\n\t\t\n","repo_name":"JadielTeofilo/General-Algorithms","sub_path":"src/interviewbit/dp/increasing_path_in_matrix.py","file_name":"increasing_path_in_matrix.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"31245515489","text":"import pytest\nfrom src.day_06_solution import find_start\n\n\n@pytest.mark.parametrize(\n \"message,position\",\n [\n (\"mjqjpqmgbljsphdztnvjfqwrcgsmlb\", 7),\n (\"bvwbjplbgvbhsrlpgdmjqwftvncz\", 5),\n (\"nppdvjthqldpwncqszvftbrmjlhg\", 6),\n (\"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg\", 10),\n (\"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw\", 11)\n ]\n)\ndef test_find_start_of_packet(message, position):\n assert find_start(message, 4) == position\n\n\n@pytest.mark.parametrize(\n \"message,position\",\n [\n (\"mjqjpqmgbljsphdztnvjfqwrcgsmlb\", 19),\n (\"bvwbjplbgvbhsrlpgdmjqwftvncz\", 23),\n (\"nppdvjthqldpwncqszvftbrmjlhg\", 23),\n (\"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg\", 29),\n (\"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw\", 26)\n ]\n)\ndef test_find_start_of_message(message, position):\n assert find_start(message, 14) == position\n","repo_name":"dvalp/advent_of_code","sub_path":"2022/tests/test_day_06_solution.py","file_name":"test_day_06_solution.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"3775079467","text":"from FileLoader import FileLoader\nfrom YoungestFellah import youngest_fellah\n\ndef main():\n\tdata = FileLoader.load(\"../data/athlete_events.csv\").drop_duplicates(subset='Name')\n\tprint('2004:', youngest_fellah(data, 2004))\n\tprint('2012:', youngest_fellah(data, 2012))\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"AntoineA67/42-ai-bootcamp","sub_path":"04/ex01/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"39523683641","text":"class Node:\n\tdef __init__(self, value, address):\n\t\tself.value = value\n\t\tself.address = address\n\nclass Stack:\n\tdef __init__(self):\n\t\tself.head = Node(None, None)\n\t\tself.end = Node(None, None)\n\t\n\tdef append(self, newValue):\n\t\tnextNode = self.head.address\n\t\twhile nextNode is not None:\n\t\t\tnextNode = nextNode.address\n\t\tnextNode.address = Node(newValue, None)\n\t\tself.end = nextNode\n\t\treturn nextNode\n\n\tdef remove(self):\n\t\tnextNode = self.head\n\t\twhile nextNode is not None:\n\t\t\tnextNode = nextNode.address\n\t\tif nextNode == self.head:\n\t\t\treturn None\n\t\toutput = nextNode.value\n\t\tnextNode = None\n\t\treturn output\n\t\n\tdef getAllValues(self):\n\t\tvalues = []\n\t\tnextNode = self.head\n\t\twhile nextNode is not None:\n\t\t\tvalues.append(nextNode.value)\n\t\treturn values\n\nl = Stack()\nl.append(3)\nl.append(4)\nprint(l.getAllValues())","repo_name":"oof2win2/protab-2021","sub_path":"prednasky/datove_struktury/spojovy_seznam.py","file_name":"spojovy_seznam.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"43032546626","text":"import os\nimport torchvision\nfrom matplotlib import pyplot as plt\nimport torch\nimport glob\nimport os\nfrom shutil import copyfile\nfrom io import BytesIO\nfrom PIL import Image\nimport time\nimport heapq\nfrom heapq import heappush\nfrom heapq import heappop\nfrom torchvision import datasets\nimport sys\n\n\nimport gc\ngc.collect()\ntorch.cuda.empty_cache() \n\n\ncheckpoint_path = './models/model_best_age.pth.tar'\n# checkpoint_path = 'checkpoint1283.pth.tar'\ndata_folder = \"D:\\\\MaskedFaceRecognitionCompetition\\\\dataset\\\\UTKface_inthewild-20210331T075050Z-001\\\\UTKface_inthewild\\\\classification\\\\age_separate\\\\test\"\n\nnum_classes = 1\nshape = 224\nBATCHSIZE = 1\n\n\ntransform = torchvision.transforms.Compose([\n torchvision.transforms.Resize(shape),\n torchvision.transforms.CenterCrop(shape),\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n])\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\narch = 'resnet50'\nmodel = torchvision.models.__dict__[arch](pretrained=False)\nmodel.fc = torch.nn.Linear(2048, num_classes)\nmodel.fc.weight.data.normal_(mean=0.0, std=0.01)\nmodel.fc.bias.data.zero_()\n\nstate_dict = torch.load(checkpoint_path)\n\nparallel_model = torch.nn.DataParallel(model)\nparallel_model.load_state_dict(\n torch.load(checkpoint_path, map_location=str(device))['state_dict']\n)\n\nmodel = parallel_model.module\n\n#print(model)\n\n#model.nograd()\nmodel.eval()\nmodel.to(device)\n\ndata_transforms = {\n 'predict': transform \n }\n\n\ndataset = datasets.ImageFolder(data_folder, transform=transform)\ndataloader = {'predict': torch.utils.data.DataLoader(dataset, batch_size = BATCHSIZE , shuffle=False, pin_memory=True)}\n\ncount = 0\ntotal_correct = 0\ntotal_correctsq = 0\nwith torch.no_grad():\n for inputs, labels in dataloader['predict']:\n count += 1\n inputs = inputs.to(device)\n output = model(inputs)\n output = output.to(device)\n out_labels = output*60 + 60\n out_labels = torch.transpose(out_labels, 0, 1).to(device)\n labels = labels.to(device)\n #print(labels)\n #print(out_labels)\n correct = (abs(out_labels - labels)).float().sum().to(device)\n correct_sq = (abs(out_labels - labels)**2).float().sum()\n #print(correct)\n #print(out_labels)\n total_correct += correct\n total_correctsq += correct_sq\n #print(out_labels)\n\nprint(\"MAE = \" + str(total_correct/len(dataloader['predict'].dataset)))\nprint(\"RMSE = \" + str((total_correctsq/len(dataloader['predict'].dataset))**0.5))\n#print(\"Accuracy = \" + str(total_correct) + \"/\" + str(len(dataloader['predict'].dataset)))\n#print(\" === \" + str(total_correct/len(dataloader['predict'].dataset)) + \" ===\")\n","repo_name":"sachith500/MaskedFaceRepresentation","sub_path":"AJCAI2021/predict_age.py","file_name":"predict_age.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"27"} +{"seq_id":"29207307770","text":"import os\nimport pickle\n\nfrom sklearn.datasets import load_iris\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import LinearSVC\n\nimport mlflow\nfrom mlflow.sklearn import log_model\n\n# get port from running kubectl get services\nos.environ[\"MLFLOW_S3_ENDPOINT_URL\"] = \"http://10.99.12.53:9000/\"\nos.environ[\"AWS_ACCESS_KEY_ID\"] = \"minio\"\nos.environ[\"AWS_SECRET_ACCESS_KEY\"] = \"minio123\"\n\n\ndef main():\n\n mlflow.set_tracking_uri(\"http://10.100.163.22:5000\")\n mlflow.set_experiment(\"test-iris\")\n\n X, y = load_iris(return_X_y=True)\n\n with mlflow.start_run():\n\n #clf = LogisticRegression(random_state=0)\n clf = LinearSVC(random_state=0)\n clf.fit(X, y)\n\n mlflow.log_params(\n clf.get_params()\n )\n\n mlflow.log_metric(\"accuracy - train\", clf.score(X, y))\n\n mlflow.sklearn.log_model(clf, \"iris_svm\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"MatthiasRoels/mlflow-deployment","sub_path":"examples/train-job/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"4209705359","text":"\"\"\"\nDate:\n 23.05.11\nNumber:\n LeetCode 205\nTitle:\n Isomorphic Strings\nLevel:\n Easy\nName:\n thelight0804\n\"\"\"\n\nclass Solution(object):\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n #create two hast talbe\n table1 = {}\n table2 = {}\n\n for i in range(len(s)):\n #get value\n char1 = table1.get(s[i])\n char2 = table2.get(t[i])\n\n #None value\n if char1 is None and char2 is None:\n table1[s[i]] = t[i]\n table2[t[i]] = s[i]\n #dismatch value\n elif char1 != t[i] or char2 != s[i]:\n return False\n\n #match\n return True","repo_name":"thelight0804/Algorithm-study","sub_path":"Python/LeetCode/Num205.py","file_name":"Num205.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"32986806104","text":"\"\"\"\nRun to query all objects in AWS bucket\n\"\"\"\nimport boto3\nimport os\nprint('Connecting to s3')\ns3_client = boto3.client('s3')\ns3_resource = boto3.resource('s3')\nbucket_name = 'testpicmetric'\n# ### ASSUMING JSON FROM BACK-END\n# directory_name =\n# user_id = ’textpicmetric/\n##### CREATING DIRECTORIES FOR testpicmetric\n# import boto3\n# s3 = boto3.client(‘s3’)\n# bucket_name = “aniketbucketpython”\n# directory_name = “aniket/bucket/python” #it’s name of your folders\n# s3.put_object(Bucket=bucket_name, Key=(directory_name+‘/’))\ncurrent_region = 'us-east-2'\nfor my_bucket_object in s3_resource.Bucket(bucket_name).objects.all():\n print(my_bucket_object)\n","repo_name":"Build-Week-Pic-Metric-2/DataScience","sub_path":"Pic-Metric/flask_app/list_buckets.py","file_name":"list_buckets.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"34579536359","text":"from sqlalchemy.orm import Session\nfrom sqlalchemy import and_\n\nfrom ..interfaces import Clients\nfrom .models import Client\n\nimport pyrogram\n\n\nclass ClientsMYSQL(Clients):\n def __init__(self, engine):\n self.engine = engine\n \n def create(self, client: pyrogram.client.Client, phone_number: str, session_string: str) -> Client:\n with Session(self.engine) as session:\n client = Client(api_id=client.api_id,\n api_hash=client.api_hash,\n phone_number=phone_number,\n name=client.name,\n session_string=session_string,\n requests_balance=100)\n \n session.add(client)\n session.commit()\n return client\n \n def get_by_info(self, phone_number: str) -> Client|None:\n with Session(self.engine) as session:\n return session.query(Client).filter(\n and_(Client.phone_number == phone_number)).first()\n \n def get_by_name(self, name: str) -> Client|None:\n with Session(self.engine) as session:\n return session.query(Client).get(name)\n \n def update_by_name(self, name: str, **kwargs) -> Client:\n client = self.get_by_name(name)\n\n with Session(self.engine) as session:\n for attr, value in kwargs.items():\n client.__setattr__(attr, value)\n \n session.add(client)\n session.commit()\n return client\n\n def get_available(self) -> Client|None:\n with Session(self.engine) as session:\n return session.query(Client).filter(\n and_(Client.is_used_by == None, \n Client.requests_balance > 0)).first()\n \n def clear(self):\n with Session(self.engine) as session:\n clients = session.query(Client).all()\n for client in clients:\n client.is_used_by = None\n session.add(client)\n \n session.commit()\n \n def get(self) -> list[Client]:\n with Session(self.engine) as session:\n return session.query(Client).all()\n \n def update_values(self):\n with Session(self.engine) as session:\n for client in session.query(Client).all():\n client.requests_balance = 100\n session.commit()\n\n ","repo_name":"morpheus228/anubis_mirror_bot","sub_path":"repositories/mysql/clients.py","file_name":"clients.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"20894621266","text":"import cv2\r\nimport numpy as np\r\nvideo = cv2.VideoCapture(0)\r\nwhile True:\r\n (grabbed,frame)= video.read()\r\n if not grabbed:\r\n break\r\n blur = cv2.GaussianBlur(frame,(21,21),0)\r\n hsv = cv2.cvtColor(blur,cv2.COLOR_BGR2HSV)\r\n lower =[18,50,50]\r\n upper=[35,255,255]\r\n lower=np.array(lower,dtype=\"uint8\")\r\n upper=np.array(upper,dtype=\"uint8\")\r\n mask=cv2.inRange(hsv,lower, upper)\r\n\r\n output=cv2.bitwise_and(frame,hsv,mask=mask)\r\n no_red=cv2.countNonZero(mask)\r\n cv2.imshow(\"output\", output)\r\n cv2.imshow('original image',frame)\r\n\r\n if(no_red>10 and no_red<100):\r\n print(\"good leaf\")\r\n if(no_red>5000 and no_red<100000):\r\n print(\"leaf diseas\")\r\n print(int(no_red))\r\n if cv2.waitKey(1)&0xFF==ord('q'):\r\n break\r\ncv2.destroyAllWindows()\r\nvideo.release()\r\n","repo_name":"Shreaya-Nair/Dedection-of-Good-Bad-leaf-","sub_path":"leaf.py","file_name":"leaf.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"25313408946","text":"import random\n\ncomp_list = []\nwith open('안려환 학우\\\\코드잇\\\\프로그래밍 기초 in Python\\\\data\\\\vocabulary.txt','rt', encoding='UTF8') as d:\n for i in d:\n comp_list.append(i.strip().split(': '))\n\n\nwhile True:\n rand = random.randint(0,len(comp_list) - 1) # 그냥 for 문써서 순서대로 할 수도 있었으나 랜덤으로 물어보는게 \n check = input(f\"{comp_list[rand][1]}: \") # 단어 암기에 더 도움이 될 것이기에 이렇게 했읍니다.\n if check == comp_list[rand][0]:\n print(\"맞았습니다!\")\n elif check == 'q': # 종료가 q이고 이걸 누르기 전까진 계속 합니다.\n break\n else:\n print(f\"아쉽습니다. 정답은 {comp_list[rand][0]}입니다.\")","repo_name":"ingkoon/GeonSung","sub_path":"안려환 학우/코드잇/프로그래밍 기초 in Python/파일 읽고 쓰기/단어 퀴즈.py","file_name":"단어 퀴즈.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"42475633339","text":"import json\nimport traceback\nfrom . import _error\nfrom . import _lang\nfrom nonebot import on_command\nfrom nonebot.adapters.onebot.v11 import Message, MessageSegment\nfrom nonebot.adapters.onebot.v11.bot import Bot\nfrom nonebot.adapters.onebot.v11.event import GroupMessageEvent\nfrom typing import List\n\n# from nonebot.adapters.onebot.v11.message import MessageSegment\nfrom nonebot.exception import FinishedException\nfrom nonebot.params import CommandArg\n\nctrlGroup = json.load(open(\"data/ctrl.json\", encoding=\"utf-8\"))[\"control\"]\nfakenode = on_command(\"fakenode\", aliases={\"伪转发\"})\n\n\n@fakenode.handle()\nasync def fakenodeHandle(\n bot: Bot, event: GroupMessageEvent, msg: Message = CommandArg()\n):\n try:\n argument = str(msg).split(\"\\n\")\n group = event.get_session_id().split(\"_\")[1]\n message: List[MessageSegment] = []\n for argv in argument:\n data = argv.split(\":\")\n userData = await bot.get_stranger_info(user_id=data[0])\n message.append(\n MessageSegment.node_custom(\n user_id=data[0].strip(),\n nickname=userData[\"nickname\"],\n content=data[1].strip(),\n )\n )\n await bot.call_api(\n api=\"send_group_forward_msg\", messages=message, group_id=group\n )\n await bot.send_group_msg(\n message=_lang.text(\"fakenode.new\", [event.get_user_id(), msg]),\n group_id=ctrlGroup,\n )\n await bot.call_api(\n api=\"send_group_forward_msg\", messages=message, group_id=ctrlGroup\n )\n await fakenode.finish()\n\n except FinishedException:\n raise FinishedException()\n except Exception:\n await _error.report(traceback.format_exc(), fakenode)\n\n\n# [HELPSTART] Version: 2\n# Command: fakenode\n# Usage: fakenode :<消息>:伪造群消息转发(见fakenode(0))\n# Info: 伪造一个QQ群转发消息并发送到当前群聊\n# Msg: 伪造消息转发\n# [HELPEND]\n","repo_name":"ITCraftDevelopmentTeam/XDbot2","sub_path":"src/plugins/Core/plugins/fakenode.py","file_name":"fakenode.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"27"} +{"seq_id":"31733255530","text":"\ndef array_manipulation(elem_num, input_queries):\n \"\"\"\n Complete the function arrayManipulation in the editor below. It must return an integer, the maximum value in the resulting array.\n\n :param elem_num: the number of elements in your array\n :param input_queries: a two dimensional array of queries where each queries[i] contains three integers, a, b, and k.\n :return: the integer maximum value in the finished array.\n \"\"\"\n zeros = [0 for _ in range(elem_num + 1)]\n\n for i in input_queries:\n a, b, k = i[0], i[1], i[2]\n zeros[a - 1] += k\n zeros[b] -= k\n\n get_max = 0\n _sum = 0\n\n for i in zeros:\n _sum += i\n if _sum > get_max:\n get_max = _sum\n\n return get_max\n\n\nif __name__ == '__main__':\n nm = input().split()\n\n n = int(nm[0])\n\n m = int(nm[1])\n\n queries = []\n\n for _ in range(m):\n queries.append(list(map(int, input().rstrip().split())))\n\n result = array_manipulation(n, queries)\n\n print(str(result) + '\\n')\n","repo_name":"Dadajon/100-days-of-code","sub_path":"competitive-programming/hackerrank/data-structures/06-array-manipulation/array-manipulation.py","file_name":"array-manipulation.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"8667290822","text":"\n# 测试函数前后位置是否有影响\ndef add(a, b):\n c = multiply(a, b)\n return c + 1\n\ndef multiply(a, b):\n return a * b\n\n# 结论:不影响\nimport numpy as np\nimport os\n\n\n# 保存变量\nimport tensorflow as tf\n\n# 创建两个变量\nv1 = tf.Variable(tf.random_normal([784, 200], stddev=0.35), name=\"v_1\")\nv2 = tf.Variable(tf.zeros([200]), name=\"v_2\")\n\n# 添加用于初始化变量的节点\ninit_op = tf.global_variables_initializer()\n\n# Create a saver.\nsaver = tf.train.Saver(tf.global_variables())\n\n\n# 运行,保存变量\nwith tf.Session() as sess:\n tf.global_variables_initializer().run()\n for step in range(5000):\n sess.run(init_op)\n if step % 1000 == 0:\n saver.save(sess, 'modelTest/' + 'my-model', global_step=step)\n\n\nfrom tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file\nprint_tensors_in_checkpoint_file('modelTest/' + \"my-model-0\", None, True) # 通过这个方法,我们可以打印出保存了什么变量和值。\n\nsaver = tf.train.Saver()\nwith tf.Session() as sess:\n #tf.global_variables_initializer().run()\n module_file = tf.train.latest_checkpoint( 'modelTest')\n saver.restore(sess, module_file)\n #print(\"w1:\", sess.run(v3))\n #print(\"b1:\", sess.run(v4))\n # print(\"w1:\", sess.run(v1))\n # print(\"b1:\", sess.run(v2))\n\n\n# if __name__ == '__main__':\n# a = os.path.join('model', 'fnk.ckpt')\n# model = os.path.dirname(a) + '/'\n# print(model)\n\nif __name__ == '__main__':\n print(int(7 / 4))","repo_name":"KevinYe1014/Style-Transfer","sub_path":"Style-Transfer-test.py","file_name":"Style-Transfer-test.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18266736053","text":"import json\n\ndef build_map(t):\n m = {}\n # remove the last two element of the path\n map_path = '/'.join(__file__.split('/')[:-2]) + '/map.json'\n transform_map = json.load(open(map_path, 'r'))\n for k, v in transform_map.items():\n for k1, v1 in v['map'].items():\n if t in v1:\n if k not in m:\n m[k] = {}\n\n if 'origin' in v1[t]:\n m[k][v1[t]['origin']] = k1\n return m \n","repo_name":"EkkoG/subio","sub_path":"src/subio/unify/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"27"} +{"seq_id":"13166679154","text":"\"\"\"\nhttps://leetcode.com/problems/binary-tree-vertical-order-traversal/\nExample 1:\nsee figure in leetcode 314. Binary Tree Vertical Order Traversal\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: [[9],[3,15],[20],[7]]\n\n\"\"\"\nfrom collections import defaultdict\nfrom collections import deque\ndef verticalOrder(root):\n if not root:\n return []\n columns = defaultdict(list)\n queue = deque([(root, 0)])\n max_col, min_col = 0, 0\n while queue:\n node, col = queue.pop()\n if node:\n columns[col].append(node.val)\n queue.append((node.left, col-1))\n queue.append((node.right, col+1))\n max_col = max(max_col, col)\n min_col = min(min_col, col)\n\n res = []\n for i in range(min_col, max_col+1):\n res.append(columns[i])\n\n return res\n","repo_name":"Linda-Gong/myLeetcode_2022","sub_path":"314_binary_tree_vertical_order_traversal.py","file_name":"314_binary_tree_vertical_order_traversal.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18354397855","text":"'''The module top_k_elements allows you \n to get record_identifiers of k-largest values\n by processing file (method 'get_top_k_from_file') or\n by processing stdin (method 'process_stdin')\n\n Example:\n output = TopElements.get_top_k_from_file(k, file_path)\n where k is your desired number of max values\n output = TopElements.get_top_k_from_stdin(5, \"tests/input_test_3.txt\")\n\n Expected input format:\n \n e.g.:\n 1426828011 9\n 1426828028 350\n 1426828037 25\n Lines that do not conform to the format are ignored.\n Module notifies you about them by issuing warning message.\n\n Time complexity: O(log(k) + O(n) = O(n) \n - Algorithm itself takes O(log k) where k is your desired number of max values\n - However, processing of extremely large files exceeding available RAM\n requires reading line by line which itself is O(n) operation\n\n Space complexity: \n - O(k) where k is your desired number of max values\n\n The algorithm is based on binary heap\n\n TODO: Depends on end-users feedback. Few options:\n - speedup processing:\n - E.g. if bottleneck would be CPU and not I/O, \n we could add multiprocessing, each processing a different part of the file\n - improve user experience:\n - E.g. improve input data quality analysis so user sees how many and which lines were skipped\n - E.g. display progress % with number of processed/remaining lines\n'''\nimport unittest\nimport heapq\nimport sys\nimport logging\nimport os.path\nfrom typing import List\n\nlogger = logging.getLogger(__name__)\n\nclass TopElements:\n '''TopElements allows you \n to get record_identifiers of k-largest values\n by processing file (method 'get_top_k_from_file') or\n by processing stdin (method 'process_stdin')\n '''\n @staticmethod\n def get_top_k_from_stdin(k: int)-> List[int]:\n '''Returns top k record_identifiers associated with the highest value\n\n Args:\n k (int) : number of top k record_identifiers to be returned\n Returns:\n top_k : top k record_identifiers with the highest value\n '''\n # return empty list for k-values that are 0 or negative \n if k < 1:\n return []\n\n # variables\n top_k_candidates = [] # binary heap (min-heap)\n line_idx = 1\n \n # process stdin\n for line in sys.stdin:\n if 'Exit' == line.rstrip():\n break\n res = TopElements.__process_line(top_k_candidates, k, line)\n if res == 0:\n logging.warning(\n f'Invalid data format. Skipping this one: \\'{line}\\'') \n line_idx += 1\n\n # return top-x elements\n return TopElements.__return_top_k(top_k_candidates)\n\n @staticmethod\n def get_top_k_from_file(k: int, input_file : str = None) -> List[int]:\n '''Returns top k record_identifiers associated with the highest value\n \n Args:\n k (int): number of top k record_identifiers to be returned\n input_file (str): path to file containing data to be analyzed\n Returns:\n top_k: top k record_identifiers with the highest value \n '''\n # return empty list for k-values that are 0 or negative \n if k < 1:\n return []\n\n # variables\n top_k_candidates = [] # binary heap (min-heap)\n invalid_lines = 0\n line_idx = 1\n\n # Process input file\n try:\n f = open(input_file, 'r')\n except IOError:\n logging.error(f'Cannot open file \\'{input_file}\\'') \n return []\n\n # Reading line by line (O(n)) allows us to read extremely large files exceeding available RAM\n for line in f:\n res = TopElements.__process_line(top_k_candidates, k, line)\n if res == 0:\n invalid_lines += 1\n logging.warning(\n f'{invalid_lines}. Invalid data format. input_file: \\'{input_file}\\' Skipping line: \\'{line_idx}\\'. Line data: \\'{line}\\'') \n line_idx += 1\n f.close()\n \n # Return top-x elements\n return TopElements.__return_top_k(top_k_candidates)\n\n @staticmethod\n def __process_line(top_k_candidates: list, k: int, line: str) -> int:\n '''Process data in a given line \n and keep it between top_k_candidates \n if it has a higher value than previous candidates or if k limit was not reached yet.\n Only the highest k candicates are kept to optimize memory and handle even extremely large files. \n\n Args:\n top_k_candidates (list): number of top k elements that will be returned\n k (int): number of top k elements that will be returned\n line (str): data of a given line to be processed\n\n Returns:\n (int): 1 if the line was processed. 0 if data were in the wrong format\n\n Algorithm time complexity: O(log(k)\n Space complexity: O(k) \n ''' \n # parse the line\n # & catch and skip incorrect input line processing\n item = line.split()\n \n if len(item) != 2:\n return 0\n try:\n index = int(item[0])\n except:\n return 0\n try: \n value = int(item[1])\n except:\n return 0\n \n # Store first top k elements into the heap\n if len(top_k_candidates) < k:\n heapq.heappush(top_k_candidates, (value, index))\n\n # Keep only top k elements in the heap\n else:\n min_top_value = top_k_candidates[0][0] #It's min-heap\n if value > min_top_value:\n # Time complexity: O(log(k))\n # Space complexity: O(k)\n heapq.heappushpop(top_k_candidates, (value, index))\n return 1\n\n @staticmethod\n def __return_top_k(top_k_candidates: list) -> List[int]:\n top_k = []\n for item in top_k_candidates:\n index = item[1]\n top_k.append(index)\n\n return top_k","repo_name":"JMarcan/exercises_algorithms_data_structures_big_o","sub_path":"exercises_coding/top_k_elements_in_data/top_k_elements/top_k_elements.py","file_name":"top_k_elements.py","file_ext":"py","file_size_in_byte":6249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"27493295934","text":"from django.contrib import admin\nfrom django.urls import path, include, re_path\nfrom django.views.generic import TemplateView\nfrom rest_framework import permissions\nfrom drf_yasg.views import get_schema_view\nfrom drf_yasg import openapi\n\n\nschema_view = get_schema_view(\n openapi.Info(\n title=\"Snippets API\",\n default_version='v1',\n description=\"Test description\",\n terms_of_service=\"https://www.google.com/policies/terms/\",\n contact=openapi.Contact(email=\"contact@snippets.local\"),\n license=openapi.License(name=\"BSD License\"),\n ),\n public=True,\n permission_classes=(permissions.AllowAny,),\n)\n\nurlpatterns = [\n path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),\n path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),\n path('api-auth/', include('rest_framework.urls')),\n path('rest-auth/', include('rest_auth.urls')),\n path('rest-auth/registration/', include('rest_auth.registration.urls')),\n path('admin/', admin.site.urls),\n path('api/', include('api.urls'))\n # re_path(r'^.*', TemplateView.as_view(template_name='index.html')),\n]\n","repo_name":"iamharshkumar/appointment-management-system","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"2"} +{"seq_id":"26008814225","text":"#!/usr/bin/env python\n\nimport sys\n\nsys.path.append(\"../lib\")\nimport os\nfrom influxdb import InfluxDBClient, DataFrameClient\nimport numpy as np\nimport pandas as pd\nimport time\nfrom pyutils import *\nfrom pdutils import *\n\nfrom optparse import OptionParser\nimport simlogging\nfrom simlogging import mconsole\n''' \n This program deletes the data in the various databases either en masse or measurement by measurement\n'''\nLOGNAME=__name__\nLOGLEV = logging.DEBUG\n\ndef main():\n global logger\n kwargs = configure()\n \n logger = simlogging.configureLogging(LOGNAME=LOGNAME,LOGFILE=LOGFILE,loglev = LOGLEV,coloron=False)\n (options,_) = cmdOptions()\n kwargs = options.__dict__.copy()\n mconsole(\"Warning: this program will delete information from your database.\")\n entry = input(\"Do you want to continue? [y/N] \") or \"n\"\n if entry in ['Y','y']:\n entry = input(\"VERY DANGEROUS: Do you want to delete all of the data? [y/N] \") or \"n\"\n if entry in ['Y','y']:\n mconsole(\"Deleting all of the data\")\n kwargs['DELETEALL'] = True\n else:\n mconsole(\"OK, walking you through each measurement\")\n kwargs['DELETEALL'] = False\n for db in measuredict.keys():\n dfclient = DataFrameClient(host=INFLUXDB_IP, port=INFLUXDB_PORT, database=db)\n wtclient = InfluxDBClient(host=INFLUXDB_IP, port=INFLUXDB_PORT, database=db)\n for measure in measuredict[db]:\n try:\n tdfx = dfclient.query(\"select * from {}\".format(measure))[measure]\n except:\n mconsole(\"{}.{} has no measurements; continuing\".format(db,measure))\n continue\n mconsole(\"{}.{} has {} measurements\".format(db,measure,len(tdfx)))\n mdel = kwargs['DELETEALL']\n if not mdel:\n mconsole(\"NO RETURN: Do you want to drop all {} measurements from {}.{}\".format(len(tdfx),db,measure))\n entry = input(\"[y/N] \") or \"n\"\n if entry in ['Y','y']: mdel = True\n if mdel: deleteMeasure(db,measure,wtclient)\n\ndef deleteMeasure(db,measure,wtclient):\n mconsole(\"Dropping {}.{}\".format(db,measure))\n wtclient.drop_measurement(measure)\n\ndef configure():\n global seg_client;global df_seg_client; global df_cloudlet_icmp_client\n global df_magma_icmp_client;global df_ue_icmp_client\n global TZ; global CLOUDLET_IP; global EPC_IP;\n global INFLUXDB_IP; global INFLUXDB_PORT; global measuredict\n global LOGFILE; global LOGNAME; global LOGLEV\n\n LOGNAME=__name__\n LOGLEV = logging.INFO\n \n configfn = \"config.json\"\n cnf = {}; ccnf = {};gcnf = {}\n if configfn is not None and os.path.isfile(configfn):\n with open(configfn) as f:\n cnf = json.load(f)\n qcnf = cnf['QUERY']\n gcnf = cnf['GENERAL']\n ucnf = cnf['UE']\n ccnf = cnf['CLOUDLET']\n wcnf = cnf['MAGMA']\n ''' General '''\n key = \"epc_ip\"; EPC_IP = gcnf[key] if key in gcnf else \"192.168.25.4\"\n key = \"lelgw_ip\"; LELGW_IP = gcnf[key] if key in gcnf else \"128.2.212.53\"\n key = \"cloudlet_ip\" ; CLOUDLET_IP = gcnf[key] if key in gcnf else \"128.2.208.248\"\n key = \"ue_ip\"; UE_IP = gcnf[key] if key in gcnf else \"172.26.21.132\"\n key = \"influxdb_port\"; INFLUXDB_PORT = gcnf[key] if key in gcnf else 8086\n key = \"influxdb_ip\"; INFLUXDB_IP = gcnf[key] if key in gcnf else CLOUDLET_IP\n key = \"timezone\"; TZ = gcnf[key] if key in gcnf else \"America/New_York\"\n key = \"seg_db\"; SEG_DB = gcnf[key] if key in gcnf else \"segmentation\"\n key = \"offset_db\"; OFFSET_DB = gcnf[key] if key in gcnf else \"winoffset\"\n \n ''' necessary node specific '''\n LOGFILE= \"database_cleanup.log\"\n key = \"icmp_db\"; CLOUDLET_ICMP_DB = ccnf[key] if key in ccnf else \"cloudleticmp\"\n key = \"icmp_db\"; MAGMA_ICMP_DB = wcnf[key] if key in wcnf else \"magmaicmp\"\n key = \"icmp_db\"; UE_ICMP_DB = ucnf[key] if key in ucnf else \"ueicmp\"\n \n measuredict = {CLOUDLET_ICMP_DB:['latency'],UE_ICMP_DB:['latency'],MAGMA_ICMP_DB:['latency']\n ,SEG_DB:['segments'],OFFSET_DB:['winoffset']}\n \n ''' Get all the clients '''\n seg_client = InfluxDBClient(host=INFLUXDB_IP, port=INFLUXDB_PORT, database=SEG_DB)\n df_seg_client = DataFrameClient(host=INFLUXDB_IP, port=INFLUXDB_PORT, database=SEG_DB)\n df_cloudlet_icmp_client = DataFrameClient(host=INFLUXDB_IP, port=INFLUXDB_PORT, database=CLOUDLET_ICMP_DB)\n df_magma_icmp_client = DataFrameClient(host=INFLUXDB_IP, port=INFLUXDB_PORT, database=MAGMA_ICMP_DB)\n df_ue_icmp_client = DataFrameClient(host=INFLUXDB_IP, port=INFLUXDB_PORT, database=UE_ICMP_DB)\n df_offset_client = DataFrameClient(host=INFLUXDB_IP, port=INFLUXDB_PORT, database=OFFSET_DB)\n (options,_) = cmdOptions()\n kwargs = options.__dict__.copy()\n return kwargs\n\ndef cmdOptions():\n parser = OptionParser(usage=\"usage: %prog [options]\")\n parser.add_option(\"-d\", \"--debug\",\n action=\"store_true\", dest=\"debug\", default=False,\n help=\"Debugging mode\")\n return parser.parse_args()\n\nif __name__ == '__main__': main()","repo_name":"cmusatyalab/NetworkLatencySegmentation","sub_path":"processing/cleanDBs.py","file_name":"cleanDBs.py","file_ext":"py","file_size_in_byte":5192,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"30306409336","text":"from bs4 import BeautifulSoup as bs\nimport requests\n\nlink='https://www.amazon.in/ask/questions/asin/B07DJHV6VZ/ref=ask_rp_reva_ql_hza'\npage = requests.get(link)\n\nsoup = bs(page.content,'html.parser')\nprint(soup.prettify())\n\nnames = soup.find_all('span',class_='a-profile-name')\nprint(names)\n\ncust_name = []\nfor i in range(0,len(names)):\n cust_name.append(names[i].get_text())\nprint(cust_name)","repo_name":"aryanagrawal22/ref","sub_path":"Scrap/29.py","file_name":"29.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"7241036620","text":"import yfinance as yf\nimport streamlit as st\nimport pandas as pf\n\nst.write(\"\"\"\n# Simple Stock Price Application\n\nThe closing prices and volume of Google are shown below.\n\n\"\"\")\n\ntickerSymbol = 'GOOGL'\n\ntickerData = yf.Ticker(tickerSymbol)\n\ntickerDf = tickerData.history(period='1d', start='2010-8-20', end='2020-8-20')\n\nst.line_chart(tickerDf.Close)\nst.line_chart(tickerDf.Volume)","repo_name":"Mark1617/python-projects","sub_path":"stock-apps/Simple-Stock-Graph.py","file_name":"Simple-Stock-Graph.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"19705312922","text":"#coding:utf-8\nfrom reportlab.lib.styles import getSampleStyleSheet,ParagraphStyle\nfrom reportlab.platypus import *\nfrom reportlab.lib.units import inch,mm\nfrom reportlab.lib.enums import TA_JUSTIFY,TA_LEFT, TA_CENTER,TA_RIGHT\nimport copy\nimport reportlab.rl_config\nreportlab.rl_config.warnOnMissingFontGlyphs = 0\nfrom reportlab.pdfbase import pdfmetrics\nfrom reportlab.pdfbase.ttfonts import TTFont\nfrom reportlab.lib.pagesizes import A4\nfrom reportlab.pdfgen import canvas\nfrom reportlab.lib import fonts,colors\n\nclass rhwl(object):\n def export_pdf(self,risk_name,datas,footer_name,file_name):\n pdfmetrics.registerFont(TTFont('hei', '/usr/share/fonts/winfont/simkai.ttf'))\n\n fonts.addMapping('hei', 0, 0, 'hei')\n fonts.addMapping('hei', 0, 1, 'hei')\n\n stylesheet=getSampleStyleSheet()\n elements = []\n\n doc = SimpleDocTemplate(file_name,pagesize=A4,leftMargin=5*mm, rightMargin=5*mm,topMargin=0.5*inch,bottomMargin=0.5*inch)\n\n vnsoft_style1=copy.deepcopy(stylesheet[\"Heading1\"])\n vnsoft_style1.fontSize=24\n elements.append(Paragraph('%s'%(risk_name,),vnsoft_style1))\n elements.append(Spacer(1,12))\n\n vnsoft_style = copy.deepcopy(stylesheet[\"Heading1\"])\n vnsoft_style.fontSize=24\n vnsoft_style.alignment = TA_RIGHT\n data = [['序号','箱号','编号','姓名','性别']]\n for i in datas:\n data.append(i)\n\n #ts = [('ALIGN',(0,0),(-1,-1),'CENTER'),('FONT', (0,0), (-1,-1), 'hei')]\n ts=[\n ('FONT', (0,0), (-1,-1), 'hei'),\n\n (\"ALIGN\",(0,0),(1,-1),\"CENTER\"),\n (\"ALIGN\",(-1,0),(-1,-1),\"CENTER\"),\n (\"VALIGN\",(0,0),(-1,-1),\"MIDDLE\"),\n (\"LEADING\",(0,0),(-1,-1),24),\n ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),\n ('BOX', (0,0), (-1,-1), 0.25, colors.black),\n (\"FONTSIZE\",(0,0),(-1,-1),20),\n ]\n #TableStyle()\n table = Table(data, 0.8*inch, 0.64*inch, ts)\n table._argW[2]=1.8*inch\n table._argW[3]=3.5*inch\n elements.append(table)\n\n elements.append(Paragraph('%s'%(footer_name,),vnsoft_style))\n elements.append(Spacer(1,12))\n\n doc.build(elements)\n","repo_name":"vnsofthe/odoo-dev","sub_path":"addons/rhwl_gene/rhwl_reportlab.py","file_name":"rhwl_reportlab.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"32213334019","text":"import os\nimport sys\nsys.path.append('..')\nfrom PIL import Image\nfrom imresize import ImresizeWrapper, imresize_pil\n\n\n\ntarget_path = '/home/dataset/DIV2K/DIV2K_train_HR'\nsave_path = 'multiscale_DIV2K'\ntarget_scales = [0.75, 0.5]\nimg_name_list = sorted(os.listdir(target_path))\nimg_pil_list = [Image.open(os.path.join(target_path, gt)) for gt in img_name_list]\n\n\nif(not os.path.exists(save_path)): os.makedirs(save_path)\n\nfor img, name in zip(img_pil_list, img_name_list):\n img.save(os.path.join(save_path, name))\n\nfor scale in target_scales:\n for img, name in zip(img_pil_list, img_name_list):\n resized_img = imresize_pil(img, scale_factor=scale)\n img_name = '{}_{}'.format(scale, name)\n resized_img.save(os.path.join(save_path, img_name))\n print('>> saved {}'.format(img_name), flush=True)\n\nprint('\\n[*] END')\n","repo_name":"parkseobin/VDSR-pytorch-tf2","sub_path":"pytorch/data/make_multiscale.py","file_name":"make_multiscale.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"2"} +{"seq_id":"4651435487","text":"import yaml\nimport re\nfrom jinja2 import Environment, FileSystemLoader\nimport subprocess\nfrom contextlib import contextmanager\n\n\n# TODO:\n# relocate ResumeStyle.sty\n# figure out escapes (\\&, \\$, \\LaTeX{})\n# update header to pull from yaml\n# projects needs to be a list to preserve order\n\n\nenv = Environment(loader=FileSystemLoader(\n '/home/cldershem/Documents/resume/CurrentResume/templates'))\n\ntemplates = [\n ('Skills', 'tex'),\n # ('CoverLetter', 'tex'),\n # ('Gen', 'tex'),\n # ('Html', 'html'),\n # ('Text', 'text'),\n ('Dev', 'tex'),\n ]\n\nprefix = 'CameronDershemResume-'\noutput = './built'\n\n\ndef escape_tex(value):\n \"\"\"\n Escapes special LaTex characters.\n \"\"\"\n LATEX_SUBS = (\n (re.compile(r'\\\\'), r'\\\\textbackslash'),\n (re.compile(r'([{}_#%&$])'), r'\\\\\\1'),\n (re.compile(r'~'), r'\\~{}'),\n (re.compile(r'\\^'), r'\\^{}'),\n (re.compile(r'\"'), r\"''\"),\n (re.compile(r'\\.\\.\\.+'), r'\\\\ldots'),\n )\n newval = value\n for pattern, replacement in LATEX_SUBS:\n newval = pattern.sub(replacement, newval)\n return newval\n\n\ndef build_tex(template, name):\n \"\"\"\n Builds latex file.\n \"\"\"\n with set_env():\n with open('{}/{}{}.tex'.format(output, prefix, name), 'w+') as f:\n f.write(template.render(data=get_data()))\n\n\n@contextmanager\ndef set_env():\n \"\"\"\n Temporarily changes environmental variables for Jinja delimiters.\n \"\"\"\n old_block_start_string = env.block_start_string\n old_block_end_string = env.block_end_string\n old_variable_start_string = env.variable_start_string\n old_variable_end_string = env.variable_end_string\n old_comment_start_string = env.comment_start_string\n old_comment_end_string = env.comment_end_string\n\n env.block_start_string = '((*'\n env.block_end_string = '*))'\n env.variable_start_string = '((('\n env.variable_end_string = ')))'\n env.comment_start_string = '((='\n env.comment_end_string = '=))'\n env.filters['escape_tex'] = escape_tex\n\n yield\n\n env.block_start_string = old_block_start_string\n env.block_end_string = old_block_end_string\n env.variable_start_string = old_variable_start_string\n env.variable_end_string = old_variable_end_string\n env.comment_start_string = old_comment_start_string\n env.comment_end_string = old_comment_end_string\n\n\ndef make_pdf(template, name):\n \"\"\"\n Builds pdfs from latex.\n \"\"\"\n command = \"rubber --into {0} --pdf {0}/{2}{1}.tex\".format(\n output, name, prefix)\n # command = \"latexmk -quiet -aux-directory={0}/aux -output-directory={0} \"\\\n # \"-pdf {0}/{1}.tex\".format(output, name)\"\n subprocess.call(command.split())\n\n\ndef open_pdf(name):\n \"\"\"\n Opens pdf.\n \"\"\"\n command = \"xdg-open {}/{}{}.pdf\".format(output, prefix, name)\n subprocess.call(command.split())\n\n\ndef make_text(template, name):\n \"\"\"\n Builds text file from template.\n \"\"\"\n data = get_data()\n with open('{}/{}{}.txt'.format(output, prefix, name), 'w+') as f:\n f.write(template.render(data=data))\n\n\ndef get_data():\n \"\"\"\n Prints out the data.\n \"\"\"\n with open('resume.yaml', 'r') as ydata:\n ydata = yaml.load(ydata.read())\n return ydata\n\n\nif __name__ == '__main__':\n for template in templates:\n name, file_type = template\n template = env.get_template(\"{}.jinja\".format(name))\n if file_type == 'tex':\n build_tex(template, name)\n make_pdf(template, name)\n # open_pdf(name)\n elif file_type == 'text':\n make_text(template, name)\n elif file_type == 'html':\n pass\n else:\n pass\n","repo_name":"cldershem/Resume","sub_path":"makeresume.py","file_name":"makeresume.py","file_ext":"py","file_size_in_byte":3701,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"24660688355","text":"#연산\n\n'''\n\n중간결과도 항상 백만 이하의 자연수이다 => 중간결과를 ���상 알아야 한다!\n\nbfs를 쓰면서 for로 다음 숫자를 구할때 조건울 주어야 겠다는 생각이 들어야 한다.\n\n\n\n'''\n\nfrom collections import deque\n\n\n# def bfs():\n#\n#\n# #1. 그래프 구성 => 연산으로 대체\n# #2. 큐 만들기\n# q = deque()\n#\n#\n#\n# #3. 시작값 세팅\n# q.append(N)\n# #방문 표시\n# visited[N] = 1\n#\n# #4 ~ 6 번 반복\n# while q:\n#\n# #4. 큐에서 첫번째 값 꺼내기\n# now_num = q.popleft()\n#\n# #추가 연산 처리\n#\n# if now_num == M:\n# return visited[M] - 1 #몇번 만에 가는지를 물어보니깐! visited배열의 value를 반환하는 것!\n#\n# #5. next 찾기\n#\n# for next_num in [now_num + 1, now_num * 2, now_num -1, now_num-10]:\n# #방문하지 않은 곳\n# if 0 < next_num <= 1000000 and not visited[next_num]:\n# visited[next_num] = visited[now_num] + 1\n# q.append(next_num)\n\n\n\ndef bfs():\n\n\n q = deque()\n\n q.append(N)\n visited[N] = True\n\n ans = 0 #몇번만에 찾는지! 가장 최소를 만족한다!\n\n while q:\n size = len(q) #큐의 사이즈 만큼 반복한다! => 큐의 사이즈의 교체횟수가 곧 몇번만의 가는지 ,,!\n\n for i in range(size):\n num = q.popleft()\n if num == M:\n return ans\n\n for next_num in (num+1, num-1, num*2, num-10):\n if 0 < next_num <= 1000000 and not visited[next_num]:\n visited[next_num] = True\n q.append(next_num)\n\n ans += 1\nT = int(input())\n\nfor tc in range(1, T+1):\n\n N, M = map(int, input().split())\n\n visited = [0] * 1000001\n\n ans = bfs()\n\n print(f\"#{tc} {ans}\")\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"joojeehwan/algo_jjh","sub_path":"1015/today_review.py","file_name":"today_review.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"4968228543","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom urllib.parse import urlparse\nfrom ..items import ASINsItem\n\nclass ASINsSpider(scrapy.Spider):\n name = 'asin'\n\n # read file to get best sellers url\n with open('best_sellers_url.txt', 'r') as f:\n bs_url = f.readline()\n\n start_urls = [bs_url]\n\n def parse(self, response): # parse 100 products ASIN numbers\n items = ASINsItem()\n # find all products link\n product_links = response.xpath(\n \"//*[@id = 'zg-ordered-list']//span[@class = 'aok-inline-block zg-item']/a[1]/@href\").getall()\n for url in product_links: # parse urls to get ASIN numbers\n print(url)\n items['asin'] = urlparse(url).path.split('/')[-3] # sometimes it get nasty, we should count backwards\n yield items\n\n yield from response.follow_all(css='li.a-last a', callback=self.parse)\n\n","repo_name":"dlmf15/amazon_sellers","sub_path":"spiders/asin.py","file_name":"asin.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"9140959227","text":"import requests\r\n\r\nfrom bs4 import BeautifulSoup\r\n\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.contrib.auth.mixins import LoginRequiredMixin\r\nfrom django.http import HttpResponse, Http404\r\nfrom django.shortcuts import redirect\r\nfrom django.urls import reverse_lazy\r\nfrom django.views.generic import ListView, DeleteView\r\n\r\nfrom .services import link_replacement_function, serialize\r\nfrom .models import Site\r\n\r\n\r\nclass SitesPage(LoginRequiredMixin, ListView):\r\n model = Site\r\n template_name = 'vpn/sites.html'\r\n context_object_name = 'sites'\r\n login_url = '/login/'\r\n\r\n def get_queryset(self):\r\n return Site.objects.filter(user_id=self.request.user.id)\r\n\r\n def post(self, request, *args, **kwargs):\r\n site_name = request.POST['site_name']\r\n original_url = request.POST['original_url']\r\n Site.objects.create(site_name=site_name, original_url=original_url, user_id=request.user)\r\n return redirect('sites')\r\n\r\n\r\nclass SiteDelete(LoginRequiredMixin, DeleteView):\r\n model = Site\r\n success_url = reverse_lazy('sites')\r\n\r\n\r\nclass StatisticsPage(LoginRequiredMixin, ListView):\r\n model = Site\r\n template_name = 'vpn/statistics.html'\r\n context_object_name = 'sites'\r\n login_url = '/login/'\r\n\r\n def get_queryset(self):\r\n return Site.objects.filter(user_id=self.request.user)\r\n\r\n\r\n@login_required\r\ndef vpn_page(request, site_name, site_path=\"\"):\r\n \"\"\"Displaying a page via VPN\"\"\"\r\n try:\r\n # Checking whether a given site is in the user's list of sites\r\n site = Site.objects.get(user_id=request.user, site_name=site_name)\r\n except Site.DoesNotExist:\r\n raise Http404(\"No Site matches the given query\")\r\n\r\n # Parsing the page, changing links within the page and getting the final response\r\n url = site.original_url + site_path\r\n page = requests.get(url, stream=True)\r\n soup = BeautifulSoup(page.content, \"html.parser\")\r\n transformed_page = link_replacement_function(url=site.original_url.rstrip('/'), soup=soup, site_name=site_name)\r\n response = HttpResponse(str(transformed_page), status=page.status_code)\r\n\r\n # Counting the number of bytes sent and received\r\n request_weight_in_bytes = len(serialize(request))\r\n response_weight_in_bytes = len(response.__bytes__())\r\n site.sent_data += request_weight_in_bytes\r\n site.received_data += response_weight_in_bytes\r\n site.number_of_transitions += 1\r\n site.save()\r\n return response\r\n\r\n","repo_name":"Artemoskalenko/vpn-test-task","sub_path":"vpn/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"71315611247","text":"import pytesseract\nimport re\nimport cv2\nimport json\nimport os\n\n\n# Prompt the user for the image name\nimg_name = input(\"Enter the image filename (e.g., 06.jpg): \")\n\n# Check if the entered file exists\nif not os.path.isfile(img_name):\n print(f\"The file '{img_name}' does not exist.\")\n exit(1)\n\n# Load the image\nimg = cv2.imread(img_name)\n\n# Convertir l'image en niveaux de gris\ngray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n# Appliquer un flou gaussien pour réduire le bruit\nblurred_img = cv2.GaussianBlur(gray_img, (13, 13), 0)\n\n# Appliquer un seuil pour binariser l'image\n_, threshold_img = cv2.threshold(blurred_img, 60, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n\n# Trouver les contours dans l'image binarisée\ncontours, _ = cv2.findContours(threshold_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n# Trouver le contour le plus grand (probablement la carte d'identité)\nlargest_contour = max(contours, key=cv2.contourArea)\n\n# Obtenir les coordonnées du rectangle englobant du plus grand contour\nx, y, w, h = cv2.boundingRect(largest_contour)\n\n# Rogner l'image d'origine en utilisant les coordonnées du rectangle\ncropped_img = img[y:y+h, x:x+w]\n \nnew_img_gray = cv2.cvtColor(cropped_img, cv2.COLOR_BGR2GRAY)\n\n# Apply OCR using Tesseract \n#pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'\n\n# Set the TESSDATA_PREFIX environment variable\nos.environ['TESSDATA_PREFIX'] = '/usr/share/tesseract-ocr/4.00/tessdata/'\ntessdata_dir_config = '--tessdata-dir \"C:\\\\Program Files\\\\Tesseract-OCR\\\\tessdata\"'\nconfig = '--psm 4 --oem 3 -c textord_old_xheight=true textord_fix_xheight_bug=false preserve_interword_spaces=1 ' \n\ntext = pytesseract.image_to_string(new_img_gray, lang='fra', config = config)\n#text = re.sub(r'[\\u0600-\\u06FF]', '', text) \n\n# Function to clean extracted text\ndef clean_text(texte):\n cleaned_text = re.sub(r'[^a-zA-Z0-9\\s]', '', texte) # Remove non-alphanumeric characters\n cleaned_text = re.sub(r'\\s+', ' ', cleaned_text) # Replace multiple spaces with a single space\n return cleaned_text.strip() # Remove leading and trailing spaces\n\ndef clean_spaces(texte):\n new_text = re.sub(r'\\s+', ' ', texte)\n return new_text.strip() \n\n\n# Utilisation de regex pour extraire les informations\nnom_pattern = r'[Nn]?[Oo][Mm]\\s+(.+)' \ndate_naissance_pattern = r'(\\d{2})\\.(\\d{2})\\.(\\d{4})'\nlieu_naissance_pattern = r'[Àà][Aa]?\\s+(.*?)\\s+'\nadresse_pattern = r'[Dd][Oo][Mm][A-Za-z\\.]{2,}\\s+(.*?)\\s+'\nnom_pere_pattern = r'[d][e]\\s+(.+)'\nnom_mere_pattern = r'[e][t]\\s?[d][e]\\s+(.+)'\nprofession_pattern = r'[Pp][Rr][Oo][A-Za-z]{7}\\s+(.*?)\\s+'\nncni_pattern = r'(\\d{6})'\n\nnom_match = re.search(nom_pattern, text)\ndate_naissance_match = re.search(date_naissance_pattern, text)\nlieu_naissance_match = re.search(lieu_naissance_pattern, text)\nadresse_match = re.search(adresse_pattern, text)\nnom_pere_match = re.search(nom_pere_pattern, text)\nnom_mere_match = re.search(nom_mere_pattern, text)\nprofession_match = re.search(profession_pattern, text)\nncni_match = re.search(ncni_pattern, text)\n\nresult = {}\n\nif nom_match:\n text_nom = ' '.join(nom_match.groups()) \n #print(text_nom)\n new_nom_pattern = r'([A-Z]+)\\s+([A-Z]+)\\s+([A-Z]+)'\n text_nom_match = re.search(new_nom_pattern, text_nom)\n new_text_nom = ' '.join(text_nom_match.groups()) \n #print(new_text_nom2)\n result[\"nom\"] = new_text_nom\nelse:\n result[\"nom\"] = ''\n \nif date_naissance_match:\n day, month, year = date_naissance_match.group(1).strip(), date_naissance_match.group(2).strip(), date_naissance_match.group(3).strip()\n text_date_naissance = f'{day}/{month}/{year}' \n #print(text_date_naissance)\n result[\"date_naissance\"] = text_date_naissance\nelse:\n result[\"date_naissance\"] = ''\n \ndate_pattern = r'(\\d{2}\\.\\d{2}\\.\\d{4})'\n# Search for the date pattern in the extracted text\ndate_match = re.search(date_pattern, text)\nif date_match:\n ddd = date_match.group(1)\n\nif date_match:\n # Get the position where the date pattern ends\n date_end_position = date_match.end()\n\n # Find the start and end positions of the line after the date\n line_start_position = text.find('\\n', date_end_position) + 1\n line_end_position = text.find('\\n', line_start_position)\n\n # Extract the line after the date\n line_below_date = text[line_start_position:line_end_position].strip() \n line_below_date = clean_spaces(line_below_date) \n #print(line_below_date)\n \n # Use regular expression to capture uppercase sequences (including characters after /)\n uppercase_sequence_match = re.search(r'([A-Z/-]{4,})', line_below_date)\n # r'(? None:\n \"\"\"Generates a new scenario based on `options` and `scenario_name` stored in `CreateOptions.DIRECTORY`\"\"\"\n config = load_yaml(options[CreateOptions.CONFIG])\n\n cwd = os.getcwd()\n os.chdir(Path(options[CreateOptions.CONFIG]).parent)\n\n defaults = config[\"defaults\"]\n trace_file = load_yaml(defaults[\"trace_file\"])\n count = trace_file[\"total_count\"]\n set_random_seed(defaults, options, trace_file)\n options[\"scenario_name\"] = defaults[\"base_name\"] + f\"_{count}\"\n scenario = load_yaml(config[\"base_template\"])\n\n if \"create\" in config:\n for agent in config[\"create\"]:\n type_template = load_yaml(Path(agent[\"type_template\"]))\n agent_type_template = type_template[\"Agents\"]\n contract_type_template = type_template.get(\"Contracts\")\n n_to_create = round(get_value_from_field(agent[\"count\"], options, allow_negative=False))\n agent_name = agent[\"this_agent\"]\n external_ids = agent.get(\"external_ids\")\n\n for n in range(n_to_create):\n agent_to_append = copy.deepcopy(agent_type_template)\n agent_to_append[\"Id\"] = get_agent_id(agent_name, n, n_to_create)\n scenario[\"Agents\"].append(agent_to_append)\n\n if contract_type_template:\n contract_to_append = copy.deepcopy(contract_type_template)\n replace_ids_in_contracts(contract_to_append, agent_to_append[\"Id\"], external_ids)\n scenario[\"Contracts\"].extend(contract_to_append)\n else:\n logging.debug(DEBUG_NO_CREATE)\n\n resolve_identifiers(scenario, options)\n resolve_ids(scenario)\n os.chdir(cwd)\n options[\"scenario_path\"] = Path(options[CreateOptions.DIRECTORY], options[\"scenario_name\"] + \".yaml\")\n write_yaml(scenario, options[\"scenario_path\"])\n\n\ndef validate_input_range(input_range: Tuple[int, int], allow_negative: bool) -> NoReturn:\n \"\"\"\n Raises Exception if input range is no int or float or list of [minimum, maximum], and\n values >= 0 (if `allow_negative` = False)\n \"\"\"\n if (\n isinstance(input_range, tuple)\n and len(input_range) == 2\n and all(isinstance(i, (int, float)) for i in input_range)\n ):\n if not allow_negative:\n if any(i < 0 for i in input_range):\n log_and_raise_critical(ERR_INVALID_RANGE_INPUT.format(input_range, allow_negative))\n if input_range[0] >= input_range[1]:\n log_and_raise_critical(ERR_INVALID_RANGE_INPUT.format(input_range, allow_negative))\n else:\n log_and_raise_critical(ERR_INVALID_RANGE_INPUT.format(input_range, allow_negative))\n\n\ndef digest_range(input_value: str) -> Tuple[int, int]:\n \"\"\"Returns Tuple of minimum and maximum integer value digested from `input_value` in expected form\"\"\"\n numbers = extract_numbers_from_string(input_value)\n try:\n min_value, max_value = map(float, numbers.split(SEPARATOR))\n except ValueError:\n log_and_raise_critical(ERR_COULD_NOT_MAP_RANGE_VALUES.format(numbers))\n return min_value, max_value\n\n\ndef extract_numbers_from_string(input_value: str) -> str:\n \"\"\"Returns string in form 'int, int' from given `input_value` by removing RANGE_IDENTIFIER and '(' and ')'\"\"\"\n extracted_numbers = input_value.lower().replace(RANGE_IDENTIFIER, \"\").replace(\"(\", \"\").replace(\")\", \"\")\n return extracted_numbers\n\n\ndef digest_choose(input_value: str) -> List[Union[int, float, str]]:\n \"\"\"Returns List of options digested from given `input_value` string\"\"\"\n given_options = (\n input_value.lower()\n .replace(CHOOSE_IDENTIFIER, \"\")\n .replace(\"(\", \"\")\n .replace(\")\", \"\")\n .replace(\" \", \"\")\n .replace('\"', \"\")\n .replace(\"'\", \"\")\n )\n given_options = given_options.split(SEPARATOR)\n given_options = cast_numeric_strings(given_options)\n return given_options\n\n\ndef cast_numeric_strings(values: List[str]) -> List[Union[int, float, str]]:\n \"\"\"Returns given List of `values` but numerics are casted in their correct type\"\"\"\n casted_values = []\n for value in values:\n try:\n casted_value = int(value)\n except ValueError:\n try:\n casted_value = float(value)\n except ValueError:\n casted_value = value\n casted_values.append(casted_value)\n return casted_values\n\n\ndef digest_pickfile(input_value: str, scenario_path: Path) -> List[str]:\n \"\"\"Returns List of all files in given directory `input_value`\"\"\"\n relative_path = (\n input_value.lower()\n .replace(PICKFILE_IDENTIFIER, \"\")\n .replace(\"(\", \"\")\n .replace(\")\", \"\")\n .replace(\" \", \"\")\n .replace('\"', \"\")\n .replace(\"'\", \"\")\n )\n path_to_dir = Path(scenario_path, relative_path)\n files_in_dir = get_relative_paths_in_dir(path_to_dir, relative_path)\n return files_in_dir\n\n\ndef get_relative_paths_in_dir(path_to_dir: Path, relative_path: str) -> List[str]:\n \"\"\"Returns files in `path_to_dir` with suffix of `relative_path`\"\"\"\n files_in_dir = [\n str(Path(relative_path, f)) for f in os.listdir(path_to_dir) if os.path.isfile(os.path.join(path_to_dir, f))\n ]\n return files_in_dir\n\n\ndef get_value_from_field(input_value: Union[List[Any], Any], options: dict, allow_negative: bool = True) -> Any:\n \"\"\"\n Returns value stored in `input_value` based on the user specification 'RANGE_IDENTIFIER', 'CHOOSE_IDENTIFIER',\n 'PICKFILE_IDENTIFIER' or else just `input_value`.\n In option `RANGE_IDENTIFIER`, `allow_negative` is True as default but can limit allowed range to values >=0.\n In option `PICKFILE_IDENTIFIER`, `options[CreateOptions.DIRECTORY]` is used to get files with relative paths to scenario\n \"\"\"\n if isinstance(input_value, str):\n if RANGE_IDENTIFIER in input_value.lower():\n input_range = digest_range(input_value)\n validate_input_range(input_range, allow_negative)\n minimum, maximum = input_range\n value = random.uniform(minimum, maximum)\n logging.debug(f\"Chose random value '{value}' from '{input_value}'.\")\n elif CHOOSE_IDENTIFIER in input_value.lower():\n to_choose = digest_choose(input_value)\n value = random.choice(to_choose)\n logging.debug(f\"Chose random value '{value}' from list '{input_value}'.\")\n elif PICKFILE_IDENTIFIER in input_value.lower():\n to_pick = digest_pickfile(input_value, options[CreateOptions.DIRECTORY])\n value = random.choice(to_pick)\n logging.debug(f\"Chose random file '{value}' from path '{input_value}'.\")\n else:\n value = input_value\n logging.debug(f\"Received exactly one input value '{input_value}'.\")\n else:\n value = input_value\n logging.debug(f\"Received exactly one input value '{input_value}'.\")\n return value\n\n\ndef replace_ids_in_contracts(contracts: List[dict], agent_id: str, ext_id: Union[dict, None]) -> None:\n \"\"\"Replaces in-place `agent_id` and optional `ext_id` in given `contracts`\"\"\"\n replace_map = {KEY_THISAGENT: agent_id}\n if ext_id:\n for key, value in ext_id.items():\n if isinstance(value, int):\n replace_map[key] = value\n elif not value.startswith(REPLACEMENT_IDENTIFIER):\n replace_map[key] = REPLACEMENT_IDENTIFIER + value\n else:\n replace_map[key] = value\n\n for k, v in replace_map.items():\n replace_in_dict(contracts, k, v)\n\n\ndef replace_in_dict(contracts: List[dict], replace_identifier: str, replace_value: str) -> None:\n \"\"\"Recursively searches for `replace_identifier` in contracts and replaces `replace_value` if not integer\"\"\"\n for contract in contracts:\n for key, value in contract.items():\n if isinstance(value, str) and replace_identifier in value:\n contract[key] = replace_value\n\n\ndef get_all_ids_from(scenario: dict) -> List[int]:\n \"\"\"Returns list of unique Agent Ids in given `scenario`\"\"\"\n unique_ids = []\n for agent in scenario[\"Agents\"]:\n append_unique_integer_id(agent[\"Id\"], unique_ids)\n return unique_ids\n\n\ndef append_unique_integer_id(agent_id: Union[str, int], unique_ids: List[int]):\n \"\"\"Appends `agent_id` to `unique_ids` if integer and unique\"\"\"\n if isinstance(agent_id, int) and agent_id not in unique_ids:\n unique_ids.append(agent_id)\n\n\ndef create_new_unique_id(unique_ids: List[int]) -> int:\n \"\"\"Returns new unique integer by adding 1 to the highest Id in `unique_ids`. Adds new Id in-place to `unique_ids`\"\"\"\n new_id = max(unique_ids) + 1 if unique_ids else 1\n unique_ids.append(new_id)\n return new_id\n\n\ndef resolve_ids(scenario: dict) -> None:\n \"\"\"Resolves in-place all placeholder ID references in Agents & Contracts to unique Ids\"\"\"\n active_ids = get_all_ids_from(scenario)\n replacement_map: Dict[str, int] = {}\n for agent in scenario[\"Agents\"]:\n agent_id = agent[\"Id\"]\n if REPLACEMENT_IDENTIFIER in str(agent_id):\n if agent_id in replacement_map.keys():\n agent[\"Id\"] = replacement_map[agent_id]\n else:\n unique_id = create_new_unique_id(active_ids)\n agent[\"Id\"] = replacement_map[agent_id] = unique_id\n for contract in scenario[\"Contracts\"]:\n for key, value in contract.items():\n if REPLACEMENT_IDENTIFIER in str(value):\n try:\n contract[key] = replacement_map[value]\n except KeyError:\n log_and_raise_critical(ERR_FAILED_RESOLVE_ID.format(value, contract))\n\n\ndef resolve_identifiers(input_value: Any, options: dict) -> Any:\n \"\"\"\n Iterates over (potentially nested) `input_value` and returns values from fields\n considering options in `get_value_from_field`\n \"\"\"\n for key, value in input_value.items():\n if isinstance(value, dict):\n resolve_identifiers(value, options)\n elif isinstance(value, list):\n for index, item in enumerate(value):\n if isinstance(item, dict):\n resolve_identifiers(item, options)\n else:\n input_value[key][index] = get_value_from_field(item, options)\n else:\n input_value[key] = get_value_from_field(value, options)\n\n\ndef get_agent_id(agent_name: str, agent_number: int, n_of_agents_to_create: int) -> str:\n \"\"\"\n Returns `agent_id` with leading REPLACEMENT_IDENTIFIER for `agent_name` considering its `agent_number`\n and `n_of_agents_to_create`\n \"\"\"\n agent_id = REPLACEMENT_IDENTIFIER + agent_name\n agent_id += str(agent_number) if n_of_agents_to_create > 1 else \"\"\n return agent_id\n\n\ndef set_random_seed(defaults: dict, options: dict, trace_file: dict) -> None:\n \"\"\"Sets random seed if not yet saved to `options['random_seed']`\"\"\"\n if not options.get(\"random_seed\"):\n random_seed = get_random_seed(defaults)\n random.seed(random_seed + trace_file[\"total_count\"])\n options[\"random_seed\"] = trace_file[\"random_seed\"] = random_seed\n save_seed_to_trace_file(options, random_seed)\n\n\ndef get_random_seed(defaults: dict) -> int:\n \"\"\"Returns random seed as integer, defined optionally in `defaults['seed']` or from system time in ns instead\"\"\"\n if defaults.get(\"seed\"):\n random_seed = defaults[\"seed\"]\n else:\n random_seed = time.time_ns()\n return random_seed\n","repo_name":"FEAT-ML/scengen","sub_path":"scengen/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":12542,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"25012685620","text":"from typing import List\n\nimport pandas as pd\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\n\nclass ColumnDifferenceTransformer(BaseEstimator, TransformerMixin):\n \"\"\"Class to calculate the difference between two columns in a pd.DataFrame.\n\n Parameters\n ----------\n diff_columns : list\n A list of tuples with column names. For example [(col1, col2), ...],\n where col2 will be subtracted from col1.\n new_columns : list\n List of columns names for the new column created from the subtraction.\n drop_cols : bool\n Boolean flag for whether to drop the old columns after the new column\n is created.\n \"\"\"\n\n def __init__(\n self,\n diff_columns: List[tuple],\n new_columns: List[str],\n drop_cols: bool,\n ):\n\n super().__init__()\n\n if not isinstance(diff_columns, list):\n raise TypeError(\"diff columns should be a list of tuples\")\n\n if not isinstance(new_columns, list):\n raise TypeError(\"new_columns should be a list\")\n\n if not isinstance(drop_cols, bool):\n raise TypeError(\"drop_cols should be a bool\")\n\n if len(diff_columns) != len(new_columns):\n raise ValueError(\n \"diff_columns and new_columns should be the same length\"\n )\n\n self.diff_columns = diff_columns\n self.new_columns = new_columns\n self.drop_cols = drop_cols\n\n def transform(self, X):\n \"\"\"Calculates the differences for the provided list of column tuples.\n\n Parameters\n ----------\n X : pd.DataFrame\n Dataframe containing the columns in the diff_columns list.\n\n Returns\n -------\n X : pd.DataFrame\n Dataframe with the new difference columns, optionally with the old\n columns dropped.\n \"\"\"\n\n if not isinstance(X, pd.DataFrame):\n raise TypeError(\"X should be a pd.DataFrame\")\n\n all_columns = [\n val for col_tuple in self.diff_columns for val in col_tuple\n ]\n\n for col in all_columns:\n missing_columns = []\n if col not in X.columns.values:\n missing_columns.append(col)\n if len(missing_columns) != 0:\n raise ValueError(f\"Missing columns: {missing_columns}\")\n\n X = X.copy()\n\n for i in range(len(self.new_columns)):\n X[self.new_columns[i]] = (\n X[self.diff_columns[i][0]] - X[self.diff_columns[i][1]]\n )\n\n if self.drop_cols:\n X.drop(columns=all_columns, inplace=True)\n\n return X\n","repo_name":"nedwebster/starcraft_predictor","sub_path":"starcraft_predictor/modelling/custom_transformers.py","file_name":"custom_transformers.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"39982853125","text":"# Дан список целых чисел. На��ти минимальное среди простых чисел и\n# максимальное среди чисел, не являющихся простыми\n# [6, 3, 8, 5, 7, 9, 3, 6, 5, 13, 1]\n# Min: 3\n# Max: 9\n\ndef is_it_prime(k):\n if k == 2 or k == 3:\n return True\n if k % 2 == 0 or k < 2:\n return False\n for a in range(3, int(k ** 0.5) + 1, 2):\n if k % a == 0:\n return False\n return True\n\n\nlst = [6, 3, 8, 5, 7, 9, 3, 6, 5, 13, 1]\nlst_prime = []\nlst_noprime = []\nfor i in lst:\n if is_it_prime(i):\n lst_prime.append(i)\n else:\n lst_noprime.append(i)\nprint(f\"{lst}\\nMin: {min(lst_prime)}\\nMax: {max(lst_noprime)}\")\nprint(f\"Список простых чисел: {lst_prime}\\nСписок непростых чисел {lst_noprime}\")\n","repo_name":"AlanKolmakov/HomeWork_Python","sub_path":"py/part2/HomeWork_19.py","file_name":"HomeWork_19.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"27616742716","text":"import streamlit as st\nfrom engine.analysis_engine import AnalysisEngine\n\n#st.title('Fair Value Calculator')\n\nst.set_page_config(page_title=\"My App\",layout='wide')\n\ndef color(val):\n color = 'green' if val else 'red'\n return f'background-color: {color}'\n\n\ndef execute_model():\n try:\n engine = AnalysisEngine(ticker=ticker.lower())\n\n engine.prepare_data()\n engine.growth_analysis()\n st.dataframe(engine.income,height=1000,width=2000)\n #col_gr,col_quality = st.columns(2)\n #with col_gr:\n st.dataframe(engine.ratio, height=1000, width=2000)\n #with col_quality:\n st.dataframe(engine.cf,height=1000,width=2000)\n #st.dataframe(engine.quality_check_dataframe.T.style.applymap(color,subset=['valuation']),height=1000, width=2000)'''\n st.dataframe(engine.growths,height=1000,width=2000)\n option = st.selectbox(\"Valuation Method\", ['Discount Methods','EV/Ebitda'], index=0)\n if option==\"Discount Methods\":\n col1,col2,col3 = st.columns(3)\n with col1:\n years = st.selectbox(\"Years of Analysis\", [3, 5, 7, 10])\n revenue_gr = st.text_input(\"Revenue Growth % (You could insert multiple growth rate separated by ',' - es. 10,8)\",placeholder=\"10\")\n discount_rate = st.text_input(\"Discount Rate\", placeholder=\"12.5\")\n fair_value_btn = st.button(\"Discount Model\",disabled=False)\n with col2:\n fcf_margin = st.text_input(\"Free Cash Flow Margin %\",placeholder=\"10\")\n net_margin = st.text_input(\"Net Margin %\",placeholder=\"10\")\n with col3:\n terminal_multiple = st.text_input(\"Terminal Value\",placeholder=\"16\")\n perpetuity = st.text_input(\"Perpetuity Growth\",placeholder=\"0.03\")\n if fair_value_btn:\n if len(terminal_multiple)==0:\n terminal_multiple=16\n else:\n terminal_multiple = int(terminal_multiple)\n if len(revenue_gr)==0:\n st.errors(\"Revenue Growth is mandatory\")\n else:\n grs = revenue_gr.split(\",\")\n revenue_gr = [float(g)/100 for g in grs]\n if len(fcf_margin)==0:\n fcf_margin=None\n else:\n fcf_margin=float(fcf_margin)\n if len(net_margin) == 0:\n net_margin = None\n else:\n net_margin = float(net_margin)\n if len(perpetuity) == 0:\n perpetuity = 0.03\n else:\n perpetuity = float(perpetuity)\n if len(discount_rate) == 0:\n discount_rate = 0.125\n else:\n discount_rate = float(discount_rate)/100\n engine.discounted_cash_flow_analysis(\n years=years,\n discount_rate=discount_rate,\n terminal_value=terminal_multiple,\n perpetuity_growth=perpetuity,\n revenue_growth_rate=revenue_gr,fcf_margin=fcf_margin,net_margin=net_margin)\n st.dataframe(engine.future_cf, height=1000, width=2000)\n st.dataframe(engine.terminal_information, width=1000, height=2000)\n st.dataframe(engine.discount_cash_flow_final_custom,width=1000,height=2000)\n st.dataframe(engine.discount_cash_flow_final_analyst,width=1000,height=2000)\n if option == \"EV/Ebitda\":\n st.error(\"Not implemented yet\")\n col1, col2 = st.columns(2)\n with col1:\n years = st.selectbox(\"Years of Analysis\", [3, 5, 7, 10])\n revenue_gr = st.text_input(\n \"Revenue Growth % (You could insert multiple growth rate separated by ',' - es. 10,8)\",\n placeholder=\"10\")\n discount_rate = st.text_input(\"Discount Rate\", placeholder=\"12.5\")\n fair_value_btn = st.button(\"EV/Ebitda Valuation\", disabled=False)\n with col2:\n ebtda_margin = st.text_input(\"Ebitda Margin %\", placeholder=\"10\")\n terminal_multiple = st.text_input(\"Terminal Value\", placeholder=\"10\")\n if fair_value_btn:\n if len(terminal_multiple) == 0:\n terminal_multiple = 10\n else:\n terminal_multiple = int(terminal_multiple)\n if len(revenue_gr) == 0:\n st.errors(\"Revenue Growth is mandatory\")\n else:\n grs = revenue_gr.split(\",\")\n revenue_gr = [float(g) / 100 for g in grs]\n if len(ebtda_margin) == 0:\n ebitda_margin = None\n else:\n ebitda_margin = float(ebtda_margin)\n if len(discount_rate) == 0:\n discount_rate = 0.125\n else:\n discount_rate = float(discount_rate) / 100\n #engine.enterprise_value_to_ebitda_analysis(\n # years=years,\n # discount_rate=discount_rate,\n # terminal_value=terminal_multiple,\n # revenue_growth_rate=revenue_gr, ebitda_margin=ebitda_margin)\n \n st.dataframe(engine.future_ebitda, height=1000, width=2000)\n st.dataframe(engine.terminal_information, width=1000, height=2000)\n st.dataframe(engine.data_out_ebitda_analysis,width=1000,height=2000)\n except Exception as e:\n print(repr(e))\n\n\n\n\n\n\nst.sidebar.header('Insert ticker here:')\nticker = st.sidebar.text_input('Ticker', 'META')\nload_data_btn = st.sidebar.button(\"Load Data\",on_click=execute_model())\n\n\n\n\n\n\n\n\n","repo_name":"AntonioGr7/stock-market-fundamental-analysis","sub_path":"streamlit_main.py","file_name":"streamlit_main.py","file_ext":"py","file_size_in_byte":6271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"43391303532","text":"import pdb\nimport numpy as np\nimport torch.utils.data as data\nimport utils\nfrom options import *\nfrom config import *\nfrom test_all import test\nfrom model_tsl import *\nfrom tensorboard_logger import Logger\nfrom senti_features import *\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n if args.debug:\n pdb.set_trace()\n # set hyperparameter\n config = Config(args)\n worker_init_fn = None\n\n if config.seed >= 0:\n utils.set_seed(config.seed)\n worker_init_fn = np.random.seed(config.seed)\n # save config\n utils.save_config(config, os.path.join(config.output_path, \"config.txt\"))\n # initial network\n net = Model(config.len_feature, config.num_classes, config.r_act)\n net = net.cuda()\n # create dataloader\n test_loader = data.DataLoader(\n SentiFeature(data_path=config.data_path, mode='test',\n modal=config.modal, feature_fps=config.feature_fps,\n num_segments=-1, sampling='random',\n supervision='point', seed=config.seed),\n batch_size=1,\n shuffle=False, num_workers=config.num_workers,\n worker_init_fn=worker_init_fn)\n # log test results\n test_info = {\"step\": [],\n \"average_mAP[0.1:0.3]\": [], \"average_nAP[0.1:0.3]\": [],\"average_pAP[0.1:0.3]\": [], \"mAP@0.10\": [], \"mAP@0.15\": [], \"mAP@0.20\": [], \"mAP@0.25\": [], \"mAP@0.30\": [], \"Rc@0.10\": [], \"Rc@0.20\": [], \"Rc@0.30\": [], \"Rc@0.15\": [], \"Rc@0.25\": [], \"F2@0.10\": [], \"F2@0.20\": [], \"F2@0.30\": [], \"F2@0.15\": [], \"F2@0.25\": []}\n \n logger = Logger(config.log_path)\n\n net.load_state_dict(torch.load(args.model_file))\n\n test(net, config, logger, test_loader, test_info, 0)\n \n utils.save_best_record(test_info, \n os.path.join(config.output_path, \"best_record.txt\"))\n","repo_name":"nku-zhichengzhang/TSL300","sub_path":"main_eval.py","file_name":"main_eval.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"2"} +{"seq_id":"42180569585","text":"import os,json,torch,time,sys,copy,math,random\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch.utils.data import Dataset,DataLoader\r\nimport torch.optim as optim\r\nfrom torch.utils.tensorboard import SummaryWriter\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom utils import r2_score,pearson\r\n\r\n\r\nclass TrainData(Dataset):\r\n def __init__(self,input_data,data_div,window_size,mask):\r\n self.data_div=data_div\r\n self.mask=mask\r\n self.window_size=window_size\r\n self.step=int(window_size*0.4)\r\n self.window_matrix = [i for i in range(0, input_data.shape[1] - window_size, self.step)]\r\n self.encode_mask = mask.gene_chip\r\n\r\n self.encode_input1 = input_data[data_div.reference_panel,:]\r\n # sample by the random\r\n #self.encode_mask=mask.random_single_mask(input_data ,self.index,data_div.train_index)\r\n # sample by the chip\r\n self.encode_target=input_data[data_div.train_index[0]].clone()\r\n self.encode_input2=mask.chip_single_mask(input_data ,data_div.train_index[0:1])\r\n #sample by all windows\r\n #self.encode_mask = mask.random_mask(input_data)\r\n print('train ample is:' + str(len(self.window_matrix)))\r\n\r\n def __len__(self):\r\n return len(self.window_matrix)\r\n\r\n def __getitem__(self, index):\r\n dic = {}\r\n ix = self.window_matrix[index]\r\n encode_input1 = self.encode_input1[:,ix:ix + self.window_size]\r\n encode_input2 = self.encode_input2[:,ix:ix + self.window_size]\r\n encode_target = self.encode_target[ix:ix +200]\r\n encode_mask=self.encode_mask[ix:ix+200]\r\n dic['encode_input1'] = encode_input1.unsqueeze(0)\r\n dic['encode_target']=encode_target\r\n dic['encode_input2']=encode_input2.unsqueeze(0)\r\n dic['encode_mask']=encode_mask\r\n return dic\r\n\r\n\r\nclass TestData(Dataset):\r\n def __init__(self,input_data,data_div,window_size,mask):\r\n self.data_div=data_div\r\n self.mask=mask\r\n self.window_size=window_size\r\n self.step=int(window_size*0.4)\r\n self.window_matrix = [i for i in range(0, input_data.shape[1] - window_size, self.step)]\r\n self.encode_mask = mask.gene_chip\r\n\r\n self.encode_input1 = input_data[data_div.reference_panel,:]\r\n # sample by the random\r\n # self.encode_mask=mask.random_single_mask(input_data ,self.index,data_div.train_index)\r\n # sample by the chip\r\n self.encode_target = input_data[data_div.val_index[0]].clone()\r\n self.encode_input2 = mask.chip_single_mask(input_data, data_div.val_index[0:1])\r\n # sample by all windows\r\n # self.encode_mask = mask.random_mask(input_data)\r\n print('test ample is:' + str(len(self.window_matrix)))\r\n\r\n def __len__(self):\r\n return len(self.window_matrix)\r\n\r\n def __getitem__(self, index):\r\n dic = {}\r\n ix = self.window_matrix[index]\r\n encode_input1 = self.encode_input1[:,ix:ix + self.window_size]\r\n encode_input2 = self.encode_input2[:,ix:ix + self.window_size]\r\n encode_target = self.encode_target[ix:ix + 200]\r\n encode_mask=self.encode_mask[ix:ix+200]\r\n dic['encode_input1'] = encode_input1.unsqueeze(0)\r\n dic['encode_target'] = encode_target\r\n dic['encode_input2'] = encode_input2.unsqueeze(0)\r\n dic['encode_mask'] = encode_mask\r\n return dic\r\n\r\n\r\ndef train_model(model, dataloads, scheduler,num_epochs=20,board=None,\r\n train_steps=None, val_steps=256, model_save='val_loss',use_cuda=False,model_save_path='./runs',start_epoch=0,lr=None):\r\n # train step 'None' is iter all the datasets ,if num ,will iter num step.\r\n since = time.time()\r\n\r\n best_model_wts = 0\r\n best_acc = 10.0\r\n best_train_loss = 100\r\n best_val_loss=100\r\n print('dataset-size:',len(dataloads['train']),len(dataloads['val']))\r\n # print the para num in the network\r\n parasum=sum(p.numel() for p in model.parameters())\r\n print('#### the model para num is: ' , parasum)\r\n\r\n step_wide=dataloads['train'].dataset.step\r\n print('step_wide: ',step_wide)\r\n\r\n if start_epoch!=0:\r\n load_state=torch.load(os.path.join(model_save_path ,'4.best_model_wts'))\r\n start_epoch=load_state['epoch']\r\n state=load_state['state']\r\n model.load_state_dict(state)\r\n\r\n if torch.cuda.device_count() > 1 and use_cuda:\r\n print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\r\n model=nn.DataParallel(model).cuda()\r\n print('model is on cuda by gpus!')\r\n elif torch.cuda.device_count() == 1 and use_cuda:\r\n model=model.cuda()\r\n print('model is on cuda!')\r\n\r\n for epoch in range(start_epoch,num_epochs):\r\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\r\n print('-' * 10)\r\n\r\n train_epoch_loss = 0.0\r\n train_epoch_acc = 0.0\r\n val_epoch_loss = 0.0\r\n val_epoch_acc = 0.0\r\n\r\n # ??????????????\r\n for phase in ['train', 'val']:\r\n print(phase+' steps is running!')\r\n if phase == 'train':\r\n if train_steps==None:\r\n steps=0\r\n else:\r\n steps = train_steps\r\n # ?? training\r\n model=model.requires_grad_(True)\r\n\r\n elif phase=='val':\r\n if val_steps==None:\r\n steps=0\r\n else:\r\n steps = val_steps\r\n # ?? evaluate\r\n model=model.requires_grad_(False)\r\n\r\n epoch_loss = 0.0\r\n epoch_acc = 0.0\r\n stop_setps=0\r\n\r\n #\r\n for i, dataset in enumerate(dataloads[phase]):\r\n encode_input1=dataset['encode_input1'].float()\r\n\r\n encode_input2 = dataset['encode_input2'].float()\r\n\r\n encode_target=dataset['encode_target'].float()\r\n\r\n encode_mask=dataset['encode_mask']\r\n\r\n if use_cuda:\r\n encode_input1=encode_input1.cuda()\r\n encode_input2=encode_input2.cuda()\r\n encode_target=encode_target.cuda()\r\n encode_mask=encode_mask.cuda()\r\n\r\n #\r\n scheduler.optimizer.zero_grad()\r\n\r\n #\r\n output_v = model(encode_input1,encode_input2)\r\n #loss2=0.1*F.binary_cross_entropy(output_v.masked_select(~encode_mask),encode_target.masked_select(~encode_mask))\r\n #loss2 = 0.1 * F.mse_loss(output_v.masked_select(~encode_mask),encode_target.masked_select(~encode_mask))\r\n #loss1=0.9*F.binary_cross_entropy(output_v.masked_select(encode_mask),encode_target.masked_select(encode_mask))\r\n #loss1 = F.mse_loss(output_v.masked_select(encode_mask),encode_target.masked_select(encode_mask))\r\n loss = F.mse_loss(output_v,encode_target)\r\n #loss=F.binary_cross_entropy(output_v,encode_target)\r\n\r\n acc = r2_score(output_v.masked_select(encode_mask),encode_target.masked_select(encode_mask))\r\n # step\r\n if phase == 'train':\r\n loss.backward()\r\n scheduler.optimizer.step()\r\n\r\n epoch_loss += loss.item()\r\n epoch_acc += acc.item()\r\n\r\n if sys.version_info.major == 2:\r\n sys.stdout.write('{} Loss: {:.4f} Acc: {:.4f} Step:{:3d}/{:3d} \\r'.format(\r\n phase, loss.item(), acc.item(), i + 1, steps))\r\n sys.stdout.flush()\r\n elif sys.version_info.major == 3:\r\n print('{} Loss: {:.4f} Acc: {:.4f} Step:{:3d}/{:3d}'.format(\r\n phase, loss.item(), acc.item(), i + 1, steps), end='\\r')\r\n stop_setps = i\r\n if i == steps - 1:\r\n break\r\n print('\\n')\r\n\r\n if phase == 'train':\r\n train_epoch_loss = epoch_loss / (stop_setps+1)\r\n train_epoch_acc = epoch_acc / (stop_setps+1)\r\n\r\n # epoch_acc=None\r\n elif phase == 'val':\r\n val_epoch_loss = epoch_loss / (stop_setps+1)\r\n val_epoch_acc = epoch_acc / (stop_setps+1)\r\n\r\n # model save mode\r\n if model_save=='train_loss':\r\n if train_epoch_loss < best_train_loss:\r\n best_train_loss = train_epoch_loss\r\n best_epoch=epoch\r\n if torch.cuda.device_count()>1 and use_cuda:\r\n best_model_wts = copy.deepcopy(model.module).cpu().state_dict()\r\n else:\r\n best_model_wts = copy.deepcopy(model).cpu().state_dict()\r\n else:\r\n print('train loss model has not improving!')\r\n elif model_save=='val_loss':\r\n if val_epoch_loss < best_val_loss:\r\n best_val_loss = val_epoch_loss\r\n best_epoch = epoch\r\n if torch.cuda.device_count() > 1 and use_cuda:\r\n best_model_wts = copy.deepcopy(model.module).cpu().state_dict()\r\n else:\r\n best_model_wts = copy.deepcopy(model).cpu().state_dict()\r\n else:\r\n print('val loss model has not improving!')\r\n\r\n scheduler.step()\r\n # save model\r\n torch.save({'epoch':epoch,'state':best_model_wts,'comments':'1000G phase3_div'}, os.path.join(model_save_path ,'7.best_model_wts'))\r\n\r\n # board save\r\n if board:\r\n if torch.cuda.device_count() > 1 and use_cuda:\r\n for name, para in model.module.named_parameters():\r\n try:\r\n board.add_histogram(name, para.clone().cpu().data.numpy(), epoch)\r\n except:\r\n board.add_histogram(name,np.zeros(para.shape),epoch)\r\n else:\r\n for name, para in model.named_parameters():\r\n try:\r\n board.add_histogram(name, para.clone().cpu().data.numpy(), epoch)\r\n except:\r\n board.add_histogram(name,np.zeros(para.shape),epoch)\r\n\r\n print('train: Loss: {:.4f} Acc: {:.4f} ; val: Loss: {:.4f} Acc: {:.4f}'.format(\r\n train_epoch_loss, train_epoch_acc, val_epoch_loss, val_epoch_acc))\r\n print('\\n')\r\n if board:\r\n try:\r\n board.add_scalars('all_', {'train_loss': train_epoch_loss, 'train_acc': train_epoch_acc,'val_loss': val_epoch_loss, 'val_acc': val_epoch_acc}, epoch)\r\n except:\r\n continue\r\n\r\n hpara = {'batch_size_train': dataloads['train'].batch_size,'window_size': dataloads['train'].dataset.window_size,\r\n 'train_size': len(dataloads['train'].dataset),'lr':lr,'num_para':parasum,'step_wide':step_wide}\r\n mpara={'best_train_loss': best_train_loss, 'best_val_loss': best_val_loss}\r\n print('add done!')\r\n board.add_hparams(hparam_dict=hpara,metric_dict=mpara)\r\n\r\n time_elapsed = time.time() - since\r\n print('Training complete in {:.0f}m {:.0f}s'.format(\r\n time_elapsed // 60, time_elapsed % 60))\r\n print('Best train Loss: {:4f}'.format(best_train_loss))\r\n print('Best val Loss: {:4f}'.format(best_val_loss))\r\n if board:\r\n board.close()\r\n\r\n\r\ndef main2():\r\n from preprocess import Mask,Data_Div\r\n from models.fcn import Gene\r\n writer = SummaryWriter(comment='phase3_model')\r\n path = 'processed_phase3'\r\n gene_chip = np.load(os.path.join(path,'mask.npy'))\r\n input_data=np.load(os.path.join(path,'chr9.phase3.impute.hap.change.npy'))\r\n input_data=input_data.transpose()\r\n\r\n mask = Mask(gene_chip)\r\n mask.maf_cal(input_data)\r\n mask.missing_rate=0.3\r\n\r\n data_div=Data_Div()\r\n window_size = 500\r\n col=[i for i in range(input_data.shape[0])]\r\n random.seed(10)\r\n data_div.study_panel=data_div.sampler(col,2)\r\n data_div.reference_panel=list(set(col)-set(data_div.study_panel))\r\n data_div.val_index=data_div.sampler(data_div.study_panel,1)\r\n data_div.train_index=list(set(data_div.study_panel)-set(data_div.val_index))\r\n\r\n input_data=torch.from_numpy(input_data)\r\n train_dataset=TrainData(input_data,data_div,window_size,mask)\r\n val_dataset = TestData(input_data,data_div,window_size,mask)\r\n data_loader = {'train':DataLoader(train_dataset,batch_size=24,shuffle=True,drop_last=True,num_workers=8),'val':DataLoader(val_dataset,batch_size=24,drop_last=True,shuffle=True,num_workers=8)}\r\n\r\n model=Gene(1,512)\r\n lr=0.01\r\n optim1=optim.SGD(model.parameters(),lr=lr,momentum=0.9)\r\n lr_sch=optim.lr_scheduler.LambdaLR(optim1,lr_lambda=lambda epoch:epoch*0.95)\r\n use_cuda=torch.cuda.is_available()\r\n print('cuda flag: '+str(use_cuda))\r\n torch.cuda.empty_cache()\r\n train_model(model,data_loader,lr_sch,board=writer,use_cuda=use_cuda,lr=lr)\r\n\r\n\r\ndef main3():\r\n from preprocess import Mask,sampler\r\n from transformer_encoder import Gene\r\n writer = SummaryWriter(comment='phase3_model')\r\n path = 'processed_phase3'\r\n gene_chip = np.load(os.path.join(path,'mask.npy'))\r\n input_data=np.load(os.path.join(path,'chr9.phase3.impute.hap.npy'))\r\n\r\n mask = Mask(gene_chip)\r\n mask.maf_cal(input_data)\r\n mask.missing_rate=0.3\r\n\r\n window_size = 500\r\n\r\n data_div.study_panel=[1000,1001,1200,1201]\r\n\r\n data_div.train_index,data_div.val_index=data_div.study_panel[0:2],data_div.study_panel[2:4]\r\n\r\n input_data=torch.from_numpy(input_data)\r\n train_dataset=TrainData(input_data,data_div,window_size,mask)\r\n val_dataset = TestData(input_data,data_div,window_size,mask)\r\n data_loader = {'train':DataLoader(train_dataset,batch_size=8,shuffle=True,drop_last=True,num_workers=8),'val':DataLoader(val_dataset,batch_size=5,drop_last=True,shuffle=True,num_workers=8)}\r\n\r\n model=Gene(window_size)\r\n lr=0.01\r\n optim1=optim.SGD(model.parameters(),lr=lr,momentum=0.9)\r\n lr_sch=optim.lr_scheduler.LambdaLR(optim1,lr_lambda=lambda epoch:epoch*0.95)\r\n use_cuda=torch.cuda.is_available()\r\n print('cuda flag: '+str(use_cuda))\r\n torch.cuda.empty_cache()\r\n train_model(model,data_loader,lr_sch,board=writer,use_cuda=use_cuda,lr=lr)\r\n\r\nif __name__ == '__main__':\r\n #os.environ[\"CUDA_VISIBLE_DEVICES\"] = '1,2,3,4,7'\r\n main2()","repo_name":"univeryinli/genotype-imputation","sub_path":"train2d.py","file_name":"train2d.py","file_ext":"py","file_size_in_byte":14345,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"21045705048","text":"import threading\nimport queue\nimport socket\nfrom sys import argv\n\nM = int(argv[1])\nfilename = argv[2]\nlist_of_urls = []\n\n\ndef connect_with_server(url):\n client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client_sock.connect((\"localhost\", 15000))\n\n client_sock.send(url.encode('UTF-8'))\n\n top_k = client_sock.recv(1024).decode()\n if top_k:\n print(f'{url}: {top_k}')\n else:\n print('No top')\n\n client_sock.close()\n\n\nwith open(filename, \"r\") as f:\n for line in f:\n list_of_urls.append(line)\n\nfor url in list_of_urls:\n threads = [\n threading.Thread(\n target=connect_with_server,\n name=f\"class_thread_{i}\",\n args=(url,)\n )\n for i in range(M)\n]\n\nfor th in threads:\n th.start()\n\nfor th in threads:\n th.join()\n","repo_name":"MosinFAM/deep-python-course","sub_path":"06/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"32137021493","text":"# 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 binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:\n \n def dfs(root, path):\n if not root:\n return \n path.append(root.val)\n if not root.left and not root.right:\n ans.append('->'.join(map(str, path.copy())))\n \n dfs(root.left, path)\n dfs(root.right, path)\n path.pop()\n\n return \n \n ans = []\n dfs(root, [])\n return ans","repo_name":"Henokaa/Datastructure-leetcode-practice2","sub_path":"0257-binary-tree-paths/0257-binary-tree-paths.py","file_name":"0257-binary-tree-paths.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"37026712510","text":"import random\nimport time\nimport matplotlib.pyplot as plt\n\n# working version\nclass SinglePerceptron:\n def __init__(self, inputs_num: int, delta: float):\n self.input_len = inputs_num\n self.weights = [random.random(), 1]\n self.weights.append(-delta)\n\n def predict(self, input_array: list):\n if len(input_array) != self.input_len:\n raise IOError()\n sum_ = self.weights[self.input_len] # sum = bias at start\n for i in range(self.input_len):\n sum_ += self.weights[i] * input_array[i]\n\n # activation function\n\n y = 1 if sum_ > 0 else -1\n\n return y\n\n def fit(self, array_of_inputs, array_of_outputs):\n errs = -1\n tries = 0\n min_errs = len(array_of_inputs)\n while errs != 0:\n errs = 0\n for i in range(len(array_of_inputs)):\n row = array_of_inputs[i] # x, y\n prediction = self.predict(row)\n if prediction * array_of_outputs[i] < 0:\n errs += 1\n self.weights[0] += 0.001 * row[0] * array_of_outputs[i]\n temp_ = min_errs\n min_errs = min(errs, min_errs)\n if temp_ != min_errs:\n print(min_errs)\n print(*self.weights)\n plt.plot(x, y)\n plt.plot([0, len(x)], [a * 0 + b, a * len(x) + b])\n plt.plot([0, len(array_of_inputs)], [-self.weights[0] / self.weights[1] * 0 - self.weights[2],\n -self.weights[0] / self.weights[1] * len(array_of_inputs) -\n self.weights[2]])\n plt.show()\n\n\nif __name__ == '__main__':\n y = list(map(lambda string: float(string.split(\",\")[7]), open('lines.csv').readlines()))\n x = [i + 1 for i in range(len(y))]\n x_ = sum(x) / len(x)\n y_ = sum(y) / len(y)\n xy_ = 0\n for i in range(len(y)):\n xy_ += x[i] * y[i]\n xy_ /= len(y)\n x2_ = sum(map(lambda s: s * s, x)) / len(x)\n a = (xy_ - x_ * y_) / (x2_ - x_ * x_)\n b = y_ - a * x_\n print(f\"a={a}, b={b}\")\n answers = list()\n for i in range(len(x)):\n answers.append(1 if a * x[i] + b <= y[i] else -1)\n inputs = [[i, y[i]] for i in range(len(y))]\n print(x)\n print(y)\n plt.plot(x, y)\n plt.plot([0, len(x)], [a * 0 + b, a * len(x) + b])\n plt.show()\n model = SinglePerceptron(2, 3134.8901260195853)\n model.fit(inputs, answers)\n# for i in range(500, len(x)):\n","repo_name":"CAMELNINGA/dataAnalysisCourse","sub_path":"Task 1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"14216846662","text":"#!/usr/bin/python3\nimport hashlib\nimport base64\nimport string\nimport random\nimport sqlite3\n\n# External database for strategy # 2\nif (os.path.isfile(\"database.db\") == False):\n\tdb = sqlite3.connect('database.db')\n\tdb.execute('create table shortner (url_code text, url_full text)')\n\n\nclass Shortner:\n\n\tdef code_generator(self):\n\t\treturn ''.join(random.choices(string.ascii_uppercase + string.digits, k=5))\n\t\t\n\tdef add_url(self):\n\t\t#check in the database whether url exists\n\t\tnew_code = self.code_generator()\n\t\tcur = db.cursor()\n\t\tcur.execute(\"select * from shortner where url_code=?\", new_code)\n\t\tdata = cur.fetchall()\n\t\twhile (data is not None):\n\t\t\tnew_code = self.code_generator()\n\t\t\tcur.execute(\"select * from shortner where url_code=?\", new_code)\n\t\t\tdata = cur.fetchall()\n\t\t\n\t\t#when a unique code has been found, enter it in the dictionary\n\t\tresult = \"http://bit.ly/\" + new_code;\n\t\turl = input(\"Please enter your url: \")\n\t\tnew_dict[new_code] = result;\n\t\tprint(\"Your shortnened url is: \" + result)\n\t\t\n\ns1 = Shortner()\ns1.add_url()\n\t\t\n\t\t\n\t\t\t\n\t\t\n\t\n\n","repo_name":"nimesh-das/url-shortner","sub_path":"url-shortner.py","file_name":"url-shortner.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"33273481937","text":"# print pattern\n# A A A A A\n# B B B B\n# C C C\n# D D\n# E\ndef pat(n):\n num = 65\n for i in range(n):\n ch = chr(num)\n for j in range(n):\n if (i + j <= n-1):\n print(ch, end=\" \")\n else:\n print(\" \", end=' ')\n num+=1\n print('')\nif __name__ =='__main__':\n n = int(input(\"Enter number : \"))\n pat(n)","repo_name":"nikhil03singh/Python-Patterns","sub_path":"11.py","file_name":"11.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"24937301059","text":"# -*- encoding:utf-8 -*-\n\"\"\"\n 买入择时示例因子:突破买入择时因子\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nfrom .ABuFactorBuyBase import AbuFactorBuyBase, AbuFactorBuyXD, BuyCallMixin, BuyPutMixin\nfrom ..UtilBu.ABuKlineUtil import min_kline\nfrom ..UtilBu.ABuStrUtil import get_num_from_str\n\n__author__ = '阿布'\n__weixin__ = 'abu_quant'\n\n\n# noinspection PyAttributeOutsideInit\nclass AbuFactorBuyBreak(AbuFactorBuyBase, BuyCallMixin):\n \"\"\"示例正向突破买入择时类,混入BuyCallMixin,即向上突破触发买入event\"\"\"\n\n def _init_self(self, **kwargs):\n \"\"\"kwargs中必须包含: 突破参数xd 比如20,30,40天...突破\"\"\"\n # 突破参数 xd, 比如20,30,40天...突破, 不要使用kwargs.pop('xd', 20), 明确需要参数xq\n self.xd = kwargs['xd']\n # 在输出生成的orders_pd中显示的名字\n self.factor_name = '{}:{}'.format(self.__class__.__name__, self.xd)\n\n # 均线频率参数 freq, 比如5,15,30分钟.., 形如 '5M'代表5分钟线\n self.freq = get_num_from_str(kwargs['freq'])\n # 输出根据特定频率下合成的行情数据\n self.freq_kl_pd = min_kline(self.kl_pd.name, self.kl_pd, self.freq)\n\n def fit_day(self, today, holding_cnt):\n \"\"\"\n 针对每一个交易日拟合买入交易策略,寻找向上突破买入机会\n :param today: 当前驱动的交易日金融时间序列数据\n :param holding_cnt: 交易发生之前的持仓量\n :return:\n \"\"\"\n _check_if = self.check_dominant_today(today)\n _check_freq = self.check_freq_today(today, self.freq)\n\n if not _check_if:\n return None\n\n if not _check_freq:\n return None\n\n today_ind = int(self.freq_kl_pd[self.freq_kl_pd.datetime == today.datetime].key.values[0])\n # print(self.kl_pd.name)\n # print(today_ind)\n # 忽略不符合买入的天(统计周期内前xd天)\n if today_ind < self.xd - 1:\n\n return None\n # 今天的收盘价格达到xd天内最高价格则符合买入条件\n\n if today.close == self.freq_kl_pd.close[today_ind - self.xd + 1:today_ind + 1].max():\n # 把突破新高参数赋值skip_days,这里也可以考虑make_buy_order确定是否买单成立,但是如果停盘太长时间等也不好\n self.skip_days = self.xd * self.freq\n # 生成买入订单, 由于使用了今天的收盘价格做为策略信号判断,所以信号发出后,只能明天买\n return self.buy_tomorrow(holding_cnt)\n\n return None\n\n # 忽略不符合买入的天(统计周期内前xd天)\n # if self.today_ind < self.xd - 1:\n # return None\n #\n # # 今天的收盘价格达到xd天内最高价格则符合买入条件\n # if today.close == self.kl_pd.close[self.today_ind - self.xd + 1:self.today_ind + 1].max():\n # # 把突破新高参数赋值skip_days,这里也可以考虑make_buy_order确定是否买单成立,但是如果停盘太长时间等也不好\n # self.skip_days = self.xd\n # # 生成买入订单, 由于使用了今天的收盘价格做为策略信号判断,所以信号发出后,只能明天买\n # return self.buy_tomorrow(holding_cnt)\n # return None\n\n\n# noinspection PyAttributeOutsideInit\nclass AbuFactorBuyXDBK(AbuFactorBuyXD, BuyCallMixin):\n \"\"\"示例继承AbuFactorBuyXD完成正向突破买入择时类\"\"\"\n def fit_day(self, today):\n \"\"\"\n 针对每一个交易日拟合买入交易策略,寻找向上突破买入机会\n :param today: 当前驱动的交易日金融时间序列数据\n :return:\n \"\"\"\n # 今天的收盘价格达到xd天内最高价格则符合买入条件\n if today.close == self.xd_kl.close.max():\n return self.buy_tomorrow()\n return None\n\n\n# noinspection PyAttributeOutsideInit\nclass AbuFactorBuyPutBreak(AbuFactorBuyBase, BuyPutMixin):\n \"\"\"示例反向突破买入择时类,混入BuyPutMixin,即向下突破触发买入event,详情请查阅期货回测示例demo\"\"\"\n\n def _init_self(self, **kwargs):\n \"\"\"kwargs中必须包含: 突破参数xd 比如20,30,40天...突破\"\"\"\n\n # 突破参数 xd, 比如20,30,40天...突破, 不要使用kwargs.pop('xd', 20), 明确需要参数xq\n self.xd = kwargs['xd']\n self.factor_name = '{}:{}'.format(self.__class__.__name__, self.xd)\n\n def fit_day(self, today, holding_cnt):\n \"\"\"\n 针对每一个交易日拟合买入交易策略,寻找向下突破买入机会\n :param today: 当前驱动的交易日金融时间序列数据\n :param holding_cnt: 交易发生之前的持仓量\n :return:\n \"\"\"\n # 忽略不符合买入的天(统计周期内前xd天)\n if self.today_ind < self.xd - 1:\n return None\n \"\"\"\n 与AbuFactorBuyBreak区别就是买向下突破的,即min()\n \"\"\"\n if today.close == self.kl_pd.close[self.today_ind - self.xd + 1:self.today_ind + 1].min():\n self.skip_days = self.xd\n return self.buy_tomorrow(holding_cnt)\n return None\n\n\n# noinspection PyAttributeOutsideInit\nclass AbuFactorBuyPutXDBK(AbuFactorBuyXD, BuyPutMixin):\n \"\"\"示例继承AbuFactorBuyXD完成反向突破买入择时类\"\"\"\n def fit_day(self, today):\n \"\"\"\n 针对每一个交易日拟合买入交易策略,寻找向上突破买入机会\n :param today: 当前驱动的交易日金融时间序列数据\n :return:\n \"\"\"\n # 与AbuFactorBuyBreak区别就是买向下突破的,即min()\n if today.close == self.xd_kl.close.min():\n return self.buy_tomorrow()\n return None\n","repo_name":"Leo70kg/Backtesting","sub_path":"abupy/FactorBuyBu/ABuFactorBuyBreak.py","file_name":"ABuFactorBuyBreak.py","file_ext":"py","file_size_in_byte":5936,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"18976147987","text":"from odoo import _, api, exceptions, fields, models\n\n\nclass ProductTemplate(models.Model):\n _inherit = \"product.template\"\n\n fms_product_category = fields.Selection([\n ('delivery', 'Delivery Charges'),\n ('cod_charges', 'COD Charges'),\n ('expenses', 'Expenses'),\n ('other', 'Other'),],\n\n string='FMS Product Category')\n apply_for_salary = fields.Boolean()\n\n\n @api.constrains('fms_product_category')\n def unique_product_per_category(self):\n for rec in self:\n categorys = [\n ['move', 'Moves'],\n ['salary', 'Salary'],\n ['negative_balance', 'Negative Balance'],\n ['indirect_expense', 'Indirect Expense']\n ]\n for category in categorys:\n product = rec.search([\n ('fms_product_category', '=', category[0])])\n if len(product) > 1:\n raise exceptions.ValidationError(\n _('Only there must be a product with category \"' +\n category[1] + '\"'))\n\n\n","repo_name":"mohamedabuemira/courier","sub_path":"models/fms_product_template.py","file_name":"fms_product_template.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"43408654211","text":"#Set min to positive infinity: float(\"inf\").\n# For each number in the list nums, compare it to min. If num is smaller, set min to num.\n# min is now set to the smallest number in the list.\ndef find_min(nums):\n min = float('inf')\n for num in nums:\n if num < min:\n min = num\n \nnums = [7, 4, 3, 100, 2343243, 343434, 1, 2, 32]\nfind_min(nums)","repo_name":"superdfv/Introtoalgorithms","sub_path":"findmin.py","file_name":"findmin.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"29141139001","text":"import sys\nfrom collections import deque\nfrom collections import defaultdict\ninput = sys.stdin.readline\n\nN, M = map(int, input().split())\ndegree = [0] * (N+1)\nminSemester = [0] * (N+1)\ngraph = defaultdict(list)\n\nfor i in range(M):\n A, B = map(int, input().split())\n graph[A].append(B)\n degree[B] += 1\n\ndq = deque()\nfor i in range(1, N+1):\n if degree[i] == 0:\n dq.append(i)\n minSemester[i] = 1\n\nwhile dq:\n n = dq.popleft()\n for i in graph[n]:\n degree[i] -= 1\n minSemester[i] = max(minSemester[n] + 1, minSemester[i])\n if degree[i] == 0:\n dq.append(i)\n\nprint(*minSemester[1:])","repo_name":"kyunghyukCHO/Argorithm-Study","sub_path":"Argorithm_BaekJoon/위상정렬/14567.py","file_name":"14567.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"4880182154","text":"import torch\r\nimport torchvision\r\nfrom torchvision import transforms\r\n\r\n_dataset_name = [\"mnist\", \"cifar10\", \"gtsrb\", \"imagenet\"]\r\n\r\n_mean = {\r\n \"mnist\": [0.5, 0.5, 0.5],\r\n \"cifar10\": [0.4914, 0.4822, 0.4465],\r\n \"gtsrb\": [0.3337, 0.3064, 0.3171],\r\n \"imagenet\": [0.485, 0.456, 0.406],\r\n}\r\n\r\n_std = {\r\n \"mnist\": [0.5, 0.5, 0.5],\r\n \"cifar10\": [0.2470, 0.2435, 0.2616],\r\n \"gtsrb\": [0.2672, 0.2564, 0.2629],\r\n \"imagenet\": [0.229, 0.224, 0.225],\r\n}\r\n\r\n_size = {\r\n \"mnist\": (28, 28),\r\n \"cifar10\": (32, 32),\r\n \"gtsrb\": (32, 32),\r\n \"imagenet\": (224, 224),\r\n}\r\n\r\n\r\ndef get_totensor_topil():\r\n return transforms.ToTensor(), transforms.ToPILImage()\r\n\r\ndef get_normalize_unnormalize(dataset):\r\n assert dataset in _dataset_name\r\n mean = torch.FloatTensor(_mean[dataset])\r\n std = torch.FloatTensor(_std[dataset])\r\n normalize = transforms.Normalize(mean, std)\r\n unnormalize = transforms.Normalize(- mean / std, 1 / std)\r\n return normalize, unnormalize\r\n\r\ndef get_bounds(x, dataset):\r\n normalize, _ = get_normalize_unnormalize(dataset)\r\n upperbound = normalize(torch.ones_like(x))\r\n lowerbound = normalize(torch.zeros_like(x))\r\n return lowerbound, upperbound\r\n\r\ndef get_normalized_clip(dataset):\r\n normalize, _ = get_normalize_unnormalize(dataset)\r\n return lambda x : torch.min(torch.max(x, normalize(torch.zeros_like(x))), normalize(torch.ones_like(x)))\r\n\r\ndef get_resize(size):\r\n if isinstance(size, str):\r\n assert size in _dataset_name\r\n size = _size[size]\r\n return transforms.Resize(size)\r\n\r\ndef get_preprocess_deprocess(dataset, size=None):\r\n totensor, topil = get_totensor_topil()\r\n normalize, unnormalize = get_normalize_unnormalize(dataset)\r\n if size is None:\r\n preprocess = transforms.Compose([totensor, normalize])\r\n deprocess = transforms.Compose([unnormalize, topil])\r\n else:\r\n preprocess = transforms.Compose([get_resize(size), totensor, normalize])\r\n deprocess = transforms.Compose([unnormalize, topil])\r\n return preprocess, deprocess\r\n ","repo_name":"jylink/BMI-FGSM","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"32646741618","text":"import argparse\nimport os\nimport random\nimport torch\nimport torch.nn.functional as F\nimport torch.nn.init as init\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nimport toyData as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nfrom tensorboardX import SummaryWriter\nimport torchvision.models as M\nfrom torch.autograd import Variable\nfrom PIL import Image\nimport math\nimport numpy as np\n\n# import matplotlib.pyplot as plt\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataroot', required=True, help='path to dataset')\nparser.add_argument('--workers', type=int, help='number of data loading workers', default=2)\nparser.add_argument('--batchSize', type=int, default=64, help='input batch size')\nparser.add_argument('--imageSize', type=int, default=96, help='the height / width of the input image to network')\nparser.add_argument('--ngf', type=int, default=64)\nparser.add_argument('--ndf', type=int, default=64)\nparser.add_argument('--cut', type=int, default=1)\nparser.add_argument('--flag', type=int, default=0, help='Dnet pretrain flag')\nparser.add_argument('--niter', type=int, default=700, help='number of epochs to train for')\nparser.add_argument('--scale', type=float, default=1.5, help='RES scale')\n\nparser.add_argument('--lrG', type=float, default=0.0001, help='learning rate, default=0.0001')\nparser.add_argument('--lrD', type=float, default=0.0001, help='learning rate, default=0.0001')\nparser.add_argument('--beta1', type=float, default=0.5, help='beta1 for adam. default=0.5')\nparser.add_argument('--gpW', type=float, default=10, help='gradient penalty weight')\n# parser.add_argument('--ganW', type=float, default=0.01, help='gan penalty weight')\nparser.add_argument('--cuda', action='store_true', help='enables cuda')\nparser.add_argument('--netG', default='', help=\"path to netG (to continue training)\")\nparser.add_argument('--netD', default='', help=\"path to netD (to continue training)\")\nparser.add_argument('--netM', default='', required=True, help=\"path to netM (to continue training)\")\nparser.add_argument('--outf', default='.', help='folder to output images and model checkpoints')\nparser.add_argument('--Diters', type=int, default=5, help='number of D iters per each G iter')\nparser.add_argument('--manualSeed', type=int, default=2345, help='random seed to use. Default=1234')\nparser.add_argument('--baseGeni', type=int, default=2500, help='start base of pure mse loss')\nparser.add_argument('--geni', type=int, default=0, help='continue gen image num')\nparser.add_argument('--epoi', type=int, default=0, help='continue epoch num')\nparser.add_argument('--env', type=str, default=None, help='tensorboard env')\nparser.add_argument('--optim', action='store_true', help='load optimizer\\'s checkpoint')\n\n\nopt = parser.parse_args()\nprint(opt)\n\nwriter = SummaryWriter(log_dir=opt.env, comment='this is great')\n\ncuts = opt.cut # save division\nngf = opt.ngf\nndf = opt.ndf\ngen_iterations = opt.geni\n\ntry:\n os.makedirs(opt.outf)\nexcept OSError:\n pass\n# random seed setup\nprint(\"Random Seed: \", opt.manualSeed)\nrandom.seed(opt.manualSeed)\ntorch.manual_seed(opt.manualSeed)\nif opt.cuda:\n torch.cuda.manual_seed(opt.manualSeed)\n\ncudnn.benchmark = True\n\nif torch.cuda.is_available() and not opt.cuda:\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n\n# folder dataset\nLRTrans = transforms.Compose([\n transforms.Normalize((-1, -1, -1), (2, 2, 2)),\n transforms.ToPILImage(),\n transforms.Scale(opt.imageSize // 4, Image.BICUBIC),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n])\n\nHRTrans = transforms.Compose([\n transforms.Normalize((-1, -1, -1), (2, 2, 2)),\n transforms.ToPILImage(),\n transforms.Scale(opt.imageSize, Image.BICUBIC),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n])\n\ndataset = dset.ImageFolder(root=opt.dataroot,\n transform=transforms.Compose([\n # transforms.RandomSizedCrop(),\n transforms.RandomCrop(opt.imageSize),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ]),\n target_transform=LRTrans,\n target_transform2=HRTrans,\n )\n\nassert dataset\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=opt.batchSize,\n shuffle=True, num_workers=int(opt.workers))\n\n\n############################\n# G network\n###########################\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self):\n super(BasicBlock, self).__init__()\n self.conv1 = nn.Conv2d(ngf, ngf, 3, 1, 1, bias=False)\n self.conv2 = nn.Conv2d(ngf, ngf, 3, 1, 1, bias=False)\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(F.relu(x, True))\n out = self.conv2(F.relu(out, True)) * 0.3 + residual\n\n return out\n\n\nclass BasicBlock2(nn.Module):\n expansion = 1\n\n def __init__(self):\n super(BasicBlock2, self).__init__()\n self.conv1 = nn.Conv2d(ngf, ngf, 3, 1, 1, bias=False)\n self.bn1 = nn.BatchNorm2d(ngf)\n self.conv2 = nn.Conv2d(ngf, ngf, 3, 1, 1, bias=False)\n self.bn2 = nn.BatchNorm2d(ngf)\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(F.relu(self.bn1(x), True))\n out = self.conv2(F.relu(self.bn2(out), True)) * 0.3 + residual\n\n return out\n\n\nclass _netG(nn.Module):\n def __init__(self):\n super(_netG, self).__init__()\n\n self.conv1 = nn.Conv2d(3, ngf, 3, 1, 1, bias=False)\n # state size. (ngf) x W x H\n\n self.resnet = self._make_layer(16)\n # state size. (ngf) x W x H\n\n self.conv7 = nn.Conv2d(ngf, ngf * 4, 3, 1, 1, bias=False) # ngf*4 x W x H\n self.pixel_shuffle1 = nn.PixelShuffle(2) # ngf x 2W x 2H\n\n self.conv8 = nn.Conv2d(ngf, ngf * 4, 3, 1, 1, bias=False) # ngf*4 x 2W x 2H\n self.pixel_shuffle2 = nn.PixelShuffle(2) # ngf x 4W x 4H\n\n self.conv9 = nn.Conv2d(ngf, 3, 3, 1, 1, bias=False)\n\n def _make_layer(self, blocks):\n layers = []\n for i in range(0, blocks):\n layers.append(BasicBlock())\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = self.conv1(x)\n\n out = self.resnet(out)\n ######\n\n out = F.relu(self.pixel_shuffle1(self.conv7(out)), True)\n out = F.relu(self.pixel_shuffle2(self.conv8(out)), True)\n\n out = F.tanh(self.conv9(out) / 5.)\n\n return out\n\n\nnetG = _netG()\nif opt.netG != '':\n netG.load_state_dict(torch.load(opt.netG))\nprint(netG)\n\nclass _netD(nn.Module):\n def __init__(self):\n super(_netD, self).__init__()\n\n # self.bn0 = LayerNormalization(3 * 96 * 96)\n # self.bn0 = nn.BatchNorm2d(3)\n\n # input is 6 x 96 x 96\n self.conv11 = nn.Conv2d(6, ndf, 3, 1, 1, bias=False)\n # state size. (ndf) x 96 x 96\n\n self.conv12 = nn.Conv2d(ndf, ndf, 4, 2, 1, bias=False)\n # self.bn12 = nn.BatchNorm2d(ndf)\n # state size. (ndf) x 48 x 48\n\n self.conv21 = nn.Conv2d(ndf, ndf * 2, 3, 1, 1, bias=False)\n # self.bn21 = nn.BatchNorm2d(ndf * 2)\n # state size. (ndf * 2) x 48 x 48\n\n self.conv22 = nn.Conv2d(ndf * 2, ndf * 2, 4, 2, 1, bias=False)\n # self.bn22 = nn.BatchNorm2d(ndf * 2)\n # state size. (ndf * 2) x 24 x 24\n\n self.conv31 = nn.Conv2d(ndf * 2, ndf * 4, 3, 1, 1, bias=False)\n # self.bn31 = nn.BatchNorm2d(ndf * 4)\n # state size. (ndf * 4) x 24 x 24\n\n self.conv32 = nn.Conv2d(ndf * 4, ndf * 4, 4, 2, 1, bias=False)\n # self.bn32 = nn.BatchNorm2d(ndf * 4)\n # state size. (ndf * 4) x 12 x 12\n\n self.conv41 = nn.Conv2d(ndf * 4, ndf * 8, 3, 1, 1, bias=False)\n # self.bn41 = nn.BatchNorm2d(ndf * 8)\n # state size. (ndf * 8) x 12 x 12\n\n self.conv42 = nn.Conv2d(ndf * 8, ndf * 8, 4, 2, 1, bias=False)\n # self.bn42 = nn.BatchNorm2d(ndf * 8)\n # state size. (ndf * 8) x 6 x 6\n\n self.dense1 = nn.Linear(ndf * 8 * 6 * 6, 1)\n # self.dense2 = nn.Linear(1024, 1)\n\n def forward(self, x):\n # x = torch.cat((self.bn0(input), per), 1)\n out = F.leaky_relu(self.conv11(x), 0.2, True)\n out = F.leaky_relu(self.conv12(out), 0.2, True)\n out = F.leaky_relu(self.conv21(out), 0.2, True)\n out = F.leaky_relu(self.conv22(out), 0.2, True)\n out = F.leaky_relu(self.conv31(out), 0.2, True)\n out = F.leaky_relu(self.conv32(out), 0.2, True)\n out = F.leaky_relu(self.conv41(out), 0.2, True)\n out = F.leaky_relu(self.conv42(out), 0.2, True)\n\n out = self.dense1(out.view(out.size(0), -1))\n # out = self.dense2(out)\n\n return out\n\n\nnetD = _netD()\nif opt.netD != '':\n netD.load_state_dict(torch.load(opt.netD))\nprint(netD)\n\n\n############################\n# MSE network\n###########################\nclass _netM(nn.Module):\n def __init__(self):\n super(_netM, self).__init__()\n # self.convN = nn.ConvTranspose2d(100, 4, opt.imageSize // 4, 1, 0, bias=False)\n\n self.conv1 = nn.Conv2d(3, ngf, 3, 1, 1, bias=False)\n # state size. (ngf) x W x H\n\n self.resnet = self._make_layer(3)\n # state size. (ngf) x W x H\n\n self.conv7 = nn.Conv2d(ngf, ngf * 4, 3, 1, 1, bias=False) # ngf*4 x W x H\n self.pixel_shuffle1 = nn.PixelShuffle(2) # ngf x 2W x 2H\n\n self.conv8 = nn.Conv2d(ngf, ngf * 4, 3, 1, 1, bias=False) # ngf*4 x 2W x 2H\n self.pixel_shuffle2 = nn.PixelShuffle(2) # ngf x 4W x 4H\n\n self.conv9 = nn.Conv2d(ngf, 3, 3, 1, 1, bias=False)\n\n def _make_layer(self, blocks):\n layers = []\n for i in range(0, blocks):\n layers.append(BasicBlock2())\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = self.conv1(x)\n\n out = self.resnet(out)\n ######\n\n out = F.relu(self.pixel_shuffle1(self.conv7(out)), True)\n out = F.relu(self.pixel_shuffle2(self.conv8(out)), True)\n\n out = F.tanh(self.conv9(out) / 5.)\n\n return out\n\n\nnetM = _netM()\nnetM.load_state_dict(torch.load(opt.netM))\nprint(netM)\n\ncriterion_MSE = nn.MSELoss()\nL2_dist = nn.PairwiseDistance(2)\n############################\n# VGG loss\n###########################\n# vgg19 = M.vgg19()\n# vgg19.load_state_dict(torch.load('vgg19.pth'))\n\n\n# class vgg54(nn.Module):\n# def __init__(self):\n# super(vgg54, self).__init__()\n# self.features = nn.Sequential(\n# # stop at conv4\n# *list(vgg19.features.children())[:-7]\n# )\n\n# def forward(self, x):\n# x = self.features(x)\n# return x\n\n\n# vgg_features = vgg54()\n# for p in vgg_features.parameters():\n# p.requires_grad = False # to avoid computation\n\ninput = torch.FloatTensor(opt.batchSize, 3, opt.imageSize, opt.imageSize)\nzasshu = torch.FloatTensor(opt.batchSize, 3, opt.imageSize, opt.imageSize)\nfixed_zasshu = torch.FloatTensor(opt.batchSize, 3, opt.imageSize, opt.imageSize)\nfixed_PER = torch.FloatTensor(opt.batchSize, 3, opt.imageSize, opt.imageSize)\none = torch.FloatTensor([1])\nmone = one * -1\n# suber = torch.FloatTensor(\n# [np.full((96, 96), 0.485 - 0.5), np.full((96, 96), 0.456 - 0.5), np.full((96, 96), 0.406 - 0.5)])\n# diver = torch.FloatTensor([np.full((96, 96), 0.229), np.full((96, 96), 0.224), np.full((96, 96), 0.225)])\n\nif opt.cuda:\n netD.cuda()\n netG.cuda()\n netM.cuda()\n input = input.cuda()\n one, mone = one.cuda(), mone.cuda()\n zasshu, fixed_zasshu, fixed_PER = zasshu.cuda(), fixed_zasshu.cuda(), fixed_PER.cuda()\n criterion_MSE.cuda()\n L2_dist.cuda()\n # vgg_features.cuda()\n # suber, diver = suber.cuda(), diver.cuda()\n\n# setup optimizer\noptimizerD = optim.Adam(netD.parameters(), lr=opt.lrD, betas=(opt.beta1, 0.9))\noptimizerG = optim.Adam(netG.parameters(), lr=opt.lrG, betas=(opt.beta1, 0.9))\nif opt.optim:\n optimizerG.load_state_dict(torch.load('%s/optimG_checkpoint.pth' % opt.outf))\n optimizerD.load_state_dict(torch.load('%s/optimD_checkpoint.pth' % opt.outf))\n\nflag = 1\nflag4 = opt.flag\nscaler = opt.scale\n\nnetM.eval()\n\nfor epoch in range(opt.niter):\n data_iter = iter(dataloader)\n i = 0\n while i < len(dataloader):\n ############################\n # (1) Update D network\n ###########################\n for p in netD.parameters(): # reset requires_grad\n p.requires_grad = True # they are set to False below in netG update\n\n # train the discriminator Diters times\n Diters = opt.Diters\n\n if flag4: # pretrain stage\n Diters = 4000\n flag4 -= 1\n\n if gen_iterations < opt.baseGeni: # MSE stage\n Diters = 0\n\n j = 0\n while j < Diters and i < len(dataloader):\n\n j += 1\n netD.zero_grad()\n\n data = data_iter.next()\n real_cpu, fake_cpu, perceptualRes_cpu = data\n i += 1\n ###############################\n batch_size = real_cpu.size(0)\n\n if opt.cuda:\n real_cpu = real_cpu.cuda()\n fake_cpu = fake_cpu.cuda()\n perceptualRes_cpu = perceptualRes_cpu.cuda()\n\n input.resize_as_(real_cpu).copy_(real_cpu)\n zasshu.resize_as_(fake_cpu).copy_(fake_cpu)\n\n # print(input.mean(), input.std(), real_cpu.mean(), real_cpu.std())\n # plt.hist(np.array(input.cpu().numpy()).resize(96*96*3))\n # plt.show()\n # viz.histogram(input.cpu().view(-1))\n\n inputv = Variable(zasshu, volatile=True) # totally freeze netG\n mse = netM(inputv).data / scaler + perceptualRes_cpu\n\n # inputv = Variable(torch.cat((input * 10, perceptualRes_cpu), 1))\n\n\n errD_real_vec = netD(Variable(torch.cat((input, mse), 1)))\n errD_real = errD_real_vec.mean(0).view(1)\n errD_real.backward(mone, retain_graph=True) # backward on score on real\n\n # train with fake\n\n fake = Variable(netG(inputv).data)\n errD_fake_vec = netD(\n torch.cat((fake / scaler + Variable(mse), Variable(mse)), 1))\n errD_fake = errD_fake_vec.mean(0).view(1)\n errD_fake.backward(one, retain_graph=True)\n errD = errD_real - errD_fake\n\n # GP term\n dist = L2_dist(Variable(input).view(batch_size, -1),\n fake.div(scaler).add(Variable(mse)).view(batch_size, -1))\n lip_est = (errD_real_vec - errD_fake_vec).abs() / (dist + 1e-8)\n lip_loss = opt.gpW * ((1.0 - lip_est) ** 2).mean(0).view(1)\n lip_loss.backward(one)\n errD = errD + lip_loss\n # errG = errD\n\n optimizerD.step()\n\n ############################\n # (2) Update G network\n ############################\n if i < len(dataloader):\n for p in netD.parameters():\n p.requires_grad = False # to avoid computation\n netG.zero_grad()\n # in case our last batch was the tail batch of the dataloader,\n # make sure we feed a full batch of LR pic\n data = data_iter.next()\n real_cpu, fake_cpu, perceptualRes_cpu = data\n i += 1\n\n batch_size = real_cpu.size(0)\n\n if opt.cuda:\n real_cpu = real_cpu.cuda()\n fake_cpu = fake_cpu.cuda()\n perceptualRes_cpu = perceptualRes_cpu.cuda()\n\n input.resize_as_(real_cpu).copy_(real_cpu)\n zasshu.resize_as_(fake_cpu).copy_(fake_cpu)\n\n inputv = Variable(zasshu)\n mse = netM(inputv).data / scaler + perceptualRes_cpu\n\n if flag: # fix samples\n fixed_zasshu.resize_as_(fake_cpu).copy_(fake_cpu)\n fixed_PER.resize_as_(real_cpu).copy_(mse)\n writer.add_image('real_cpu imgs', vutils.make_grid(real_cpu.mul(0.5).add(0.5), nrow=16))\n writer.add_image('LRMSE imgs', vutils.make_grid(fixed_PER.mul(0.5).add(0.5).clamp(0, 1), nrow=16))\n writer.add_image('HRRes imgs', vutils.make_grid((real_cpu - fixed_PER).mul(0.5 * scaler).add(0.5).clamp(0, 1), nrow=16))\n vutils.save_image(real_cpu.mul(0.5).add(0.5),\n '%s/real_samples.png' % opt.outf)\n vutils.save_image(fixed_zasshu.mul(0.5).add(0.5),\n '%s/ori_samples.png' % opt.outf)\n\n\n flag -= 1\n\n fake = netG(inputv)\n\n if gen_iterations < opt.baseGeni:\n MSEloss = criterion_MSE(fake / scaler + Variable(perceptualRes_cpu), Variable(input))\n MSEloss.backward(one)\n errG = MSEloss\n else:\n # subb = Variable(torch.stack([suber for ww in range(batch_size)])).cuda()\n # divv = Variable(torch.stack([diver for ww in range(batch_size)])).cuda()\n\n errG = netD(\n torch.cat((fake / scaler + Variable(mse), Variable(mse)), 1)).mean(\n 0).view(1)\n # MSEloss = 0 # (vgg_features((fake.mul(0.5) - subb) / divv) - (\n # vgg_features((Variable(input).mul(0.5) - subb) / divv))).pow(2).mean()\n # errG -= MSEloss\n errG.backward(mone)\n\n optimizerG.step()\n\n ############################\n # (3) Report & 100 Batch checkpoint\n ############################\n if gen_iterations < opt.baseGeni:\n writer.add_scalar('MSE/VGG L2 loss', MSEloss.data[0], gen_iterations)\n print('[%d/%d][%d/%d][%d] mse %f '\n % (epoch, opt.niter, i, len(dataloader), gen_iterations, MSEloss.data[0]))\n else:\n writer.add_scalar('MSE/VGG L2 loss', MSEloss.data[0], gen_iterations)\n writer.add_scalar('errD(wasserstein distance)', errD.data[0], gen_iterations)\n writer.add_scalar('errD_real', errD_real.data[0], gen_iterations)\n writer.add_scalar('errD_fake', errD_fake.data[0], gen_iterations)\n writer.add_scalar('Gnet loss toward real', -errG.data[0], gen_iterations)\n writer.add_scalar('gradient_penalty'+ str(opt.gpW), lip_loss.data[0], gen_iterations)\n\n print('[%d/%d][%d/%d][%d] distance: %f err_G: %f err_D_real: %f err_D_fake %f GPLoss %f'\n % (epoch, opt.niter, i, len(dataloader), gen_iterations,\n errD.data[0], -errG.data[0], errD_real.data[0], errD_fake.data[0],\n lip_loss.data[0]))\n\n if gen_iterations % 500 == 0:\n fake = netG(Variable(fixed_zasshu, volatile=True)).data\n real = fake / scaler + fixed_PER\n writer.add_image('fakeHRRes', vutils.make_grid(fake.mul(0.5).add(0.5), nrow=16),\n gen_iterations)\n writer.add_image('fakeHR', vutils.make_grid(real.mul(0.5).add(0.5).clamp(0, 1), nrow=16),\n gen_iterations)\n vutils.save_image(real.mul(0.5).add(0.5),\n '%s/fake_samples_gen_iter_%08d.png' % (opt.outf, gen_iterations))\n\n gen_iterations += 1\n\n # do checkpointing\n if opt.cut == 0:\n torch.save(netG.state_dict(), '%s/netG_epoch_only.pth' % opt.outf)\n torch.save(netD.state_dict(), '%s/netD_epoch_only.pth' % opt.outf)\n elif epoch % opt.cut == 0:\n torch.save(netG.state_dict(), '%s/netG_epoch_%d.pth' % (opt.outf, epoch))\n torch.save(netD.state_dict(), '%s/netD_epoch_%d.pth' % (opt.outf, epoch))\n torch.save(optimizerG.state_dict(), '%s/optimG_checkpoint.pth' % opt.outf)\n torch.save(optimizerD.state_dict(), '%s/optimD_checkpoint.pth' % opt.outf)\n","repo_name":"orashi/WGAN-GP","sub_path":"wgangp_IDRESper.py","file_name":"wgangp_IDRESper.py","file_ext":"py","file_size_in_byte":20053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"43692828497","text":"# complete this function\n\n'''\n For your reference:\n'''\nclass TreeNode:\n def __init__(self, node_value):\n self.val = node_value\n self.left_ptr = None\n self.right_ptr = None\n\ndef build_balanced_bst(a):\n if a == [] : return None\n\n def bstHelper(start, end):\n if start > end : return None\n\n mid = (start + end) // 2\n LN = bstHelper(start, mid-1)\n RN = bstHelper(mid+1, end)\n newNode = TreeNode(a[mid])\n newNode.left_ptr = LN\n newNode.right_ptr= RN\n return newNode\n\n return bstHelper(0,len(a)-1)\n\nroot = build_balanced_bst([1,2,3,4,5,6,7])\n\nprint (root.val, root.left_ptr.val, root.right_ptr.val)\nroot = root.right_ptr\nprint (root.val, root.left_ptr.val, root.right_ptr.val)\n","repo_name":"prashuym/IKPrograms","sub_path":"Trees/Trees-Test2.py","file_name":"Trees-Test2.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"28218105757","text":"import math\nimport itertools \nfrom itertools import groupby\n\nfrom dv import AedatFile\nfrom dv import LegacyAedatFile\nimport numpy as np\nimport time\n\nimport os\nimport shutil\n\nwindow_time = 0.1 #ms\nstop_time = 60 #s\ncounter = [0, 0, 0, 0, 0, 0, 0, 0]\n\ndef mygrouper(n, iterable):\n args = [iter(iterable)] * n\n return ([e for e in t if e != None] for t in itertools.zip_longest(*args))\n\ndef all_equal(iterable):\n g = groupby(iterable)\n return next(g, True) and not next(g, False)\n\ndef get_time_classes(annotation_f):\n\n a_file = open(annotation_f, 'r')\n next(a_file)\n \n counter = 0\n t = 0\n\n all_samples = []\n\n for l in a_file:\n\n if (t > stop_time*1000):\n break\n\n if ((t%(window_time * 1000)) == 0):\n all_samples.append(t)\n\n l = l.replace('\\n', '')\n\n all_samples.append(l)\n\n counter += 1\n t = int(counter*(1000/30))\n\n all_samples = mygrouper((30 * window_time) + 1, all_samples) #Orig: 4\n all_samples = list(all_samples)\n\n time_classes = []\n\n for sample in all_samples:\n t = sample[0]\n\n if (t > stop_time*1000):\n break\n\n classes = sample[1:]\n\n if (all_equal(classes)):\n\n if (sample[1] == '-1'):\n time_classes.append([t/1000, '7'])\n else:\n time_classes.append([t/1000, sample[1]])\n\n all_samples = None\n\n return time_classes\n\ndef get_v2e_dvs_events(data_f):\n with LegacyAedatFile(data_f) as f:\n v2e_dvs_events = []\n for event in f:\n\n t = (event.timestamp)/1e6\n\n if (t > stop_time):\n break\n\n x = 345 - event.x\n y = 194 - event.y\n p = 1 if event.polarity else -1\n\n v2e_dvs_events.append([x, y, t, p])\n return v2e_dvs_events\n\ndef generate_numpy(target_path, list_1, list_2):\n list_numpy = []\n\n i = 0\n #counter = [0, 0, 0, 0, 0, 0, 0]\n global counter\n\n for l1 in list_1:\n ti = l1[0]\n tf = l1[0] + 0.1\n class_id = l1[1]\n\n i = 0\n for l2 in list_2:\n\n l2_t = l2[2]\n\n if (l2_t >= ti):\n if (l2_t < tf):\n list_numpy.append(l2)\n i = i + 1\n\n else:\n list_2 = list_2[i:]\n\n np.save(target_path + 'numpy/' + class_id + '/' + class_id + '_' + str(counter[int(class_id)]) + '.npy', np.array(list_numpy) )\n list_numpy = []\n\n counter[int(class_id)] += 1\n\n break\n\ndef numpy_folders(target_path):\n try:\n shutil.rmtree(target_path + 'numpy')\n except: \n print('Directory doesnt exist')\n \n access_rights = 0o777\n os.mkdir(target_path + 'numpy', access_rights)\n \n for a in range(0, 8):\n os.mkdir(target_path + 'numpy/' + str(a), access_rights)\n\n\ndef check_dimensions(target_path, f):\n\n output_height = False\n output_width = False\n\n with open(target_path + f + '/v2e-args.txt') as v2eargs:\n for line in v2eargs:\n #print(line)\n \n if ('output_height' in line and '195' in line):\n output_height = True\n \n if ('output_width' in line and '346' in line and output_height):\n output_width = True\n #break \n \n return (output_height and output_width)\n \nif __name__ == \"__main__\":\n\n target_path = 'data/Validation_Set/'\n\n numpy_folders(target_path)\n\n print(target_path)\n folders = os.listdir(target_path)\n folders.remove('annotations')\n folders.remove('numpy')\n\n print(folders)\n\n for f in folders:\n \n aedat = target_path + f + '/data.aedat'\n \n indexes = [i for i, x in enumerate(os.listdir(target_path + 'annotations/')) if f in x]\n if (len(indexes) == 1):\n\n print('\\n\\n\\n')\n print('f: ',f)\n print('target_path: ', target_path + f + '/data.aedat')\n \n print('')\n\n if (check_dimensions(target_path, f)):\n \n annotation = target_path + 'annotations/' + os.listdir(target_path + 'annotations/')[indexes[0]]\n \n print('aedat: ', aedat)\n print('annotation: ', annotation, '\\n')\n \n list_1 = get_time_classes(annotation)\n print('get_time_classes ok')\n \n \n start_time = time.time()\n list_2 = get_v2e_dvs_events(aedat)\n print('get_v2e_dvs_events ok')\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n \n \n start_time = time.time()\n generate_numpy(target_path, list_1, list_2)\n print('generate_numpy ok')\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n \n list_1 = None\n list_2 = None\n\n else:\n print('pass')\n\n","repo_name":"tlwzzy/Event-Camera-Applications","sub_path":"erl_numpy/numpy_affwild.py","file_name":"numpy_affwild.py","file_ext":"py","file_size_in_byte":5111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"31342228810","text":"import turtle as T\nimport time as t\nimport random as r\n\nCOLOR = [\"red\",\"green\",\"blue\",\"orange\",\"yellow\",\"black\",\"pink\",'lime','olive','seagreen']\n\ndef get_number_of_racers():\n racers = 0\n while True:\n racers = input(\"Enter the number of racers in the game(2 - 10): \")\n print(\"\\n\\n\")\n if racers.isdigit():\n racers = int(racers)\n else:\n print(\"Invalid input!!Please enter a character\")\n print(\"\\n\\n\")\n continue\n \n if 2 <= racers <= 10:\n return racers\n else:\n print(\"Too many racers!! Enter something small\")\n print(\"\\n\\n\")\n\ndef Screen():\n\n WIDTH = 500\n HEIGHT = 500\n T.Screen().setup(WIDTH,HEIGHT)\n T.Screen().title(\"TurtleRace\")\n\ndef turtle_racers(no):\n turtle_no = []\n x = -230; y = -230\n\n for a,b in enumerate(no):\n racers = T.Turtle()\n racers.color(b)\n racers.shape(\"turtle\")\n racers.left(90)\n racers.penup()\n racers.setpos(x , y)\n x += (480 // len(colors))\n racers.pendown()\n turtle_no.append(racers)\n\n return turtle_no\n\n\ndef Race(colors):\n\n turtleobj = turtle_racers(colors)\n\n while True:\n for racers in turtleobj:\n dis = r.randrange(1,15)\n racers.forward(dis)\n\n x , y = racers.pos()\n if y >= 240:\n return colors[turtleobj.index(racers)]\n\n\n\nScreen()\nracers = get_number_of_racers()\n\nr.shuffle(COLOR)\ncolors = COLOR[:racers]\n\nwinner = Race(colors)\nprint(\"The winner of the race is color: \" + winner.upper())\n","repo_name":"UpenTech/Turtle-Race","sub_path":"ProjectTurtle.py","file_name":"ProjectTurtle.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"18240131886","text":"import sqlite3\nimport os\nfrom typing import List\n\nfrom analyzed_tensor import AnalyzedTensor\n\n\ndef execute_db_script(sql_script : str, db_path : str):\n # Connect to the SQLite database (creates a new database if it doesn't exist)\n\n\n with sqlite3.connect(db_path) as conn:\n # Create a cursor object to execute SQL statements\n cursor = conn.cursor()\n\n # Execute the SQL code to create the tables\n cursor.executescript(sql_script)\n\n\ndef create_db(db_path : str):\n file_directory, file_name = os.path.split(os.path.realpath(__file__))\n sql_path = os.path.join(file_directory, 'sql', 'create_database.sql')\n \n with open(sql_path, 'r') as f:\n sql_script = f.read()\n execute_db_script(sql_script, db_path)\n\ndef put_experiment_data(db_path : str, results : List[AnalyzedTensor]):\n experiments = [exp.as_insert_param_list() for exp in results]\n with sqlite3.connect(db_path) as conn:\n cursor = conn.cursor()\n \n file_directory, file_name = os.path.split(os.path.realpath(__file__))\n\n insert_script_path = os.path.join(file_directory, 'sql', 'insert_experiment.sql')\n with open(insert_script_path, 'r') as f:\n insert_prep_statement = f.read()\n\n cursor.executemany(insert_prep_statement, experiments)\n\n\ndef delete_db(db_path : str):\n if os.path.exists(db_path):\n os.remove(db_path)\n\n","repo_name":"D4De/cnn-error-classifier","sub_path":"src/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"22777031993","text":"name = \"Mike\"\n\n# f stringという昨日を使う\nmessage = f\"ようこそ、{name}さん\"\n\n# 表示して確認\nprint(message)\n\nname2 = \"Kate\"\nage = 18\n\n# 複数の変数がある場合(数字もそのまま使える)\nprint(f\"{name2}は、{age}歳です\")\n","repo_name":"remopro-pro/webbasic","sub_path":"lesson/01_blog1/2_python/3_string/string2.py","file_name":"string2.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"41106261595","text":"from contextlib import suppress\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.utils import timezone\n\n####################################\n# Signals for cached prev task\n####################################\n\n# Define the previous version of the task for use it on the post_save handler\ndef cached_prev_task(sender, instance, **kwargs):\n instance.prev = None\n if instance.id:\n instance.prev = sender.objects.get(id=instance.id)\n\n\n######################################\n# Signals for close Task and Milestone\n######################################\n\ndef try_to_close_or_open_us_and_milestone_when_create_or_edit_task(sender, instance, created, **kwargs):\n _try_to_close_or_open_us_when_create_or_edit_task(instance)\n _try_to_close_or_open_milestone_when_create_or_edit_task(instance)\n\n\ndef try_to_close_or_open_us_and_milestone_when_delete_task(sender, instance, **kwargs):\n _try_to_close_or_open_us_when_delete_task(instance)\n _try_to_close_milestone_when_delete_task(instance)\n\n\n# US\ndef _try_to_close_or_open_us_when_create_or_edit_task(instance):\n from taiga.projects.userstories import services as us_service\n\n if instance.user_story_id:\n if us_service.calculate_userstory_is_closed(instance.user_story):\n us_service.close_userstory(instance.user_story)\n else:\n us_service.open_userstory(instance.user_story)\n\n if instance.prev and instance.prev.user_story_id and instance.prev.user_story_id != instance.user_story_id:\n if us_service.calculate_userstory_is_closed(instance.prev.user_story):\n us_service.close_userstory(instance.prev.user_story)\n else:\n us_service.open_userstory(instance.prev.user_story)\n\n\ndef _try_to_close_or_open_us_when_delete_task(instance):\n from taiga.projects.userstories import services as us_service\n\n with suppress(ObjectDoesNotExist):\n if instance.user_story_id:\n if us_service.calculate_userstory_is_closed(instance.user_story):\n us_service.close_userstory(instance.user_story)\n else:\n us_service.open_userstory(instance.user_story)\n\n\n# Milestone\ndef _try_to_close_or_open_milestone_when_create_or_edit_task(instance):\n from taiga.projects.milestones import services as milestone_service\n\n if instance.milestone_id:\n if milestone_service.calculate_milestone_is_closed(instance.milestone):\n milestone_service.close_milestone(instance.milestone)\n else:\n milestone_service.open_milestone(instance.milestone)\n\n if instance.prev and instance.prev.milestone_id and instance.prev.milestone_id != instance.milestone_id:\n if milestone_service.calculate_milestone_is_closed(instance.prev.milestone):\n milestone_service.close_milestone(instance.prev.milestone)\n else:\n milestone_service.open_milestone(instance.prev.milestone)\n\n\ndef _try_to_close_milestone_when_delete_task(instance):\n from taiga.projects.milestones import services\n\n with suppress(ObjectDoesNotExist):\n if instance.milestone_id and services.calculate_milestone_is_closed(instance.milestone):\n services.close_milestone(instance.milestone)\n\n\n####################################\n# Signals for set finished date\n####################################\n\ndef set_finished_date_when_edit_task(sender, instance, **kwargs):\n if instance.status is None:\n return\n if instance.status.is_closed and not instance.finished_date:\n instance.finished_date = timezone.now()\n elif not instance.status.is_closed and instance.finished_date:\n instance.finished_date = None\n","repo_name":"kaleidos-ventures/taiga-back","sub_path":"taiga/projects/tasks/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":3662,"program_lang":"python","lang":"en","doc_type":"code","stars":455,"dataset":"github-code","pt":"2"} +{"seq_id":"8159241129","text":"# encoding: utf-8\nimport multiprocessing\nimport os\nimport re\nimport uuid\nimport time\n\nfrom gozokia.i_o import Io\nfrom gozokia.conf import settings\nfrom gozokia.core import Rules\nfrom gozokia.core.text_processor import Analyzer\nfrom gozokia.utils.util_logging import Logging\nfrom gozokia.db import Model\n\n# settings.configure()\n\n# https://github.com/nltk/nltk/blob/develop/nltk/chat/util.py\n#chat = nltk.chat.util.Chat([(r'I like (.*)', ['Why do you like %1', 'Did you ever dislike %1']),], reflections)\n\n\ndef start_led():\n \"\"\"\n if the console is running on a RaspberryPi, run a led\n \"\"\"\n try:\n import RPi.GPIO as GPIO\n except ImportError:\n return False\n # Configure the Pi to use the BCM (Broadcom) pin names, rather than the pin positions\n GPIO.setmode(GPIO.BCM)\n\n red_pin = 18\n\n GPIO.setup(red_pin, GPIO.OUT)\n\n try:\n while True:\n GPIO.output(red_pin, True) # LED on\n time.sleep(0.5) # delay 0.5 seconds\n GPIO.output(red_pin, False) # LED off\n time.sleep(0.5) # delay 0.5 seconds\n finally:\n GPIO.cleanup()\n\n\nclass Gozokia:\n \"\"\"\n Queue of rules\n \"\"\"\n rules = []\n \"\"\"\n Text analyzer controller\n \"\"\"\n analyzer = None\n \"\"\"\n Input/Output controller\n \"\"\"\n io = None\n \"\"\"\n GOZOKIA_DIR: The directory where gozokia have been calling.\n \"\"\"\n GOZOKIA_DIR = os.path.dirname(os.path.abspath(__file__))\n\n \"\"\"\n PROJECT_DIR: The directory where the project is running.\n \"\"\"\n PROJECT_DIR = os.getcwd()\n\n RAISE_COND = 1\n\n OBJETIVE_COND = 2\n\n _no_rule = {'rule': \"Gozokia\", 'status': 0}\n\n def __init__(self, * args, **kwargs):\n session = kwargs.get('session', False)\n if session:\n self.session_id = session\n else:\n self.session_id = uuid.uuid1()\n user = kwargs.get('user', False)\n if user:\n self.user_id = user\n else:\n self.user_id = None\n self.rules = Rules(sessionid=self.session_id)\n\n def initialize(self, * args, **kwargs):\n # Set the text analyzer. Default nltk (http://www.nltk.org/)\n self.analyzer = Analyzer()\n\n # Set the model. Default nltk (http://www.nltk.org/)\n model = kwargs.get('model', False)\n self.db = model if model else Model()\n\n # Initialize the logger\n self.logger = Logging(__name__)\n self.logger.debug(\"DB selected: {}\".format(settings.DATABASES['default']['ENGINE']))\n self.logger.debug(\"Input selected: {}\".format(settings.GOZOKIA_INPUT_TYPE))\n self.logger.debug(\"Output selected: {}\".format(settings.GOZOKIA_OUTPUT_TYPE))\n self.logger.debug(\"Model: {}\".format(self.db,))\n\n # Initialize the i/o methods. Default input text and output text\n self.set_io(input_type=settings.GOZOKIA_INPUT_TYPE,\n output_type=settings.GOZOKIA_OUTPUT_TYPE,\n )\n\n def set_io(self, *args, **kwargs):\n self.io = Io(*args, **kwargs)\n\n def rule(self, **options):\n \"\"\"A decorator that is used to register a class for a\n given rule.\n \"\"\"\n def decorator(rule_class):\n self.__add_rule(rule_class, **options)\n return rule_class\n return decorator\n\n def __add_rule(self, rule_class, **options):\n self.rules.add(rule_class, **options)\n\n def check_system_rules(self):\n \"\"\"\n System rules are the core rules.\n \"\"\"\n rule = self._no_rule\n if self.sentence:\n sentence = self.sentence.lower()\n if sentence.startswith('gozokia'):\n if re.search(\"stop rule\", sentence):\n rule = self.rules.get_active_rule()\n if rule is not None:\n rule[\"class\"].set_completed()\n self.rules.stop_active_rule()\n return \"Stoped {}\".format(str(rule['rule'])), rule\n elif re.search(\"thanks|thank you\", sentence):\n return \"Your welcome\", rule\n elif re.search(\"bye|exit|shutdown\", sentence):\n return \"Bye\", rule\n return False, rule\n\n def retrospective(self):\n \"\"\"\n Initialize the rules based on old chats of the session or the user\n \"\"\"\n chat_history = self.db.get_chat(session=self.session_id, user=self.user_id)\n print(chat_history)\n for chat in chat_history:\n if chat.type_rule == 'O':\n for r in self.rules.get_rules():\n if str(r['rule']) == str(chat.rule):\n if chat.status == self.rules._STATUS_RULE_ACTIVE:\n self.rules.set_active_rule(r)\n elif chat.status == self.rules._STATUS_RULE_PENDING:\n self.rules.set_rule_pending(r)\n elif chat.status == self.rules._STATUS_RULE_COMPLETED:\n self.rules.set_rule_completed(r)\n\n def eval(self, sentence):\n \"\"\"\n Params:\n sentence: sting\n\n return:\n response_output: string. the response to send to the IO output\n print_output: string. The response to print, no parsed on IO output\n \"\"\"\n print_output = None\n self.sentence = sentence\n self.analyzer.set(sentence)\n\n # Add the input to DDBB\n self.db.set_chat(**{'user': self.user_id, 'session': self.session_id,\n 'text': self.sentence, 'type_rule': 'I',\n 'rule': None, 'status': None})\n self.retrospective()\n response_output, rule = self.check_system_rules()\n if not response_output:\n # Check rules:\n rule, response_output, print_output = self.rules.eval(self)\n if not rule:\n # Default \"no rules\"\n response_output = \"No rules. you said: {}\".format(sentence)\n rule = self._no_rule\n\n # Add the output to DDBB\n self.db.set_chat(**{'user': self.user_id, 'session': self.session_id,\n 'text': response_output, 'type_rule': 'O',\n 'rule': rule['rule'], 'status': rule['status']})\n\n return response_output, print_output\n\n def get_response(self, input_result):\n \"\"\"\n\n \"\"\"\n output_result = \"\"\n print_output = \"\"\n\n if input_result:\n output_result, print_output = self.eval(input_result)\n self.logger.debug(self.analyzer.get_tagged())\n if print_output:\n self.logger.debug(print_output)\n return self.io.response(output_result)\n\n return None\n\n def console(self):\n \"\"\"\n The api method's designed to run in console\n method works with the settings:\n GOZOKIA_INPUT_TYPE = \"terminal_txt\" or GOZOKIA_INPUT_TYPE = \"terminal_voice\"\n \"\"\"\n output_result = True\n p = multiprocessing.Process(target=start_led)\n p.start()\n while output_result != \"Bye\":\n output_result = self.get_response(self.io.listen())\n print(output_result)\n\n self.logger.debug(self.db.get())\n p.terminate()\n\n def api(self, input_result):\n \"\"\"\n The api methods designed to receive a value and parse. This\n method works with the settings:\n GOZOKIA_INPUT_TYPE = \"value\"\n ------------------------------------------------------------\n self.io.listen return a string\n \"\"\"\n return self.get_response(input_result=self.io.listen(value=input_result))\n","repo_name":"avara1986/gozokia","sub_path":"gozokia/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"17190278511","text":"# dfs 를 공부해 보자 -1\n# 방문 안한 정점을 push하는 방식의 코드\n# 7 8\n# 1 2 1 3 2 4 2 5 4 6 5 6 6 7 3 7\n\ndef dfs(n, v):\n stack = []\n visited = [0]*(v+1) # 방문표시\n visited[n] = 1\n\n stack.append(n)\n\n while stack:\n n = stack.pop() # 인접 노드 중 하나를 꺼내서 방문\n print(n, end=\" \")\n\n for i in range(v, 0, -1):\n if adj[n][i] != 0 and visited[i] == 0: # n 과 i가 인접이고 방문하지 않은 노드면\n stack.append(i) # n에 인접한 모든 노드를 push\n visited[i] = 1\n # return 0\n\n\n\nV, E = map(int, input().split()) # 노드 수, 선 수\nedge = list(map(int, input().split())) # 경로\n\nadj = [[0]*(V+1) for i in range(V+1)]\n\n# print(V, E)\n# print(edge)\n# print(adj)\n\nfor i in range(E):\n n1 = edge[i*2]\n n2 = edge[i*2+1]\n # print(n1, n2)\n\n adj[n1][n2] = 1\n # print(adj)\n adj[n2][n1] = 1 # 무방향의 경우\n\ndfs(1, V)\n","repo_name":"Lagom92/algorithm","sub_path":"0402/dfs01.py","file_name":"dfs01.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"8269267506","text":"#!/usr/bin/env python3\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass Player:\n def __init__(self, name):\n self.name = name\n self.raw_scores = []\n def add_score(self, score):\n self.raw_scores.append(score)\n def add_colour(self, colour):\n self.colour = colour\n def filter_scores(self):\n raw_scores_np = np.array(self.raw_scores, np.float)\n self.scores = np.ma.masked_invalid(raw_scores_np).compressed()\n def filter_rounds(self):\n rounds = np.arange(len(self.raw_scores))\n rounds += 1\n idx = np.isfinite(np.array(self.raw_scores, np.float))\n self.played_rounds = np.ma.masked_equal(np.array(rounds*idx),0).compressed()\n \n\n\n# old scores\nX = float('nan')\nquiz_1 = [[],[],[],[],[],[]]\n######### brns, bckt, wazz, arns, kirk, frew\nquiz_1[0] = (9612, X , 8094, 5612, 6634, 5135)\nquiz_1[1] = (X , 5228, 6386, 3631, 3346, 1688)\nquiz_1[2] = (8867, 7904, 8043, X , 5847, 6620)\nquiz_1[3] = (9207, 9775, 2812, 5630, 5266, X )\nquiz_1[4] = (9254, 4953, X , 5769, 5919, 5597)\nquiz_1[5] = (8776, 7751, 7361, 8850, X , 7276)\n\nplayers = {}\nplayers_names = [\"burns\", \"beckett\", \"waz\", \"airns\", \"kirk\", \"frew\"]\np1 = Player(\"Burns\")\nfor i in range(6):\n name = players_names[i]\n players[name] = Player(name)\n scores_old = [x[i] for x in quiz_1]\n\n for j in range(6):\n players[name].add_score(scores_old[j])\n\nplayers[\"burns\"].add_colour(\"blue\")\nplayers[\"beckett\"].add_colour(\"red\")\nplayers[\"waz\"].add_colour(\"indigo\")\nplayers[\"airns\"].add_colour(\"gold\")\nplayers[\"kirk\"].add_colour(\"tab:cyan\")\nplayers[\"frew\"].add_colour(\"magenta\")\n\n#scores_brns_mod = players[\"burns\"].scores\n#scores_bckt_mod = players[\"beckett\"].scores\n\n\n# linear fit\n# for key, player in players.items():\n# player.filter_rounds()\n# player.filter_scores()\n# #print(player.name,\":\", player.scores, player.played_rounds)\n \n# plt.plot(player.played_rounds, player.scores, 'o', label=key.format('o'), color=player.colour)\n# function = np.poly1d(np.polyfit(player.played_rounds, player.scores, 1))\n# plt.plot((1, len(player.raw_scores)), (function(1), function(len(player.raw_scores))),color=player.colour)\n\n\nfor key, player in players.items():\n player.filter_rounds()\n player.filter_scores()\n print(player.name,\":\", player.scores, player.played_rounds)\n \n plt.plot(player.played_rounds, player.scores, label=key.format('o'), color=player.colour)\n plt.plot(player.played_rounds, player.scores, 'o', color=player.colour)\n\n \n \nplt.legend(numpoints=1)\n\nplt.show()\n","repo_name":"neilwarrack/quiz_scorekeeper","sub_path":"progress.py","file_name":"progress.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"6226922662","text":"#EXERCICIO 1\n\ndef par_ou_impar(numero):\n if numero % 2 == 0:\n print(f'O número {numero} é par.')\n else:\n print(f'O número {numero} é impar.')\n\npar_ou_impar(int(input(\"Digite o número inteiro: \")))\n\n#EXERCICIO 2\ndef multiplo_ou_nao(numero):\n if numero % 5 == 0:\n print(f'O número {numero} é multiplo de 5.')\n else:\n print(f'O número {numero} não é multiplo de 5.')\n\nmultiplo_ou_nao(int(input(\"Digite o numero inteiro: \")))\n\n#EXERCICIO 3\ndef multiplo_de_5(numero):\n if numero % 5 == 0:\n return True\n else:\n return False\n \ndef multiplo_de_3(numero):\n if numero % 3 == 0:\n return True\n else:\n return False\n \nnumero = int(input(\"Digite o número inteiro: \"))\nif multiplo_de_5(numero) and multiplo_de_3(numero):\n print(f\"O número {numero} é multiplo de 5 e de 3.\")\nelif multiplo_de_5(numero):\n print(f\"O número {numero} é multiplo de 5.\")\nelif multiplo_de_3(numero):\n print(f\"O número {numero} é multiplo de 3.\")\nelse:\n print(f\"O número {numero} não é multiplo de 5 e nem de 3.\")\n\n#EXERCICIO 4\n\ndef fibonacci(numero_de_elementos):\n if numero_de_elementos == 1:\n return 0\n elif numero_de_elementos == 2:\n return [0,1]\n else: \n fibonacci = [0,1]\n for i in range(2,numero_de_elementos):\n novo_elemento_da_lista = fibonacci[-1] + fibonacci[-2]\n fibonacci.append(novo_elemento_da_lista)\n return fibonacci\n \nprint(fibonacci(int(input(\"Digite a quantidade de números de Fibonacci que você\"))))\n\n#EXERCICIO 5\n\ndef checagem_multiplo_5(numero):\n if numero % 5 == 0:\n print(f\"O número {numero} é múltiplo de 5.\")\n return True\n else:\n print(f\"O número {numero} não é múltiplo de 5.\")\n return False\n \nchecagem_multiplo_5(numero)\n\n#EXERCICIO 6\n\n#Solicitar ao usuario inserir um numero inteiro positivo\n\ndef solicitar_numero():\n numero_inserido = int(input(\"Digite um número inteiro positivo: \"))\n if numero_inserido == \"\":\n print(\"Você não digitou um número.\")\n return solicitar_numero()\n if numero_inserido.isnumeric():\n print(\"Você não digitou um número.\")\n return solicitar_numero()\n return int(numero_inserido)\n\n","repo_name":"walrich/Atividades---Romes","sub_path":"ativ04-09.py","file_name":"ativ04-09.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"7723644045","text":"#\n# @lc app=leetcode id=338 lang=python3\n#\n# [338] Counting Bits\n#\n\n# @lc code=start\nclass Solution:\n def countBits(self, n: int) -> List[int]:\n '''\n ans = [0]\n for i in range(1,n+1):\n num = 0\n k = i\n while(k!=0):\n num = num + (k%2==1)\n k = int(k/2)\n ans.append(num)\n return ans\n '''\n \n ans = [0,1]\n if n<=1:return ans[:n+1]\n b = int(log2(n))\n for i in range(1,b+2):\n for j in range(0,2**i):\n ans.append(ans[j]+1)\n return ans[:n+1]\n\n \n# @lc code=end\n\n","repo_name":"mry603/pyleetcode","sub_path":"dynamicProgram/338.counting-bits.py","file_name":"338.counting-bits.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"70208909167","text":"# Uses python3\nimport sys\nfrom collections import namedtuple\nfrom itertools import combinations\nfrom typing import List\n\nSegment = namedtuple('Segment', 'start end')\n\n\ndef is_point_inside_segment(segment: Segment, point: float) -> bool:\n return segment.start <= point <= segment.end\n\n\ndef is_segment_covered(segment: Segment, list_of_points: List[float]) -> bool:\n covered = False\n\n for point in list_of_points:\n if is_point_inside_segment(segment, point):\n covered = True\n break\n\n return covered\n\n\ndef is_combination_covering_all_segments(segments: List[Segment], list_of_points: List[float]) -> bool:\n covered = True\n\n for segment in segments:\n if not is_segment_covered(segment, list_of_points):\n covered = False\n break\n\n return covered\n\n\ndef optimal_points_naive(segments: List[Segment]) -> List[float]:\n min_point = 1\n max_point = max([x.end for x in segments])\n\n all_possible_points = range(min_point, max_point + 1)\n\n right_combination = None\n\n for number_of_points in all_possible_points:\n all_possible_combinations = combinations(all_possible_points, number_of_points)\n\n for possible_combination in iter(reversed(list(all_possible_combinations))):\n if is_combination_covering_all_segments(segments, possible_combination):\n right_combination = possible_combination\n break\n\n if right_combination:\n break\n\n return right_combination\n\n\ndef optimal_points_efficient(segments: List[Segment]) -> List[float]:\n segments = iter(sorted(segments, key=lambda x: x.end))\n segment = next(segments)\n maximum_point = segment.end\n right_combination = list()\n\n while True:\n try:\n if not is_point_inside_segment(segment, maximum_point):\n right_combination.append(maximum_point)\n maximum_point = segment.end\n else:\n segment = next(segments)\n except StopIteration:\n break\n\n right_combination.append(maximum_point)\n\n return right_combination\n\n\nif __name__ == '__main__':\n input_data = sys.stdin.read()\n n, *data = map(int, input_data.split())\n input_segments = list(map(lambda x: Segment(x[0], x[1]), zip(data[::2], data[1::2])))\n output_points = optimal_points_efficient(input_segments)\n\n print(len(output_points))\n for p in output_points:\n print(p, end=' ')\n","repo_name":"Giuco/data-structures-and-algorithms","sub_path":"course-1-algorithmic-toolbox/week-3/5-collecting-signatures/covering_segments.py","file_name":"covering_segments.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"38571482586","text":"#Importing modules\n\nimport json\nimport os\n\nfrom joblib import dump\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestRegressor\n\n\n# Load directory paths for persisting model and metadata \n\nMODEL_DIR = os.environ[\"MODEL_DIR\"]\nMODEL_FILE = os.environ[\"MODEL_FILE\"]\nMETADATA_FILE = os.environ[\"METADATA_FILE\"]\nMODEL_PATH = os.path.join(MODEL_DIR, MODEL_FILE)\nMETADATA_PATH = os.path.join(MODEL_DIR, METADATA_FILE)\n\n# Preprocessing and Model build\ntop_features=['OverallQual',\n'GrLivArea',\n 'TotalBsmtSF',\n '1stFlrSF',\n 'BsmtFinSF1',\n 'GarageArea',\n '2ndFlrSF',\n 'TotRmsAbvGrd',\n 'LotArea',\n 'YearBuilt',\n 'SalePrice']\n\nprint(\"Loading data ...\")\n\ndf_train=pd.read_csv('train.csv')\ndf_train_sub=df_train[top_features]\nlabels = np.array(df_train_sub['SalePrice'])\nfeatures= df_train_sub.drop('SalePrice', axis = 1)\nfeature_list = list(features.columns)\nfeatures = np.array(features)\n\nprint(\"Splitting data ..\")\ntrain_features, test_features, train_labels, test_labels = \\\n train_test_split(features, labels, test_size = 0.2, random_state = 42)\n\nprint(\"Building model and prediction..\")\n\nrf = RandomForestRegressor(n_estimators = 1000, random_state = 42)\nrf.fit(train_features, train_labels)\npredictions = rf.predict(test_features)\n\n\n# Error calculation\n\nerrors = abs(predictions - test_labels)\n# Calculate mean absolute percentage error (MAPE)\nmape = 100 * (errors / test_labels)\n# Calculate and display accuracy\naccuracy = 100 - np.mean(mape)\n\nmetadata = {\n \"test_accuracy\": accuracy\n}\n\n# Serialize model and metadata \n\nprint(\"Serializing model to: {}\".format(MODEL_PATH))\ndump(rf,MODEL_FILE)\n\nprint(\"Serializing metadata to: {}\".format(METADATA_PATH))\nwith open(METADATA_FILE,'w') as outfile: \n json.dump(metadata, outfile)\n\n","repo_name":"krishanubanerjee/kaggle-housing","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"31462253754","text":"#from sklearn import datasets\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import roc_curve, auc\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.preprocessing import label_binarize\r\nfrom sklearn.multiclass import OneVsRestClassifier\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom pandas import read_csv\r\n\r\n\r\n#load the csv file using read_csv function of pandas library\r\nfilename = 'iris_encoded.csv'\r\nnames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']\r\ndataframe = read_csv(filename, names=names)\r\narray = dataframe.values\r\n#splitting the array to input and output\r\nX = array[:,0:4]\r\ny = array[:,4]\r\n\r\n#iris = datasets.load_iris()\r\n#X, y = iris.data, iris.target\r\n\r\ny = label_binarize(y, classes=[0,1,2])\r\nn_classes = 3\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.75, random_state=50)\r\n\r\nclf = OneVsRestClassifier(LogisticRegression())\r\ny_score = clf.fit(X_train, y_train).decision_function(X_test)\r\n\r\nfpr = dict()\r\ntpr = dict()\r\nroc_auc = dict()\r\nfor i in range(n_classes):\r\n fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])\r\n roc_auc[i] = auc(fpr[i], tpr[i])\r\n \r\n# plotting \r\nplt.plot(fpr[0], tpr[0], linestyle='--',color='orange', label='ROC curve Class 0 vs Rest (area = %0.2f)' % roc_auc[0])\r\nplt.plot(fpr[1], tpr[1], linestyle='--',color='green', label='ROC curve Class 1 vs Rest (area = %0.2f)' % roc_auc[1])\r\nplt.plot(fpr[2], tpr[2], linestyle='--',color='blue', label='ROC curve Class 2 vs Rest (area = %0.2f)' % roc_auc[2])\r\nplt.xlabel('False Positive Rate')\r\nplt.ylabel('True Positive Rate')\r\nplt.title('Receiver operating characteristic example')\r\nplt.legend(loc=\"lower right\")\r\nplt.show()\r\n\r\n\r\n","repo_name":"PacktPublishing/Machine-Learning-and-Data-Science-with-Python-A-Complete-Beginners-Guide","sub_path":"iris_final_model_auc.py","file_name":"iris_final_model_auc.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"20"} +{"seq_id":"7808494639","text":"import requests\nfrom urllib.parse import urljoin\nfrom constants import ENDPOINTS, DEFAULT_LIMIT, API_TIME_FORMAT\nfrom CyberintParser import CyberintParser\nfrom UtilsManager import validate_response, filter_old_alerts\nimport math\nimport datetime\n\n\nclass CyberintManager:\n def __init__(self, api_root, api_key, verify_ssl, siemplify_logger=None):\n \"\"\"\n The method is used to init an object of Manager class\n :param api_root: {str} Cyberint API root\n :param api_key: {str} Cyberint password\n :param verify_ssl: {bool} Specifies if certificate that is configured on the api root should be validated\n :param siemplify_logger: Siemplify logger\n \"\"\"\n self.api_root = api_root[:-1] if api_root.endswith(\"/\") else api_root\n self.api_key = api_key\n self.verify_ssl = verify_ssl\n self.siemplify_logger = siemplify_logger\n self.session = requests.session()\n self.session.verify = verify_ssl\n self.session.headers.update({\"Cookie\": f\"access_token={self.api_key}\"})\n self.parser = CyberintParser()\n\n def _get_full_url(self, url_id, **kwargs):\n \"\"\"\n Get full url from url identifier.\n :param url_id: {str} The id of url\n :param kwargs: {dict} Variables passed for string formatting\n :return: {str} The full url\n \"\"\"\n return urljoin(self.api_root, ENDPOINTS[url_id].format(**kwargs))\n\n def test_connectivity(self):\n \"\"\"\n Test connectivity\n \"\"\"\n request_url = self._get_full_url(\"ping\")\n payload = {\n \"page\": 1,\n \"size\": 10\n }\n response = self.session.post(request_url, json=payload)\n validate_response(response)\n\n def update_alert(self, alert_id, status, closure_reason):\n \"\"\"\n Update alert status\n :param alert_id: {str} Alert id\n :param status: {str} Status to update\n :param closure_reason: {str} Closure reason, if status is \"closed\"\n \"\"\"\n request_url = self._get_full_url(\"update_alert\")\n payload = {\n \"alert_ref_ids\": [alert_id],\n \"data\": {\n \"status\": status\n }\n }\n\n if closure_reason:\n payload[\"data\"][\"closure_reason\"] = closure_reason\n\n response = self.session.put(request_url, json=payload)\n validate_response(response)\n\n def get_alerts(self, existing_ids, limit, start_timestamp, type_filter, severity_filter):\n \"\"\"\n Get alerts\n :param existing_ids: {list} The list of existing ids\n :param limit: {int} The limit for results\n :param start_timestamp: {datetime} The timestamp for oldest alert to fetch\n :param type_filter: {list} Type filter to apply\n :param severity_filter: {list} Severity filter to apply\n :return: {list} The list of filtered Finding objects\n \"\"\"\n request_url = self._get_full_url(\"get_alerts\")\n payload = {\n \"page\": 1,\n \"size\": DEFAULT_LIMIT,\n \"filters\": {\n \"created_date\": {\n \"from\": start_timestamp.strftime(API_TIME_FORMAT),\n \"to\": datetime.datetime.now().strftime(API_TIME_FORMAT)\n },\n \"severity\": severity_filter,\n \"status\": [\"open\", \"acknowledged\"]\n }\n }\n if type_filter:\n payload[\"filters\"][\"type\"] = type_filter\n\n response = self.session.post(request_url, json=payload)\n validate_response(response)\n json_result = response.json()\n total = json_result.get(\"total\", 0)\n pages = math.ceil(total/DEFAULT_LIMIT)\n\n alerts = self.parser.build_alerts_list(json_result)\n\n for page in range(pages):\n if page > 0:\n payload[\"page\"] = page + 1\n response = self.session.post(request_url, json=payload)\n validate_response(response)\n alerts.extend(self.parser.build_alerts_list(response.json()))\n\n filtered_alerts = filter_old_alerts(logger=self.siemplify_logger, alerts=alerts, existing_ids=existing_ids)\n return sorted(filtered_alerts, key=lambda alert: alert.created_date)[:limit]\n","repo_name":"chronicle/tip-marketplace","sub_path":"Integrations/Cyberint/Managers/CyberintManager.py","file_name":"CyberintManager.py","file_ext":"py","file_size_in_byte":4259,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"4158019465","text":"from Renderer.Objects.Components.component import Component\nfrom Renderer.Objects.Components.image import Image\nfrom Renderer.renderer import Renderer\nfrom log import Log\n\n\nclass Gif(Component):\n\n def __init__(self, path, timeToChange, action=None):\n self.__activeImage = 0\n self.__timeToChange = timeToChange\n self.__timer = timeToChange\n self.__images = dict()\n self.__action = action\n i = 0\n while 1:\n try:\n self.__images[i] = Image(f\"{path}_{i+1}\", (0.5, 0.5))\n i += 1\n except Exception as e:\n Log.executionLog(f\"Loaded gif {path} with {i} images.\")\n break\n\n def isRenderable(self):\n return True\n\n def nextImage(self):\n self.__activeImage += 1\n if self.__activeImage == len(self.__images):\n self.__activeImage = 0\n if self.__action:\n self.__action()\n\n def render(self):\n return self.__images[self.__activeImage].render()\n\n def tick(self):\n self.__timer -= Renderer.getDeltaTime()\n if self.__timer < 0:\n self.__timer += self.__timeToChange\n self.nextImage()\n\n def getActiveImage(self):\n return self.__activeImage\n","repo_name":"Suabyak/PiPO-projekt","sub_path":"Renderer/Objects/Components/gif.py","file_name":"gif.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"14327583293","text":"from ._skyBase import RadianceSky\nfrom ..command.genskyvec import Genskyvec\nfrom ..command.gensky import Gensky\nfrom ..command.gendaylit import Gendaylit\nfrom ..parameters.gendaylit import GendaylitParameters\n\nfrom ladybug.epw import EPW\nfrom ladybug.dt import DateTime\nimport os\n\n\nclass SkyVector(RadianceSky):\n \"\"\"Radiance sky vector.\n\n Attributes:\n sky: A sky object generated either by gensky or gendaylit. If you're not\n sure how to create them use one of the classmethods.\n skyDensity: A positive intger for sky density. [1] Tregenza Sky,\n [2] Reinhart Sky, etc. (Default: 1)\n \"\"\"\n\n def __init__(self, sky, skyDensity=1, isClimateBased=False):\n \"\"\"Create sky.\"\"\"\n RadianceSky.__init__(self)\n self.sky = sky\n self.__month = self.sky.monthDayHour[0]\n self.__day = self.sky.monthDayHour[1]\n self.__hour = self.sky.monthDayHour[2]\n self.skyDensity = skyDensity or 1\n self.__isClimateBased = isClimateBased\n\n # from radiation values\n @classmethod\n def fromRadiationValues(\n cls, location, directNormalRadiation, diffuseHorizontalRadiation,\n month=6, day=21, hour=12, skyDensity=1, north=0):\n \"\"\"From radiation values.\"\"\"\n skyfile = 'CB_{}_{}_{}_{}_{}_{}_{}_{}.sky'.format(\n location.stationId, location.city.replace(' ', ''), location.latitude,\n location.longitude, month, day, hour, north\n )\n\n gdp = GendaylitParameters(dirNormDifHorzIrrad=(directNormalRadiation,\n diffuseHorizontalRadiation))\n\n gendl = Gendaylit(monthDayHour=(month, day, hour), rotation=north,\n gendaylitParameters=gdp)\n\n gendl.outputFile = skyfile\n\n return cls(gendl, skyDensity, isClimateBased=True)\n\n @classmethod\n def fromEpwFile(cls, epwFile, month=6, day=21, hour=12, skyDensity=1,\n north=0):\n \"\"\"Generate a climate-based sky vector.\n\n This methos uses Radiance's gendaylit.\n\n Args:\n epwFile: Full path to epw weather file.\n month: Month [1..12] (default: 6).\n day: Day [1..31] (default: 21).\n hour: Hour [0..23] (default: 12).\n skyType: An intger between 0-5 for CIE sky type.\n 0: [+s] Sunny with sun, 1: [-s] Sunny without sun,\n 2: [+i] Intermediate with sun, 3: [-i] Intermediate with no sun,\n 4: [-c] Cloudy overcast sky, 5: [-u] Uniform cloudy sky\n skyDensity: A positive intger for sky density. [1] Tregenza Sky,\n [2] Reinhart Sky, etc. (Default: 1)\n \"\"\"\n epw = EPW(epwFile)\n location = epw.location\n HOY = DateTime(month, day, hour).HOY\n dnr = epw.directNormalRadiation.values()[HOY]\n dhr = epw.diffuseHorizontalRadiation.values()[HOY]\n\n return cls.fromRadiationValues(location, dnr, dhr, month, day, hour,\n skyDensity, north)\n\n @classmethod\n def fromCIESky(cls, location, month=6, day=21, hour=12, skyType=0,\n skyDensity=1, north=0):\n \"\"\"Generate a sky vector from an standard CIE sky.\n\n Args:\n month: Month [1..12] (default: 6).\n day: Day [1..31] (default: 21).\n hour: Hour [0..23] (default: 12).\n skyType: An intger between 0-5 for CIE sky type.\n 0: [+s] Sunny with sun, 1: [-s] Sunny without sun,\n 2: [+i] Intermediate with sun, 3: [-i] Intermediate with no sun,\n 4: [-c] Cloudy overcast sky, 5: [-u] Uniform cloudy sky\n skyDensity: A positive intger for sky density. [1] Tregenza Sky,\n [2] Reinhart Sky, etc. (Default: 1)\n \"\"\"\n skyfile = 'CIE_{}_{}_{}_{}_{}_{}_{}_{}_{}.sky'.format(\n location.stationId, location.city.replace(' ', ''), location.latitude,\n location.longitude, month, day, hour, skyType, north\n )\n gensk = Gensky.fromSkyType(skyfile, monthDayHour=(month, day, hour),\n skyType=skyType,\n latitude=location.latitude,\n longitude=location.longitude,\n meridian=float(location.timeZone) * -15,\n rotation=north)\n gensk.outputFile = skyfile\n\n return cls(gensk, skyDensity, isClimateBased=False)\n\n @property\n def isClimateBased(self):\n \"\"\"Return True if the sky is generated from values from weather file.\"\"\"\n return self.__isClimateBased\n\n @property\n def isSkyVector(self):\n \"\"\"Return True.\"\"\"\n return True\n\n @property\n def hour(self):\n \"\"\"Return hour.\"\"\"\n return self.__hour\n\n @property\n def day(self):\n \"\"\"Return hour.\"\"\"\n return self.__day\n\n @property\n def month(self):\n \"\"\"Return hour.\"\"\"\n return self.__month\n\n @property\n def name(self):\n \"\"\"Sky default name.\"\"\"\n try:\n return \"SKYVEC_{}\".format(\n '.'.join(os.path.split(self.sky.outputFile)[-1].split('.')[:-1])\n )\n except TypeError:\n return \"SKYVEC_{}\".format(\n '.'.join(str(self.sky.outputFile).split('.')[:-1])\n )\n\n # TODO: re-write the method! It's Currently very shaky\n def toRadString(self, workingDir=None, relativePath=None):\n \"\"\"Return Radiance command line.\"\"\"\n if workingDir:\n # make sure the original sky (*.sky) will be writtern to working dir\n skyoutputFile = os.path.join(workingDir, str(self.sky.outputFile))\n # set the sky vector to be written to the working dir (*.vec)\n outfilepath = os.path.join(workingDir, '{}.vec'.format(self.name))\n if relativePath:\n outfilepath = os.path.relpath(outfilepath, relativePath)\n skyoutputFile = os.path.relpath(skyoutputFile, relativePath)\n else:\n outfilepath = '{}.vec'.format(self.name)\n skyoutputFile = str(self.sky.outputFile)\n\n self.sky.outputFile = skyoutputFile\n self.sky.execute()\n\n genskv = Genskyvec()\n genskv.inputSkyFile = skyoutputFile\n genskv.outputFile = outfilepath\n genskv.skySubdivision = self.skyDensity\n return genskv.toRadString()\n\n def execute(self, workingDir, reuse=True):\n \"\"\"Generate sky vector.\n\n Args:\n workingDir: Folder to execute and write the output.\n reuse: Reuse the matrix if already existed in the folder.\n \"\"\"\n outfilepath = os.path.join(workingDir, '{}.vec'.format(self.name))\n if reuse and os.path.isfile(outfilepath):\n return outfilepath\n\n # update path for the sky file\n self.sky.outputFile = os.path.join(workingDir, str(self.sky.outputFile))\n genskv = Genskyvec()\n genskv.inputSkyFile = str(self.sky.execute())\n genskv.outputFile = outfilepath\n genskv.skySubdivision = self.skyDensity\n genskv.execute()\n return outfilepath\n\n def ToString(self):\n \"\"\"Overwrite .NET ToString method.\"\"\"\n return self.__repr__()\n\n def __repr__(self):\n \"\"\"Sky representation.\"\"\"\n return self.name\n","repo_name":"ladybug-tools/honeybee-server","sub_path":"honeybee/radiance/sky/skyvector.py","file_name":"skyvector.py","file_ext":"py","file_size_in_byte":7388,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"20"} +{"seq_id":"21052704346","text":"import sys\nimport os\n\nFORMATT = \"gg/mm/aaaa\"\n\nfitt_translate ={'0' : 'linear', '1':'AVD', '2':'SVE', '3':'CIR', '4':'NS' }\n\nnameSheetCurve = 'SwapCurve'\nnameSheetBootstrap = 'ElabSwapCurve'\nnameSheetCDSBootSurv = 'Surv Prob CDS'\nnameSheetCDSBootMarginal = 'Marginal default'\nnameSheetCDSBootHazard = 'Hazard rate'\nnameSheetCDSBootSpread = 'Spread CDS'\nnameSheetCDSBootZcSpread = 'ZC Spread CDS'\nnameSheetCDSBootPySpread = 'PY Spread CDS'\nnameSheetBVolBoot = 'Spot volatilities'\n\nnameSheetBondSurv = 'Surv Prob BOND'\nnameSheetBondSpread = 'Spread BOND'\nnameSheetBondResults = 'Bond results'\nnameSheetBondFittig = 'Bond fitting'\nnameSheetResBondFittig = 'Results Bond fitting'\nnameSheetBondOptPrms = 'Opt prms'\n\n\nnameSheetCDS = 'CDS'\nnameSheetBond = 'Bond data'\nnameSheetCalib = 'Calib data'\nnameSheetCalibRes = 'Calib result'\n\n#INSERITA PER IL CARICAMENTO DATI, ANCORA DA UTILIZZARE\nnameSheetLoadAnagrafica = 'Anagrafica'\nnameSheetLoadDati = 'Dati'\n\n#INSERITA PER LO SCARICO DELLA MATRICE SWAPTION\nnameSheetScaricoSwaption='Matrix_Swaption'\n\n#INSERITA PER L'ELABORAZIONE DELLE MATRICI\nnameSheetElabMatrix = 'Matrix_Elab'\nnameSheetElabMatrixResult = 'Matrix_Elab_Result'\n\n#INSERITA PER LO SCARICO DELLE VOLATILITA FLAT IMPLICITE NEI CAP E FLOOR\nnameSheetCapFloorVolatilities = 'Cap Floor Vols'\n","repo_name":"monacoa/scenario","sub_path":"sc_elab/excel_hook/DEF_intef.py","file_name":"DEF_intef.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"26969327068","text":"def search(cnt):\n global result\n if cnt == len(check): # 모든 요소 True/False 로 뽑기 => 팀 나누기\n temp = 0\n for i in range(len(check)): # True 값 세주기\n if check[i] == True:\n temp += 1\n if temp == N//2: # 반으로 나눴을 때 값을 체크\n a_list = []\n b_list = []\n a_team = 0\n b_team = 0\n for i in range(len(check)): # a팀 누구누군지\n if check[i] == True:\n a_list.append(i)\n else: # b팀 누구누군지\n b_list.append(i)\n for i in a_list:\n for j in a_list:\n if i != j:\n a_team += arr[i][j] # a팀 시너지합\n for i in b_list:\n for j in b_list:\n if i != j:\n b_team += arr[i][j] # b팀 시너지합\n if abs(a_team - b_team) < result: # 각 팀의 합의 차 계산해서 결과값에 최솟값 저장\n result = abs(a_team - b_team)\n\n return \n\n check[cnt] = True # 재\n search(cnt+1) # 귀\n check[cnt] = False # 함\n search(cnt+1) # 수\n\n\n\n\nN = int(input())\narr = [list(map(int, input().split())) for i in range(N)]\n\ncnt = 0\ncheck = [False] * N\nresult = 100000\n\nsearch(0)\nprint(result)","repo_name":"titiman1013/Algorithm","sub_path":"20.02.25/백준 14889.py","file_name":"백준 14889.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"70132574769","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import Http404\n\nfrom .models import Topic, Entry\nfrom .forms import TopicForm, EntryForm\n\n\ndef index(request):\n \"\"\"Домашняя страница приложения Learning Log\"\"\"\n return render(request, 'site/index.html')\n\n\n@login_required\ndef topics(request):\n \"\"\"Выводит список тем\"\"\"\n topics = Topic.objects.filter(owner=request.user).order_by('date_added')\n context = {'topics': topics}\n return render(request, 'site/topics.html', context)\n\n\n@login_required\ndef topic(request, topic_id):\n \"\"\"Выводит одну из тем и все её записи\"\"\"\n topic = Topic.objects.get(id=topic_id)\n if topic.owner != request.user:\n raise Http404\n\n entries = topic.entry_set.order_by('-date_add')\n context = {'topic': topic, 'entries': entries}\n return render(request, 'site/topic.html', context)\n\n\n@login_required\ndef new_topic(request):\n \"\"\"Страница создания топиков\"\"\"\n if request.method != 'POST':\n form = TopicForm()\n else:\n form = TopicForm(data=request.POST)\n if form.is_valid():\n new_topic = form.save(commit=False)\n new_topic.owner = request.user\n new_topic.save()\n\n return redirect('topics')\n context = {'form': form}\n return render(request, 'site/new_topic.html', context)\n\n\n@login_required\ndef new_entry(request, topic_id):\n \"\"\"Добавляет новую запись по конкретной теме\"\"\"\n topic = Topic.objects.get(id=topic_id)\n\n if request.method != 'POST':\n form = EntryForm()\n else:\n form = EntryForm(data=request.POST)\n if form.is_valid():\n new_entry = form.save(commit=False)\n new_entry.topic = topic\n new_entry.save()\n return redirect('topic', topic_id=topic.id)\n context = {'topic': topic, 'form': form}\n return render(request, 'site/new_entry.html', context)\n\n\n@login_required\ndef edit_entry(request, entry_id):\n \"\"\"Редактирует новую запись по конкретной теме\"\"\"\n entry = Entry.objects.get(id=entry_id)\n topic = entry.topic\n\n if topic.owner != request.user:\n raise Http404\n\n if request.method != 'POST':\n form = EntryForm(instance=entry)\n else:\n form = EntryForm(instance=entry, data=request.POST)\n if form.is_valid():\n form.save()\n return redirect('topic', topic_id=topic.id)\n context = {'entry': entry, 'form': form}\n return render(request, 'site/edit_entry.html', context)\n\n","repo_name":"ofaxtab/learning_log","sub_path":"learning_log/app_learning_log/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"40130380714","text":"# -*- coding: utf-8 -*-\n\n# BCDI: tools for pre(post)-processing Bragg coherent X-ray diffraction imaging data\n# (c) 07/2017-06/2019 : CNRS UMR 7344 IM2NP\n# (c) 07/2019-05/2021 : DESY PHOTON SCIENCE\n# authors:\n# Jerome Carnis, jerome.carnis@esrf.fr\n# Clement Atlan, c.atlan@outlook.com\n\n\"\"\"Workflow for BCDI data orthogonalization of a single scan, after phase retrieval.\"\"\"\nimport logging\nfrom datetime import datetime\nfrom logging import Logger\nfrom pathlib import Path\nfrom typing import Any, Dict, Optional, Tuple\n\nimport h5py\nimport numpy as np\nimport yaml\nfrom matplotlib import pyplot as plt\n\nimport bcdi.utils.utilities as util\nfrom bcdi.constants import AXIS_TO_ARRAY\nfrom bcdi.experiment.setup import Setup\nfrom bcdi.postprocessing.analysis import create_analysis\nfrom bcdi.utils.snippets_logging import FILE_FORMATTER\n\nlogger = logging.getLogger(__name__)\n\n\ndef orthogonalize(\n scan_idx: int, prm: Dict[str, Any]\n) -> Tuple[Path, Path, Optional[Logger]]:\n \"\"\"\n Run the orthogonalization defined by the configuration parameters for a single scan.\n\n This function is meant to be run as a process in multiprocessing, although it can\n also be used as a normal function for a single scan. It assumes that the dictionary\n of parameters was validated via a ConfigChecker instance.\n\n :param scan_idx: index of the scan to be processed in prm[\"scans\"]\n :param prm: the parsed parameters\n \"\"\"\n scan_nb = prm[\"scans\"][scan_idx]\n tmpfile = Path(\n prm[\"save_dir\"][scan_idx]\n if prm[\"save_dir\"][scan_idx] is not None\n else prm[\"root_folder\"]\n ) / (f\"interpolation_run{scan_idx}_{prm['sample_name'][scan_idx]}\" f\"{scan_nb}.log\")\n\n filehandler = logging.FileHandler(tmpfile, mode=\"w\", encoding=\"utf-8\")\n filehandler.setFormatter(FILE_FORMATTER)\n logger.setLevel(logging.DEBUG)\n logger.addHandler(filehandler)\n if not prm[\"multiprocessing\"] or len(prm[\"scans\"]) == 1:\n logger.propagate = True\n\n # prm[\"sample\"] = f\"{prm['sample_name']}+{scan_nb}\"\n tmp_str = f\"Scan {scan_idx + 1}/{len(prm['scans'])}: S{scan_nb}\"\n logger.info(f\"Start {orthogonalize.__name__} at {datetime.now()}\")\n logger.info(f'\\n{\"#\" * len(tmp_str)}\\n' + tmp_str + \"\\n\" + f'{\"#\" * len(tmp_str)}')\n\n #################################\n # define the experimental setup #\n #################################\n setup = Setup(\n parameters=prm,\n scan_index=scan_idx,\n logger=logger,\n )\n\n logger.info(f\"##############\\nSetup instance\\n##############\\n{setup.params}\")\n logger.info(\n \"#################\\nDetector instance\\n#################\\n\"\n f\"{setup.detector.params}\"\n )\n\n ######################\n # start the analysis #\n ######################\n logger.info(\"###############\\nProcessing data\\n###############\")\n\n analysis = create_analysis(\n scan_index=scan_idx, parameters=prm, setup=setup, logger=logger\n )\n\n ##########################################################\n # correct the detector angles for the direct beam offset #\n ##########################################################\n if analysis.detector_angles_correction_needed:\n logger.info(\"Trying to correct detector angles using the direct beam\")\n\n if analysis.undefined_bragg_peak_but_retrievable:\n metadata = analysis.retrieve_bragg_peak()\n analysis.update_parameters({\"bragg_peak\": metadata[\"bragg_peak\"]})\n\n analysis.update_detector_angles(bragg_peak_position=prm[\"bragg_peak\"])\n\n #########################################################\n # calculate q of the Bragg peak in the laboratory frame #\n #########################################################\n q_lab = analysis.get_normalized_q_bragg_laboratory_frame\n if q_lab is None:\n raise ValueError(\"q_lab is None\")\n logger.info(\n \"Normalized diffusion vector in the laboratory frame (z*, y*, x*): \"\n f\"{[f'{val:.4f}' for _, val in enumerate(q_lab)]} (1/A)\"\n )\n logger.info(f\"Wavevector transfer: {analysis.get_norm_q_bragg:.4f} 1/A\")\n logger.info(f\"Atomic planar distance: {analysis.get_interplanar_distance:.4f} nm\")\n\n #######################\n # orthogonalize data #\n #######################\n logger.info(f\"Shape before interpolation {analysis.data.shape}\")\n analysis.interpolate_into_crystal_frame()\n\n if analysis.voxel_sizes is None:\n raise ValueError(\"voxel sizes undefined\")\n logger.info(f\"Voxel size: {analysis.voxel_sizes}\")\n\n ######################################################\n # center the object (centering based on the modulus) #\n ######################################################\n logger.info(\"Centering the crystal\")\n analysis.center_object_based_on_modulus(centering_method=\"com\")\n\n #######################################\n # optionally rotates back the crystal #\n # into the laboratory frame #\n #######################################\n if analysis.get_normalized_q_bragg_laboratory_frame is None:\n raise ValueError(\"analysis.get_normalized_q_bragg_laboratory_frame is None\")\n if prm[\"save_frame\"] in [\"laboratory\", \"lab_flat_sample\"]:\n amplitude, phase = util.rotate_crystal(\n arrays=(np.abs(analysis.data), np.angle(analysis.data)),\n axis_to_align=AXIS_TO_ARRAY[prm[\"ref_axis_q\"]],\n voxel_size=analysis.voxel_sizes,\n is_orthogonal=prm[\"is_orthogonal\"],\n reciprocal_space=False,\n reference_axis=analysis.get_normalized_q_bragg_laboratory_frame[::-1],\n debugging=(False, False),\n )\n q_bragg_in_saving_frame = q_lab\n\n if prm[\"save_frame\"] == \"lab_flat_sample\":\n if setup.q_laboratory is None:\n raise ValueError(\"setup.q_laboratory is None\")\n (amplitude, phase), q_bragg_in_saving_frame = setup.beamline.flatten_sample(\n arrays=(amplitude, phase),\n voxel_size=analysis.voxel_sizes,\n q_bragg=setup.q_laboratory / float(np.linalg.norm(setup.q_laboratory)),\n is_orthogonal=prm[\"is_orthogonal\"],\n reciprocal_space=False,\n rocking_angle=setup.rocking_angle,\n debugging=(False, False),\n )\n\n complex_object = amplitude * np.exp(1j * phase)\n\n else: # crystal frame\n complex_object = analysis.data\n q_bragg_in_saving_frame = np.asarray(\n util.rotate_vector(\n vectors=analysis.get_normalized_q_bragg_laboratory_frame[::-1],\n axis_to_align=AXIS_TO_ARRAY[prm[\"ref_axis_q\"]],\n reference_axis=analysis.get_normalized_q_bragg_laboratory_frame[::-1],\n )\n )\n\n # rescale q (it is normalized)\n if analysis.get_interplanar_distance is None:\n raise ValueError(\"analysis.get_interplanar_distanc is None\")\n q_bragg_in_saving_frame *= 2 * np.pi / (10 * analysis.get_interplanar_distance)\n\n # Save the complex object in the desired output file\n output_file_path_template = (\n f\"{prm['save_dir'][scan_idx]}/S{scan_nb}\"\n f\"_orthogonolized_reconstruction_{prm['save_frame']}\"\n )\n np.savez(\n f\"{output_file_path_template}.npz\",\n data=complex_object,\n voxel_sizes=analysis.voxel_sizes,\n q_bragg=q_bragg_in_saving_frame,\n detector=str(yaml.dump(setup.detector.params)),\n setup=str(yaml.dump(setup.params)),\n params=str(yaml.dump(prm)),\n )\n\n with h5py.File(f\"{output_file_path_template}.h5\", \"w\") as hf:\n output = hf.create_group(\"output\")\n parameters = hf.create_group(\"parameters\")\n output.create_dataset(\"data\", data=complex_object)\n output.create_dataset(\"q_bragg\", data=q_bragg_in_saving_frame)\n output.create_dataset(\"voxel_sizes\", data=analysis.voxel_sizes)\n parameters.create_dataset(\"detector\", data=str(setup.detector.params))\n parameters.create_dataset(\"setup\", data=str(setup.params))\n parameters.create_dataset(\"parameters\", data=str(prm))\n\n if len(prm[\"scans\"]) > 1:\n plt.close(\"all\")\n\n logger.removeHandler(filehandler)\n filehandler.close()\n\n return tmpfile, Path(setup.detector.savedir), logger\n","repo_name":"carnisj/bcdi","sub_path":"bcdi/postprocessing/raw_orthogonalization.py","file_name":"raw_orthogonalization.py","file_ext":"py","file_size_in_byte":8287,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"20"} +{"seq_id":"72107919729","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n#sensorData = pd.read_csv('./MnCAV/mncav-vehicle-demographics.csv')\n\nsubDF = pd.read_csv('../00-sensor-sources/MnCAV/intermediate.csv')\n\n#types = sensorData['Type'].unique()\n#tputs = []\n\n#for dataType in types:\n# tputs.append(sensorData[sensorData['Type'] == dataType]['Need (Mbps)'].sum())\n\n#subDF['Type'] = types\n#subDF['Need (Mbps)'] = tputs\nsubDF = subDF.set_index('Type')\n#subDF.to_csv('./intermediate.csv')\n\nplotAx = subDF.plot.pie(y='Need', autopct='%1.1f%%', fontsize=22, figsize=(8, 7),title=None, explode=[0.05,0.05,0.05,0.25,0.25,0.55,0.05], rotatelabels=True)\nplotAx.get_legend().remove()\nplotAx.set_ylabel(None)\nplt.tight_layout()\nplt.savefig('./data-analysis/mncav-vehicle-sensor-demographics.jpg')\nplt.close()\n","repo_name":"Jcarpenter-0/Teleop-Testbed","sub_path":"05-data-analysis/05-map-sensor-footprints.py","file_name":"05-map-sensor-footprints.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"34083502728","text":"import time\nimport logging\nimport os\nimport random\n\nimport torch\nimport numpy as np\nimport pandas as pd\n\nfrom holoclean.dataset import Dataset, Table, Source, AuxTables\nfrom holoclean.dcparser import Parser\nfrom holoclean.domain import DomainEngine\nfrom holoclean.detect import DetectEngine\nfrom holoclean.repair import RepairEngine\nfrom holoclean.evaluate import EvalEngine\nfrom holoclean.dataset.quantization import quantize_km\nfrom .utils import NULL_REPR\n\n\ngensim_logger = logging.getLogger('gensim')\ngensim_logger.setLevel(logging.WARNING)\n\n\n# Arguments for HoloClean\narguments = [\n (('-u', '--db_user'),\n {'metavar': 'DB_USER',\n 'dest': 'db_user',\n 'default': 'kamino',\n 'type': str,\n 'help': 'User for DB used to persist state.'}),\n (('-p', '--db-pwd', '--pass'),\n {'metavar': 'DB_PWD',\n 'dest': 'db_pwd',\n 'default': 'kamino',\n 'type': str,\n 'help': 'Password for DB used to persist state.'}),\n (('-h', '--db-host'),\n {'metavar': 'DB_HOST',\n 'dest': 'db_host',\n 'default': 'localhost',\n 'type': str,\n 'help': 'Host for DB used to persist state.'}),\n (('-d', '--db_name'),\n {'metavar': 'DB_NAME',\n 'dest': 'db_name',\n 'default': 'db4kamino',\n 'type': str,\n 'help': 'Name of DB used to persist state.'}),\n (('-t', '--threads'),\n {'metavar': 'THREADS',\n 'dest': 'threads',\n 'default': 20,\n 'type': int,\n 'help': 'How many threads to use for parallel execution. If <= 1, then no pool workers are used.'}),\n (('-dbt', '--timeout'),\n {'metavar': 'TIMEOUT',\n 'dest': 'timeout',\n 'default': 60000,\n 'type': int,\n 'help': 'Timeout for expensive featurization queries.'}),\n (('-s', '--seed'),\n {'metavar': 'SEED',\n 'dest': 'seed',\n 'default': 45,\n 'type': int,\n 'help': 'The seed to be used for torch.'}),\n (('-ls', '--layer_sizes'),\n {'metavar': 'LAYER_SIZES',\n 'dest': 'layer_sizes',\n 'default': [1],\n 'type': list,\n 'help': 'List of layer sizes of the final FC layers. Last layer must have output size of 1. For example for a hidden layer of size 200 one can specify [200,1].'}),\n (('-l', '--learning-rate'),\n {'metavar': 'LEARNING_RATE',\n 'dest': 'learning_rate',\n 'default': 0.001,\n 'type': float,\n 'help': 'The learning rate used during training.'}),\n (('-o', '--optimizer'),\n {'metavar': 'OPTIMIZER',\n 'dest': 'optimizer',\n 'default': 'adam',\n 'type': str,\n 'help': 'Optimizer used for learning.'}),\n (('-e', '--epochs'),\n {'metavar': 'LEARNING_EPOCHS',\n 'dest': 'epochs',\n 'default': 20,\n 'type': float,\n 'help': 'Number of epochs used for training.'}),\n (('-w', '--weight_decay'),\n {'metavar': 'WEIGHT_DECAY',\n 'dest': 'weight_decay',\n 'default': 0.01,\n 'type': float,\n 'help': 'Weight decay across iterations.'}),\n (('-m', '--momentum'),\n {'metavar': 'MOMENTUM',\n 'dest': 'momentum',\n 'default': 0.0,\n 'type': float,\n 'help': 'Momentum for SGD.'}),\n (('-b', '--batch-size'),\n {'metavar': 'BATCH_SIZE',\n 'dest': 'batch_size',\n 'default': 1,\n 'type': int,\n 'help': 'The batch size during training.'}),\n (('-wlt', '--weak-label-thresh'),\n {'metavar': 'WEAK_LABEL_THRESH',\n 'dest': 'weak_label_thresh',\n 'default': 0.90,\n 'type': float,\n 'help': 'Threshold of posterior probability to assign weak labels.'}),\n (('-dt1', '--domain_thresh_1'),\n {'metavar': 'DOMAIN_THRESH_1',\n 'dest': 'domain_thresh_1',\n 'default': 0.1,\n 'type': float,\n 'help': 'Minimum co-occurrence probability threshold required for domain values in the first domain pruning stage. Between 0 and 1.'}),\n (('-dt2', '--domain-thresh-2'),\n {'metavar': 'DOMAIN_THRESH_2',\n 'dest': 'domain_thresh_2',\n 'default': 0,\n 'type': float,\n 'help': 'Threshold of posterior probability required for values to be included in the final domain in the second domain pruning stage. Between 0 and 1.'}),\n (('-md', '--max-domain'),\n {'metavar': 'MAX_DOMAIN',\n 'dest': 'max_domain',\n 'default': 1000000,\n 'type': int,\n 'help': 'Maximum number of values to include in the domain for a given cell.'}),\n (('-cs', '--cor-strength'),\n {'metavar': 'COR_STRENGTH',\n 'dest': 'cor_strength',\n 'default': 0.05,\n 'type': float,\n 'help': 'Correlation threshold (absolute) when selecting correlated attributes for domain pruning.'}),\n (('-cs', '--nb-cor-strength'),\n {'metavar': 'NB_COR_STRENGTH',\n 'dest': 'nb_cor_strength',\n 'default': 0.3,\n 'type': float,\n 'help': 'Correlation threshold for correlated attributes when using NaiveBayes estimator.'}),\n (('-fn', '--feature-norm'),\n {'metavar': 'FEATURE_NORM',\n 'dest': 'feature_norm',\n 'default': False,\n 'type': bool,\n 'help': 'Normalize the features before training.'}),\n (('-wn', '--weight_norm'),\n {'metavar': 'WEIGHT_NORM',\n 'dest': 'weight_norm',\n 'default': False,\n 'type': bool,\n 'help': 'Normalize the weights after every forward pass during training.'}),\n (('-et', '--estimator_type'),\n {'metavar': 'ESTIMATOR_TYPE',\n 'dest': 'estimator_type',\n 'default': 'NaiveBayes',\n 'type': str,\n 'help': 'Which weak labelling and domain generation estimator to use. One of {NaiveBayes, Logistic, TupleEmbedding}.'}),\n (('-ee', '--estimator_epochs'),\n {'metavar': 'ESTIMATOR_EPOCHS',\n 'dest': 'estimator_epochs',\n 'default': 10,\n 'type': int,\n 'help': 'Number of epochs to run the weak labelling and domain generation estimator.'}),\n (('-ebs', '--estimator_batch_size'),\n {'metavar': 'ESTIMATOR_BATCH_SIZE',\n 'dest': 'estimator_batch_size',\n 'default': 32,\n 'type': int,\n 'help': 'Size of batch used in SGD in the weak labelling and domain generation estimator.'}),\n (('-ees', '--estimator_embedding_size'),\n {'metavar': 'ESTIMATOR_EMBEDDING_SIZE',\n 'dest': 'estimator_embedding_size',\n 'default': 10,\n 'type': int,\n 'help': 'If embeding_type = TupleEmbedding, uses this for the embedding size of the learned embedding vectors.'}),\n (('-ta', '--train_attrs'),\n {'metavar': 'TRAIN_ATTRS',\n 'dest': 'train_attrs',\n 'default': None,\n 'type': list,\n 'help': 'List of attributes to train and infer on. If None, train and infer on all columns. For example passing a list of one column allows one to train HoloClean on one column.'}),\n (('-im', '--infer_mode'),\n {'metavar': 'INFER_MODE',\n 'dest': 'infer_mode',\n 'default': 'dk',\n 'type': str,\n 'help': 'Infer on only possibly erroneous (DK) cells or all cells. One of {dk, all}.'}),\n (('-dp', '--privacy'),\n {'metavar': 'PRIVACY',\n 'dest': 'privacy',\n 'default': False,\n 'type': bool,\n 'help': 'Synthetic data under differential privacy.'}),\n]\n\n# Flags for Holoclean mode\nflags = [\n (tuple(['--verbose']),\n {'default': False,\n 'dest': 'verbose',\n 'action': 'store_true',\n 'help': 'verbose'}),\n (tuple(['--bias']),\n {'default': False,\n 'dest': 'bias',\n 'action': 'store_true',\n 'help': 'Use bias term'}),\n (tuple(['--printfw']),\n {'default': False,\n 'dest': 'print_fw',\n 'action': 'store_true',\n 'help': 'print the weights of featurizers'}),\n (tuple(['--debug-mode']),\n {'default': False,\n 'dest': 'debug_mode',\n 'action': 'store_true',\n 'help': 'dump a bunch of debug information to debug\\/'}),\n]\n\n\nclass HoloClean:\n \"\"\"\n Main entry point for HoloClean.\n It creates a HoloClean Data Engine\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Constructor for Holoclean\n :param kwargs: arguments for HoloClean\n \"\"\"\n\n # Initialize default execution arguments\n arg_defaults = {}\n for arg, opts in arguments:\n if 'directory' in arg[0]:\n arg_defaults['directory'] = opts['default']\n else:\n arg_defaults[opts['dest']] = opts['default']\n\n # Initialize default execution flags\n for arg, opts in flags:\n arg_defaults[opts['dest']] = opts['default']\n\n # check env vars\n for arg, opts in arguments:\n # if env var is set use that\n if opts[\"metavar\"] and opts[\"metavar\"] in os.environ.keys():\n logging.debug(\n \"Overriding {} with env varible {} set to {}\".format(\n opts['dest'],\n opts[\"metavar\"],\n os.environ[opts[\"metavar\"]])\n )\n arg_defaults[opts['dest']] = os.environ[opts[\"metavar\"]]\n\n # Override defaults with manual flags\n for key in kwargs:\n arg_defaults[key] = kwargs[key]\n\n # Initialize additional arguments\n for (arg, default) in arg_defaults.items():\n setattr(self, arg, kwargs.get(arg, default))\n\n # Init empty session collection\n self.session = Session(arg_defaults)\n\n\nclass Session:\n \"\"\"\n Session class controls the entire pipeline of HC\n \"\"\"\n\n def __init__(self, env, name=\"session\"):\n \"\"\"\n Constructor for Holoclean session\n :param env: Holoclean environment\n :param name: Name for the Holoclean session\n \"\"\"\n # use DEBUG logging level if verbose enabled\n if env['verbose']:\n root_logger.setLevel(logging.DEBUG)\n gensim_logger.setLevel(logging.DEBUG)\n\n logging.debug('initiating session with parameters: %s', env)\n\n # Initialize random seeds.\n random.seed(env['seed'])\n torch.manual_seed(env['seed'])\n np.random.seed(seed=env['seed'])\n\n # Initialize members\n self.name = name\n self.env = env\n self.ds = Dataset(name, env)\n self.dc_parser = Parser(env, self.ds)\n self.domain_engine = DomainEngine(env, self.ds)\n self.detect_engine = DetectEngine(env, self.ds)\n self.repair_engine = RepairEngine(env, self.ds)\n self.eval_engine = EvalEngine(env, self.ds)\n\n def load_data(self, name, fpath, na_values=None, entity_col=None, src_col=None,\n exclude_attr_cols=None, numerical_attrs=None):\n \"\"\"\n load_data takes the filepath to a CSV file to load as the initial dataset.\n\n :param name: (str) name to initialize dataset with.\n :param fpath: (str) filepath to CSV file.\n :param na_values: (str) value that identifies a NULL value\n :param entity_col: (st) column containing the unique\n identifier/ID of an entity. For fusion tasks, rows with\n the same ID will be fused together in the output.\n If None, assumes every row is a unique entity.\n :param src_col: (str) if not None, for fusion tasks\n specifies the column containing the source for each \"mention\" of an\n entity.\n :param exclude_attr_cols: (str list)\n :param numerical_attrs: (str list)\n \"\"\"\n status, load_time = self.ds.load_data(name,\n fpath,\n na_values=na_values,\n entity_col=entity_col,\n src_col=src_col,\n exclude_attr_cols=exclude_attr_cols,\n numerical_attrs=numerical_attrs)\n logging.info(status)\n logging.debug('Time to load dataset: %.2f secs', load_time)\n\n def load_dcs(self, fpath):\n \"\"\"\n load_dcs ingests the Denial Constraints for initialized dataset.\n\n :param fpath: filepath to TXT file where each line contains one denial constraint.\n \"\"\"\n status, load_time = self.dc_parser.load_denial_constraints(fpath)\n logging.info(status)\n logging.debug('Time to load dirty data: %.2f secs', load_time)\n\n def get_dcs(self):\n return self.dc_parser.get_dcs()\n\n def detect_errors(self, detect_list):\n status, detect_time = self.detect_engine.detect_errors(detect_list)\n logging.info(status)\n logging.debug('Time to detect errors: %.2f secs', detect_time)\n\n def disable_quantize(self):\n self.do_quantization = False\n self.ds.do_quantization = False\n self.domain_engine.do_quantization = False\n\n def quantize_numericals(self, num_attr_groups_bins):\n \"\"\"\n :param num_attr_groups_bins: list[tuple] where each tuple consists of\n (# of bins, list[str]) where the list[str] is a group of attribues to be\n treated as numerical.\n \"\"\"\n self.do_quantization = True\n self.ds.do_quantization = True\n self.domain_engine.do_quantization = True\n\n status, quantize_time, quantized_data = \\\n quantize_km(self.env, self.ds.get_raw_data(), num_attr_groups_bins)\n\n logging.info(status)\n logging.debug('Time to quantize the dataset: %.2f secs' % quantize_time)\n\n self.load_quantized_data(quantized_data)\n\n\n return quantized_data\n\n def load_quantized_data(self, df):\n tic = time.time()\n name = self.ds.raw_data.name + '_quantized'\n self.ds.quantized_data = Table(name, Source.DF, df=df)\n\n # Re-store to DB, ensuring numerical values are stored as floats.\n df_correct_type = df.copy()\n for attr in self.ds.numerical_attrs:\n df_correct_type.loc[df_correct_type[attr] == NULL_REPR, attr] = np.nan\n df_correct_type[attr] = df_correct_type[attr].astype(float)\n df_correct_type.to_sql(name, self.ds.engine.engine, if_exists='replace', index=False,\n index_label=None)\n\n for attr in self.ds.quantized_data.get_attributes():\n self.ds.quantized_data.create_db_index(self.ds.engine, [attr])\n logging.debug('Time to load quantized dataset: %.2f secs' % (time.time() - tic))\n\n def generate_domain(self):\n status, domain_time = self.domain_engine.setup()\n logging.info(status)\n logging.debug('Time to generate the domain: %.2f secs', domain_time)\n\n def run_estimator(self):\n \"\"\"\n Uses estimator to weak label and prune domain.\n \"\"\"\n self.domain_engine.run_estimator()\n\n def repair_errors(self, featurizers):\n return self._repair_errors(featurizers)\n\n def repair_validate_errors(self, featurizers, fpath, tid_col, attr_col,\n val_col, validate_period, na_values=None):\n return self._repair_errors(featurizers, fpath, tid_col, attr_col,\n val_col, na_values, validate_period)\n\n def _repair_errors(self, featurizers, fpath=None,\n tid_col=None, attr_col=None, val_col=None, na_values=None,\n validate_period=None):\n \"\"\"\n Repair errors and optionally runs validation set per epoch.\n\n Must specify the following parameters if validation required:\n\n :param fpath: (str) filepath to test set (ground truth) CSV file.\n :param tid_col: (str) column in CSV that corresponds to the TID.\n :param attr_col: (str) column in CSV that corresponds to the attribute.\n :param val_col: (str) column in CSV that corresponds to correct value\n for the current TID and attribute (i.e. cell).\n :param na_values: (Any) how na_values are represented in the data.\n :param validate_period: (int) perform validation every nth epoch.\n \"\"\"\n status, feat_time = self.repair_engine.setup_featurized_ds(featurizers)\n logging.info(status)\n logging.debug('Time to featurize data: %.2f secs', feat_time)\n status, setup_time = self.repair_engine.setup_repair_model()\n logging.info(status)\n logging.debug('Time to setup repair model: %.2f secs', feat_time)\n\n # If validation fpath provided, fit and validate\n if fpath is None:\n status, fit_time = self.repair_engine.fit_repair_model()\n else:\n # Set up validation set\n name = self.ds.raw_data.name + '_clean'\n status, load_time = self.eval_engine.load_data(name, fpath,\n tid_col, attr_col, val_col, na_values=na_values)\n logging.info(status)\n logging.debug('Time to evaluate repairs: %.2f secs', load_time)\n\n status, fit_time = self.repair_engine.fit_validate_repair_model(self.eval_engine,\n validate_period)\n\n logging.info(status)\n logging.debug('Time to fit repair model: %.2f secs', fit_time)\n status, infer_time = self.repair_engine.infer_repairs()\n logging.info(status)\n logging.debug('Time to infer correct cell values: %.2f secs', infer_time)\n status, time = self.ds.get_inferred_values()\n logging.info(status)\n logging.debug('Time to collect inferred values: %.2f secs', time)\n status, time = self.ds.get_repaired_dataset()\n logging.info(status)\n logging.debug('Time to store repaired dataset: %.2f secs', time)\n if self.env['print_fw']:\n status, time = self.repair_engine.get_featurizer_weights()\n logging.info(status)\n logging.debug('Time to store featurizer weights: %.2f secs', time)\n return status\n\n def evaluate(self, fpath, tid_col, attr_col, val_col, na_values=None):\n \"\"\"\n evaluate generates an evaluation report with metrics (e.g. precision,\n recall) given a test set.\n\n :param fpath: (str) filepath to test set (ground truth) CSV file.\n :param tid_col: (str) column in CSV that corresponds to the TID.\n :param attr_col: (str) column in CSV that corresponds to the attribute.\n :param val_col: (str) column in CSV that corresponds to correct value\n for the current TID and attribute (i.e. cell).\n :param na_values: (Any) how na_values are represented in the data.\n\n Returns an EvalReport named tuple containing the experiment results.\n \"\"\"\n name = self.ds.raw_data.name + '_clean'\n status, load_time = self.eval_engine.load_data(name, fpath, tid_col, attr_col, val_col, na_values=na_values)\n logging.info(status)\n logging.debug('Time to evaluate repairs: %.2f secs', load_time)\n status, report_time, eval_report = self.eval_engine.eval_report()\n logging.info(status)\n logging.debug('Time to generate report: %.2f secs', report_time)\n return eval_report\n\n def get_predictions(self):\n \"\"\"\n Returns a dataframe with 3 columns:\n - tid, attribute, inferred_val, proba\n \"\"\"\n\n query = \"\"\"\n SELECT\n _tid_, attribute, inferred_val, prob\n FROM {dom}\n INNER JOIN {inf_vals} USING(_vid_)\n \"\"\".format(inf_vals=AuxTables.inf_values_idx.name,\n dom=AuxTables.cell_domain.name)\n res = self.ds.engine.execute_query(query)\n df_preds = pd.DataFrame(res,\n columns=['tid', 'attribute', 'inferred_val', 'proba'],\n dtype=str)\n return df_preds\n","repo_name":"mshubhankar/DP-DataGeneration-MissingData","sub_path":"kamino/holoclean/holoclean.py","file_name":"holoclean.py","file_ext":"py","file_size_in_byte":19516,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"5663139029","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('registrar', '0001_initial'),\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Publication',\n fields=[\n ('publication_id', models.AutoField(serialize=False, primary_key=True)),\n ('title', models.CharField(max_length=127, null=True)),\n ('description', models.TextField(null=True)),\n ('published_date', models.DateField(auto_now=True, null=True)),\n ('file', models.FileField(upload_to='uploads', null=True)),\n ('author', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ('reviews', models.ManyToManyField(to='registrar.PeerReview')),\n ],\n options={\n 'db_table': 'at_publications',\n },\n ),\n ]\n","repo_name":"AcademicsToday/academicstoday-django","sub_path":"academicstoday_project/publisher/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":193,"dataset":"github-code","pt":"20"} +{"seq_id":"26198822208","text":"#!/usr/bin/env python3\n\nfrom math import sqrt\n\n\ndef sieve_of_eratosthenes(n):\n \"\"\"\n Implements The Sieve of Eratosthenes, which finds prime numbers up to given number n. Complexity: O(n*log(log(n)))\n\n :param n: upper bound\n :return: list (sieve) of booleans where sieve[i] is True iff i is composed number\n \"\"\"\n sieve = [False] * n\n sieve[0] = sieve[1] = True\n for i in range(2, int(sqrt(n)) + 1):\n if sieve[i]:\n continue\n for j in range(2 * i, n, i):\n sieve[j] = True\n return sieve\n\n\ndef print_sieve(sieve):\n for i in range(len(sieve)):\n print('{:d} is {:s}'.format(i, 'composed' if sieve[i] else 'prime'))\n\n\nif __name__ == '__main__':\n\n composed = sieve_of_eratosthenes(20)\n print_sieve(composed)\n","repo_name":"matyama/zal-tutorials","sub_path":"solution/primes.py","file_name":"primes.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"39944482979","text":"#!/usr/bin/env python\n\nimport roslib\nroslib.load_manifest('kcl_sbc')\nimport rospy \nimport numpy as np\nfrom std_msgs.msg import Float64\nimport tf\nfrom tf import TransformListener\nfrom sensor_msgs.msg import JointState\nfrom kcl_sbc.msg import SBC_Output, PressureControl\nfrom sr_grasp_msgs.msg import KCL_ContactStateStamped\nfrom geometry_msgs.msg import PointStamped, Point\n\n\n\n\nclass Collector():\n def __init__(self):\n rospy.init_node('collector', anonymous = False) \n self.lis=TransformListener();\n self.data_out=SBC_Output();\n rospy.Subscriber(\"/joint_states\", JointState, self.j_callback)\n rospy.Subscriber(\"/finger1/ContactState\", KCL_ContactStateStamped, self.f_callback1)\n rospy.Subscriber(\"/finger2/ContactState\", KCL_ContactStateStamped, self.f_callback2)\n rospy.Subscriber(\"/pressure\", PressureControl, self.p_callback) \n rospy.Subscriber(\"/prob_fail\", Float64, self.prob_callback)\n self.publisher=rospy.Publisher(\"sbc_data\", SBC_Output)\n self.point1=PointStamped()\n self.point2=PointStamped()\n self.rate=rospy.Rate(20);\n\n def getParams(self): \n self.data_out.D_Gain=rospy.get_param(\"/bhand_pid/d_gain\") \n self.data_out.F_ref_pid=rospy.get_param(\"/bhand_pid/f_ref\")\n self.data_out.I_Gain=rospy.get_param(\"/bhand_pid/i_gain\")\n self.data_out.P_Gain=rospy.get_param(\"/bhand_pid/p_gain\")\n self.data_out.freq=rospy.get_param(\"/pressure_reg/frequency\")\n self.data_out.Beta=rospy.get_param(\"/bhand_sbc/beta\")\n self.data_out.Delta=rospy.get_param(\"/bhand_sbc/delta\")\n self.data_out.Eta=rospy.get_param(\"/bhand_sbc/eta\")\n self.data_out.F_ref_sbc=rospy.get_param(\"/bhand_sbc/f_ref\")\n \n def j_callback(self,data):\n self.joints=data;\n self.data_out.effort1=data.effort[1]\n self.data_out.effort2=data.effort[0]\n \n def f_callback1(self,data): \n self.data_out.Fn1=data.Fnormal; \n ft=np.array([data.tangential_force.x,data.tangential_force.y,data.tangential_force.z])\n self.data_out.Ft1=np.sqrt(ft.dot(ft));\n\n self.point1=PointStamped();\n self.point1.header=data.header;\n self.point1.point=data.contact_position;\n \n \n def f_callback2(self,data):\n self.data_out.Fn2=data.Fnormal;\n ft=np.array([data.tangential_force.x,data.tangential_force.y,data.tangential_force.z])\n self.data_out.Ft2=np.sqrt(ft.dot(ft)); \n \n self.point2=PointStamped();\n self.point2.header=data.header;\n self.point2.point=data.contact_position;\n\n \n def p_callback(self,data):\n self.data_out.p_demand=data.p_demand;\n self.data_out.p_measure=data.p_measure;\n def prob_callback(self,data):\n self.data_out.Pfailure=data.data;\n \n def transform_it(self,data):\n if(data.header.frame_id):\n #data.header.stamp=rospy.Time.now();\n if(self.lis.canTransform(\"base_link\",data.header.frame_id,data.header.stamp) or True):\n #print(rospy.Time.now()) \n data.header.stamp=data.header.stamp-rospy.Duration(0.02) \n #point=self.lis.transformPoint(\"base_link\", data)\n try: \n #self.lis.waitForTransform(\"base_link\", data.header.frame_id, data.header.stamp, rospy.Duration(1))\n # print(rospy.Time.now()) \n self.point=self.lis.transformPoint(\"base_link\", data)\n return True\n except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):\n rospy.logwarn(\"TF problem 2\") \n pass\n else:\n rospy.logwarn(\"Cannot Transform\")\n else:\n print(data.header.frame_id) \n return False\n \n def get_distance(self,point1,point2): \n d=np.array([point1.x-point2.x, point1.y-point2.y, point1.z-point2.z])\n return np.sqrt(d.dot(d));\n \n \n \n def send_it(self):\n while not rospy.is_shutdown(): \n self.data_out.header.stamp=rospy.Time.now();\n self.getParams() \n \n got_it=self.transform_it(self.point1);\n if(got_it):\n self.data_out.contact1=self.point.point\n got_it=self.transform_it(self.point2);\n if(got_it):\n self.data_out.contact2=self.point.point \n self.data_out.distance=self.get_distance(self.data_out.contact1,self.data_out.contact2)*100\n self.publisher.publish(self.data_out);\n self.rate.sleep(); \n\n\nif __name__ == \"__main__\":\n colector=Collector() \n# rospy.spin(); \n print(\"Joao\") \n rospy.sleep(1)\n colector.send_it(); \n","repo_name":"hoppss/kcl_sbc","sub_path":"scripts/kcl_sbc/data_collector.py","file_name":"data_collector.py","file_ext":"py","file_size_in_byte":4957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"20"} +{"seq_id":"33201266202","text":"from django.contrib.admin.views.decorators import staff_member_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.urls import reverse_lazy\nfrom django.utils.decorators import method_decorator\nfrom django.views import generic as views\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\nfrom django.views.generic import edit\n\nfrom WellMaintained.accounts.models import Profile\nfrom WellMaintained.common.decorators import allow_groups\nfrom WellMaintained.vehicles.forms import CarCreateForm, CarEditForm, VanEditForm, HireCarForm, \\\n VehicleReturnForm\nfrom WellMaintained.vehicles.models import Car\nfrom WellMaintained.vehicles.utils import get_vehicle_by_reg, get_profile_by_pk\n\n\n@login_required\n@staff_member_required\ndef add_car(request):\n if request.method == 'GET':\n form = CarCreateForm()\n else:\n form = CarCreateForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('index')\n\n context = {\n 'form': form,\n }\n\n return render(request, 'vehicle/car-create.html', context)\n\n\n@login_required\ndef vehicle_details_view(request, reg_number):\n vehicle = get_vehicle_by_reg(reg_number)\n context = {\n 'vehicle': vehicle,\n }\n\n return render(request, 'vehicle/car-details.html', context)\n\n\n@login_required\n@staff_member_required\ndef vehicle_edit_view(request, reg_number):\n vehicle = get_vehicle_by_reg(reg_number)\n if isinstance(vehicle, Car):\n get_form = CarEditForm(instance=vehicle)\n post_form = CarEditForm(request.POST, instance=vehicle)\n else:\n get_form = VanEditForm(instance=vehicle)\n post_form = VanEditForm(request.POST, instance=vehicle)\n\n if request.method == 'GET':\n form = get_form\n else:\n form = post_form\n if form.is_valid():\n form.save()\n return redirect('detail vehicle', reg_number=reg_number)\n\n context = {\n 'form': form,\n 'vehicle': vehicle,\n }\n\n return render(request, 'vehicle/car-edit.html', context)\n\n\n@login_required\ndef vehicle_hire_view(request, reg_number):\n vehicle = get_vehicle_by_reg(reg_number)\n profile = get_profile_by_pk(request.user.id)\n\n if request.method == 'GET':\n form = HireCarForm(instance=profile)\n else:\n form = HireCarForm(request.POST, instance=profile)\n if form.is_valid():\n profile.hired_cars.add(Car.objects.get(pk=vehicle.pk))\n return redirect('index')\n\n context = {\n 'form': form,\n 'vehicle': vehicle,\n 'accounts': profile,\n }\n\n return render(request, 'vehicle/vehicle-hire.html', context)\n\n\n@login_required\ndef vehicle_return_view(request, reg_number):\n vehicle = get_vehicle_by_reg(reg_number)\n profile = get_profile_by_pk(request.user.id)\n\n get_form = VehicleReturnForm(instance=vehicle)\n post_form = VehicleReturnForm(request.POST, instance=vehicle)\n\n if request.method == 'GET':\n form = get_form\n else:\n form = post_form\n if form.is_valid():\n form.save()\n profile.hired_cars.remove(Car.objects.filter(id=vehicle.id).get())\n return redirect('hired cars accounts', pk=request.user.pk)\n\n context = {\n 'form': form,\n 'vehicle': vehicle,\n }\n\n return render(request, 'vehicle/vehicle-return.html', context)\n\n\nclass YourVehicles(LoginRequiredMixin, views.ListView):\n template_name = 'vehicle/your_vehicles.html'\n\n def get_context_data(self, *, object_list=None, **kwargs):\n profile = Profile.objects.filter(id=self.kwargs['pk'])\n\n\nclass DeleteVehicleView(LoginRequiredMixin, edit.DeleteView):\n model = Car\n success_url = reverse_lazy('index')\n template_name = \"vehicle/car-delete.html\"\n\n @method_decorator(staff_member_required)\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args,**kwargs)\n","repo_name":"vlad-iliev/WMproject","sub_path":"WellMaintained/vehicles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3959,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"7982255190","text":"\nimport math\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import DataLoader\nimport torchvision\n\n# To filter mnist digits: https://stackoverflow.com/questions/57913825/how-to-select-specific-labels-in-pytorch-mnist-dataset\nclass YourSampler(torch.utils.data.sampler.Sampler):\n def __init__(self, mask, data_source):\n self.mask = mask\n self.data_source = data_source\n\n def __iter__(self):\n return iter([i.item() for i in torch.nonzero(mask)])\n\n def __len__(self):\n return len(self.data_source)\n\n# run this to convert mnist 4/9 labels to 1 or 0\ndef convert_bool(y):\n return (y == 9).float()\n \n\n# Load different datasets based on args.\ndef load_datasets(args):\n use_cuda = True\n kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}\n\n if(args[\"dataset\"] == \"mnist\"):\n mnist_train = datasets.MNIST('data', train=True, download=True,\n transform = torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize((0.1307,),(0.3081,)),\n ]))\n\n\n mnist_validation = datasets.MNIST('data', train=False, download=True, \n transform = torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize((0.1307,),(0.3081,)),\n ]))\n\n mnist_test = datasets.MNIST('data', train=False, download=True, \n transform = torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize((0.1307,),(0.3081,)),\n ]))\n\n\n bs = 128\n train_dl = DataLoader(mnist_train, batch_size=bs, shuffle=True, **kwargs)\n\n\n validation_dl = DataLoader(mnist_validation, batch_size = 100, shuffle=True, **kwargs)\n\n test_dl = DataLoader(mnist_test, batch_size = 100, shuffle=True, **kwargs)\n\n dataiter = iter(train_dl)\n train_x, train_y = dataiter.next()\n train_x = nn.Upsample(size=(32, 32))(train_x)\n\n\n\n dataiter = iter(validation_dl)\n validation_x, validation_y = dataiter.next()\n validation_x = nn.Upsample(size=(32, 32))(validation_x)\n\n\n dataiter = iter(test_dl)\n test_x, test_y = dataiter.next()\n test_x = nn.Upsample(size=(32, 32))(test_x)\n\n\n elif(args[\"dataset\"] == \"mnist-49\"):\n\n mnist_train = datasets.MNIST('data', train=True, download=True,\n transform = torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize((0.1307,),(0.3081,)),\n ]))\n\n bs = 128\n train_dl = DataLoader(mnist_train, batch_size=len(mnist_train))\n dataiter = iter(train_dl)\n train_x, train_y = dataiter.next()\n train_x = nn.Upsample(size=(32, 32))(train_x)\n filted_indices = np.logical_or(train_y == 4, train_y == 9)\n train_y = train_y[filted_indices]\n train_x = train_x[filted_indices]\n sampled_indics = np.random.randint(0, len(train_x), size = bs)\n train_y = convert_bool(train_y[sampled_indics]).unsqueeze(dim=-1)\n train_x = train_x[sampled_indics]\n\n # Validation and Test\n mnist_validation_test = datasets.MNIST('data', train=False, download=True,\n transform = torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize((0.1307,),(0.3081,)),\n ]))\n\n bs = 100\n validation_test_dl = DataLoader(mnist_train, batch_size=len(mnist_validation_test))\n dataiter = iter(validation_test_dl)\n validation_test_x, validation_test_y = dataiter.next()\n validation_test_x = nn.Upsample(size=(32, 32))(validation_test_x)\n\n # Validation\n filted_indices = np.logical_or(validation_test_y == 4, validation_test_y == 9)\n validation_test_y = validation_test_y[filted_indices]\n validation_test_x = validation_test_x[filted_indices]\n validation_sampled_indics = np.random.randint(0, len(validation_test_x), size = bs)\n validation_y = convert_bool(validation_test_y[validation_sampled_indics]).unsqueeze(dim=-1)\n validation_x = validation_test_x[validation_sampled_indics]\n\n\n\n # Test\n filted_indices = np.logical_or(validation_test_y == 4, validation_test_y == 9)\n test_sampled_indics = np.random.randint(0, len(validation_test_x), size = bs)\n test_y = convert_bool(validation_test_y[test_sampled_indics]).unsqueeze(dim=-1)\n test_x = validation_test_x[test_sampled_indics]\n\n return train_x.view(-1, 32*32).to(device), validation_x.view(-1, 32*32).to(device), test_x.view(-1, 32*32).to(device), train_y.to(device), validation_y.to(device), test_y.to(device)\n\n\ndef accuracy(output, labels):\n\n # From programming assignment 4.\n predictions = output.max(1)[1].type_as(labels)\n correct = predictions.eq(labels).double()\n correct = correct.sum()\n return correct / len(labels)\n\ndef accuracy(output, labels, binary = False):\n\n # From programming assignment 4.\n if binary:\n return torch.mean(((output > 0.5) == labels.bool()).float())\n predictions = output.max(1)[1].type_as(labels)\n correct = predictions.eq(labels).double()\n correct = correct.sum()\n return correct / len(labels)\n\ndef train(model, args):\n # model is the model we are going to train.\n # args is a dictionary of all the hyperparameters.\n\n train_losses = []\n valid_losses = []\n valid_accs = []\n # Load optimizer, and loss.\n #optimizer = args['optimizer']() not using function pointer\n #loss = args['loss']()\n\n\n # train_x, validation_x, test_x, train_y, validation_y, test_y = load_datasets(args)\n binary = False # for accuracy function\n if args[\"optimizer\"] == \"adam\":\n optimizer = torch.optim.Adam(model.parameters(), lr=args[\"lr\"])\n\n if args[\"criterion\"] == \"cross_entropy\":\n loss = nn.CrossEntropyLoss()\n \n if args[\"criterion\"] == \"bce\":\n loss = nn.BCELoss()\n binary = True\n\n model = model.to(device=device)\n for epoch in range(args[\"epochs\"]):\n model.train()\n optimizer.zero_grad()\n output = model(train_x)\n\n loss_train = loss(output, train_y)\n acc_train = accuracy(output, train_y, binary)\n loss_train.backward()\n optimizer.step()\n\n model.eval()\n output = model(validation_x)\n\n\n # calculate validation loss and accuracy.\n loss_val = loss(output, validation_y)\n acc_val = accuracy(output, validation_y, binary)\n\n print(f\"Epoch: {epoch}, Train Loss {round(loss_train.item(), 3)}, Train Acc: {round(acc_train.item(), 3)}, Valid Loss: {round(loss_val.item(), 3)}, Valid Acc: {round(acc_val.item(), 3)}\")\n\n\n\nargs = {\n \"optimizer\": \"adam\",\n \"dataset\": \"mnist\",\n \"criterion\": \"cross entropy\",\n \"epochs\": 100\n}\n\ntrain_x, validation_x, test_x, train_y, validation_y, test_y = load_datasets(args)\n\nmodel = MLNClassifier(32*32, 10)\ntrain(model, args)\n\n","repo_name":"zw123han/DendriticNeuralNetwork","sub_path":"src/training_loop.py","file_name":"training_loop.py","file_ext":"py","file_size_in_byte":7127,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"32235580412","text":"from modules_definition import get_modules\r\nimport dtlpy as dl\r\nimport pathlib\r\n\r\n\r\ndef deploy_package(project, new_package_deployment):\r\n package_name = \"add-classification\"\r\n ###############\r\n # package #\r\n ###############\r\n src_path = str(pathlib.Path('.').resolve())\r\n\r\n if new_package_deployment:\r\n package = project.packages.push(package_name=package_name,\r\n modules=get_modules(),\r\n src_path=src_path)\r\n print('New Package has been deployed')\r\n else:\r\n package = project.packages.get(package_name=package_name)\r\n print('Got last package')\r\n return package\r\n\r\n\r\ndef deploy_service(package):\r\n project = package.project\r\n ###############\r\n # bot #\r\n ###############\r\n\r\n try:\r\n bot = project.bots.get(bot_name=package.name)\r\n print(\"Package {} Bot {} {} has been gotten\".format(package.name, bot.name, bot.email))\r\n except dl.exceptions.NotFound:\r\n bot = project.bots.create(name=package.name)\r\n print(\"New bot has been created: {} email: {}\".format(bot.name, bot.email))\r\n\r\n ###########\r\n # service #\r\n ###########\r\n\r\n try:\r\n service = package.services.get(service_name=package.name)\r\n print(\"Service has been gotten: \", service.name)\r\n except dl.exceptions.NotFound:\r\n runtime = dl.KubernetesRuntime(num_replicas=1,\r\n concurrency=10,\r\n autoscaler=dl.KubernetesRabbitmqAutoscaler(min_replicas=0,\r\n max_replicas=1,\r\n queue_length=10))\r\n\r\n service = package.services.deploy(service_name=package.name,\r\n module_name=package.name,\r\n runtime=runtime)\r\n filters = dl.Filters(field='datasetId', values='dataset id')\r\n trigger=service.triggers.create(\r\n name='add-classification',\r\n function_name='add_classification',\r\n resource=dl.TriggerResource.ITEM,\r\n actions=[dl.TriggerAction.CREATED],\r\n filters=filters\r\n )\r\n print(\"New trigger has been created: \", trigger.name)\r\n\r\n\r\n print(\"New service has been created: \", service.name)\r\n\r\n print(\"package.version: \", package.version)\r\n print(\"service.package_revision: \", service.package_revision)\r\n print(\"service.runtime.concurrency: \", service.runtime.concurrency)\r\n service.runtime.autoscaler.print()\r\n\r\n if package.version != service.package_revision:\r\n service.package_revision = package.version\r\n service.update()\r\n print(\"service.package_revision has been updated: \", service.package_revision)\r\n\r\n else:\r\n print('No need to update service.package_revision')\r\n\r\n\r\ndef main(project_name):\r\n if dl.token_expired():\r\n dl.login()\r\n\r\n project = dl.projects.get(project_name=project_name)\r\n\r\n package = deploy_package(project, new_package_deployment=True)\r\n deploy_service(package=package)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main(project_name='your project name')\r\n","repo_name":"SewarDra/dtlpyTraining-Sessions","sub_path":"Session 2-FaaS&Pipelines/add_classification-basic FaaS/create_service.py","file_name":"create_service.py","file_ext":"py","file_size_in_byte":3340,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"20"} +{"seq_id":"32019196908","text":"import argparse\nfrom pathlib import Path\nimport numpy as np\nfrom typing import Tuple, List\nimport re\n\nSTUDY_ID = 'CC'\nwave = '1'\n\n\ndef go_trial_success_converter(s: bytes) -> int:\n \"\"\"\n Converter to translate :param s: containing a trial type into 1 or 0.\n :param s: Trial type. Trial type containing 'correct-go' indicates successful 'go' trials.\n Trial type containing 'failed-go' indicates unsuccessful 'go' trials.\n :return: 1 for successful go trials, 0 for failure go trials\n \"\"\"\n if s.startswith(b'correct-go'):\n return 1\n elif s.startswith(b'failed-go'):\n return 0\n else:\n return -1\n\n\ndef tsv_data_read_for_latent_class(file: Path) -> Tuple[int, float, float]:\n \"\"\"\n Read behavioral data out of events.tsv files.\n Return a list of tuples of (duration, go trial success or failure)\n \"\"\"\n converters = {2: go_trial_success_converter}\n\n _, duration, trial_type = np.loadtxt(str(file),\n delimiter='\\t',\n skiprows=1,\n converters=converters,\n unpack=True)\n num_failed_go = trial_type.size - np.count_nonzero(trial_type)\n successful_go_duration = np.ma.masked_where(trial_type != 1, duration)\n mean = successful_go_duration.mean()\n std_deviation = successful_go_duration.std()\n\n return num_failed_go, mean, std_deviation\n\n\ndef write_for_rescorla_wagner(file: Path, events: List[Tuple], is_go: bool = True):\n \"\"\"\n Write a new file containing only the go-trial success or failure\n \"\"\"\n trial_type = \"_go\"\n if not is_go:\n trial_type = \"_stop\"\n new_file = file.with_name(str(file.stem) + trial_type + str(file.suffix))\n with open(str(new_file), mode='w') as f:\n for e in events:\n f.write(f'{e[0]}\\t{int(e[1])}\\n')\n\n\ndef write_for_latent_class_analysis(file, subject_id: str, event: Tuple[int, float, float]):\n file.write(f'{subject_id}\\t{event[0]}\\t{event[1]}\\t{event[2]}\\n')\n\n\ndef main(input_dir: str):\n files = sorted(Path(input_dir).glob('*_task-SST_acq-1_events.tsv'))\n\n pattern = f'({STUDY_ID}' + '\\\\d{3})_ses-wave1_task-SST_acq-1_events.tsv'\n new_file_name = files[0].with_name('latent_class_analysis' + str(files[0].suffix))\n with open(str(new_file_name), mode='w') as outfile:\n for f in files:\n match = re.search(pattern, str(f.name))\n subject_id = ''\n if match:\n subject_id, = match.groups()\n events = tsv_data_read_for_latent_class(f)\n write_for_latent_class_analysis(outfile, subject_id, events)\n\n\nif __name__ == \"__main__\":\n description = f'Create a file for modeling SST task in {STUDY_ID} study using latent class analysis'\n\n parser = argparse.ArgumentParser(description=description,\n add_help=True,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument('-i', '--input', metavar='Input directory', action='store',\n type=str, required=True,\n help='absolute path to directory containing events.tsv files from the SST task.',\n dest='input_dir'\n )\n args = parser.parse_args()\n\n main(args.input_dir)\n","repo_name":"UOSAN/CC_scripts","sub_path":"fMRI/fx/multiconds/SST/multiconds_latent_class.py","file_name":"multiconds_latent_class.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"40888500723","text":"from os.path import dirname, join\nimport numpy as np\n\ndef load_narma2():\n\n datadir = join(dirname(__file__), 'data/NARMA')\n inp = np.loadtxt(join(datadir, 'Input_narma.dat'))\n target = np.loadtxt(join(datadir, 'NARMA2.dat'))\n x_train, x_test = np.split(np.reshape(inp, [1, -1, 1]), 2, axis=1)\n y_train, y_test = np.split(np.reshape(target, [-1, 1]), 2, axis=0)\n\n return(x_train, x_test, y_train, y_test)\n","repo_name":"pomacanthidae/python-reservoir","sub_path":"pyres/datasets/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"74895215729","text":"import json\nimport os\n\nclass PositionCheck:\n def __init__(self) -> None:\n pass\n\n def Check(self):\n path=os.path.split(os.path.realpath(__file__))[0]\n with open(os.path.join(path, 'holding.json')) as f:\n totalValue=0\n currentHolding=json.load(f)\n for single in currentHolding['holding']:\n code = single['code']\n number= float(single['number'])\n price= float(single['price'])\n totalValue = totalValue+ number* price\n \n cash = float(currentHolding['cash'])\n totalValue= totalValue+ cash\n\n totalPosition=(totalValue-cash)*100/totalValue\n self.CheckTotalPosition(totalPosition)\n\n for single in currentHolding['holding']:\n code = single['code']\n number= float(single['number'])\n price= float(single['price'])\n\n singlePosition= number*price*100/totalValue\n self.CheckSinglePosition(code, singlePosition)\n return True\n \n ## 整体仓位检测\n def CheckTotalPosition(self,totalPosition):\n if self.GetBondSpread()-20 > totalPosition:\n print(\"警告:整体仓位过高,当前仓位:%d%%\"%totalPosition)\n return True\n\n ## 个股持仓检测\n def CheckSinglePosition(self, code, singlePosition):\n if singlePosition > 30:\n print(\"警告:个股%s 仓位过高,当前仓位:%d%%\"%(code,singlePosition))\n return True\n\n\n ## 获取股债利差百分位\n def GetBondSpread(self):\n return 80","repo_name":"Neverrepentance/principle","sub_path":"source/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"8061483848","text":"import logging\nfrom typing import Optional\n\nfrom snr.prelude import *\n\n\nclass Context(AbstractContext):\n\n def __init__(self,\n name: str,\n profiler: Optional[AbstractProfiler],\n timer: TimerProtocol,\n ) -> None:\n self.name = name\n self.log = logging.getLogger(self.name)\n self.profiler = profiler\n self.timer = timer\n","repo_name":"sfshaw/SNR","sub_path":"snr/core/contexts/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"74291769648","text":"# Itachi Userbot - A telegram userbot.\r\n# Copyright (C) 2021 Itachisann\r\n\r\n# This program is free software: you can redistribute it and / or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n\r\n# This program is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY\r\n# without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n\r\n# You should have received a copy of the GNU General Public License\r\n# along with this program. If not, see < https: // www.gnu.org/licenses/>.\r\n\r\n\r\nimport io\r\n\r\nimport PIL\r\nfrom telethon import errors\r\nfrom telethon.tl import functions, types\r\nfrom telethon.utils import get_peer_id\r\nfrom userbot import LOGGER, client\r\nfrom userbot.core.events import NewMessage\r\nfrom userbot.plugins.functions.parser import Parser\r\n\r\nplugin_category = \"user\"\r\n\r\n\r\n@client.createCommand(\r\n command=(\"info [Utente]\", plugin_category),\r\n outgoing=True, regex=r\"info(?: |$|\\n)([\\s\\S]*)\"\r\n)\r\nasync def info(event: NewMessage.Event) -> None:\r\n match = event.matches[0].group(1)\r\n entities = []\r\n if match:\r\n entities, _ = await client.parse_arguments(match)\r\n if \"this\" in entities:\r\n entities.remove(\"this\")\r\n entities.append(event.chat_id)\r\n elif event.reply_to_msg_id:\r\n if not entities:\r\n reply = await event.get_reply_message()\r\n user = reply.sender_id\r\n if reply.fwd_from:\r\n if reply.fwd_from.from_id:\r\n user = reply.fwd_from.from_id\r\n entities.append(user)\r\n else:\r\n entities.append(\"self\")\r\n users = \"\"\r\n chats = \"\"\r\n channels = \"\"\r\n failed = []\r\n for user in entities:\r\n try:\r\n input_entity = await client.get_input_entity(user)\r\n if isinstance(input_entity, types.InputPeerChat):\r\n full_chat = await client(\r\n functions.messages.GetFullChatRequest(input_entity)\r\n )\r\n string = await Parser.parse_full_chat(full_chat, event)\r\n chats += f\"\\n{chats}\\n\"\r\n elif isinstance(input_entity, types.InputPeerChannel):\r\n full_channel = await client(\r\n functions.channels.GetFullChannelRequest(input_entity)\r\n )\r\n string = await Parser.parse_full_chat(full_channel, event)\r\n channels += f\"\\n{string}\\n\"\r\n else:\r\n full_user = await client(\r\n functions.users.GetFullUserRequest(input_entity)\r\n )\r\n string = await Parser.parse_full_user(full_user, event)\r\n users += f\"\\n{string}\\n\"\r\n except Exception as e:\r\n LOGGER.debug(e)\r\n failed.append(user)\r\n\r\n if users:\r\n photo = full_user.profile_photo\r\n if photo:\r\n await event.delete()\r\n await client.send_message(event.chat_id, \"⚙️ INFO UTENTE ⚙️ \" + users, file=photo, parse_mode='html')\r\n else:\r\n await event.answer(\"⚙️ INFO UTENTE ⚙️ \" + users, parse_mode='html')\r\n if chats:\r\n await event.answer(\"⚙️ INFO GRUPPO ⚙️\" + chats, parse_mode='html')\r\n if channels:\r\n await event.answer(\"⚙️ INFO CHAT ⚙️\" + channels, parse_mode='html')\r\n\r\n if failed:\r\n failedtext = \"**Impossibile trovare:**\\n\"\r\n failedtext += \", \".join(f'`{u}`' for u in failed)\r\n await event.answer(failedtext)\r\n elif not (users or chats or channels):\r\n await event.answer(\"**Impossibile trovare:**\", self_destruct=2)\r\n\r\n\r\n@client.createCommand(\r\n command=(\"bio [Bio]\", plugin_category),\r\n outgoing=True, regex=\"bio(?: |$)(.*)$\"\r\n)\r\nasync def bio(event: NewMessage.Event) -> None:\r\n match = event.matches[0].group(1)\r\n about = (await client(functions.users.GetFullUserRequest(\"self\"))).about\r\n if not match:\r\n if about:\r\n await event.answer(f\"**📕 Bio:\\n {about}**\")\r\n else:\r\n await event.answer(\"`Attualmente non hai bio.`\")\r\n return\r\n\r\n try:\r\n await client(functions.account.UpdateProfileRequest(about=match))\r\n await event.answer(\r\n f\"`✅ Bio cambiata in {match}.`\",\r\n log=(\"bio\", f\"Bio cambiata da {about} a{match}\")\r\n )\r\n except errors.AboutTooLongError:\r\n await event.answer(\"`La bio che vuoi impostare è troppo lunga.`\")\r\n\r\n\r\n@client.createCommand(\r\n command=(\"username [Username]\", plugin_category),\r\n outgoing=True, regex=\"username(?: |$)(.*)$\"\r\n)\r\nasync def username(event: NewMessage.Event) -> None:\r\n match = event.matches[0].group(1)\r\n u1 = (await client.get_me()).username\r\n if not match:\r\n if u1:\r\n await event.answer(f\"👤 Utente: **@{u1}**\")\r\n else:\r\n await event.answer(\"`Attualmente non hai username.`\")\r\n return\r\n\r\n try:\r\n await client(functions.account.UpdateUsernameRequest(username=match))\r\n await event.answer(\r\n f\"**✅ Hai cambiato il tuo username in @{match}**\",\r\n log=(\"username\", f\"Username cambiato da @{u1} a @{match}\")\r\n )\r\n except errors.UsernameOccupiedError:\r\n await event.answer(\"`Questo username è già in uso.`\")\r\n except errors.UsernameNotModifiedError:\r\n await event.answer(\"`Username non modificato.`\")\r\n except errors.UsernameInvalidError:\r\n await event.answer(\"`Username non modificato.`\")\r\n\r\n\r\n@client.createCommand(\r\n command=(\"on\", plugin_category),\r\n outgoing=True, regex=\"on(?: |$)(.*)$\"\r\n)\r\nasync def on(event: NewMessage.Event) -> None:\r\n string = '[Online] '\r\n me = await client.get_me()\r\n if string not in me.first_name:\r\n new_name = string + me.first_name\r\n else:\r\n new_name = me.first_name\r\n if '[Offline] ' in me.first_name:\r\n v = me.first_name\r\n new_name = v.replace('[Offline] ', string)\r\n\r\n try:\r\n await client(functions.account.UpdateProfileRequest(\r\n first_name=new_name\r\n ))\r\n await event.answer(\"__Sei andato online!__\", self_destruct=2)\r\n except errors.FirstNameInvalidError:\r\n await event.answer(\"`Nome invalido`\")\r\n except Exception as e:\r\n await event.answer(f'```{await client.get_traceback(e)}```')\r\n\r\n\r\n@client.createCommand(\r\n command=(\"off\", plugin_category),\r\n outgoing=True, regex=\"off(?: |$)(.*)$\"\r\n)\r\nasync def off(event: NewMessage.Event) -> None:\r\n string = '[Offline] '\r\n me = await client.get_me()\r\n if '[Online] ' in me.first_name:\r\n v = me.first_name\r\n new_name = v.replace('[Online] ', string)\r\n try:\r\n await client(functions.account.UpdateProfileRequest(\r\n first_name=new_name\r\n ))\r\n await event.answer(\"__Sei andato offline!__\", self_destruct=2)\r\n except errors.FirstNameInvalidError:\r\n await event.answer(\"`Nome invalido`\")\r\n except Exception as e:\r\n await event.answer(f'```{await client.get_traceback(e)}```')\r\n\r\n\r\n@client.createCommand(\r\n command=(\"pfp\", plugin_category),\r\n outgoing=True, regex=\"pfp$\"\r\n)\r\nasync def pfp(event: NewMessage.Event) -> None:\r\n reply = await event.get_reply_message()\r\n if not reply:\r\n photo = await client(functions.users.GetFullUserRequest(\"self\"))\r\n photo = photo.profile_photo\r\n if photo:\r\n await event.delete()\r\n await event.answer(file=photo)\r\n else:\r\n await event.answer(\"`Attualmente non hai foto profilo.`\")\r\n return\r\n\r\n if (\r\n (reply.document and reply.document.mime_type.startswith(\"image\")) or\r\n reply.photo or reply.sticker\r\n ):\r\n if reply.sticker and not reply.sticker.mime_type == \"image/webp\":\r\n await event.answer(\"`Sticker invalido.`\")\r\n return\r\n try:\r\n temp_file = io.BytesIO()\r\n await client.download_media(reply, temp_file)\r\n except Exception as e:\r\n await event.answer(\r\n f'```{await client.get_traceback(e)}```',\r\n reply=True\r\n )\r\n temp_file.close()\r\n return\r\n temp_file.seek(0)\r\n if reply.sticker:\r\n sticker = io.BytesIO()\r\n pilImg = PIL.Image.open(temp_file)\r\n pilImg.save(sticker, format=\"PNG\")\r\n pilImg.close()\r\n sticker.seek(0)\r\n sticker.name = \"sticcer.png\"\r\n photo = await client.upload_file(sticker)\r\n temp_file.close()\r\n sticker.close()\r\n else:\r\n photo = await client.upload_file(temp_file)\r\n temp_file.close()\r\n else:\r\n await event.answer(\"`Media invalido.`\")\r\n return\r\n\r\n try:\r\n await client(functions.photos.UploadProfilePhotoRequest(photo))\r\n await event.answer(\r\n \"`✅ La tua foto profilo è stata cambiata con successo.`\",\r\n log=(\"pfp\", \"Changed profile picture\")\r\n )\r\n except errors.FilePartsInvalidError:\r\n await event.answer(\"`Il numero di file è invalido.`\")\r\n except errors.ImageProcessFailedError:\r\n await event.answer(\"`Errore nel processare l'immagine`\")\r\n except errors.PhotoCropSizeSmallError:\r\n await event.answer(\"`Foto troppo piccola`\")\r\n except errors.PhotoExtInvalidError:\r\n await event.answer(\"`Questa foto non è supportata.`\")\r\n\r\n\r\n@client.createCommand(\r\n command=(\"id [Utente]\", plugin_category),\r\n outgoing=True, regex=r\"id(?: |$|\\n)([\\s\\S]*)\"\r\n)\r\nasync def whichid(event: NewMessage.Event) -> None:\r\n match = event.matches[0].group(1)\r\n text = \"\"\r\n if not match and not event.reply_to_msg_id:\r\n attr = \"first_name\" if event.is_private else \"title\"\r\n text = f\"🆔 {getattr(event.chat, attr)}: \"\r\n text += f\"`{get_peer_id(event.chat_id)}`\"\r\n elif event.reply_to_msg_id:\r\n reply = await event.get_reply_message()\r\n user = reply.sender_id\r\n if reply.fwd_from:\r\n if reply.fwd_from.from_id:\r\n user = reply.fwd_from.from_id\r\n peer = get_peer_id(user)\r\n text = f\"🆔 [{peer}](tg://user?id={peer}): `{peer}`\"\r\n else:\r\n failed = []\r\n strings = []\r\n users, _ = await client.parse_arguments(match)\r\n for user in users:\r\n try:\r\n entity = await client.get_input_entity(user)\r\n peer = get_peer_id(entity)\r\n if isinstance(entity, types.InputPeerChat):\r\n chat = await client(\r\n functions.messages.GetFullChatRequest(entity)\r\n )\r\n strings.append(\r\n f\"🆔 [{chat.chats[0].title}](tg://resolve?domain={peer}): `{peer}`\"\r\n )\r\n elif isinstance(entity, types.InputPeerChannel):\r\n channel = await client(\r\n functions.channels.GetFullChannelRequest(entity)\r\n )\r\n strings.append(\r\n f\"🆔 [{channel.chats[0].title}](tg://resolve?domain={peer}): `{peer}`\"\r\n )\r\n else:\r\n user = await client(\r\n functions.users.GetFullUserRequest(entity)\r\n )\r\n strings.append(\r\n f\"🆔 [@{user.user.username}](tg://user?id={peer}): `{peer}`\"\r\n )\r\n except Exception as e:\r\n failed.append(user)\r\n LOGGER.debug(e)\r\n if strings:\r\n text = \"\\n\".join(strings)\r\n if failed:\r\n ftext = \"**Utenti non trovati:**\\n\"\r\n ftext += \", \".join(f'`{f}`' for f in failed)\r\n await event.answer(ftext, reply=True)\r\n if text:\r\n await event.answer(text)\r\n","repo_name":"Itachisann/ItachiUserbot","sub_path":"userbot/plugins/userdata.py","file_name":"userdata.py","file_ext":"py","file_size_in_byte":12139,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"20814539816","text":"from PyQt6.QtCore import Qt, QSize\nfrom PyQt6.QtWidgets import (QToolBar, QTabWidget, QWidget, QHBoxLayout,\n QVBoxLayout, QLabel, QToolButton)\nfrom PyQt6.QtGui import QPainter, QColor\n\n\nclass PyShowRibbon(QToolBar):\n \"\"\"The RibbonBar for the PyShow main window.\"\"\"\n\n def __init__(self, parent):\n super().__init__()\n\n # Remember the parent so we can interact with it\n self._parent = parent\n\n # Remove the moving handle\n self.setMovable(False)\n\n # To make this toolbar a ribbonbar, the whole toolbar is filled\n # with a tabwidget, that actually contains all buttons and stuff\n self._widget = QTabWidget(self)\n self._widget.setMaximumHeight(125)\n self._widget.setMinimumHeight(125)\n self.addWidget(self._widget)\n\n self.makeup()\n\n def add_tab(self, name):\n \"\"\"Add a new tab to the RibbonBar.\"\"\"\n # Make a new ribbon tab widget\n tab = PyShowRibbonTab(self)\n # Give the tab a name so we can activate it later when necessary\n tab.setObjectName('tab_' + name)\n # Add the tab to the ribbon\n self._widget.addTab(tab, name)\n\n # Now add a spacer tab. This is a hack, but the only one\n # I know of right now that works\n spacer = QWidget()\n spacer.setObjectName('spacer_' + name)\n self._widget.setTabEnabled(self._widget.addTab(spacer, 'spacer'),\n False)\n\n return tab\n\n def set_active(self, name):\n \"\"\"Set a tab of the RibbonBar as active.\"\"\"\n # Select a tab by name\n self.setCurrentWidget(self.findChild(PyShowRibbonTab, 'tab_' + name))\n\n def makeup(self):\n \"\"\"Style the RibbonBar so it looks cool.\"\"\"\n # The top-most widget\n self.setStyleSheet(\"background-color: white;\"\n \"border: none;\"\n \"padding: 0;\")\n\n # The tab view widget\n self._widget.setStyleSheet(\"QTabWidget:pane {\"\n \"background-color: white;\"\n \"border-top: 1px solid #DDD;\"\n \"border-bottom: 1px solid #DDD;\"\n \"top: -1px;\"\n \"margin: 0px;\"\n \"padding: 0px;\"\n \"}\"\n \"QTabBar { \"\n \"font-size: 10pt;\"\n \"}\"\n \"QTabBar::tab{\"\n \"background-color: white;\"\n \"padding: 6px 12px 6px 12px;\"\n \"color: #333;\"\n \"border-bottom: 1px solid #DDD;\"\n \"}\"\n \"QTabBar::tab::hover{\"\n \"color: #D15E00;\"\n \"}\"\n \"QTabBar::tab::selected{\"\n \"border: 1px solid #DDD;\"\n \"border-bottom: 1px solid #FFF;\"\n \"color: #D15E00;\"\n \"}\"\n \"QTabBar::tab::disabled {\"\n \"width: 4px;\"\n \"margin: 0px;\"\n \"padding: 0px;\"\n \"background: transparent;\"\n \"color: transparent;\"\n \"}\"\n \"QTabWidget::tab-bar{left:2px;}\")\n\n def __getitem__(self, name):\n \"\"\"Get a tab by name.\"\"\"\n return self.findChild(PyShowRibbonTab, 'tab_' + name)\n\n\nclass PyShowRibbonTab(QWidget):\n \"\"\"Tab that can reside in the RibbonBar.\"\"\"\n\n def __init__(self, parent):\n super().__init__()\n\n # Remember the parent so we can interact with it\n self._parent = parent\n\n # The ribbon tab is filled horizontally with panels containing controls\n layout = QHBoxLayout()\n # No margins\n layout.setContentsMargins(0, 0, 0, 0)\n # No spacing between items in the layout\n layout.setSpacing(0)\n # Don't spread the widgets over the whole length\n layout.setAlignment(Qt.AlignmentFlag.AlignLeft)\n\n # Add the layout to the ribbon tab\n self.setLayout(layout)\n\n self.makeup()\n\n def add_pane(self, name):\n \"\"\"Add a pane to the tab, which contains controls.\"\"\"\n pane = PyShowRibbonPane(self, name)\n self.layout().addWidget(pane)\n return pane\n\n def makeup(self):\n \"\"\"Style the tab so it looks cool.\"\"\"\n pass\n\n\nclass PyShowRibbonPane(QWidget):\n \"\"\"A pane in the ribbon tab, to organize the controls on the tab.\"\"\"\n\n def __init__(self, parent, name):\n super().__init__(parent)\n\n # The pane consists of a horizontal layout that contains\n # all the controls, within a vertical layout that\n # contains this horizontal layout and the name of the pane\n\n container = QHBoxLayout()\n container.setSpacing(0)\n container.setContentsMargins(0, 0, 0, 0)\n self.setLayout(container)\n\n vertical_widget = QWidget(self)\n container.addWidget(vertical_widget)\n container.addWidget(PyShowRibbonSeparator(self))\n\n vbox = QVBoxLayout()\n vbox.setSpacing(0)\n vbox.setContentsMargins(5, 0, 5, 0)\n vertical_widget.setLayout(vbox)\n\n label = QLabel(name)\n label.setAlignment(Qt.AlignmentFlag.AlignCenter)\n label.setStyleSheet(\"color: #666;margin-bottom:2px;\")\n\n content = QWidget(self)\n\n vbox.addWidget(content, 100)\n vbox.addWidget(label)\n\n content_layout = QHBoxLayout()\n content_layout.setAlignment(Qt.AlignmentFlag.AlignLeft)\n content_layout.setSpacing(0)\n content_layout.setContentsMargins(0, 0, 0, 0)\n\n self.contentLayout = content_layout\n content.setLayout(content_layout)\n\n def add_widget(self, widget):\n \"\"\"Add a control to the ribbon pane.\"\"\"\n self.contentLayout.addWidget(widget, 0, Qt.AlignmentFlag.AlignTop)\n\n\nclass PyShowRibbonSeparator(QWidget):\n \"\"\"The separator between ribbon panes.\"\"\"\n\n def __init__(self, parent):\n super().__init__(parent)\n self.setMinimumHeight(85)\n self.setMaximumHeight(85)\n self.setMinimumWidth(1)\n self.setMaximumWidth(1)\n self.setLayout(QHBoxLayout())\n\n def paintEvent(self, event):\n \"\"\"Paint the single separator line.\"\"\"\n qp = QPainter()\n qp.begin(self)\n qp.fillRect(event.rect(), QColor(\"#DDDDDD\"))\n qp.end()\n\n\nclass PyShowRibbonPushButton(QToolButton):\n \"\"\"A simple push button for in the ribbon pane.\"\"\"\n\n def __init__(self, owner, action, style):\n super().__init__(owner)\n\n self._action = action\n self.clicked.connect(self._action.trigger)\n self.update_button()\n self._action.changed.connect(self.update_button)\n\n self.setToolButtonStyle(Qt.ToolButtonStyle(style))\n self.setIconSize(QSize(32, 32))\n\n self.setStyleSheet(\"QToolButton {\"\n \"border: 1px solid transparent;\"\n \"margin: 2px 2px 0px 2px;\"\n \"min-height:70px;\"\n \"}\"\n \"QToolButton:hover {\"\n \"border: 1px solid #999;\"\n \"background-color: #ffaf87;\"\n \"}\"\n \"QToolButton:pressed {\"\n \"border: 1px solid #666;\"\n \"background-color: #ff9966;\"\n \"}\"\n \"QToolButton:checked {\"\n \"border: 1px solid transparent;\"\n \"background-color: #ffaf87;\"\n \"}\")\n\n def update_button(self):\n \"\"\"Update the button due to an external change.\"\"\"\n self.setText(self._action.text())\n self.setIcon(self._action.icon())\n self.setEnabled(self._action.isEnabled())\n self.setCheckable(self._action.isCheckable())\n self.setChecked(self._action.isChecked())\n","repo_name":"raimund89/PyShow","sub_path":"Interface/PyShowRibbon.py","file_name":"PyShowRibbon.py","file_ext":"py","file_size_in_byte":8461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"10043704408","text":"#coding=utf8\n\nfrom transformers import AutoTokenizer\nfrom processor.util import trunc_string\nimport json\n\nclass MultiToOneLead(object):\n def __init__(self, args, high_freq_src, high_freq_tgt):\n self.args = args\n\n root_dir = self.args.root_dir\n output_dir = self.args.output_dir\n dataset_name = self.args.dataset_name\n self.train_path = root_dir + '/train.json'\n self.train_src_path = output_dir+'/'+dataset_name+'_train_src.jsonl'\n self.train_tgt_path = output_dir+'/'+dataset_name+'_train_tgt.jsonl'\n\n self.dev_path = root_dir + '/dev.json'\n self.dev_src_path = output_dir+'/'+dataset_name+'_dev_src.jsonl'\n self.dev_tgt_path = output_dir+'/'+dataset_name+'_dev_tgt.jsonl'\n\n self.test_path = root_dir + '/test.json'\n self.test_src_path = output_dir+'/'+dataset_name+'_test_src.jsonl'\n self.test_tgt_path = output_dir+'/'+dataset_name+'_test_tgt.jsonl'\n\n self.high_freq_src = high_freq_src\n self.high_freq_tgt = high_freq_tgt\n\n if self.args.tokenizer_model_path == '':\n self.tokenizer = None\n else:\n self.tokenizer = AutoTokenizer.from_pretrained(\n self.args.tokenizer_model_path,\n do_lower_case=True,\n use_fast=True,\n revision=\"main\",\n use_auth_token=False,\n local_files_only=False)\n\n tmp_tokenizer = AutoTokenizer.from_pretrained(\n self.args.potential_model_path,\n do_lower_case=True,\n use_fast=True,\n revision=\"main\",\n use_auth_token=False,\n local_files_only=False)\n\n self.cls_tok = tmp_tokenizer.cls_token\n self.sep_tok = tmp_tokenizer.sep_token\n\n\n def process(self, path, src_path, tgt_path):\n fpout_src = open(src_path, 'w')\n fpout_tgt = open(tgt_path, 'w')\n with open(path) as f:\n line = f.read().strip()\n json_obj = json.loads(line)\n\n for line in json_obj:\n flist = line.strip().split('\\t')\n cluster_id = flist[0]\n summ_url = flist[1]\n pairs = flist[2]\n pair_obj = json.loads(pairs)\n\n docs = []; summs = []; sups = []\n sup_doc_num = len(pair_obj)-1\n if self.args.max_len_sup == -1:\n max_sup_len = self.args.max_len_doc\n else:\n max_sup_len = self.args.max_len_sup / sup_doc_num\n for pid in pair_obj:\n pair = pair_obj[pid]\n document = '\\t'.join(pair['[DOCUMENT]'])\n source = pair['[SORUCE]'].replace(':80', '')\n if source.find('www.newser.com') > -1:\n summary = '\\t'.join(pair['[TITLE]']) + '\\t' + '\\t'.join(pair['[SUMMARY]'])\n else:\n summary = '\\t'.join(pair['[SUMMARY]'])\n document, _ = trunc_string(document, \n self.args.max_len_doc, \n self.args.min_sentence_length,\n self.high_freq_src, \n tokenizer=self.tokenizer)\n sup_document, _ = trunc_string(document, \n max_sup_len, \n self.args.min_sentence_length,\n self.high_freq_src,\n tokenizer=self.tokenizer)\n summary, _ = trunc_string(summary, \n self.args.max_len_summ,\n self.args.min_sentence_length,\n self.high_freq_tgt)\n\n if len(document.split('\\t')) < self.args.min_doc_sent_num:\n continue\n if len(summary.split('\\t')) < self.args.min_summ_sent_num:\n continue\n document = ' '.join(document.split('\\t'))\n summary = ' '.join(summary.split('\\t'))\n sup_document = ' '.join(sup_document.split('\\t'))\n docs.append(document)\n summs.append(summary)\n sups.append(sup_document)\n\n if len(docs) == self.args.max_docs_in_cluster:\n break\n\n if len(docs) < 2:\n continue\n\n for i in range(len(docs)):\n src, tgt = self._prepare_sup_docs(docs, summs, sups, i)\n fpout_src.write(src+'\\n')\n fpout_tgt.write(tgt+'\\n')\n\n fpout_src.close()\n fpout_tgt.close()\n\n def _prepare_sup_docs(self, docs, summs, sup_docs, idx):\n new_docs = [docs[idx]]\n for i in range(len(docs)):\n if i == idx:\n continue\n new_docs.append(sup_docs[i])\n return (' '+self.sep_tok+' ').join(new_docs), summs[idx]\n\n def run(self):\n self.process(self.train_path,\n self.train_src_path,\n self.train_tgt_path)\n self.process(self.dev_path,\n self.dev_src_path,\n self.dev_tgt_path)\n self.process(self.test_path,\n self.test_src_path,\n self.test_tgt_path)\n\n\n","repo_name":"XinnuoXu/MiRANews","sub_path":"data_construction/processor/process_multi2one_lead.py","file_name":"process_multi2one_lead.py","file_ext":"py","file_size_in_byte":5650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"10219375038","text":"import pandas as pd\nimport json\n\ndata = pd.read_excel(\"COVID-19DataToday.xlsx\")\ndata = data.dropna()\nL = list(data.countriesAndTerritories.unique())\n\njsonList = []\ndic = {}\n\nfor i in L:\n temp_df = data[data['countriesAndTerritories']==i]\n data1 = {}\n data1['value'] = int(temp_df['cases'].sum())\n data1['id'] = temp_df['geoId'].iloc[0]\n data1['population'] = int(temp_df['popData2018'].iloc[0])\n data1['countryName'] = temp_df['countriesAndTerritories'].iloc[0]\n temp_df['dateRep'] = temp_df['dateRep'].dt.strftime('%Y-%m-%d')\n K = list(temp_df['dateRep'])\n K = K[::-1] \n data1['allDates'] = K\n M = list(temp_df['cases'])\n M = M[::-1] \n data1['allDatesCases'] = M\n temp_df1 = temp_df[temp_df['cases']!=0]\n data1['firstCase'] = str(temp_df1['dateRep'].iloc[-1]) \n json_data = json.dumps(data1)\n jsonList.append(json_data)\n \nwith open('data.txt', 'w', encoding='utf-8') as f:\n f.write(\"var covid19Data = \")\n json.dump(jsonList, f, ensure_ascii=False, indent=4) \n\nwith open('data.txt', 'r') as infile, open('js/data.js', 'w') as outfile:\n temp = infile.read().replace(\"\\\\\", \"\").replace(\"\\\"{\", \"{\").replace(\"}\\\"\",\"}\").replace(\"_\", \" \")\n outfile.write(temp)","repo_name":"bhupesh1177/covid19World","sub_path":"ImportingData.py","file_name":"ImportingData.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"71978149811","text":"import sys, argparse\nimport pdb\nfrom operator import itemgetter\nfrom argparse import RawTextHelpFormatter\nfrom random import randint\n\nparser = argparse.ArgumentParser(description=\"Given a prefix and an int, appends the prefix to the int from 0 to int and assigns each a random colour, to output a dictionary that adjust to plotTree.py format. Separator: space\")\nparser.add_argument(dest=\"max\", type=int, nargs=1, metavar=\"m\", help=\"Max num of items\")\nparser.add_argument(dest=\"prefix\", type=str, nargs=1, metavar=\"p\", help=\"Desired prefix\")\n\ndef setup():\n if len(sys.argv)== 1:\n parser.print_help()\n sys.exit(1)\n \n arguments = parser.parse_args()\n maxim = arguments.max[0]\n prefix = arguments.prefix[0] \n \n parseString(prefix, maxim)\n\ndef parseString(prefix, maxim):\n arrayOut = []\n #colours_50 = [\"#E41A1C\",\"#C72A35\",\"#AB3A4E\",\"#8F4A68\",\"#735B81\",\"#566B9B\",\"#3A7BB4\",\"#3A85A8\",\"#3D8D96\",\"#419584\",\"#449D72\",\"#48A460\",\"#4CAD4E\",\"#56A354\",\"#629363\",\"#6E8371\",\"#7A7380\",\"#87638F\",\"#93539D\",\"#A25392\",\"#B35A77\",\"#C4625D\",\"#D46A42\",\"#E57227\",\"#F67A0D\",\"#FF8904\",\"#FF9E0C\",\"#FFB314\",\"#FFC81D\",\"#FFDD25\",\"#FFF12D\",\"#F9F432\",\"#EBD930\",\"#DCBD2E\",\"#CDA12C\",\"#BF862B\",\"#B06A29\",\"#A9572E\",\"#B65E46\",\"#C3655F\",\"#D06C78\",\"#DE7390\",\"#EB7AA9\",\"#F581BE\",\"#E585B8\",\"#D689B1\",\"#C78DAB\",\"#B791A5\",\"#A8959F\",\"#999999\"]\n colours_50 = [\"Red\", \"DarkBlue\", \"Gold\", \"LimeGreen\",\"Violet\",\"MediumTurquoise\", \"LimeGreen\", \"LimeGreen\", \"Sienna\",\"LightCoral\",\"LightSkyBlue\",\"Indigo\",\"Tan\",\"Coral\",\"OliveDrab\",\"Teal\", \"#E41A1C\",\"#C72A35\",\"#AB3A4E\",\"#8F4A68\",\"#735B81\",\"#566B9B\",\"#3A7BB4\",\"#3A85A8\",\"#3D8D96\",\"#419584\", \"#FF8904\",\"#FF9E0C\",\"#FFB314\",\"#FFC81D\",\"#FFDD25\",\"#FFF12D\",\"#F9F432\",\"#EBD930\",\"#DCBD2E\",\"DarkBlue\", \"Gold\", \"LimeGreen\",\"Violet\",\"MediumTurquoise\",\"Sienna\",\"LightCoral\",\"LightSkyBlue\",\"Indigo\",\"Tan\",\"Coral\",\"OliveDrab\",\"Teal\", \"#E41A1C\",\"#C72A35\"]\n for i in xrange(1, maxim+1):\n print(i)\n colours_50, chosen = randomColour(colours_50)\n temp = \"\\\"\"+ prefix + \" \" + str(i) +\"\\\": \\\"\"+ chosen +\"\\\"\"\n arrayOut.append(temp)\n stringed = \", \".join(arrayOut)\n stringed = \"{\" + stringed + \"}\"\n print(stringed)\n\n\ndef randomColour(arrayRemainingColours):\n size = len(arrayRemainingColours)\n random = randint(0, size-1)\n chosen = arrayRemainingColours[random]\n del arrayRemainingColours[random]\n return arrayRemainingColours, chosen\n\nsetup()\n\n\n","repo_name":"emmaielle/thesis_mbovis_genomics-part2","sub_path":"7.treeVisualization/numberedPrefix_toColor.py","file_name":"numberedPrefix_toColor.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"20353683631","text":"from curses import window\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup as bs\nimport requests\nimport argparse\nfrom random import randint \nimport time\nfrom tkinter import *\nimport wikipedia as wiki\nimport time \nfrom os import system\n\nUSER_AGENT = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36\"\n# US english\nLANGUAGE = \"en-US,en;q=0.5\"\n\nclass Weather: \n def get_weather_data(url):\n session = requests.Session()\n session.headers['User-Agent'] = USER_AGENT\n session.headers['Accept-Language'] = LANGUAGE\n session.headers['Content-Language'] = LANGUAGE\n html = session.get(url)\n # create a new soup\n soup = bs(html.text, \"html.parser\")\n # store all results on this dictionary\n result = {}\n # extract region\n result['region'] = soup.find(\"div\", attrs={\"id\": \"wob_loc\"}).text\n # extract temperature now\n result['temp_now'] = soup.find(\"span\", attrs={\"id\": \"wob_tm\"}).text\n # get the day and hour now\n result['dayhour'] = soup.find(\"div\", attrs={\"id\": \"wob_dts\"}).text\n # get the actual weather\n result['weather_now'] = soup.find(\"span\", attrs={\"id\": \"wob_dc\"}).text\n # get the precipitation\n result['precipitation'] = soup.find(\"span\", attrs={\"id\": \"wob_pp\"}).text\n # get the % of humidity\n result['humidity'] = soup.find(\"span\", attrs={\"id\": \"wob_hm\"}).text\n # extract the wind\n result['wind'] = soup.find(\"span\", attrs={\"id\": \"wob_ws\"}).text\n # get next few days' weather\n next_days = []\n days = soup.find(\"div\", attrs={\"id\": \"wob_dp\"})\n for day in days.findAll(\"div\", attrs={\"class\": \"wob_df\"}):\n # extract the name of the day\n day_name = day.findAll(\"div\")[0].attrs['aria-label']\n # get weather status for that day\n weather = day.find(\"img\").attrs[\"alt\"]\n temp = day.findAll(\"span\", {\"class\": \"wob_t\"})\n # maximum temparature in Celsius, use temp[1].text if you want fahrenheit\n max_temp = temp[0].text\n # minimum temparature in Celsius, use temp[3].text if you want fahrenheit\n min_temp = temp[2].text\n next_days.append({\"name\": day_name, \"weather\": weather, \"max_temp\": max_temp, \"min_temp\": min_temp})\n # append to result\n result['next_days'] = next_days\n return result\n # print data\n def DataPrint(data):\n strorage=\"\"\n strorage+=\"Weather for: {}\".format(data[\"region\"])\n #print(\"Now:\", data[\"dayhour\"])\n strorage+=\"\\nNow: {}\".format(data[\"dayhour\"])\n #print(f\"Temperature now: {data['temp_now']}°C\")\n strorage+=\"\\nTemperature now: {}°C\".format(data[\"temp_now\"])\n #print(\"Description:\", data['weather_now'])\n strorage+=\"\\nDescription: {}\".format(data[\"weather_now\"])\n #print(\"Precipitation:\", data[\"precipitation\"])\n strorage+=\"\\nPrecipitation: {}\".format(data[\"precipitation\"])\n #print(\"Humidity:\", data[\"humidity\"])\n strorage+=\"\\nHumidity: {}\".format(data[\"humidity\"])\n #print(\"Wind:\", data[\"wind\"])\n strorage+=\"\\nWind: {}\".format(data[\"wind\"])\n #print(\"Next days:\")\n strorage+=\"\\nNext days: \"\n for dayweather in data[\"next_days\"]:\n #print(\"=\"*40, dayweather[\"name\"], \"=\"*40)\n strorage+=\"\\n {} {} {}\".format((\"=\"*40),dayweather[\"name\"],(\"=\"*40))\n #print(\"Description:\", dayweather[\"weather\"])\n strorage+=\"\\n Description: {}\".format(dayweather[\"weather\"])\n #print(f\"Max temperature: {dayweather['max_temp']}°C\")\n strorage+=\"\\n Max temperature: {}°C\".format(dayweather[\"max_temp\"])\n #print(f\"Min temperature: {dayweather['min_temp']}°C\")\n strorage+=\"\\n Min temperature: {}°C\".format(dayweather['min_temp'])\n return strorage\nclass Weathercall:\n def inputString(bemenet): \n st=\"This city does not exist or you miswrote it!\"\n bemenettömb=bemenet.split()\n def Ugyanaz(be, masikbe):\n for i in range(0,len(be)):\n if (be[i]==masikbe[i]):\n return True\n def BenneVan(bemenettömb):\n for i in range(0,len(bemenettömb)):\n seged=bemenettömb[i]\n for j in range(0,len(seged)):\n if(seged[j]==':'):\n segedtömb=seged.split(\":\")\n exseged=\"\"\n for z in range(0,len(segedtömb)-1):\n exseged+=f\"{segedtömb[z]} \"\n exseged+=segedtömb[len(segedtömb)-1]\n bemenettömb[i]=exseged\n #print(bemenettömb[i])\n BenneVan(bemenettömb)\n Nagybetus=[]\n MegynitandoVaros=[]\n for i in range(0,len(bemenettömb)):\n if(bemenettömb[i][0].isupper()):\n Nagybetus.append(bemenettömb[i])\n MegynitandoVaros.append(f\"City{bemenettömb[i][0]}.txt\")\n #print(Nagybetus)\n #print(MegynitandoVaros)\n for k in range(0,len(bemenettömb)): \n #print(f\"Én vagyok a k:{k}\") \n for j in range(0,len(bemenettömb)):\n #print(f\"Én vagyok a j:{j}\") \n if (Ugyanaz(bemenettömb[k],\"weather\")):\n #print(\"Én vagyok az ellenőr\") \n z=0;\n if len(MegynitandoVaros)!=0 & z<=len(MegynitandoVaros):#Sajnos a subproces nem müködött\n with open(MegynitandoVaros[z], \"r+\",encoding=\"utf-8\")as f:\n help=f.read()\n lista=help.split(\"\\n\")\n if (lista.__contains__(bemenettömb[j])):\n URL = \"https://www.google.com/search?lr=lang_en&ie=UTF-8&q=weather\"\n parser = argparse.ArgumentParser(description=\"Quick Script for Extracting Weather data using Google Weather\")\n parser.add_argument(\"region\", nargs=\"?\", help=\"\"\"Region to get weather for, must be available region.\n Default is your current location determined by your IP Address\"\"\", default=\"\")\n # parse arguments\n args = parser.parse_args() \n region=bemenettömb[j] \n URL += region\n # get data\n data = Weather.get_weather_data(URL)\n #Weather.DataPrint(data)\n st=Weather.DataPrint(data)\n z+=1\n return st\n elif len(MegynitandoVaros)==0:\n URL = \"https://www.google.com/search?lr=lang_en&ie=UTF-8&q=weather\"\n parser = argparse.ArgumentParser(description=\"Quick Script for Extracting Weather data using Google Weather\")\n parser.add_argument(\"region\", nargs=\"?\", help=\"\"\"Region to get weather for, must be available region.\n Default is your current location determined by your IP Address\"\"\", default=\"\")\n # parse arguments\n args = parser.parse_args() \n region=args.region \n URL += region\n # get data\n data = Weather.get_weather_data(URL)\n #Weather.DataPrint(data)\n st=Weather.DataPrint(data)\n z+=1\n return st\n return st\nclass Joke:\n def Joke(): \n jokes=[\"Whoever said that the definition of insanity is doing the same thing over and over again and expecting different results has obviously never had to reboot a computer.\", \"Did you hear about the monkeys who shared an Amazon account? They were Prime mates.\", \"Why are iPhone chargers not called Apple Juice?!\", \"PATIENT: Doctor, I need your help. I'm addicted to checking my Twitter! DOCTOR: I'm so sorry, I don't follow.\", \"He: You are \\';\\' to me. She: I code in Python\"]\n st=jokes[randint(0,len(jokes)-1)]\n return st\nclass Time:\n def current_time():\n t = time.localtime()\n current_time = time.strftime(\"%H:%M:%S\", t)\n st=f\"Actual time: {current_time}\"\n return st\nclass WhoAmI:\n def Who():\n st1=\"I am just a program\"#Én csak egy program vagyok\n return st1\n def Old():\n t = datetime.today()\n old=\"04-15-2022\"\n oldtime=datetime.strptime(old,\"%m-%d-%Y\")\n deltatime=t-oldtime\n if(deltatime.days>365):\n st2=f\"I born {round((deltatime.days)/365,2)} years ago.\"\n else:\n st2=f\"I born {deltatime.days} days ago.\"\n return st2\n def Name():\n st3=\"My name is LAIS\"\n return st3\nclass Info:\n def Info(bemenet):\n st=\"\"\n #wiki first few row implementation\n bemenettömb=bemenet.split()\n #print(bemenettömb)\n Nagybetus=[]\n MegynitandoVaros=[]\n for i in range(0,len(bemenettömb)):\n if(bemenettömb[i][0].isupper()):\n Nagybetus.append(bemenettömb[i])\n MegynitandoVaros.append(f\"City{bemenettömb[i][0]}.txt\")\n for k in range(0,len(bemenettömb)): \n #print(f\"Én vagyok a k:{k}\") \n for j in range(0,len(bemenettömb)):\n #print(f\"Én vagyok a j:{j}\") \n if (bemenettömb[k]==\"info\"):\n #print(\"Én vagyok az ellenőr\") \n z=0;\n if len(MegynitandoVaros)!=0 & z<=len(MegynitandoVaros):\n with open(MegynitandoVaros[z], \"r+\",encoding=\"utf-8\")as f:\n help=f.read()\n lista=help.split(\"\\n\")\n if (lista.__contains__(bemenettömb[j])):\n #st+=\"{}\\n\".format((\"=\"*60))\n st+=wiki.summary(bemenettömb[j])\n #st+=\"{}\\n\".format((\"=\"*60)) \n z+=1\n elif len(MegynitandoVaros)==0:\n def IP(): \n response = requests.get('https://api64.ipify.org?format=json').json()\n ip_address =response[\"ip\"]\n #print(ip_address)\n #print(f\"1: {ip_address}\")\n response = requests.get(f'https://ipapi.co/{ip_address}/json/').json()\n location_data = response.get(\"city\")\n return location_data\n tester=IP()\n #print(tester)\n if((tester==\"Debrecen\")|(tester==\"debrecen\")):\n checker=IP()\n #print(checker)\n #st+=\"{}\\n\".format((\"=\"*60))\n st+=wiki.summary(checker)\n #st+=\"{}\\n\".format((\"=\"*60)) \n else:\n #print(tester)\n #st=\"{}\\n\".format((\"=\"*60))\n st+=f\"{wiki.summary(tester)}\\n\"\n #st+=\"{}\".format((\"=\"*60))\n z+=1\n else:\n st+=\"Something went wrong\"\n return st \nclass Main:\n def WhatIsIt(bemenet):\n bemenetcopy=bemenet.lower()\n bemenettömb=bemenetcopy.split()\n if(bemenettömb.__contains__(\"weather\")):\n st=Weathercall.inputString(bemenet)\n return st\n elif(bemenettömb.__contains__(\"joke\")):\n st=Joke.Joke()\n system(\"say \"+st)\n return st\n elif(bemenettömb.__contains__(\"time\") & (bemenettömb.__contains__(\"weather\")==True)):\n st=Weathercall.inputString(bemenet)\n return st\n elif(bemenettömb.__contains__(\"info\")):\n st=Info.Info(bemenet)\n return st \n elif(bemenettömb.__contains__(\"time\")):\n st=Time.current_time()\n system(\"say \"+st)\n return st \n elif(bemenettömb.__contains__(\"old\")|bemenettömb.__contains__(\"who\")):\n if(bemenettömb.__contains__(\"old\")):\n st=WhoAmI.Old()\n system(\"say \"+st)\n return st \n else:\n st=WhoAmI.Who()\n system(\"say \"+st)\n return st \n elif(bemenettömb.__contains__(\"name\")):\n st=WhoAmI.Name()\n system(\"say \"+st)\n return st \n else:\n st=\"Sorry, I am not capable answearing that question! :(\"\n system(\"say \"+st)\n return st\n \nwindow=Tk()\nwindow.geometry(\"822x722\")\nwindow.title(\"Creativ machine\")\nwindow.configure(bg=\"Green\")\nlabel=Label(window,text=\"Ask something:\", font=(\"Times New Roman\", 30,\"bold\"),fg=\"Black\")\nlabel.configure(bg=\"Green\")\nent=Entry(window)\nout=Text(window, fg = \"black\",bg=\"White\", cursor=\"hand\", font=(\"Times New Roman\", 16,\"bold\") ,width=500,height=500, yscrollcommand=True,spacing1=2)\nout.insert(INSERT,\"Hello...\")\nbemenet=\"\"\ndef bekero():\n bemenet=ent.get()\n #print(bemenet)\n #bemenet[0].lower()\n help=Main.WhatIsIt(bemenet)\n #print(help)\n Settext(help)\ndef Settext(text):\n out.delete('1.0',END)\n out.insert(INSERT,text)\ndef Clear():\n ent.delete(0,END)\n out.delete('1.0',END)\nlabel.pack()\nbtns_frame = Frame(window, bg=\"Green\",border=0)\nent.pack(expand=True,ipadx=100,ipady=0)\nbtns_frame.pack(expand=True,ipadx=0,ipady=0)\nout.pack(expand=True)#, width = 9, height = 3\naff=Button(btns_frame, text = \"Talk\",font=(\"Times New Roman\", 16,\"bold\"),border=0,fg = \"Black\", width = 10,height=1,bd = 0, bg = \"Green\", cursor = \"hand2\", command =lambda:bekero()).grid(row = 0, column = 0, columnspan = 1, padx = 1, pady = 1) \nclear=Button(btns_frame,text=\"Clear\",font=(\"Times New Roman\", 16,\"bold\"), border=0,fg = \"Black\", width = 10,height=1,bd = 0, bg = \"Green\", cursor = \"hand2\", command=lambda:Clear()).grid(row = 0, column = 5, columnspan = 1, padx = 1, pady = 1)\nwindow.mainloop()\n\n \n","repo_name":"LandAbel/PythonWeatherAndInfoReq","sub_path":"TalkativeAPIcopy.py","file_name":"TalkativeAPIcopy.py","file_ext":"py","file_size_in_byte":14516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"43643246334","text":"import numpy\nimport matplotlib.pyplot as plt\n\nx = numpy.linspace(0, 50, num=256)\na = numpy.sin(x * numpy.pi / 25)\nb = numpy.cos(x * numpy.pi / 25)\nc = numpy.sin(-x * numpy.pi / 25)\nd = -numpy.cos(x * numpy.pi / 25)\n\nplt.plot(x, a) #label='sin(x * π / 25)'\nplt.plot(x, b) #label='cos(x * π / 25)'\nplt.plot(x, c) #label='sin(-x * π / 25)'\nplt.plot(x, d) #label='cos(-x * π / 25)'\n\nplt.xlabel('')\nplt.ylabel('')\n#plt.legend()\nplt.grid(True)\nplt.show()\n","repo_name":"aabniaz/python2","sub_path":"python2/hw10/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7294989866","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Python version: 3.6\n\nimport torch\nfrom torch import nn, autograd\nfrom torch.utils.data import DataLoader, Dataset\nimport numpy as np\nfrom torch.autograd import Variable\nimport copy\nimport torch.nn.functional as F\n\ndef dist_l2(w, w_ema):\n a = 0.0\n for i in list(w.keys()) :\n a += (w[i]-w_ema[i]).float().norm(2)\n return a\n \ndef dist_l1(w):\n a = 0.0\n for i in list(w.keys()) :\n a += w[i].float().norm(1)\n return a\n\ndef softmax_mse_loss(input_logits, target_logits):\n assert input_logits.size() == target_logits.size()\n input_softmax = F.softmax(input_logits, dim=1)\n target_softmax = F.softmax(target_logits, dim=1)\n num_classes = input_logits.size()[1]\n return F.mse_loss(input_softmax, target_softmax, size_average=False) / num_classes\n\n\ndef penalty(model,copy_):\n\n w_epoch = list(model.parameters())\n copy_list=list(copy_.parameters())\n # print(\"layer0 :\", w_epoch[0])\n # print(\"layer2:\",w_epoch[2])\n deltaw_list = []\n k=[]\n # sum_w = 0\n for p in range(len(w_epoch)):\n deltaw_list.append(w_epoch[p]-copy_list[p])\n # print(\"i:\",p,\"layer:\",deltaw_list[p].flatten())\n c=torch.dot(deltaw_list[p].flatten(), deltaw_list[p].flatten()).reshape(-1)[0]\n # print(\"c\",c)\n if p==0:\n k.append(c)\n else:\n k.append(c+k[p-1])\n # print(\"sum_list\", k)\n sum_w=k[p]\n return sum_w\n\nclass DatasetSplit(Dataset):\n def __init__(self, dataset, idxs, pseudo_label = None):\n self.dataset = dataset\n self.idxs = list(idxs)\n self.pseudo_label = pseudo_label\n\n def __len__(self):\n return len(self.idxs)\n\n def __getitem__(self, item):\n image, label = self.dataset[self.idxs[item]]\n if self.pseudo_label != None:\n label = int(self.pseudo_label[self.idxs[item]]) \n return image, label\n\nclass DatasetSplit_aug(Dataset):\n def __init__(self, dataset, dataset_weak, idxs):\n self.dataset = dataset\n self.dataset_weak = dataset_weak\n self.idxs = list(idxs)\n\n def __len__(self):\n return len(self.idxs)\n\n def __getitem__(self, item):\n batch = [self.dataset[self.idxs[item]], self.dataset_weak[self.idxs[item]]]\n return batch\n\n\ndef batch_generator(x_mat, y, batch_size, seq_len):\n mean_data_x = np.mean(x_mat, axis=0)\n mean_data_y = np.mean(y, axis=0)\n # pad the beginning of the data with mean rows in order to minimize the error\n # on first rows while using sequence\n prefix_padding_x = np.asarray([mean_data_x for _ in range(seq_len - 1)])\n prefix_padding_y = np.asarray([mean_data_y for _ in range(seq_len - 1)])\n padded_data_x = np.vstack((prefix_padding_x, x_mat))\n padded_data_y = np.vstack((prefix_padding_y, y))\n seq_data = []\n seq_y = []\n for i in range(len(padded_data_x) - seq_len + 1):\n seq_data.append(padded_data_x[i:i + seq_len, :])\n # seq_y.append(padded_data_y[i + seq_len - 1:i + seq_len, :])\n seq_y.append(padded_data_y[i + seq_len - 2:i + seq_len - 1, :])\n if len(seq_data) == batch_size:\n if torch.cuda.is_available():\n yield Variable(torch.cuda.FloatTensor(seq_data)), Variable(torch.cuda.LongTensor(seq_y))\n else:\n yield Variable(torch.FloatTensor(seq_data)), Variable(torch.LongTensor(seq_y))\n seq_data = []\n seq_y = []\n if len(seq_data) > 0: # handle data which is not multiply of batch size\n if torch.cuda.is_available():\n yield Variable(torch.cuda.FloatTensor(seq_data)), Variable(torch.cuda.LongTensor(seq_y))\n else:\n yield Variable(torch.FloatTensor(seq_data)), Variable(torch.LongTensor(seq_y))\n\nclass ServerUpdate_fedavg(object):\n def __init__(self, args, dataset_train, dict_users_labeled):\n self.args = args\n self.loss_func = nn.CrossEntropyLoss(ignore_index= -1)\n self.dict_users_labeled = dict_users_labeled\n self.ldr_train = DataLoader(\n DatasetSplit(dataset = dataset_train, idxs = dict_users_labeled),\n batch_size=self.args.local_bs, \n shuffle=True\n )\n\n def train(self, model):\n model.train()\n opt = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)\n\n # print('Start model training')\n\n # for epoch in range(self.args.local_ep):\n loss_total = []\n for batch_idx, (images, labels) in enumerate(self.ldr_train):\n images, labels = images.to(self.args.device), labels.to(self.args.device)\n opt.zero_grad()\n output = model(images)\n loss = self.loss_func(output, labels)\n loss.backward()\n opt.step()\n loss_total.append(loss.item())\n return model.state_dict(), sum(loss_total) / len(loss_total)\n\n\n\nclass ClientUpdate_fedavg(object):\n def __init__(self, args, dataset_train, dict_users_unlabeled, pseudo_label):\n self.args = args\n self.loss_func = nn.CrossEntropyLoss(ignore_index= -1)\n self.dict_users_unlabeled = dict_users_unlabeled\n self.pseudo_label = pseudo_label\n self.ldr_train = DataLoader(\n DatasetSplit(dataset = dataset_train, idxs = dict_users_unlabeled, pseudo_label = pseudo_label),\n batch_size=self.args.local_bs, \n shuffle=True\n )\n\n\n def train(self, model):\n model.train()\n opt = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)\n\n # print('Start model training')\n\n for epoch in range(self.args.local_ep):\n loss_total = []\n for batch_idx, (images, labels) in enumerate(self.ldr_train):\n images, labels = images.to(self.args.device), labels.to(self.args.device)\n opt.zero_grad()\n output = model(images)\n loss = self.loss_func(output, labels)\n loss.backward()\n opt.step()\n loss_total.append(loss.item())\n return model.state_dict(), sum(loss_total) / len(loss_total)\n\n # for epoch in range(self.args.local_ep):\n # loss_total = []\n # for i, ((x_batch_pos, y_batch_pos), (x_batch_neg, y_batch_neg)) in enumerate(zip(batch_generator(self.X_train_pos_server, self.y_train_pos_server, self.args.local_bs, 2), batch_generator(self.X_train_neg_server, self.y_train_neg_server, self.args.local_bs, 2))):\n # # feed data from two dataloader\n # y_batch_pos = y_batch_pos.to(self.args.device)\n # y_batch_neg = y_batch_neg.to(self.args.device)\n # # print(y_batch_pos)\n # opt.zero_grad()\n # out_pos = model(x_batch_pos)\n # out_neg = model(x_batch_neg)\n # loss_pos = self.loss_func(out_pos, torch.flatten(y_batch_pos))\n # loss_neg = self.loss_func(out_neg, torch.flatten(y_batch_neg))\n # loss = loss_pos + loss_neg\n # loss.backward()\n # # print(loss.item())\n # if loss.item() > 0:\n # loss_total.append(loss.item())\n # opt.step()\n # return model.state_dict(), sum(loss_total) / len(loss_total) if len(loss_total) != 0 else 0\n\n\nclass ClientUpdate_fedmatch(object):\n def __init__(self, args, dataset_train, dataset_train_weak, dict_users_unlabeled):\n self.args = args\n self.loss_func = nn.CrossEntropyLoss(ignore_index= -1)\n self.dict_users_unlabeled = dict_users_unlabeled\n self.ldr_train = DataLoader(\n DatasetSplit_aug(dataset_train, dataset_train_weak, dict_users_unlabeled),\n batch_size=self.args.local_bs, \n shuffle=True\n )\n\n\n\n def train(self, model, model_h1, model_h2):\n model.train()\n opt = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)\n model_local_static = copy.deepcopy(model).to(self.args.device)\n # print('Start model training')\n\n for epoch in range(self.args.local_ep):\n loss_total = []\n for batch_idx, batch in enumerate(self.ldr_train):\n images_1 = batch[0][0].to(self.args.device)\n images_2 = batch[1][0].to(self.args.device)\n\n opt.zero_grad()\n output = model(images_2)\n output_h1 = model_h1(images_2)\n output_h2 = model_h2(images_2)\n output_aug = model(images_1)\n\n # _, logits = output.loss, output.logits\n # loss_h1, logits_h1 = output_h1.loss, output_h1.logits\n # loss_h2, logits_h2 = output_h2.loss, output_h2.logits\n # loss_aug, logits_aug = output_aug.loss, output_aug.logits\n logits = output\n logits_h1 = output_h1\n logits_h2 = output_h2\n logits_aug = output_aug\n\n\n pseudo_label_1 = torch.softmax(logits.detach_(), dim=-1)\n pseudo_label_2 = torch.softmax(logits_h1.detach_(), dim=-1)\n pseudo_label_3 = torch.softmax(logits_h2.detach_(), dim=-1)\n\n max_probs1, targets_u1 = torch.max(pseudo_label_1, dim=-1)\n max_probs2, targets_u2 = torch.max(pseudo_label_2, dim=-1)\n max_probs3, targets_u3 = torch.max(pseudo_label_3, dim=-1)\n\n if torch.equal(targets_u1, targets_u2) and torch.equal(targets_u1, targets_u3):\n max_probs = torch.max(max_probs1, max_probs2)\n max_probs = torch.max(max_probs, max_probs3)\n else: \n max_probs = max_probs1 - 0.2\n targets_u = targets_u1\n mask = max_probs.ge(0.95).float()\n Lu = (F.cross_entropy(logits_aug, targets_u, reduction='none') * mask).mean()\n\n lambda_iccs = 0.01\n lambda_l2 = 0.0000001\n lambda_l1 = 0.0000001\n\n L2 = lambda_l2*dist_l2(model.state_dict(), model_local_static.state_dict())\n \n L3 = lambda_l1*dist_l1(model.state_dict())\n \n loss = lambda_iccs*(Lu) + L2 + L3\n\n loss.backward()\n opt.step()\n loss_total.append(loss.item())\n return model.state_dict(), sum(loss_total) / len(loss_total)\n\n\n\n\nclass ClientUpdate_fedmix(object):\n def __init__(self, args, dataset_train, dataset_train_aug, dict_users_unlabeled):\n self.args = args\n self.loss_func = nn.CrossEntropyLoss(ignore_index= -1)\n self.dict_users_unlabeled = dict_users_unlabeled\n self.ldr_train = DataLoader(\n DatasetSplit_aug(dataset = dataset_train, dataset_weak = dataset_train_aug, idxs = dict_users_unlabeled),\n batch_size=self.args.local_bs, \n shuffle=True\n )\n\n def train(self, model, model_2):\n model.train()\n opt = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)\n consistency_criterion = softmax_mse_loss\n # print('Start model training')\n\n for epoch in range(self.args.local_ep):\n loss_total = []\n for batch_idx, batch in enumerate(self.ldr_train):\n images_1 = batch[0][0].to(self.args.device)\n images_2 = batch[1][0].to(self.args.device)\n\n opt.zero_grad()\n output = model(images_2)\n output_aug = model(images_1)\n\n logits = output\n logits_aug = output_aug\n\n pseudo_label_1 = torch.softmax(logits.detach_(), dim=-1)\n pseudo_label_2 = torch.softmax(logits_aug.detach_(), dim=-1)\n\n max_probs, targets_u = torch.max((pseudo_label_1 + pseudo_label_2)/2, dim=-1)\n\n mask = max_probs.ge(0.8).float()\n loss1 = (F.cross_entropy(logits, targets_u, reduction='none') * mask).mean()\n loss2 = consistency_criterion(logits, logits_aug)\n loss3 = penalty(model, model_2)\n\n loss = loss1 + loss2 + 0.1 * loss3\n\n loss.backward()\n opt.step()\n loss_total.append(loss.item())\n return model.state_dict(), sum(loss_total) / len(loss_total)\n\n","repo_name":"JackqqWang/sony_image","sub_path":"models/Update.py","file_name":"Update.py","file_ext":"py","file_size_in_byte":12356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73264830770","text":"# coding: utf-8\n\nfrom blinker import signal\n\nchannel = signal('channel')\n\n\n@channel.connect\ndef receive(sender, **kwargs):\n print('[receive] channel from : {}, data:{}'.format(sender, kwargs))\n test = 1 / 0\n return test\n\n\n@channel.connect\ndef receive2(sender, **kwargs):\n print('[receive2] channel from : {}, data:{}'.format(sender, kwargs))\n return 'received'\n\n\nif __name__ == '__main__':\n rv = channel.send('anonymous', message='I feel it coming')\n print(rv)\n","repo_name":"xingl01/pyground","sub_path":"blinker_try/sync_one_callback_break.py","file_name":"sync_one_callback_break.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"29477773673","text":"WORD_WIDTH = 100\nWORD_HEIGHT = 100\n\nBOARD_GAP = 10\nBOARD_WIDTH = (WORD_WIDTH * 5) + (BOARD_GAP * 6)\nBOARD_HEIGHT = (WORD_HEIGHT * 6) + (BOARD_GAP * 7)\n\nFONT_SIZE = 65\n\nINCORRECT_CHAR = '#787c7f'\nMISPLACED_CHAR = '#c8b653'\nCORRECT_CHAR = '#6ca965'\n\nWORDLE_COLORS = {\n 0 : INCORRECT_CHAR,\n 1 : MISPLACED_CHAR,\n 2 : CORRECT_CHAR\n}\n\nWORDLE_URL = 'https://wordle-api.vercel.app/api/wordle'\n\nDB_PATH = 'db/wordle.db'","repo_name":"JaredIsaacs/worlde-discord","sub_path":"globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"16514830368","text":"import Modules.ufirebase as firebase\nimport ujson\n\nclass FirebaseConnect:\n \n with open(\"./Shared/config.json\") as config_file:\n data = ujson.load(config_file)\n \n url = data[\"urlFirebase\"]\n pathDht = '/Sensors/Environment'\n pathFC = '/Sensors/Humidity'\n pathLDR = '/Sensors/Light'\n pathIndex = '/Indices/'\n pathBomb = '/Bomb'\n \n def __init__(self) -> None:\n firebase.setURL(self.__class__.url)\n \n #Send to cloud DHT\n def sendDHT(self, hum, temp):\n \n message = ujson.dumps({\n \"Humidity\": hum,\n \"Temperature\": temp,\n })\n \n print(message) \n firebase.put(self.__class__.pathDht, message, bg = 0 )\n \n #Send to cloud Humidity\n def SendFC(self, GroundMoisture):\n \n message = ujson.dumps({\n \"GroundMoisture\": GroundMoisture\n })\n \n print(message)\n firebase.put(self.__class__.pathFC, message, bg = 0 )\n \n #Send to cloud LDR\n def SendLDR(self, LightLevel):\n message = ujson.dumps({\n \"LightLevel\": LightLevel\n })\n firebase.put(self.__class__.pathLDR, message, bg = 0 )\n \n #Send to cloud Index List\n def SendIndexSensor(self, list, path):\n firebase.put(self.__class__.pathIndex + path, list, bg = 0)\n \n #Send to cloud Active Bomb\n def SendDataBomb(self, data):\n firebase.put(self.__class__.pathBomb, data, bg = 0)","repo_name":"JhonWester/Be_Agro","sub_path":"Models/FireConnect.py","file_name":"FireConnect.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"32845260761","text":"import os\r\nimport argparse\r\nimport random\r\nimport secrets\r\nimport logging\r\n\r\nimport imageio\r\nimport imgaug as ia\r\nimport imgaug.augmenters as iaa\r\nimport numpy as np\r\n\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--in_dir', help=\"Input Directory\")\r\nparser.add_argument('--out_dir', help='Output directory')\r\nparser.add_argument('--save_original', action='store_true')\r\n\r\nargs = parser.parse_args()\r\n\r\nlogging.basicConfig(level=logging.INFO)\r\n\r\nfor filename in os.listdir(args.in_dir):\r\n image = imageio.imread(os.path.join(\r\n os.getcwd(),\r\n args.in_dir,\r\n filename\r\n ))\r\n\r\n rotate = iaa.Affine(rotate=(-50, 30))\r\n rotated_image = rotate.augment_image(image)\r\n imageio.imsave(\r\n os.path.join(\r\n args.out_dir, f'{secrets.token_hex(12)}.png'\r\n ), rotated_image\r\n )\r\n logging.info(f'Rotated {filename} image saved')\r\n\r\n gaussian_noise = iaa.AdditiveGaussianNoise(10, 20)\r\n noise_image = gaussian_noise.augment_image(image)\r\n imageio.imsave(\r\n os.path.join(args.out_dir, f'{secrets.token_hex(12)}.png'), noise_image\r\n )\r\n logging.info(f'Gaussian {filename} image saved')\r\n\r\n crop = iaa.Crop(percent=(\r\n round(random.choices(np.arange(0, 0.4, 0.1))[0], 2),\r\n round(random.choices(np.arange(0, 0.4, 0.1))[0], 2)\r\n ))\r\n crop_image = crop.augment_image(image)\r\n imageio.imsave(\r\n os.path.join(args.out_dir, f'{secrets.token_hex(12)}.png'), crop_image\r\n )\r\n logging.info(f'Crop {filename} image saved')\r\n\r\n flip_hr = iaa.Fliplr(p=1.0)\r\n flip_hr_image = flip_hr.augment_image(image)\r\n imageio.imsave(\r\n os.path.join(\r\n args.out_dir, f'{secrets.token_hex(12)}.png'\r\n ), flip_hr_image\r\n )\r\n logging.info(f'Flip {filename} image saved')\r\n\r\n contrast = iaa.GammaContrast(gamma=random.choices(range(1, 4)))\r\n contrast_image = contrast.augment_image(image)\r\n imageio.imsave(\r\n os.path.join(\r\n args.out_dir, f'{secrets.token_hex(12)}.png'\r\n ), contrast_image\r\n )\r\n logging.info(f'Contrast Shift {filename} image saved')\r\n\r\n scale_im = iaa.Affine(\r\n scale={\r\n 'x': (1.0, round(random.choices(np.arange(1.1, 1.7, 0.1))[0], 2)),\r\n 'y': (1.0, round(random.choices(np.arange(1.1, 1.7, 0.1))[0], 2))\r\n }\r\n )\r\n scale_image = scale_im.augment_image(image)\r\n imageio.imsave(\r\n os.path.join(args.out_dir, f'{secrets.token_hex(12)}.png'), scale_image\r\n )\r\n logging.info(f'Rotated {filename} image saved')\r\n\r\n if args.save_original:\r\n imageio.imsave(\r\n os.path.join(\r\n args.out_dir, f'{secrets.token_hex(12)}.png'\r\n ), image\r\n )\r\n logging.info(f'original {filename} image saved')\r\n","repo_name":"samayakmalhotra/Smart-Parking-Detection-Edge-TPU","sub_path":"scripts/image_augmentation.py","file_name":"image_augmentation.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"39308007366","text":"import os\nfrom PIL import Image\n\ndef resize_image(image_path, output_path, target_width, target_height):\n # Open the image\n image = Image.open(image_path)\n\n # Calculate the aspect ratio of the original image\n original_width, original_height = image.size\n aspect_ratio = original_width / original_height\n\n # Calculate the new width while maintaining the aspect ratio\n new_width = target_width\n new_height = int(target_width / aspect_ratio)\n\n # Resize the image\n resized_image = image.resize((new_width, new_height), Image.LANCZOS)\n\n # Create a new canvas with the target size\n canvas = Image.new(\"RGB\", (target_width, target_height), (255, 255, 255))\n\n # Calculate the center position to paste the resized image\n paste_x = 0\n paste_y = (target_height - new_height) // 2\n\n # Paste the resized image onto the canvas\n canvas.paste(resized_image, (paste_x, paste_y))\n\n # Update the file extension of the output filename to .bmp\n output_path = os.path.splitext(output_path)[0] + \".bmp\"\n\n # Save the canvas as a 24-bit BMP file\n canvas.save(output_path, \"BMP\")\n\n# Directory containing the original images\ninput_directory = \"OriginalImages\"\n\n# Output directory for the resized images\noutput_directory = \"ResizedImages\"\n\n# Target dimensions for resizing\ntarget_width = 480\ntarget_height = 800\n\n# Create the output directory if it doesn't exist\nos.makedirs(output_directory, exist_ok=True)\n\n# Iterate through all image files in the input directory\nfor filename in os.listdir(input_directory):\n if filename.endswith(\".jpg\") or filename.endswith(\".png\") or filename.endswith(\".bmp\") or filename.endswith(\".webp\"):\n # Get the full path of the input image\n input_image = os.path.join(input_directory, filename)\n\n # Generate the output path for the resized image\n output_image = os.path.join(output_directory, filename)\n\n # Resize the image and save it\n resize_image(input_image, output_image, target_width, target_height)\n","repo_name":"AnicetusCer/waveshare_7_colour_e-ink_photo_painter_display_frame_image_converter","sub_path":"ResizeImageTo480800.py","file_name":"ResizeImageTo480800.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"21080274246","text":"# -*- coding: utf-8 -*-\r\nimport scrapy\r\nimport requests\r\nimport re\r\nfrom scrapy.http import HtmlResponse\r\n\r\ntry:\r\n import urlparse as parse\r\nexcept:\r\n from urllib import parse\r\ntry:\r\n import cookielib\r\nexcept:\r\n import http.cookiejar as cookielib\r\nimport time\r\nimport json\r\nfrom scrapy.http.cookies import CookieJar\r\nimport os.path\r\n\r\ntry:\r\n from PIL import Image\r\nexcept:\r\n pass\r\n\r\n# 使用登录cookie信息\r\nsession = requests.session()\r\nsession.cookies = cookielib.LWPCookieJar(filename='cookies.txt')\r\ntry:\r\n session.cookies.load(ignore_discard=True)\r\nexcept:\r\n print(\"Cookie 未能加载\")\r\n\r\n\r\nclass ZhihuSpider(scrapy.Spider):\r\n name = \"zhihu\"\r\n allowed_domains = [\"www.zhihu.com\"]\r\n start_urls = ['http://www.zhihu.com/']\r\n\r\n headers = {\r\n\r\n \"HOST\": \"www.zhihu.com\",\r\n \"Referer\": \"https://www.zhihu.com\",\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36\"\r\n\r\n }\r\n\r\n def parse(self, response):\r\n '''\r\n\r\n 提取出html页面中的所有的url 并跟踪这些url进一步爬取\r\n 如果提取的url中格式为/question/xx就下载后直接进入解析函数\r\n :param response: \r\n :return: \r\n '''\r\n\r\n all_urls = response.css(\"a::attr(href)\").extract()\r\n all_urls = [parse.urljoin(response.url, url) for url in all_urls]\r\n # all_urls = filter(lambda x: True if x.startWith(\"https\") else False, all_urls)\r\n for url in all_urls:\r\n print(url)\r\n match_obj = re.match(\"(.*zhihu.com/question/(\\d+))(/|$).*\", url)\r\n if match_obj:\r\n request_url = match_obj.group(1)\r\n question_id = match_obj.group(2)\r\n print(request_url, question_id)\r\n\r\n def start_requests(self):\r\n return [scrapy.Request(\"https://www.zhihu.com/#signin\", meta={'cookiejar': 1}, headers=self.headers,\r\n callback=self.login)]\r\n\r\n def login(self, response):\r\n t = str(int(time.time() * 1000))\r\n captcha_url = 'https://www.zhihu.com/captcha.gif?r=' + t + \"&type=login&lang=cn\"\r\n r = session.get(captcha_url, headers=self.headers)\r\n with open('captcha.jpg', 'wb') as f:\r\n f.write(r.content)\r\n f.close()\r\n\r\n # 用pillow 的 Image 显示验证码\r\n # 如果没有安装 pillow 到源代码所在的目录去找到验证码然后手动输入\r\n try:\r\n im = Image.open('captcha.jpg')\r\n im.show()\r\n im.close()\r\n except:\r\n print(u'请到 %s 目录找到captcha.jpg 手动输入' % os.path.abspath('captcha.jpg'))\r\n captcha = input(\"please input the captcha\\n>\")\r\n\r\n # response_text = response.text\r\n match_obj = re.match('.*name=\"_xsrf\" value=\"(.*?)\"', response.text, re.DOTALL)\r\n xsrf = ''\r\n if match_obj:\r\n xsrf = (match_obj.group(1))\r\n\r\n self.headers[\"X-Xsrftoken\"] = xsrf\r\n self.headers[\"X-Requested-With\"] = \"XMLHttpRequest\"\r\n\r\n post_url = 'https://www.zhihu.com/login/email'\r\n postdata = {'_xsrf': xsrf,\r\n 'password': \"yumin716\",\r\n 'email': \"yupei0318@gmail.com\",\r\n\r\n }\r\n # 不需要验证码直接登���成功\r\n login_page = session.post(post_url, data=postdata, headers=self.headers)\r\n # print(login_page)\r\n login_code = login_page.json()\r\n # login_page = session.post(post_url, data=postdata, headers=headers)\r\n # login_code = login_page.json()\r\n # print(login_code['msg'])\r\n if login_code['r'] == 1:\r\n # 不输入验证码登录失败\r\n # 使用需要输入验证码的方式登录\r\n print (captcha)\r\n postdata[\"captcha\"] = captcha\r\n ##login_page = session.post(post_url, data=postdata, headers=self.headers)\r\n # login_code = login_page.json()\r\n # print(login_code['msg'])\r\n ##text_json = login_page.json()\r\n ##resp = session.get(\"https://www.zhihu.com\", headers=self.headers)\r\n\r\n session.cookies.save()\r\n\r\n ##with open(\"index_page.html\", \"wb\") as f:\r\n ##f.write(resp.text.encode('utf-8'))\r\n # response = HtmlResponse(\"index_page.html\",body=respon.text, encoding=\"utf-8\")\r\n # return [scrapy.FormRequest(response=response)]\r\n # return [response]\r\n # print(\"1\"+text_json['msg'])\r\n\r\n ##if \"msg\" in text_json and text_json[\"msg\"] == \"登录成功\":\r\n ##print(\"successful!\")\r\n return [scrapy.FormRequest.from_response(response,\r\n url=post_url,\r\n formdata=postdata,\r\n headers=self.headers,\r\n meta={'cookiejar': response.meta['cookiejar']},\r\n callback=self.check_login\r\n )]\r\n def check_login(self, response):\r\n print (response.status)\r\n with open(\"index.html\", \"wb\") as f:\r\n f.write(response.text.encode('utf-8'))\r\n for url in self.start_urls:\r\n yield scrapy.Request(url=url,\r\n meta={'cookiejar': response.meta['cookiejar']},\r\n headers=self.headers,\r\n dont_filter=True\r\n )\r\n #yield scrapy.Request(url, dont_filter=True, headers=self.headers)\r\n # response = session.get(\"https://www.zhihu.com\", headers=self.headers)\r\n # with open(\"index_page1.html\", \"wb\") as f:\r\n # f.write(response.text.encode('utf-8'))","repo_name":"yupei0318cs/QuestionAnswerWeb","sub_path":"spiders/zhihu.py","file_name":"zhihu.py","file_ext":"py","file_size_in_byte":5972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"28716261481","text":"\"\"\"\nRoom Cleaning using robot\n\nApproach: We can take a Visited list which can store cells we clean and run DFS to\ndo the actual cleaning\n\"\"\"\n# This is the robot's control interface.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n#class Robot:\n# def move(self):\n# \"\"\"\n# Returns true if the cell in front is open and robot moves into the cell.\n# Returns false if the cell in front is blocked and robot stays in the current cell.\n# :rtype bool\n# \"\"\"\n#\n# def turnLeft(self):\n# \"\"\"\n# Robot will stay in the same cell after calling turnLeft/turnRight.\n# Each turn will be 90 degrees.\n# :rtype void\n# \"\"\"\n#\n# def turnRight(self):\n# \"\"\"\n# Robot will stay in the same cell after calling turnLeft/turnRight.\n# Each turn will be 90 degrees.\n# :rtype void\n# \"\"\"\n#\n# def clean(self):\n# \"\"\"\n# Clean the current cell.\n# :rtype void\n# \"\"\"\n\nclass Solution:\n def cleanRoom(self, robot):\n \"\"\"\n :type robot: Robot\n :rtype: None\n \"\"\"\n self.robot = robot\n self.robot.clean()\n self.visited = [(0,0)]\n self.dfs(0, 0)\n \n def dfs(self, x, y):\n if (x-1, y) not in self.visited and self.up():\n self.robot.clean()\n self.visited.append((x-1, y))\n self.dfs(x-1, y)\n self.down()\n if (x, y-1) not in self.visited and self.left():\n self.robot.clean()\n self.visited.append((x, y-1))\n self.dfs(x, y-1)\n self.right()\n if (x+1, y) not in self.visited and self.down():\n self.robot.clean()\n self.visited.append((x+1, y))\n self.dfs(x+1, y)\n self.up()\n if (x, y+1) not in self.visited and self.right():\n self.robot.clean()\n self.visited.append((x, y+1))\n self.dfs(x, y+1)\n self.left()\n \n \n def up(self):\n return self.robot.move()\n \n def left(self):\n self.robot.turnLeft()\n result = self.robot.move()\n self.robot.turnRight()\n return result\n \n def right(self):\n self.robot.turnRight()\n result = self.robot.move()\n self.robot.turnLeft()\n return result\n \n def down(self):\n self.robot.turnLeft()\n self.robot.turnLeft()\n result = self.robot.move()\n self.robot.turnRight()\n self.robot.turnRight()\n return result\n","repo_name":"plawanrath/Leetcode_Python","sub_path":"RobotRoomCleaner.py","file_name":"RobotRoomCleaner.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"9110032394","text":"from collections import defaultdict\ncom_num = int(input())\ncom_pair_num = int(input())\n\ncom_pair_dict = defaultdict(list)\nfor _ in range(com_pair_num):\n _c1, _c2 = map(int, input().split())\n com_pair_dict[_c2].append(_c1)\n com_pair_dict[_c1].append(_c2)\n\nvisited = [0] * (com_num+1)\nstack = [1]\nresult = -1\nwhile stack:\n curr_com = stack.pop()\n visited[curr_com] = 1\n result += 1\n for next_com in com_pair_dict[curr_com]:\n if not visited[next_com] and next_com not in stack:\n stack.append(next_com)\n\nprint(result)\n","repo_name":"nakevin96/AlogirithmPrac","sub_path":"algo_prac/beakjoon_2606.py","file_name":"beakjoon_2606.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"3064779256","text":"from collections import defaultdict\nfrom typing import List\n\n\n# 枚举 + 哈希表\nclass Solution:\n def numberOfBoomerangs(self, points: List[List[int]]) -> int:\n ans = 0\n for p in points:\n c = defaultdict(int)\n for q in points:\n c[(p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1])] += 1\n for v in c.values():\n ans += v * (v - 1)\n return ans\n","repo_name":"papilong123/LeetCode","sub_path":"python/hash_table/$447_NumberOfBoomerangs.py","file_name":"$447_NumberOfBoomerangs.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"37525005424","text":"# #100days of code - day 15 - Coffee Machine\n\nLOGO = \"\"\"\n ##### ####### ####### ####### ####### # # # ##### # # ### # # ####### \n # # # # # # # ## ## # # # # # # # ## # # \n # # # # # # # # # # # # # # # # # # # # \n # # # ##### ##### ##### # # # # # # ####### # # # # ##### \n # # # # # # # # ####### # # # # # # # # \n # # # # # # # # # # # # # # # # # ## # \n ##### ####### # # ####### # # # # ##### # # ### # # ####### \n\"\"\"\n\nMENU = {\n \"espresso\": {\n \"ingredients\": {\n \"water\": 50,\n \"coffee\": 18,\n },\n \"cost\": 1.5,\n },\n \"latte\": {\n \"ingredients\": {\n \"water\": 200,\n \"milk\": 150,\n \"coffee\": 24,\n },\n \"cost\": 2.5,\n },\n \"cappuccino\": {\n \"ingredients\": {\n \"water\": 250,\n \"milk\": 100,\n \"coffee\": 24,\n },\n \"cost\": 3.0,\n }\n}\n\nresources = {\n \"water\": 300,\n \"milk\": 200,\n \"coffee\": 100,\n}\n\nmoney_in_machine = 0\n\n\ndef print_report():\n \"\"\" Print status of resources in coffee machine. No return\"\"\"\n print(\" => ЁЯУД RESOURCES IN MACHINE REPORT: ЁЯУД\")\n print(\" => Water: \" + str(resources[\"water\"]) + \" ml\")\n if resources[\"water\"] == 0:\n print(\" => !!!! You should add some water!\")\n print(\" => Milk: \" + str(resources[\"milk\"]) + \" ml\")\n if resources[\"milk\"] == 0:\n print(\" => !!!! You should add some milk!\")\n print(\" => Coffee: \" + str(resources[\"coffee\"]) + \" g\")\n if resources[\"coffee\"] == 0:\n print(\" => !!!! You should add some coffee!\")\n print(f\" => Money: $\" + \"%.2f\" % money_in_machine + \"\\n\")\n return\n\n\ndef check_resources(drink):\n \"\"\"Function is checking sufficient resources to prepare drink in input\n Return: 1 if there are sufficient resources, 0 otherwise\"\"\"\n # print(\"Drink cost: \" + str(MENU[drink][\"cost\"]))\n need_water = MENU.get(drink).get(\"ingredients\").get(\"water\", 0)\n need_milk = MENU.get(drink).get(\"ingredients\").get(\"milk\", 0)\n need_coffee = MENU.get(drink).get(\"ingredients\").get(\"coffee\", 0)\n # print(f\"We need: Water: {need_water}, milk: {need_milk} and coffee: {need_coffee}\")\n existing_water = resources[\"water\"]\n existing_milk = resources[\"milk\"]\n existing_coffee = resources[\"coffee\"]\n # print(f\"We have: Water: {existing_water}, milk: {existing_milk} and coffee: {existing_coffee}\")\n if existing_water >= need_water and existing_milk >= need_milk and existing_coffee >= need_coffee:\n # print(\"We have all ingredients\")\n return 1\n elif existing_water < need_water:\n print(\"! тЪая╕ПSorry there is not enough water. :( Choose another drink.\")\n return 0\n elif existing_milk < need_milk:\n print(\"! тЪая╕ПSorry there is not enough milk. :( Choose another drink.\")\n return 0\n elif existing_coffee < need_coffee:\n print(\"! тЪая╕ПSorry there is not enough coffee. :( Choose another drink.\")\n return 0\n else:\n return 0\n\n\ndef payment_for_drink(drink):\n \"\"\"Process payment for drink in input.\n Returns: 1 if paid, 0 - otherwise\"\"\"\n global money_in_machine\n to_pay = MENU.get(drink).get(\"cost\", 0)\n print(f\"Amount to pay for {drink}: $\" + \"%.2f\" % to_pay) # formatted like a price\n print(\"Please insert coins:\")\n try:\n quarters = int(input(\"How many quarters?: \")) # quarter = $0.25\n except ValueError:\n print(\"! тЪая╕ПWrong number. Count as 0.\")\n quarters = 0\n try:\n dimes = int(input(\"How many dimes?: \")) # dime = $0.1\n except ValueError:\n print(\"! тЪая╕ПWrong number. Count as 0.\")\n dimes = 0\n try:\n nickles = int(input(\"How many nickles?: \")) # nickel = $0.05\n except ValueError:\n print(\"! тЪая╕ПWrong number. Count as 0.\")\n nickles = 0\n try:\n pennies = int(input(\"How many pennies?: \")) # penny = $0.01\n except ValueError:\n print(\"! тЪая╕ПWrong number. Count as 0.\")\n pennies = 0\n user_inserted = quarters*0.25 + dimes*0.1 + nickles*0.05 + pennies*0.01\n print(f\"You inserted $\" + \"%.2f\" % user_inserted + \" in coins.\")\n if user_inserted == to_pay:\n money_in_machine += to_pay\n return 1\n elif user_inserted > to_pay:\n money_in_machine += to_pay\n print(f\"Here is ${round(user_inserted-to_pay,2)} in change.\")\n return 1\n else:\n print(\"! тЪая╕ПSorry that's not enough money. Money refunded.\")\n return 0\n\n\ndef prepare_drink(drink):\n # existing_water = resources[\"water\"]\n # existing_milk = resources[\"milk\"]\n # existing_coffee = resources[\"coffee\"]\n need_water = MENU.get(drink).get(\"ingredients\").get(\"water\", 0)\n need_milk = MENU.get(drink).get(\"ingredients\").get(\"milk\", 0)\n need_coffee = MENU.get(drink).get(\"ingredients\").get(\"coffee\", 0)\n resources[\"water\"] -= need_water\n resources[\"milk\"] -= need_milk\n resources[\"coffee\"] -= need_coffee\n\n print(f\"тШХ Here is your {drink}. Enjoy!\")\n return\n\n\ndef ask_user():\n user_choice = input(\"What would you like? (espresso/latte/cappuccino): \").lower()\n if user_choice == \"off\":\n print(\"ЁЯЪз ЁЯФз Maintenance - machine turned off ЁЯФз ЁЯЪз\")\n exit()\n elif user_choice == \"report\":\n print_report()\n elif user_choice == \"espresso\" or user_choice == \"e\":\n if check_resources(\"espresso\") == 1:\n if payment_for_drink(\"espresso\") == 1:\n prepare_drink(\"espresso\")\n elif user_choice == \"latte\" or user_choice == \"l\":\n if check_resources(\"latte\") == 1:\n if payment_for_drink(\"latte\") == 1:\n prepare_drink(\"latte\")\n elif user_choice == \"cappuccino\" or user_choice == \"c\":\n if check_resources(\"cappuccino\") == 1:\n if payment_for_drink(\"cappuccino\") == 1:\n prepare_drink(\"cappuccino\")\n else:\n print(\"! тЪая╕ПSorry. We don't have such drink!\")\n return\n\n\nwhile True:\n print(LOGO)\n ask_user()\n","repo_name":"IrekBigaj/Python_exercises","sub_path":"cofee_machine.py","file_name":"cofee_machine.py","file_ext":"py","file_size_in_byte":6307,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"41156325106","text":"class ListNode:\n def __init__(self, val):\n self.val = val\n self.next = None\n\nclass MyHashSet:\n def __init__(self, capacity=10):\n self.capacity = capacity\n self.data = [None] * capacity\n \n def add(self, key):\n index = key % self.capacity\n node = self.data[index]\n if self.contains(key) is True:\n return\n if self.contains(key) is False:\n if node == None:\n self.data[index] = ListNode(key)\n return\n else:\n while node.next is not None:\n node = node.next \n node.next = ListNode(key) \n\n def contains(self, key):\n index = key % self.capacity\n node = self.data[index] \n if node == None:\n return False\n else:\n while node is not None and node.val != key:\n node = node.next\n if node is not None:\n return True\n else: \n return False\n \n def remove(self, key): \n index = key % self.capacity\n node = self.data[index] \n if node == None:\n return\n else:\n while node is not None and node.val != key:\n node = node.next\n if node is not None:\n node.val = None\n node = node.next\n return \n else: \n return \n","repo_name":"pignini/as","sub_path":"Leetcode/705_Design HashSet_06170129.py","file_name":"705_Design HashSet_06170129.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"28432797267","text":"from nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import PorterStemmer\n\nstemming = PorterStemmer()\nstop_list = set(stopwords.words('english'))\n\nimport re\nreg = re.compile(r'[a-zA-Z]')\n\ndef remove_noise(quote_word):\n words = word_tokenize(quote_word)\n currentQuote = []\n for word in words:\n if word not in stop_list and word.isalpha() and word not in [\",\", \".\", \"!\", \" \", \";\"] and reg.match(word):\n currentQuote.append(stemming.stem(word.lower()))\n\n return \" \".join(currentQuote)\n\n","repo_name":"spaden/analytics_app","sub_path":"nlp/myapp/remove_noise.py","file_name":"remove_noise.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17884828535","text":"'''\n\nCreate a class named User and create a way to check the number of users (number of instances) were created, so that the value can be \naccessed as a class attribute.\n\nExamples\nu1 = User(\"johnsmith10\")\nUser.user_count ➞ 1\n\nu2 = User(\"marysue1989\")\nUser.user_count ➞ 2\n\nu3 = User(\"milan_rodrick\")\nUser.user_count ➞ 3\nMake sure that the usernames are accessible via the instance attribute username.\n\nu1.username ➞ \"johnsmith10\"\n\nu2.username ➞ \"marysue1989\"\n\nu3.username ➞ \"milan_rodrick\"\n\n'''\n\nclass User:\n count = 0\n def __init__(self,u_name):\n self.uname = u_name\n User.count += 1\n\n\n'''\n\nCreate a function which takes a list of objects from the class IceCream and returns the sweetness value of the sweetest icecream. \nNote that there is a class is provided for you in the Tests tab.\n\nclass IceCream:\n def __init__(self, flavor, num_sprinkles):\n self.flavor = flavor\n self.num_sprinkles = num_sprinkles\nEach sprinkle has a sweetness value of 1\nCheck below for the sweetness values of the different flavors.\n\nFlavors \tSweetness Value\nPlain\t 0\nVanilla \t5\nChocolateChip\t5\nStrawberry \t10\nChocolate\t 10\n\nExamples\nice1 = IceCream(\"Chocolate\", 13) # value of 23\nice2 = IceCream(\"Vanilla\", 0) # value of 5\nice3 = IceCream(\"Strawberry\", 7) # value of 17\nice4 = IceCream(\"Plain\", 18) # value of 18\nice5 = IceCream(\"ChocolateChip\", 3) # value of 8\nsweetest_icecream([ice1, ice2, ice3, ice4, ice5]) ➞ 23\n\nsweetest_icecream([ice3, ice1]) ➞ 23\n\nsweetest_icecream([ice3, ice5]) ➞ 17\n\nWrite a Python program to find intersection of two given arrays using Lambda. Go to the editor\nOriginal arrays:\n[1, 2, 3, 5, 7, 8, 9, 10]\n[1, 2, 4, 8, 9]\nIntersection of the said arrays: [1, 2, 8, 9]\n\n'''\n\nl1 = [1, 2, 3, 5, 7, 8, 9, 10]\nl2 = [1, 2, 4, 8, 9]\nresults = list(filter(lambda i: i in l1,l2))\nprint(results)","repo_name":"Sandeep165/PYTHON_M1","sub_path":"Day_31/practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"20"} +{"seq_id":"39360556606","text":"import re\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.preprocessing import LabelEncoder\n\n# Define a list of common English stopwords\nstop_words = set([\n \"ourselves\", \"hers\", \"between\", \"yourself\", \"but\",\n \"again\", \"there\", \"about\", \"once\", \"during\", \"out\",\n \"very\", \"having\", \"with\", \"they\", \"own\", \"an\", \"be\",\n \"some\", \"for\", \"do\", \"its\", \"yours\", \"such\", \"into\",\n \"of\", \"most\", \"itself\", \"other\", \"off\", \"is\", \"s\", \"am\",\n \"or\", \"who\", \"as\", \"from\", \"him\", \"each\", \"the\", \"themselves\",\n \"until\", \"below\", \"are\", \"we\", \"these\", \"your\", \"his\", \"through\",\n \"don\", \"nor\", \"me\", \"were\", \"her\", \"more\", \"himself\", \"this\",\n \"down\", \"should\", \"our\", \"their\", \"while\", \"above\", \"both\", \"up\",\n \"to\", \"ours\", \"had\", \"she\", \"all\", \"no\", \"when\", \"at\", \"any\", \"before\",\n \"them\", \"same\", \"and\", \"been\", \"have\", \"in\", \"will\", \"on\", \"does\",\n \"yourselves\", \"then\", \"that\", \"because\", \"what\", \"over\", \"why\", \"so\",\n \"can\", \"did\", \"not\", \"now\", \"under\", \"he\", \"you\", \"herself\", \"has\", \"just\",\n \"where\", \"too\", \"only\", \"myself\", \"which\", \"those\", \"i\", \"after\", \"few\",\n \"whom\", \"t\", \"being\", \"if\", \"theirs\", \"my\", \"against\", \"a\", \"by\", \"doing\",\n \"it\", \"how\", \"further\", \"was\", \"here\", \"than\"\n])\n\n# Function to preprocess text\n\n\ndef preprocess_text(text):\n # Lowercase the text\n text = text.lower()\n # Remove punctuation\n text = re.sub(r'[^\\w\\s]', '', text)\n # Tokenize and remove stop words\n words = text.split()\n words = [word for word in words if word not in stop_words]\n # Return the processed text\n return ' '.join(words)\n","repo_name":"Maggodbz/GraphClassification","sub_path":"notebooks/src/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"29167920471","text":"from twilio.rest import Client\nimport time\nimport random\nimport os\nfrom dotenv import load_dotenv\nimport requests\nimport json\n\n\ndef main():\n load_dotenv()\n account_sid = os.getenv(\"TWILIO_SID\")\n auth_token = os.getenv(\"TWILIO_TOKEN\")\n twilio_number = os.getenv(\"TWILIO_NUMBER\")\n whatsapp_number = os.getenv(\"WHATSAPP_NUMBER\")\n client = Client(account_sid, auth_token)\n\n while True:\n subreddits = [\"https://meme-api.herokuapp.com/gimme/MAUU/1\",\n \"https://meme-api.herokuapp.com/gimme/DylanteroYT/1\",\n \"https://meme-api.herokuapp.com/gimme/linuxmemes/1\"]\n\n url = random.choice(subreddits)\n x = requests.get(url)\n parse_json = json.loads(x.text)\n image = parse_json[\"memes\"][0][\"url\"]\n message = client.messages.create(\n from_=f'whatsapp:{twilio_number}',\n body=f'{parse_json[\"memes\"][0][\"title\"]}',\n to=f'whatsapp:{whatsapp_number}',\n media_url=f'{image}'\n )\n\n print(message.sid)\n # send a image every 1 hour\n time.sleep(3600)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"paij0se/whatsapp-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"20"}