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 \"\"\".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}
', 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 = '