diff --git "a/4020.jsonl" "b/4020.jsonl" new file mode 100644--- /dev/null +++ "b/4020.jsonl" @@ -0,0 +1,902 @@ +{"seq_id":"35054496228","text":"import hashlib\nfrom pathlib import Path\n\nclass FileHandler:\n\n def __init__(self, resource_path: Path):\n self._resource_path = resource_path\n\n def write_file(self, path: Path, data: bytes):\n full_path = self._resource_path / path\n full_path.parent.mkdir(parents=True, exist_ok=True)\n with open(full_path, \"wb\") as f:\n f.write(data)\n print(\"Wrote file \" + str(path))\n \n def get_hashes(self, path=None):\n if path is None:\n path = self._resource_path\n if path.is_dir():\n hashes = {}\n for sub_path in path.iterdir():\n hashes.update(self.get_hashes(sub_path))\n else:\n if path.name == \".gitignore\":\n return {}\n with open(path, \"rb\") as f:\n data = f.read()\n checksum = hashlib.md5(data).hexdigest()\n # Represent as a POSIX path (forward slashes) on Windows too, since\n # Core and the component need to agree\n relative_path = path.relative_to(self._resource_path).as_posix()\n hashes = { relative_path: checksum }\n return hashes","repo_name":"kulturkrock/screencrash-components","sub_path":"audio/src/file_handler.py","file_name":"file_handler.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"3992315643","text":"\"\"\"\nMain Entry Point\n\"\"\"\n\nfrom __future__ import print_function\nimport traceback\nfrom alexa_intent import Intent\nfrom intent_funcs import milestone_handler_func, briefing_handler_func, error_handler_func, cancel_handler_func, help_handler_func\n\ndef handle_intent(intent):\n if intent.request.type == \"IntentRequest\":\n intent_name = intent.request.intent.name\n \n if intent_name == \"IntentActivity\":\n intent.func = milestone_handler_func\n elif intent_name == \"AMAZON.CancelIntent\" or intent_name == \"AMAZON.StopIntent\":\n intent.func = cancel_handler_func\n elif intent_name == \"AMAZON.HelpIntent\":\n intent.func = help_handler_func\n elif intent.request.type == \"LaunchRequest\":\n intent.func = briefing_handler_func\n else:\n intent.func = error_handler_func\n \n return intent.execute()\n\ndef lambda_handler(event, context):\n \"\"\" Route the incoming request based on type (LaunchRequest, IntentRequest,\n etc.) The JSON body of the request is provided in the event parameter.\n \"\"\"\n #print(\"event.session.application.applicationId=\" + event['session']['application']['applicationId'])\n\n #if event['session']['new']:\n # on_session_started({'requestId': event['request']['requestId']},event['session'])\n \n intent = None\n try:\n intent = Intent(**event)\n return handle_intent(intent)\n except Exception as ex:\n err = traceback.format_exc()\n print(err)\n return error_handler_func(intent,msg=str(err))","repo_name":"salendron/alexa-skill-little-light","sub_path":"lambda/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"17578472842","text":"# twitter api\n\nimport requests\nfrom requests_oauthlib import OAuth1 # authorize request\nfrom donthackme import *\n\n\nauth = OAuth1(CONSUMER_KEY, CONSUMER_SECRET, TOKEN, TOKEN_SECRET)\n\ndef verify_credentials():\n # api url\n url = 'https://api.twitter.com/1.1/account/verify_credentials.json'\n verify_response = requests.get(url, auth=auth)\n assert(verify_response.status_code == 200)\n\ndef search_query(query,result_type):\n search_url = 'https://api.twitter.com/1.1/search/tweets.json'\n params = {'q': query, 'result_type': result_type}\n search_response = requests.get(search_url, params=params, auth=auth)\n assert(search_response.status_code == 200)\n return search_response\n\n\n\nverify_credentials()\n\n\n\n# search\nquery = 'data science'\nresult_type = 'recent'\nsearch_response = search_query(query,result_type)\n\nimport pprint\nre_json = search_response.json()\npprint.pprint( re_json['statuses'][0] ) # statuses = tweets\n\n#re_json.get('statuses', [] ) # advanced?!\n#re_json.get('statuses', [{}] )[0] # ...\n\n\n\n# streaming api\n\nimport json\nfrom itertools import islice\nparams = {'track': '#Trump'}\n#params = {'track': '#python'}\nr = requests.post('https://stream.twitter.com/1.1/statuses/filter.json',\n params=params, auth=auth, stream=True)\ntweets = r.iter_lines()\nfor tweet in tweets: #islice(tweets, 20):\n if tweet:\n tmp = json.loads( tweet.decode('utf-8') )\n print(tmp['text'])\n else:\n print('Timeout.')\n\nr.close()\n","repo_name":"danielosen/DataScience","sub_path":"old/twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"35001328467","text":"import os\nfrom lib.colors import *\nimport logging\nimport netifaces\n\nclass monitorMode(object):\n\n def __init__(self):\n self.__interface = None\n\n def interface(self, iface):\n self.__interface = iface\n return self.__interface\n\n def enable_air(self):\n cmd = os.system(\"airmon-ng check kill\")\n if cmd == 32512:\n return False\n os.system(\"airmon-ng start {}\".format(self.__interface))\n return True\n\n def disable_air(self):\n os.system(\"airmon-ng stop {}\".format(self.__interface))\n\n def enable_iw(self):\n os.system(\"ifconfig {} down\".format(self.__interface))\n os.system(\"iwconfig {} mode monitor\".format(self.__interface))\n os.system(\"ifconfig {} up\".format(self.__interface))\n\n def disable_iw(self):\n os.system(\"ifconfig {} down\".format(self.__interface))\n os.system(\"iwconfig {} mode managed\".format(self.__interface))\n os.system(\"ifconfig {} up\".format(self.__interface))\n\n def Main(self):\n if not self.enable_air():\n self.enable_iw()\n else:\n return True\n\nclass interfaces(monitorMode):\n\n def __init__(self):\n self._ifaces = None\n\n def get_ifaces(self):\n self._ifaces = netifaces.interfaces()\n return self._ifaces\n \n def get_wlan(self):\n ifaces = self.get_ifaces()\n for iface in ifaces:\n if iface.endswith(\"mon\"):\n return [iface, True]\n elif iface.startswith(\"wl\") or iface.startswith(\"ath\") and not iface.endswith(\"mon\"):\n self.interface(iface)\n return [iface, False]\n return None\n\n def checking(self):\n if self.get_wlan() == None:\n for x, y in enumerate(self._ifaces):\n print(\"[{2}{0}{3}] {4}{1}{3}\".format(x+1, y, LRED, RST, RD))\n choose = int(input(\"\\nSelect your wireless interface: \"))\n if choose > len(self._ifaces) or 1 > choose:\n print(\"Choose one of the numbers\")\n os._exit(1)\n self.interface(self._ifaces[choose-1])\n self.Main()\n return self._ifaces[choose-1] + \"mon\"\n try:\n wlaniface = self.get_wlan()\n if wlaniface[1] == True:\n return wlaniface[0]\n elif wlaniface[1] == False:\n self.Main()\n return wlaniface[0] + \"mon\"\n except:\n pass\n \n","repo_name":"THE4W350M3R00T/takeover","sub_path":"lib/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"29610062578","text":"# -*- coding: utf-8 -*-\n\"\"\"\nBinary Search Tree \nhttps://www.laurentluce.com/posts/binary-search-tree-library-in-python/comment-page-1/\nCreated on Thu Feb 22 11:38:50 2018\n\n@author: Alex\n\"\"\"\n\nclass Node:\n \"\"\"\n Tree node: left and right child + data which can be any object\n \"\"\"\n def __init__(self, data):\n \"\"\"\n Node constructor\n @param data node object\n \"\"\"\n self.left = None\n self.right = None\n self.data = data\n\n def insert(self,data):\n \"\"\"\n Insert new node with data\n @param data node data object to insert\n \"\"\"\n if self.data:\n if data < self.data:\n if self.left is None:\n self.left = Node(data)\n else:\n self.left.insert(data)\n elif data > self.data:\n if self.right is None:\n self.right = Node(data)\n else:\n self.right.insert(data)\n else:\n self.data = data\n ","repo_name":"apalom/CS6140_DataMining","sub_path":"CS6140_A3_Clustering/bst_nodeClass.py","file_name":"bst_nodeClass.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"38271679660","text":"# 5 Layer DNN for digits 0 to 4 of MNIST\n# 100 neurons in each layer\n# ADAM optimization and early stopping\n\n# Import modules and data\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow.contrib.layers import fully_connected, batch_norm, dropout\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# Set random seed\ntf.set_random_seed(123)\nnp.random.seed(123)\n\nn_inputs = 28 * 28\nn_hidden_1 = 100\nn_hidden_2 = 100\nn_hidden_3 = 100\nn_hidden_4 = 100\nn_hidden_5 = 100\n\nlearning_rate = 0.005\n\n# Use only digits 0 to 4\nn_outputs = 5\n\n# Get data and separate digits 0-4 out\nmnist = input_data.read_data_sets(\"/tmp/data/\")\nX_images, y_images = mnist.train.images, mnist.train.labels\nX_images_test, y_images_test = mnist.test.images, mnist.test.labels\n\n# Create 'index' and subset of MNIST\nindices = [idx for idx in range(len(y_images)) if y_images[idx] < 5]\nX_masked_train = X_images[indices]\ny_masked_train = y_images[indices]\n\n# Do same for test set\nindices_test = [idx for idx in range(len(y_images_test)) if y_images_test[idx] < 5]\nX_test = X_images_test[indices_test]\ny_test = y_images_test[indices_test]\n\nvalidation_metrics = {\n \"accuracy\":\n tf.contrib.learn.MetricSpec(\n metric_fn=tf.contrib.metrics.streaming_accuracy,\n prediction_key=tf.contrib.learn.prediction_key.PredictionKey.CLASSES)}\n\nvalidation_monitor = tf.contrib.learn.monitors.ValidationMonitor(\n x=X_test, y=y_test, early_stopping_rounds=50, metrics=validation_metrics)\n\n# Construct graph\n# Use He initalization\nhe_init = tf.contrib.layers.variance_scaling_initializer()\n\nX = tf.placeholder(tf.float32, shape=(None, n_inputs), name='X')\ny = tf.placeholder(tf.int64, shape=(None), name='y')\n\n# Set up necessary variables for batch norm\nis_training = tf.placeholder(tf.bool, shape=(), name='Is_Training')\nbn_params = {'is_training': is_training, 'decay': 0.999, 'updates_collections': None}\n\n# Set up drop out regularization\nkeep_prob = 0.5\n\nwith tf.contrib.framework.arg_scope([fully_connected],\n normalizer_fn=batch_norm, normalizer_params=bn_params,\n weights_initializer=he_init, scope='DNN'):\n X_drop = dropout(X, keep_prob, is_training=is_training)\n hidden_1 = fully_connected(X_drop, n_hidden_1,\n activation_fn=tf.nn.elu, scope='Hidden_1')\n hidden_1_drop = dropout(hidden_1, keep_prob, is_training=is_training)\n hidden_2 = fully_connected(hidden_1_drop,\n n_hidden_2, activation_fn=tf.nn.elu, scope='Hidden_2')\n hidden_2_drop = dropout(hidden_2, keep_prob, is_training=is_training)\n hidden_3 = fully_connected(hidden_2_drop,\n n_hidden_3, activation_fn=tf.nn.elu, scope='Hidden_3')\n hidden_3_drop = dropout(hidden_3, keep_prob, is_training=is_training)\n hidden_4 = fully_connected(hidden_3_drop,\n n_hidden_4, activation_fn=tf.nn.elu, scope='Hidden_4')\n hidden_4_drop = dropout(hidden_4, keep_prob, is_training=is_training)\n hidden_5 = fully_connected(hidden_4_drop,\n n_hidden_5, activation_fn=tf.nn.elu, scope='Hidden_5')\n hidden_5_drop = dropout(hidden_5, keep_prob, is_training=is_training)\n logits = fully_connected(hidden_5_drop,\n n_outputs, activation_fn=None, scope='Outputs')\n\nwith tf.name_scope('Loss'):\n xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=logits)\n loss = tf.reduce_mean(xentropy, name='Loss')\n\nwith tf.name_scope('Train'):\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\n training_op = optimizer.minimize(loss)\n\nwith tf.name_scope('Eval'):\n correct = tf.nn.in_top_k(logits, y, 1)\n accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n\ninit = tf.global_variables_initializer()\n\n# Execution\nn_epochs = 1000\nbatch_size = 200\nbatches = len(y_masked_train)//batch_size\n\nwith tf.Session() as sess:\n init.run()\n for epoch in range(n_epochs):\n for k in range(batches):\n X_batch = X_masked_train[k*batch_size:k*batch_size+batch_size]\n y_batch = y_masked_train[k*batch_size:k*batch_size+batch_size]\n sess.run(training_op, feed_dict={is_training: True, X: X_batch, y: y_batch})\n # print('Max logits: ', max_logits.eval(feed_dict={X: X_test}))\n # print('Max labels: ', max_labels.eval(feed_dict={y: y_test}))\n acc_train = accuracy.eval(feed_dict={is_training: False, X: X_batch, y: y_batch})\n acc_test = accuracy.eval(feed_dict={is_training: False, X: X_test, y: y_test})\n if epoch % 5 == 0:\n print(epoch, \"Train accuracy: \", acc_train, \"Test accuracy: \", acc_test)\n","repo_name":"KT12/hands_on_machine_learning","sub_path":"5_layer_dnn.py","file_name":"5_layer_dnn.py","file_ext":"py","file_size_in_byte":4533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36437898666","text":"# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %%\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn\nimport skill_metrics as sm\nimport torch\nfrom pytorch_lightning import Trainer\nfrom torch.utils.data import DataLoader\n\nfrom src.dataset import CERDataset\nfrom src.mlp import MLPLucas\n\nseaborn.set()\n\nHORIZONS = 12\nDECOMP_METHOD = \"2fft\"\n\ncomplexos = {\n \"Amontada\": [\"BC\", \"IG\", \"RIB\"],\n \"Caldeirao\": [\n \"Santa_Angelina\",\n \"Santa_Barbara\",\n \"Santa_Edwiges\",\n \"Santa_Fatima\",\n \"Santa_Regina\",\n \"Santo_Adriano\",\n \"Santo_Albano\",\n ],\n \"Icarai\": [\"Icarai_I\", \"Icarai_II\"],\n \"Riachao\": [\"Riachao_I\", \"Riachao_II\", \"Riachao_IV\", \"Riachao_VI\", \"Riachao_VII\",],\n \"Taiba\": [\"Aguia\", \"Andorinha\", \"Colonia\"],\n}\nsteps = [\"30_min\", \"1_day\"]\nmeses = [\"Sep\", \"Oct\", \"Nov\", \"Dec\"]\nresults = {}\nfor COMPLEXO_EOLICO, centrais in complexos.items():\n for CENTRAL_EOLICA in centrais:\n for TIME_STEP in steps:\n BATCH_SIZE = 128\n WINDOW = 3\n EPOCHS = 30\n if TIME_STEP == \"1_day\":\n WINDOW = 10\n BATCH_SIZE = 16\n EPOCHS = 50\n for MES in meses:\n DECOMP = True\n DEVICE = torch.device(\"cuda\")\n if not os.path.exists(\n f\"data/components/{CENTRAL_EOLICA}_{MES}_{TIME_STEP}\"\n ):\n os.system(\n f\"mkdir data/components/{CENTRAL_EOLICA}_{MES}_{TIME_STEP}\"\n )\n if not os.path.exists(f\"data/out/{COMPLEXO_EOLICO}\"):\n os.system(f\"mkdir data/out/{COMPLEXO_EOLICO}\")\n\n dataset_lucas = CERDataset(\n window=WINDOW,\n horizons=HORIZONS,\n complexo_eolico=COMPLEXO_EOLICO,\n central_eolica=CENTRAL_EOLICA,\n time_step=TIME_STEP,\n mes=MES,\n decomp=DECOMP,\n decomp_method=DECOMP_METHOD,\n )\n for i in range(HORIZONS):\n again = True\n while again:\n print(\n \"--------------------------------------------------------\"\n )\n print()\n print()\n print()\n print(\n f\"{COMPLEXO_EOLICO}->{CENTRAL_EOLICA}->{TIME_STEP}->{MES}\"\n )\n print(f\"Horizon: {i+1}\")\n dataset_lucas.set_type(\"train\")\n dataset_lucas.set_horizon(i)\n train_loader_lucas = DataLoader(\n dataset_lucas,\n batch_size=BATCH_SIZE,\n shuffle=True,\n num_workers=8,\n )\n input_example_lucas = next(iter(train_loader_lucas))[0]\n input_size_lucas = (\n input_example_lucas.shape[1] * input_example_lucas.shape[2]\n )\n\n mlp = MLPLucas(\n window_size=input_example_lucas.shape[1],\n n_comps=input_example_lucas.shape[2],\n horizons=1,\n )\n trainer = Trainer(gpus=1, max_epochs=EPOCHS)\n trainer.fit(mlp, train_dataloaders=train_loader_lucas)\n dataset_lucas.set_type(\"test\")\n mlp = mlp.cpu()\n X_test_lucas = dataset_lucas.samples\n y_mlp = (\n mlp(X_test_lucas).detach()\n / dataset_lucas.test_scaler.scale_\n )\n y_mlp = y_mlp.numpy()\n latest_loss = trainer.callback_metrics[\"train_loss\"].item()\n if TIME_STEP == \"30_min\":\n again = latest_loss > 0.01\n else:\n again = False\n if not again:\n if TIME_STEP == \"30_min\":\n res = [None] * 3 + [None] * i + y_mlp.tolist()\n else:\n ori_test_len = len(dataset_lucas.df_test)\n res = y_mlp[-ori_test_len:]\n res = np.array(res)\n if COMPLEXO_EOLICO not in results:\n results[COMPLEXO_EOLICO] = {}\n if CENTRAL_EOLICA not in results[COMPLEXO_EOLICO]:\n results[COMPLEXO_EOLICO][CENTRAL_EOLICA] = {}\n if (\n TIME_STEP\n not in results[COMPLEXO_EOLICO][CENTRAL_EOLICA]\n ):\n results[COMPLEXO_EOLICO][CENTRAL_EOLICA][TIME_STEP] = {}\n if (\n MES\n not in results[COMPLEXO_EOLICO][CENTRAL_EOLICA][\n TIME_STEP\n ]\n ):\n results[COMPLEXO_EOLICO][CENTRAL_EOLICA][TIME_STEP][\n MES\n ] = {}\n results[COMPLEXO_EOLICO][CENTRAL_EOLICA][TIME_STEP][MES][\n i + 1\n ] = res\n res = pd.DataFrame(\n results[COMPLEXO_EOLICO][CENTRAL_EOLICA][TIME_STEP][MES]\n )\n res = res.set_index(dataset_lucas.df_test[\"Timestamps\"])\n res.to_csv(\n f\"data/out/{COMPLEXO_EOLICO}/{CENTRAL_EOLICA}_{MES}_{TIME_STEP}.csv\",\n header=False,\n )\n","repo_name":"goncamateus/time_series","sub_path":"cer.py","file_name":"cer.py","file_ext":"py","file_size_in_byte":6246,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"8110458232","text":"# script to interogate clusters for GOI - convert gene names though\r\n# author Pete Thorpe 2022 march\r\n# imports\r\n\r\nimport os\r\nimport sys\r\nfrom optparse import OptionParser\r\nimport datetime\r\nimport logging\r\nimport logging.handlers\r\nimport time\r\nfrom collections import defaultdict\r\nfrom modules.database import parse_NCBI_gffcol9_info, test_line\r\n\r\n\r\n\r\n\r\ndef parse_file(infile, gene_to_up_or_down, gene_to_LFC, logger):\r\n \"\"\"func to parse the de results and writes the sig results\"\"\"\r\n count = 0\r\n name_set = set([])\r\n data = open (infile, \"r\")\r\n gene_names = set([])\r\n\r\n for line in data:\r\n if test_line(line):\r\n test = line.split()\r\n if len(test) !=3 : continue\r\n name, logfc, FDR = line.split()\r\n logfc = float(logfc)\r\n FDR = float(FDR)\r\n if name in name_set:\r\n # print(\"duplicate\", name)\r\n continue\r\n # add the name to the set \r\n name_set.add(name)\r\n if logfc > 0:\r\n gene_to_up_or_down[name] = \"up\"\r\n gene_to_LFC[name] = logfc\r\n # convert the negative to positive for easy testing\r\n if logfc < 0:\r\n gene_to_up_or_down[name] = \"down\"\r\n gene_to_LFC[name] = logfc\r\n return gene_to_up_or_down, gene_to_LFC\r\n\r\n\r\ndef parse_orthofinder(orthofinder, outfile, hu_gene_to_prot,\r\n mo_gene_to_prot,\r\n gene_to_up_or_down, gene_to_LFC,\r\n logger):\r\n \"\"\"fucn take in the GOI_set\r\n if the gene in the orthofinder output check if gene in cluster. \"\"\"\r\n f_in = open(orthofinder, \"r\")\r\n f_out = open(outfile, \"w\")\r\n matrix_found_count = 0\r\n for line in f_in:\r\n if test_line(line):\r\n elements = line.split()\r\n for protein in elements:\r\n # i thought it was a good idea to name the species\r\n # Homo_NP_001001331.1 get rid of that. \r\n if \"_\" in protein:\r\n protein = protein.replace(\"Homo_\", \"\")\r\n protein = protein.replace(\"Phy_\", \"\")\r\n protein = protein.replace(\"Mus_\", \"\")\r\n protein = protein.strip()\r\n LFC = gene_to_LFC[protein]\r\n print(protein)\r\n print(LFC)\r\n if float(LFC) > 0.4:\r\n out_data = \"%s (LOGFC = %s) \" % (protein, LFC)\r\n line = line.replace(protein, out_data)\r\n f_out.write(line)\r\n f_out.close()\r\n\r\n \r\nif \"-v\" in sys.argv or \"--version\" in sys.argv:\r\n print(\"v0.0.1\")\r\n sys.exit(0)\r\n\r\n\r\nusage = \"\"\"Use as follows:\r\n\r\n$ python interog....py -c orthofinder.clusters.txt\r\n--goi list_of_gene_of_interest -o outfile\r\n\r\n\"\"\"\r\n\r\nparser = OptionParser(usage=usage)\r\n\r\nparser.add_option(\"-c\", dest=\"orthofinder\",\r\n default=\"Orthogroups.txt\",\r\n help=\"Orthogroups.txt\")\r\n \r\n\r\nparser.add_option(\"--in1\", dest=\"in1\",\r\n default=\"/storage/home/users/sonia_vernes/human_mouse_bat_clustering/filtered_by_logFC_0.40_FDR_0.01/human_prot_id_LOGFC_0.40_FDR_0.01\",\r\n help=\"human filtered RNAseq results\")\r\n\r\nparser.add_option(\"--in2\", dest=\"in2\",\r\n default=\"/storage/home/users/sonia_vernes/human_mouse_bat_clustering/filtered_by_logFC_0.40_FDR_0.01/mouse_prot_id_LOGFC_0.40_FDR_0.01\",\r\n help=\"mouse filtered RNAseq results\")\r\n\r\nparser.add_option(\"--in3\", dest=\"in3\",\r\n default=\"/storage/home/users/sonia_vernes/human_mouse_bat_clustering/filtered_by_logFC_0.40_FDR_0.01/phydis_LOGFC_0.40_FDR_0.01\",\r\n help=\"phydis filtered RNAseq results\")\r\n\r\nparser.add_option(\"--hu\", dest=\"human\",\r\n default=\"human_gene_to_symblo.info\",\r\n help=\"human_gene_to_symblo.info\")\r\n\r\nparser.add_option(\"--mu\", dest=\"mouse\",\r\n default=\"mus_gene_to_symblo.info\",\r\n help=\"mus_gene_to_symblo.info\") \r\nparser.add_option(\"-o\", dest=\"outfile\",\r\n default=\"rewite_test\",\r\n help=\"out file\")\r\n\r\n\r\n\r\n(options, args) = parser.parse_args()\r\n\r\nin1 = options.in1\r\nin2 = options.in2\r\nin3 = options.in3\r\n\r\nhuman = options.human\r\nmouse = options.mouse\r\northofinder = options.orthofinder\r\noutfile = options.outfile\r\n\r\nlogfile = \"GOI_counts.log\" \r\n# Run as script\r\nif __name__ == '__main__':\r\n start_time = time.time()\r\n # Set up logging\r\n logger = logging.getLogger('get_GOI.py: %s'\r\n % time.asctime())\r\n logger.setLevel(logging.DEBUG)\r\n err_handler = logging.StreamHandler(sys.stderr)\r\n err_formatter = logging.Formatter('%(levelname)s: %(message)s')\r\n err_handler.setFormatter(err_formatter)\r\n logger.addHandler(err_handler)\r\n try:\r\n logstream = open(logfile, 'w')\r\n err_handler_file = logging.StreamHandler(logstream)\r\n err_handler_file.setFormatter(err_formatter)\r\n # logfile is always verbose\r\n err_handler_file.setLevel(logging.INFO)\r\n logger.addHandler(err_handler_file)\r\n except:\r\n logger.error(\"Could not open %s for logging\" %\r\n logfile)\r\n sys.exit(1)\r\n # get gene of interests\r\n # parse the matrix\r\n hu_gene_to_prot, hu_prot_id_to_gene, hu_gene_to_product, \\\r\n hu_prot_id_to_product = parse_NCBI_gffcol9_info(human)\r\n\r\n mo_gene_to_prot, mo_prot_id_to_gene, mo_gene_to_product, \\\r\n mo_prot_id_to_product = parse_NCBI_gffcol9_info(mouse)\r\n\r\n # set up some dictionaries to capture the data. \r\n gene_to_up_or_down = defaultdict(str)\r\n gene_to_LFC = defaultdict(float)\r\n # add the human data\r\n gene_to_up_or_down, gene_to_LFC = parse_file(in1, gene_to_up_or_down, gene_to_LFC, logger)\r\n # mouse\r\n gene_to_up_or_down, gene_to_LFC = parse_file(in2, gene_to_up_or_down, gene_to_LFC, logger)\r\n # bat \r\n gene_to_up_or_down, gene_to_LFC = parse_file(in3, gene_to_up_or_down, gene_to_LFC, logger) \r\n \r\n parse_orthofinder(orthofinder, outfile, hu_gene_to_prot,\r\n mo_gene_to_prot,\r\n gene_to_up_or_down, gene_to_LFC,\r\n logger)\r\n \r\n","repo_name":"peterthorpe5/PhyDis_RNAseq_and_more","sub_path":"Human_mouse_bats_clusters/re_write_orthofinder.py","file_name":"re_write_orthofinder.py","file_ext":"py","file_size_in_byte":6350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21324214287","text":"# ============================================================================\r\n# >> IMPORTS\r\n# ============================================================================\r\n# Python Imports\r\n# Math\r\nimport math\r\n# String\r\nimport string\r\n# Time\r\nimport time\r\n# Random\r\nfrom random import choice\r\nfrom random import randint\r\n\r\n# Source.Python Imports\r\n# Colors\r\nfrom colors import Color\r\n# Commands\r\nfrom commands.server import ServerCommand\r\n# Core\r\nfrom core import SOURCE_ENGINE_BRANCH\r\n# Cvars\r\nfrom cvars import ConVar\r\n# Effects\r\nfrom effects.base import TempEntity\r\n# Engines\r\nfrom engines.precache import Model\r\nfrom engines.server import queue_command_string\r\nfrom engines.server import execute_server_command\r\nfrom engines.trace import ContentMasks\r\nfrom engines.trace import engine_trace\r\nfrom engines.trace import GameTrace\r\nfrom engines.trace import Ray\r\nfrom engines.trace import TraceFilterSimple\r\n# Entities\r\nfrom entities import BaseEntityGenerator\r\nfrom entities import CheckTransmitInfo\r\nfrom entities import TakeDamageInfo\r\nfrom entities.constants import DamageTypes\r\nfrom entities.constants import MoveType\r\nfrom entities.entity import Entity\r\nfrom entities.helpers import index_from_edict\r\nfrom entities.helpers import index_from_inthandle\r\nfrom entities.helpers import index_from_pointer\r\nfrom entities.helpers import inthandle_from_pointer\r\nfrom entities.hooks import EntityCondition\r\nfrom entities.hooks import EntityPreHook\r\n# Events\r\nfrom events import Event\r\nfrom events.hooks import PreEvent\r\n# Filters\r\nfrom filters.players import PlayerIter\r\nfrom filters.recipients import RecipientFilter\r\n# Listeners\r\nfrom listeners.tick import Delay\r\nfrom listeners.tick import Repeat\r\nfrom listeners.tick import RepeatStatus\r\n# Mathlib\r\nfrom mathlib import Vector,QAngle\r\n# Memory\r\nfrom memory import make_object\r\n# Messages\r\nfrom messages import Fade\r\nfrom messages import FadeFlags\r\nfrom messages import HudMsg\r\nfrom messages import SayText2\r\nfrom messages import TextMsg\r\nfrom messages.base import Shake\r\n# Players\r\nfrom players.entity import Player\r\nfrom players.helpers import userid_from_edict\r\nfrom players.helpers import index_from_userid\r\nfrom players.helpers import playerinfo_from_userid\r\nfrom players.helpers import index_from_playerinfo\r\nfrom players.helpers import userid_from_index\r\nfrom players.helpers import edict_from_userid\r\nfrom players.helpers import inthandle_from_userid\r\nfrom players.helpers import playerinfo_from_index\r\n# Weapons\r\nfrom weapons.entity import Weapon\r\n# WCS Imports\r\nfrom wcs.core.players.entity import Player as WCSPlayer\r\nfrom wcs import wcsgroup\r\n# Headshot Immunity\r\nfrom players.constants import HitGroup\r\n\r\n\r\n# =============================================================================\r\n# >> GLOBAL VARIABLES\r\n# =============================================================================\r\nentity_health = {}\r\n_game_models = {}\r\n\r\nweapon_list = [\"weapon_ak47\",\"weapon_aug\",\"weapon_awp\",\"weapon_bizon\",\"weapon_c4\",\"weapon_cz75a\",\"weapon_deagle\",\"weapon_decoy\",\"weapon_elite\",\"weapon_famas\",\"weapon_fiveseven\",\"weapon_flashbang\",\"weapon_g3sg1\",\"weapon_galil\",\"weapon_galilar\",\"weapon_glock\",\"weapon_hegrenade\",\"weapon_incgrenade\",\"weapon_hkp2000\",\"weapon_knife\",\"weapon_m249\",\"weapon_m3\",\"weapon_m4a1\",\"weapon_m4a1_silencer\",\"weapon_mac10\",\"weapon_mag7\",\"weapon_molotov\",\"weapon_mp5navy\",\"weapon_mp7\",\"weapon_mp9\",\"weapon_negev\",\"weapon_nova\",\"weapon_p228\",\"weapon_p250\",\"weapon_p90\",\"weapon_sawedoff\",\"weapon_scar17\",\"weapon_scar20\",\"weapon_scout\",\"weapon_sg550\",\"weapon_sg552\",\"weapon_sg556\",\"weapon_ssg08\",\"weapon_smokegrenade\",\"weapon_taser\",\"weapon_tec9\",\"weapon_tmp\",\"weapon_ump45\",\"weapon_usp\",\"weapon_usp_silencer\",\"weapon_xm1014\",\"weapon_revolver\"]\r\n\r\nanti_falldamage = {}\r\nrepeat_dict = {}\r\nfor player in PlayerIter('all'):\r\n repeat_dict[player.userid] = 0\r\n\r\n\r\n# =============================================================================\r\n# >> SERVER COMMANDS\r\n# =============================================================================\r\n# A functional teleportation ultimate which will allow for adjusting all races with one code if velocity updates gets pushed out\r\n@ServerCommand('wcs_teleport_push')\r\ndef _push_teleport(command):\r\n userid = int(command[1])\r\n force = float(command[2])\r\n if exists(userid):\r\n player = Player.from_userid(userid)\r\n origin = player.origin\r\n coords = player.view_coordinates\r\n coords -= origin\r\n player.set_property_vector('localdata.m_vecBaseVelocity', coords*force)\r\n\r\n\r\n# Works and also provides the position math for wcs_doteleport\r\n@ServerCommand('wcs_teleport')\r\ndef _wcs_teleport(command):\r\n userid = int(command[1])\r\n x = float(command[2])\r\n y = float(command[3])\r\n z = float(command[4])\r\n target_location = Vector(x,y,z,)\r\n player = Player.from_userid(userid)\r\n origin = player.origin\r\n angles = QAngle(*player.get_property_vector('m_angAbsRotation'))\r\n forward = Vector()\r\n right = Vector()\r\n up = Vector()\r\n angles.get_angle_vectors(forward, right, up)\r\n forward.normalize()\r\n forward *= 10.0\r\n loop_limit = 100\r\n can_teleport = 1\r\n while is_player_stuck(player.index, target_location):\r\n target_location -= forward\r\n loop_limit -= 1\r\n if target_location.get_distance(origin) <= 10.0 or loop_limit < 1:\r\n can_teleport = 0\r\n break\r\n if can_teleport == 1:\r\n player.teleport(target_location,None,None)\r\n\r\n\r\n# Tested and Works\r\n@ServerCommand('wcs_doteleport')\r\ndef _doteleport_command(command):\r\n userid = int(command[1])\r\n if exists(userid):\r\n player = Player.from_userid(userid)\r\n view_vector = player.view_coordinates\r\n queue_command_string('wcs_teleport %s %s %s %s' % (userid, view_vector[0], view_vector[1], view_vector[2]))\r\n\r\n\r\n# Works as intended\r\n@ServerCommand('wcs_explosive_barrel')\r\ndef wcs_explosive_barrel(command):\r\n userid = int(command[1])\r\n player = Player.from_userid(userid)\r\n entity = Entity.create('prop_exploding_barrel')\r\n entity.origin = player.view_coordinates\r\n entity.spawn()\r\n\r\n\r\n@ServerCommand('wcs_getviewcoords')\r\ndef viewcoord(command):\r\n userid = int(command[1])\r\n xvar = str(command[2])\r\n yvar = str(command[3])\r\n zvar = str(command[4])\r\n if exists(userid):\r\n player = Player(index_from_userid(userid))\r\n view_vec = player.get_view_coordinates()\r\n ConVar(xvar).set_float(view_vec[0])\r\n ConVar(yvar).set_float(view_vec[1])\r\n ConVar(zvar).set_float(view_vec[2])\r\n\r\n\r\n@ServerCommand('wcs_setmodel')\r\ndef set_model(command):\r\n userid = int(command[1])\r\n model = str(command[2])\r\n\r\n if model == '0':\r\n inthandle = _remove_model(userid)\r\n\r\n if inthandle is not None:\r\n Player.from_userid(userid).color = Color(255, 255, 255, 255)\r\n\r\n return\r\n\r\n _remove_model(userid)\r\n\r\n if 'models/' not in model:\r\n model = 'models/' + model\r\n\r\n player = Player.from_userid(userid)\r\n player.color = Color(255, 255, 255, 0)\r\n\r\n model = Model(model)\r\n\r\n entity = Entity.create('prop_dynamic_override')\r\n entity.origin = player.origin\r\n entity.parent = player\r\n entity.set_model(model)\r\n entity.spawn()\r\n\r\n _game_models[entity.inthandle] = player.userid\r\n\r\n entity.add_output('OnUser1 !self,Kill,,0,1')\r\n\r\n\r\ndef _remove_model(userid):\r\n for inthandle in _game_models:\r\n if userid == _game_models[inthandle]:\r\n try:\r\n index = index_from_inthandle(inthandle)\r\n except ValueError:\r\n pass\r\n else:\r\n entity = Entity(index)\r\n\r\n entity.clear_parent()\r\n entity.call_input('FireUser1', '1')\r\n finally:\r\n del _game_models[inthandle]\r\n\r\n return inthandle\r\n\r\n return None\r\n\r\n\r\n# =============================================================================\r\n# >> Kami's - Poison smoke grenade\r\n# =============================================================================\r\n@ServerCommand('poison_smoke')\r\ndef poison_smoke(command):\r\n # poison_smoke \r\n do_poison_smoke(Vector(float(command[1]),float(command[2]),float(command[3])),int(command[4]),float(command[5]),int(command[6]),float(command[7]),float(command[8]))\r\n\r\n\r\ndef do_poison_smoke(position,userid,range,damage,delay,duration):\r\n attacker = Player.from_userid(int(userid))\r\n duration = duration - delay\r\n for player in PlayerIter('all'):\r\n if player.origin.get_distance(position) <= range:\r\n player.take_damage(damage,attacker_index=attacker.index, weapon_index=None)\r\n if duration > 0:\r\n Delay(delay,do_poison_smoke,(position,userid,range,damage,delay,duration))\r\n\r\n\r\n# =============================================================================\r\n# >> Headshot Immunity\r\n# =============================================================================\r\n\r\n@ServerCommand('wcs_headshot_immunity')\r\ndef headshot_immunity(command):\r\n userid = int(command[1])\r\n amount = float(command[2])\r\n if exists(userid):\r\n wcsgroup.setUser(userid,'headshot_immunity',amount)\r\n\r\n\r\n@PreEvent('player_hurt')\r\ndef pre_hurt(ev):\r\n victim = Player.from_userid(int(ev['userid']))\r\n if ev['attacker'] > 1:\r\n damage = int(ev['dmg_health'])\r\n headshot_immunity = wcsgroup.getUser(victim.userid,'headshot_immunity')\r\n if headshot_immunity != None:\r\n if victim.hitgroup == HitGroup.HEAD:\r\n headshot_immunity = float(headshot_immunity)\r\n if headshot_immunity > 0:\r\n headshot_immunity_dmg = damage*headshot_immunity\r\n if int(headshot_immunity_dmg) > 0:\r\n victim.health += int(headshot_immunity_dmg)\r\n ##wcs.wcs.tell(victim.userid,'\\x04[WCS] \\x05Your headshot immunity prevented %s damage!' % int(headshot_immunity_dmg))\r\n\r\n\r\n# =============================================================================\r\n# >> HOOKS\r\n# =============================================================================\r\n@EntityPreHook(EntityCondition.equals_entity_classname('prop_physics_multiplayer'), 'on_take_damage')\r\ndef take_damage_hook(stack_data):\r\n take_damage_info = make_object(TakeDamageInfo, stack_data[1])\r\n victim = make_object(Entity, stack_data[0])\r\n if victim.index in entity_health:\r\n damage = take_damage_info.damage\r\n if entity_health[victim.index] <= 0:\r\n Delay(0.1,victim.remove)\r\n else:\r\n entity_health[victim.index] -= damage\r\n else:\r\n return\r\n\r\n\r\n# TODO: Only register this callback when _game_models is populated\r\n@EntityPreHook(EntityCondition.equals_entity_classname('prop_dynamic_override'), 'set_transmit')\r\ndef pre_set_transmit(stack):\r\n if _game_models:\r\n inthandle = inthandle_from_pointer(stack[0])\r\n userid = _game_models.get(inthandle)\r\n\r\n if userid is not None:\r\n target = userid_from_edict(make_object(CheckTransmitInfo, stack[1]).client)\r\n\r\n if target == userid:\r\n return False\r\n\r\n\r\n# =============================================================================\r\n# >> EVENTS\r\n# =============================================================================\r\n@Event('player_activate')\r\ndef player_activate(ev):\r\n repeat_dict[ev['userid']] = 0\r\n\r\n\r\n@Event('player_death')\r\ndef player_death(ev):\r\n if valid_repeat(repeat_dict[ev['userid']]):\r\n repeat_dict[ev['userid']].stop()\r\n repeat_dict[ev['userid']] = 0\r\n\r\n _remove_model(ev['userid'])\r\n\r\n # userid = ev['userid']\r\n\r\n # for inthandle in list(_game_models.keys()):\r\n # if _game_models[inthandle] == userid:\r\n # try:\r\n # index = index_from_inthandle(inthandle)\r\n # except ValueError:\r\n # pass\r\n # else:\r\n # Entity(index).call_input('FireUser1', '1')\r\n # finally:\r\n # del _game_models[inthandle]\r\n\r\n\r\n@Event('round_prestart')\r\ndef round_prestart(event):\r\n _game_models.clear()\r\n\r\n\r\n@Event('round_end')\r\ndef round_end(ev):\r\n for user in repeat_dict:\r\n if valid_repeat(repeat_dict[user]):\r\n repeat_dict[user].stop()\r\n repeat_dict[user] = 0\r\n for player in PlayerIter('all'):\r\n wcsplayer = WCSPlayer.from_userid(player.userid)\r\n\r\n for weapon in weapon_list:\r\n wcsplayer.data['resist_' + weapon] = 0.0\r\n\r\n\r\n@Event('player_spawn')\r\ndef player_spawn(ev):\r\n if ev['userid'] not in repeat_dict:\r\n repeat_dict[ev['userid']] = 0\r\n if repeat_dict[ev['userid']] != 0:\r\n repeat_dict[ev['userid']].stop()\r\n repeat_dict[ev['userid']] = 0\r\n\r\n\r\n# =============================================================================\r\n# >> HELPER FUNCTIONS\r\n# =============================================================================\r\ndef check_space(position, mins, maxs):\r\n mask = ContentMasks.ALL\r\n generator = BaseEntityGenerator\r\n ray = Ray(position, position, mins, maxs)\r\n\r\n trace = GameTrace()\r\n engine_trace.trace_ray(ray, mask, TraceFilterSimple(generator()), trace)\r\n return trace\r\n\r\n\r\ndef exists(userid):\r\n try:\r\n index_from_userid(userid)\r\n except ValueError:\r\n return False\r\n return True\r\n\r\n\r\ndef is_player_stuck(player_index, origin):\r\n '''Return whether or not the given player is stuck in solid.'''\r\n\r\n # Get the player's PlayerInfo instance...\r\n player_info = playerinfo_from_index(player_index)\r\n\r\n # Get the player's origin...\r\n origin = player_info.origin\r\n\r\n # Get a Ray object based on the player physic box...\r\n ray = Ray(origin, origin, player_info.mins, player_info.maxs)\r\n\r\n # Get a new GameTrace instance...\r\n trace = GameTrace()\r\n\r\n # Do the trace...\r\n engine_trace.trace_ray(ray, ContentMasks.PLAYER_SOLID, TraceFilterSimple(\r\n PlayerIter()), trace)\r\n\r\n # Return whether or not the trace did hit...\r\n return trace.did_hit()\r\n\r\n\r\ndef valid_repeat(repeat):\r\n try:\r\n if repeat.status == RepeatStatus.RUNNIN:\r\n return True\r\n except:\r\n return False\r\n","repo_name":"mmastrocinque/Warcraft-Source-Essentials","sub_path":"addons/source-python/plugins/commandsx/commandsx.py","file_name":"commandsx.py","file_ext":"py","file_size_in_byte":14342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6728971001","text":"import PyPDF2\nimport os\n\npath = 'C:/Users/Herick/Desktop/validar_assinatura'\nfor f in os.listdir(path):\n if f.endswith('.pdf'):\n with open(f'{path}/{f}', 'rb') as file:\n pdf_reader = PyPDF2.PdfReader(file)\n\n try:\n if pdf_reader.trailer['/Root']['/AcroForm']:\n sig_flags = pdf_reader.trailer['/Root']['/AcroForm']['/SigFlags'] & 1\n print(f'{f} - Assinatura válida' if sig_flags == 1 else f'{f} - Assinatura inválida')\n if sig_flags == 1:\n file.close()\n continue\n else:\n file.close()\n continue\n\n except:\n file.close()\n print(f'{f} - Sem assinatura digital')\n continue","repo_name":"hericklima22/python","sub_path":"first_automacao/scripts_antigos/prod/assinatura.py","file_name":"assinatura.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"18296162066","text":"import socket\nimport sys\nimport threading\nimport time\nimport os\n\n\nserver = socket.socket()\nHOST = \"127.0.0.1\"\nport = 4000\nSEPARATOR = \"\"\n\n\n\n\nprint(\"starting up on %s port %s\" %(HOST, port))\nserver.bind((HOST, port))\n\nserver.listen()\nprint(\"Listening for connection\")\n\nclient, address = server.accept()\nno_files, concurrency = client.recv(1024).decode().split(SEPARATOR)\nclient.close()\n\n\n\n#\tThe download path for the server needs to created if it doesnt exist.\n\n#\tIf it exist, then it won't be created\n\n\ndownload_path = os.path.join(os.getcwd(), 'server_files')\nos.makedirs(download_path, exist_ok = True)\n\ndef handle_clients(client):\n\n\t\n\twith client, client.makefile('rb') as clientfile:\t\t\n\t\ttry:\n\t\t\t\t\n\t\t\tfilename = clientfile.readline().strip().decode()\n\t\t\tdata = clientfile.read()\n\t\t\t\n\t\t\t\n\t\texcept UnicodeDecodeError as e:\n\n\t\t\tdata = clientfile.read()\n\t\t\tfilename = clientfile.readline().strip().decode()\n\t\tfinally:\n\t\t\tlength = len(data)\n\t\ttry:\n\n\t\t\tif len(data) < 2:\n\t\t\t\tpass\n\t\t\telse:\n\n\t\t\t\tchecksum = length/1048576\n\t\t\t\tprint(f\"Receiving {filename} : [{'{0:.1f}'.format(checksum)}M]\")\n\t\t\t\twith open(os.path.join(download_path, filename) , 'wb') as file:\t\t\t\n\t\t\t\t\tfile.write(data)\n\t\t\t\t\tprogress = length/1048576\n\t\t\t\tprint(f\"Received {filename} : [{'{0:.1f}'.format(checksum)}M\\{'{0:.1f}'.format(checksum)}M]\")\n\n\t\t\t\tprint()\n\t\texcept FileNotFoundError as e:\n\t\t\tpass\n\t\tfinally:\n\t\t\tclient.close()\n\n\n\n#\tThis thread handles all connected clients concurrently. It ensures that \n\n#\tthe files are received from connected clients concurrently because the clients are connected concurrently.\n\n#\tHowever, if concurrency == 1, the files are sent one by one. concurrency greater than two are handled concurrently\n\n\n\n\n\nfor i in range(int(no_files)):\n\n\n\n\tif int(concurrency) == 1:\n\t\tclient, address = server.accept()\n\t\t#print(f\"{address} is connected\")\n\n\t\thandle_clients(client)\n\telse:\n\t\tclient, address = server.accept()\n\t\t#print(f\"{address} is connected\")\n\n\t\t\n\t\tthread = threading.Thread(target = handle_clients, args = [client])\n\t\tthread.start()\n\t\t\n\n\n\n\t\n\t\n\t\n\t\n\t\n\n\t\n\n\t\n\n\n\t\n\n\n\n\t\n","repo_name":"komus-Israel/TCP-concurrent-file-transfer","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"8365650393","text":"with open(\"d4.txt\", \"r\") as f:\n inp = f.read()\n\nPART = 2\npairs = inp.split(\"\\n\")[:-1]\n\nfully_contain = 0\ncontain = 0\n\nfor p in pairs:\n p1, p2 = p.split(\",\")\n p1s = p1.split(\"-\")\n p2s = p2.split(\"-\")\n if PART == 1:\n counter = 0\n for i in range(int(p1s[0]), int(p1s[1]) + 1):\n if i in range(int(p2s[0]), int(p2s[1]) + 1):\n counter += 1\n if counter == len(range(int(p1s[0]), int(p1s[1]) + 1)):\n fully_contain += 1\n continue\n\n counter = 0\n for i in range(int(p2s[0]), int(p2s[1]) + 1):\n if i in range(int(p1s[0]), int(p1s[1]) + 1):\n counter += 1\n if counter == len(range(int(p2s[0]), int(p2s[1]) + 1)):\n fully_contain += 1\n else:\n for i in range(int(p1s[0]), int(p1s[1]) + 1):\n if i in range(int(p2s[0]), int(p2s[1]) + 1):\n contain += 1\n break\n\nprint(fully_contain)\nprint(contain)\n","repo_name":"martinezpl/aoc2022","sub_path":"d4.py","file_name":"d4.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9667890226","text":"from ctypes import *\n\nclass Type():\n \"\"\"Defines type names similary to the c++ module.\n \"\"\"\n cellId_t = c_uint32\n stateId_t = c_uint32\n state_t = c_double\n cellPos_t = c_uint16\n nodeFlag_t = c_uint8\n\nclass Const():\n noCellId = 0xFFFFFFFF\n noStateId = 0xFFFFFFFF\n\nclass Vec3DBase():\n \"\"\"Base parent class for the Vec3D (resembles template Vec3D).\n Class is inherited from other Vec3D_ classes.\n \n \"\"\"\n\n def __init__(self, x=0, y=0, z=0):\n self.x = x\n self.y = y\n self.z = z\n\n def asTuple(self):\n return (self.x, self.y, self.z)\n\n def asList(self):\n return [self.x, self.y, self.z]\n\n def __mul__(self, val):\n # Check if it is another Vec3DBase\n if Vec3DBase in [baseClass for baseClass in val.__class__.__bases__]:\n return Vec3DClass(self.type)(self.x*val.x, self.y*val.y, self.z*val.z) \n # Val is a single value (float or int)\n else:\n return Vec3DClass(self.type)(self.x*val, self.y*val, self.z*val) \n\n def __str__(self):\n return f\"{{x: {self.x}, y: {self.y}, z: {self.z}}}\"\n\nclass Vec3D_double(Structure, Vec3DBase):\n _fields_ = [\n ('x', c_double),\n ('y', c_double),\n ('z', c_double)\n ]\n type = c_double\n\nclass Vec3D_float(Structure, Vec3DBase):\n _fields_ = [\n ('x', c_float),\n ('y', c_float),\n ('z', c_float)\n ]\n type = c_float\n\nclass Vec3D_int(Structure, Vec3DBase):\n _fields_ = [\n ('x', c_int),\n ('y', c_int),\n ('z', c_int)\n ]\n type = c_int\n\nclass Vec3D_uint32(Structure, Vec3DBase):\n _fields_ = [\n ('x', c_uint32),\n ('y', c_uint32),\n ('z', c_uint32)\n ]\n type = c_uint32\n\nclass Vec3D_uint16(Structure, Vec3DBase):\n _fields_ = [\n ('x', c_uint16),\n ('y', c_uint16),\n ('z', c_uint16)\n ]\n type = c_uint16\n\ndef Vec3DClass(cType = c_int):\n if cType == c_float:\n return Vec3D_float\n elif cType == c_double:\n return Vec3D_double\n elif cType == c_int:\n return Vec3D_int\n elif cType == c_uint32:\n return Vec3D_uint32\n elif cType == c_uint16:\n return Vec3D_uint16\n else:\n return None\n \nclass Gas(Structure):\n \"\"\"Wrapper for the parfis::Gas class\n \"\"\"\n _fields_ = [\n ('id', c_uint32),\n ('name', c_char_p),\n ('amuMass', c_double),\n ('volumeFraction', c_double),\n ('temperature', c_double),\n ('molDensity', c_double)\n ]\n\nclass State_float(Structure):\n _fields_ = [\n ('next', Type.stateId_t),\n ('prev', Type.stateId_t),\n ('pos', Vec3DClass(c_float)),\n ('vel', Vec3DClass(c_float))\n ]\n\nclass State_double(Structure):\n _fields_ = [\n ('next', Type.stateId_t),\n ('prev', Type.stateId_t),\n ('pos', Vec3DClass(c_double)),\n ('vel', Vec3DClass(c_double))\n ]\n\ndef StateClass():\n if Type.state_t == c_float:\n return State_float\n elif Type.state_t == c_double:\n return State_double\n else:\n return None\n\nclass Cell(Structure):\n _fields_ = [\n ('pos', Vec3DClass(Type.cellPos_t))\n ]\n\nclass Specie(Structure):\n _fields_ = [\n ('id', c_uint32),\n ('name', c_char_p),\n ('velInitDist', c_int),\n ('statesPerCell', c_int),\n ('timestepRatio', c_int),\n ('dt', c_double),\n ('idt', c_double),\n ('maxVel', c_double),\n ('maxEv', c_double),\n ('velInitDistMin', Vec3DClass(c_double)),\n ('velInitDistMax', Vec3DClass(c_double)),\n ('qm', c_double),\n ('amuMass', c_double),\n ('mass', c_double)\n ]\n\nclass PyStructBase:\n \"\"\"A common base class so PyVec can have a defined struct for \n overloaded types tha have PyVec inside them.\n \"\"\"\n def className(self):\n return \"PyStructBase\"\n\nclass PyVecBase:\n def asList(self):\n if self.__class__ == PyVec_char_p:\n return [self.ptr[i].decode() for i in range(self.size)]\n else:\n return [self.ptr[i] for i in range(self.size)]\n\nclass PyVec_char_p(Structure, PyVecBase):\n _fields_ = [\n ('ptr', POINTER(c_char_p)),\n ('size', c_size_t)\n ]\n\nclass PyVec_double(Structure, PyVecBase):\n _fields_ = [\n ('ptr', POINTER(c_double)),\n ('size', c_size_t)\n ]\n\nclass PyVec_int(Structure, PyVecBase):\n _fields_ = [\n ('ptr', POINTER(c_int)),\n ('size', c_size_t)\n ]\n\nclass PyVec_State_float(Structure, PyVecBase):\n _fields_ = [\n ('ptr', POINTER(State_float)),\n ('size', c_size_t)\n ]\n\nclass PyVec_State_double(Structure, PyVecBase):\n _fields_ = [\n ('ptr', POINTER(State_double)),\n ('size', c_size_t)\n ]\n\nclass PyVec_Cell(Structure, PyVecBase):\n _fields_ = [\n ('ptr', POINTER(Cell)),\n ('size', c_size_t)\n ]\n\nclass PyVec_uint32(Structure, PyVecBase):\n _fields_ = [\n ('ptr', POINTER(c_uint32)),\n ('size', c_size_t)\n ]\n\nclass PyVec_uint8(Structure, PyVecBase):\n _fields_ = [\n ('ptr', POINTER(c_uint8)),\n ('size', c_size_t)\n ]\n\nclass PyVec_uint8(Structure, PyVecBase):\n _fields_ = [\n ('ptr', POINTER(c_uint8)),\n ('size', c_size_t)\n ]\n\nclass PyVec_Specie(Structure, PyVecBase):\n _fields_ = [\n ('ptr', POINTER(Specie)),\n ('size', c_size_t)\n ]\n\nclass PyVec_Gas(Structure, PyVecBase):\n _fields_ = [\n ('ptr', POINTER(Gas)),\n ('size', c_size_t)\n ]\n\ndef PyVecClass(cType = c_char_p):\n \"\"\"Function returns a class PyVec class for a coresponding argument.\n\n Args:\n cType (ctypes type, optional): Type of class. Defaults to c_char_p.\n\n Returns:\n PyVec_: Class that inherited PyVecBase and has data of the\n specified type.\n \"\"\"\n if cType == c_char_p:\n return PyVec_char_p\n elif cType == c_int:\n return PyVec_int\n elif cType == c_double:\n return PyVec_double\n elif cType == c_uint32:\n return PyVec_uint32\n elif cType == c_uint8:\n return PyVec_uint8\n elif cType == State_float:\n return PyVec_State_float\n elif cType == State_double:\n return PyVec_State_double\n elif cType == Specie:\n return PyVec_Specie\n elif cType == Cell:\n return PyVec_Cell\n elif cType == Gas:\n return PyVec_Gas\n elif cType == PyGasCollision:\n return PyVec_PyGasCollision\n elif cType == PyFuncTable:\n return PyVec_PyFuncTable\n else:\n return None\n\nclass PyFuncTable(Structure):\n \"\"\"Wrapper for the parfis::PyFuncTable class. The structure\n is coppied from :cpp:class:`parfis::PyFuncTable`.\n \n Attributes:\n type (c_int): Type of tabulation (0: linear, 1:nonlinear).\n colCnt (c_int): Number of columns (increase of 1, in memory \n address increases the column counter). If you want values ordered in memory\n pack them in successive columns.\n rowCnt (c_int): Number of rows.\n ranges (c_double): Ranges for tabulation.\n nbins (c_int): Number of bins per range.\n idx (c_double): Delta x in every range.\n xVec (c_double): X axis.\n yVec (c_double): Y axis (or multiple axis - a matrix).\n \n Example:\n :ref:`/collisional_files/generating_simple_cross_sections.ipynb`\n \"\"\"\n _fields_ = [\n ('type', c_int),\n ('colCnt', c_int), \n ('rowCnt', c_int),\n ('ranges', PyVecClass(c_double)),\n ('nbins', PyVecClass(c_int)),\n ('idx', PyVecClass(c_double)),\n ('xVec', PyVecClass(c_double)),\n ('yVec', PyVecClass(c_double))\n ]\n\nclass PyGasCollision(Structure):\n \"\"\"Wrapper for the parfis::PyGasCollision class\n \"\"\"\n _fields_ = [\n ('id', c_uint32),\n ('name', c_char_p),\n ('fileName', c_char_p),\n ('specieId', c_uint32),\n ('gasId', c_uint32),\n ('threshold', c_double),\n ('type', c_int),\n ('scatterAngle', PyVecClass(c_double)),\n ('xSecFtab', PyFuncTable),\n ('freqFtab', PyFuncTable)\n ]\n\nclass PyVec_PyGasCollision(Structure, PyVecBase):\n _fields_ = [\n ('ptr', POINTER(PyGasCollision)),\n ('size', c_size_t)\n ]\n \nclass PyVec_PyFuncTable(Structure, PyVecBase):\n _fields_ = [\n ('ptr', POINTER(PyFuncTable)),\n ('size', c_size_t)\n ]\n\nclass PyCfgData(Structure):\n \"\"\"PyCfgData(ctypes.Structure)\n\n Args:\n geometry: Geometry type (0: cubical, 1: cylindrical)\n timestep: Timestep in seconds\n geometrySize: Pointer to Vec3D_double, size of geometry in meters\n cellCount: Pointer to Vec3D_int, number of cells\n \"\"\"\n _fields_ = [\n ('geometry', c_int),\n ('timestep', c_double),\n ('geometrySize', POINTER(Vec3DClass(c_double))),\n ('cellSize', POINTER(Vec3DClass(c_double))),\n ('periodicBoundary', POINTER(Vec3DClass(c_int))),\n ('cellCount', POINTER(Vec3DClass(c_int))),\n ('specieNameVec', PyVecClass(c_char_p)),\n ('gasNameVec', PyVecClass(c_char_p)),\n ('gasCollisionNameVec', PyVecClass(c_char_p)),\n ('gasCollisionFileNameVec', PyVecClass(c_char_p))\n ]\n\nclass PySimData_float(Structure):\n _fields_ = [\n ('stateVec', PyVecClass(State_float)),\n ('cellIdVec', PyVecClass(Type.cellId_t)),\n ('cellIdAVec', PyVecClass(Type.cellId_t)),\n ('cellIdBVec', PyVecClass(Type.cellId_t)),\n ('specieVec', PyVecClass(Specie)),\n ('cellVec', PyVecClass(Cell)),\n ('nodeFlagVec', PyVecClass(Type.nodeFlag_t)),\n ('headIdVec', PyVecClass(Type.stateId_t)),\n ('gasVec', PyVecClass(Gas)),\n ('pyGasCollisionVec', PyVecClass(PyGasCollision)),\n ('pyGasCollisionProbVec', PyVecClass(PyFuncTable))\n ]\n\nclass PySimData_double(Structure):\n _fields_ = [\n ('stateVec', PyVecClass(State_double)),\n ('cellIdVec', PyVecClass(Type.cellId_t)),\n ('cellIdAVec', PyVecClass(Type.cellId_t)),\n ('cellIdBVec', PyVecClass(Type.cellId_t)),\n ('specieVec', PyVecClass(Specie)),\n ('cellVec', PyVecClass(Cell)),\n ('nodeFlagVec', PyVecClass(Type.nodeFlag_t)),\n ('headIdVec', PyVecClass(Type.stateId_t)),\n ('gasVec', PyVecClass(Gas)),\n ('pyGasCollisionVec', PyVecClass(PyGasCollision)),\n ('pyGasCollisionProbVec', PyVecClass(PyFuncTable))\n ]\n\ndef PySimDataClass():\n if Type.state_t == c_float:\n return PySimData_float\n elif Type.state_t == c_double:\n return PySimData_double\n else:\n return None\n\n\nif __name__ == '__main__':\n pass","repo_name":"GinkoBalboa/parfis","sub_path":"python-package/parfis/clib/datastruct.py","file_name":"datastruct.py","file_ext":"py","file_size_in_byte":10655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9361730658","text":"fin = open(\"fibonacci.in\")\r\nfout = open(\"fibonacci.out\", \"w\")\r\nn = int(fin.readline())\r\n\r\n\r\ndef get_num(n):\r\n prev2_num = 1\r\n prev_num = 0\r\n nth_term = 0\r\n for x in range(0, n):\r\n nth_term = prev_num + prev2_num\r\n prev2_num = prev_num\r\n prev_num = nth_term\r\n fout.write(str(nth_term))\r\n\r\n\r\nget_num(n)\r\n","repo_name":"AsianGang1/Usaco","sub_path":"fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"41064273731","text":"from oslo.config import cfg\nfrom neutron.openstack.common import log as logging\nfrom neutron.plugins.common import utils as plugin_utils\nfrom neutron.plugins.zvm.common import utils\n\nLOG = logging.getLogger(__name__)\n\nvswitch_opts = [\n cfg.StrOpt('rdev_list',\n help='RDev list for vswitch uplink port')]\n\nCONF = cfg.CONF\nCONF.import_opt('flat_networks', \"neutron.plugins.ml2.drivers.type_flat\",\n 'ml2_type_flat')\nCONF.import_opt('network_vlan_ranges', \"neutron.plugins.ml2.drivers.type_vlan\",\n 'ml2_type_vlan')\n\n\nclass zvmVswitch(object):\n def __init__(self, zhcp, name, vlan):\n self._utils = utils.zvmUtils()\n self._utils.add_vswitch(zhcp, name,\n eval(\"CONF.\" + name + \".rdev_list\"), vid=vlan)\n self.zhcp = zhcp\n\n\nclass zvmNetwork(object):\n def __init__(self):\n self._zhcp = CONF.AGENT.xcat_zhcp_nodename\n self._vsws = []\n self._maps = {}\n self._creat_networks()\n\n def _creat_networks(self):\n self._maps = plugin_utils.parse_network_vlan_ranges(\n CONF.ml2_type_vlan.network_vlan_ranges\n + CONF.ml2_type_flat.flat_networks)\n self._vsws = []\n for vsw in self._maps.keys():\n CONF.register_opts(vswitch_opts, vsw)\n self._vsws.append(zvmVswitch(self._zhcp, vsw, self._maps[vsw]))\n\n def get_network_maps(self):\n return self._maps\n","repo_name":"stackforge-attic/zvm-driver","sub_path":"neutron-zvm-plugin/neutron/plugins/zvm/agent/zvm_network.py","file_name":"zvm_network.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"29"} +{"seq_id":"28920817409","text":"import requests\nfrom bs4 import BeautifulSoup\nimport mysql\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport ftp as MyFtp\nimport os\nimport urllib\nimport urllib.request\nimport zlib\nimport time\nimport errorRecoder\nfrom fake_useragent import UserAgent\nfrom lxml import html\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nimport undetected_chromedriver as uc\nimport asyncio\nfrom playwright.sync_api import sync_playwright\nimport json\nimport os\nimport codecs\nimport random\n\nbase = 'https://ceomap.site/#/main'\nsleepSec = 2\n# define your header\n\n\nclass MySpider:\n\n def __init__(self, url, proxies):\n self.rootUrl = url\n self.proxies = proxies\n\n def start_requests(self):\n try:\n fu = UserAgent(verify_ssl=False)\n headers = {'user-agent': fu.firefox,\n 'referer': 'https://ceomap.site/#/advertising#about'\n }\n session = requests.Session()\n proxies = {\n \"http\": \"http://\"+random.choice(self.proxies),\n # \"http\": \"http://10.10.1.10:1080\",\n }\n rootResp = requests.get(\n url=self.rootUrl, headers=headers, proxies=proxies)\n rootResp.encoding = 'utf-8'\n # respone\n content = rootResp.content\n soup = BeautifulSoup(content, \"html5lib\")\n element_data = soup.select('div.class')\n print(element_data)\n except requests.exceptions.HTTPError as err:\n raise SystemExit(err)\n\n def save_json(json_arrary):\n storePath_name = os.getcwd() + '\\\\error.json'\n with codecs.open(storePath_name, 'a', encoding='UTF-8') as f:\n line = json.dumps(json_arrary, ensure_ascii=False) + '\\n'\n f.write(line)\n f.close()\n\n def save_img(self, img_name, enter_ftp_path, img_url):\n print('star saving pic: ' + img_url)\n # locale store path\n document = os.getcwd() + '\\\\image'\n # path nameing\n comics_path = document + '\\\\' + enter_ftp_path\n exists = os.path.exists(comics_path)\n\n if not exists:\n print('create document: ' + enter_ftp_path)\n os.makedirs(comics_path)\n # nameing image\n pic_name = comics_path + '\\\\' + img_name\n\n # check we had img\n exists = os.path.exists(pic_name)\n if exists:\n print('pic exists: ' + pic_name)\n return False\n\n try:\n ua = UserAgent()\n headers = {'User-Agent': ua.random}\n req = urllib.request.Request(img_url, headers=headers)\n response = urllib.request.urlopen(req, timeout=300)\n\n # reponse data\n data = response.read()\n\n # we need extract data use zip\n if response.info().get('Content-Encoding') == 'gzip':\n data = zlib.decompress(data, 16 + zlib.MAX_WBITS)\n\n # 图片保存到本地\n fp = open(pic_name, \"wb\")\n fp.write(data)\n fp.close()\n print('save image finished:' + pic_name)\n return True\n # ftp write method\n\n # fpLocal = open(pic_name, 'rb')\n # ftp = MyFtp.ftpconnect('156.67.222.57', 'u565698326.topceo.online', 'T5204t5204')\n # return MyFtp.uploadftpfile(ftp, fpLocal, enter_ftp_path, img_name)\n\n except Exception as e:\n print('save image error.')\n print(e)\n error = []\n error.append(img_name)\n error.append(enter_ftp_path)\n error.append(img_url)\n errorRecoder.saveErrorUrlToJson(error)\n","repo_name":"outsider987/mySpider-Sample","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":3794,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"11236082145","text":"class CharArray(object):\n\n def __init__(self, word):\n if not isinstance(word, str):\n raise TypeError(\"No the correct type for a char array\")\n\n self.vocales_fuertes = [\"a\", \"e\", \"o\", \"á\", \"é\", \"ó\", \"í\", \"ú\", \"ä\"]\n self.vocales_debiles = [\"i\", \"u\"]\n self.vocales = self.vocales_debiles + self.vocales_fuertes\n\n self.consontant_y = [\"y\" + vowel for vowel in self.vocales]\n\n diptongos_crecientes = [d + f for d in self.vocales_debiles\\\n for f in self.vocales_fuertes]\n diptongos_decrecientes = [f + d for d in self.vocales_debiles\\\n for f in self.vocales_fuertes] + \\\n [f + \"y\" for f in self.vocales_fuertes]\n diptongos_homogeneos = [\"iu\", \"ui\"]\n self.diptongos = diptongos_crecientes + \\\n diptongos_decrecientes + \\\n diptongos_homogeneos\n\n self.triptongos = [dip + d for dip in diptongos_crecientes \\\n for d in self.vocales_debiles] +\\\n [dip + \"y\" for dip in diptongos_crecientes if \\\n not dip.endswith(\"y\")]\n\n self.grupos_inseparables = [\"br\", \"cr\",\"dr\", \"gr\", \"fr\", \"kr\", \"tr\", \"bl\",\n \"cl\", \"gl\", \"fl\", \"kl\", \"pl\", \"tl\", \"ll\", \"ch\",\n \"rr\", \"pr\", \"qu\", \"gü\"]\n\n self.word = word\n self.vocal_representation = self.build_abstract_representation(word)\n\n def build_abstract_representation(self, word):\n representation = {}\n\n if word == \"y\":\n word = \"|\"\n\n for consonant_y in self.consontant_y:\n while consonant_y in word:\n word = word.replace(\"y\", \"#\", 1)\n\n for triptongo in self.triptongos:\n while triptongo in word:\n beginning = word.index(triptongo)\n end = beginning + len(word)\n interval = (beginning, end)\n representation[triptongo] = representation.get(triptongo, [])\n representation[triptongo].append(interval)\n word = word.replace(triptongo, \"@\", 1)\n\n for diptongo in self.diptongos:\n while diptongo in word:\n beginning = word.index(diptongo)\n end = beginning + len(word)\n interval = (beginning, end)\n representation[diptongo] = representation.get(diptongo, [])\n representation[diptongo].append(interval)\n word = word.replace(diptongo, \"@\", 1)\n\n for grupo_c in self.grupos_inseparables:\n while grupo_c in word:\n beginning = word.index(grupo_c)\n end = beginning + len(word)\n interval = (beginning, end)\n representation[grupo_c] = representation.get(grupo_c, [])\n representation[grupo_c].append(interval)\n word = word.replace(grupo_c, \"#\", 1)\n\n for vowel in self.vocales_debiles + [\"y\"]:\n while vowel in word:\n word = word.replace(vowel, \"|\", 1)\n\n\n\n for vowel in self.vocales_fuertes:\n while vowel in word:\n word = word.replace(vowel, \"@\", 1)\n\n for consonant in list(\"bcdfghjklmnñpqrstvwxz\"):\n while consonant in word:\n word = word.replace(consonant, \"#\", 1)\n\n word = word.replace(\"#\", \"C\").replace(\"@\", \"V\").replace(\"|\", \"V\")\n extra_chars = word.replace(\"C\", \"\").replace(\"V\", \"\").replace(\"v\", \"\")\n\n if extra_chars != \"\":\n for extra_char in list(extra_chars):\n word = word.replace(extra_char, \"C\")\n return word\n\n def unmask(self, pattern):\n result = []\n word = self.word\n for syllable in pattern:\n subsyl = \"\"\n for character in syllable:\n found = False\n if character == \"C\":\n if len(word) > 1 and\\\n word[1] in \"bcdfghjklmnñpqrstvwxz\" and not found:\n for grupo_c in self.grupos_inseparables:\n if word.startswith(grupo_c):\n subsyl += grupo_c\n word = word[2:]\n found = True\n break\n if not found:\n subsyl += word[0]\n word = word[1:]\n elif character == \"V\":\n if len(word) > 2 and \\\n word[1] in self.vocales and \\\n word[2] in self.vocales + [\"y\"]:\n for triptongo in self.triptongos:\n if word.startswith(triptongo):\n if triptongo.endswith(\"y\"):\n is_consonant_y = False\n if len(word) != 3: # Not end of word\n is_consonant_y = True\n elif len(word) > 3:\n if word[3] in self.vocales: #y is consonant\n is_consonant_y = True\n if is_consonant_y:\n break\n subsyl += triptongo\n word = word[3:]\n found = True\n break\n if len(word) > 1 and \\\n word[1] in self.vocales + [\"y\"] and not found:\n for diptongo in self.diptongos:\n if word.startswith(diptongo):\n if diptongo.endswith(\"y\"):\n is_consonant_y = False\n if len(word) == 2: # Not end of word\n is_consonant_y = True\n elif len(word) > 2:\n if word[2] in self.vocales: #y is consonant\n is_consonant_y = True\n if is_consonant_y:\n break\n subsyl += diptongo\n word = word[2:]\n found = True\n break\n if not found:\n try:\n subsyl += word[0]\n word = word[1:]\n except:\n print(\"%s couldn't separate\" % self.word)\n return []\n\n result.append(subsyl)\n #print(result)\n\n return result\n\n def __str__(self, *args, **kwargs):\n return str(self.vocal_representation)\n\n def __repr__(self, *args, **kwargs):\n return str(self)\n\n\nclass Silabicador(object):\n\n def __call__(self, word):\n '''http://ponce.inter.edu/acad/cursos/ciencia/lasvi/modulo2.htm'''\n res = []\n lower_word = word.lower()\n char_array = CharArray(lower_word)\n abstract_word = list(str(char_array))\n\n while len(abstract_word) != 0:\n if abstract_word[0] == \"V\":\n if len(abstract_word) == 1:\n res += [\"V\"]\n abstract_word = []\n elif len(abstract_word) == 2:\n if abstract_word[1] == \"C\":\n res += [\"VC\"]\n else:\n res += [\"V\", \"V\"]\n abstract_word = []\n elif len(abstract_word) == 3:\n res += [\"V\", abstract_word[1] + abstract_word[2]]\n abstract_word = []\n else:\n # No hay consonantes en frente, sino otra vocal\n if abstract_word[1] == \"V\":\n res += [\"V\"]\n del abstract_word[0]\n # Una consonante entre dos vocales se agrupa con la vocal de la derecha:\n elif abstract_word[1] == \"C\" and\\\n abstract_word[2] == \"V\":\n res += [\"V\", \"CV\"]\n del abstract_word[2]\n del abstract_word[1]\n del abstract_word[0]\n # Dos consonantes entre dos vocales se separan y cada consonante se queda con una vocal:\n elif abstract_word[1] == \"C\" and\\\n abstract_word[2] == \"C\" and\\\n abstract_word[3] == \"V\":\n res += [\"VC\", \"CV\"]\n del abstract_word[3]\n del abstract_word[2]\n del abstract_word[1]\n del abstract_word[0]\n\n # Cuando hay tres consonantes entre vocales, las primeras dos se unen con la primera vocal y la tercera se une a la segunda vocal.\n elif len(abstract_word) > 4 and\\\n abstract_word[1] == \"C\" and\\\n abstract_word[2] == \"C\" and\\\n abstract_word[3] == \"C\" and\\\n abstract_word[4] == \"V\":\n res += [\"VCC\", \"CV\"]\n del abstract_word[4]\n del abstract_word[3]\n del abstract_word[2]\n del abstract_word[1]\n del abstract_word[0]\n # Cuando hay cuatro consonantes entre vocales, las primeras dos se unen a la primera vocal y las otras dos se unen a la segunda vocal.\n elif len(abstract_word) > 5 and\\\n abstract_word[1] == \"C\" and\\\n abstract_word[2] == \"C\" and\\\n abstract_word[3] == \"C\" and\\\n abstract_word[4] == \"C\" and\\\n abstract_word[5] == \"V\":\n res += [\"VCC\", \"CCV\"]\n del abstract_word[5]\n del abstract_word[4]\n del abstract_word[3]\n del abstract_word[2]\n del abstract_word[1]\n del abstract_word[0]\n # Chain of consonants\n else:\n consonant_chain = \"\"\n for _ in range(len(abstract_word) - 2):\n consonant_chain += \"C\"\n res += [\"VC\", consonant_chain]\n abstract_word = []\n\n elif abstract_word[0] == \"C\":\n res.append(abstract_word.pop(0))\n\n final_grouping = []\n while len(res)>0:\n if res[0] == \"C\" and \\\n len(res) != 1 and \\\n res[1].startswith(\"V\"):\n final_grouping.append(res[0] + res[1])\n del res[1]\n del res[0]\n # Si existe la consonante pega con la silaba anterior\n elif res[0] == \"C\" and\\\n len(final_grouping)>0 and\\\n final_grouping[-1].endswith(\"V\"):\n final_grouping[-1] = final_grouping[-1] + res[0]\n del res[0]\n # Else, assume it is a valid syllable\n else:\n final_grouping.append(res[0])\n del res[0]\n\n #print(final_grouping)\n return char_array.unmask(final_grouping),final_grouping\n","repo_name":"RicardoJC/syllabics","sub_path":"syllabicator.py","file_name":"syllabicator.py","file_ext":"py","file_size_in_byte":11752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13804235977","text":"from __future__ import annotations\n\nimport datetime as dt\nfrom typing import List, Union\n\nimport attr\nimport gspread\nfrom pytz import utc\nimport warnings\n\nfrom .utils import (\n EntityRotation,\n Minutes,\n _parse_counts,\n all_values_from_sheet,\n SectorV1Compat,\n)\n\ntry:\n from typing import Self\nexcept ImportError:\n from typing_extensions import Self\n\n# For future reference, this file pulls data from google sheets\n# The library used to pull this data is gspread\n# The spreadsheet file has headings which need to be removed\n# from our pulled data before being used\n# The [1:] slices in from_gspread methods\n# omit the headings in the google sheets file\n\n\n@attr.s\nclass DifficultySpecificSectorData:\n \"\"\"Represents sector data for specific difficulties\n\n Note: for all counts, -1 means at least 1 and 0 means none\n\n Attributes:\n barrier_champions (int): Number of barrier champions in the lost sector.\n overload_champions (int): Number of overload champions in the lost sector.\n unstoppable_champions (int): Number of unstoppable champions in the lost sector.\n arc_shields (int): Number of arc shields in the lost sector.\n void_shields (int): Number of void shields in the lost sector.\n solar_shields (int): Number of solar shields in the lost sector.\n stasis_shields (int): Number of stasis shields in the lost sector.\n strand_shields (int): Number of strand shields in the lost sector.\n modifiers (str): Modifiers on the lost sector.\n champions_list (List[str]): List of champions in the lost sector.\n champions (str): Comma separated list of champions in the lost sector.\n shields_list (List[str]): List of shields in the lost sector.\n shields (str): Comma separated list of shields in the lost sector.\n \"\"\"\n\n barrier_champions = attr.ib(0, converter=_parse_counts)\n overload_champions = attr.ib(0, converter=_parse_counts)\n unstoppable_champions = attr.ib(0, converter=_parse_counts)\n arc_shields = attr.ib(0, converter=_parse_counts)\n void_shields = attr.ib(0, converter=_parse_counts)\n solar_shields = attr.ib(0, converter=_parse_counts)\n stasis_shields = attr.ib(0, converter=_parse_counts)\n strand_shields = attr.ib(0, converter=_parse_counts)\n modifiers = attr.ib(\"\")\n\n @property\n def champions_list(self) -> List[str]:\n champions = []\n if self.barrier_champions != 0:\n champions.append(\"Barrier\")\n if self.overload_champions != 0:\n champions.append(\"Overload\")\n if self.unstoppable_champions != 0:\n champions.append(\"Unstoppable\")\n return champions\n\n @property\n def champions(self) -> str:\n return \", \".join(self.champions_list) or \"None\"\n\n @property\n def shields_list(self) -> List[str]:\n shields = []\n if self.arc_shields != 0:\n shields.append(\"Arc\")\n if self.void_shields != 0:\n shields.append(\"Void\")\n if self.solar_shields != 0:\n shields.append(\"Solar\")\n if self.stasis_shields != 0:\n shields.append(\"Stasis\")\n if self.strand_shields != 0:\n shields.append(\"Strand\")\n return shields\n\n @property\n def shields(self) -> str:\n return \", \".join(self.shields_list) or \"None\"\n\n def __bool__(self):\n return bool(\n self.barrier_champions\n or self.overload_champions\n or self.unstoppable_champions\n or self.arc_shields\n or self.void_shields\n or self.solar_shields\n or self.stasis_shields\n or self.strand_shields\n or self.modifiers\n )\n\n\n@attr.s\nclass Sector:\n \"\"\"Represents an in game lost sector.\n\n Attributes:\n name (str): Name of the lost sector.\n reward (str): Name of the reward for the lost sector.\n surge (str): Surge of the lost sector.\n threat (str): Threat of the lost sector.\n overcharged_weapon (str): Overcharged weapon of the lost sector.\n shortlink_gfx (str): Shortlink to the lost sector's graphic.\n legend_data (DifficultySpecificSectorData): Data for the lost sector\n on legend difficulty.\n master_data (DifficultySpecificSectorData): Data for the lost sector\n on master difficulty.\n \"\"\"\n\n # From \"Lost Sectors (Internal)\" sheet 0\n name = attr.ib(type=str)\n reward = attr.ib(\"\")\n surge = attr.ib(\"\")\n # From \"Lost Sector Shield & Champion Counts\" sheet 2\n threat = attr.ib(\"\")\n overcharged_weapon = attr.ib(\"\")\n shortlink_gfx = attr.ib(\"\")\n # From \"Lost Sector Shield & Champion Counts\" sheet 0\n legend_data = attr.ib(DifficultySpecificSectorData())\n # From \"Lost Sector Shield & Champion Counts\" sheet 1\n master_data = attr.ib(DifficultySpecificSectorData())\n\n @property\n def surges(self) -> List[str]:\n return [s.strip() for s in self.surge.split(\"&\")]\n\n def __add__(self, other: Sector):\n if not self.name == other.name:\n raise ValueError(\"Cannot add sectors with different names\")\n return Sector(\n self.name,\n self.reward or other.reward,\n self.surge or other.surge,\n self.threat or other.threat,\n self.overcharged_weapon or other.overcharged_weapon,\n self.shortlink_gfx or other.shortlink_gfx,\n self.legend_data or other.legend_data,\n self.master_data or other.master_data,\n )\n\n def to_sector_v1(self) -> SectorV1Compat:\n modifiers = \"\"\n\n if self.legend_data.modifiers:\n modifiers += self.legend_data.modifiers\n\n if self.legend_data.modifiers and self.master_data.modifiers:\n modifiers += \" + \"\n\n if self.master_data.modifiers:\n modifiers += self.master_data.modifiers + \" on Master\"\n\n return SectorV1Compat(\n name=self.name,\n shortlink_gfx=self.shortlink_gfx,\n reward=self.reward,\n champions=self.legend_data.champions,\n shields=self.legend_data.shields,\n burn=self.threat,\n modifiers=modifiers,\n overcharged_weapon=self.overcharged_weapon,\n surge=self.surge,\n )\n\n\nclass SectorData(dict):\n def __init__(\n self,\n general: gspread.Spreadsheet,\n legend: gspread.Spreadsheet,\n master: gspread.Spreadsheet,\n ):\n general = all_values_from_sheet(general, columns_are_major=False)[1:]\n legend = all_values_from_sheet(legend, columns_are_major=False)[1:]\n master = all_values_from_sheet(master, columns_are_major=False)[1:]\n\n for general_row, legend_row, master_row in zip(general, legend, master):\n sector: Sector = self.gspread_data_row_to_sector(\n general_row, legend_row, master_row\n )\n self[sector.name] = sector\n\n @staticmethod\n def gspread_data_row_to_sector(\n general_row: list, legend_row: list, master_row: list\n ) -> Sector:\n return Sector(\n name=general_row[0],\n threat=general_row[1],\n overcharged_weapon=general_row[2],\n shortlink_gfx=general_row[3],\n legend_data=DifficultySpecificSectorData(\n void_shields=legend_row[1],\n solar_shields=legend_row[2],\n arc_shields=legend_row[3],\n stasis_shields=legend_row[4],\n strand_shields=legend_row[5],\n barrier_champions=legend_row[6],\n overload_champions=legend_row[7],\n unstoppable_champions=legend_row[8],\n modifiers=legend_row[9],\n ),\n master_data=DifficultySpecificSectorData(\n void_shields=master_row[1],\n solar_shields=master_row[2],\n arc_shields=master_row[3],\n stasis_shields=master_row[4],\n strand_shields=master_row[5],\n barrier_champions=master_row[6],\n overload_champions=master_row[7],\n unstoppable_champions=master_row[8],\n modifiers=master_row[9],\n ),\n )\n\n\n@attr.s\nclass Rotation:\n start_date = attr.ib(type=dt.datetime)\n _reward_rot = attr.ib(type=EntityRotation)\n _sector_rot = attr.ib(type=EntityRotation)\n _surge_rot = attr.ib(type=EntityRotation)\n _sector_data = attr.ib(SectorData)\n\n @classmethod\n def from_gspread_url(\n cls,\n url: str,\n # Google API credentials, see https://docs.gspread.org/en/latest/oauth2.html\n credentials: dict,\n **kwargs,\n ) -> Self:\n # Instantiates the spreadsheet, only uses the first worksheet by default\n # Ignore the client_factory deprecation warning\n # it looks like gspread.http_client is not implmented as of 5.10\n warnings.filterwarnings(\n \"ignore\",\n message=(\n \"\\[Deprecated\\]\\[in version 6\\.0\\.0\\]: client_factory \"\n + \"will be replaced by gspread\\.http_client types\"\n ),\n )\n spreadsheet: gspread.Spreadsheet = gspread.service_account_from_dict(\n credentials\n ).open_by_url(url)\n return cls.from_gspread(spreadsheet, **kwargs)\n\n @classmethod\n def from_gspread(\n cls, worksheet: gspread.Spreadsheet, buffer: Minutes = 10 # in minutes\n ) -> Rotation:\n rotation_sheet = worksheet.get_worksheet(1)\n legend_sheet = worksheet.get_worksheet(2)\n master_sheet = worksheet.get_worksheet(3)\n general_sheet = worksheet.get_worksheet(4)\n values = all_values_from_sheet(rotation_sheet)\n\n self = cls(\n # Lost sector start date\n cls._start_date_from_gspread(rotation_sheet, buffer),\n reward_rot=EntityRotation.from_gspread(values, 1),\n sector_rot=EntityRotation.from_gspread(values, 2),\n surge_rot=EntityRotation.from_gspread(values, 3),\n sector_data=SectorData(general_sheet, legend_sheet, master_sheet),\n )\n\n return self\n\n def __call__(self, date: Union[dt.datetime, None] = None) -> Sector:\n # Returns the lost sector in rotation on date or for today by default\n date = date if date is not None else dt.datetime.now(tz=utc)\n days_since_ref_date = (date - self.start_date).days\n\n sector = Sector(\n name=self._sector_rot[days_since_ref_date],\n reward=self._reward_rot[days_since_ref_date],\n surge=self._surge_rot[days_since_ref_date],\n )\n\n return sector + self._sector_data[sector.name]\n\n @staticmethod\n def _start_date_from_gspread(\n sheet: gspread.Worksheet, buffer: int = 10 # in minutes\n ) -> dt.datetime:\n # Lost sector schedule start/reference date logic\n # Reset time is set to \"buffer\" minutes before destiny reset\n # This gives 10 minutes of tolerance in case of an early trigger\n # of a lost sector annoucement\n reset_time = dt.timedelta(hours=16, minutes=(60 - buffer))\n # Google sheets epoch date (reference date for all dates in sheets)\n google_sheets_epoch_date = dt.datetime(1899, 12, 30, 0, 0, 0, tzinfo=utc)\n # Note that the reference date below is actually not a date,\n # it is the number of days since the google sheets epoch date\n # hence we need to convert this into a usable date before returning\n ls_reference_date = sheet.acell(\"A2\", \"UNFORMATTED_VALUE\").value\n relative_ls_start_date = dt.timedelta(days=ls_reference_date)\n # Actual lost sector rotation start date\n start_date = relative_ls_start_date + google_sheets_epoch_date + reset_time\n return start_date\n\n def __len__(self):\n return len(self._sector_rot)\n","repo_name":"gs729/sector_accounting","sub_path":"sector_accounting/sector_accounting.py","file_name":"sector_accounting.py","file_ext":"py","file_size_in_byte":11900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13729445828","text":"__author__ = \"Felix Arnold (@fear)\"\n__copyright__ = \"Copyright (c) 2020 Felix Arnold\"\n__credits__ = [\"Richard Moore (@ricmoo)\", \"everybody helping others on stackoverflow or somewhere else\"]\n__license__ = \"MIT\"\n__version__ = \"0.4\"\n__maintainer__ = \"Felix Arnold (@fear)\"\n__email__ = \"hello@felix-arnold.dev\"\n__status__ = \"Beta\"\n__topic__ = \"Home Automation\"\n\nfrom siro.siro import (\n Bridge,\n Driver,\n RadioMotor,\n)\nfrom siro.const import (\n CALLBACK_PORT,\n CONFIGFILE_DEVICE_NAMES,\n CURRENT_STATE,\n DOWN,\n LOG_FILE,\n LOGLEVEL,\n MSG_TYPES,\n MULTICAST_GRP,\n POSITION,\n RADIO_MOTOR,\n SEND_PORT,\n STATE_DOWN,\n STATE_UP,\n STATUS,\n STOP,\n UDP_TIMEOUT,\n UP,\n WIFI_BRIDGE,\n)\n","repo_name":"fear/siro","sub_path":"siro/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"27637160166","text":"import sys\ninput = sys.stdin.readline\n\nn, k = map(int, input().split())\n\ne = list(map(int, input().split()))\n\ncnt = 0\ntable = [[] for _ in range(k+1)]\nfor i in range(k):\n table[e[i]].append(i)\n \nplug = {}\nsize = n\nfor i in range(k):\n if size > 0 and not e[i] in plug:\n plug[e[i]] = i\n size -= 1\n elif size >= 0 and e[i] in plug:\n plug[e[i]] = i\n elif size == 0 and e[i] not in plug:\n remove = [0, 0]\n for key in plug.keys():\n exist = False\n for idx in table[key]:\n if idx > plug[key]:\n exist = True\n if idx > remove[0]:\n remove[0] = idx\n remove[1] = key\n break\n if not exist:\n remove = [plug[key], key]\n break\n plug.pop(remove[1])\n plug[e[i]] = i\n cnt += 1\nprint(cnt)\n ","repo_name":"Hin1209/SWJUNGLE_ALGORITHM","sub_path":"week04/1700멀티탭스케줄링.py","file_name":"1700멀티탭스케줄링.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36025454411","text":"import logging\nimport os\nimport tempfile\nimport time\nimport unittest\n\nimport numpy as np\nimport transformer_util as util\nfrom dygraph_to_static_util import (\n dy2static_unittest,\n test_and_compare_with_new_ir,\n)\nfrom transformer_dygraph_model import (\n CrossEntropyCriterion,\n Transformer,\n position_encoding_init,\n)\n\nimport paddle\nfrom paddle import base\n\ntrainer_count = 1\nplace = base.CUDAPlace(0) if base.is_compiled_with_cuda() else base.CPUPlace()\nSEED = 10\nSTEP_NUM = 10\n\n\n@test_and_compare_with_new_ir(True)\ndef train_static(args, batch_generator):\n paddle.enable_static()\n paddle.seed(SEED)\n paddle.framework.random._manual_program_seed(SEED)\n train_prog = base.Program()\n startup_prog = base.Program()\n\n with base.program_guard(train_prog, startup_prog):\n with base.unique_name.guard():\n # define input and reader\n input_field_names = (\n util.encoder_data_input_fields\n + util.decoder_data_input_fields[:-1]\n + util.label_data_input_fields\n )\n input_descs = util.get_input_descs(args)\n input_slots = [\n {\n \"name\": name,\n \"shape\": input_descs[name][0],\n \"dtype\": input_descs[name][1],\n }\n for name in input_field_names\n ]\n input_field = util.InputField(input_slots)\n # Define DataLoader\n data_loader = paddle.io.DataLoader(\n batch_generator,\n feed_list=input_field.feed_list,\n return_list=False,\n batch_size=None,\n places=place,\n )\n\n # define model\n transformer = Transformer(\n args.src_vocab_size,\n args.trg_vocab_size,\n args.max_length + 1,\n args.n_layer,\n args.n_head,\n args.d_key,\n args.d_value,\n args.d_model,\n args.d_inner_hid,\n args.prepostprocess_dropout,\n args.attention_dropout,\n args.relu_dropout,\n args.preprocess_cmd,\n args.postprocess_cmd,\n args.weight_sharing,\n args.bos_idx,\n args.eos_idx,\n )\n logits = transformer(*input_field.feed_list[:7])\n # define loss\n criterion = CrossEntropyCriterion(args.label_smooth_eps)\n lbl_word, lbl_weight = input_field.feed_list[7:]\n sum_cost, avg_cost, token_num = criterion(\n logits, lbl_word, lbl_weight\n )\n # define optimizer\n learning_rate = paddle.optimizer.lr.NoamDecay(\n args.d_model, args.warmup_steps, args.learning_rate\n )\n optimizer = paddle.optimizer.Adam(\n learning_rate=learning_rate,\n beta1=args.beta1,\n beta2=args.beta2,\n epsilon=float(args.eps),\n )\n optimizer.minimize(avg_cost)\n # the best cross-entropy value with label smoothing\n loss_normalizer = -(\n (1.0 - args.label_smooth_eps)\n * np.log(1.0 - args.label_smooth_eps)\n + args.label_smooth_eps\n * np.log(\n args.label_smooth_eps / (args.trg_vocab_size - 1) + 1e-20\n )\n )\n step_idx = 0\n total_batch_num = 0\n avg_loss = []\n exe = base.Executor(place)\n exe.run(startup_prog)\n for pass_id in range(args.epoch):\n batch_id = 0\n for feed_dict in data_loader:\n outs = exe.run(\n program=train_prog,\n feed=feed_dict,\n fetch_list=[sum_cost.name, token_num.name],\n )\n if step_idx % args.print_step == 0:\n sum_cost_val, token_num_val = np.array(outs[0]), np.array(\n outs[1]\n )\n total_sum_cost = sum_cost_val.sum()\n total_token_num = token_num_val.sum()\n total_avg_cost = total_sum_cost / total_token_num\n avg_loss.append(total_avg_cost)\n if step_idx == 0:\n logging.info(\n \"step_idx: %d, epoch: %d, batch: %d, avg loss: %f, \"\n \"normalized loss: %f, ppl: %f\"\n % (\n step_idx,\n pass_id,\n batch_id,\n total_avg_cost,\n total_avg_cost - loss_normalizer,\n np.exp([min(total_avg_cost, 100)]),\n )\n )\n avg_batch_time = time.time()\n else:\n logging.info(\n \"step_idx: %d, epoch: %d, batch: %d, avg loss: %f, \"\n \"normalized loss: %f, ppl: %f, speed: %.2f steps/s\"\n % (\n step_idx,\n pass_id,\n batch_id,\n total_avg_cost,\n total_avg_cost - loss_normalizer,\n np.exp([min(total_avg_cost, 100)]),\n args.print_step / (time.time() - avg_batch_time),\n )\n )\n avg_batch_time = time.time()\n batch_id += 1\n step_idx += 1\n total_batch_num = total_batch_num + 1\n if step_idx == STEP_NUM:\n if args.save_dygraph_model_path:\n model_path = os.path.join(\n args.save_static_model_path, \"transformer\"\n )\n paddle.static.save(train_prog, model_path)\n break\n return np.array(avg_loss)\n\n\ndef train_dygraph(args, batch_generator):\n with base.dygraph.guard(place):\n if SEED is not None:\n paddle.seed(SEED)\n paddle.framework.random._manual_program_seed(SEED)\n # define data loader\n\n train_loader = paddle.io.DataLoader(\n batch_generator, batch_size=None, places=place\n )\n\n # define model\n transformer = Transformer(\n args.src_vocab_size,\n args.trg_vocab_size,\n args.max_length + 1,\n args.n_layer,\n args.n_head,\n args.d_key,\n args.d_value,\n args.d_model,\n args.d_inner_hid,\n args.prepostprocess_dropout,\n args.attention_dropout,\n args.relu_dropout,\n args.preprocess_cmd,\n args.postprocess_cmd,\n args.weight_sharing,\n args.bos_idx,\n args.eos_idx,\n )\n # define loss\n criterion = CrossEntropyCriterion(args.label_smooth_eps)\n # define optimizer\n learning_rate = paddle.optimizer.lr.NoamDecay(\n args.d_model, args.warmup_steps, args.learning_rate\n )\n # define optimizer\n optimizer = paddle.optimizer.Adam(\n learning_rate=learning_rate,\n beta1=args.beta1,\n beta2=args.beta2,\n epsilon=float(args.eps),\n parameters=transformer.parameters(),\n )\n # the best cross-entropy value with label smoothing\n loss_normalizer = -(\n (1.0 - args.label_smooth_eps) * np.log(1.0 - args.label_smooth_eps)\n + args.label_smooth_eps\n * np.log(args.label_smooth_eps / (args.trg_vocab_size - 1) + 1e-20)\n )\n ce_time = []\n ce_ppl = []\n avg_loss = []\n step_idx = 0\n for pass_id in range(args.epoch):\n pass_start_time = time.time()\n batch_id = 0\n for input_data in train_loader():\n (\n src_word,\n src_pos,\n src_slf_attn_bias,\n trg_word,\n trg_pos,\n trg_slf_attn_bias,\n trg_src_attn_bias,\n lbl_word,\n lbl_weight,\n ) = input_data\n logits = transformer(\n src_word,\n src_pos,\n src_slf_attn_bias,\n trg_word,\n trg_pos,\n trg_slf_attn_bias,\n trg_src_attn_bias,\n )\n sum_cost, avg_cost, token_num = criterion(\n logits, lbl_word, lbl_weight\n )\n avg_cost.backward()\n optimizer.minimize(avg_cost)\n transformer.clear_gradients()\n if step_idx % args.print_step == 0:\n total_avg_cost = avg_cost.numpy() * trainer_count\n avg_loss.append(float(total_avg_cost))\n if step_idx == 0:\n logging.info(\n \"step_idx: %d, epoch: %d, batch: %d, avg loss: %f, \"\n \"normalized loss: %f, ppl: %f\"\n % (\n step_idx,\n pass_id,\n batch_id,\n total_avg_cost,\n total_avg_cost - loss_normalizer,\n np.exp([min(total_avg_cost, 100)]),\n )\n )\n avg_batch_time = time.time()\n else:\n logging.info(\n \"step_idx: %d, epoch: %d, batch: %d, avg loss: %f, \"\n \"normalized loss: %f, ppl: %f, speed: %.2f steps/s\"\n % (\n step_idx,\n pass_id,\n batch_id,\n total_avg_cost,\n total_avg_cost - loss_normalizer,\n np.exp([min(total_avg_cost, 100)]),\n args.print_step\n / (time.time() - avg_batch_time),\n )\n )\n ce_ppl.append(np.exp([min(total_avg_cost, 100)]))\n avg_batch_time = time.time()\n batch_id += 1\n step_idx += 1\n if step_idx == STEP_NUM:\n if args.save_dygraph_model_path:\n model_dir = os.path.join(args.save_dygraph_model_path)\n if not os.path.exists(model_dir):\n os.makedirs(model_dir)\n paddle.save(\n transformer.state_dict(),\n os.path.join(model_dir, \"transformer\")\n + '.pdparams',\n )\n paddle.save(\n optimizer.state_dict(),\n os.path.join(model_dir, \"transformer\")\n + '.pdparams',\n )\n break\n time_consumed = time.time() - pass_start_time\n ce_time.append(time_consumed)\n return np.array(avg_loss)\n\n\ndef predict_dygraph(args, batch_generator):\n with base.dygraph.guard(place):\n paddle.seed(SEED)\n paddle.framework.random._manual_program_seed(SEED)\n\n # define data loader\n test_loader = paddle.io.DataLoader(\n batch_generator, batch_size=None, places=place\n )\n\n # define model\n transformer = Transformer(\n args.src_vocab_size,\n args.trg_vocab_size,\n args.max_length + 1,\n args.n_layer,\n args.n_head,\n args.d_key,\n args.d_value,\n args.d_model,\n args.d_inner_hid,\n args.prepostprocess_dropout,\n args.attention_dropout,\n args.relu_dropout,\n args.preprocess_cmd,\n args.postprocess_cmd,\n args.weight_sharing,\n args.bos_idx,\n args.eos_idx,\n )\n\n # load the trained model\n model_dict, _ = util.load_dygraph(\n os.path.join(args.save_dygraph_model_path, \"transformer\")\n )\n # to avoid a longer length than training, reset the size of position\n # encoding to max_length\n model_dict[\"encoder.pos_encoder.weight\"] = position_encoding_init(\n args.max_length + 1, args.d_model\n )\n model_dict[\"decoder.pos_encoder.weight\"] = position_encoding_init(\n args.max_length + 1, args.d_model\n )\n transformer.load_dict(model_dict)\n\n # set evaluate mode\n transformer.eval()\n\n step_idx = 0\n speed_list = []\n for input_data in test_loader():\n (\n src_word,\n src_pos,\n src_slf_attn_bias,\n trg_word,\n trg_src_attn_bias,\n ) = input_data\n seq_ids, seq_scores = transformer.beam_search(\n src_word,\n src_pos,\n src_slf_attn_bias,\n trg_word,\n trg_src_attn_bias,\n bos_id=args.bos_idx,\n eos_id=args.eos_idx,\n beam_size=args.beam_size,\n max_len=args.max_out_len,\n )\n seq_ids = seq_ids.numpy()\n seq_scores = seq_scores.numpy()\n if step_idx % args.print_step == 0:\n if step_idx == 0:\n logging.info(\n \"Dygraph Predict: step_idx: %d, 1st seq_id: %d, 1st seq_score: %.2f\"\n % (step_idx, seq_ids[0][0][0], seq_scores[0][0])\n )\n avg_batch_time = time.time()\n else:\n speed = args.print_step / (time.time() - avg_batch_time)\n speed_list.append(speed)\n logging.info(\n \"Dygraph Predict: step_idx: %d, 1st seq_id: %d, 1st seq_score: %.2f, speed: %.3f steps/s\"\n % (step_idx, seq_ids[0][0][0], seq_scores[0][0], speed)\n )\n avg_batch_time = time.time()\n\n step_idx += 1\n if step_idx == STEP_NUM:\n break\n logging.info(\n \"Dygraph Predict: avg_speed: %.4f steps/s\" % (np.mean(speed_list))\n )\n return seq_ids, seq_scores\n\n\n@test_and_compare_with_new_ir(True)\ndef predict_static(args, batch_generator):\n test_prog = base.Program()\n with base.program_guard(test_prog):\n paddle.seed(SEED)\n paddle.framework.random._manual_program_seed(SEED)\n\n # define input and reader\n input_field_names = (\n util.encoder_data_input_fields + util.fast_decoder_data_input_fields\n )\n input_descs = util.get_input_descs(args, 'test')\n input_slots = [\n {\n \"name\": name,\n \"shape\": input_descs[name][0],\n \"dtype\": input_descs[name][1],\n }\n for name in input_field_names\n ]\n\n input_field = util.InputField(input_slots)\n feed_list = input_field.feed_list\n\n loader = paddle.io.DataLoader(\n batch_generator,\n feed_list=feed_list,\n return_list=False,\n batch_size=None,\n places=place,\n )\n\n # define model\n transformer = Transformer(\n args.src_vocab_size,\n args.trg_vocab_size,\n args.max_length + 1,\n args.n_layer,\n args.n_head,\n args.d_key,\n args.d_value,\n args.d_model,\n args.d_inner_hid,\n args.prepostprocess_dropout,\n args.attention_dropout,\n args.relu_dropout,\n args.preprocess_cmd,\n args.postprocess_cmd,\n args.weight_sharing,\n args.bos_idx,\n args.eos_idx,\n )\n\n out_ids, out_scores = transformer.beam_search(\n *feed_list,\n bos_id=args.bos_idx,\n eos_id=args.eos_idx,\n beam_size=args.beam_size,\n max_len=args.max_out_len\n )\n\n # This is used here to set dropout to the test mode.\n test_prog = test_prog.clone(for_test=True)\n\n # define the executor and program for training\n exe = base.Executor(place)\n\n util.load(\n test_prog, os.path.join(args.save_static_model_path, \"transformer\"), exe\n )\n\n loader.set_batch_generator(batch_generator, places=place)\n\n step_idx = 0\n speed_list = []\n for feed_dict in loader:\n seq_ids, seq_scores = exe.run(\n test_prog,\n feed=feed_dict,\n fetch_list=[out_ids.name, out_scores.name],\n return_numpy=True,\n )\n if step_idx % args.print_step == 0:\n if step_idx == 0:\n logging.info(\n \"Static Predict: step_idx: %d, 1st seq_id: %d, 1st seq_score: %.2f,\"\n % (step_idx, seq_ids[0][0][0], seq_scores[0][0])\n )\n avg_batch_time = time.time()\n else:\n speed = args.print_step / (time.time() - avg_batch_time)\n speed_list.append(speed)\n logging.info(\n \"Static Predict: step_idx: %d, 1st seq_id: %d, 1st seq_score: %.2f, speed: %.3f steps/s\"\n % (step_idx, seq_ids[0][0][0], seq_scores[0][0], speed)\n )\n avg_batch_time = time.time()\n\n step_idx += 1\n if step_idx == STEP_NUM:\n break\n logging.info(\n \"Static Predict: avg_speed: %.4f steps/s\" % (np.mean(speed_list))\n )\n\n return seq_ids, seq_scores\n\n\n@dy2static_unittest\nclass TestTransformer(unittest.TestCase):\n def setUp(self):\n self.temp_dir = tempfile.TemporaryDirectory()\n\n def tearDwon(self):\n self.temp_dir.cleanup()\n\n def prepare(self, mode='train'):\n args = util.ModelHyperParams()\n args.save_dygraph_model_path = os.path.join(\n self.temp_dir.name, args.save_dygraph_model_path\n )\n args.save_static_model_path = os.path.join(\n self.temp_dir.name, args.save_static_model_path\n )\n args.inference_model_dir = os.path.join(\n self.temp_dir.name, args.inference_model_dir\n )\n args.output_file = os.path.join(self.temp_dir.name, args.output_file)\n batch_generator = util.get_feed_data_reader(args, mode)\n if mode == 'train':\n batch_generator = util.TransedWMT16TrainDataSet(\n batch_generator, args.batch_size * (args.epoch + 1)\n )\n else:\n batch_generator = util.TransedWMT16TestDataSet(\n batch_generator, args.batch_size * (args.epoch + 1)\n )\n return args, batch_generator\n\n def _test_train(self):\n args, batch_generator = self.prepare(mode='train')\n static_avg_loss = train_static(args, batch_generator)\n dygraph_avg_loss = train_dygraph(args, batch_generator)\n np.testing.assert_allclose(\n static_avg_loss, dygraph_avg_loss, rtol=1e-05\n )\n\n def _test_predict(self):\n args, batch_generator = self.prepare(mode='test')\n static_seq_ids, static_scores = predict_static(args, batch_generator)\n dygraph_seq_ids, dygraph_scores = predict_dygraph(args, batch_generator)\n\n np.testing.assert_allclose(static_seq_ids, static_seq_ids, rtol=1e-05)\n np.testing.assert_allclose(static_scores, dygraph_scores, rtol=1e-05)\n\n def test_check_result(self):\n self._test_train()\n # TODO(zhangliujie) fix predict fail due to precision misalignment\n # self._test_predict()\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"PaddlePaddle/Paddle","sub_path":"test/dygraph_to_static/test_transformer.py","file_name":"test_transformer.py","file_ext":"py","file_size_in_byte":20248,"program_lang":"python","lang":"en","doc_type":"code","stars":21032,"dataset":"github-code","pt":"29"} +{"seq_id":"42489139672","text":"#We will first be looking at Feature Selection with VarianceThreshold.\n# VarianceThreshold is a useful tool to removing features with a threshold variance.\n# It is a simple and basic Feature Selection.\nfrom sklearn.feature_selection import VarianceThreshold\n# nstantiate VarianceThreshold as a variable\nsel = VarianceThreshold()\n#VarianceThreshold removes all zero-variance features by default.\n# These features are any constant value features.\n\ndataset = [[0, 2, 0, 3], [0, 1, 4, 3], [0, 1, 1, 3]]\nprint (dataset)\n#VarianceThreshold removes all zero-variance features by default.\n# These features are any constant value features\nsel.fit_transform(dataset)\n#We can change the threshold by adding threshold='threshold value'\n# inside the brackets during the instantiation of VarianceThreshold.\n# Where 'threshold value' is equal to p(1-p) Where 'p' is your threshold % in decimal format.\n# 60% threshold\nsel60 = VarianceThreshold(threshold=(0.6 * (1 - 0.6)))\n#We will need to import SelectKBest from sklearn.feature_selection,\n# chi2 from sklearn.feature_selection, numpy as np, and pandas.\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\nimport numpy as np\nimport pandas\nmy_data = pandas.read_csv(\"https://vincentarelbundock.github.io/Rdatasets/csv/HSAUR/skulls.csv\", delimiter=\",\")\n\n# Remove the column containing the target name since it doesn't contain numeric values.\n# Also remove the column that contains the row number\n# axis=1 means we are removing columns instead of rows.\n# Function takes in a pandas array and column numbers and returns a numpy array without\n# the stated columns\ndef removeColumns(pandasArray, *column):\n return pandasArray.drop(pandasArray.columns[[column]], axis=1).values\nX = removeColumns(my_data, 0, 1)\n\ndef target(numpyArray, targetColumnIndex):\n target_dict = dict()\n target = list()\n count = -1\n for i in range(len(my_data.values)):\n if my_data.values[i][targetColumnIndex] not in target_dict:\n count += 1\n target_dict[my_data.values[i][targetColumnIndex]] = count\n target.append(target_dict[my_data.values[i][targetColumnIndex]])\n return np.asarray(target)\ny = target(my_data, 1)\nprint (X.shape)\n#How Univariance works is that it selects features based off of univariance statistical tests.\n# chi2 is used as a univariance scoring function which returns p values.\n# We specified k=3 for the 3 best features to be chosen.\nX_new = SelectKBest(chi2, k=3).fit_transform(X, y)\n#we will use the fit_transform function with parameters\n# X, y of SelectKBest with parameters chi2, k=3. This will be stored as X_new.\nprint (X_new.shape)\n\n#DictVectorizer is a very simple Feature Extraction class\n# as it can be used to convert feature arrays in a dict to NumPy/SciPy representations.\nfrom sklearn.feature_extraction import DictVectorizer\ndataset = [\n {'Day': 'Monday', 'Temperature': 18},\n {'Day': 'Tuesday', 'Temperature': 13},\n {'Day': 'Wednesday', 'Temperature': 7},\n]\nvec = DictVectorizer()\nvec.fit_transform(dataset).toarray()\nprint (vec.get_feature_names())\n\n#pip install --upgrade matplotlib\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn import decomposition\n#%matplotlib inline\n\nfig = plt.figure(1, figsize=(10, 8))\nax = Axes3D(fig, rect=[0, 0, .95, 1], elev=0, azim=0)\nax.scatter(X_new[:, 0], X_new[:, 1], X_new[:, 2], c=y, cmap=plt.cm.seismic)\nax.set_xlabel('X Label')\nax.set_ylabel('Y Label')\nax.set_zlabel('Z Label')\nplt.show()\n\npca = decomposition.PCA(n_components=2)\npca.fit(X_new)\nPCA_X = pca.transform(X_new)\nprint (PCA_X.shape)","repo_name":"pawan-agnihotri/PycharmProjects","sub_path":"untitled/python/unsupervised/PCA.py","file_name":"PCA.py","file_ext":"py","file_size_in_byte":3621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"27310580806","text":"import requests\r\n\r\nclass CurrencyConverter:\r\n \"\"\"\r\n A simple currency converter class that converts between different currencies using the Exchange Rates API.\r\n \"\"\"\r\n\r\n def __init__(self, api_key):\r\n self.api_key = api_key\r\n self.base_url = \"https://api.exchangeratesapi.io/latest\"\r\n\r\n def convert(self, amount, from_currency, to_currency):\r\n \"\"\"\r\n Convert an amount from one currency to another.\r\n \"\"\"\r\n # Construct the API URL.\r\n url = f\"{self.base_url}?access_key={self.api_key}&base={from_currency}&symbols={to_currency}\"\r\n\r\n # Make the API request.\r\n response = requests.get(url)\r\n\r\n if response.status_code == 200:\r\n # Parse the response JSON.\r\n response_json = response.json()\r\n\r\n # Get the exchange rate from the response.\r\n exchange_rate = response_json[\"rates\"][to_currency]\r\n\r\n # Convert the amount using the exchange rate.\r\n converted_amount = amount * exchange_rate\r\n\r\n return converted_amount\r\n else:\r\n # Handle API errors.\r\n response.raise_for_status()\r\n\r\n# Example usage: convert 100 USD to EUR.\r\nconverter = CurrencyConverter(api_key=\"your_api_key_here\")\r\n\r\namount = 100\r\nfrom_currency = \"USD\"\r\nto_currency = \"EUR\"\r\n\r\nconverted_amount = converter.convert(amount, from_currency, to_currency)\r\n\r\nprint(f\"{amount} {from_currency} = {converted_amount} {to_currency}\")\r\n","repo_name":"mayurpatle/Exchange-Rates-API-","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28551329853","text":"#DEV 1/NOV/2022 JAKSON LEAL\nimport pyautogui as pg, webbrowser as web, time as t\nimport pyperclip as ppc\nimport util.Recordatorio as r\n\ndef enviarWhatsapp(numWhatsapp, name, correoDestino, direccion, txtValor, deuda):\n \n message = r.mensaje(numWhatsapp, name, correoDestino, direccion, txtValor, deuda)\n\n #formatear numero\n phone_no = \"+57\"+str(numWhatsapp)\n parsedMessage=\"\"\n\n #API de whatsapp\n web.open('https://web.whatsapp.com/send?phone='+phone_no+'&text='+parsedMessage) #abrir una ventana en el navegador\n \n t.sleep(12)\n ppc.copy(message)\n pg.hotkey('ctrl', 'v')\n t.sleep(6)\n pg.press('enter')\n t.sleep(5)\n pg.hotkey('ctrl', 'w')\n t.sleep(2)\n","repo_name":"JaksonLeal/cobros-python","sub_path":"util/Whatsapp.py","file_name":"Whatsapp.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"42892034422","text":"from urllib import urlencode\nimport urllib, re\n\ndef tsol(arret, dir):\n dir = dir.lower();\n if not dir in ['a', 'r']:\n dir = 'a'\n\n directions = {'a':'L', 'r':'R'}\n\n base_url = 'http://www.t-l.ch/htr.php?'\n payload = dict(ligne='70', sens=dir, arret=arret+'_'+directions[dir])\n socket = urllib.urlopen( base_url + urlencode(payload))\n content = socket.read()\n socket.close()\n\n table_re = re.compile(']*id=\\\"htr_param_table\\\"[^>]*>(.*)<\\/table>', re.I|re.M|re.S)\n time_re = re.compile(']*>]*>([^<]*)<\\/span>[^<]*<\\/td>', re.I|re.M|re.S)\n table = table_re.findall(content)\n if len(table) == 0:\n return []\n elements = time_re.findall(table[0])\n\n return elements\n","repo_name":"anbreww/robopoly-api","sub_path":"robopolyapi/helpers/tsol.py","file_name":"tsol.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"34925779648","text":"#-*-Mode:python;coding:utf-8;tab-width:4;c-basic-offset:4;indent-tabs-mode:()-*-\n# ex: set ft=python fenc=utf-8 sts=4 ts=4 sw=4 et nomod:\n\"\"\"\nCloudI Service API .\n\"\"\"\n\n# pylint: disable=wrong-import-position\nimport sys\nimport os\n_FILE_DIRECTORY = os.path.dirname(os.path.abspath(__file__)).split(os.path.sep)\nsys.path.extend([\n os.path.sep.join(_FILE_DIRECTORY + ['jsonrpclib']),\n])\nimport jsonrpclib\n\nclass CloudI(object):\n \"\"\"\n CloudI Service API object (communicating with JSON-RPC)\n \"\"\"\n # pylint: disable=too-few-public-methods\n\n # initialize with configuration file defaults\n def __init__(self, host='localhost', port=6464):\n address = 'http://%s:%d/cloudi/api/rpc.json' % (host, port)\n self.__server = jsonrpclib.Server(address)\n\n def __getattr__(self, name):\n return self.__server.__getattr__(name)\n","repo_name":"CloudI/CloudI","sub_path":"src/service_api/python/cloudi_service_api.py","file_name":"cloudi_service_api.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":395,"dataset":"github-code","pt":"29"} +{"seq_id":"31624665521","text":"from django import forms\nfrom django.contrib.auth.forms import UserCreationForm, UserChangeForm\nfrom django.db import transaction\nfrom .models import User,Useradminpage, Vacancies, Summaries\nfrom django.dispatch import receiver\nfrom django.contrib.auth.models import Group\nfrom summary_vacancy.models import Professions_da, Language_Da, Vacancies_Createes, Student, Marks\nfrom django.views.generic import CreateView, ListView, View\nfrom django.db import transaction\nfrom django.dispatch import receiver\nfrom django.forms import CheckboxSelectMultiple\n\nfrom multiselectfield import MultiSelectField\n\n\nclass UserChangeForm(UserChangeForm):\n\n class Meta:\n model = User\n fields = ('last_name', 'first_name', 'email')\n\n\n\n# FORM FAQAT ADMINISTRATORLARNI RO'YHATDAN O'TKAZISH UCHUN\nclass UseradminpageSignUpForm(UserCreationForm):\n last_name = forms.CharField(required=True)\n first_name = forms.CharField(required=True) \n email = forms.CharField(required=True)\n father_name = forms.CharField(required=True)\n admin_image = forms.ImageField(required=True) \n\n \n class Meta(UserCreationForm.Meta):\n model = User \n\n @transaction.atomic\n def save(self, commit=True):\n user = super().save(commit=False)\n user.is_customer = True\n user.is_employee = True\n user.is_active = True\n user.is_staff = True\n user.is_superuser = True\n user.save() \n\n user.first_name = self.cleaned_data.get('first_name')\n user.last_name = self.cleaned_data.get('last_name')\n user.email = self.cleaned_data.get('email')\n user.save()\n useradminpage = Useradminpage.objects.create(user=user)\n useradminpage.father_name=self.cleaned_data.get('father_name')\n useradminpage.admin_image = self.cleaned_data.get('admin_image') \n \n \n useradminpage.save()\n return user\n \n \n\n\n\n# FORM FAQAT ADMINISTRATORLARNI RO'YHATDAN O'TKAZISH UCHUN\nclass UservacanciesSignUpForm(UserCreationForm):\n last_name = forms.CharField(required=True, widget=forms.TextInput(\n attrs = {'class':'form-control', 'placeholder': 'фамилия'}\n ))\n first_name = forms.CharField(required=True, widget=forms.TextInput(\n attrs = {'class':'form-control', 'placeholder': 'имя'}\n )) \n father_name = forms.CharField(required=True, widget=forms.TextInput(\n attrs = {'class':'form-control', 'placeholder': 'отчество'}\n ))\n email = forms.CharField(required=True, widget=forms.TextInput(\n attrs = {'class':'form-control', 'placeholder': 'электронная почта'}\n ))\n phone_numer = forms.CharField(required=True, widget=forms.TextInput(\n attrs = {'class':'form-control', 'placeholder': 'номер телефона '}\n ))\n name_company = forms.CharField(required=True, widget=forms.TextInput(\n attrs = {'class':'form-control', 'placeholder': 'названия компания'}\n ))\n region = forms.CharField(required=True, widget=forms.TextInput(\n attrs = {'class':'form-control', 'placeholder': '��егион'}\n ))\n \n class Meta(UserCreationForm.Meta):\n model = User \n\n @transaction.atomic\n def save(self, commit=True):\n user = super().save(commit=False)\n user.is_active = True\n user.is_staff = True\n \n if commit:\n user.save()\n group = Group.objects.get(name=\"vacancies\")\n user.groups.add(group)\n\n user.first_name = self.cleaned_data.get('first_name')\n user.last_name = self.cleaned_data.get('last_name')\n user.email = self.cleaned_data.get('email')\n user.save()\n useradminpage = Vacancies.objects.create(user=user)\n useradminpage.father_name=self.cleaned_data.get('father_name')\n useradminpage.phone_numer=self.cleaned_data.get('phone_numer')\n useradminpage.name_company=self.cleaned_data.get('name_company')\n useradminpage.region=self.cleaned_data.get('region')\n useradminpage.save()\n return user\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['username'].widget.attrs.update({'class': 'form-control', 'placeholder': 'логин'}) \n self.fields['password1'].widget.attrs.update({'class': 'form-control', 'placeholder': 'пароль'}) \n self.fields['password2'].widget.attrs.update({'class': 'form-control', 'placeholder': 'проверка пароль'}) \n \n\n\n\n \n\n# FORM FAQAT ADMINISTRATORLARNI RO'YHATDAN O'TKAZISH UCHUN\nclass UsersummariesSignUpForm(UserCreationForm):\n last_name = forms.CharField(required=True, widget=forms.TextInput(\n attrs = {'class':'form-control', 'placeholder': 'фамилия'}\n ))\n first_name = forms.CharField(required=True, widget=forms.TextInput(\n attrs = {'class':'form-control', 'placeholder': 'имя'}\n )) \n email = forms.CharField(required=True, widget=forms.TextInput(\n attrs = {'class':'form-control', 'placeholder': 'электронная почта или номер телефона'}\n ))\n\n \n class Meta(UserCreationForm.Meta):\n model = User \n\n @transaction.atomic\n def save(self, commit=True):\n user = super().save(commit=False)\n user.is_active = True\n user.is_staff = True\n\n if commit:\n user.save()\n group = Group.objects.get(name=\"summaries\")\n user.groups.add(group)\n\n user.first_name = self.cleaned_data.get('first_name')\n user.last_name = self.cleaned_data.get('last_name')\n user.email = self.cleaned_data.get('email')\n user.save()\n useradminpage = Summaries.objects.create(user=user)\n\n useradminpage.save()\n return user\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['username'].widget.attrs.update({'class': 'form-control', 'placeholder': 'логин'}) \n self.fields['password1'].widget.attrs.update({'class': 'form-control', 'placeholder': 'пароль'}) \n self.fields['password2'].widget.attrs.update({'class': 'form-control', 'placeholder': 'проверка пароль'})\n\n\n\n\nclass SummariesUpdateForm(forms.ModelForm):\n\n class Meta:\n model = Summaries\n fields = ('father_name',)\n\n\nclass SummariesssUpdateForm(forms.ModelForm):\n\n class Meta:\n model = Summaries\n fields = ('summary_image_u',)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['summary_image_u'].widget.attrs.update({'class': 'form-control'}) \n \n\n\n\n\n\n\n\n\n\n\n\nSEX_CHOICES = (\n ('Мужской', 'Мужской'),\n ('Женский', 'Женский'),\n\n )\nWORK_CHOICES = (\n ('Есть опыт работы', 'Есть опыт работы'),\n ('Нет опыта работы', 'Нет опыта работы'),\n\n )\nDG_CHOICES = (\n ('неокончание выше', 'неокончание выше'),\n ('высшее', 'высшее'),\n ('бакалавр', 'бакалавр'),\n ('магистр', 'Магистр'),\n ('магистр', 'Магистр'),\n ('кандидат наук', 'кандидат наук'),\n ('доктор наук', 'доктор наук'),\n )\n\nSAL_CHOICES = (\n ('руб', 'руб'),\n ('USD', 'USD'),\n ('EUR', 'EUR'),\n\n )\nLAN_CHOICES = (\n ('английский', 'английский'),\n ('русский', 'русский'),\n ('немецкий', 'немецкий'),\n )\n\nclass StudentForm(forms.ModelForm):\n\n last_name = forms.CharField(required=False, widget=forms.TextInput(\n attrs = {'class':'form-control', 'type':'text', 'placeholder': \"Фамилия\"}\n ))\n first_name = forms.CharField(required=False, widget=forms.TextInput(\n attrs = {'class':'form-control', 'type':'text', 'placeholder': \"Имя\"}\n ))\n phone_numer = forms.CharField(required=False, widget=forms.TextInput(\n attrs = {'class':'form-control', 'type':'number', 'placeholder': \"+7\"}\n ))\n city_of_residence = forms.CharField(required=False, widget=forms.TextInput(\n attrs = {'class':'form-control', 'type':'text', 'placeholder': \"Город проживания\"}\n ))\n date_of_birth = forms.CharField(required=False, widget=forms.TextInput(\n attrs = {'class':'form-control', 'type':'date', 'placeholder': \"Дата рождения\"}\n ))\n sex = forms.ChoiceField(choices=SEX_CHOICES, widget=forms.RadioSelect)\n \n work = forms.ChoiceField(required=False, choices=WORK_CHOICES, widget=forms.RadioSelect)\n\n career_objective = forms.CharField(required=False, widget=forms.TextInput(\n attrs = {'class':'form-control', 'type':'text', 'placeholder': \"Желаемая должность\"}\n ))\n salary = forms.CharField(required=False, widget=forms.TextInput(\n attrs = {'class':'form-control col-md-12', 'type':'number', 'placeholder': \"Зарплата\"}\n ))\n salaryy = forms.ChoiceField(required=False, choices = SAL_CHOICES)\n dgree = forms.ChoiceField(required=False, choices = DG_CHOICES)\n language = forms.ChoiceField(required=False, choices = LAN_CHOICES) \n\n # professions = forms.ModelMultipleChoiceField(queryset=Professions_da.objects.all(), widget=forms.CheckboxSelectMultiple(), required=False)\n opnachala = forms.CharField(required=False, widget=forms.TextInput(\n attrs = {'class':'form-control col-md-12', 'type':'date', 'placeholder': \"Начало работы\"}\n ))\n opndo = forms.CharField(required=False, widget=forms.TextInput(\n attrs = {'class':'form-control col-md-12', 'type':'date', 'placeholder': \"По настоящее время\"}\n ))\n organizatsiya = forms.CharField(required=False, widget=forms.TextInput(\n attrs = {'class':'form-control col-md-12', 'type':'text', 'placeholder': \"Организация\"}\n ))\n doljinos = forms.CharField(required=False, widget=forms.TextInput(\n attrs = {'class':'form-control col-md-12', 'type':'text', 'placeholder': \"Должность\"}\n ))\n shto_vi_del_na = forms.CharField(required=False, widget=forms.Textarea(\n attrs = {'class':'form-control col-md-12', 'type':'text', 'placeholder': \"Обязанности на рабочем месте\"}\n ))\n raskajiti_o_sebya = forms.CharField(required=False, widget=forms.Textarea(\n attrs = {'class':'form-control col-md-12', 'type':'text', 'placeholder': \"О себе\"}\n ))\n kluchniy_naviki = forms.CharField(required=False, widget=forms.TextInput(\n attrs = {'class':'form-control col-md-12', 'type':'text', 'placeholder': \"Ключевые навыки\"}\n ))\n # languagee = forms.ModelMultipleChoiceField(queryset=Language_Da.objects.all(), required=False, widget=forms.CheckboxSelectMultiple())\n\n\n\n class Meta:\n model = Student\n\n fields = [\n # 'user',\n 'last_name',\n 'first_name',\n 'phone_numer',\n 'city_of_residence',\n 'date_of_birth',\n 'sex', \n 'work',\n 'career_objective',\n 'salary',\n 'salaryy',\n 'dgree',\n 'language',\n # 'professions',\n 'opnachala',\n 'opndo',\n 'organizatsiya',\n 'doljinos',\n 'shto_vi_del_na',\n 'raskajiti_o_sebya', \n 'kluchniy_naviki',\n 'Abxaziya',\n 'Avstraliya',\n 'Avstriya',\n 'Ozarbayjon',\n 'Albaniya',\n 'Jazoir',\n 'Angola', \n 'Andorra',\n 'Argentina',\n 'Armaniston',\n 'Afgoniston',\n 'Bagama_orollari',\n 'Bangladesh',\n 'Barbados',\n 'Bahrayn',\n 'Belorussiya',\n 'Beliz',\n 'Belgiya',\n 'Bolgariya',\n 'Boliviya',\n 'Bosniya_Gertsegovina',\n 'Braziliya', \n 'Bruney_Darussalom',\n 'Burkina_Faso', \n 'Buyuk_Britaniya',\n 'Vengriya', \n 'Venesuela',\n 'Vetnam',\n 'Gabon', \n 'Gvineya',\n 'Germaniya',\n 'Rossiya',\n 'AQSH',\n 'Ozbekiston',\n 'Yaponiya',\n 'English',\n 'French',\n 'German',\n 'Ukrainian',\n 'Italian',\n 'Uzbek',\n 'Car',\n 'Administrative',\n 'Accounting_department',\n 'Mining',\n 'Other',\n 'Procurement',\n 'Information',\n 'Art',\n 'Consulting',\n 'Marketing',\n 'The_medicine', \n 'The_science',\n 'Sales',\n 'Production',\n 'Working',\n 'Insurance',\n 'Building',\n 'Transport',\n 'Tourism',\n 'Control',\n 'Finance',\n 'Lawyers',\n \n ]\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # self.fields['user'].widget.attrs.update({'class': 'form-control'}) \n self.fields['salaryy'].widget.attrs.update({'class': 'form-control col-md-6'}) \n self.fields['dgree'].widget.attrs.update({'class': 'form-control'}) \n self.fields['language'].widget.attrs.update({'class': 'form-control'}) \n\n\nclass MarksForm(forms.ModelForm):\n class_name = forms.CharField(required=False, widget=forms.TextInput(\n attrs = {'class':'form-control col-md-12', 'type':'text', 'placeholder': \"Учебное заведение\"}\n ))\n english = forms.CharField(required=False, widget=forms.TextInput(\n attrs = {'class':'form-control col-md-12', 'type':'text', 'placeholder': \"Факультет\"}\n ))\n nepali = forms.CharField(required=False, widget=forms.TextInput(\n attrs = {'class':'form-control col-md-12', 'type':'text', 'placeholder': \"Специализация\"}\n ))\n nepalii = forms.CharField(required=False, widget=forms.TextInput(\n attrs = {'class':'form-control col-md-12', 'type':'text', 'placeholder': \"Год окончания\"}\n ))\n class Meta:\n model = Marks\n\n fields = [\n 'class_name',\n 'english',\n 'nepali',\n 'nepalii',\n ]\n\n widgets = {\n 'class_name': forms.TextInput(attrs={'class': 'formset-field'}),\n 'english': forms.TextInput(attrs={'class': 'formset-field'}),\n 'nepali': forms.TextInput(attrs={'class': 'formset-field'}),\n 'nepalii': forms.TextInput(attrs={'class': 'formset-field'})\n }\n\n\n\n\n\n\n\n\n\n\n\n\nNAL_CHOICES = (\n ('до вычета налогов', 'до вычета налогов'),\n ('на руки', 'на руки'),\n\n )\n\nTIPZ_CHOICES = (\n ('полная занятость', 'полная занятость'),\n ('частные занятость', 'частные занятость'),\n ('проектная работа или розовое задание', 'проектная работа или розовое задание'),\n ('волонтерство', 'волонтерство'),\n ('стажировка', 'стажировка'),\n\n )\n\nRABOTI_CHOICES = (\n ('работа только пн сб', 'работа только пн сб'),\n ('работа только пн сб и вс', 'работа только пн сб и вс'),\n ('можно работать сменами по 4-6 часов в день', 'можно работать сменами по 4-6 часов в день'),\n\n )\nOPT_CHOICES = (\n ('Нет опыта', 'Нет опыта'),\n ('От 1 года до 3 лет', 'От 1 года до 3 лет'),\n ('От 3 до 6 лет', 'От 3 до 6 лет'),\n ('Более 6 лет', 'Более 6 лет'),\n\n )\nGRAF_CHOICES = (\n ('Полный день', 'Полный день'),\n ('Сменный график', 'Сменный график'),\n ('Гибкий график', 'Гибкий график'),\n ('Удаленная работа', 'Удаленная работа'),\n ('Вахтовый метод', 'Вахтовый метод'),\n\n )\n\n\nclass Vacancies_CreateesForm(forms.ModelForm):\n \n name_vac = forms.CharField(widget=forms.TextInput(\n attrs = {'class':'form-control', 'type':'text', 'placeholder': \"название вакансии\"}\n ))\n sifr = forms.CharField(widget=forms.TextInput(\n attrs = {'class':'form-control', 'type':'text', 'placeholder': \"код вакансии\"}\n ))\n kluchniy_naviki = forms.CharField(widget=forms.TextInput(\n attrs = {'class':'form-control', 'type':'text', 'placeholder': \"ключевые навыки\"}\n ))\n doxodot = forms.CharField(widget=forms.TextInput(\n attrs = {'class':'form-control col-md-12', 'type':'number', 'placeholder': \"от\"}\n ))\n doxoddo = forms.CharField(widget=forms.TextInput(\n attrs = {'class':'form-control', 'type':'number', 'placeholder': \"до\"}\n ))\n nalog = forms.ChoiceField(choices=NAL_CHOICES, widget=forms.RadioSelect)\n\n maestarabota = forms.CharField(widget=forms.TextInput(\n attrs = {'class':'form-control', 'type':'text', 'placeholder': \"Вакансия в городе\"}\n ))\n tipza = forms.ChoiceField(choices=TIPZ_CHOICES, widget=forms.RadioSelect)\n\n \n # vozmojno = forms.MultipleChoiceField(choices=Vacancies_Createes.VOZMO_CHOICES,widget=forms.CheckboxSelectMultiple())\n # vozmojno = forms.ModelMultipleChoiceField(queryset=Vozmojno.objects.all(), widget=forms.CheckboxSelectMultiple(), required=False)\n # rejimraboti = forms.ModelMultipleChoiceField(queryset=Rejimrabota.objects.all(), widget=forms.CheckboxSelectMultiple(), required=False)\n \n\n optrabota = forms.ChoiceField(choices=OPT_CHOICES, widget=forms.RadioSelect)\n grafik_rab = forms.ChoiceField(choices=GRAF_CHOICES, widget=forms.RadioSelect)\n # professionsss = forms.ModelMultipleChoiceField(queryset=Car_business.objects.all(), widget=forms.CheckboxSelectMultiple(), required=False)\n\n\n\n class Meta:\n model = Vacancies_Createes\n fields = ('name_vac', 'sifr', 'opisaniya', 'kluchniy_naviki', 'doxodot', 'doxoddo', 'salaryy', 'nalog', 'maestarabota',\n 'tipza', 'vozmojno', 'rejimraboti1', 'rejimraboti2', 'rejimraboti3', 'optrabota', 'grafik_rab', 'Abxaziya', 'Avstraliya', 'Avstriya',\n 'Ozarbayjon', 'Albaniya', 'Jazoir', 'Angola', 'Andorra', 'Argentina', 'Armaniston', 'Afgoniston', 'Bagama_orollari', 'Bangladesh',\n 'Barbados', 'Bahrayn', 'Belorussiya', 'Beliz', 'Belgiya', 'Bolgariya', 'Boliviya', 'Bosniya_Gertsegovina', 'Braziliya', \n 'Bruney_Darussalom', 'Burkina_Faso', 'Buyuk_Britaniya', 'Vengriya', 'Venesuela', 'Vetnam', 'Gabon', 'Gvineya', 'Germaniya',\n 'Rossiya', 'AQSH', 'Ozbekiston', 'Yaponiya', 'English', 'French', 'German', 'Ukrainian', 'Italian', 'Uzbek')\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # self.fields['user'].widget.attrs.update({'class': 'form-control'}) \n self.fields['salaryy'].widget.attrs.update({'class': 'form-control'}) \n # self.fields['opisaniya'].widget.attrs.update({'class': 'form-control'}) \n \n\n\n\n","repo_name":"Salohiddinov-Davronbek/YOUi-Software","sub_path":"administrator/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":19828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"23455019851","text":"'''\n1 2\n1 3\n2 1\n2 3\n3 1\n3 2\n\n1 2 != 2 1\n'''\n\n# 1. DFS를 이용\n# 2. 체크리스트 이용\n# 순열 암기\n\ndef DFS(L):\n # 종료 조건\n if(L == r):\n print(result)\n else:\n for i in range(len(n)):\n if(checklist[i] == 0):\n result[L] = n[i]\n checklist[i] = 1\n DFS(L+1)\n checklist[i] = 0\n\nif __name__ == '__main__':\n n = [1,2,3]\n r = 2\n\n result = [0] * r\n checklist = [0] * len(n)\n\n DFS(0)","repo_name":"sdm6410/algorithm-study","sub_path":"Shin/알고리즘 정리/순열.py","file_name":"순열.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31153754213","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.apiOverview, name='api-overview'),\n path('product-list/', views.productList, name='task-list'),\n path('product-detail//', views.productDetails, name='task-detail'),\n path('product-create/', views.productCreate, name=\"task-create\"),\n path('product-update//', views.productUpdate, name='task-update'),\n path('product-delete//', views.productDelete, name='task-delete'),\n]\n","repo_name":"alkadoHs/niceCart-products-api","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"43033883500","text":"import os\nimport csv\nfrom pathlib import Path\n\nelection_data = '/Users/bethanymorton/Desktop/python-challenge/PyPoll/Resources/election_data.csv'\n\nvote_total = 0\nvotes_khan = 0\nvotes_li = 0\nvotes_correy = 0\nvotes_otooley = 0\n\nwith open(election_data,newline=\"\", encoding=\"utf-8\") as datafile:\n datareader = csv.reader(datafile, delimiter = \",\")\n\n dataheader = next(datareader)\n\n for row in datareader:\n vote_total +=1\n\n if row[2] == \"Khan\":\n votes_khan +=1\n elif row[2] == \"Li\":\n votes_li +=1\n elif row[2] == \"Correy\":\n votes_correy +=1\n elif row[2] == \"O'Tooley\":\n votes_otooley +=1\n \ncandidates = [\"Khan\", \"Li\", \"Correy\", \"O'Tooley\"]\nvotes = [votes_khan, votes_li, votes_correy, votes_otooley]\n\ncv_dict= dict(zip(candidates,votes))\nkey = max(cv_dict, key=cv_dict.get)\n\npct_khan = (votes_khan/ vote_total) *100\npct_li = (votes_li/ vote_total) *100\npct_correy = (votes_correy/ vote_total) *100\npct_otooley = (votes_otooley/ vote_total) *100\n\nprint(f\"Election Results\")\nprint(f\"Total Votes: {vote_total}\")\nprint(f\"Khan: {pct_khan:.3f}% ({votes_khan})\")\nprint(f\"Correy: {pct_correy:.3f}% ({votes_correy})\")\nprint(f\"Li: {pct_li:.3f}% ({votes_li})\")\nprint(f\"O'Tooley: {pct_otooley:.3f}% ({votes_otooley})\")\nprint(f\"Winner: {key}\")\n\noutput_file = '/Users/bethanymorton/Desktop/python-challenge/PyPoll/analysis/Election_Results'\n\nwith open(output_file,\"w\") as file:\n\n file.write(f\"Election Results\")\n file.write(\"\\n\")\n file.write(f\"Total Votes: {vote_total}\")\n file.write(\"\\n\")\n file.write(f\"Khan: {pct_khan:.3f}% ({votes_khan})\")\n file.write(\"\\n\")\n file.write(f\"Correy: {pct_correy:.3f}% ({votes_correy})\")\n file.write(\"\\n\")\n file.write(f\"Li: {pct_li:.3f}% ({votes_li})\")\n file.write(\"\\n\")\n file.write(f\"O'Tooley: {pct_otooley:.3f}% ({votes_otooley})\")\n file.write(\"\\n\")\n file.write(f\"Winner: {key}\")\n file.write(\"\\n\")\n\n\n","repo_name":"15bmorton/python-challenge","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35423927371","text":"from concurrent.futures import Future\n\n# 1. Establecer un objeto cuyo resultado es a futuro\nfuture_person = Future()\n\n# ...\n\n# 2. Diseñar una función que espere cuándo el resultado\n# futuro esté ajustado\n# 9. Se ejecuta finalmente la función con el future listo\ndef wait_person(future_person):\n # 10. Recuperamos el valor ajustado a futuro\n person = future_person.result()\n\n # 11. Procesamos los datos a futuro como se deba\n print(person)\n\n# ...\n\n# 3. Registramos la función que procesará\n# el valor a futuro cuándo esté listo\nfuture_person.add_done_callback(wait_person)\n# 8. El valor a futuro ya está ajustado\n# por lo que se llama a la función registrada\n\n# ...\n\n# 4. Diseñamos una función que recupere información\n# en tiempo diferido (dependiente de la respuesta de un servidor)\ndef fetch_person():\n import requests\n \n # 5. Hacemos la petición que durará un tiempo prolongado\n response = requests.get(\"https://randomuser.me/api\")\n\n import json\n\n data = json.loads(response.text)\n\n results = data[\"results\"]\n\n user = results[0]\n\n name = user[\"name\"][\"first\"] + \" \" + user[\"name\"][\"last\"]\n gender = user[\"gender\"]\n email = user[\"email\"]\n picture = user[\"picture\"][\"medium\"]\n\n # 6. Construimos un resultado\n person = {\n \"name\": name,\n \"gender\": gender,\n \"email\": email,\n \"picture\": picture\n }\n\n # 7. Establecemos el valor a futuro\n future_person.set_result(person)\n\n# ... En espera de ejecutar (4.)\n\n# Ahora ya podemos ejecutar `fetch_person`\n# y procesar los resultados\nfetch_person()","repo_name":"dragonnomada/python-avanzado-2023","sub_path":"d105/c10_repaso_future.py","file_name":"c10_repaso_future.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"1318851233","text":"import os\nimport time\nimport threading\n\nMAX_PAUSE_TIME = 7200\n\nclass ResumableTimer:\n '''\n Resumable timer will run the given callback function\n after the given timeout. The Timer can be paused more than once\n until the MAX_PAUSE_TIME has been reached\n '''\n def __init__(self, timeout, callback):\n self.timeout = timeout\n self.callback = callback\n self.timer = threading.Timer(timeout, callback)\n self.start_time = time.time()\n self.pause_time = 0\n self.pause_timer = None\n\n def start(self):\n self.timer.start()\n\n def pause(self,pause_seconds):\n '''\n Stop the main timer and start the pause timer. Once the\n pause timer has run to completion the main timer will\n proceed with rest of its timeout.\n '''\n cur_time = time.time()\n\n if self.pause_timer is None:\n self.pause_time = cur_time\n self.timer.cancel()\n else:\n elapsed = cur_time - self.pause_time\n if elapsed + pause_seconds > MAX_PAUSE_TIME:\n ret = -2\n if pause_seconds == 0:\n ret = 0\n self.pause_timer.cancel()\n self.resume()\n return ret\n\n self.pause_timer = threading.Timer(pause_seconds,\n self.resume)\n self.pause_timer.start()\n return 0\n\n def resume(self):\n '''\n Resume the main timer and schedule the callback function\n to be executed\n '''\n self.timer = threading.Timer(\n self.timeout - (self.pause_time - self.start_time),\n self.callback)\n\n self.timer.start()\n","repo_name":"LairdCP/igupd","sub_path":"resumetimer.py","file_name":"resumetimer.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16591482255","text":"import itertools\n\ndef get_num_consecutive_ints_in_list(nums: list) -> int:\n \"\"\"Return the number of consecutive integers in a list of integers.\"\"\"\n nums = sorted(nums)\n if nums[0] != 1:\n return 0\n \n if len(nums) == 1:\n return 1\n\n consec = 1\n for i in range(len(nums)-1):\n if nums[i+1] - nums[i] == 1:\n consec += 1\n else:\n return consec\n \n return consec\n\ndef get_result_for_digit_set(digits: list, verbose: bool = False) -> int:\n operations = ['+', '-', '*', '/']\n \n digits_perm = itertools.permutations(digits)\n op_perms = itertools.product(operations, repeat=3)\n\n target_nums = set()\n for d in digits_perm:\n op_perms = itertools.product(operations, repeat=3) # reset op_perms\n for op in op_perms:\n for order in [0, 1]:\n sum = d[0]\n for i in range(3):\n \n if order == 0:\n if op[i] == '/' and d[i+1] == 0: # division by zero\n break\n sum = eval(f\"{sum} {op[i]} {d[i+1]}\")\n else:\n if op[i] == '/' and sum == 0: # division by zero\n break\n sum = eval(f\"{d[i+1]} {op[i]} {sum}\")\n else:\n\n if sum % 1 != 0 or sum <= 0: # discard non-integers and negative numbers\n continue\n \n sum = int(sum)\n target_nums.add(sum)\n\n if verbose:\n if order == 0:\n print(f\"((( {d[0]} {op[0]} {d[1]} ) {op[1]} {d[2]} ) {op[2]} {d[3]} ) = {sum}\")\n else:\n print(f\"( {d[0]} {op[0]} ( {d[1]} {op[1]} ( {d[2]} {op[2]} {d[3]} ))) = {sum}\") \n\n num_consecutive = get_num_consecutive_ints_in_list(list(target_nums))\n print(f\"Digits: {sorted(digits)}\")\n print(f\"Target numbers: {target_nums}\")\n print(f\"Number of consecutive integers: {num_consecutive}\\n\")\n return num_consecutive\n\ndef main():\n max_num_consecutive = 0\n max_num_consecutive_d = None\n digits = (1, 2, 3, 4, 5, 6, 7, 8, 9)\n digits_combs = itertools.combinations(digits, 4)\n for d in digits_combs:\n longest = get_result_for_digit_set(d, verbose=False)\n if longest > max_num_consecutive:\n max_num_consecutive = longest\n max_num_consecutive_d = d\n\n print(f\"--- Max ---\")\n get_result_for_digit_set(max_num_consecutive_d, verbose=True)\n print(f\"Answer: {''.join([str(i) for i in max_num_consecutive_d])}\")\n \n\nif __name__ == '__main__':\n main()","repo_name":"MyosQ/euler-solutions","sub_path":"src/093peuler.py","file_name":"093peuler.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"24800366957","text":"class PriorityQueueNode:\n def __init__(self, value, priority):\n self.value = value\n self.priority = priority\n\n\nclass PriorityQueue:\n def __init__(self):\n self.pq = []\n\n def getSize(self):\n return len(self.pq)\n\n def isEmpty(self):\n return self.getSize() == 0\n\n def getMin(self):\n if self.isEmpty():\n return None\n return self.pq[0].value\n\n def __percolateUp(self):\n childIndex = self.getSize()-1\n while childIndex > 0:\n parentIndex = (childIndex-1)//2\n if self.pq[childIndex].priority < self.pq[parentIndex].priority:\n self.pq[childIndex], self.pq[parentIndex] = self.pq[parentIndex], self.pq[childIndex]\n childIndex = parentIndex\n else:\n break\n\n def insert(self, value, priority):\n node = PriorityQueueNode(value, priority)\n self.pq.append(node)\n self.__percolateUp()\n\n def __percolateDown(self):\n parentIndex = 0\n while parentIndex < self.getSize():\n child1Index = 2*parentIndex+1\n child2Index = 2*parentIndex+2 \n if child1Index < self.getSize() and (self.pq[child1Index].priority <= self.pq[child2Index].priority) and (self.pq[child1Index].priority < self.pq[parentIndex].priority):\n self.pq[child1Index], self.pq[parentIndex] = self.pq[parentIndex], self.pq[child1Index]\n parentIndex = child1Index\n elif child2Index < self.getSize() and (self.pq[child2Index].priority < self.pq[child1Index].priority) and (self.pq[child2Index].priority < self.pq[parentIndex].priority):\n self.pq[child2Index], self.pq[parentIndex] = self.pq[parentIndex], self.pq[child2Index]\n parentIndex = child2Index\n else:\n break\n\n def removeMin(self):\n if self.isEmpty():\n return None\n\n ele = self.pq[0].value\n self.pq[0], self.pq[self.getSize()-1] = self.pq[self.getSize() -\n 1], self.pq[0]\n self.pq.pop()\n print(self.pq)\n self.__percolateDown()\n return ele\n\npq = PriorityQueue()\n\npq.insert(\"A\", 10)\npq.insert(\"C\", 5)\npq.insert(\"B\", 19)\npq.insert(\"D\", 4)\n\nfor i in range(4):\n print(pq.removeMin())","repo_name":"visheshdvn/DSA","sub_path":"DSA/14Heap_PriorityQueue/PriorityQueues/PriorityQueue.py","file_name":"PriorityQueue.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"1450185103","text":"from pathlib import Path\n\n\nfrom p4 import get_dict\ndict=get_dict()\n\nf = open( Path(__file__).with_name('filtered.txt'),'w')\nfor i in dict:\n name=dict[i]['name']\n birth=dict[i]['birth']\n f.write(f'{i} {name} - {birth} \\n')\n","repo_name":"MohamedHamed12345/IEEE_AI","sub_path":"task2/p5.py","file_name":"p5.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14296043384","text":"from multiprocessing import cpu_count\nimport os\nimport re\n\nimport wmi\n\nfrom common.guard import FileGuard\n\n\nclass Host(object):\n '''\n # 收集主机运行时信息\n '''\n info = None\n\n def __init__(self, os='linux'):\n '''\n Constructor\n '''\n self.os = os\n self.info = {}\n \n def cpuInfo(self):\n return {}\n \n def memInfo(self):\n return {}\n \n def diskInfo(self):\n return {}\n \n \nclass WindowsHost(Host):\n system = None\n def __init__(self):\n '''\n Constructor\n '''\n Host.__init__(self,\"windows\")\n self.system = wmi.WMI()\n \n def cpuInfo(self):\n self.info['cpuPercent'] = []\n index = 1\n for cpu in self.system.Win32_Processor():\n self.info['cpuPercent'][index] = cpu.loadPercentage\n index += 1\n \n def memInfo(self):\n cs = self.system.Win32_ComputerSystem()\n os = self.system.Win32_OperatingSystem()\n self.info['memTotal'] = int(int(cs[0].TotalPhysicalMemory)/1024/1024)\n self.info['memFree'] = int(int(os[0].FreePhysicalMemory)/1024)\n \n def diskInfo(self):\n self.info['diskTotal'] = 0\n self.info['diskFree'] = 0\n for disk in self.system.Win32_LogicalDisk(DriveType=3):\n self.info['diskTotal'] += int(disk.Size)\n self.info['diskFree'] += int(disk.FreeSpace)\n self.info['diskTotal'] = int(self.info['diskTotal']/1024/1024)\n self.info['diskFree'] = int(self.info['diskFree']/1024/1024)\n \nclass LinuxHost(Host):\n def __init__(self):\n '''\n Constructor\n '''\n Host.__init__(self)\n self.info['cpu_num'] = cpu_count()\n \n def get_mem_info(self):\n meminfo = {}\n with FileGuard('/proc/meminfo', 'r') as fp:\n for line in fp:\n arr = line.split(':')\n if len(arr) == 2:\n if arr[1][-2:] == 'kB':\n arr[1] = arr[1][0:-2]\n meminfo[arr[0]] = arr[1].strip()\n self.info.update(meminfo)\n \n def get_cpu_info(self):\n CPUinfo={}\n procinfo={}\n \n nprocs = 0\n with FileGuard('/proc/cpuinfo', 'r') as fp:\n for line in fp:\n if not line.strip():\n #end of one processor\n CPUinfo['proc%s' % nprocs]=procinfo\n nprocs = nprocs+1\n #Reset\n procinfo={}\n else:\n if len(line.split(':')) == 2:\n procinfo[line.split(':')[0].strip()] = line.split(':')[1].strip()\n else:\n procinfo[line.split(':')[0].strip()] = ''\n return CPUinfo\n \n def get_network_data(self, iface=\"eth0\"):\n \"\"\"\n $ cat /proc/net/dev\n Inter-| Receive | Transmit\n face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed\n vethfa61e9b: 648 8 0 0 0 0 0 0 13409 97 0 0 0 0 0 0\n veth024d62a: 648 8 0 0 0 0 0 0 13385 96 0 0 0 0 0 0\n eth0: 5523703 7237 0 0 0 0 0 51 1455967 5435 0 0 0 0 0 0\n lo: 9505 133 0 0 0 0 0 0 9505 133 0 0 0 0 0 0\n docker0: 996 15 0 0 0 0 0 0 8840 61 0 0 0 0 0 0\n \"\"\"\n with FileGuard('/proc/net/dev', 'r') as fp:\n for line in fp:\n if line.index(iface) >= 0 :\n index = line.index(':')\n line = line[index:]\n arr = re.findall(r\"\\d+\", line)\n return {'Receive':arr[0], 'Transmit':arr[8]}\n return {'Receive':0, 'Transmit':0}\n \n def parse_disk_info(self):\n with os.popen('df -l --total') as fp:\n for line in fp:\n if line[0:5] == 'total':\n arr = re.findall(r\"\\d+\", line)\n return {'Size':arr[0], 'Used':arr[1],'Available':arr[2],'UsePercent':arr[3]}\n \n return {'Size':0, 'Used':0,'Available':0,'UsePercent':0}\n\n \n def parse_top_info(self):\n \"\"\"\n $ top -bi -n 1\n top - 15:15:43 up 1:13, 1 user, load average: 0.00, 0.01, 0.05\n Tasks: 112 total, 1 running, 111 sleeping, 0 stopped, 0 zombie\n %Cpu(s): 0.4 us, 0.4 sy, 0.1 ni, 98.0 id, 1.1 wa, 0.1 hi, 0.0 si, 0.0 st\n KiB Mem: 1017852 total, 822092 used, 195760 free, 121492 buffers\n KiB Swap: 1046524 total, 0 used, 1046524 free. 470244 cached Mem\n \"\"\"\n with os.popen('top -bi -n 1') as fp:\n for line in fp:\n if line[0:4] == '%Cpu':\n cpu = self.parse_top_line(line)\n self.info['cpu_user_percent'] = cpu.get('us', 0)\n self.info['cpu_sys_percent'] = cpu.get('sy', 0)\n self.info['cpu_level_change'] = cpu.get('ni', 0)\n self.info['cpu_free_percent'] = cpu.get('id', 0)\n self.info['cpu_wait_in_out'] = cpu.get('wa', 0)\n self.info['cpu_hard_break_'] = cpu.get('hi', 0)\n self.info['cpu_soft_break'] = cpu.get('si', 0)\n self.info['cpu_vm_percent'] = cpu.get('st', 0)\n elif line[0:7] == 'KiB Mem':\n mem = self.parse_top_line(line)\n self.info['MemTotal'] = mem.get('total', 0)\n self.info['MemUsed'] = mem.get('used', 0)\n self.info['MemFree'] = mem.get('free', 0)\n self.info['Buffers'] =mem.get('buffers', 0)\n\n def parse_top_line(self, txt):\n info = {}\n txt = txt.split(':')[1]\n arr = txt.split(',')\n for pair in arr:\n keys = pair.split(' ')\n info[keys[1].strip()] = keys[0].strip()\n return info\n\n def parse_proc_line(self, txt):\n info = {}\n arr = txt.split(':')\n info[arr[0].strip()] = arr[1].strip()\n\n\n \nif __name__ == '__main__':\n host = LinuxHost()\n host.parse_top_info()\n host.get_network_data()\n host.get_mem_info()\n host.get_cpu_info()\n\n \n \n ","repo_name":"LuckStone/DockerCollector","sub_path":"frame/host.py","file_name":"host.py","file_ext":"py","file_size_in_byte":6677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"2617061379","text":"import gettext\nt = gettext.translation('fedmsg', 'locale', fallback=True)\n_ = t.ugettext\n\nimport fedmsg.crypto\n\nfrom fedmsg.text.bodhi import BodhiProcessor\nfrom fedmsg.text.scm import SCMProcessor\nfrom fedmsg.text.tagger import TaggerProcessor\nfrom fedmsg.text.supybot import SupybotProcessor\nfrom fedmsg.text.mediawiki import WikiProcessor\nfrom fedmsg.text.fas import FASProcessor\nfrom fedmsg.text.logger import LoggerProcessor\nfrom fedmsg.text.default import DefaultProcessor\n\nprocessors = [\n BodhiProcessor(_),\n SCMProcessor(_),\n TaggerProcessor(_),\n SupybotProcessor(_),\n WikiProcessor(_),\n FASProcessor(_),\n LoggerProcessor(_),\n DefaultProcessor(_),\n]\n\n\ndef msg2repr(msg, **config):\n \"\"\" Return a human-readable or \"natural language\" representation of a\n dict-like fedmsg message.\n\n \"\"\"\n\n fmt = \"{title} -- {subtitle} {link}\"\n title = _msg2title(msg, **config)\n subtitle = _msg2subtitle(msg, **config)\n link = _msg2link(msg, **config)\n return fmt.format(**locals())\n\n\ndef _msg2title(msg, **config):\n for p in processors:\n if not p.handle_title(msg, **config):\n continue\n title = p.title(msg, **config)\n break\n\n suffix = _msg2suffix(msg, **config)\n if suffix:\n title = title + \" \" + suffix\n\n return title\n\n\ndef _msg2subtitle(msg, **config):\n for p in processors:\n if not p.handle_subtitle(msg, **config):\n continue\n return p.subtitle(msg, **config)\n\n # This should never happen.\n # DefaultProcessor should always catch messages.\n raise RuntimeError(\"No text processor caught the message.\")\n\n\ndef _msg2link(msg, **config):\n for p in processors:\n if not p.handle_link(msg, **config):\n continue\n return p.link(msg, **config)\n\n # This should never happen.\n # DefaultProcessor should always catch messages.\n raise RuntimeError(\"No text processor caught the message.\")\n\n\ndef _msg2suffix(msg, **config):\n if 'signature' not in msg:\n return _(\"(unsigned)\")\n elif config.get('validate_signatures'):\n if not fedmsg.crypto.validate(msg, **config):\n return _(\"(invalid signature!)\")\n\n return \"\"\n","repo_name":"ryansb/fedmsg","sub_path":"fedmsg/text/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"20511939197","text":"import torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport numpy as np\n\nfrom .. import BaseModel, register_model\nfrom cogdl.trainers.sampled_trainer import SAINTTrainer\nfrom cogdl.utils import spmm\n\n\nF_ACT = {\"relu\": nn.ReLU(), \"I\": lambda x: x}\n\n\"\"\"\nBorrowed from https://github.com/GraphSAINT/GraphSAINT\n\"\"\"\n\n\nclass HighOrderAggregator(nn.Module):\n def __init__(self, dim_in, dim_out, dropout=0.0, act=\"relu\", order=1, aggr=\"mean\", bias=\"norm-nn\", **kwargs):\n \"\"\"\n Layer implemented here combines the GraphSAGE-mean [1] layer with MixHop [2] layer.\n We define the concept of `order`: an order-k layer aggregates neighbor information\n from 0-hop all the way to k-hop. The operation is approximately:\n X W_0 [+] A X W_1 [+] ... [+] A^k X W_k\n where [+] is some aggregation operation such as addition or concatenation.\n\n Special cases:\n Order = 0 --> standard MLP layer\n Order = 1 --> standard GraphSAGE layer\n\n [1]: https://cs.stanford.edu/people/jure/pubs/graphsage-nips17.pdf\n [2]: https://arxiv.org/abs/1905.00067\n\n Inputs:\n dim_in int, feature dimension for input nodes\n dim_out int, feature dimension for output nodes\n dropout float, dropout on weight matrices W_0 to W_k\n act str, activation function. See F_ACT at the top of this file\n order int, see definition above\n aggr str, if 'mean' then [+] operation adds features of various hops\n if 'concat' then [+] concatenates features of various hops\n bias str, if 'bias' then apply a bias vector to features of each hop\n if 'norm' then perform batch-normalization on output features\n\n Outputs:\n None\n \"\"\"\n super(HighOrderAggregator, self).__init__()\n assert bias in [\"bias\", \"norm\", \"norm-nn\"]\n self.order, self.aggr = order, aggr\n self.act, self.bias = F_ACT[act], bias\n self.dropout = dropout\n self.f_lin, self.f_bias = [], []\n self.offset, self.scale = [], []\n self.num_param = 0\n for o in range(self.order + 1):\n self.f_lin.append(nn.Linear(dim_in, dim_out, bias=False))\n nn.init.xavier_uniform_(self.f_lin[-1].weight)\n self.f_bias.append(nn.Parameter(torch.zeros(dim_out)))\n self.num_param += dim_in * dim_out\n self.num_param += dim_out\n self.offset.append(nn.Parameter(torch.zeros(dim_out)))\n self.scale.append(nn.Parameter(torch.ones(dim_out)))\n if self.bias == \"norm\" or self.bias == \"norm-nn\":\n self.num_param += 2 * dim_out\n self.f_lin = nn.ModuleList(self.f_lin)\n self.f_dropout = nn.Dropout(p=self.dropout)\n self.params = nn.ParameterList(self.f_bias + self.offset + self.scale)\n self.f_bias = self.params[: self.order + 1]\n if self.bias == \"norm\":\n self.offset = self.params[self.order + 1 : 2 * self.order + 2]\n self.scale = self.params[2 * self.order + 2 :]\n elif self.bias == \"norm-nn\":\n final_dim_out = dim_out * ((aggr == \"concat\") * (order + 1) + (aggr == \"mean\"))\n self.f_norm = nn.BatchNorm1d(final_dim_out, eps=1e-9, track_running_stats=True)\n self.num_param = int(self.num_param)\n\n def _f_feat_trans(self, _feat, _id):\n feat = self.act(self.f_lin[_id](_feat) + self.f_bias[_id])\n if self.bias == \"norm\":\n mean = feat.mean(dim=1).view(feat.shape[0], 1)\n var = feat.var(dim=1, unbiased=False).view(feat.shape[0], 1) + 1e-9\n feat_out = (feat - mean) * self.scale[_id] * torch.rsqrt(var) + self.offset[_id]\n else:\n feat_out = feat\n return feat_out\n\n def forward(self, input):\n \"\"\"\n Inputs:.\n adj_norm normalized adj matrix of the subgraph\n feat_in 2D matrix of input node features\n\n Outputs:\n adj_norm same as input (to facilitate nn.Sequential)\n feat_out 2D matrix of output node features\n \"\"\"\n\n graph, x = input\n feat_in = self.f_dropout(x)\n feat_hop = [feat_in]\n # generate A^i X\n for o in range(self.order):\n feat_hop.append(spmm(graph, x))\n feat_partial = [self._f_feat_trans(ft, idf) for idf, ft in enumerate(feat_hop)]\n if self.aggr == \"mean\":\n feat_out = feat_partial[0]\n for o in range(len(feat_partial) - 1):\n feat_out += feat_partial[o + 1]\n elif self.aggr == \"concat\":\n feat_out = torch.cat(feat_partial, 1)\n else:\n raise NotImplementedError\n if self.bias == \"norm-nn\":\n feat_out = self.f_norm(feat_out)\n return graph, feat_out # return adj_norm to support Sequential\n\n\ndef parse_arch(architecture, aggr, act, bias, hidden_size, num_features):\n num_layers = len(architecture.split(\"-\"))\n # set default values, then update by arch_gcn\n bias_layer = [bias] * num_layers\n act_layer = [act] * num_layers\n aggr_layer = [aggr] * num_layers\n dims_layer = [hidden_size] * num_layers\n order_layer = [int(order) for order in architecture.split(\"-\")]\n return [num_features] + dims_layer, order_layer, act_layer, bias_layer, aggr_layer\n\n\n@register_model(\"graphsaint\")\nclass GraphSAINT(BaseModel):\n @staticmethod\n def add_args(parser):\n \"\"\"Add model-specific arguments to the parser.\"\"\"\n # fmt: off\n parser.add_argument(\"--num-features\", type=int)\n parser.add_argument(\"--hidden-size\", type=int, default=128)\n parser.add_argument(\"--architecture\", type=str, default=\"1-1-0\")\n parser.add_argument(\"--aggr\", type=str, default=\"concat\")\n parser.add_argument(\"--act\", type=str, default=\"relu\")\n parser.add_argument(\"--bias\", type=str, default=\"norm\")\n parser.add_argument(\"--dropout\", type=float, default=0.1)\n parser.add_argument(\"--weight-decay\", type=int, default=0)\n # fmt: on\n\n @classmethod\n def build_model_from_args(cls, args):\n return cls(\n args.num_features,\n args.num_classes,\n args.architecture,\n args.aggr,\n args.act,\n args.bias,\n args.weight_decay,\n args.dropout,\n args.hidden_size,\n )\n\n def __init__(self, num_features, num_classes, architecture, aggr, act, bias, weight_decay, dropout, hidden_size):\n \"\"\"\n Build the multi-layer GNN architecture.\n\n Inputs:\n num_classes int, number of classes a node can belong to\n arch_gcn dict, config for each GNN layer\n train_params dict, training hyperparameters (e.g., learning rate)\n feat_full np array of shape N x f, where N is the total num of\n nodes and f is the dimension for input node feature\n label_full np array, for single-class classification, the shape\n is N x 1 and for multi-class classification, the\n shape is N x c (where c = num_classes)\n cpu_eval bool, if True, will put the model on CPU.\n\n Outputs:\n None\n \"\"\"\n super(GraphSAINT, self).__init__()\n self.aggregator_cls = HighOrderAggregator\n self.mulhead = 1\n self.weight_decay = weight_decay\n self.dropout = dropout\n self.sigmoid_loss = True\n self.num_classes = num_classes\n self.num_layers = len(architecture.split(\"-\"))\n _dims, self.order_layer, self.act_layer, self.bias_layer, self.aggr_layer = parse_arch(\n architecture, aggr, act, bias, hidden_size, num_features\n )\n # get layer index for each conv layer, useful for jk net last layer aggregation\n self.set_idx_conv()\n self.set_dims(_dims)\n\n self.loss = 0\n self.opt_op = None\n\n # build the model below\n self.num_params = 0\n self.aggregators, num_param = self.get_aggregators()\n self.num_params += num_param\n self.conv_layers = nn.Sequential(*self.aggregators)\n self.classifier = HighOrderAggregator(\n self.dims_feat[-1], self.num_classes, act=\"I\", order=0, dropout=self.dropout, bias=\"bias\"\n )\n self.num_params += self.classifier.num_param\n\n def set_dims(self, dims):\n \"\"\"\n Set the feature dimension / weight dimension for each GNN or MLP layer.\n We will use the dimensions set here to initialize PyTorch layers.\n\n Inputs:\n dims list, length of node feature for each hidden layer\n\n Outputs:\n None\n \"\"\"\n self.dims_feat = [dims[0]] + [\n ((self.aggr_layer[layer] == \"concat\") * self.order_layer[layer] + 1) * dims[layer + 1]\n for layer in range(len(dims) - 1)\n ]\n self.dims_weight = [(self.dims_feat[layer], dims[layer + 1]) for layer in range(len(dims) - 1)]\n\n def set_idx_conv(self):\n \"\"\"\n Set the index of GNN layers for the full neural net. For example, if\n the full NN is having 1-0-1-0 arch (1-hop graph conv, followed by 0-hop\n MLP, ...). Then the layer indices will be 0, 2.\n \"\"\"\n idx_conv = np.where(np.array(self.order_layer) >= 1)[0]\n idx_conv = list(idx_conv[1:] - 1)\n idx_conv.append(len(self.order_layer) - 1)\n _o_arr = np.array(self.order_layer)[idx_conv]\n if np.prod(np.ediff1d(_o_arr)) == 0:\n self.idx_conv = idx_conv\n else:\n self.idx_conv = list(np.where(np.array(self.order_layer) == 1)[0])\n\n def forward(self, graph):\n x = graph.x\n _, emb_subg = self.conv_layers(((graph, x)))\n emb_subg_norm = F.normalize(emb_subg, p=2, dim=1)\n pred_subg = self.classifier((None, emb_subg_norm))[1]\n return pred_subg\n\n def _loss(self, preds, labels, norm_loss):\n \"\"\"\n The predictor performs sigmoid (for multi-class) or softmax (for single-class)\n \"\"\"\n if self.sigmoid_loss:\n norm_loss = norm_loss.unsqueeze(1)\n return torch.nn.BCEWithLogitsLoss(weight=norm_loss, reduction=\"sum\")(preds, labels)\n else:\n _ls = torch.nn.CrossEntropyLoss(reduction=\"none\")(preds, labels)\n return (norm_loss * _ls).sum()\n\n def get_aggregators(self):\n \"\"\"\n Return a list of aggregator instances. to be used in self.build()\n \"\"\"\n num_param = 0\n aggregators = []\n for layer in range(self.num_layers):\n aggr = self.aggregator_cls(\n *self.dims_weight[layer],\n dropout=self.dropout,\n act=self.act_layer[layer],\n order=self.order_layer[layer],\n aggr=self.aggr_layer[layer],\n bias=self.bias_layer[layer],\n mulhead=self.mulhead,\n )\n num_param += aggr.num_param\n aggregators.append(aggr)\n return aggregators, num_param\n\n def predict(self, data):\n return self.forward(data)\n # return nn.Sigmoid()(preds) if self.sigmoid_loss else F.softmax(preds, dim=1\n\n @staticmethod\n def get_trainer(task, args):\n return SAINTTrainer\n","repo_name":"RockabyeW/Expert-Finding-for-AMiner-THU-ZhipuAI-","sub_path":"cogdl/cogdl/models/nn/graphsaint.py","file_name":"graphsaint.py","file_ext":"py","file_size_in_byte":11491,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"70751780880","text":"\"\"\"\nday: 2020-09-09\nurl: https://leetcode-cn.com/problems/map-sum-pairs/\n题目名: 键值映射\n实现一个 MapSum 类里的两个方法,insert 和 sum。\n对于方法 insert,你将得到一对(字符串,整数)的键值对。字符串表示键,整数表示值\n如果键已经存在,那么原来的键值对将被替代成新的键值对\n对于方法 sum,你将得到一个表示前缀的字符串,你需要返回所有以该前缀开头的键的值的总和。\n\n思路:\n\n 前缀树.\n\n\"\"\"\n\n\nclass MapSum(object):\n def __init__(self):\n self.root = {}\n\n def insert(self, key, val):\n node = self.root\n for char in key:\n if char not in node:\n node[char] = {}\n node = node[char]\n node['val'] = val\n\n def dfs(self, node, sum):\n for child in node:\n if child == 'val':\n sum += node[child]\n else:\n sum = self.dfs(node[child], sum)\n return sum\n\n def sum(self, prefix):\n node = self.root\n for char in prefix:\n if char not in node:\n return 0\n node = node[char]\n return self.dfs(node, 0)\n","repo_name":"challeger/leetCode","sub_path":"模拟面试/leetCode_154_键值映射.py","file_name":"leetCode_154_键值映射.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"22943190952","text":"import setuptools\nimport os\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as f:\n long_description = f.read()\n\nsetuptools.setup(\n name=\"pyread\",\n version=\"0.0.0a0\",\n author=\"Jack Luby\",\n author_email=\"jack.o.luby@gmail.com\",\n description=\"Read selected .txt files aloud, storing progress.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n classifiers=[\n \"License :: Other/Proprietary License\",\n \"Natural Language :: English\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 3\",\n ],\n package_dir={\"\": \"src\"},\n packages=setuptools.find_packages(where=\"src\"),\n python_requires=\">=3.6\",\n #package_data={'': ['helpers/config.json']},\n include_package_data=True,\n entry_points={\n 'console_scripts': [f'{file[:-3]} = pyread.{file[:-3]}:main' for file in os.listdir(\"src/pyread\") if file[-3:] == \".py\"]\n }\n)","repo_name":"jluby/pyread","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9650001818","text":"import time\nimport numpy as np\nimport imgaug as ia\nfrom imgaug import augmenters as iaa\nfrom PIL import Image\nimport pandas as pd\nfrom concurrent.futures import ThreadPoolExecutor as threadPool\nimport os\nimport pydicom\nimport warnings\nfrom keras import backend as k\nimport matplotlib.pylab as plt\nimport random\nwarnings.filterwarnings('ignore')\n\n\nia.seed(1)\n\nclass DataGenerator:\n def __init__(self,data_path_root,images_path,csv_path,num_thread=None,is_train=False):\n index_array,train_labels = self.read_csv(csv_path)\n self.data_path=data_path_root\n self.image_path=images_path\n self.csv_path=csv_path\n self.num_thread=num_thread\n self.is_train=is_train\n self.train_label=train_labels\n self.index_array=index_array\n self.seq = iaa.Sequential([\n iaa.Fliplr(0.5),\n iaa.Crop(percent=(0, 0.1)),\n iaa.OneOf([iaa.GaussianBlur((0, 0.5)),iaa.AverageBlur(k=(2, 7)),iaa.MedianBlur(k=(3, 11))]),\n iaa.ContrastNormalization((0.75, 1.5)),\n iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05*255), per_channel=0.5),\n iaa.Multiply((0.8, 1.2), per_channel=0.2),\n iaa.Affine(\n scale={\"x\": (0.8, 1.2), \"y\": (0.8, 1.2)},\n translate_percent={\"x\": (-0.2, 0.2), \"y\": (-0.2, 0.2)},\n rotate=(-25, 25),\n shear=(-8, 8))], random_order=True)\n def load_image(self,temp_path):\n im = np.array(Image.open(self.image_path+'/'+temp_path+'.png'))\n return im\n def get_img(self,img_paths, img_size):\n p = threadPool()\n X = np.zeros((len(img_paths), img_size, img_size), dtype=np.uint8)\n i = 0\n for future in p.map(self.load_image, img_paths):\n img = np.resize(future, (img_size, img_size))\n X[i, :, :] = img\n i += 1\n p.shutdown(wait=False)\n return X\n def random_pick(self,some_list):\n probabilities = [0.3,0.2,0.2,0.2,0.1]\n x = random.uniform(0,1)\n cumulative_probability = 0.0\n for item, item_probability in zip(some_list, probabilities):\n cumulative_probability += item_probability\n if x < cumulative_probability:break\n return item\n def creat_batch_data(self,x_path,batch_size):\n dia_dic={}\n np.random.shuffle(x_path)\n change_index=self.train_label.loc[x_path]\n change_index.index=range(0,len(change_index.index)) \n keep_prob=change_index.iloc[:,0].map({0:0.18,1:0.9})\n keep=(keep_prob>np.random.rand(len(keep_prob)))\n indices=np.arange(len(x_path))[keep]\n csv=change_index.iloc[indices]\n neg_group=csv['Label'][csv['Label']['any']==0].index\n any_group=csv['Label'][csv['Label']['any']==1].index\n ratio=len(any_group)/len(csv.index)\n posi_num=int(ratio*batch_size)\n dia_dic[1]=csv['Label'][csv['Label']['epidural']>=1].index\n dia_dic[2]=csv['Label'][csv['Label']['intraparenchymal']>=1].index\n dia_dic[3]=csv['Label'][csv['Label']['intraventricular']>=1].index\n dia_dic[4]=csv['Label'][csv['Label']['subarachnoid']>=1].index\n dia_dic[5]=csv['Label'][csv['Label']['subdural']>=1].index\n groups=[]\n for i in range(posi_num):\n item=self.random_pick(dia_dic.keys())\n groups.append(random.choice(dia_dic[item]))\n groups.extend(np.random.choice(neg_group,size=batch_size-len(groups)))\n random.shuffle(groups)\n return groups\n\n def get_X_batch(self, X_path, batch_size, img_size, is_train=True):\n try:\n if len(X_path) % batch_size != 0:\n raise Exception(\"batchSize not match the size of data!\")\n except Exception as err:\n print(err)\n else:\n while 1:\n indice=self.creat_batch_data(X_path,batch_size)\n X = self.get_img(X_path[indice], img_size)\n Y = self.train_label.loc[X_path[indice]].values\n if is_train:\n X = (self.seq.augment_images(X))\n yield np.resize(X / 155, (len(X), img_size, img_size, 1)).astype('float16'), Y.astype('float16')\n else:\n X = np.resize(X / 155, (batch_size, img_size, img_size, 1))\n yield X.astype('float16'), Y.astype('float16')\n\n def get_test_batch(self,X_path,batch_size,img_size):\n try:\n if len(X_path) %batch_size != 0:\n raise Exception(\"batchSize not match the size of data!\")\n except Exception as err:\n print(err)\n else:\n while 1:\n for i in range(0, len(X_path), batch_size):\n X =(self.get_img(X_path[i:i + batch_size], img_size))\n yield np.resize(X/155,(len(X),img_size,img_size,1)).astype('float16')\n def read_csv(self, filename):\n df = pd.read_csv(filename)\n df[\"ImageID\"] = df[\"ID\"].str.slice(stop=12)\n df[\"Diagnosis\"] = df[\"ID\"].str.slice(start=13)\n duplicates_to_remove = [\n 56346, 56347, 56348, 56349,\n 56350, 56351, 1171830, 1171831,\n 1171832, 1171833, 1171834, 1171835,\n 3705312, 3705313, 3705314, 3705315,\n 3705316, 3705317, 3842478, 3842479,\n 3842480, 3842481, 3842482, 3842483\n ]\n df = df.drop(index=duplicates_to_remove)\n df = df.reset_index(drop=True)\n df = df.loc[:, [\"Label\", \"Diagnosis\", \"ImageID\"]]\n df = df.set_index(['ImageID', 'Diagnosis']).unstack(level=-1)\n index_array = df.index.values.tolist()\n return index_array, df\n\n\n# gener=DataGenerator(data_path,images_path=f'{data_path}/stage_2_train_images',csv_path=f'{data_path}/stage_2_train.csv',num_thread=None,is_train=True)\n\n\n\n","repo_name":"TangBoo/CS583-Deep-Learning","sub_path":"Project/augmentation.py","file_name":"augmentation.py","file_ext":"py","file_size_in_byte":5874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"8923704342","text":"import tkinter as tk\nfrom tkinter import *\nfrom tkinter import ttk\n\n\n# Functions\ndef btn_a_fn(a, b):\n lbl_a_var = a + b\n return lbl_a_var\n\n\nwindow = tk.Tk()\nwindow.title(\"Test2 app\")\nwindow.geometry(\"500x300\")\n# print(window.configure())\n\ninf_a_var = tk.IntVar()\ninf_b_var = tk.IntVar()\nlbl_a_var = tk.IntVar()\n\nlbl_a = ttk.Label(window, text=\"default\", textvariable=lbl_a_var)\nlbl_a.pack()\n\ninf_a = ttk.Entry(window, textvariable=inf_a_var)\ninf_b = ttk.Entry(window, textvariable=inf_b_var)\ninf_a.pack()\ninf_b.pack()\n\nbtn_a = ttk.Button(window, text='Click', command=btn_a_fn(inf_a_var, inf_b_var))\nbtn_a.pack()\n\nwindow.mainloop()\n","repo_name":"vhomelab/Python-Scripts","sub_path":"Projects/PyUI/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"2375617735","text":"import datetime\nimport random\n\nfrom django.test import TestCase\nfrom django.utils import timezone\nfrom django.urls import reverse\n\nfrom .models import *\n\n\nclass MoviesModelTests(TestCase):\n\n def test_was_published_recently_with_future_movie(self):\n \"\"\"\n was_published_recently() returns False for movies whose date_creation\n is in the future.\n \"\"\"\n time = timezone.now() + datetime.timedelta(days=30)\n future_movie = Movie(date_creation=time)\n self.assertIs(future_movie.was_published_recently(), False)\n\n def test_was_published_recently_with_old_question(self):\n \"\"\"\n was_published_recently() returns False for questions whose pub_date\n is older than 1 day.\n \"\"\"\n time = timezone.now() - datetime.timedelta(days=1, seconds=1)\n old_question = Movie(date_creation=time)\n self.assertIs(old_question.was_published_recently(), False)\n\n def test_was_published_recently_with_recent_question(self):\n \"\"\"\n was_published_recently() returns True for questions whose pub_date\n is within the last day.\n \"\"\"\n time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)\n recent_question = Movie(date_creation=time)\n self.assertIs(recent_question.was_published_recently(), True)\n\n\ndef create_genre(genre_name):\n \"\"\"\n Create a genre with the given `movie_data` and published the\n given number of `days` offset to now (negative for movies added\n in the past, positive for movies that have yet to be visible).\n \"\"\"\n return Genre.objects.create(name=genre_name,\n slug=genre_name.lower().replace(' ', '-'))\n\n\ndef create_movie(movie_data, days):\n \"\"\"\n Create a movie with the given `movie_data` and published the\n given number of `days` offset to now (negative for movies added\n in the past, positive for movies that have yet to be visible).\n \"\"\"\n time = timezone.now() + datetime.timedelta(days=days)\n return Movie.objects.create(title=movie_data['title'],\n slug=f'test{round(random.random() * 1000)}',\n description=movie_data['description'],\n cover='',\n year=movie_data['year'],\n rating=movie_data['rating'],\n genre=movie_data['genre'],\n date_creation=time,\n date_update=time)\n\n\nclass MovieListTests(TestCase):\n def test_no_movie(self):\n \"\"\"\n If no movie exist, an appropriate message is displayed.\n \"\"\"\n response = self.client.get(reverse('movie_app:main'))\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"No movies are available.\")\n self.assertQuerysetEqual(response.context['movies'], [])\n\n def test_past_movie(self):\n \"\"\"\n Movies with a date_creation in the past are displayed on the\n index page.\n \"\"\"\n create_genre('Adventure')\n create_movie(movie_data={'title': 'past movie',\n 'description': 'test1',\n 'cover': '',\n 'year': 2021,\n 'rating': 100,\n 'genre': Genre.objects.get(name='Adventure')},\n days=-30)\n response = self.client.get(reverse('movie_app:main'))\n self.assertQuerysetEqual(\n response.context['movies'],\n [\"\"]\n )\n\n def test_future_movie(self):\n \"\"\"\n Movies with a date_creation in the future aren't displayed on\n the index page.\n \"\"\"\n create_genre('Adventure')\n create_movie(movie_data={'title': 'future movie',\n 'description': 'test1',\n 'cover': '',\n 'year': 2021,\n 'rating': 100,\n 'genre': Genre.objects.get(name='Adventure')},\n days=30)\n response = self.client.get(reverse('movie_app:main'))\n self.assertContains(response, \"No movies are available.\")\n self.assertQuerysetEqual(response.context['movies'], [])\n\n def test_future_movie_and_past_movie(self):\n \"\"\"\n Even if both past and future movies exist, only past movie\n are displayed.\n \"\"\"\n create_genre('Adventure')\n create_movie(movie_data={'title': 'past movie',\n 'description': 'test1',\n 'cover': '',\n 'year': 2021,\n 'rating': 100,\n 'genre': Genre.objects.get(name='Adventure')},\n days=-30)\n create_movie(movie_data={'title': 'future movie',\n 'description': 'test1',\n 'cover': '',\n 'year': 2021,\n 'rating': 100,\n 'genre': Genre.objects.get(name='Adventure')},\n days=30)\n response = self.client.get(reverse('movie_app:main'))\n self.assertQuerysetEqual(\n response.context['movies'],\n [\"\"]\n )\n\n def test_two_past_movies(self):\n \"\"\"\n The movies index page may display multiple movies.\n \"\"\"\n create_genre('Adventure')\n create_movie(movie_data={'title': 'past movie 1',\n 'description': 'test1',\n 'cover': '',\n 'year': 2021,\n 'rating': 100,\n 'genre': Genre.objects.get(name='Adventure')},\n days=-30)\n create_movie(movie_data={'title': 'past movie 2',\n 'description': 'test1',\n 'cover': '',\n 'year': 2021,\n 'rating': 100,\n 'genre': Genre.objects.get(name='Adventure')},\n days=-5)\n response = self.client.get(reverse('movie_app:main'))\n self.assertQuerysetEqual(\n response.context['movies'],\n [\"\",\n \"\"]\n )\n\n\nclass MovieDetailViewTests(TestCase):\n\n def test_future_movie(self):\n \"\"\"\n The detail view of a movie with a date_creation in the future\n returns a 404 not found.\n \"\"\"\n create_genre('Adventure')\n future_movie = create_movie(movie_data={'title': 'future movie',\n 'description': 'test1',\n 'cover': '',\n 'year': 2021,\n 'rating': 100,\n 'genre': Genre.objects.get(name='Adventure')},\n days=5)\n url = reverse('movie_app:movie', args=(future_movie.slug,))\n response = self.client.get(url)\n self.assertEqual(response.status_code, 404)\n\n def test_past_movie(self):\n \"\"\"\n The detail view of a movie with a date_creation in the past\n displays the movie's description.\n \"\"\"\n create_genre('Adventure')\n past_movie = create_movie(movie_data={'title': 'past movie',\n 'description': 'test1',\n 'cover': '',\n 'year': 2021,\n 'rating': 100,\n 'genre': Genre.objects.get(name='Adventure')},\n days=-5)\n url = reverse('movie_app:movie', args=(past_movie.slug,))\n response = self.client.get(url)\n self.assertContains(response, past_movie.title)\n","repo_name":"artshenberg/Movies","sub_path":"movie_app/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":8345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34613500402","text":"from multiprocessing import freeze_support\nfrom threading import Thread\nfrom tkinter import filedialog\nfrom tkinter import ttk\nfrom PIL import Image, ImageTk\nimport asstosrt\nimport pysubs2\nimport tkinter\nimport sys\nimport os\nfrom tkinterdnd2 import TkinterDnD, DND_FILES\nfrom tktooltip import ToolTip\nimport tkinter.messagebox\n# pyinstaller --noconfirm --onefile --noconsole --add-data \"venv/lib/site-packages/tkinterdnd2;tkinterdnd2/\" --add-data 'background.png;.' --add-data 'ico.ico;.' --icon=ico.ico SRTwithROLES.py\n\n\ndef ass_sub_convert(subs: str) -> None:\n with open(subs, 'r', encoding='utf-8') as ass_file:\n srt_sub = asstosrt.convert(ass_file)\n srt_path = subs.replace('.ass', '.srt')\n with open(srt_path, 'w', encoding='utf-8') as srt_file:\n srt_file.write(srt_sub)\n\n\ndef resource_path(path):\n try:\n base_path = sys._MEIPASS\n except Exception:\n base_path = os.path.abspath('.')\n\n return os.path.join(base_path, path)\n\n\ndef path_choice() -> str or None:\n defaultextension = 'ass'\n filetypes = [('Субтитры \".ass\"', '*.ass')]\n title = 'Выберите файл субтитров'\n path = filedialog.askopenfilename(\n defaultextension=defaultextension,\n filetypes=filetypes,\n title=title,\n )\n return path\n\n\ndef subs_edit() -> None:\n subs = path_choice()\n if subs:\n subtitles = pysubs2.load(subs)\n for sub in subtitles.events:\n if sub.name:\n sub.text = f'\"{sub.name}\": {sub.text}'\n subtitles.save(subs)\n ass_sub_convert(subs)\n os.remove(subs)\n\n\ndef subs_edit_on_drop(subs) -> None:\n subtitles = pysubs2.load(subs)\n for sub in subtitles.events:\n if sub.name:\n sub.text = f'\"{sub.name}\": {sub.text}'\n subtitles.save(subs)\n ass_sub_convert(subs)\n os.remove(subs)\n\n\ndef on_start_click():\n thread = Thread(target=subs_edit)\n thread.start()\n\n\ndef on_drop(event):\n data = event.data.replace('{', '')\n data = data.replace('}', '')\n if os.path.splitext(data)[-1] == '.ass':\n thread = Thread(target=subs_edit_on_drop, args=(data,))\n thread.start()\n else:\n tkinter.messagebox.showerror(\n 'Ошибка',\n 'Выберите \".ass\" файл'\n )\n\n\nmaster = TkinterDnD.Tk()\nwidth = 300\nheight = 200\ns_width = master.winfo_screenwidth()\ns_height = master.winfo_screenheight()\nupper = s_height // 8\nx = (s_width - width) // 2\ny = (s_height - height) // 2\nmaster.geometry(f'{width}x{height}+{x}+{y - upper}')\nmaster.resizable(width=False, height=False)\nmaster.title('SRT WITH ROLES v0.04')\nmaster.iconbitmap(default=resource_path('ico.ico'))\nmaster.configure(background='#7ce6ef')\nimg = Image.open(resource_path('background.png'))\ntk_img = ImageTk.PhotoImage(img)\nbackground_label = tkinter.Label(master, image=tk_img)\nbackground_label.place(x=0, y=0, relwidth=1, relheight=1)\nbutton_style = ttk.Style()\nbutton_style.configure('TButton', background='#7ce6ef')\nstart_bttn = ttk.Button(\n master,\n text='START',\n name='start',\n command=lambda: on_start_click()\n)\nstart_bttn.place(relx=0.5, rely=1.0, anchor=\"s\", y=-9)\nToolTip(start_bttn, 'Выберите файл или перетащите его в окно', 1)\nmaster.drop_target_register(DND_FILES)\nmaster.dnd_bind('<>', on_drop)\n\nif __name__ == '__main__':\n freeze_support()\n master.focus_force()\n master.mainloop()\n","repo_name":"DoobyDouglas/SRTwithROLES","sub_path":"SRTwithROLES.py","file_name":"SRTwithROLES.py","file_ext":"py","file_size_in_byte":3448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70751797520","text":"\"\"\"\nday: 2020-10-10\nurl: https://leetcode-cn.com/problems/linked-list-cycle-ii/\n题目名: 环形链表II\n如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环,返回入环的第一个节点\n没有则返回null\n思路:\n 先用快慢指针判断是否��环\n 如果有环,那么用一个从头结点出发的指针,与当前相遇的指针\n 同时出发,再次相遇就是环的入口\n\n 没有环就返回null\n\n 我们假设起点到环入口的距离是a,相遇时slow指针在环内走了距离b,环剩下的长度为c\n 那么fast指针,在与slow指针相遇时,走的总长度为 a + n(b+c) + b,n为fast指针走完的环的n圈\n\n 因为fast指针的速度是slow的两倍,所以有\n 2(a+b) = a + n(b+c) + b\n => a = (n-1)(b+c) + c\n 那么slow在走了 (n-1)(b+c) + c步后,会回到环的入口, 因为环剩下的长度是c\n 所以只需要让一个指针从head出发,与slow同步走,那么当他们走了a步后,会在环的入口\n 相遇.\n\"\"\"\n\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n def detectCycle(self, head: ListNode) -> ListNode:\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n break\n else:\n return None\n slow = head\n while slow != fast:\n slow = slow.next\n fast = fast.next\n return fast\n","repo_name":"challeger/leetCode","sub_path":"每日一题/2020_10_10_环形链表II.py","file_name":"2020_10_10_环形链表II.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"16287444839","text":"import numpy as np\nimport math\nfrom scipy.special import erf\nfrom scipy.ndimage import zoom\nfrom scipy.ndimage import uniform_filter\nfrom scipy.optimize import curve_fit\n\ndef gauss_psf(sigma, psf_size = 0):\n if psf_size == 0:\n psf_size = math.ceil(sigma * 3)\n\n psf = np.exp(-np.arange(-psf_size,psf_size+1, dtype=np.float32)**2 / 2 / sigma / sigma)\n psf /= psf.sum()\n\n psf = psf[..., np.newaxis] * psf[np.newaxis, ...]\n return psf\n\ndef erf_psf(sigma, psf_size = 0):\n if psf_size == 0:\n psf_size = math.ceil(sigma * 3)\n\n x = (np.arange(-psf_size, psf_size + 2, dtype=np.float32) - 0.5)\n y = np.diff(erf(x / math.sqrt(2) / sigma))\n y /= y.sum()\n psf = y[..., np.newaxis] * y[np.newaxis,...]\n return psf\n\ndef adjusted_psf_subpixel(psf_in, zoom, scale_psf = False):\n ''' Adjust psf to accormodate subpixel computations.\n Input\n psf_in: orginal 2D psf\n zoom: integer representing size ratio of original pixel to subpixel\n scale_psf: boolean. If true, the psf_in was in original pixel size scale; otherwise, it is in subpixel size.\n\n Output:\n psf_out: the adjusted psf at subpixel size\n '''\n if scale_psf:\n psf_out = zoom(psf_in, zoom)\n else:\n fs = psf_in.shape[0]\n hfs = math.ceil(fs/2/zoom - 0.5)\n dfs = (2 * hfs + 1) * zoom - fs\n dfs1 = dfs // 2\n dfs2 = dfs - dfs1\n psf_out = np.pad(psf_in, ((dfs1, dfs2),(dfs1, dfs2)))\n\n psf_out = uniform_filter(psf_out, size=zoom, mode='constant')\n psf_out /= psf_out.sum()\n\n return psf_out\n\ndef analyze_flux(cnts):\n #cnts = np.sum(imgs, axis = (1,2))\n x = np.arange(cnts.size)\n\n def _exp_func(x,a,b,k):\n return a * np.exp(-k*x) + b\n\n pars, _ = curve_fit(_exp_func, x, cnts, [cnts[0],0.0,1.0])\n vals = _exp_func(x, *pars)\n dvals = -np.diff(vals)\n\n x_eq = pars[1]\n x_0 = pars[0] - x_eq\n kn = pars[2] * x_eq / x_0\n kp = pars[2] * (x_0 - x_eq) / x_0\n jn = (x_0 - x_eq) / x_0 * dvals + kp * x_eq\n jp = kn * (x_0 - x_eq) - x_eq / x_0 * dvals\n flux = (jn+jp) / vals[:-1]\n\n return flux\n","repo_name":"jiyuuchc/Drizzle","sub_path":"drizzle/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70715898638","text":"import logging\n\nfrom scotchwsgi import const\n\nlogger = logging.getLogger(__name__)\n\nclass WSGIRequest(object):\n def __init__(self, method, path, query, http_version, headers, body):\n self.method = method\n self.path = path\n self.query = query\n self.http_version = http_version\n self.headers = headers\n self.body = body\n\n @staticmethod\n def read_request_line(reader):\n request_line = reader.readline().decode(const.STR_ENCODING)\n logger.info(\"Received request %s\", request_line)\n\n try:\n request_method, request_uri, http_version = request_line.split(' ', 3)\n except ValueError:\n raise ValueError(\"Invalid request line: %s\" % request_line)\n\n http_version = http_version.rstrip()\n request_uri_split = request_uri.split('?', 1)\n request_path = request_uri_split[0]\n if len(request_uri_split) > 1:\n request_query = request_uri_split[1]\n else:\n request_query = ''\n\n return request_method, request_path, request_query, http_version\n\n @staticmethod\n def read_headers(reader):\n headers = {}\n while True:\n header = reader.readline().decode(const.STR_ENCODING).replace('\\r\\n', '\\n').rstrip('\\n')\n if header == '':\n break\n\n try:\n header_name, header_value = header.split(':', 1)\n except ValueError:\n raise ValueError(\"Invalid header: %s\" % header)\n\n header_name = header_name.lower()\n header_value = header_value.lstrip()\n headers[header_name] = header_value\n\n logger.debug(\"Headers: %s\", headers)\n\n return headers\n\n @staticmethod\n def read_body(reader, content_length=None):\n if content_length is not None:\n logger.debug(\"Reading body (content-length: %d)\", content_length)\n message_body = reader.read(content_length)\n logger.debug(\"Body: %s\", message_body)\n\n if content_length != len(message_body):\n raise ValueError(\n \"content-length %d too large, only read %d bytes\" % (\n content_length, len(message_body)\n )\n )\n else:\n logger.debug(\"Reading chunked body\")\n message_body = b\"\"\n\n while True:\n chunk_length_hex = reader.readline().rstrip()\n logger.debug(\"Chunk length hex: %s\", chunk_length_hex)\n chunk_length = int(chunk_length_hex, 16)\n logger.debug(\"Reading chunk of length %d\", chunk_length)\n if chunk_length == 0:\n while reader.readline() not in (b\"\\r\\n\", b\"\\n\"):\n continue # Ignore trailer headers\n break\n\n chunk_data = reader.read(chunk_length)\n logger.debug(\"Chunk: %r\", chunk_data)\n chunk_newline = reader.readline()\n\n # Reconstruct message (though ideally the chunks should feed into the application as they arrive)\n message_body += chunk_data\n\n return message_body\n\n @staticmethod\n def from_reader(reader):\n method, path, query, http_version = WSGIRequest.read_request_line(\n reader\n )\n\n headers = WSGIRequest.read_headers(\n reader\n )\n\n transfer_encoding = headers.get('transfer-encoding')\n content_length = headers.get('content-length')\n\n if transfer_encoding:\n if transfer_encoding.lower() != 'chunked':\n raise NotImplementedError(\n \"Received unsupported transfer-encoding: %s\" % transfer_encoding\n )\n\n body = WSGIRequest.read_body(reader)\n elif content_length:\n body = WSGIRequest.read_body(reader, int(content_length))\n else:\n body = b\"\"\n\n return WSGIRequest(\n method=method,\n path=path,\n query=query,\n http_version=http_version,\n headers=headers,\n body=body,\n )\n","repo_name":"libcthorne/scotchwsgi","sub_path":"scotchwsgi/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":4158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35655487959","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@File : admin_view.py\n@Time : 2022/03/23 22:56:16\n@Author : Jeffrey Wang\n@Version : 1.0\n@Contact : shwangjj@163.com\n@Desc : 系统管理模块模块Views\n\nviews:\n\n部门维护部分:\nEndpoint Methods Rule\n----------------- --------- ------------------------------\nadmin.dept_index GET /admin/dept\nadmin.dept_list GET, POST /admin/dept_query\nadmin.dept_new GET, POST /admin/dept/new\nadmin.dept_add GET, POST /admin/dept/add\nadmin.dept_detail GET, POST /admin/dept/\nadmin.dept_modify GET, POST /admin/dept/modify/\nadmin.dept_save GET, POST /admin/dept/update/\nadmin.dept_delete GET, POST /admin/dept/delete/\n'''\nfrom flask import (\n Blueprint, render_template, request, jsonify\n)\nfrom flask import current_app as app\nfrom app.models.auth import AdminDepartment, AdminUser, InvaidIdException\nfrom sqlalchemy import func\nfrom app.extensions import db\nfrom sqlalchemy import or_\nfrom app.commons.utils.flask_utils import AjaxResponse, query2tabledata\nfrom app.service.ft_mis.hr import create_dept, query_user\n\n\n# 构建蓝图\nbp = Blueprint('admin', __name__, url_prefix='/admin')\n\n\n# @bp.route('/test_auth')\n# @login_required\n# def test_auth():\n# return '这个页面需要登录后才能看'\n\n\n# ===========================================================\n# 人员维护部分\n\n# 人员列表\n@bp.route('/user')\ndef user_index():\n \"\"\" 返回部门清单页面 \"\"\"\n return render_template('admin/user.html')\n\n\n# 人员查询数据\n@bp.route('/user_query', methods=('GET', 'POST'))\ndef user_query():\n \"\"\" 返回查询数据 \"\"\"\n if request.method == 'GET':\n page = int(request.args.get(\"page\", 1))\n limit = int(request.args.get(\"limit\", 5))\n # 根据查询字段:\n query_list = []\n q_id = request.args.get('id', default=None)\n if q_id:\n query_list.append(AdminUser.id == q_id)\n q_name = request.args.get('name', default=None)\n if q_name:\n query_list.append(AdminUser.name.like(\n '%{name}%'.format(name=q_name)))\n query_condition = or_(*query_list) # 查询条件\n app.logger.debug(\"人员查询:{0}\".format(request.args))\n\n try:\n users = AdminUser.query.filter(query_condition).offset(\n (page - 1) * limit).limit(limit).all()\n data = []\n for obj in users:\n obj.dept_name = obj.get_dept_name() # 部门名\n obj.status_desc = obj.get_status()\n data.append(obj.to_dict())\n # data = query2tabledata(users)\n if len(query_list) > 0:\n record_count = db.session.query(func.count(\n AdminUser.id).filter(query_condition)).scalar()\n else:\n record_count = db.session.query(\n func.count(AdminUser.id)).scalar()\n\n # 返回前台数据接口\n json_data = {\n \"code\": 0,\n \"msg\": \"\",\n \"count\": record_count,\n \"data\": data\n }\n print(data)\n return jsonify(json_data)\n except Exception as e:\n app.logger.error(str(e))\n return jsonify({\"code\": \"500\", \"msg\": \"异常,\" + str(e), \"count\": 0, \"data\": []})\n\n\n# 人员部门页面\n@bp.route('/user/new')\ndef user_new():\n \"\"\"返回添加录入页面\"\"\"\n return render_template('admin/user_new.html')\n\n\n# 单用户查看\n@bp.route('/user/', methods=('GET', 'POST'))\ndef user_detail(user_id: str):\n \"\"\" 查询并返回人员对象 \"\"\"\n user = AdminUser.query.filter(AdminUser.id == user_id).first()\n if user:\n context = {\n 'user': user,\n }\n return render_template(\"/admin/user_detail.html\", **context)\n else:\n return \"数据读取错误\"\n\n\n# ===========================================================\n# 部门维护部分\n\n# 部门列表\n@bp.route('/dept')\ndef dept_index():\n \"\"\" 返回部门清单页面 \"\"\"\n return render_template('admin/dept.html')\n\n\n# 新建部门页面\n@bp.route('/dept/new', methods=('GET', 'POST'))\ndef dept_new():\n \"\"\"返回添加录入页面\"\"\"\n return render_template('admin/dept_new.html')\n\n\n# 新建部门动作\n@bp.route('/dept/add', methods=('GET', 'POST'))\ndef dept_add():\n \"\"\"接受新增请求,执行新增动作并反馈结果\n \"\"\"\n app.logger.info(\"新建部门\")\n if request.method == 'POST':\n dept_id = request.form.get(\"id\")\n dept_name = request.form.get(\"name\")\n\n try:\n dept = create_dept(dept_id=dept_id, name=dept_name)\n if dept:\n return jsonify(AjaxResponse(message=\"添加成功\").to_json())\n else:\n return jsonify(AjaxResponse(False, code=AjaxResponse.SERVER_ERROR, message=\"添加部门失败!\").to_json())\n except InvaidIdException as ide:\n return jsonify(AjaxResponse(False, code=AjaxResponse.SERVER_ERROR, message=\"添加部门失败!\" + str(ide)).to_json())\n\n return jsonify(AjaxResponse(False, code=AjaxResponse.SERVER_ERROR, message=\"系统错误\").to_json())\n\n\n# 部门查询数据\n@bp.route('/dept_query', methods=('GET', 'POST'))\ndef dept_query():\n \"\"\" 返回查询数据 \"\"\"\n if request.method == 'GET':\n page = int(request.args.get(\"page\", 1))\n limit = int(request.args.get(\"limit\", 5)) # TODO 默认的每页显示,要加入到系统参数中\n # TODO 分页参数的引用,要抽象出去\n # 根据查询字段:\n query_list = []\n q_id = request.args.get('id', default=None)\n if q_id:\n query_list.append(AdminDepartment.id == q_id)\n q_name = request.args.get('name', default=None)\n if q_name:\n query_list.append(AdminDepartment.name.like(\n '%{name}%'.format(name=q_name)))\n query_condition = or_(*query_list) # 查询条件\n app.logger.debug(\"部门查询:{0}\".format(request.args))\n\n try:\n depts = AdminDepartment.query.filter(query_condition).offset(\n (page - 1) * limit).limit(limit).all()\n data = query2tabledata(depts)\n # TODO 计算count,要抽象出去\n if len(query_list) > 0:\n record_count = db.session.query(func.count(\n AdminDepartment.id).filter(query_condition)).scalar()\n else:\n record_count = db.session.query(\n func.count(AdminDepartment.id)).scalar()\n\n # 返回前台数据接口\n json_data = {\n \"code\": 0,\n \"msg\": \"\",\n \"count\": record_count,\n \"data\": data\n }\n print(data)\n return jsonify(json_data)\n except Exception as e:\n app.logger.error(str(e))\n return jsonify({\"code\": \"500\", \"msg\": \"异常,\" + str(e), \"count\": 0, \"data\": []})\n\n\n# 部门查看\n@bp.route('/dept/', methods=('GET', 'POST'))\ndef dept_detail(id):\n \"\"\" 查询并返回部门对象 \"\"\"\n dept = db.session.query(AdminDepartment).filter(AdminDepartment.id == id).first()\n print(dept)\n if dept:\n context = {\n 'dept': dept,\n }\n return render_template(\"/admin/dept_detail.html\", **context)\n else:\n return \"数据读取错误\"\n\n\n# 部门编辑\n@bp.route('/dept/modify/', methods=('GET', 'POST'))\ndef dept_modify(id):\n dept = db.session.query(AdminDepartment).filter(AdminDepartment.id == id).first()\n if dept:\n context = {\n 'dept': dept,\n }\n return render_template(\"/admin/dept_edit.html\", **context)\n else:\n return \"数据读取错误\"\n\n\n# 部门编辑保存\n@bp.route('/dept/update/', methods=('GET', 'POST'))\ndef dept_save(id):\n app.logger.info(\"保存部门\")\n if request.method == 'POST':\n dept = db.session.query(AdminDepartment).filter(AdminDepartment.id == id).first()\n if dept:\n dept.name = request.form.get(\"name\")\n db.session.commit()\n return jsonify(AjaxResponse(message=\"更新{0}成功\".format(dept.name)).to_json())\n else:\n app.logger.error(\"部门{0}未找到\".format(id))\n return jsonify(AjaxResponse(False, code=AjaxResponse.SERVER_ERROR, message=\"部门{0}未找到\".format(id)).to_json())\n\n return jsonify(AjaxResponse(False, code=AjaxResponse.SERVER_ERROR, message=\"系统错误\").to_json())\n\n\n# 部门删除\n@bp.route('/dept/delete/', methods=('GET', 'POST'))\ndef dept_delete(id):\n \"\"\" 接受删除请求,执行并反馈结果 \"\"\"\n app.logger.info(\"删除部门\")\n if request.method == 'POST':\n dept = db.session.query(AdminDepartment).filter(AdminDepartment.id == id).first()\n if dept:\n db.session.delete(dept)\n db.session.commit()\n return jsonify(AjaxResponse(message=\"删除{0}成功\".format(dept.name)).to_json())\n\n return jsonify(AjaxResponse(False, code=AjaxResponse.SERVER_ERROR, message=\"系统错误\").to_json())\n\n\n# ===========================================================\n# 公共组件\n# 人员选择\n@bp.route('/choose_user', methods=('GET', 'POST'))\ndef choose_user():\n \"\"\" 人员选择 \"\"\"\n if request.method == 'POST':\n name = request.form.get(\"name\")\n oa_id = request.form.get(\"oa_id\")\n users = query_user(name=name, oa_id=oa_id)\n print(users)\n context = {\n 'users': users,\n 'f_name': name,\n 'f_oa_id': oa_id,\n }\n return render_template(\"/admin/user_picker.html\", **context)\n\n return render_template('/admin/user_picker.html')\n\n\n# if __name__ == \"__main__\":\n# from app import app\n# with app.app_context():\n# dept_detail('00')\n","repo_name":"shwdbd/feedme","sub_path":"app/views/admin_view.py","file_name":"admin_view.py","file_ext":"py","file_size_in_byte":9802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32162907714","text":"import math\nimport random\nimport time\n\nimport turtle\n\nt = turtle.Turtle()\n\n\n# from python src\ndef hsv_to_rgb(h, s, v):\n if s == 0.0:\n return v, v, v\n i = int(h*6.0) # XXX assume int() truncates!\n f = (h*6.0) - i\n p = v*(1.0 - s)\n q = v*(1.0 - s*f)\n t = v*(1.0 - s*(1.0-f))\n i = i%6\n if i == 0:\n return v, t, p\n if i == 1:\n return q, v, p\n if i == 2:\n return p, v, t\n if i == 3:\n return p, q, v\n if i == 4:\n return t, p, v\n if i == 5:\n return v, p, q\n # Cannot get here\n\n\ndef alpha(n):\n ''' rad '''\n return (n-2) * math.pi / n\n\n\ndef beta(n):\n ''' deg '''\n return 360. / n \n\n\ndef rhex():\n return '{:x}'.format(random.randrange(1 << 8))\n\n\ndef rcolor():\n return '#' + ''.join([rhex() for _ in range(3)])\n\n\ndef rcolor2():\n r = random.random\n rgb = hsv_to_rgb(r() * 255, 1, 255)\n print('rgb', rgb)\n int_rgb = [int(i) for i in rgb]\n print('int_rgb', int_rgb)\n hex_rgb = [hex(i)[2:] for i in int_rgb]\n print('hex_rgb', hex_rgb)\n hex2_rgb = ['{:0>2}'.format(i) for i in hex_rgb]\n print(hex2_rgb)\n return '#' + ''.join(hex2_rgb)\n\n\ndef rcolor3(n):\n colors = []\n for i in range(n):\n rgb = hsv_to_rgb(.5 * i / n, 1, 255)\n # print('rgb', rgb)\n int_rgb = [int(i) for i in rgb]\n # print('int_rgb', int_rgb)\n hex_rgb = [hex(i)[2:] for i in int_rgb]\n # print('hex_rgb', hex_rgb)\n hex2_rgb = ['{:0>2}'.format(i) for i in hex_rgb]\n print(hex2_rgb)\n colors.append('#' + ''.join(hex2_rgb))\n return colors\n\n\ndef deg2rad(deg):\n return deg * math.pi / 180.\n\n\ndef rad2deg(rad):\n return rad * 180. / math.pi\n\n\ndef epsilon(x, alp):\n num = x * math.sin(alp)\n den = 1 - x * (1 + math.cos(alp))\n return math.atan(num / den)\n\n\ndef b(ax, alp, eps):\n num = ax * math.sin(alp)\n return num / math.sin(eps)\n\n\ndef multi(t, n, a, bet):\n t.begin_fill()\n for i in range(n):\n print(i)\n t.fd(a)\n t.lt(bet)\n t.end_fill()\n\n\ndef mv(t, ax, alp, eps):\n t.fd(ax)\n t.lt(rad2deg(eps))\n\n\ndef main1():\n for i in range(3, 10):\n bet = beta(i)\n col = rcolor2()\n print('\\t{} {}'.format(i, col))\n t.color(col)\n multi(t, i, 20, bet)\n\n\ndef main2():\n n = 3\n a = 400\n x = .01\n N = 200\n\n alp = alpha(n)\n bet = beta(n)\n eps = epsilon(x, alp)\n cs = rcolor3(N)\n\n for i in range(N):\n col = cs[i]\n print('\\t{} {}'.format(i, col))\n t.color(col)\n multi(t, n, a, bet)\n ax = a * x\n mv(t, ax, alp, eps)\n a = b(ax, alp, eps)\n\n\ndef tests():\n for i in (0, 90, 180, 360):\n print(i, deg2rad(i))\n\n for i in (0, 1./3, 1./2, 2./3, 1):\n print(i, rad2deg(i * math.pi))\n\n for i in (1./2, 1./3):\n print(i, epsilon(.5, i * math.pi))\n\n\nif __name__ == '__main__':\n random.seed(42)\n # main1()\n main2()\n # tests()\n","repo_name":"matbur/some-python","sub_path":"turtle_examples/t1.py","file_name":"t1.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15548614899","text":"import sklearn.cross_validation as cv\nimport sklearn.metrics as metrics\nimport pandas as pd\nimport numpy as np\n\ndef evaluateModel(x,y,model,training_pct = 0.75, randomstate=10):\n \"\"\" Takes in x and y data and a model to be trained in order, performs cross validation based on the specified percentage allocated to training, and returns the RMSE for the test data \"\"\"\n\n x_train, x_test, y_train, y_test= cv.train_test_split(x,y, train_size=training_pct, random_state = randomstate)\n fitted_model = model.fit(x_train, y_train)\n y_fitted = model.predict(x_test)\n rmse = (metrics.mean_squared_error(y_test, y_fitted))**0.5\n return rmse\n \n \ndef evaluateModelAvg(x,y,models, training_pct = 0.75):\n \"\"\" average the predicted results of models, which is a list of regressors to produce the final estimated y\"\"\"\n x_train, x_test, y_train, y_test= cv.train_test_split(x,y, train_size=training_pct)\n outcome = pd.DataFrame()\n for model in models:\n fitted = model.fit(x_train, y_train)\n outcome[model] = pd.Series(model.predict(x_test))\n y_hat = outcome.mean(axis = 1).values\n rmse = (metrics.mean_squared_error(y_test, y_hat))**0.5\n return mse\n","repo_name":"bchnge/YelpRecSys13","sub_path":"src/regression_methods.py","file_name":"regression_methods.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"37852093621","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Dec 29 22:16:20 2019\r\n\r\n@author: raghed\r\n\"\"\"\r\n\r\nmy_list=[x**2 for x in range(10) if x%2==0]\r\nprint (my_list)\r\n\r\nsquare = lambda x: x**2\r\ndouble = lambda x: x + x\r\nprint(list(map(square, my_list)))\r\nprint(list(map(double, my_list)))\r\n\r\n\r\nimport functools\r\nmy_list = [1, 2, 3, 4, 5]\r\ndef add_it(x, y):\r\n return (x + y)\r\nsum = functools.reduce(add_it, my_list)\r\nprint(sum)","repo_name":"raghedisae/DEVUTC503_03","sub_path":"list_comprehension.py","file_name":"list_comprehension.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"72675552717","text":"import sqlite3\nfrom datetime import datetime\nfrom prettytable import PrettyTable\n\ndef open_database(): \n db = 'pydb.db' \n\n print('Connecting to SQLite...')\n conn = sqlite3.connect(db)\n print('connected') \n\n return conn\n\ndef create_table(conn):\n cursor = conn.cursor()\n sql = ''' create table if not exists imagefiles(\n id integer primary key autoincrement,\n filename char(30) not null,\n imagetype char(30) not null,\n imgfile blob,\n created datetime\n )'''\n\n cursor.execute(sql)\n conn.commit() \n print('created a table')\n\n\ndef insert_image_data(conn,full_file_path,file_name,file_type):\n print('inserting image data')\n cursor = conn.cursor()\n\n with open(full_file_path, 'rb') as f:\n imagedata = f.read()\n \n params = (file_name,file_type,imagedata,datetime.now())\n query = (\"insert into imagefiles(filename,imagetype,imgfile,created) \"\n \"values(?,?,?,?)\")\n \n cursor.execute(query, params)\n img_id = cursor.lastrowid\n print('inserted with id=',img_id) \n \n conn.commit()\n cursor.close()\n\ndef read_image_data(conn, id,save_as_file):\n print('reading data id=',id)\n cursor = conn.cursor()\n try:\n\n params = (id,)\n query = (\"select filename,imagetype,imgfile,created \"\n \"from imagefiles where id=?\") \n \n cursor.execute(query,params)\n t = PrettyTable(['ID','File Name', 'Image Type','Created']) \n for (filename, imagetype, imgfile, created) in cursor: \n t.add_row([id, filename, imagetype, created])\n\n with open(save_as_file, 'wb') as f:\n f.write(imgfile) \n f.close()\n print('Save image data as ',save_as_file) \n \n print(t)\n except Exception as e:\n print(e)\n \n finally:\n cursor.close()\n pass\n\n# open database\nconn = open_database()\n\n# # creating data demo\n# create_table(conn)\n\n# # inserting image data demo\n# print('inserting image data demo')\n# full_file_path = './image1.png'\n# file_name = 'image1.png'\n# file_type = 'image/png'\n# insert_image_data(conn,full_file_path,file_name,file_type)\n# print('done')\n\n\n# reading image data demo\nprint('reading image data demo')\nsave_as_file = 'image1-read.png'\nid = 1\nread_image_data(conn,id,save_as_file)\nprint('done')\n\n# close database\n#conn.close()","repo_name":"TonySelfStudy/database_projects","sub_path":"sql_lite/src/book_src/db_image_demo.py","file_name":"db_image_demo.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15423885064","text":"Decimal = 987 #c'est la fonction dans le cas où Decimal est positif\n\ndef ConvertBinToDic(Decimal):\n Binary = \"\" #on a définit binary comme une chaîne de caractères vide\n while Decimal >= 0:\n Binary += str(Decimal % 2) #append permet d'ajouter decimal % 2 dans Binary\n Decimal //= 2 #on va diviser sur 2 et obtient le quotient jusqu'à 0\n if Decimal == 0:\n break\n return Binary[::-1] #on a slicing: [start: end: step] inverser la chaîne de caractères\n\nprint(ConvertBinToDic(Decimal))\n\n\n\n","repo_name":"hmce1/atelier1","sub_path":"exercice4.py","file_name":"exercice4.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26846972663","text":"from tkinter import PhotoImage\nfrom example_generators import base_repr, int\n\n\n# From https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_RGB_alternative\ndef hsv_to_rgb(h, s, v):\n # h: hue: 0 to 360\n # s: saturation: 0 to 1\n # v: value: 0 to 1\n def f(n):\n k = (n + (h / 60)) % 6\n return v - (v * s * max(0, min(k, 4 - k, 1)))\n r, g, b = int(f(5) * 255), int(f(3) * 255), int(f(1) * 255)\n r, g, b = base_repr(r, base=16).zfill(2), base_repr(g, base=16).zfill(2), base_repr(b, base=16).zfill(2)\n return \"#\" + r + g + b\n\n\nclass Coordinate:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\nclass AffineTransformation:\n \"\"\"\n _ _ _ _ _ _ _ _\n | a b || x | | e | | ax + by + e |\n | || | + | | = | |\n | c d || y | | f | | cx + dy + f |\n - - - - - - - -\n \n \"\"\"\n def __init__(self, a, b, c, d, e, f):\n self.a = a\n self.b = b\n self.c = c\n self.d = d\n self.e = e\n self.f = f\n\n def transform(self, coord):\n new_x = self.a * coord.x + self.b * coord.y + self.e\n new_y = self.c * coord.x + self.d * coord.y + self.f\n\n return Coordinate(new_x, new_y)\n\n def as_array(self):\n return [self.a, self.b, self.c, self.d, self.e, self.f]\n\n\nclass IteratedFunctionSystem:\n def __init__(self, transformations):\n self.transformations = transformations\n\n self.size = len(transformations)\n\n def get_image(self, image_width, image_height, num_iters, generator, starting_point=Coordinate(0, 0),\n bg_color=\"#000000\", fg_color=\"#00FF00\", colors=True, first_transformations=100):\n img = PhotoImage(width=image_width, height=image_height)\n\n # Set background color\n img.put(bg_color, to=(0, 0, image_width, image_height))\n\n # Calculation of points\n all_points = [starting_point]\n all_transformations = [0]\n gen_str = \"\"\n\n current_point = starting_point\n\n for i in range(num_iters):\n gen_val = next(generator)\n index = int(gen_val, base=self.size)\n\n t = self.transformations[index]\n current_point = t.transform(current_point)\n\n all_points.append(current_point)\n all_transformations.append(index)\n gen_str += gen_val\n\n # Stretch to fit image\n min_x = min(all_points, key=lambda pt: pt.x).x\n max_x = max(all_points, key=lambda pt: pt.x).x\n\n min_y = min(all_points, key=lambda pt: pt.y).y\n max_y = max(all_points, key=lambda pt: pt.y).y\n\n fractal_width = max_x - min_x\n fractal_height = max_y - min_y\n\n fractal_size = max(fractal_width, fractal_height)\n\n drawn_points = []\n draw_colors = []\n\n for pt, index in zip(all_points, all_transformations):\n new_x = ((pt.x - min_x) / fractal_size) * image_width\n new_y = ((pt.y - min_y) / fractal_size) * image_height\n\n new_y = image_height - new_y\n\n drawn_points.append(Coordinate(new_x, new_y))\n draw_colors.append(hsv_to_rgb(index * 360 / self.size, 1, 1))\n\n # Draw points\n if colors:\n for pt, dot_color in zip(drawn_points, draw_colors):\n img.put(dot_color, (round(pt.x), round(pt.y)))\n else:\n for pt in drawn_points:\n img.put(fg_color, (round(pt.x), round(pt.y)))\n\n return img, gen_str[:first_transformations]\n","repo_name":"adelapo/biased-normality-ifs","sub_path":"ifs_python_gui/ifs_classes.py","file_name":"ifs_classes.py","file_ext":"py","file_size_in_byte":3573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6999757232","text":"\"\"\"@package Tests\nView documentation\n\n\"\"\"\nfrom django.test import TestCase\nfrom MeancoApp.models import *\nfrom MeancoApp.functions.search import *\n## Test cases.\n#\nclass ModelTestCases(TestCase):\n ## Test set up.\n #\n def setUp(self):\n self.u = User.objects.create_user(username=\"TestUser\",email=\"test@test.com\",password=\"test\")\n self.p = Profile.objects.create(user=self.u)\n self.t1 = Topic.objects.create(label=\"Test\")\n self.t2 = Topic.objects.create(label=\"Test2\")\n self.c = Comment.objects.create(topic=self.t1,profile=self.p)\n self.v = Version.objects.create(comment=self.c,content=\"test\")\n self.r = Relation.objects.create(topic_a=self.t1,topic_b=self.t2,label=\"test\")\n self.tag = Tag.objects.create(label=\"test\",description=\"test\",URL=\"test.com\")\n self.ot =OfTopic.objects.create(tag=self.tag,topic=self.t1)\n\n ## Model Tests\n def testModel(self):\n self.assertEquals(self.u.id,User.objects.get(username=\"TestUser\").id)\n self.assertEquals(self.p.id,Profile.objects.get(user_id=self.u.id).id)\n self.assertEquals(self.t1.label,Topic.objects.get(label=\"Test\").label)\n self.assertEquals(self.t2.id, Topic.objects.get(label=\"Test2\").id)\n self.assertEqual(self.c.id,Comment.objects.get(topic_id=self.t1.id,profile_id=self.p.id).id)\n self.assertEquals(self.v.id,Version.objects.get(comment_id=self.c.id,content__contains=\"test\").id)\n self.assertEquals(self.r.label,Relation.objects.get(id=self.r.id).label)\n self.assertEquals(self.tag.label,Tag.objects.get(URL__contains=\"test\").label)\n self.assertEquals(self.ot.id,OfTopic.objects.get(tag_id=self.tag.id,topic_id=self.t1.id).id)\n\n ##Vote testing\n def testVote(self):\n com= Comment.objects.get(id=self.c.id)\n voter = Voter(comment_id=com.id,profile_id=self.p.id)\n voter.save()\n v_count= com.vote_count\n voter.toggle(\"upvote\")\n self.assertEquals(v_count+1,Comment.objects.get(id=com.id).vote_count)\n voter.toggle(\"downvote\")\n self.assertEquals(v_count - 1, Comment.objects.get(id=com.id).vote_count)\n voter.toggle(\"downvote\")\n self.assertEquals(v_count, com.vote_count)\n ##topic tests\n def testTopic(self):\n t_view_count=self.t1.view_count\n t_comment_count=self.t1.comment_count\n self.t1.viewed()\n self.t1.commented()\n self.assertEquals(t_view_count+1,self.t1.view_count)\n self.assertEquals(t_comment_count+1,self.t1.comment_count)\n\n ##search Test\n def testSearch(self):\n t= Topic(label=\"Fenerbahce\")\n t.save()\n getRefOfTopic(\"Fenerbahce\",t.id)\n self.assertEquals(t.id,findStringMatchedTopics(\"Fener\")[0])\n self.assertEquals(t.id, findRefTopics(\"Galatasaray\")[0])\n\n\n\n\n\n\n\n","repo_name":"bounswe/bounswe2016group12","sub_path":"WEB-BACKEND/Meanco/MeancoApp/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"29"} +{"seq_id":"39576926914","text":"\r\nclass Solution:\r\n def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:\r\n dup_indices = []\r\n for i in indices:\r\n dup_indices += i\r\n\r\n matrix = [[0 for p in range(0 ,n)]\r\n for q in range(0 ,m)]\r\n\r\n\r\n for i in range(0 ,len(dup_indices)):\r\n if i % 2 == 0:\r\n matrix[dup_indices[i]] = self.change_row(matrix[dup_indices[i]])\r\n else:\r\n matrix = self.change_col(matrix ,dup_indices[i])\r\n\r\n count = 0\r\n\r\n for r in range(0 ,len(matrix)):\r\n for c in range(0 ,len(matrix[0])):\r\n if matrix[r][c] % 2 != 0:\r\n count += 1\r\n\r\n return count\r\n\r\n\r\n def change_row(self ,arr):\r\n for i in range(0 ,len(arr)):\r\n arr[i] += 1\r\n return arr\r\n\r\n\r\n def change_col(self ,matrix ,col_num):\r\n for r in range(0 ,len(matrix)):\r\n matrix[r][col_num] += 1\r\n return matrix\r\n\r\n","repo_name":"saurav935/DSA-Java-Bootcamp","sub_path":"Leetcode assignments/Arrays/14. Cells with Odd Values in a Matrix.py","file_name":"14. Cells with Odd Values in a Matrix.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"23004759512","text":"#!/usr/bin/env python3\n\nimport argparse\nimport os\nimport random\nimport sys\n\nfrom numpy import median\n\nfrom cacheLib import *\nimport cacheSim\n\nimport logging\nlog = logging.getLogger(__name__)\n\n\ndef getActualHits(seq, level, cacheSets, cBox, cSlice, nMeasurements=10):\n nb = runCacheExperiment(level, seq, cacheSets=cacheSets, cBox=cBox, cSlice=cSlice, clearHL=True, loop=1, wbinvd=True, nMeasurements=nMeasurements, agg='med')\n return int(nb['L' + str(level) + '_HIT']+0.1)\n\n\ndef findSmallCounterexample(policy, initSeq, level, sets, cBox, cSlice, assoc, seq, nMeasurements):\n seqSplit = seq.split()\n for seqPrefix in [seqSplit[:i] for i in range(assoc+1, len(seqSplit)+1)]:\n seq = initSeq + ' '.join(seqPrefix)\n actual = getActualHits(seq, level, sets, cBox, cSlice, nMeasurements)\n sim = cacheSim.getHits(seq, cacheSim.AllPolicies[policy], assoc, sets)\n print('seq:' + seq + ', actual: ' + str(actual) + ', sim: ' + str(sim))\n if sim != actual:\n break\n\n for i in reversed(range(0, len(seqPrefix)-1)):\n tmpPrefix = seqPrefix[:i] + seqPrefix[(i+1):]\n seq = initSeq + ' '.join(tmpPrefix)\n actual = getActualHits(seq, level, sets, cBox, cSlice, nMeasurements)\n sim = cacheSim.getHits(seq, cacheSim.AllPolicies[policy], assoc, sets)\n print('seq:' + seq + ', actual: ' + str(actual) + ', sim: ' + str(sim))\n if sim != actual:\n seqPrefix = tmpPrefix\n\n return ((initSeq + ' ') if initSeq else '') + ' '.join(seqPrefix)\n\n\ndef getRandomSeq(n):\n seq = [0]\n seqAct = ['']\n for _ in range(0,n):\n if random.choice([True, False]):\n seq.append(max(seq)+1)\n seqAct.append('')\n else:\n seq.append(random.choice(seq))\n if random.randint(0,8)==0:\n seqAct.append('?')\n else:\n seqAct.append('?')\n return ' '.join(str(s) + a for s, a in zip(seq, seqAct))\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Replacement Policies')\n parser.add_argument(\"-level\", help=\"Cache level (Default: 1)\", type=int, default=1)\n parser.add_argument(\"-sets\", help=\"Cache set(s) (default: 0)\", default='0')\n parser.add_argument(\"-cBox\", help=\"cBox (default: 0)\", type=int)\n parser.add_argument(\"-slice\", help=\"Slice (within the cBox) (default: 0)\", type=int, default=0)\n parser.add_argument(\"-nMeasurements\", help=\"Number of measurements\", type=int, default=3)\n parser.add_argument(\"-rep\", help=\"Number of repetitions of each experiment (Default: 1)\", type=int, default=1)\n parser.add_argument(\"-findCtrEx\", help=\"Tries to find a small counterexample for each policy (only available for deterministic policies)\", action='store_true')\n parser.add_argument(\"-policies\", help=\"Comma-separated list of policies to consider (Default: all deterministic policies)\")\n parser.add_argument(\"-best\", help=\"Find the best matching policy (Default: abort if no policy agrees with all results)\", action='store_true')\n parser.add_argument(\"-randPolicies\", help=\"Test randomized policies\", action='store_true')\n parser.add_argument(\"-allQLRUVariants\", help=\"Test all QLRU variants\", action='store_true')\n parser.add_argument(\"-assoc\", help=\"Override the associativity\", type=int)\n parser.add_argument(\"-initSeq\", help=\"Adds an initialization sequence to each sequence\")\n parser.add_argument(\"-nRandSeq\", help=\"Number of random sequences (default: 100)\", type=int, default=100)\n parser.add_argument(\"-lRandSeq\", help=\"Length of random sequences (default: 50)\", type=int, default=50)\n parser.add_argument(\"-logLevel\", help=\"Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)\", default='WARNING')\n parser.add_argument(\"-output\", help=\"Output file name\", default='replPolicy.html')\n args = parser.parse_args()\n\n logging.basicConfig(stream=sys.stdout, format='%(message)s', level=logging.getLevelName(args.logLevel))\n\n policies = sorted(cacheSim.CommonPolicies.keys())\n if args.policies:\n policies = args.policies.split(',')\n elif args.allQLRUVariants:\n policies = sorted(set(cacheSim.CommonPolicies.keys())|set(cacheSim.AllDetQLRUVariants.keys()))\n elif args.randPolicies:\n if args.rep > 1:\n sys.exit('rep > 1 not supported for random policies')\n policies = sorted(cacheSim.AllRandPolicies.keys())\n\n if args.assoc:\n assoc = args.assoc\n else:\n assoc = getCacheInfo(args.level).assoc\n\n cBox = 0\n if args.cBox:\n cBox = args.cBox\n\n title = cpuid.cpu_name(cpuid.CPUID()) + ', Level: ' + str(args.level) + (', CBox: ' + str(cBox) if args.cBox else '')\n\n html = ['', '', '' + title + '', '', '']\n html += ['

' + title + '

']\n html += ['']\n html += ['']\n html += ['' for p in policies]\n html += ['']\n\n possiblePolicies = set(policies)\n counterExamples = dict()\n dists = {p: 0.0 for p in policies}\n\n seqList = []\n seqList.extend(getRandomSeq(args.lRandSeq) for _ in range(0,args.nRandSeq))\n\n for seq in seqList:\n fullSeq = ((args.initSeq + ' ') if args.initSeq else '') + seq\n print(fullSeq)\n\n html += ['']\n actualHits = set([getActualHits(fullSeq, args.level, args.sets, cBox, args.slice, args.nMeasurements) for _ in range(0, args.rep)])\n html += ['']\n\n outp = ''\n for p in policies:\n if not args.randPolicies:\n sim = cacheSim.getHits(fullSeq, cacheSim.AllPolicies[p], assoc, args.sets)\n\n if sim not in actualHits:\n possiblePolicies.discard(p)\n dists[p] += 1\n color = 'red'\n if args.findCtrEx and not p in counterExamples:\n counterExamples[p] = findSmallCounterexample(p, ((args.initSeq + ' ') if args.initSeq else ''), args.level, args.sets, cBox, args.slice,\n assoc, seq, args.nMeasurements)\n elif len(actualHits) > 1:\n color = 'yellow'\n else:\n color = 'green'\n else:\n sim = median(sum(cacheSim.getHits(fullSeq, cacheSim.AllPolicies[p], assoc, args.sets) for _ in range(0, args.nMeasurements)))\n dist = (sim - actual) ** 2\n dists[p] += dist\n\n colorR = min(255, dist)\n colorG = max(0, min(255, 512 - dist))\n color = 'rgb(' + str(colorR) + ',' + str(colorG) + ',0)'\n\n html += ['']\n\n html += ['']\n\n if not args.randPolicies and not args.best:\n print('Possible policies: ' + ', '.join(possiblePolicies))\n if not possiblePolicies: break\n\n if not args.randPolicies and args.findCtrEx:\n print('')\n print('Counter example(s):')\n for p, ctrEx in counterExamples.items():\n print(' ' + p + ': ' + ctrEx)\n\n html += ['
SequenceActual' + p.replace('_', '
_') + '
' + fullSeq + '' + ('{' if len(actualHits) > 1 else '') + ', '.join(map(str, sorted(actualHits))) + ('}' if len(actualHits) > 1 else '') + '' + str(sim) + '
', '', '']\n\n with open(args.output ,'w') as f:\n f.write('\\n'.join(html))\n os.chown(args.output, int(os.environ['SUDO_UID']), int(os.environ['SUDO_GID']))\n\n if not args.randPolicies and not args.best:\n print('Possible policies: ' + ', '.join(possiblePolicies))\n else:\n for p, d in reversed(sorted(dists.items(), key=lambda d: d[1])):\n print(p + ': ' + str(d))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"andreas-abel/nanoBench","sub_path":"tools/CacheAnalyzer/replPolicy.py","file_name":"replPolicy.py","file_ext":"py","file_size_in_byte":7582,"program_lang":"python","lang":"en","doc_type":"code","stars":394,"dataset":"github-code","pt":"29"} +{"seq_id":"6570710303","text":"import pytest\nimport json\nfrom tests.utils.dynamodb import mocked_table\n\n\nclass Context:\n pass\n\n\ngood_event = {\n \"requestContext\": {\n 'authorizer': {\n 'jwt': {\n 'claims': {\n 'sub': '1'\n }\n }\n }\n }\n}\n\n\n@pytest.fixture(scope='function')\ndef setup_table_item(dynamodb_table):\n table = mocked_table()\n item = {\n 'PK': 'CUSTOMER#1',\n 'SK': 'PROFILE#1',\n 'customer_id': '1',\n 'profile_data': {'some': 'data'}\n }\n table.put_item(Item=item)\n\n\ndef test_get_customer_handler_returns_200(setup_table_item):\n from src.handlers.get_customer_handler import handler\n result = handler(good_event, Context())\n print(result)\n assert result['statusCode'] == 200\n\n\ndef test_get_customer_handler_has_cors_headers(setup_table_item):\n from src.handlers.get_customer_handler import handler\n result = handler(good_event, Context)\n assert result['headers'] == {'Access-Control-Allow-Origin': '*'}\n\n\ndef test_get_customer_handler_has_json_body(setup_table_item):\n from src.handlers.get_customer_handler import handler\n result = handler(good_event, Context)\n assert isinstance(json.loads(result['body']), dict)\n\n\ndef test_get_customer_handler_returns_schema_validation_error(setup_table_item):\n from src.handlers.get_customer_handler import handler\n result = handler({\"bad\": \"input\"}, Context)\n assert result['statusCode'] == 400\n assert 'RequestValidationError' in result['body']\n","repo_name":"fernando-mc/serverless-surveys","sub_path":"tests/unit/handler/test_get_customer_handler.py","file_name":"test_get_customer_handler.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"22302357633","text":"# Python Packages\nimport time\nimport logging\nimport speedtest\nfrom statemachine import State\n# DAD Packages\nfrom dad.fsm.dad_fsm import DADFSM\nfrom dad.fsm.led_fsm import LedFSM\n\n\nclass InternetFSM(DADFSM):\n \"\"\" State machine for handling the internet speed indicator LED (red). LED will be solid when there is a strong internet\n download speed, slowly blinking when the internet speed is good, really slowly blinking when the internet speed is bad, and\n off when there is no internet available.\n\n .. _Speedtest-Cli\n https://github.com/sivel/speedtest-cli/wiki\n\n \"\"\"\n\n # Define states\n strong = State('Strong')\n good = State('Good')\n weak = State('Weak')\n off = State('Off', initial=True)\n\n # Define state transitions\n strong_to_good = strong.to(good)\n good_to_strong = good.to(strong)\n good_to_weak = good.to(weak)\n weak_to_good = weak.to(good)\n weak_to_off = weak.to(off)\n off_to_weak = off.to(weak)\n\n def __init__(self):\n super().__init__('/home/dad003/logging/internet_status.log')\n self._led = LedFSM(LedFSM.INTERNET_STATUS_LED_PIN)\n self._speed_test = speedtest.Speedtest()\n self._speed_test.get_best_server()\n\n def on_strong_to_good(self):\n \"\"\" State transition action, automatically called on strong to good transition.\n\n \"\"\"\n logging.warning(\"Internet connection reduction (strong to good connection).\")\n\n def on_good_to_strong(self):\n \"\"\" State transition action, automatically called on good to strong transition.\n\n \"\"\"\n logging.warning(\"Internet connection improvement (good to strong connection).\")\n\n def on_good_to_weak(self):\n \"\"\" State transition action, automatically called on good to weak transition.\n\n \"\"\"\n logging.warning(\"Internet connection reduction (good to weak connection).\")\n\n def on_weak_to_good(self):\n \"\"\" State transition action, automatically called on weak to good transition.\n\n \"\"\"\n logging.warning(\"Internet connection improvement (weak to good connection).\")\n\n def on_weak_to_off(self):\n \"\"\" State transition action, automatically called on weak to off transition.\n\n \"\"\"\n logging.warning(\"Internet connection reduction (Weak to no connection).\")\n\n def on_off_to_weak(self):\n \"\"\" State transition action, automatically called on weak to off transition.\n\n \"\"\"\n logging.warning(\"Internet connection improvement (no connection to weak).\")\n\n def run(self, transition_frequency=2):\n logging.info(\"Starting Internet FSM...\")\n super().run()\n\n def fetch_input(self):\n try:\n internet_speed = self._speed_test.download(threads=1) # internet speed in bit/s\n except Exception as e:\n logging.error(e)\n internet_speed = 0\n return internet_speed\n\n def handle_transitions(self, input):\n if self.is_strong and input <= 25000:\n self.strong_to_good()\n elif self.is_good:\n if input >= 25000:\n self.good_to_strong()\n elif input <= 9000:\n self.good_to_weak()\n elif self.is_weak:\n if input >= 9000:\n self.weak_to_good()\n elif input == 0:\n self.weak_to_off()\n elif self.is_off and input >= 0:\n self.off_to_weak()\n\n def handle_state_action(self):\n if self.is_strong:\n if self._led.is_low:\n self._led.low_to_high()\n time.sleep(2)\n elif self.is_good:\n self._led.toggle()\n time.sleep(1)\n elif self.is_weak:\n self._led.toggle()\n time.sleep(2)\n elif self.is_off:\n if self._led.is_high:\n self._led.high_to_low()\n time.sleep(2)\n\n def cleanup(self):\n try:\n if self._led.is_high:\n self._led.high_to_low()\n except Exception as e:\n logging.error(e)\n\n\nif __name__ == '__main__':\n internet_indicator = InternetFSM()\n internet_indicator.run()\n","repo_name":"BrendenDielissen-uofc/UofC-DAD","sub_path":"dad/fsm/internet_fsm.py","file_name":"internet_fsm.py","file_ext":"py","file_size_in_byte":4114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"42888658631","text":"\"\"\"\nTakes a json file and returns a csv with some of the\njson attributes\n\"\"\"\n\nimport json\nimport csv\n\nfrom collections import OrderedDict\n\ndef json2csv():\n '''\n no docstring\n '''\n header = ['index', 'shortname', 'name', 'unicode', 'unicode_encoded', 'aliases', 'image']\n columns = ['shortname', 'name', 'unicode']\n with open('emojione.json', 'r') as j:\n #load the json file in memory keeping the original ordering\n emojis = json.load(j, object_pairs_hook=OrderedDict)\n with open('emojis.csv', 'w', encoding='utf-8') as output:\n emojis_csv = csv.writer(output, delimiter=',', lineterminator='\\n',\n quotechar='\"', quoting=csv.QUOTE_ALL)\n emojis_csv.writerow(header)\n for i, ele in enumerate(emojis):\n row = [str(i+1)]\n row += [emojis[ele][x] for x in columns\n if x not in ('unicode_encoded', 'aliases', 'image')]\n unicodes = emojis[ele]['unicode'].split('-')\n unicode_encoded = [chr(int(code, 16)) for code in unicodes]\n row.append(' '.join(unicode_encoded))\n row.append(' '.join(emojis[ele]['aliases']))\n row.append('!https://cdn.jsdelivr.net/emojione/assets/png/%s.png?v=2.2.7!'\n % emojis[ele]['unicode'])\n emojis_csv.writerow(row)\n\nif __name__ == '__main__':\n json2csv()\n","repo_name":"lopezz/json2csv","sub_path":"json2csv.py","file_name":"json2csv.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36693112501","text":"import logging\nimport re\nimport os\n\nimport azure.functions as func\n\nimport pymongo\n\ndef find_bldg_from_id(ap):\n bldg = re.search(\"(^[A-Za-z]+)\", ap)[0]\n\n uri = \"mongodb://localhost:27017/ninerfi\"# os.environ[\"COSMOS_CONNECTION_STRING\"]\n client = pymongo.MongoClient(uri)\n\n db = client.ninerfi\n collection = db.access_points\n\n result = collection.find_one({\"prefix\": bldg})\n if (result):\n return result['_id']\n \n if (collection.count_documents({\"prefix\": \"\"}) > 0):\n result = collection.find({\"prefix\": \"\"})\n for doc in result:\n if (doc['building'].startswith(bldg)):\n collection.update_one({\"_id\": doc['_id']}, {\"$set\": {\"prefix\": bldg}})\n return doc['_id']\n \n logging.info('MANUAL --- ' + bldg)\n return None\n\n\ndef main(req: func.HttpRequest) -> func.HttpResponse:\n logging.info('Python HTTP trigger function processed a request.')\n\n log_batch = req.params.get('log_batch')\n if not log_batch:\n try:\n req_body = req.get_json()\n except ValueError:\n pass\n else:\n try:\n log_batch = req_body['log_batch']\n except KeyError:\n pass\n\n if log_batch:\n\n for log in list(log_batch):\n logging.info(f'{log}')\n\n entered_ap = re.search(\"<\\s(?:[0-9]{1,3}\\.){3}[0-9]{1,3}>\\s\\s(Assoc success) @ .{17}(.{17}).+?AP.+?(?:EXT-)?((?:[A-Za-z]){3,}[^\\s]+)\", log['log'])\n exited_ap = re.search(\"<\\s(?:[0-9]{1,3}\\.){3}[0-9]{1,3}>\\s\\s(Deauth to sta): (.{17}).+?AP.+?(?:EXT-)?((?:[A-Za-z]){3,}[^\\s]+)\", log['log'])\n\n if (entered_ap):\n uri = \"mongodb://localhost:27017/ninerfi\"#os.environ[\"COSMOS_CONNECTION_STRING\"]\n client = pymongo.MongoClient(uri)\n\n db = client.ninerfi\n collection = db.connected_devices\n\n mac_address = entered_ap[2]\n ap = entered_ap[3]\n\n apId = find_bldg_from_id(ap)\n\n if (apId):\n collection.update_one({\"mac_address\": mac_address}, {\"$set\": {\n \"access_point\": apId\n }}, upsert=True)\n\n logging.info(f'Access Point {ap} count updated.')\n \n elif (exited_ap):\n uri = \"mongodb://localhost:27017/ninerfi\"#os.environ[\"COSMOS_CONNECTION_STRING\"]\n client = pymongo.MongoClient(uri)\n\n db = client.ninerfi\n collection = db.connected_devices\n\n mac_address = exited_ap[2]\n ap = exited_ap[3]\n\n apId = find_bldg_from_id(ap)\n\n if (apId):\n result = collection.delete_one({\"mac_address\": mac_address})\n\n if (result.deleted_count > 0): logging.info(f'Access Point {ap} count updated.')\n \n else:\n pass\n\n return func.HttpResponse(\n \"Log batch parsed successfully.\",\n status_code=200\n )\n\n else:\n return func.HttpResponse(\n \"No log batch provided in request body.\",\n status_code=400\n )\n","repo_name":"mrusse54/NinerFi","sub_path":"python/azurefunc/ParseLog/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12938392155","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def middleNode(self, head):\n cur=head\n lg=1\n while cur.next:\n lg+=1\n cur=cur.next\n lg//=2\n for i in range(lg):\n head=head.next\n return head\n \n","repo_name":"bemnet16/competitive-programming","sub_path":"MiddleoftheLinkedList.py","file_name":"MiddleoftheLinkedList.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12860957977","text":"# Given a collection of intervals, merge all overlapping intervals.\n#\n# Example 1:\n#\n# Input: [[1,3],[2,6],[8,10],[15,18]]\n# Output: [[1,6],[8,10],[15,18]]\n# Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].\n# Example 2:\n#\n# Input: [[1,4],[4,5]]\n# Output: [[1,5]]\n# Explanation: Intervals [1,4] and [4,5] are considerred overlapping.\n\n\n# Definition for an interval.\n# class Interval(object):\n# def __init__(self, s=0, e=0):\n# self.start = s\n# self.end = e\n\nclass Solution(object):\n def merge(self, intervals):\n \"\"\"\n :type intervals: List[Interval]\n :rtype: List[Interval]\n \"\"\"\n\n if not intervals:\n return []\n\n intervals.sort(key=lambda x: x.start)\n\n output = [intervals[0]]\n\n for i in range(1, len(intervals)):\n if intervals[i].start <= output[-1].end:\n output[-1].end = max(output[-1].end, intervals[i].end)\n else:\n output.append(intervals[i])\n\n return output\n\n# i = 0\n\n# while i < len(intervals)-1:\n\n# if intervals[i].end >= intervals[i+1].start:\n# start = min(intervals[i].start, intervals[i+1].start)\n# end = max(intervals[i].end, intervals[i+1].end)\n# i += 2\n# else:\n# start = intervals[i].start\n# end = intervals[i].end\n# i += 1\n# output.append(Interval(start,end))\n\n# if i == len(intervals)-1:\n# output.append(intervals[i])\n\n# if len(output) == len(intervals):\n# return output\n# else:\n# return self.merge(output)\n\n\n\n# 252 - Meeting Rooms\n\"\"\"\nGiven an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings.\n\nFor example,\nGiven [[0, 30],[5, 10],[15, 20]],\nreturn false.\n\"\"\"\n\n\n# Definition for an interval.\n# class Interval(object):\n# def __init__(self, s=0, e=0):\n# self.start = s\n# self.end = e\n\nclass Solution(object):\n def canAttendMeetings(self, intervals):\n \"\"\"\n :type intervals: List[Interval]\n :rtype: bool\n \"\"\"\n\n intervals.sort(key=lambda x: x.start)\n\n for i in range(1, len(intervals)):\n if intervals[i].start < intervals[i - 1].end:\n return False\n\n return True\n","repo_name":"mansi135/LeetcodeProblems","sub_path":"Arrays_and_Numbers/56- MergeIntervals.py","file_name":"56- MergeIntervals.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3175844227","text":"import cv2 as cv\nimport numpy as np\nimport scipy\nimport PIL.Image\nimport math\nimport caffe\nimport time\nfrom config_reader import config_reader\nimport util\nimport copy\nimport matplotlib\nimport pylab as plt\nimport scipy\nfrom scipy.ndimage.filters import gaussian_filter\n\n# find connection in the specified sequence, center 29 is in the position 15\nlimbSeq = [[2,3], [2,6], [3,4], [4,5], [6,7], [7,8], [2,9], [9,10], \\\n [10,11], [2,12], [12,13], [13,14], [2,1], [1,15], [15,17], \\\n [1,16], [16,18], [3,17], [6,18]]\n# the middle joints heatmap correpondence\nmapIdx = [[31,32], [39,40], [33,34], [35,36], [41,42], [43,44], [19,20], [21,22], \\\n [23,24], [25,26], [27,28], [29,30], [47,48], [49,50], [53,54], [51,52], \\\n [55,56], [37,38], [45,46]]\nmap_to_3d = [13, 12, 8, 7, 6, 9, 10, 11, 2, 1, 0, 3, 4, 5] # different convention\n# with smpl\n\ndef get_heatmap(oriImg, param, model, multiplier, net):\n \"\"\"\n this function allows to get the heat map from the image according to\n param multiplier and the neural network\n \"\"\"\n heatmap_avg = np.zeros((oriImg.shape[0], oriImg.shape[1], 19))\n paf_avg = np.zeros((oriImg.shape[0], oriImg.shape[1], 38))\n for m in range(len(multiplier)):\n scale = multiplier[m]\n imageToTest = cv.resize(oriImg, (0,0), fx=scale, fy=scale, interpolation=cv.INTER_CUBIC)\n imageToTest_padded, pad = util.padRightDownCorner(imageToTest,\n model['stride'], model['padValue'])\n # we first rescale the image to see different layers of the image\n net.blobs['data'].reshape(*(1, 3, imageToTest_padded.shape[0], imageToTest_padded.shape[1]))\n #net.forward() # dry run\n net.blobs['data'].data[...] = np.transpose(np.float32(imageToTest_padded[:,:,:,np.newaxis]), (3,2,0,1))/256 - 0.5;\n start_time = time.time()\n output_blobs = net.forward()\n print('At scale %d, The CNN took %.2f ms.' % (m, 1000 * (time.time() - start_time)))\n # extract outputs, resize, and remove padding\n heatmap = np.transpose(np.squeeze(net.blobs[output_blobs.keys()[1]].data), (1,2,0)) # output 1 is heatmaps\n heatmap = cv.resize(heatmap, (0,0), fx=model['stride'], fy=model['stride'], interpolation=cv.INTER_CUBIC)\n heatmap = heatmap[:imageToTest_padded.shape[0]-pad[2], :imageToTest_padded.shape[1]-pad[3], :]\n heatmap = cv.resize(heatmap, (oriImg.shape[1], oriImg.shape[0]), interpolation=cv.INTER_CUBIC)\n \n paf = np.transpose(np.squeeze(net.blobs[output_blobs.keys()[0]].data), (1,2,0)) # output 0 is PAFs\n paf = cv.resize(paf, (0,0), fx=model['stride'], fy=model['stride'], interpolation=cv.INTER_CUBIC)\n paf = paf[:imageToTest_padded.shape[0]-pad[2], :imageToTest_padded.shape[1]-pad[3], :]\n paf = cv.resize(paf, (oriImg.shape[1], oriImg.shape[0]), interpolation=cv.INTER_CUBIC)\n heatmap_avg = heatmap_avg + heatmap / len(multiplier)\n paf_avg = paf_avg + paf / len(multiplier)\n \n return heatmap_avg, paf_avg\n \n\ndef NMS(heatmap_avg, paf_avg, param):\n \"\"\"\n select peaks among many others \n \"\"\"\n all_peaks = []\n peak_counter = 0\n \n for part in range(19):\n x_list = []\n y_list = []\n map_ori = heatmap_avg[:,:,part]\n map = gaussian_filter(map_ori, sigma=3)\n map_left = np.zeros(map.shape)\n map_left[1:,:] = map[:-1,:]\n map_right = np.zeros(map.shape)\n map_right[:-1,:] = map[1:,:]\n map_up = np.zeros(map.shape)\n map_up[:,1:] = map[:,:-1]\n map_down = np.zeros(map.shape)\n map_down[:,:-1] = map[:,1:]\n\n peaks_binary = np.logical_and.reduce((map>=map_left, map>=map_right, map>=map_up, map>=map_down, map > param['thre1']))\n peaks = zip(np.nonzero(peaks_binary)[1], np.nonzero(peaks_binary)[0]) # note reverse\n peaks_with_score = [x + (map_ori[x[1],x[0]],) for x in peaks]\n id = range(peak_counter, peak_counter + len(peaks))\n peaks_with_score_and_id = [peaks_with_score[i] + (id[i],) for i in range(len(id))]\n\n all_peaks.append(peaks_with_score_and_id)\n peak_counter += len(peaks)\n return all_peaks, peak_counter\n\n\ndef create_connection(all_peaks, peak_counter, paf_avg, oriImg, param):\n connection_all = []\n special_k = []\n mid_num = 10\n\n for k in range(len(mapIdx)):\n score_mid = paf_avg[:,:,[x-19 for x in mapIdx[k]]]\n candA = all_peaks[limbSeq[k][0]-1]\n candB = all_peaks[limbSeq[k][1]-1]\n nA = len(candA)\n nB = len(candB)\n indexA, indexB = limbSeq[k]\n if(nA != 0 and nB != 0):\n connection_candidate = []\n for i in range(nA):\n for j in range(nB):\n vec = np.subtract(candB[j][:2], candA[i][:2])\n norm = math.sqrt(vec[0]*vec[0] + vec[1]*vec[1])\n if (norm == 0):\n break\n vec = np.divide(vec, norm)\n \n startend = zip(np.linspace(candA[i][0], candB[j][0], num=mid_num), \\\n np.linspace(candA[i][1], candB[j][1], num=mid_num))\n \n vec_x = np.array([score_mid[int(round(startend[I][1])), int(round(startend[I][0])), 0] \\\n for I in range(len(startend))])\n vec_y = np.array([score_mid[int(round(startend[I][1])), int(round(startend[I][0])), 1] \\\n for I in range(len(startend))])\n\n score_midpts = np.multiply(vec_x, vec[0]) + np.multiply(vec_y, vec[1])\n score_with_dist_prior = sum(score_midpts)/len(score_midpts) + min(0.5*oriImg.shape[0]/norm-1, 0)\n criterion1 = len(np.nonzero(score_midpts > param['thre2'])[0]) > 0.8 * len(score_midpts)\n criterion2 = score_with_dist_prior > 0\n if criterion1 and criterion2:\n connection_candidate.append([i, j, score_with_dist_prior, score_with_dist_prior+candA[i][2]+candB[j][2]])\n\n connection_candidate = sorted(connection_candidate, key=lambda x: x[2], reverse=True)\n connection = np.zeros((0,5))\n for c in range(len(connection_candidate)):\n i,j,s = connection_candidate[c][0:3]\n if(i not in connection[:,3] and j not in connection[:,4]):\n connection = np.vstack([connection, [candA[i][3], candB[j][3], s, i, j]])\n if(len(connection) >= min(nA, nB)):\n break\n\n connection_all.append(connection)\n else:\n special_k.append(k)\n connection_all.append([])\n return connection_all, special_k\n\ndef create_subset(connection_all, special_k, all_peaks, peak_counter):\n \"\"\"\n We have peaks now we want to associate it to person. So this function\n give us the subset for a person.\n \"\"\"\n subset = -1 * np.ones((0, 20))\n candidate = np.array([item for sublist in all_peaks for item in sublist])\n for k in range(len(mapIdx)):\n if k not in special_k:\n partAs = connection_all[k][:,0]\n partBs = connection_all[k][:,1]\n indexA, indexB = np.array(limbSeq[k]) - 1\n for i in range(len(connection_all[k])): #= 1:size(temp,1)\n found = 0\n subset_idx = [-1, -1]\n for j in range(len(subset)): #1:size(subset,1):\n if subset[j][indexA] == partAs[i] or subset[j][indexB] == partBs[i]:\n subset_idx[found] = j\n found += 1\n if found == 1:\n j = subset_idx[0]\n if(subset[j][indexB] != partBs[i]):\n subset[j][indexB] = partBs[i]\n subset[j][-1] += 1\n subset[j][-2] += candidate[partBs[i].astype(int), 2] + connection_all[k][i][2]\n elif found == 2: # if found 2 and disjoint, merge them\n j1, j2 = subset_idx\n # print \"found = 2\"\n membership = ((subset[j1]>=0).astype(int) + (subset[j2]>=0).astype(int))[:-2]\n if len(np.nonzero(membership == 2)[0]) == 0: #merge\n subset[j1][:-2] += (subset[j2][:-2] + 1)\n subset[j1][-2:] += subset[j2][-2:]\n subset[j1][-2] += connection_all[k][i][2]\n subset = np.delete(subset, j2, 0)\n else: # as like found == 1\n subset[j1][indexB] = partBs[i]\n subset[j1][-1] += 1\n subset[j1][-2] += candidate[partBs[i].astype(int), 2] + connection_all[k][i][2]\n elif not found and k < 17:\n row = -1 * np.ones(20)\n row[indexA] = partAs[i]\n row[indexB] = partBs[i]\n row[-1] = 2\n row[-2] = sum(candidate[connection_all[k][i,:2].astype(int), 2]) + connection_all[k][i][2]\n subset = np.vstack([subset, row])\n deleteIdx = [];\n for i in range(len(subset)):\n if subset[i][-1] < 4 or subset[i][-2]/subset[i][-1] < 0.4:\n deleteIdx.append(i)\n subset = np.delete(subset, deleteIdx, axis=0)\n return subset, candidate\n\n\ndef save_person(subset, candidate):\n \"\"\"\n save all the complete persons of an image\n \"\"\"\n n_pers = 0\n list_cand = []\n for n in range(len(subset)):\n # for each subset, we check -1\n if(np.sum(subset[n,:16]==-1)==0):\n n_pers = n_pers + 1\n # index of the subset from nose to elbow\n index = subset[n,:16].astype(int)\n X = candidate[index, 0]\n Y = candidate[index, 1]\n score = candidate[index, 2]\n perso = np.vstack((X, Y, score))\n new_pers = np.zeros(perso.shape)\n for i in range(len(map_to_3d)):\n new_pers[:, map_to_3d[i]] = perso[:, i]\n eye = 0.5*(perso[:2,15]+perso[:2,14])\n new_pers[:2, 13] = eye \n new_pers[2,13] = 0.5*(perso[2,15]+perso[2,14])\n list_cand.append(new_pers)\n return list_cand, n_pers\n \n \n","repo_name":"sofsoo1995/RECVIS_Project","sub_path":"func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":10342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3777145392","text":"class Solution:\r\n def maxSubArray(self, nums) -> int:\r\n res = nums[0]\r\n max_end = nums[0]\r\n\r\n for i in range(1, len(nums)):\r\n max_end = max(max_end + nums[i], nums[i])\r\n \r\n res = max(res, max_end)\r\n\r\n return res \r\n\r\ntest = Solution()\r\nprint(test.maxSubArray( [-2,1,-3,4,-1,2,1,-5,4]))\r\n","repo_name":"dinhphu2k1-gif/Algorithm","sub_path":"Problem/LeetCode/Python/Maximum Subarray.py","file_name":"Maximum Subarray.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26474671208","text":"import os\nimport requests\n\nfrom django import http\nfrom django.core.cache import cache\nfrom django.views.decorators.http import require_http_methods\n\n\nLISTEN_API_KEY = os.environ.get('LISTEN_API_KEY', '')\nBASE_URL = 'https://listen-api.listennotes.com/api/v2'\n\n\n@require_http_methods(['GET'])\ndef search(request):\n query = request.GET.get('q')\n sort_by_date = request.GET.get('sort_by_date')\n result_type = request.GET.get('type')\n offset = request.GET.get('offset', '0')\n\n if cache.get('quota_exceeded', False):\n # Listen API won't bill HEAD requests. You can use HEAD requests to check API usage.\n head_response = requests.head(\n '%s/search' % BASE_URL,\n headers={\n 'X-ListenAPI-Key': LISTEN_API_KEY,\n 'Accept': 'application/json',\n })\n\n if int(head_response.headers['X-ListenAPI-Usage']) > int(head_response.headers['X-ListenAPI-FreeQuota']):\n return http.HttpResponse(status=429)\n else:\n cache.set('quota_exceeded', False)\n\n response = requests.get(\n '{}/search?q={}&sort_by_date={}&type={}&offset={}'.format(BASE_URL, query, sort_by_date, result_type, offset),\n headers={\n 'X-ListenAPI-Key': LISTEN_API_KEY,\n 'Accept': 'application/json'\n })\n\n if int(response.headers['X-ListenAPI-Usage']) > int(response.headers['X-ListenAPI-FreeQuota']):\n cache.set('quota_exceeded', True)\n\n return http.JsonResponse(response.json())\n","repo_name":"markthomas93/ListenApiDemo","sub_path":"backend/ListenApiDemo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"18609689723","text":"### Model free learning using Q-learning and SARSA\n### You must not change the arguments and output types of the given function. \n### You may debug in Main and elsewhere.\n\nimport numpy as np\nimport gym\nimport time\nfrom gym.wrappers import Monitor\nfrom taxi_envs import *\nimport random\nimport matplotlib.pyplot as plt\n\ndef QLearning(env, num_episodes, gamma, lr, e):\n \"\"\"Implement the Q-learning algorithm following the epsilon-greedy exploration.\n Update Q at the end of every episode.\n\n Parameters\n ----------\n env: gym.core.Environment\n Environment to compute Q function\n num_episodes: int \n Number of episodes of training.\n gamma: float\n Discount factor. \n learning_rate: float\n Learning rate. \n e: float\n Epsilon value used in the epsilon-greedy method. \n\n\n Returns\n -------\n np.array\n An array of shape [env.nS x env.nA] representing state, action values\n \"\"\"\n\n ############################\n # YOUR CODE #\n ############################\n if __name__ == \"__main__\":\n global q_rewards\n global q_nums\n else:\n q_rewards = list()\n q_nums = list()\n\n Q = np.ones((env.nS, env.nA))\n for i in range (env.nS):\n for j in range(env.nA):\n if env.P[i][j][0][3]:\n Q[i][j] = 0\n\n total_reward = 0\n for n in range (num_episodes):\n #total_reward = 0\n cnt = 0\n s = np.random.randint(env.nS)\n if random.random() > e:\n a = np.argmax(Q[s])\n else:\n a = random.choice([i for i in range(env.nA) if i != np.argmax(Q[s])])\n\n while True:\n R = env.P[s][a][0][2]\n total_reward += R\n cnt += 1\n s_next = env.P[s][a][0][1]\n if random.random() > e:\n a_next = np.argmax(Q[s_next])\n else:\n a_next = random.choice([i for i in range (env.nA) if i != np.argmax(Q[s_next])])\n\n Q[s][a] += lr * (R + gamma * max(Q[s_next][j] for j in range (6)) - Q[s][a])\n s = s_next\n a = a_next\n\n if env.P[s][a][0][3]:\n break\n\n episode_reward = total_reward / (n + 1)\n q_rewards.append(episode_reward)\n q_nums.append(cnt)\n\n return Q\n\n\ndef SARSA(env, num_episodes, gamma, lr, e):\n \"\"\"Implement the SARSA algorithm following epsilon-greedy exploration.\n Update Q at the end of every episode.\n\n Parameters\n ----------\n env: gym.core.Environment\n Environment to compute Q function \n num_episodes: int \n Number of episodes of training\n gamma: float\n Discount factor. \n learning_rate: float\n Learning rate. \n e: float\n Epsilon value used in the epsilon-greedy method. \n\n\n Returns\n -------\n np.array\n An array of shape [env.nS x env.nA] representing state-action values\n \"\"\"\n\n ############################\n # YOUR CODE #\n ############################\n if __name__ == \"__main__\":\n global s_rewards\n global s_nums\n else:\n s_rewards = list()\n s_nums = list()\n\n Q = np.ones((env.nS, env.nA))\n for i in range (env.nS):\n for j in range (env.nA):\n if env.P[i][j][0][3]:\n Q[i][j] = 0\n\n total_reward = 0\n for n in range (num_episodes):\n #total_reward = 0\n cnt = 0\n s = np.random.randint(env.nS)\n if random.random() > e:\n a = np.argmax(Q[s])\n else:\n a = random.choice([i for i in range (env.nA) if i != np.argmax(Q[s])])\n\n while True:\n s_next = env.P[s][a][0][1]\n R = env.P[s][a][0][2]\n total_reward += R\n cnt += 1\n\n if random.random() > e:\n a_next = np.argmax(Q[s_next])\n else:\n a_next = random.choice([i for i in range (env.nA) if i != np.argmax(Q[s])])\n\n Q[s][a] += lr * (R + gamma * Q[s_next][a_next] - Q[s][a])\n s = s_next\n a = a_next\n \n if env.P[s][a][0][3]:\n break\n \n episode_reward = total_reward / (n + 1)\n s_rewards.append(episode_reward)\n s_nums.append(cnt)\n\n return Q\n\n\ndef render_episode_Q(env, Q):\n \"\"\"Renders one episode for Q functionon environment.\n\n Parameters\n ----------\n env: gym.core.Environment\n Environment to play Q function on. \n Q: np.array of shape [env.nS x env.nA]\n state-action values.\n \"\"\"\n\n episode_reward = 0\n state = env.reset()\n done = False\n while not done:\n env.render()\n time.sleep(0.5) \n action = np.argmax(Q[state])\n state, reward, done, _ = env.step(action)\n episode_reward += reward\n\n print (\"Episode reward: %f\" %episode_reward)\n\n\n\ndef main():\n env = gym.make(\"Assignment1-Taxi-v2\")\n Q_QL = QLearning(env, num_episodes=1000, gamma=0.95, lr=0.1, e=0.1)\n Q_Sarsa = SARSA(env, num_episodes=1000, gamma=0.95, lr=0.1, e=0.1)\n #render_episode_Q(env, Q_QL)\n plt.plot(q_rewards)\n plt.show()\n '''\n for i in range(len(Q_QL)):\n print([Q_QL[i][j] for j in range(len(Q_QL[0]))])\n '''\n plt.plot(s_rewards)\n plt.show()\n '''\n for i in range(len(Q_QL)):\n print([Q_Sarsa[i][j] for j in range(len(Q_Sarsa[0]))])\n '''\n plt.plot(q_nums)\n plt.show()\n plt.plot(s_nums)\n plt.show()\n\nif __name__ == '__main__':\n q_rewards = list()\n s_rewards = list()\n q_nums = list()\n s_nums = list()\n main()\n","repo_name":"nysm007/playground","sub_path":"reinforcement-learning/hw1/ql_sarsa.py","file_name":"ql_sarsa.py","file_ext":"py","file_size_in_byte":5558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9664839695","text":"from django.shortcuts import render\n\n# Create your views here.\ndef example_view(req):\n return render(req, 'my_app/example.html')\n\ndef variable_view(request):\n my_var = {\n 'first_name': 'Rose',\n 'last_name': 'Mask',\n 'some_list': [1,2,3],\n 'some_dict': {'inside_key': 'inside_value'},\n 'user_logged_in': False\n\n }\n return render(request, 'my_app/variable.html', context=my_var)","repo_name":"Kartik2301/Recurrence","sub_path":"Django/second_site/my_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"4391159329","text":"# 2023/01/28 BruteForce\n# https://www.acmicpc.net/problem/2531\nimport sys\ninput = sys.stdin.readline\n\nN, d, k, c = map(int,input().split())\n# 초밥 정보 입력\ncho_list = []\nfor _ in range(N):\n cho = int(input())\n cho_list.append(cho)\n\n# 탐색 시작\nres = 0\nfor i in range(N):\n # 연속된 초밥을 먹는 경우 확인\n if i + k <= N:\n check = set(list(cho_list[i:i+k]))\n else:\n check = set(list(cho_list[i:N]) + cho_list[0: (i+k) % N])\n p = len(check)\n if c not in check: # 먹은 것 중 쿠폰에 적힌 번호가 없는 경우 +1\n p += 1\n res = max(res, p)\n\n# 정답 출력\nprint(res)\n","repo_name":"simple0710/BOJ","sub_path":"silver/[2531] 회전 초밥.py","file_name":"[2531] 회전 초밥.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"32471523257","text":"#!/usr/bin/python\n#\n# This is a free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This Ansible library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this library. If not, see .\n\nDOCUMENTATION = '''\n---\nmodule: ec2_vpc_route_table\nshort_description: Manage route tables for AWS virtual private clouds\ndescription:\n - Manage route tables for AWS virtual private clouds\nversion_added: \"2.2\"\nauthor: Robert Estelle (@erydo), Rob White (@wimnat), Allen Sanabria (@linuxdynasty)\noptions:\n lookup:\n description:\n - \"This option is deprecated. Tags are manadatory when creating a route\n table. If a route table id is specified, then that will be use. Otherwise, this module will perform an exact match for all the tags applied. If a match is not found, it will than search by tag Name.\"\n - \"Look up route table by either tags or by route table ID. Non-unique\n tag lookup will fail. If no tags are specifed then no lookup for an existing route table is performed and a new route table will be created. To change tags of a route table, you must look up by id.\"\n required: false\n default: tag\n choices: [ 'tag', 'id' ]\n propagating_vgw_ids:\n description:\n - \"Enable route propagation from virtual gateways specified by ID. Only 1 virtual gateway can only be applied to a vpc at a time.\"\n default: None\n required: false\n route_table_id:\n description:\n - \"The ID of the route table to update or delete.\"\n required: false\n default: null\n routes:\n description:\n - \"List of routes in the route table. Routes are specified as dicts\n containing the keys 'dest' and one of 'gateway_id', 'instance_id', 'nat_gateway_id', interface_id', or 'vpc_peering_connection_id'. If 'gateway_id' is specified, you can refer to the VPC's IGW by using the value 'igw'.\"\n required: true\n state:\n description:\n - \"Create or destroy the VPC route table\"\n required: false\n default: present\n choices: [ 'present', 'absent' ]\n subnets:\n description:\n - \"An array of subnets to add to this route table. Subnets may be specified by either subnet ID, Name tag, or by a CIDR such as '10.0.0.0/24'.\"\n required: true\n tags:\n description:\n - \"A dictionary of resource tags of the form: { tag1: value1, tag2: value2 }. Tags are used to uniquely identify route tables within a VPC when the route_table_id is not supplied.\"\n required: false\n default: null\n aliases: [ \"resource_tags\" ]\n vpc_id:\n description:\n - \"VPC ID of the VPC in which to create the route table.\"\n required: true\nextends_documentation_fragment:\n - aws\n - ec2\n'''\n\nEXAMPLES = '''\n# Note: These examples do not set authentication details, see the AWS Guide for details.\n\n# Basic creation example:\n- name: Set up public subnet route table\n ec2_vpc_route_table:\n vpc_id: vpc-1245678\n region: us-west-1\n tags:\n Name: Public\n subnets:\n - \"{{ jumpbox_subnet.subnet.id }}\"\n - \"{{ frontend_subnet.subnet.id }}\"\n - \"{{ vpn_subnet.subnet_id }}\"\n routes:\n - dest: 0.0.0.0/0\n gateway_id: \"{{ igw.gateway_id }}\"\n register: public_route_table\n\n- name: Set up NAT-protected route table\n ec2_vpc_route_table:\n vpc_id: vpc-1245678\n region: us-west-1\n tags:\n Name: Internal\n subnets:\n - \"{{ application_subnet.subnet.id }}\"\n - 'Database Subnet'\n - '10.0.0.0/8'\n routes:\n - dest: 0.0.0.0/0\n instance_id: \"{{ nat.instance_id }}\"\n register: nat_route_table\n\n'''\nRETURN = '''\nassociations:\n description: List of subnets attached to this route table with its association id.\n returned: success\n type: string\n sample: [\n {\n \"subnet_id\": \"subnet-12345667\",\n \"route_table_id\": \"rtb-1234567\",\n \"main\": false,\n \"route_table_association_id\": \"rtbassoc-1234567\"\n },\n {\n \"subnet_id\": \"subnet-78654321\",\n \"route_table_id\": \"rtb-78654321\",\n \"main\": false,\n \"route_table_association_id\": \"rtbassoc-78654321\"\n }\n ]\npropagating_vgws:\n description: List of virtual gateways applied to the route table.\n returned: success\n type: string\n sample: [\n {\n 'gateway_id': 'vgw-1234567'\n }\n ]\nroutes:\n description: List of tags applied to the route table.\n returned: success\n type: string\n sample: [\n {\n \"gateway_id\": \"local\",\n \"origin\": \"CreateRouteTable\",\n \"state\": \"active\",\n \"destination_cidr_block\": \"10.100.0.0/16\"\n },\n {\n \"origin\": \"CreateRoute\",\n \"state\": \"active\",\n \"nat_gateway_id\": \"nat-12345678\",\n \"destination_cidr_block\": \"0.0.0.0/0\"\n }\n ]\ntags:\n description: List of tags applied to the route table.\n returned: success\n type: string\n sample: [\n {\n \"key\": \"Name\",\n \"value\": \"dev_route_table\"\n },\n {\n \"key\": \"env\",\n \"value\": \"development\"\n }\n ]\nroute_table_id:\n description: The resource id of an Amazon route table.\n returned: success\n type: string\n sample: \"rtb-1234567\"\nvpc_id:\n description: id of the VPC.\n returned: In all cases.\n type: string\n sample: \"vpc-12345\"\n'''\ntry:\n import botocore\n import boto3\n HAS_BOTO3 = True\nexcept ImportError:\n HAS_BOTO3 = False\n\nimport re\nimport datetime\nfrom functools import reduce\n\nDRY_RUN_MATCH = re.compile(r'DryRun flag is set')\n\ndef convert_to_lower(data):\n \"\"\"Convert all uppercase keys in dict with lowercase_\n Args:\n data (dict): Dictionary with keys that have upper cases in them\n Example.. NatGatewayAddresses == nat_gateway_addresses\n if a val is of type datetime.datetime, it will be converted to\n the ISO 8601\n\n Basic Usage:\n >>> test = {'NatGatewaysAddresses': []}\n >>> test = convert_to_lower(test)\n {\n 'nat_gateways_addresses': []\n }\n\n Returns:\n Dictionary\n \"\"\"\n results = dict()\n if isinstance(data, dict):\n for key, val in data.items():\n key = re.sub(r'(([A-Z]{1,3}){1})', r'_\\1', key).lower()\n if key[0] == '_':\n key = key[1:]\n if isinstance(val, datetime.datetime):\n results[key] = val.isoformat()\n elif isinstance(val, dict):\n results[key] = convert_to_lower(val)\n elif isinstance(val, list):\n converted = list()\n for item in val:\n converted.append(convert_to_lower(item))\n results[key] = converted\n else:\n results[key] = val\n return results\n\nGATEWAY_MAP = {\n 'gateway_id': 'GatewayId',\n 'instance_id': 'InstanceId',\n 'network_interface_id': 'NetworkInterfaceId',\n 'vpc_peering_connection_id': 'VpcPeeringConnectionId',\n 'nat_gateway_id': 'NatGatewayId',\n}\n\ndef valid_gateway_types():\n \"\"\"List of currently supported gateway types in Boto3\n\n Basic Usage\n >>> valid_gateway_types()\n\n Returns:\n List\n \"\"\"\n return [\n 'gateway_id',\n 'instance_id',\n 'network_interface_id',\n 'vpc_peering_connection_id',\n 'nat_gateway_id'\n ]\n\ndef valid_route_type(route):\n \"\"\"Validate if dictionary contains a valid gateway key.\n\n Args:\n route (dict): Dictionary containing the route information.\n\n Basic Usage:\n >>> route = {'dest': '0.0.0.0/0', 'nat_gateway_id': 'ngw-123456789'}\n >>> success, key = valid_route_type(route)\n\n Returns:\n Tuple (bool, str)\n \"\"\"\n success = False\n for key, val in route.items():\n if key != 'dest' and key in valid_gateway_types():\n success = True\n return success, key\n elif key != 'dest' and key not in valid_gateway_types():\n return success, key\n\ndef validate_routes(routes):\n \"\"\"Validate if all of the routes contain valid gateway keys.\n Args:\n routes (list): List of routes.\n\n Basic Usage:\n >>> routes = [{'dest': '0.0.0.0/0', 'nat_gateway_id': 'ngw-123456789'}]\n >>> success, err_msg = validate_routes(routes)\n\n Returns:\n Tuple (bool, str)\n \"\"\"\n success = True\n err_msg = ''\n for route in routes:\n success, route_type = valid_route_type(route)\n if not success:\n err_msg = '{0} is not a valid gateway type'.format(route_type)\n return success, err_msg\n\ndef route_keys(client, vpc_id, routes, check_mode=False):\n \"\"\"Return a new list containing updated keys.\n Args:\n client (botocore.client.EC2): Boto3 client.\n vpc_id (str): The vpc_id of the vpc.\n routes (list): List of routes.\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> vpc_id = 'vpc-1234567'\n >>> routes = [{'dest': '0.0.0.0/0', 'nat_gateway_id': 'ngw-123456789'}]\n >>> new_routes = route_keys(client, vpc_id, routes)\n [\n {\n 'dest': '0.0.0.0/0',\n 'id': 'ngw-123456789',\n 'gateway_type': 'nat_gateway_id'\n }\n ]\n\n Returns:\n List\n \"\"\"\n new_routes = list()\n for route in routes:\n info = dict()\n for key, val in route.items():\n if key != 'dest' and key in valid_gateway_types():\n if key == 'gateway_id' and val == 'igw':\n igw_success, igw_msg, igw_id = (\n find_igw(client, vpc_id, check_mode=check_mode)\n )\n if igw_success and igw_id:\n val = igw_id\n info['id'] = val\n info['gateway_type'] = key\n elif key == 'dest':\n info['dest'] = val\n new_routes.append(info)\n return new_routes\n\ndef make_tags_in_proper_format(tags):\n \"\"\"Take a list of tags and convert them into a proper dictionary.\n Args:\n tags (list): The tags you want applied.\n\n Basic Usage:\n >>> tags = [{u'Key': 'env', u'Value': 'development'}]\n >>> make_tags_in_proper_format(tags)\n [\n {\n \"env\": \"development\"\n }\n ]\n\n Returns:\n Dict\n \"\"\"\n formatted_tags = dict()\n for tag in tags:\n formatted_tags[tag.get('Key')] = tag.get('Value')\n\n return formatted_tags\n\ndef make_tags_in_aws_format(tags):\n \"\"\"Take a dictionary of tags and convert them into the AWS Tags format.\n Args:\n tags (dict): The tags you want applied.\n\n Basic Usage:\n >>> tags = {'env': 'development', 'service': 'web'}\n >>> make_tags_in_proper_format(tags)\n [\n {\n \"Value\": \"web\",\n \"Key\": \"service\"\n },\n {\n \"Value\": \"development\",\n \"key\": \"env\"\n }\n ]\n\n Returns:\n List\n \"\"\"\n formatted_tags = list()\n for key, val in tags.items():\n formatted_tags.append({\n 'Key': key,\n 'Value': val\n })\n\n return formatted_tags\n\ndef find_igw(client, vpc_id, check_mode=False):\n \"\"\"Find an Internet Gateway for a VPC.\n Args:\n client (botocore.client.EC2): Boto3 client.\n vpc_id (str): The vpc_id of the vpc.\n\n Kwargs:\n check_mode (bool): This will pass DryRun as one of the parameters to the aws api.\n default=False\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> vpc_id = 'vpc-1234567'\n >>> find_igw(client, vpc_id)\n\n Returns:\n Tuple (bool, str, str)\n \"\"\"\n err_msg = ''\n success = False\n igw_id = None\n params = {\n 'DryRun': check_mode,\n 'Filters': [\n {\n 'Name': 'attachment.vpc-id',\n 'Values': [vpc_id],\n }\n ]\n }\n try:\n results = (\n client.describe_internet_gateways(**params)['InternetGateways']\n )\n if len(results) == 1:\n success = True\n igw_id = results[0]['InternetGatewayId']\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == 'DryRunOperation':\n success = True\n err_msg = e.message\n else:\n err_msg = str(e)\n\n return success, err_msg, igw_id\n\ndef find_subnet_associations(client, vpc_id, subnet_ids, check_mode=False):\n \"\"\"Find all route tables that contain the subnet_ids within vpc_id.\n Args:\n client (botocore.client.EC2): Boto3 client.\n vpc_id (str): The vpc_id of the vpc.\n subnet_ids (list): List of subnet_ids.\n\n Kwargs:\n check_mode (bool): This will pass DryRun as one of the parameters to the aws api.\n default=False\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> vpc_id = 'vpc-1234567'\n >>> subnet_ids = ['subnet-1234567', 'subnet-7654321']\n >>> find_subnet_associations(client, vpc_id, subnet_ids)\n\n Returns:\n Tuple (bool, str, list)\n \"\"\"\n err_msg = ''\n success = False\n results = list()\n params = {\n 'DryRun': check_mode,\n 'Filters': [\n {\n 'Name': 'vpc-id',\n 'Values': [vpc_id],\n },\n {\n 'Name': 'association.subnet-id',\n 'Values': subnet_ids\n }\n ]\n }\n try:\n results = client.describe_route_tables(**params)['RouteTables']\n success = True\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == 'DryRunOperation':\n success = True\n err_msg = e.message\n else:\n err_msg = str(e)\n\n return success, err_msg, results\n\ndef find_route_table(client, vpc_id, tags=None, route_table_id=None,\n check_mode=False):\n \"\"\"Find a route table in a vpc by either the route_table_id or by matching\n the exact list of tags that were passed.\n Args:\n client (botocore.client.EC2): Boto3 client.\n vpc_id (str): The vpc_id of the vpc.\n\n Kwargs:\n tags (dict): Dictionary containing the tags you want to search by.\n route_table_id (str): The route table id.\n check_mode (bool): This will pass DryRun as one of the parameters to the aws api.\n default=False\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> vpc_id = 'vpc-1234567'\n >>> tags = {'Name': 'Public-Route-Table-A'}\n >>> find_route_table(client, vpc_id, tags=tags)\n\n Returns:\n Tuple (bool, str, list)\n \"\"\"\n\n err_msg = ''\n success = False\n results = dict()\n params = {\n 'DryRun': check_mode,\n 'Filters': [\n {\n 'Name': 'vpc-id',\n 'Values': [vpc_id],\n }\n ]\n }\n if tags and not route_table_id:\n for key, val in tags.items():\n params['Filters'].append(\n {\n 'Name': 'tag:{0}'.format(key),\n 'Values': [ val ]\n }\n )\n elif route_table_id and not tags:\n params['RouteTableIds'] = [route_table_id]\n\n elif route_table_id and tags:\n #If route table id is passed with tags, use route_table_id\n params['RouteTableIds'] = [route_table_id]\n else:\n err_msg = 'Must lookup by tag or by id'\n\n try:\n results = client.describe_route_tables(**params)['RouteTables']\n if len(results) == 1:\n results = results[0]\n success = True\n elif len(results) > 1:\n err_msg = 'More than 1 route found'\n else:\n err_msg = 'No routes found'\n success = True\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == 'DryRunOperation':\n success = True\n err_msg = e.message\n else:\n err_msg = str(e)\n\n return success, err_msg, results\n\ndef tags_action(client, resource_id, tags, action='create', check_mode=False):\n \"\"\"Create or delete multiple tags from an Amazon resource id\n Args:\n client (botocore.client.EC2): Boto3 client.\n resource_id (str): The Amazon resource id.\n tags (list): List of dictionaries.\n examples.. [{Name: \"\", Values: [\"\"]}]\n\n Kwargs:\n action (str): The action to perform.\n valid actions == create and delete\n default=create\n check_mode (bool): This will pass DryRun as one of the parameters to the aws api.\n default=False\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> resource_id = 'pcx-123345678'\n >>> tags = [{'Name': 'env', 'Values': ['Development']}]\n >>> update_tags(client, resource_id, tags)\n [True, '']\n\n Returns:\n List (bool, str)\n \"\"\"\n success = False\n err_msg = \"\"\n params = {\n 'Resources': [resource_id],\n 'Tags': tags,\n 'DryRun': check_mode\n }\n try:\n if action == 'create':\n client.create_tags(**params)\n success = True\n elif action == 'delete':\n client.delete_tags(**params)\n success = True\n else:\n err_msg = 'Invalid action {0}'.format(action)\n\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == 'DryRunOperation':\n success = True\n err_msg = e.message\n else:\n err_msg = str(e)\n\n return success, err_msg\n\ndef recreate_tags_from_list(list_of_tags):\n \"\"\"Recreate tags from a list of tuples into the Amazon Tag format.\n Args:\n list_of_tags (list): List of tuples.\n\n Basic Usage:\n >>> list_of_tags = [('Env', 'Development')]\n >>> recreate_tags_from_list(list_of_tags)\n [\n {\n \"Value\": \"Development\",\n \"Key\": \"Env\"\n }\n ]\n\n Returns:\n List\n \"\"\"\n tags = list()\n i = 0\n list_of_tags = list_of_tags\n for i in range(len(list_of_tags)):\n key_name = list_of_tags[i][0]\n key_val = list_of_tags[i][1]\n tags.append(\n {\n 'Key': key_name,\n 'Value': key_val\n }\n )\n return tags\n\ndef update_tags(client, resource_id, current_tags, tags, check_mode=False):\n \"\"\"Update tags for an amazon resource.\n Args:\n resource_id (str): The Amazon resource id.\n current_tags (list): List of dictionaries.\n examples.. [{Name: \"\", Values: [\"\"]}]\n tags (list): List of dictionaries.\n examples.. [{Name: \"\", Values: [\"\"]}]\n\n Kwargs:\n check_mode (bool): This will pass DryRun as one of the parameters to the aws api.\n default=False\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> resource_id = 'pcx-123345678'\n >>> tags = [{'Name': 'env', 'Values': ['Development']}]\n >>> update_tags(client, resource_id, tags)\n [True, '']\n\n Return:\n Tuple (bool, str)\n \"\"\"\n success = False\n err_msg = ''\n if current_tags:\n current_tags_set = (\n set(\n reduce(\n lambda x, y: x + y,\n [x.items() for x in make_tags_in_proper_format(current_tags)]\n )\n )\n )\n\n new_tags_set = (\n set(\n reduce(\n lambda x, y: x + y,\n [x.items() for x in make_tags_in_proper_format(tags)]\n )\n )\n )\n tags_to_delete = list(current_tags_set.difference(new_tags_set))\n tags_to_update = list(new_tags_set.difference(current_tags_set))\n if tags_to_delete:\n tags_to_delete = recreate_tags_from_list(tags_to_delete)\n delete_success, delete_msg = (\n tags_action(\n client, resource_id, tags_to_delete, action='delete',\n check_mode=check_mode\n )\n )\n if not delete_success:\n return delete_success, delete_msg\n if tags_to_update:\n tags = recreate_tags_from_list(tags_to_update)\n else:\n return True, 'Tags do not need to be updated'\n\n if tags:\n create_success, create_msg = (\n tags_action(\n client, resource_id, tags, action='create',\n check_mode=check_mode\n )\n )\n return create_success, create_msg\n\n return success, err_msg\n\ndef vgw_action(client, route_table_id, vgw_id, action='create'):\n \"\"\"Enable or disable multiple a virtual gateway from an Amazon route table.\n Args:\n client (botocore.client.EC2): Boto3 client.\n route_table_id (str): The Amazon resource id.\n vgw_id (str): The virtual gateway id.\n\n Kwargs:\n action (str): The action to perform.\n valid actions == create and delete\n default=create\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> route_table_id = 'rtb-123345678'\n >>> vgw_id = 'vgw-1234567'\n >>> vgw_action(client, route_table_id, vgw_id, 'create')\n [True, '']\n\n Returns:\n List (bool, str)\n \"\"\"\n success = False\n err_msg = ''\n params = {\n 'GatewayId': vgw_id,\n 'RouteTableId': route_table_id,\n }\n try:\n if action == 'create':\n client.enable_vgw_route_propagation(**params)\n success = True\n elif action == 'delete':\n client.disable_vgw_route_propagation(**params)\n success = True\n else:\n err_msg = 'Invalid action {0}'.format(action)\n\n except botocore.exceptions.ClientError as e:\n err_msg = str(e)\n\n return success, err_msg\n\ndef update_vgw(client, route_table_id, current_vgws, vgw_id=None):\n \"\"\"Update the virtual gateway status on an Amazon route table.\n Args:\n client (botocore.client.EC2): Boto3 client.\n route_table_id (str): The Amazon resource id.\n current_vgws (list): List, containing enabled virtual gateways.\n vgw_id (str): The virtual gateway id you want to keep enabled.\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> route_table_id = 'rtb-123345678'\n >>> current_vgws = [{u'GatewayId': 'vgw-1234567'}]\n >>> vgw_id = 'vgw-1234567'\n >>> update_vgw(client, route_table_id, current_vgws, vgw_id)\n [True, '']\n\n Returns:\n List (bool, str)\n \"\"\"\n success = True\n err_msg = ''\n if current_vgws:\n for vgws in current_vgws:\n for vgw in vgws.values():\n if vgw != vgw_id or not vgw_id:\n if not vgw_id:\n vgw_to_delete_id = vgw\n else:\n vgw_to_delete_id = vgw_id\n disable_success, disable_msg = (\n vgw_action(\n client, route_table_id, vgw_to_delete_id, 'delete'\n )\n )\n if vgw_id and disable_success:\n enable_success, enable_msg = (\n vgw_action(client, route_table_id, vgw_id)\n )\n return enable_success, enable_msg\n else:\n return disable_success, disable_msg\n elif not current_vgws and vgw_id:\n enable_success, enable_msg = (\n vgw_action(client, route_table_id, vgw_id)\n )\n return enable_success, enable_msg\n return success, err_msg\n\ndef subnet_action(client, route_table_id, subnet_id=None, association_id=None,\n action='create', check_mode=False):\n \"\"\"Associate or Disasscoiate subnet_id from an Amazon route table.\n Args:\n client (botocore.client.EC2): Boto3 client.\n route_table_id (str): The Amazon resource id for a route table.\n\n Kwargs:\n subnet_id (str): The Amazon resource id for a subnet.\n association_id (str): The Amazon resource id for an association.\n action (str): The action to perform.\n valid actions == create and delete\n default=create\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> route_table_id = 'rtb-123345678'\n >>> subnet_id = 'subnet-1234567'\n >>> subnet_action(client, route_table_id, subnet_id, 'create')\n [True, '']\n\n Returns:\n List (bool, str)\n \"\"\"\n success = False\n err_msg = ''\n params = {\n 'DryRun': check_mode\n }\n try:\n if action == 'create':\n params['SubnetId'] = subnet_id\n params['RouteTableId'] = route_table_id\n client.associate_route_table(**params)\n success = True\n elif action == 'delete':\n params['AssociationId'] = association_id\n client.disassociate_route_table(**params)\n success = True\n else:\n err_msg = 'Invalid action {0}'.format(action)\n\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == 'DryRunOperation':\n success = True\n err_msg = e.message\n else:\n del routes_to_match[i]\n\n # NOTE: As of boto==2.38.0, the origin of a route is not available\n # (for example, whether it came from a gateway with route propagation\n # enabled). Testing for origin == 'EnableVgwRoutePropagation' is more\n # correct than checking whether the route uses a propagating VGW.\n # The current logic will leave non-propagated routes using propagating\n # VGWs in place.\n routes_to_delete = [r for r in routes_to_match\n if r.gateway_id != 'local'\n and (propagating_vgw_ids is not None\n and r.gateway_id not in propagating_vgw_ids)]\n\n changed = routes_to_delete or route_specs_to_create\n if changed:\n for route_spec in route_specs_to_create:\n try:\n vpc_conn.create_route(route_table.id,\n dry_run=check_mode,\n **route_spec)\n except EC2ResponseError as e:\n if e.error_code == 'DryRunOperation':\n pass\n\n for route in routes_to_delete:\n try:\n vpc_conn.delete_route(route_table.id,\n route.destination_cidr_block,\n dry_run=check_mode)\n except EC2ResponseError as e:\n if e.error_code == 'DryRunOperation':\n pass\n\n return {'changed': bool(changed)}\n\ndef update_subnets(client, vpc_id, route_table_id, current_subnets,\n new_subnet_ids, check_mode=False):\n \"\"\"Update the associated subnets on an Amazon route table.\n Args:\n client (botocore.client.EC2): Boto3 client.\n vpc_id (str): The Amazon resource id of the vpc.\n route_table_id (str): The Amazon resource id of the route table.\n current_subnets (list): List, containing the current subnets.\n new_subnet_ids (str): List, containing the new subnet ids you want\n associated with this route table.\n\n Kwargs:\n check_mode (bool): This will pass DryRun as one of the parameters to the aws api.\n default=False\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> vpc_id = 'vpc-1234567'\n >>> route_table_id = 'rtb-123345678'\n >>> current_subnets = [\n {\n u'SubnetId': 'subnet-1234567',\n u'RouteTableAssociationId': 'rtbassoc-1234567',\n u'Main': False,\n u'RouteTableId': 'rtb-1234567'\n }\n ]\n >>> subnet_ids = ['subnet-7654321', 'subnet-243567']\n >>> update_subnets(client, vpc_id, route_table_id, current_subnets, subnet_ids)\n [True, '']\n\n Returns:\n List (bool, str)\n \"\"\"\n current_subnet_ids = (\n map(\n lambda subnet: subnet['SubnetId'], current_subnets\n )\n )\n subnet_ids_to_add = (\n list(set(new_subnet_ids).difference(current_subnet_ids))\n )\n subnet_ids_to_remove = (\n list(set(current_subnet_ids).difference(new_subnet_ids))\n )\n association_ids_to_remove = list()\n for subnet_id in subnet_ids_to_remove:\n for subnet in current_subnets:\n subnet = convert_to_lower(subnet)\n if subnet_id == subnet['subnet_id']:\n association_ids_to_remove.append(\n subnet['route_table_association_id']\n )\n\n success, err_msg, routes = (\n find_subnet_associations(\n client, vpc_id, subnet_ids_to_add, check_mode=check_mode\n )\n )\n association_ids_to_remove_before_adding = list()\n if success:\n for route in routes:\n for association in route['Associations']:\n association_ids_to_remove_before_adding.append(\n association['RouteTableAssociationId']\n )\n for association_id in association_ids_to_remove_before_adding:\n delete_success, delete_msg = (\n subnet_action(\n client, route_table_id, association_id=association_id,\n action='delete', check_mode=check_mode\n )\n )\n if not delete_success:\n return delete_success, delete_msg\n\n for subnet_id in subnet_ids_to_add:\n create_success, create_msg = (\n subnet_action(\n client, route_table_id, subnet_id, action='create',\n check_mode=check_mode\n )\n )\n if not create_success:\n return create_success, create_msg\n\n for association_id in association_ids_to_remove:\n delete_success, delete_msg = (\n subnet_action(\n client, route_table_id, association_id=association_id,\n action='delete', check_mode=False\n )\n )\n if not delete_success:\n return delete_success, delete_msg\n\n return True, ''\n\ndef route_table_action(client, vpc_id=None, route_table_id=None,\n action='create', check_mode=False):\n \"\"\"Create or Delete an Amazon route table.\n Args:\n client (botocore.client.EC2): Boto3 client.\n\n Kwargs:\n vpc_id (str): The Amazon resource id for a vpc.\n route_table_id (str): The Amazon resource id for a route table.\n action (str): The action to perform.\n valid actions == create and delete\n default=create\n check_mode (bool): This will pass DryRun as one of the parameters to the aws api.\n default=False\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> vpc_id = 'vpc-123345678'\n >>> route_table_action(client, vpc_id, 'create')\n [True, '']\n\n Returns:\n List (bool, str)\n \"\"\"\n success = False\n err_msg = ''\n route_table = dict()\n params = {\n 'DryRun': check_mode\n }\n try:\n if action == 'create' and vpc_id:\n params['VpcId'] = vpc_id\n route_table = client.create_route_table(**params)['RouteTable']\n success = True\n elif action == 'delete' and route_table_id:\n params['RouteTableId'] = route_table_id\n client.delete_route_table(**params)\n success = True\n elif action == 'create' and not vpc_id:\n err_msg = 'Action create needs parameter vpc_id'\n elif action == 'delete' and not route_table_id:\n err_msg = 'Action delete needs parameter route_table_id'\n else:\n err_msg = 'Invalid action {0}'.format(action)\n\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == 'DryRunOperation':\n success = True\n err_msg = e.message\n else:\n err_msg = str(e)\n\n return success, err_msg, route_table\n\ndef route_action(client, route, route_table_id, action='create',\n check_mode=False):\n \"\"\"Create or Delete a route on an Amazon route table.\n Args:\n client (botocore.client.EC2): Boto3 client.\n route (dict): Dictionary, containing the necessary data for a route.\n route_table_id (str): The Amazon resource id for a route table.\n\n Kwargs:\n action (str): The action to perform.\n valid actions == create and delete\n default=create\n check_mode (bool): This will pass DryRun as one of the parameters to the aws api.\n default=False\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> route = {\n 'dest': '0.0.0.0/0',\n 'gateway_type': 'nat_gateway_id',\n 'id': 'ngw-12345678'\n }\n >>> route_table_id = 'rtb-123345678'\n >>> route_action(client, route, route_table_id, 'create')\n [True, '']\n\n Returns:\n List (bool, str)\n \"\"\"\n success = False\n err_msg = ''\n params = {\n 'DestinationCidrBlock': route['dest'],\n 'RouteTableId': route_table_id,\n 'DryRun': check_mode\n }\n if action == 'create':\n params[GATEWAY_MAP[route['gateway_type']]] = route['id']\n\n try:\n if action == 'create':\n success = client.create_route(**params)['Return']\n elif action == 'delete':\n client.delete_route(**params)\n success = True\n else:\n err_msg = 'Invalid action {0}'.format(action)\n\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == 'DryRunOperation':\n success = True\n err_msg = e.message\n else:\n err_msg = str(e)\n\n return success, err_msg\n\ndef update_route(client, route_table_id, current_routes, route_to_update,\n check_mode=False):\n \"\"\"Update the routes on an Amazon route table.\n Args:\n client (botocore.client.EC2): Boto3 client.\n route_table_id (str): The Amazon resource id of the route table.\n current_routes (list): List, containing the current routes.\n route_to_update (str): List, containing the new subnet ids you want\n associated with this route table.\n\n Kwargs:\n check_mode (bool): This will pass DryRun as one of the parameters to the aws api.\n default=False\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> vpc_id = 'vpc-1234567'\n >>> route_table_id = 'rtb-123345678'\n >>> current_routes = [\n {\n u'GatewayId': 'local',\n u'DestinationCidrBlock': '10.100.0.0/16',\n u'State': 'active',\n u'Origin': 'CreateRouteTable'\n },\n {\n u'Origin': 'CreateRoute',\n u'DestinationCidrBlock': '0.0.0.0/0',\n u'GatewayId': 'igw-1234567',\n u'State': 'active'\n }\n ]\n >>> routes_to_update = [\n {\n 'dest': '0.0.0.0/0',\n 'gateway_type': 'nat_gateway_id',\n 'id': 'nat-987654321'\n }\n ]\n >>> update_route(client, route_table_id, current_routes, routes_to_update)\n [True, '']\n\n Returns:\n List (bool, str)\n \"\"\"\n for route in current_routes:\n route = convert_to_lower(route)\n if route['origin'] != 'create_route_table' and len(current_routes) > 1:\n if route['destination_cidr_block'] == route_to_update['dest']:\n gateway_key = route_to_update['gateway_type']\n if route.has_key(gateway_key):\n return True, 'route already exists'\n else:\n delete_success, delete_msg = (\n route_action(\n client, route_to_update, route_table_id,\n 'delete', check_mode=check_mode\n )\n )\n if delete_success:\n create_success, create_msg = (\n route_action(\n client, route_to_update, route_table_id,\n 'create', check_mode=check_mode\n )\n )\n return create_success, create_msg\n else:\n return delete_success, delete_msg\n elif len(current_routes) == 1:\n create_success, create_msg = (\n route_action(\n client, route_to_update, route_table_id,\n 'create', check_mode\n )\n )\n return create_success, create_msg\n\ndef update(client, vpc_id, route_table_id, current_route_table, routes=None,\n subnets=None, tags=None, vgw_id=None, check_mode=False):\n \"\"\"Update the attributes of a route table.\n Args:\n client (botocore.client.EC2): Boto3 client.\n vpc_id (str): The Amazon resource id for a vpc.\n route_table_id (str): The Amazon resource id of the route table.\n current_routes (list): List, containing the current routes.\n\n Kwargs:\n routes (list): List, containing the necessary data for a route.\n subnets (str): List, containing the new subnet ids you want\n associated with this route table.\n tags (dict): Dictionary containing the tags you want to search by.\n vgw_id (str): The Virtual Gateway you want to enable.\n check_mode (bool): This will pass DryRun as one of the parameters to the aws api.\n default=False\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> vpc_id = 'vpc-1234567'\n >>> current_routes = [\n {\n u'GatewayId': 'local',\n u'DestinationCidrBlock': '10.100.0.0/16',\n u'State': 'active',\n u'Origin': 'CreateRouteTable'\n }\n ]\n >>> routes = [\n {\n 'dest': '0.0.0.0/0',\n 'nat_gateway_id': 'nat-12345678'\n }\n ]\n >>> subnets = ['subnet-1234567', 'subnet-7654321']\n >>> tags = {'env': 'development', 'Name': 'dev_route_table'}\n\n Returns:\n Tuple (bool, bool, str, dict)\n \"\"\"\n success = True\n err_msg = ''\n if tags:\n tags = make_tags_in_aws_format(tags)\n tag_success, tag_msg = (\n update_tags(\n client, route_table_id, current_route_table['Tags'], tags,\n check_mode=check_mode\n )\n )\n if not tag_success:\n success = False\n return tag_success, tag_msg\n\n if subnets:\n subnet_success, subnet_msg = (\n update_subnets(\n client, vpc_id, route_table_id,\n current_route_table['Associations'], subnets,\n check_mode=check_mode\n )\n )\n if not subnet_success:\n success = False\n return subnet_success, subnet_msg\n\n if routes:\n routes = route_keys(client, vpc_id, routes, check_mode)\n for route in routes:\n routes_success, routes_msg = (\n update_route(\n client, route_table_id, current_route_table['Routes'],\n route, check_mode\n )\n )\n if not routes_success:\n success = False\n return routes_success, routes_msg\n\n vgw_success, vgw_msg = (\n update_vgw(\n client, route_table_id, current_route_table['PropagatingVgws'],\n vgw_id\n )\n )\n if not vgw_success:\n success = False\n return vgw_success, vgw_msg\n\n return success, err_msg\n\ndef pre_create_route_table(client, vpc_id, routes, subnets, tags, vgw_id=None,\n route_table_id=None, check_mode=False):\n \"\"\"Find route and if it exists update it. If not return back to\n create_route_table. This should not be called directly, except by\n create_route_table.\n Args:\n client (botocore.client.EC2): Boto3 client.\n vpc_id (str): The Amazon resource id for a vpc.\n routes (list): List, containing the necessary data for a route.\n subnets (str): List, containing the new subnet ids you want\n associated with this route table.\n tags (dict): Dictionary containing the tags you want to search by.\n\n Kwargs:\n vgw_id (str): The Virtual Gateway you want to enable.\n route_table_id (str): The Amazon resource id of the route table.\n check_mode (bool): This will pass DryRun as one of the parameters to the aws api.\n default=False\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> vpc_id = 'vpc-1234567'\n >>> routes = [\n {\n 'dest': '0.0.0.0/0',\n 'nat_gateway_id': 'nat-12345678'\n }\n ]\n >>> subnets = ['subnet-1234567', 'subnet-7654321']\n >>> tags = {'env': 'development', 'Name': 'dev_route_table'}\n\n Returns:\n Tuple (bool, bool, str, dict)\n \"\"\"\n\n route_table_exist = False\n route_table = None\n success, err_msg, route_table = (\n find_route_table(client, vpc_id, tags, route_table_id, check_mode)\n )\n if route_table and success:\n route_table_exist = True\n\n if not route_table and not route_table_id:\n if tags.get('Name', None):\n tag_wth_name_only = {'Name': tags.get('Name')}\n success, err_msg, route_table = (\n find_route_table(\n client, vpc_id, tag_wth_name_only, check_mode=check_mode\n )\n )\n if route_table and success:\n route_table_exist = True\n\n if route_table_exist:\n if not route_table_id:\n route_table_id = route_table['RouteTableId']\n success, err_msg = (\n update(\n client, vpc_id, route_table_id, route_table, routes, subnets,\n tags, vgw_id, check_mode=check_mode\n )\n )\n\n if success:\n changed = True\n success, err_msg, route_table = (\n find_route_table(\n client, vpc_id, tags, route_table_id, check_mode\n )\n )\n else:\n changed = False\n\n return success, changed, err_msg, route_table\n\n else:\n return False, False, 'Route table does not exist', dict()\n\ndef create_route_table(client, vpc_id, routes, subnets, tags, vgw_id=None,\n route_table_id=None, check_mode=False):\n \"\"\"Create a new route table. If route table is found by id if not\n by tag, it will then update the existing one.\n Args:\n client (botocore.client.EC2): Boto3 client.\n vpc_id (str): The Amazon resource id for a vpc.\n routes (dict): Dictionary, containing the necessary data for a route.\n subnets (str): List, containing the new subnet ids you want\n associated with this route table.\n tags (dict): Dictionary containing the tags you want to search by.\n\n Kwargs:\n vgw_id (str): The Virtual Gateway you want to enable.\n route_table_id (str): The Amazon resource id of the route table.\n check_mode (bool): This will pass DryRun as one of the parameters to the aws api.\n default=False\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> vpc_id = 'vpc-1234567'\n >>> routes = [\n {\n 'dest': '0.0.0.0/0',\n 'nat_gateway_id': 'nat-12345678'\n }\n ]\n >>> subnets = ['subnet-1234567', 'subnet-7654321']\n >>> tags = {'env': 'development', 'Name': 'dev_route_table'}\n [ [4/967]\n true,\n true,\n \"Route table rtb-1234567 updated.\",\n {\n \"associations\": [\n {\n \"subnet_id\": \"subnet-12345667\",\n \"route_table_id\": \"rtb-1234567\",\n \"main\": false,\n \"route_table_association_id\": \"rtbassoc-1234567\"\n },\n {\n \"subnet_id\": \"subnet-78654321\",\n \"route_table_id\": \"rtb-78654321\",\n \"main\": false,\n \"route_table_association_id\": \"rtbassoc-78654321\"\n }\n ],\n \"tags\": [\n {\n \"key\": \"Name\",\n \"value\": \"dev_route_table\"\n },\n {\n \"key\": \"env\",\n \"value\": \"development\"\n }\n ],\n \"routes\": [\n {\n \"gateway_id\": \"local\",\n \"origin\": \"CreateRouteTable\",\n \"state\": \"active\",\n \"destination_cidr_block\": \"10.100.0.0/16\"\n },\n {\n \"origin\": \"CreateRoute\",\n \"state\": \"active\",\n \"nat_gateway_id\": \"nat-12345678\",\n \"destination_cidr_block\": \"0.0.0.0/0\"\n }\n ],\n \"route_table_id\": \"rtb-1234567\",\n \"vpc_id\": \"vpc-1234567\",\n \"propagating_vgws\": []\n }\n ]\n\n Returns:\n Tuple (bool, bool, str, dict)\n \"\"\"\n success, changed, err_msg, results = (\n pre_create_route_table(\n client, vpc_id, routes, subnets, tags, vgw_id,\n route_table_id, check_mode=check_mode\n )\n )\n if not success and not changed and err_msg == 'Route table does not exist':\n route_table_success, route_table_msg, route_table = (\n route_table_action(\n client, vpc_id=vpc_id, action='create', check_mode=check_mode\n )\n )\n if route_table_success:\n route_table_id = route_table['RouteTableId']\n success, changed, err_msg, results = (\n update(\n client, vpc_id, route_table_id, route_table, routes,\n subnets, tags, vgw_id, check_mode\n )\n )\n if success:\n err_msg = 'Route table {0} created.'.format(route_table_id)\n return success, changed, err_msg, convert_to_lower(results)\n\n else:\n if success and changed:\n route_table_id = results['RouteTableId']\n err_msg = 'Route table {0} updated.'.format(route_table_id)\n return success, changed, err_msg, convert_to_lower(results)\n\ndef delete_route_table(client, route_table_id, check_mode=False):\n \"\"\"Create a new route table. If route table is found by id if not\n by tag, it will then update the existing one.\n Args:\n client (botocore.client.EC2): Boto3 client.\n route_table_id (str): The Amazon resource id of the route table.\n\n Kwargs:\n check_mode (bool): This will pass DryRun as one of the parameters to the aws api.\n default=False\n\n Basic Usage:\n >>> client = boto3.client('ec2')\n >>> route_table_id = 'rtb-1234567'\n >>> delete_route_table(client, route_table_id)\n\n Returns:\n Tuple (bool, bool, str, dict)\n \"\"\"\n success = False\n changed = False\n success, err_msg, results = (\n route_table_action(\n client, route_table_id=route_table_id, action='delete'\n )\n )\n if success:\n changed = True\n err_msg = 'Route table id {0} deleted'.format(route_table_id)\n\n return success, changed, err_msg, results\n\ndef main():\n argument_spec = ec2_argument_spec()\n argument_spec.update(\n dict(\n lookup = dict(default='tag', required=False, choices=['tag', 'id']),\n propagating_vgw_ids = dict(default=None, required=False, type='list'),\n route_table_id = dict(default=None, required=False),\n routes = dict(default=None, required=False, type='list'),\n state = dict(default='present', choices=['present', 'absent']),\n subnets = dict(default=None, required=False, type='list'),\n tags = dict(default=None, required=False, type='dict', aliases=['resource_tags']),\n vpc_id = dict(default=None, required=True)\n )\n )\n module = AnsibleModule(\n argument_spec=argument_spec,\n supports_check_mode=True,\n )\n\n propagating_vgw_ids = module.params.get('propagating_vgw_ids')\n route_table_id = module.params.get('route_table_id')\n routes = module.params.get('routes')\n state = module.params.get('state')\n subnets = module.params.get('subnets')\n tags = module.params.get('tags')\n vpc_id = module.params.get('vpc_id')\n\n #In order to maintain backward compatability with the original version\n #I am leaving propagating_vgw_ids parameter as a list. Though you can\n #only have 1 virtual gateway enabled on a route table.\n if isinstance(propagating_vgw_ids, list):\n if len(propagating_vgw_ids) == 1:\n propagating_vgw_ids = propagating_vgw_ids[0]\n elif len(propagating_vgw_ids) == 0:\n propagating_vgw_ids = None\n else:\n module.fail_json(\n success=False, changed=False,\n msg='propagating_vgw_ids can only take in 1 parameter.'\n )\n\n if not HAS_BOTO3:\n module.fail_json(msg='boto3 is required.')\n\n check_mode = module.check_mode\n try:\n region, ec2_url, aws_connect_kwargs = (\n get_aws_connection_info(module, boto3=True)\n )\n client = (\n boto3_conn(\n module, conn_type='client', resource='ec2',\n region=region, endpoint=ec2_url, **aws_connect_kwargs\n )\n )\n except botocore.exceptions.ClientError as e:\n err_msg = 'Boto3 Client Error - {0}'.format(str(e.msg))\n module.fail_json(\n success=False, changed=False, result={}, msg=err_msg\n )\n\n if routes:\n routes_validated, err_msg = validate_routes(routes)\n if not routes_validated:\n module.fail_json(\n success=False, changed=False, result={}, msg=err_msg\n )\n\n if state == 'present':\n success, changed, err_msg, results = (\n create_route_table(\n client, vpc_id, routes, subnets, tags,\n propagating_vgw_ids, route_table_id, check_mode\n )\n )\n elif state == 'absent':\n if route_table_id:\n success, changed, err_msg, results = (\n delete_route_table(client, route_table_id)\n )\n else:\n success = False\n changed = False\n err_msg = 'When state == absent, you must pass a route_table_id'\n results = dict()\n\n if success:\n module.exit_json(\n success=success, changed=changed, msg=err_msg, **results\n )\n else:\n module.fail_json(\n success=success, changed=changed, msg=err_msg, result=results\n )\n\n# import module snippets\nfrom ansible.module_utils.basic import *\nfrom ansible.module_utils.ec2 import *\n\nif __name__ == '__main__':\n main()\n","repo_name":"linuxdynasty/ld-ansible-modules","sub_path":"ec2_vpc_route_table.py","file_name":"ec2_vpc_route_table.py","file_ext":"py","file_size_in_byte":52200,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"29"} +{"seq_id":"18866057320","text":"import logging\nfrom logging import exception\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException, NoSuchElementException\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as ec\nimport re\nfrom bs4 import BeautifulSoup as Bs\nimport time\nimport os\n\n# dados do zoom\nlink = 'https://ovly.adobeconnect.com/p7e5kwit0m38/'\nuser_mail = 'vanderleyy@gmail.com'\npassword = '@chevete'\n\ndef definir_navegador():\n # Definindo Browser:\n browser = int(input(\"Selecione o Navegador: (0) Chrome, (1) Firefox: \"))\n # Matando os Processos\n if browser == 0:\n os.system(\"taskkill /f /im chromedriver.exe\")\n else:\n os.system(\"taskkill /f /im geckodriver.exe\")\n if not browser:\n navegador = webdriver.Chrome('chromedriver')\n else:\n navegador = webdriver.Firefox()\n print(f'-> Navegador Selecionado: {navegador.name}')\n return navegador\n\ndef abrir_navegador(link):\n try:\n # Abrindo o navegador\n print(f'-> Site: {link}')\n navegador.get(link)\n print(f'-> Aguarde por 3 segundos...')\n time.sleep(3)\n\n # digitar o site\n print(f'-> Verificando se o site foi aberto:')\n except NoSuchElementException:\n print(f'-> ###Site não encontrado###')\n\n\ndef executar_login(navegador, link, user_mail, password):\n try:\n _ = navegador.find_element(By.ID, \"name\")\n print(f'-> Site Encontrato!')\n # Aceitar os termos do site\n print(f'-> SESSAO: {navegador.session_id}')\n\n # Digitar Senha\n campo_email = navegador.find_element(By.ID, \"name\")\n campo_email.send_keys(user_mail)\n campo_senha = navegador.find_element(By.ID, \"pwd\")\n campo_senha.send_keys(password)\n campo_senha.send_keys(Keys.ENTER)\n\n except NoSuchElementException:\n print(f'-> ###Site não encontrado###')\n\ndef site_correto(navegador, link):\n try:\n _ = navegador.find_element(By.ID, \"name\")\n return True\n except NoSuchElementException:\n return False\n print(f'Elemento não encontrado')\n\ndef executar_player():\n try:\n time.sleep(15)\n botao_tocar = navegador.find_element(By.XPATH, \"//iframe[@id='html-meeting-frame']\")\n print(f'-> Site Encontrato!')\n print(f'-> Executando o Player')\n botao_tocar.click()\n\n except NoSuchElementException:\n print(\"-> Erro\")\n\ndef criando_download():\n\n # verifique se o chat carregou\n print(f'-> Aguarde o Chat Ser Carregado - 15 segundos')\n time.sleep(10)\n print(f'-> Continuando.....')\n delay = 10\n\n try:\n elements = WebDriverWait(navegador, delay).until(ec.visibility_of_all_elements_located((By.XPATH, \"/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[4]/div[1]/div[1]/div[1]/div[1]/h2[1]\")))\n print(\"-> Elemento encontrado!\")\n for element in elements:\n print(element.get_attribute(\"innerHTML\"))\n except Exception as e:\n print(e)\n\n\n # salvar codigo-fonte\n pagina = navegador.page_source\n parsed = Bs(pagina)\n\n # procure pelo link do video, no player\n tag_link = parsed.find(\"div\", attrs={\"class\": \"player-view\"})\n # separa o link por regex\n link = re.search('src=\\\"(http.+?)\\\" ', str(tag_link)).group(1)\n\n # altere o html fonte da pagina usando JS\n # troque o titulo do chat por um link de Download\n\n navegador.execute_script(\n \"\"\"document.querySelector(\"h2[class='title']\").innerHTML=\"Pimba!\";\"\"\")\n action = ActionChains(navegador)\n pimba = navegador.find_element(By.XPATH, '/html/body/div/section/div/div[3]/div[2]/div/div/h2')\n\n # depois desse comando o usuário precisa clicar em salvar como, selecionar a pasta e escolher o nome do arquivo\n action.context_click(pimba).perform()\n\n\nif __name__ == \"__main__\":\n navegador = definir_navegador()\n abrir_navegador(link)\n if site_correto(navegador, link):\n executar_login(navegador, link, user_mail, password)\n executar_player()\n criando_download()","repo_name":"cleitoncsl/conversor_csv","sub_path":"ZOOM/adobe.py","file_name":"adobe.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"12906556074","text":"import datetime\nimport random\nimport string\nfrom typing import Any\n\nimport ujson\n\n\ndef random_str(length=10):\n all_str = string.digits + string.ascii_lowercase + string.ascii_uppercase\n return ''.join(random.sample(all_str, length))\n\n\ndef is_chinese_char(c):\n \"\"\"判断一个 unicode 字符是否是汉字\"\"\"\n return '\\u4e00' <= c <= '\\u9fa5'\n\n\ndef is_number_char(c):\n \"\"\"判断一个 unicode 字符是否是数字\"\"\"\n return '\\u0030' <= c <= '\\u0039'\n\n\ndef is_alphabet_char(c):\n \"\"\"判断一个 unicode 字符是否是英文字母\"\"\"\n return '\\u0041' <= c <= '\\u005a' or '\\u0061' <= c <= '\\u007a'\n\n\ndef is_legal_char_for_user_name(c):\n \"\"\"可用于用户名的字符\"\"\"\n return is_chinese_char(c) or is_number_char(c) or is_alphabet_char(c) or c in ('-', '_')\n\n\ndef has_illegal_txt_for_user_name(s):\n '''是否包含不可用于用户名的字符'''\n for c in s:\n if not is_legal_char_for_user_name(c):\n return True\n return False\n\n\ndef filter_illegal_txt_for_user_name(s):\n '''过滤掉不可用于用户名的字符'''\n cs = [c for c in s if is_legal_char_for_user_name(c)]\n return ''.join(cs)\n\n\ndef humanize_time(date: Any) -> str:\n \"\"\" https://stackoverflow.com/questions/1551382/user-friendly-time-format-in-python \"\"\"\n\n now = datetime.datetime.now()\n if type(date) is int:\n diff = now - datetime.datetime.fromtimestamp(date)\n\n elif isinstance(date, datetime.datetime):\n diff = now - date\n\n else:\n return date\n\n second_diff = diff.seconds\n day_diff = diff.days\n\n if day_diff < 0:\n return date\n\n if day_diff == 0 or day_diff == -1:\n if second_diff < 10:\n return \"刚刚\"\n if second_diff < 60:\n return f\"{int(second_diff)}秒前\"\n if second_diff < 120:\n return \"一分钟前\"\n if second_diff < 3600:\n return f\"{int(second_diff / 60)}分钟前\"\n if second_diff < 7200:\n return \"一小时前\"\n if second_diff < 86400:\n return f\"{int(second_diff / 3600)}小时前\"\n\n if day_diff == 1:\n return \"昨天\"\n if day_diff < 7:\n return f\"{day_diff}天前\"\n if day_diff < 31:\n return f\"{int(day_diff / 7)}个星期前\"\n if day_diff < 365:\n return f\"{int(day_diff / 30)}个月前\"\n return f\"{int(day_diff / 365)}年前\"\n\n\ndef json_dumps(data: Any, *args, **kw) -> str:\n return ujson.dumps(data, *args, **kw)\n\n\ndef json_loads(data: str, *args, **kw) -> Any:\n return ujson.loads(data, *args, **kw)\n\n\n","repo_name":"tonghs/pandora","sub_path":"pandora/core/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"4228968464","text":"class Passport:\n \"\"\" Модель паспортные данные заёмщика \"\"\"\n\n def __init__(\n self,\n series=None,\n number=None,\n issue_date=None,\n issuer_code=None,\n issuer=None\n ):\n self.series = series\n self.number = number\n self.issue_date = issue_date\n self.issuer_code = issuer_code\n self.issuer = issuer\n\n def __repr__(self):\n return \"<%s instance at %s>\" % (self.__class__.__name__, id(self))\n\n def __str__(self):\n result = f\"Паспорт:\\n\"\n result += f\" Серия/номер: {self.series} {self.number}\\n\"\n result += f\" Выдан: {self.issue_date} {self.issue_date}\\n\"\n result += f\" Код подразделения: {self.issuer_code}\\n\"\n\n return result\n","repo_name":"marinabel1/automation-master","sub_path":"borrow/newbie/model/Passport.py","file_name":"Passport.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26477748574","text":"# -*- coding: utf-8 -*-\r\n\r\nimport sys\r\n\r\n\r\ndef silnia(n):\r\n if n == 0 or n == 1:\r\n return 1\r\n else:\r\n return n * silnia(n - 1)\r\n \r\n\r\nif __name__ == '__main__': # to sie wykonuje tylko kieyd nasz plik jest uruchamiany bezposrednio\r\n print(silnia(int(sys.argv[1]))) # liczy silnie dla podanego przy wywolaniu komendy z argumentem\r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n ","repo_name":"MikolajKasprzyk/Python_A_do_Z","sub_path":"08_wbudowane_pakiety/silnia.py","file_name":"silnia.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3692792377","text":"\nfrom prism_api import get_vms, change_power_state, clone_vm, delete_vm\nfrom cli import log, get_credentials, get_operation, print_vms, select_vm_clone, select_vm, select_vm_delete\nfrom config import Config\n\n\ndef main():\n\n log(Config.APP_TITLE, color='blue', figlet=True)\n log(Config.WELCOME_MSG, color='green')\n cred = get_credentials()\n vms = get_vms(cred)\n\n while True:\n selection = get_operation()\n\n if selection['operation'] == 'list':\n vms = get_vms(cred)\n print_vms(vms)\n elif selection['operation'] == 'power':\n vm_power = select_vm(vms)\n change_power_state(cred, vm_power['uuid'])\n elif selection['operation'] == 'delete':\n vm_delete = select_vm_delete(vms)\n if vm_delete['confirm']:\n delete_vm(cred, vm_delete['uuid'])\n elif selection['operation'] == 'clone':\n vm_clone = select_vm_clone(vms)\n clone_vm(cred, vm_clone['uuid'], int(vm_clone['count']))\n elif selection['operation'] == 'exit':\n exit(0)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"halsayed/oner-cli","sub_path":"oner-cli.py","file_name":"oner-cli.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"24463734886","text":"#\n# @lc app=leetcode.cn id=2023 lang=python3\n#\n# [2023] 连接后等于目标字符串的字符串对\n#\n# https://leetcode-cn.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/description/\n#\n# algorithms\n# Medium (74.90%)\n# Likes: 4\n# Dislikes: 0\n# Total Accepted: 3.2K\n# Total Submissions: 4.2K\n# Testcase Example: '[\"777\",\"7\",\"77\",\"77\"]\\n\"7777\"'\n#\n# 给你一个 数字 字符串数组 nums 和一个 数字 字符串 target ,请你返回 nums[i] + nums[j] (两个字符串连接)结果等于\n# target 的下标 (i, j) (需满足 i != j)的数目。\n# \n# \n# \n# 示例 1:\n# \n# 输入:nums = [\"777\",\"7\",\"77\",\"77\"], target = \"7777\"\n# 输出:4\n# 解释:符合要求的下标对包括:\n# - (0, 1):\"777\" + \"7\"\n# - (1, 0):\"7\" + \"777\"\n# - (2, 3):\"77\" + \"77\"\n# - (3, 2):\"77\" + \"77\"\n# \n# \n# 示例 2:\n# \n# 输入:nums = [\"123\",\"4\",\"12\",\"34\"], target = \"1234\"\n# 输出:2\n# 解释:符合要求的下标对包括\n# - (0, 1):\"123\" + \"4\"\n# - (2, 3):\"12\" + \"34\"\n# \n# \n# 示例 3:\n# \n# 输入:nums = [\"1\",\"1\",\"1\"], target = \"11\"\n# 输出:6\n# 解释:符合要求的下标对包括\n# - (0, 1):\"1\" + \"1\"\n# - (1, 0):\"1\" + \"1\"\n# - (0, 2):\"1\" + \"1\"\n# - (2, 0):\"1\" + \"1\"\n# - (1, 2):\"1\" + \"1\"\n# - (2, 1):\"1\" + \"1\"\n# \n# \n# \n# \n# 提示:\n# \n# \n# 2 <= nums.length <= 100\n# 1 <= nums[i].length <= 100\n# 2 <= target.length <= 100\n# nums[i] 和 target 只包含数字。\n# nums[i] 和 target 不含有任何前导 0 。\n# \n# \n#\n\n# @lc code=start\nfrom collections import Counter\n\n\nclass Solution:\n @staticmethod\n def string_sub(a: str, b: str) -> str:\n if len(a) <= len(b):\n return ''\n\n if a[:len(b)] != b:\n return ''\n return a[len(b):]\n\n def numOfPairs(self, nums: list[str], target: str) -> int:\n counter = Counter(nums)\n result = 0\n\n keys = counter.keys()\n for n in keys:\n sub_result = Solution.string_sub(target, n)\n if not sub_result:\n continue\n\n if sub_result == n:\n result += counter[n] * (counter[n] - 1)\n else:\n result += counter[sub_result] * counter[n]\n\n return result\n# @lc code=end\n\ns = Solution()\nprint(s.numOfPairs(nums = [\"777\",\"7\",\"77\",\"77\"], target = \"7777\"))\nprint(s.numOfPairs(nums = [\"123\",\"4\",\"12\",\"34\"], target = \"1234\"))\nprint(s.numOfPairs(nums = [\"1\",\"1\",\"1\"], target = \"11\"))\n","repo_name":"SR2k/leetcode","sub_path":"first-round/2023.连接后等于目标字符串的字符串对.py","file_name":"2023.连接后等于目标字符串的字符串对.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"27960909821","text":"\"\"\"\r\n\r\nWrite an expression which returns True if and only if 'pupper'\r\nis in the list of dogs, and 'minion' is an element of the cats list.\r\n\"\"\"\r\ndogs = cats = []\r\n# this is what you need:\r\n'pupper' in dogs and 'minion' in cats\r\n\r\n\"\"\"\r\nWrite an expression that returns True if and only if a\r\nstring test_string contains only uppercase or lowercase letters.\r\n\"\"\"\r\ntest_string = ''\r\n# this is what you need:\r\ntest_string == test_string.upper() or test_string == test_string.lower()\r\n\r\n\"\"\"\r\nWrite an expression that returns True if and only if birds is an\r\nempty list and either password (a string) is \"password1\" or \"asdf1234\".\r\n\"\"\"\r\nbirds = []\r\npassword = 'asdf1234'\r\nnot birds and (password == \"password1\" or password == 'asdf1234')\r\n# len(birds) == 0 or birds == []\r\n\r\n\"\"\"\r\nplanets = {\"Mercury\": 0.24, \"Venus\": 0.615, \"Earth\": 1, \"Mars\": 1.881}\r\n\r\nprint( planets[\"Venus\"] )\r\n\r\nanswer:\r\n 0.615\r\n\r\nprint( planets[\"Earth\"] + planets[\"Mars\"] )\r\n\r\n1 + 1.881 = 2.881\r\nanswer:\r\n 2.881\r\n\r\nprint( planets.get(\"Jupiter\", 0))\r\n\r\nanswer:\r\n 0\r\n\r\n\r\nplanets[\"Jupiter\"] = 11.862\r\nprint(planets)\r\n\r\n{\"Mercury\": 0.24, \"Venus\": 0.615, \"Earth\": 1,\r\n \"Mars\": 1.881, \"Jupiter\": 11.862}\r\n\r\nprint(planets[\"Neptune\"])\r\n\r\nanswer:\r\n KeyError\r\n\r\n\r\nConvert the decimal number 15\r\n 15 odd => 7 odd => 3 odd => 1 odd\r\n 1111\r\n \tto binary: \t\t0b1111\r\n \tto hexadecimal:\t0xF\r\n\r\n\r\nConvert the decimal number 241\r\n \tto binary: \t0b 1111 0001\r\n \tto hexadecimal:\t0xF1\r\n\r\n 241 odd => 120 even => 60 even => 30 even => 15 (i know this one)\r\n 1111 0001\r\n <----\r\nConvert the binary number 0011 1101\r\n \tto decimal: 13 + 16 + 32 = 61\r\n \tto hexadecimal:\t3d\r\n \t 3 * 16 + 13\r\n\r\n\r\nConvert the binary number 1010 1111\r\n\tto decimal: \t 10 * 16 + 15 = 1 + 2 + 4 + 8 + 32 + 128 = 175\r\n \tto hexadecimal:\t AF\r\n\r\nbin hex\r\n0000 0 0100 4 1000 8 1100 C\r\n0001 1 0101 5 1001 9 1101 D\r\n0010 2 0110 6 1010 A 1110 E\r\n0011 3 0111 7 1011 B 1111 F\r\n\r\nConvert the hexadecimal number 40DE59FA\r\n \tto binary: 0100 0000 1101 1110 0101 1001 1111 1010\r\n(Make sure to leave space between each group of four!)\r\n\"\"\"\r\n\r\nprint(\"Have\\\\a\\ngreat\\\\\\n\\tSummer\\\\\")\r\n\"\"\"\r\nHave\\a\r\ngreat\\\r\n Summer\\\r\n\"\"\"\r\nprint('\\\\\\\\\\\\\\\\\\\\')\r\n\r\n\"\"\"\r\n Answer: 15\r\n Reason: ints are immutable pass by value, not modified\r\n \r\n Other version of the question replaces\r\n count +=1 with count.append(1)\r\n and count = 15 with count = []\r\n\"\"\"\r\n\r\n\r\ndef increment_count(count):\r\n count += 1\r\n\r\n\r\nif __name__ == \"__main__\":\r\n count = 15\r\n increment_count(count)\r\n increment_count(count)\r\n print(count)\r\n\r\na_var = 'hello'\r\nb_var = 4\r\nif a_var or b_var == 'hello': # a_var is true, so the or executes\r\n print('think about order of operations') # this happens\r\nelse:\r\n print('b_var is hello right?')\r\n\r\n\r\ndef count_down(n):\r\n \"\"\"\r\n count_down(5) = 5 + count_down(4) ==> prints 5\r\n count_down(4) = 4 + count_down(3) ==> prints 4\r\n count_down(3) = 3 + count_down(2) ==> prints 3\r\n count_down(2) = 2 + count_down(1) ==> prints 2\r\n count_down(1) = 1 + count_down(0) ==> prints 1\r\n count_down(0) = 0 ==> prints Surprise!\r\n \"\"\"\r\n if n == 0:\r\n print('Surprise!')\r\n return 0\r\n else:\r\n print(n)\r\n return n + count_down(n - 1)\r\n\r\n\r\n# if there's a print statement, then 15 gets printed (should have had that on the exam)\r\ncount_down(5)\r\n\r\nthe_matrix = [[4, 3, 9], [7, 2, 8], [1, 5, 10]]\r\nprint(the_matrix[1][1]) # 2\r\nprint(the_matrix[0][2]) # 9\r\nprint(the_matrix[2][1]) # 5\r\n\r\nprint('\\n\\n')\r\n\r\nmy_int = 32\r\nwhile my_int:\r\n print(my_int)\r\n my_int //= 5\r\n\r\nprint('\\n\\n')\r\nthe_string = 'abcabcabc'\r\nfor i in range(len(the_string)):\r\n if the_string[i: i + 3] == 'abc':\r\n print(i)\r\n\r\n# invalid slices produce empty strings\r\nmy_string = 'asdfasfdasfdasdf'\r\nprint(my_string[7:4], 'did i print?')\r\n\r\n\r\na_list = []\r\nfor i in range(2, 15, 3):\r\n a_list.append(i)\r\n\r\nprint(a_list)\r\nprint(list(range(2, 15, 3)))\r\n\r\n\r\n\"\"\"\r\n\r\ndef find_matches(my_grid):\r\n # my_grid is a 2-d list, this function should print any\r\n # symbol which is found more than once in the grid\r\n elements = {}\r\n for i in range(my_grid): # range(len(my_grid))\r\n for j in range(len(my_grid)): # range(len(my_grid[i]))\r\n the_element = my_grid[i] # need to add my_grid[i][j]\r\n if the_element in elements # need the colon:\r\n the_element += 1 # elements[the_element] += 1\r\n elif: # else:\r\n elements[the_element] = 1 # this is right... wow\r\n for elem in elements:\r\n if elem >= 1: # elements[elem] > 1\r\n print elem, 'has matches' # add parentheses\r\n\r\nif __name__ == __main__:\r\n find_matches([['a', 'a', 'b'], ['c', 'a', 'b'], ['d', 'x', 'g']])\r\n\r\n\r\n\r\nWrite a function called a_distance which takes a string message\r\n and calculates the minimum \"distance\" between two a's.\r\n\r\na_distance(\"abba\") will return 3 since that is the\r\n difference in positions.\r\na_distance(\"abbbbbabbbabbbbbbabbbaba\") will return 2\r\n because the last a's are only two apart.\r\na_distance(\"abcdbazzzza\") will return 5 since the\r\n a's are 5 characters apart.\r\n\"\"\"\r\n\r\ndef a_distance(message):\r\n prev_index = -1\r\n min_distance = len(message) + 1\r\n for i in range(len(message)):\r\n if message[i] == 'a':\r\n if prev_index == -1:\r\n prev_index = i\r\n else:\r\n if i - prev_index < min_distance:\r\n min_distance = i - prev_index\r\n prev_index = i\r\n \r\n return min_distance\r\n\r\n\r\ndef a_distance_two(message):\r\n prev_index = -1\r\n min_distance = len(message) + 1\r\n for i in range(len(message)):\r\n if message[i] == 'a' and prev_index == -1:\r\n prev_index = i\r\n elif message[i] == 'a' and i - prev_index < min_distance:\r\n min_distance = i - prev_index\r\n prev_index = i\r\n elif message[i] == 'a':\r\n prev_index = i\r\n \r\n return min_distance\r\n\r\n\r\ndef a_distance_three(message):\r\n indices = []\r\n for i in range(len(message)):\r\n if message[i] == 'a':\r\n indices.append(i)\r\n \r\n min_dist = len(message) + 1\r\n for j in range(len(indices) - 1):\r\n if indices[j + 1] - indices[j] < min_dist:\r\n min_dist = indices[j + 1] - indices[j]\r\n \r\n return min_dist\r\n\r\n\r\n\"\"\"\r\nAssume that the_list is a one dimensional list.\r\nWrite a function called force_sort which will take a\r\nlist and return a new list with only the elements that\r\nwere in sorted order. For example if we would \"force sort\"\r\n[1, 2, 8, 4, 5] then we would get [1, 2, 8] since those are\r\n in order. If we force sorted [1, 2, 3, 8, 4, 5, 10, 12] we\r\n would get [1, 2, 3, 4, 8, 10, 12] because they are also in order.\r\n You don't have to try to make the longest sorted list,\r\n just produce a sorted list starting with the first element in the\r\n list passed as an argument.\r\n\r\n\tforce_sort([5, 4, 3, 2, 1]) returns [5]\r\n\tforce_sort([1, 2, 4, 3, 6, 5, 10, 9]) returns [1, 2, 4, 6, 10]\r\n\r\n\"\"\"\r\n\r\ndef force_sort(a_list):\r\n if not a_list:\r\n return []\r\n the_new_list = [a_list[0]]\r\n current = a_list[0]\r\n for i in range(1, len(a_list)):\r\n if a_list[i] >= current:\r\n the_new_list.append(a_list[i])\r\n current = a_list[i]\r\n \r\n return the_new_list\r\n ","repo_name":"UMBC-CMSC-Hamilton/cmsc201fall23","sub_path":"final_review_1pm.py","file_name":"final_review_1pm.py","file_ext":"py","file_size_in_byte":7482,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"23745475292","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n # HOW TO TRAVERSE A BINARY TREE?\n\n ###############################\n ###### DFS RECURSIVE WAY ######\n ###############################\n\n # Pre-order traversal\n def printPreOrder(self, root):\n\n if root == None:\n return 0\n else:\n print(root.val)\n self.printPreOrder(root.left)\n self.printPreOrder(root.right)\n\n\n # Post-order traversal\n def printPostOrder(self, root):\n\n if root == None:\n return 0\n else:\n \n self.printPostOrder(root.left)\n self.printPostOrder(root.right)\n print(root.val)\n\n # In-order traversal\n def printInOrder(self, root):\n\n if root == None:\n return 0\n else:\n \n self.printInOrder(root.left)\n print(root.val)\n self.printInOrder(root.right)\n\n # Breadth-First Search (BFS) \n\n\n ###############################\n ###### BFS ITERATIVE WAY ######\n ###############################\n\n # Level Order \n def BFS(self, root):\n if root == None:\n return 0\n\n else:\n queue = list()\n\n # First of all, we put our root into the queue\n queue.append(root)\n\n # Now we start the algorithm\n\n while len(queue) != 0:\n # Remember, in queues we respect FIFO, so we remove the first element in\n node = queue.pop(0)\n\n print(node.val)\n\n # If we have a left child, we enqueue it \n if node.left != None:\n queue.append(node.left)\n\n # If we have a right child, we enqueue it \n if node.right != None:\n queue.append(node.right)\n\n\n ###############################\n ###### DFS ITERATIVE WAY ######\n ###############################\n\n\n \n # Pre order traversal\n def DFS(self, root):\n if root == None:\n return 0\n\n else:\n stack = list()\n\n # First of all, we put our root into a stack\n stack.append(root)\n\n # Now we start the algorithm\n\n while len(stack) != 0:\n # Remember, in queues we respect FIFO, so we remove the first element in\n node = stack.pop()\n\n print(node.val) \n\n # If we have a right child, we enqueue it \n if node.right != None:\n stack.append(node.right)\n\n # If we have a left child, we enqueue it \n if node.left != None:\n stack.append(node.left)\n\n\n\nif __name__ == \"__main__\":\n\n # 1\n # 2 3\n # 4 5\n\n root = TreeNode(1)\n root.left = TreeNode(2)\n root.right = TreeNode(3)\n root.left.left = TreeNode(4)\n root.left.right = TreeNode(5)\n\n root.printPreOrder(root)\n","repo_name":"chamox/tech-mentorship","sub_path":"module_2/binary_trees/bt_traversals.py","file_name":"bt_traversals.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"9036738142","text":"from django.db import models\nfrom django.db.models import Q\nfrom django.utils import timezone\nfrom django.utils.html import conditional_escape\nfrom ckeditor.fields import RichTextField\nfrom ckeditor_uploader.fields import RichTextUploadingField\n\n\nclass PostManager(models.Manager):\n\n def published(self):\n now = timezone.now()\n return self.filter(Q(publish_date__lte=now) | Q(publish_date=None)).order_by(\"-publish_date\")\n\n\nclass ItemManager(models.Manager):\n\n def available(self):\n return self.all()\n\n\nclass Tag(models.Model):\n\n name = models.SlugField(\n max_length=32,\n db_index=True,\n unique=True,\n help_text='Tag name'\n )\n\n def __str__(self):\n return self.name\n\n\nclass Project(models.Model):\n\n name = models.SlugField(\n max_length=32,\n db_index=True,\n unique=True,\n help_text='Project internal name'\n )\n title = models.CharField(\n max_length=255,\n help_text='Project title'\n )\n description = models.TextField(\n help_text='Project description'\n )\n\n def __str__(self):\n return self.name\n\n\nclass Post(models.Model):\n\n objects = PostManager()\n\n created = models.DateTimeField(\n auto_now_add=True,\n help_text='Date and time the post was created'\n )\n updated = models.DateTimeField(\n auto_now=True,\n help_text='Date and time the post was last updated',\n )\n publish_date = models.DateTimeField(\n blank=True,\n null=True,\n help_text='(optional) If set, when to publish the post'\n )\n title = models.CharField(\n max_length=255,\n help_text='Title of the post'\n )\n slug = models.SlugField(\n help_text='Slug of the post',\n db_index=True,\n unique=True,\n null=True,\n blank=True,\n )\n preview_upload = models.ImageField(\n help_text='Preview image',\n blank=True,\n )\n preview_image = models.CharField(\n max_length=255,\n help_text='URL of the preview image (internal)',\n blank=True,\n )\n preview_image_external = models.CharField(\n max_length=255,\n help_text='URL of the preview image (external sites)',\n blank=True,\n )\n preview_text = models.TextField(\n help_text='Short preview text',\n )\n content = RichTextUploadingField(\n help_text='Content of the post'\n )\n tags = models.ManyToManyField(\n Tag,\n help_text='Tags'\n )\n\n def __str__(self):\n return self.title\n\n\nclass Item(models.Model):\n\n objects = ItemManager()\n\n title = models.CharField(\n max_length=255,\n help_text='Name of the item'\n )\n sku = models.CharField(\n max_length=255,\n unique=True,\n help_text='SKU of the item'\n )\n slug = models.SlugField(\n help_text='Slug of the item',\n db_index=True,\n unique=True,\n null=True,\n blank=True,\n )\n preview_upload = models.ImageField(\n help_text='Preview image',\n blank=True,\n )\n preview_image = models.TextField(\n help_text='URL of the preview image',\n blank=True,\n )\n preview_image_external = models.TextField(\n help_text='URL of the preview image (external sites)',\n blank=True,\n )\n preview_text = models.TextField(\n help_text='Short preview text',\n )\n preview_docs = models.TextField(\n\t\tblank=True,\n help_text='Preview datasheet link',\n )\n description = RichTextUploadingField(\n help_text='Long item description'\n )\n specifications = RichTextUploadingField(\n help_text='Technical specifications (specifications tab)'\n )\n docs = RichTextUploadingField(\n blank=True,\n help_text='Links to datasheets and stuff (docs tab)'\n )\n info = RichTextUploadingField(\n blank=True,\n help_text='Additional information about item (info tab)'\n )\n project = models.ManyToManyField(\n Project,\n help_text='Project'\n )\n\n def __str__(self):\n return self.title\n\n\n\nclass Feedback(models.Model):\n name = models.CharField(\n max_length=255,\n help_text='User name'\n )\n code = models.CharField(\n max_length=255,\n\t\tblank=True,\n help_text='Internal code'\n\t)\n created = models.DateTimeField(\n auto_now_add=True,\n help_text='Date feedback was submitted'\n )\n email = models.CharField(\n max_length=255,\n help_text='User email'\n )\n text = models.TextField(\n help_text='Feedback text'\n )\n\n def __str__(self):\n return 'Feedback from ' + self.email","repo_name":"cansat-ptl/yktaero-web","sub_path":"yktaero/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"43307512991","text":"\"\"\" Create by Ken at 2020 May 02 \"\"\"\nimport os\nimport argparse\nimport numpy as np\nimport time\n\nfrom tqdm import tqdm\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nimport tensorflow as tf\nfrom pymongo import MongoClient\n\nfrom model.han_sparsemax_model import create_model\nfrom utils.string_utils import process_text\nfrom evaluating.ndcg import n_dcg\n\ntf.get_logger().setLevel('ERROR')\n\narg_parser = argparse.ArgumentParser(description='Encode articles')\narg_parser.add_argument(\n '--db_host',\n type=str,\n default='localhost',\n help='Mongo DB host'\n)\narg_parser.add_argument(\n '--db_port',\n type=int,\n default=5007,\n help='Mongo DB port'\n)\narg_parser.add_argument(\n '--db_name',\n type=str,\n default='legal_doc',\n help='DB name'\n)\narg_parser.add_argument(\n '--exp_db_name',\n type=str,\n default='exp_legal_doc',\n help='MongoDB output DB name'\n)\narg_parser.add_argument(\n '--db_test_collection',\n type=str,\n default='test_ground_truth',\n help='Test ground truth collection name'\n)\narg_parser.add_argument(\n '--db_encoded_article_collection',\n type=str,\n default='encoded_articles',\n help='Test encoded article collection name'\n)\narg_parser.add_argument(\n '--es_output_file',\n type=str,\n default='data/bm25_article_recall_5000_unlimited_output.csv',\n help='Path to ES output file'\n)\narg_parser.add_argument(\n '--es_output_limit',\n type=int,\n help='Limit number of results from ES output file'\n)\narg_parser.add_argument(\n '--exp_name',\n type=str,\n help='Experiment name'\n)\narg_parser.add_argument(\n '--dict_file',\n type=str,\n default='data/dict.txt',\n help='Path to dict file'\n)\n\n\ndef pad_query(vec, max_query_len):\n vec = vec[:max_query_len]\n if len(vec) < max_query_len:\n vec.extend([0] * (max_query_len - len(vec)))\n return vec\n\n\ndef parse_dict_file():\n lines = open(args.dict_file, 'r').readlines()\n dict_ = {}\n for line in lines:\n tokens = line.split(',')\n id_ = int(tokens[0].strip())\n term = tokens[1].strip()\n dict_[term] = id_\n return dict_\n\n\ndef parse_experiment_file():\n experiment_data = {}\n lines = open(es_output_file, 'r').readlines()[:-1]\n for line in lines:\n parts = line.strip().split(',')\n query_id = parts[0]\n exp_out = parts[2].strip().split('|')[:es_output_limit]\n experiment_data[query_id] = exp_out\n return experiment_data\n\n\ndef run():\n _, query_encoder, _ = create_model()\n print('Loading query encider weights from {}...'.format(query_encoder_weights_path))\n query_encoder.load_weights(query_encoder_weights_path)\n\n mongo_client = MongoClient(db_host, db_port)\n exp_db = mongo_client[args.exp_db_name]\n test_collection = exp_db[db_test_collection]\n encoded_article_collection = exp_db[db_encoded_article_collection]\n\n encoded_articles = {}\n print('Loading encoded articles from {}...'.format(db_encoded_article_collection))\n for record in tqdm(list(encoded_article_collection.find())):\n doc_code = record['so_hieu_vb'].lower()\n article_name = record['ten_dieu'].lower()\n encoded_articles[f'{article_name}@{doc_code}'] = record['vector']\n\n examples = list(test_collection.find())\n os.makedirs('output', exist_ok=True)\n output = open('output/{}_es_limit_{}_recall_20.csv'.format(exp_name, es_output_limit), 'w')\n total_recall = 0\n total_n_dcg = 0\n ignore_examples = 0 # Number of examples don't contain article ground truth\n\n start_time = time.time()\n for example in tqdm(examples):\n ground_truth = []\n for document in example[\"documents\"]:\n doc_code = document['code'].lower()\n if 'articles' in document:\n for article in document['articles']:\n article_name = article['name'].lower()\n ground_truth.append('{}@{}'.format(article_name, doc_code))\n\n es_res = es_output[str(example['_id'])]\n articles = []\n articles_rep = []\n for item in es_res:\n if item not in encoded_articles:\n print(f'cannot found {item}')\n continue\n article = encoded_articles[item]\n if article is not None:\n articles.append(item)\n articles_rep.append(article)\n articles_rep = np.array(articles_rep)\n\n query = process_text(example[\"query\"], text_to_seq_dict)\n query = pad_query(query, 40)\n query = np.array(query, dtype='int32')\n query = query[np.newaxis, :]\n query_rep = query_encoder(query)\n\n group_size = len(articles_rep)\n query_rep = tf.tile(query_rep, [group_size, 1])\n scores = tf.keras.layers.dot([query_rep, articles_rep], axes=-1)\n scores = tf.reshape(scores, (group_size,))\n\n scores = tf.keras.backend.eval(scores)\n articles_scores = []\n for i in range(len(articles)):\n articles_scores.append({\n 'article': articles[i],\n 'score': scores[i].item()\n })\n\n articles_scores = sorted(articles_scores, key=lambda x: x['score'], reverse=True)\n predicted_articles = [article_score['article'] for article_score in articles_scores[:20]]\n scores = [str(article_score['score']) for article_score in articles_scores[:20]]\n intersection = set(ground_truth) & set(predicted_articles)\n if len(ground_truth) == 0:\n recall = 0\n n_dcg_score = 0\n ignore_examples += 1\n else:\n recall = len(intersection) / len(ground_truth)\n n_dcg_score = n_dcg(predicted_articles, ground_truth)\n\n total_recall += recall\n total_n_dcg += n_dcg_score\n output.write(\"{},{},{},{},{}\\n\".format(example[\"_id\"], recall, n_dcg_score, '|'.join(predicted_articles),\n ','.join(scores)))\n\n print('time: ', time.time() - start_time)\n output.write(\"Average recall: {},Average nDCG: {}\".format(\n total_recall / (len(examples) - ignore_examples),\n total_n_dcg / (len(examples) - ignore_examples))\n )\n output.close()\n\n\nif __name__ == '__main__':\n args = arg_parser.parse_args()\n exp_name = args.exp_name\n db_host = args.db_host\n db_port = args.db_port\n db_name = args.db_name\n db_test_collection = exp_name + '_' + args.db_test_collection\n db_encoded_article_collection = exp_name + '_' + args.db_encoded_article_collection\n query_encoder_weights_path = \"trained_models/{}/query_encoder.h5\".format(exp_name)\n es_output_file = args.es_output_file\n es_output_limit = args.es_output_limit\n print(f'>>> es_output_file: {es_output_file}')\n print(f'>>> es_output_limit: {es_output_limit}')\n print(f'>>> Dict file: {args.dict_file}')\n print(f'>>> query_encoder_weights_path: {query_encoder_weights_path}')\n\n text_to_seq_dict = parse_dict_file()\n es_output = parse_experiment_file()\n run()\n","repo_name":"nguyenthanhasia/legal_doc_retrieval","sub_path":"evaluating/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":6998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14040611585","text":"\"\"\"CheckSimulation class.\"\"\"\n# 1. Standard python modules\nimport os\n\n# 2. Third party modules\n\n# 3. Aquaveo modules\nfrom xmsapi.dmi import ModelCheckError\n\n# 4. Local modules\n\n__copyright__ = \"(C) Copyright Aquaveo 2020\"\n__license__ = \"All rights reserved\"\n\n\nclass SimulationCheck:\n \"\"\"Model check for Standard Interface Template simulation.\"\"\"\n\n def __init__(self, check_thread):\n \"\"\"\n Constructor.\n\n Args:\n check_thread (:obj:`CheckThread`): A class for holding the data that will be used for checking this\n simulation.\n \"\"\"\n super().__init__()\n self.errors = []\n self.error_text = ''\n self._model_control = None\n self._sim_comp_dir = ''\n if check_thread.sim_component:\n self._model_control = check_thread.sim_component.data\n self._sim_comp_dir = os.path.dirname(check_thread.sim_component.main_file)\n self._ugrid = check_thread.ugrid\n self._grid_units = check_thread.grid_units\n self._bc_data = check_thread.bc_data\n self._bc_comp_id_to_arc_id = check_thread.bc_comp_ids_to_arc_ids\n self._mat_data = check_thread.mat_data\n\n def run_check(self):\n \"\"\"\n Runs model check on the simulation.\n\n Raises:\n (Exception): There was a problem running checks on the simulation.\n \"\"\"\n try:\n self._check_mesh()\n self._check_bcs()\n self._check_materials()\n except: # pragma: no cover # noqa\n raise RuntimeError('Error checking simulation.')\n return self.errors\n\n def _add_error(self, problem, description, fix):\n \"\"\"\n Adds a model check error.\n\n Args:\n problem (str): An explanation of the problem that has been discovered.\n description (str): A description of the problem.\n fix (str): An explanation of how to fix the problem.\n \"\"\"\n error = ModelCheckError()\n error.set_problem_text(problem)\n error.set_description_text(description)\n error.set_fix_text(fix)\n self.errors.append({\"#description\": \"ModelCheck\", \"\": error})\n self.error_text = f'{self.error_text}' \\\n f'Problem: {problem}\\n' \\\n f'Description: {description}\\n' \\\n f'Fix: {fix}\\n'\n\n def _check_mesh(self):\n \"\"\"Check metrics on the mesh.\"\"\"\n # make sure a mesh is in the simulation\n if not self._ugrid:\n problem = 'STOP! Simulation requires an unstructured mesh.'\n description = 'An unstructured mesh is required for this simulation.'\n fix = 'Add an unstructured mesh to the simulation.'\n self._add_error(problem, description, fix)\n return\n\n # check the number of elements in the mesh\n num_cells = self._ugrid.cell_count\n if num_cells < 200000:\n pass\n else:\n problem = f'Warning: The unstructured mesh contains {num_cells} elements.'\n if num_cells < 500000:\n description = 'Best performance for Standard Template Interface occurs with meshes with under ' \\\n '100,000 elements.'\n fix = 'Review the mesh and verify that this many elements is required.'\n elif num_cells < 2000000:\n description = 'Poor performance for Standard Template Interface will occur with this mesh.'\n fix = 'You are STRONGLY encouraged to reduce the number of elements in the mesh.'\n else:\n description = 'The existing mesh greatly exceeds the maximum number of elements.'\n fix = 'Reduce the number of elements to get a workable solution.'\n self._add_error(problem, description, fix)\n\n # check the units for the mesh (must be feet or meters)\n if not self._grid_units:\n problem = 'STOP! Horizontal units are not FEET or METERS.'\n description = 'Horizontal units must be FEET or METERS for this simulation.'\n fix = 'Change the horizontal units to FEET or METERS.'\n self._add_error(problem, description, fix)\n\n def _check_bcs(self):\n \"\"\"Check the boundary conditions.\"\"\"\n # bc coverage must exist in the simulation\n if not self._bc_data:\n problem = 'STOP! A boundary condition coverage must be included in simulation.'\n description = 'A boundary condition coverage is required for this simulation.'\n fix = 'Add a boundary condition coverage to the simulation.'\n self._add_error(problem, description, fix)\n return\n\n def _check_materials(self):\n \"\"\"Check the material properties.\"\"\"\n # material coverage must exist in the simulation\n if not self._mat_data:\n problem = 'STOP! A material coverage must be included in simulation.'\n description = 'A material coverage is required for this simulation.'\n fix = 'Add a material coverage to the simulation.'\n self._add_error(problem, description, fix)\n return\n\n # must have material defined in addition to 'unassigned'\n df = self._mat_data.coverage_data.to_dataframe()\n mat_names = df['name'].to_list()\n if len(mat_names) < 2:\n problem = 'STOP! No user defined material zones found.'\n description = 'User defined materials are required for this simulation.'\n fix = 'Define materials for the material coverage.'\n self._add_error(problem, description, fix)\n\n # material names must be unique\n unique_names = set(mat_names)\n if len(mat_names) != len(unique_names):\n problem = 'STOP! Material names must be unique.'\n description = 'Standard Interface Template requires unique material names.'\n fix = 'Define unique material names for the material coverage.'\n self._add_error(problem, description, fix)\n","repo_name":"Aquaveo/standard-interface-template","sub_path":"standard_interface_template/check/simulation_check.py","file_name":"simulation_check.py","file_ext":"py","file_size_in_byte":6077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36008203441","text":"import argparse\nimport re\n\nfrom api_gen import (\n INTARRAY_ATTRIBUTE,\n NAMESPACE_TEMPLATE,\n OP_INPUT,\n VECTOR_TYPE,\n CodeGen,\n)\n\nH_FILE_TEMPLATE = \"\"\"\n\n#pragma once\n\n#include \n\n// Avoid a problem with copysign defined in pyconfig.h on Windows.\n#ifdef copysign\n#undef copysign\n#endif\n\n{body}\n\n\"\"\"\n\nAPI_DECLARE_TEMPLATE = \"\"\"\nPyObject *static_api_{name}(PyObject *self, PyObject *args, PyObject *kwargs);\n\"\"\"\n\n\nCPP_FILE_TEMPLATE = \"\"\"\n\n#include \"paddle/fluid/pybind/static_op_function.h\"\n#include \"paddle/fluid/pir/dialect/operator/ir/pd_api.h\"\n#include \"paddle/fluid/pybind/eager_utils.h\"\n#include \"paddle/fluid/pybind/exception.h\"\n#include \"paddle/fluid/pybind/op_function_common.h\"\n#include \"paddle/phi/common/int_array.h\"\n#include \"paddle/phi/core/enforce.h\"\n\n\n{body}\n\n\"\"\"\n\nNO_MUTABLE_ATTR_API_IMPL_TEMPLATE = \"\"\"\nPyObject *static_api_{api_name}(PyObject *self, PyObject *args, PyObject *kwargs) {{\n try {{\n VLOG(6) << \"Add {api_name} op into program\";\n VLOG(8) << \"args count: \" << (PyTuple_Size(args) / 2);\n\n // Get Value from args\n {inputs}\n\n // Parse Attributes\n {attrs}\n\n // Call ir static api\n auto static_api_out = paddle::dialect::{api_name}({args});\n\n return ToPyObject(static_api_out);\n }} catch (...) {{\n ThrowExceptionToPython(std::current_exception());\n return nullptr;\n }}\n}}\n\"\"\"\n\nNO_OUTPUT_API_IMPL_TEMPLATE = \"\"\"\nPyObject *static_api_{api_name}(PyObject *self, PyObject *args, PyObject *kwargs) {{\n try {{\n VLOG(6) << \"Add {api_name} op into program\";\n VLOG(8) << \"args count: \" << (PyTuple_Size(args) / 2);\n\n // Get Value from args\n {inputs}\n\n // Parse Attributes\n {attrs}\n\n // Call ir static api\n paddle::dialect::{api_name}({args});\n\n return nullptr;\n }} catch (...) {{\n ThrowExceptionToPython(std::current_exception());\n return nullptr;\n }}\n}}\n\"\"\"\n\nINPUT_TEMPLATE = \"\"\"\n PyObject *{name}_obj = PyTuple_GET_ITEM(args, {index});\n auto {name} = {cast_func}({name}_obj, \"{api_name}\", {index});\"\"\"\n\nNO_MUTABLE_ATTR_CAST_TEMPLATE = \"\"\"\n PyObject *{name}_obj = PyTuple_GET_ITEM(args, {index});\n {type} {name} = {cast_func}({name}_obj, \"{api_name}\", {index});\"\"\"\n\nMUTABLE_ATTR_API_IMPL_TEMPLATE = \"\"\"\nPyObject *static_api_{api_name}(PyObject *self, PyObject *args, PyObject *kwargs) {{\n try {{\n VLOG(6) << \"Add {api_name} op into program\";\n VLOG(8) << \"args count: \" << (PyTuple_Size(args) / 2);\n\n // Get Value from args\n {inputs}\n\n // Parse Attributes\n {attrs_py_obj}\n\n // Check for mutable attrs\n {init_attrs}\n {cast_attrs}\n\n // Call ir static api\n auto static_api_out = paddle::dialect::{api_name}({args_with_mutable_attrs});\n return ToPyObject(static_api_out);\n\n\n }} catch (...) {{\n ThrowExceptionToPython(std::current_exception());\n return nullptr;\n }}\n}}\n\"\"\"\n\nINIT_ATTRS_TEMPLATE = \"\"\"\n {type} {name};\n\"\"\"\nMUTABLE_ATTR_TEMPLATE = \"\"\"\n if (PyObject_CheckIROpResult({name}_obj)){{\n {mutable_cast_attrs}\n }}else{{\n {no_mutable_cast_attrs}\n }}\"\"\"\n\nMUTABLE_ATTR_LIST_TEMPLATE = \"\"\"\n if (PyObject_CheckIROpResult({name}_obj)){{\n {mutable_cast_attrs}\n }}else if (PyObject_CheckIRVectorOfOpResult({name}_obj)){{\n {mutable_vector_cast_attrs}\n }}else{{\n {no_mutable_cast_attrs}\n }}\"\"\"\n\nMUTABLE_ATTR_OBJ_TEMPLATE = \"\"\"\n PyObject *{name}_obj = PyTuple_GET_ITEM(args, {index});\"\"\"\n\nMUTABLE_ATTR_CAST_TEMPLATE = \"\"\"\n {type} {name_} = {cast_func}({name}_obj, \"{api_name}\", {index});\"\"\"\n\nFULL_OP_TEMPLATE = \"\"\"\n {name} = paddle::dialect::full(std::vector{{1}}, {name}_tmp, phi::DataType::{phi_datatype}, phi::CPUPlace());\n\"\"\"\n\nFULL_INT_ARRAY_OP_TEMPLATE = \"\"\"\n {name} = paddle::dialect::full_int_array({name}_tmp, phi::DataType::{phi_datatype}, phi::CPUPlace());\n\"\"\"\n\nBUILTIN_STACK_OP_TEMPLATE = \"\"\"\n {name} = paddle::dialect::stack({name}_tmp, /*axis*/0);\n\"\"\"\nTYPE_TO_FUNC_MAP = {\n \"bool\": \"CastPyArg2Boolean\",\n \"int\": \"CastPyArg2Int\",\n \"long\": \"CastPyArg2Long\",\n \"int64_t\": \"CastPyArg2Long\",\n \"float\": \"CastPyArg2Float\",\n \"double\": \"CastPyArg2Double\",\n \"std::string\": \"CastPyArg2String\",\n \"std::vector\": \"CastPyArg2Booleans\",\n \"std::vector\": \"CastPyArg2Ints\",\n \"std::vector\": \"CastPyArg2Longs\",\n \"std::vector\": \"CastPyArg2Longs\",\n \"std::vector\": \"CastPyArg2Floats\",\n \"std::vector\": \"CastPyArg2Float64s\",\n \"std::vector\": \"CastPyArg2Strings\",\n \"paddle::experimental::Scalar\": \"CastPyArg2Scalar\",\n \"std::vector\": \"CastPyArg2ScalarArray\",\n \"paddle::experimental::IntArray\": \"CastPyArg2IntArray\",\n \"paddle::Place\": \"CastPyArg2Place\",\n \"Place\": \"CastPyArg2Place\",\n \"phi::DataType\": \"CastPyArg2DataTypeDirectly\",\n}\n\nTYPE_TO_PHI_DATATYPE_MAP = {\n \"bool\": \"BOOL\",\n \"int\": \"INT32\",\n \"long\": \"INT64\",\n \"int64_t\": \"INT64\",\n \"float\": \"FLOAT32\",\n \"double\": \"FLOAT64\",\n \"std::vector\": \"BOOL\",\n \"std::vector\": \"INT32\",\n \"std::vector\": \"INT64\",\n \"std::vector\": \"INT64\",\n \"std::vector\": \"FLOAT32\",\n \"std::vector\": \"FLOAT64\",\n}\n\nMANUAL_STATIC_OP_FUNCTION_LIST = ['full']\n\n\nclass PythonCCodeGen(CodeGen):\n def __init__(self) -> None:\n super().__init__()\n\n def _gen_one_declare(self, op_name):\n return API_DECLARE_TEMPLATE.format(name=op_name)\n\n def _gen_h_file(self, op_info_items, namespaces, h_file_path):\n declare_str = ''\n for op_info in op_info_items:\n for op_name in op_info.op_phi_name:\n # NOTE:When infer_meta_func is None, the Build() function generated in pd_op\n # is wrong, so temporarily skip the automatic generation of these APIs\n if self._need_skip(op_info, op_name):\n continue\n declare_str += self._gen_one_declare(op_name)\n\n body = declare_str\n for namespace in reversed(namespaces):\n body = NAMESPACE_TEMPLATE.format(namespace=namespace, body=body)\n with open(h_file_path, 'w') as f:\n f.write(H_FILE_TEMPLATE.format(body=body))\n\n def _gen_inputs(self, op_info, op_name):\n name_list = op_info.input_name_list\n type_list = op_info.input_type_list\n optional_list = op_info.input_optional_list\n assert len(name_list) == len(type_list) == len(optional_list)\n ret = ''\n for i, (name, type, optional) in enumerate(\n zip(name_list, type_list, optional_list)\n ):\n if optional == 'true':\n cast_func = (\n 'CastPyArg2OptionalVectorOfValue'\n if VECTOR_TYPE in type\n else 'CastPyArg2OptionalValue'\n )\n else:\n cast_func = (\n 'CastPyArg2VectorOfValue'\n if VECTOR_TYPE in type\n else 'CastPyArg2Value'\n )\n ret += INPUT_TEMPLATE.format(\n name=name, index=i, cast_func=cast_func, api_name=op_name\n )\n return ret\n\n def _gen_attrs_without_mutable(self, op_info, op_name):\n input_size = len(op_info.input_name_list)\n name_list = op_info.attribute_name_list\n type_list = op_info.attribute_build_arg_type_list\n assert len(name_list) == len(type_list)\n ret = ''\n for i, (name, type) in enumerate(zip(name_list, type_list)):\n type = type.replace('const ', '').replace('&', '')\n cast_func = TYPE_TO_FUNC_MAP[type]\n ret += NO_MUTABLE_ATTR_CAST_TEMPLATE.format(\n name=name,\n index=input_size + i,\n type=type,\n cast_func=cast_func,\n api_name=op_name,\n )\n return ret\n\n def _gen_attrs_py_obj_with_mutable(self, op_info):\n input_size = len(op_info.input_name_list)\n name_list = op_info.attribute_name_list\n ret = ''\n for i, name in enumerate(name_list):\n ret += MUTABLE_ATTR_OBJ_TEMPLATE.format(\n name=name, index=input_size + i\n )\n return ret\n\n def _gen_init_mutable_attrs(self, op_info):\n mutable_attr_name_list = op_info.mutable_attribute_name_list\n ret = ''\n for name in mutable_attr_name_list:\n ret += INIT_ATTRS_TEMPLATE.format(type=OP_INPUT, name=name)\n\n return ret\n\n def _gen_cast_attrs(self, op_info, op_name):\n input_size = len(op_info.input_name_list)\n attr_name_list = op_info.attribute_name_list\n attr_type_list = op_info.attribute_build_arg_type_list\n mutable_attr_name_list = op_info.mutable_attribute_name_list\n mutable_attr_type_list = op_info.mutable_attribute_type_list\n assert len(attr_name_list) == len(attr_type_list)\n ret = ''\n for i, (name, type) in enumerate(zip(attr_name_list, attr_type_list)):\n type = type.replace('const ', '').replace('&', '')\n cast_func = TYPE_TO_FUNC_MAP[type]\n\n if name in mutable_attr_name_list:\n phi_dtype = TYPE_TO_PHI_DATATYPE_MAP[type]\n if (\n mutable_attr_type_list[mutable_attr_name_list.index(name)][\n 0\n ]\n == INTARRAY_ATTRIBUTE\n ):\n mutable_cast_str = MUTABLE_ATTR_CAST_TEMPLATE.format(\n type='',\n name_=name,\n name=name,\n cast_func='CastPyArg2Value',\n api_name=op_name,\n index=input_size + i,\n )\n\n mutable_vector_cast_str = MUTABLE_ATTR_CAST_TEMPLATE.format(\n type='std::vector',\n name_=name + '_tmp',\n name=name,\n cast_func='CastPyArg2VectorOfValue',\n api_name=op_name,\n index=input_size + i,\n )\n mutable_vector_cast_str += BUILTIN_STACK_OP_TEMPLATE.format(\n name=name\n )\n\n else:\n mutable_cast_str = MUTABLE_ATTR_CAST_TEMPLATE.format(\n type='',\n name_=name,\n name=name,\n cast_func='CastPyArg2Value',\n api_name=op_name,\n index=input_size + i,\n )\n\n no_mutable_cast_str = MUTABLE_ATTR_CAST_TEMPLATE.format(\n type=type,\n name_=name + '_tmp',\n name=name,\n cast_func=cast_func,\n api_name=op_name,\n index=input_size + i,\n )\n\n if (\n mutable_attr_type_list[mutable_attr_name_list.index(name)][\n 0\n ]\n == INTARRAY_ATTRIBUTE\n ):\n no_mutable_cast_str += FULL_INT_ARRAY_OP_TEMPLATE.format(\n name=name,\n phi_datatype=phi_dtype,\n )\n ret += MUTABLE_ATTR_LIST_TEMPLATE.format(\n name=name,\n mutable_cast_attrs=mutable_cast_str,\n mutable_vector_cast_attrs=mutable_vector_cast_str,\n no_mutable_cast_attrs=no_mutable_cast_str,\n )\n else:\n no_mutable_cast_str += FULL_OP_TEMPLATE.format(\n name=name,\n phi_datatype=phi_dtype,\n )\n ret += MUTABLE_ATTR_TEMPLATE.format(\n name=name,\n mutable_cast_attrs=mutable_cast_str,\n no_mutable_cast_attrs=no_mutable_cast_str,\n )\n else:\n mutable_cast_str = MUTABLE_ATTR_CAST_TEMPLATE.format(\n type=type,\n name_=name,\n name=name,\n cast_func=cast_func,\n api_name=op_name,\n index=input_size + i,\n )\n ret += mutable_cast_str\n\n return ret\n\n def _gen_one_impl(self, op_info, op_name):\n input_name_list = op_info.input_name_list\n output_name_list = op_info.output_name_list\n attr_name_list = op_info.attribute_name_list\n mutable_attr_name_list = op_info.mutable_attribute_name_list\n no_mutable_attr_name_list = op_info.non_mutable_attribute_name_list\n\n if len(output_name_list) == 0:\n ret = NO_OUTPUT_API_IMPL_TEMPLATE.format(\n api_name=op_name,\n inputs=self._gen_inputs(op_info, op_name),\n attrs=self._gen_attrs_without_mutable(op_info, op_name),\n args=', '.join(input_name_list + attr_name_list),\n )\n elif len(mutable_attr_name_list) > 0:\n ret = MUTABLE_ATTR_API_IMPL_TEMPLATE.format(\n api_name=op_name,\n inputs=self._gen_inputs(op_info, op_name),\n attrs_py_obj=self._gen_attrs_py_obj_with_mutable(op_info),\n init_attrs=self._gen_init_mutable_attrs(op_info),\n cast_attrs=self._gen_cast_attrs(op_info, op_name),\n args_with_mutable_attrs=', '.join(\n input_name_list\n + mutable_attr_name_list\n + no_mutable_attr_name_list\n ),\n )\n else:\n ret = NO_MUTABLE_ATTR_API_IMPL_TEMPLATE.format(\n api_name=op_name,\n inputs=self._gen_inputs(op_info, op_name),\n attrs=self._gen_attrs_without_mutable(op_info, op_name),\n args=', '.join(input_name_list + attr_name_list),\n )\n ret = re.sub(r' +\\n', '', ret)\n return ret\n\n def _need_skip(self, op_info, op_name):\n return (\n super()._need_skip(op_info, op_name)\n or op_name in MANUAL_STATIC_OP_FUNCTION_LIST\n )\n\n def _gen_cpp_file(self, op_info_items, namespaces, cpp_file_path):\n impl_str = ''\n for op_info in op_info_items:\n for op_name in op_info.op_phi_name:\n # NOTE:When infer_meta_func is None, the Build() function generated in pd_op\n # is wrong, so temporarily skip the automatic generation of these APIs\n if self._need_skip(op_info, op_name):\n continue\n impl_str += self._gen_one_impl(op_info, op_name)\n body = impl_str\n for namespace in reversed(namespaces):\n body = NAMESPACE_TEMPLATE.format(namespace=namespace, body=body)\n with open(cpp_file_path, 'w') as f:\n f.write(CPP_FILE_TEMPLATE.format(body=body))\n\n\ndef ParseArguments():\n parser = argparse.ArgumentParser(\n description='Generate Dialect Python C Files By Yaml'\n )\n parser.add_argument('--op_yaml_files', type=str)\n parser.add_argument('--op_compat_yaml_file', type=str)\n parser.add_argument('--namespaces', type=str)\n parser.add_argument('--python_c_def_h_file', type=str)\n parser.add_argument('--python_c_def_cc_file', type=str)\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n args = ParseArguments()\n op_yaml_files = args.op_yaml_files.split(\",\")\n op_compat_yaml_file = args.op_compat_yaml_file\n if args.namespaces is not None:\n namespaces = args.namespaces.split(\",\")\n python_c_def_h_file = args.python_c_def_h_file\n python_c_def_cc_file = args.python_c_def_cc_file\n\n code_gen = PythonCCodeGen()\n code_gen.gen_h_and_cpp_file(\n op_yaml_files,\n op_compat_yaml_file,\n namespaces,\n python_c_def_h_file,\n python_c_def_cc_file,\n )\n","repo_name":"PaddlePaddle/Paddle","sub_path":"paddle/fluid/pir/dialect/op_generator/python_c_gen.py","file_name":"python_c_gen.py","file_ext":"py","file_size_in_byte":16332,"program_lang":"python","lang":"en","doc_type":"code","stars":21032,"dataset":"github-code","pt":"29"} +{"seq_id":"154255918","text":"\"\"\"\n~/GitHubs/PhispyAnalysis/scripts/merge_annotations.py makes about 900 large files, and the total size is 29TB. Oops!\n\nWe filter them for annotations that appear in more than n genomes\n\n\n\"\"\"\n\nimport os\nimport sys\nimport argparse\nimport re\n\n__author__ = 'Rob Edwards'\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Filter annotations')\n parser.add_argument('-d', help='directory of annotations', required=True)\n parser.add_argument('-o', help='output directory of annotations', required=True)\n group = parser.add_mutually_exclusive_group(required=True)\n group.add_argument('-n', help='minimum number of entries', type=int)\n group.add_argument('-p', help='percent of the records that must be non zero', type=float)\n parser.add_argument('-v', help='verbose output', action='store_true')\n args = parser.parse_args()\n\n os.makedirs(args.o, exist_ok=True)\n noan = re.compile('^.*?\\t')\n\n if args.p and args.p > 1:\n args.p /= 100\n\n filecount = 0\n for f in os.listdir(args.d):\n filecount += 1\n if args.v:\n sys.stderr.write(f\"Parsing {filecount} {f}\\n\")\n with open(os.path.join(args.d, f), 'r') as fin, open(os.path.join(args.o, f), 'w') as out:\n for l in fin:\n if l.startswith('Function'):\n out.write(l)\n continue\n if args.n:\n if len([x for x in map(int, noan.sub('', l).strip().split(\"\\t\")) if x > 0]) > args.n:\n out.write(l)\n else:\n if len([x for x in map(int, noan.sub('', l).strip().split(\"\\t\")) if x > 0])/l.count(\"\\t\") > args.p:\n out.write(l)\n\n\n","repo_name":"linsalrob/PhispyAnalysis","sub_path":"scripts/filter_combined_annotations.py","file_name":"filter_combined_annotations.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"71247255437","text":"import json\nimport time\n\nfrom app.utils import timeit, get_order_code\nfrom ext_app import db\nfrom manager import app\n\nfrom app.models import JCRanking, JCTicket, JCRace, Accounts, Races, Orders, PointTrace, League, Team\n\nVOTE_DICT = {\n \"1\": [\n \"1:0\",\n \"2:0\",\n \"2:1\",\n \"3:0\",\n \"3:1\",\n \"3:2\",\n \"4:0\",\n \"4:1\",\n \"4:2\",\n \"5:0\",\n \"5:1\",\n \"5:2\"\n ],\n \"X\": [\n \"0:0\",\n \"1:1\",\n \"2:2\",\n \"3:3\"\n ],\n \"2\": [\n \"0:1\",\n \"0:2\",\n \"0:3\",\n \"0:4\",\n \"0:5\",\n \"1:2\",\n \"1:3\",\n \"1:4\",\n \"1:5\",\n \"2:3\",\n \"2:4\",\n \"2:5\"\n ]\n}\n\n\ndef handle_race(race):\n \"\"\"\n 处理订单详情以及比分\n :param race:\n :return:\n \"\"\"\n league = League.query.filter(League.league_id == race.league_id).first().en_name\n home = Team.query.filter(Team.team_id == race.home_id).first().en_name\n guest = Team.query.filter(Team.team_id == race.guest_id).first().en_name\n host_score, guest_score = json.loads(race.scores) if race.scores else (\"\", \"\")\n scores = \":\".join([host_score, guest_score])\n if not host_score and not guest_score:\n scores = \"\"\n elif int(host_score) > int(guest_score):\n if scores not in VOTE_DICT.get(\"1\"):\n scores = \"1 else\"\n elif int(host_score) == int(guest_score):\n if scores not in VOTE_DICT.get(\"X\"):\n scores = \"X else\"\n else:\n if scores not in VOTE_DICT.get(\"2\"):\n scores = \"2 else\"\n return [league, home, guest], scores\n\n\ndef settle_ticket(race, is_delete=0):\n \"\"\"\n 结算下注以及生成订单以及流水\n :param race:\n :param is_delete:\n :return:\n \"\"\"\n order_desc, scores = handle_race(race)\n jc_tickets = JCTicket.query.filter(JCTicket.rid == race.race_id, JCTicket.status == 1).all()\n item_list = []\n cat = time.time()\n if is_delete:\n for jc_ticket in jc_tickets:\n order_desc_ = \" \".join(order_desc + [jc_ticket.vote])\n jc_ticket.status = 2\n jc_ticket.settle_at = cat\n jc_ticket.settle_number = jc_ticket.number\n jc_ticket.result = \"C\"\n account = Accounts.query.filter(Accounts.user_id == jc_ticket.uid).first()\n account.available = account.available + jc_ticket.settle_number\n\n rank = JCRanking.query.filter(JCRanking.user_id == jc_ticket.uid, JCRanking.race_id == race.race_id).first()\n rank.settle_num = jc_ticket.number\n\n order_num = get_order_code()\n order = Orders(\n user_id=jc_ticket.uid,\n order_num=order_num,\n create_at=cat,\n pay_time=cat,\n number=jc_ticket.settle_number,\n desc=order_desc_,\n source=\"Pick'em Canceled(score)\"\n )\n pt = PointTrace(\n user_id=jc_ticket.uid,\n create_at=cat,\n points=jc_ticket.settle_number,\n desc=order_desc_,\n way=\"Pick'em Canceled(score)\",\n title=\"Pick'em Canceled(score)\",\n order_num=order_num,\n current=account.available,\n )\n item_list.append(pt)\n item_list.append(order)\n else:\n won_ticket = [i for i in jc_tickets if i.vote == scores]\n print(f\"won {len((won_ticket))}\")\n for won in won_ticket:\n order_desc_ = \" \".join(order_desc + [won.vote])\n won.status = 2\n won.settle_at = time.time()\n won.settle_number = int(won.number * won.odds)\n won.result = \"W\"\n account = Accounts.query.filter(Accounts.user_id == won.uid).first()\n account.available = account.available + won.settle_number\n\n rank = JCRanking.query.filter(JCRanking.user_id == won.uid, JCRanking.race_id == race.race_id).first()\n rank.settle_num = won.settle_number\n rank.title = f\"{order_desc[1]} {scores.split(':')[0]}-{scores.split(':')[1]} {order_desc[2]}\"\n order_num = get_order_code()\n order = Orders(\n user_id=won.uid,\n order_num=order_num,\n create_at=cat,\n pay_time=cat,\n number=won.settle_number,\n desc=order_desc_,\n source=\"Pick'em Return(score)\"\n )\n pt = PointTrace(\n user_id=won.uid,\n create_at=cat,\n points=won.settle_number,\n desc=order_desc_,\n way=\"Pick'em Return(score)\",\n title=\"Pick'em Return(score)\",\n order_num=order_num,\n current=account.available,\n )\n item_list.append(pt)\n item_list.append(order)\n lose_ticket = [i for i in jc_tickets if i.vote != scores]\n print(f\"lose {len((lose_ticket))}\")\n\n for lose in lose_ticket:\n lose.status = 2\n lose.settle_at = time.time()\n lose.settle_number = 0\n lose.result = \"L\"\n rank = JCRanking.query.filter(JCRanking.user_id == lose.uid, JCRanking.race_id == race.race_id).first()\n rank.title = f\"{order_desc[1]} {scores.split(':')[0]}-{scores.split(':')[-1]} {order_desc[2]}\"\n\n return jc_tickets + item_list\n\n\n@timeit\ndef main():\n with app.app_context():\n jc_races = JCRace.query.filter(JCRace.selected == 1, JCRace.settled == 0).all()\n print(jc_races)\n if jc_races:\n for jc_race in jc_races:\n race = Races.query.filter(Races.race_id == jc_race.race_id).first()\n print(race.race_id, race.scores)\n ticket_list = []\n if race.is_delete == 1:\n # 比赛取消 结算jcticket,更新排行榜,锁定jc_race\n ticket_list = settle_ticket(race, is_delete=1)\n jc_race.settled = 1\n elif race.is_started == 2:\n # 比赛结束 结算jcticket,更新排行榜,锁定jc_race\n ticket_list = settle_ticket(race)\n jc_race.settled = 1\n db.session.bulk_save_objects(ticket_list)\n db.session.commit()\n db.session.close()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"chseng213/Questionnaire","sub_path":"crontab_task.py","file_name":"crontab_task.py","file_ext":"py","file_size_in_byte":6434,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"29488937333","text":"# we may need to pip install flask\n# python -m pip install flask\nfrom flask import Flask\nfrom flask import render_template\nimport requests # we may need this\nimport json\n\n# we wil explore Flask architecture and create web URL links (known as 'routes')\napp = Flask(__name__) # any name will do, but by convention we use the module name\n# we then declare one or more routes for our app (each route uses http 'get')\n@app.route('/') # this is the root of our website\ndef root():\n return 'hello and welcome to our Flask application' # or '

Hello

'\n\n@app.route('/home') # we can invent any names for our routes\ndef home():\n content = '''\n

Flask Home Web Page

\n '''\n return content\n\n@app.route('/todos')\ndef todos():\n data = json.load(open('todos.json', 'r'))\n data_j = json.dumps(data)\n return data_j # we can only send string data\n\n@app.route('/links')\ndef links():\n content = '''\n

Visit these links

\n Top level |\n Home |\n To do list\n '''\n return content\n\n@app.route('/person')\n@app.route('/folk') # cover mis-spellings, diferrent product names, historical changes\ndef person():\n # we can pass aa structure and Flask will encode it\n struct = {'name':'Timnit', 'age':42, 'member':True}\n return struct # Flask will parse this structure into encoded text\n\n@app.route('/greet')\n@app.route('/greet/') # here we allow a parameter in the URL\ndef greet(name='Grommet'):\n # Flask will look in the 'templates' folder\n return render_template('greet.html', n = name) # we can pass the URL parameter along to the HTML page\n\n\n\nif __name__ == '__main__':\n app.run() # this starts our Flask web server","repo_name":"onionmccabbage/advPyMar23","sub_path":"using_microservices/using_flask.py","file_name":"using_flask.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"70636700237","text":"class TimeMap:\n\n def __init__(self):\n self.DP={}\n\n \n\n def set(self, key: str, value: str, timestamp: int) -> None:\n if key not in self.DP:\n self.DP[key]=[[value,timestamp]]\n else:\n self.DP[key].append([value,timestamp])\n def get(self, key: str, timestamp: int) -> str:\n if key not in self.DP:\n return \"\"\n else:\n Arr=self.DP[key]\n i=0\n j=len(Arr)-1\n L=\"\"\n while(i<=j):\n mid=(i+j)>>1\n if Arr[mid][1]==timestamp:\n return Arr[mid][0]\n elif Arr[mid][1]\"\ntrans_dict = {\n '-': '',\n '–': '',\n '—': '',\n '“': SPL,\n '”': SPL,\n '.': SPL,\n '!': SPL,\n '¡': SPL,\n '?': SPL,\n '¿': SPL,\n ';': SPL,\n '\"': SPL,\n '«': SPL,\n '»': SPL,\n 'ѳ': 'ø',\n }\nlines = []\nfor ind in df.index:\n spa_text = df[\"spa_text\"][ind]\n gum_text = df[\"gum_text\"][ind]\n # spa_text = str(spa_text).translate(trans_dict)\n # gum_text = str(gum_text).translate(trans_dict)\n spa_text = re.sub(r'[-–—]', '', spa_text)\n spa_text = re.sub('[“”.:¡!¿?\"«»‘’]', SPL, spa_text)\n gum_text = re.sub(r'[-–—]', '', gum_text)\n gum_text = re.sub('[ѳ]', 'ø', gum_text)\n gum_text = re.sub('[“”.:¡!¿?\"«»‘’]', SPL, gum_text)\n # print(gum_text)\n\n # strip all phrases\n split_spa = [x.strip() for x in str(spa_text).split(SPL)]\n split_gum = [x.strip() for x in str(gum_text).split(SPL)]\n\n # remove empty strings\n split_spa = [i for i in split_spa if i]\n split_gum = [i for i in split_gum if i]\n #los tamaños que se deben comparar son los inetervalos no vacios\n if len(split_spa) == len(split_gum):\n # print(\"-----------\")\n # print(split_spa)\n # print(split_gum)\n for idx in range(len(split_spa)):\n if not len(split_gum[idx]) == 0 and not len(split_spa[idx]) == 0:\n lines.append(f'{split_spa[idx].replace(SPL,\"\").strip().lower()}\\t{split_gum[idx].replace(SPL,\"\").strip().lower()}') \n else:\n lines.append(f'{spa_text.replace(SPL,\"\").strip().lower()}\\t{gum_text.replace(SPL,\"\").strip().lower()}')\n # break\n\n# Save to TXT\nwith open('spa-gum.txt', 'w', encoding=\"utf-8\") as f:\n for line in lines: \n f.write(line)\n f.write('\\n')","repo_name":"AYTECOL/traductor-esp-gum","sub_path":"dataset_cleanup.py","file_name":"dataset_cleanup.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"17941345688","text":"import argparse\nimport cv2\nfrom pyzbar import pyzbar\nimport numpy as np\nimport imutils\n\n# construct argument parse and parse the argument\nap = argparse.ArgumentParser()\nap.add_argument(\"-o\", \"--output\", type=str, default=\"barcodes.csv\", help=\"path to output CSV file containing barcodes\")\nargs = vars(ap.parse_args())\n\ncap = cv2.VideoCapture(\"udp://@0.0.0.0:11111\")\n# opening webcam\n# cap = cv2.VideoCapture(0)\n\n# initialize target and counter for fps\ntarget = 5\ncounter = 0\n\n# loop over frames from VideoCapture\nwhile True:\n if counter == target:\n ret, frame = cap.read()\n barcodes = pyzbar.decode(frame) # find barcode/QR code in frame and decode it\n\n if ret:\n # loop over detected barcode/QR code\n for barcode in barcodes:\n # extract bounding box location of barcode/QR code and draw bounding box surrounding it\n (x, y, w, h) = barcode.rect\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)\n\n # convert output(bytes) to string\n barcodeData = barcode.data.decode(\"utf-8\")\n barcodeType = barcode.type\n\n # draw barcode data and type on the frame/image\n text = \"{} ({})\".format(barcodeData, barcodeType)\n cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\n\n # show output\n cv2.imshow(\"Scanner\", frame)\n counter = 0\n\n else:\n ret = cap.grab()\n counter += 1\n\n # if `q` key was pressed, break from the loop\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n\n\n\n\n\n\n\n\n","repo_name":"harithzainudin/DragonFly","sub_path":"Development Code/DJI Tello/tello-ai/camera-better-scanning-and-distance.py","file_name":"camera-better-scanning-and-distance.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"39914772009","text":"import os\nimport sys\nimport subprocess\nimport time\n\nfrom pymol.Qt import QtCore, QtWidgets\n\nfrom pymod_lib.pymod_exceptions import PyModInterruptedProtocol\n\n\nclass PyMod_protocol_thread(QtCore.QThread):\n \"\"\"\n Class for a 'QThread' to launch a function where a time-consuming process is\n executed. It is used when showing a 'Protocol_exec_dialog' dialog.\n \"\"\"\n\n # Signals.\n terminate_thread_signal = QtCore.pyqtSignal(int)\n exception_thread_signal = QtCore.pyqtSignal(Exception)\n\n def set_params(self, function, args, wait_start, wait_end):\n self.function = function\n self.args = args\n self.wait_start = wait_start\n self.wait_end = wait_end\n\n def run(self):\n if self.wait_start is not None:\n time.sleep(self.wait_start)\n\n # Attempts to execute the function in this thread.\n try:\n if type(self.args) is dict:\n self.function(**self.args)\n else:\n self.function(*self.args)\n self._wait_end()\n self.terminate_thread_signal.emit(0) # Terminate sucessully.\n\n # If there was an error, emit the exception, so that it can be handled in the main thread.\n except Exception as e:\n self._wait_end()\n self.exception_thread_signal.emit(e) # Terminate by raising an exception.\n\n def _wait_end(self):\n if self.wait_end is not None:\n time.sleep(self.wait_end)\n\n\nclass Protocol_exec_dialog(QtWidgets.QDialog):\n \"\"\"\n A dialog with a progress bar used when running long and time-consuming functions in PyMod.\n \"\"\"\n\n is_pymod_window = True\n\n def __init__(self, app, pymod, function, args,\n wait_start=0.15,\n wait_end=0.15,\n wait_close=0.20,\n title=\"Running a new protocol\",\n label_text=\"Running. Please wait for the protocol to complete.\",\n lock=False,\n lock_title=\"Can not Exit\",\n lock_message=\"Can not safely exit. Please wait for the threa to complete.\",\n progress=True,\n stdout_silence=False,\n stdout_filepath=None,\n backend=\"qthread\"):\n\n QtWidgets.QDialog.__init__(self, parent=app)\n\n self.main_window = app\n self.pymod = pymod\n self.function = function\n self.args = args\n self.wait_start = wait_start # Time to wait before the protocol is actually executed.\n self.wait_end = wait_end # Time to wait after the protocol completes.\n self.wait_close = wait_close # Time to wait before the dialog closes.\n self.title = title\n self.label_text = label_text\n\n self.lock = lock\n self.lock_title = lock_title\n self.lock_message = lock_message\n self.progress = progress\n self.error = None\n\n if not backend in (\"qthread\", \"python\"):\n raise KeyError(\"Unknown 'backend': %s\" % backend)\n self.backend = backend\n\n self.initUI()\n self.setModal(True) # Set the type of dialog.\n\n # Revert the terminal output to a file.\n self.stdout_filepath = stdout_filepath\n # Silence all stdout.\n self.stdout_silence = stdout_silence\n self._revert_stdout = self.stdout_silence or self.stdout_filepath is not None\n\n # Protocol thread.\n if self.backend == \"qthread\":\n self.p_thread = PyMod_protocol_thread()\n self.p_thread.set_params(self.function, self.args, self.wait_start, self.wait_end)\n self.p_thread.terminate_thread_signal.connect(self.on_terminate_thread_signal)\n self.p_thread.exception_thread_signal.connect(self.on_exception_thread_signal)\n # self.worker = QtCore.QObject()\n # self.worker.moveToThread(self.p_thread)\n\n elif self.backend == \"python\":\n # self.p_thread = threading.Thread(target=self.function,\n # args=self.args,\n # daemon=True)\n raise NotImplementedError\n\n\n def initUI(self):\n\n self.setWindowTitle(self.title)\n\n vertical_layout = QtWidgets.QVBoxLayout()\n self.thread_progressbar = QtWidgets.QProgressBar(self)\n if self.progress:\n self.thread_progressbar.setMinimum(0)\n self.thread_progressbar.setMaximum(0)\n progressbar_label = \"Computing...\" # \"Wait for the protocol to complete.\"\n self.thread_progressbar.setFormat(progressbar_label)\n self.thread_progressbar.setValue(0)\n vertical_layout.addWidget(self.thread_progressbar)\n\n self.thread_progress_label = QtWidgets.QLabel(self.label_text, self)\n self.thread_progress_label.setWordWrap(True)\n vertical_layout.addWidget(self.thread_progress_label)\n\n # Button for canceling the execution of the thread.\n horizontal_layout = QtWidgets.QHBoxLayout()\n self.cancel_button = QtWidgets.QPushButton('Cancel', self)\n self.cancel_button.clicked.connect(self.on_cancel_button_click)\n self.cancel_button.setEnabled(not self.lock)\n horizontal_layout.addWidget(self.cancel_button)\n\n vertical_layout.addLayout(horizontal_layout)\n\n self.setLayout(vertical_layout)\n\n\n def exec_(self):\n \"\"\"\n Opens the dialog and performs checks on the errors at the end.\n \"\"\"\n # Redirect stdout.\n if self._revert_stdout:\n original_stdout = sys.stdout\n if self.stdout_silence:\n sys.stdout = open(os.devnull, \"w\")\n else:\n sys.stdout = open(self.stdout_filepath, \"w\")\n\n # Starts the thread before showing the progress dialog.\n self.p_thread.start()\n QtWidgets.QDialog.exec_(self)\n\n # Revert stdout.\n if self._revert_stdout:\n sys.stdout.close()\n sys.stdout = original_stdout\n\n # Complete.\n if self.wait_close is not None:\n time.sleep(self.wait_close)\n self.check_error()\n\n\n def check_error(self):\n \"\"\"\n Checks if there was an exception in the child thread.\n \"\"\"\n if self.error is None:\n return None\n else: # If there was an exception, then raise it in the main thread.\n raise self.error\n\n\n def get_cancel_exception(self):\n \"\"\"\n Getr the exception raised when interrupting a protocol.\n \"\"\"\n return PyModInterruptedProtocol(\"Interrupted the protocol\")\n\n\n # Interactions with the buttons.\n def on_cancel_button_click(self):\n \"\"\"\n Stops the protocol thread and provides an exception to stop the execution in the main thread.\n \"\"\"\n self.on_exception_thread_signal(self.get_cancel_exception())\n\n\n def closeEvent(self, evnt):\n\n # Closes the dialog.\n if not self.lock:\n # The user clicked the \"close\" button on the window.\n if evnt.spontaneous():\n self._on_exception_thread_signal(self.get_cancel_exception())\n super(Protocol_exec_dialog, self).closeEvent(evnt)\n\n # Can not close the dialog when the user clicks on it.\n else:\n # Inactivates the \"close\" button on the window.\n if evnt.spontaneous():\n evnt.ignore()\n\n\n # Interactions with the thread.\n def on_terminate_thread_signal(self, status):\n \"\"\"\n The thread has successfully terminated, closes the dialog.\n \"\"\"\n if status == 0:\n self.close()\n else:\n raise NotImplementedError\n\n\n def on_exception_thread_signal(self, e):\n \"\"\"\n An exception has been raised while executing the protocol. Stores the exception\n raised in the protocol thread, so that it can be raised in the main thread.\n Then closes the dialog, so that the exception can be raised.\n \"\"\"\n self._on_exception_thread_signal(e)\n self.close()\n\n def _on_exception_thread_signal(self, e):\n self.error = e\n self._terminate_threads()\n\n def _terminate_threads(self):\n if self.p_thread.isRunning():\n # self.worker.stop()\n self.p_thread.terminate()\n # self.p_thread.quit()\n # self.p_thread.wait()\n\n\n def keyPressEvent(self, event):\n \"\"\"\n By overriding this method, the dialog will not close when pressing the \"esc\" key.\n \"\"\"\n if event.key() == QtCore.Qt.Key_Escape:\n pass\n else:\n QtWidgets.QDialog.keyPressEvent(self, event)\n","repo_name":"pymodproject/pymod","sub_path":"pymod3/pymod_lib/pymod_threading.py","file_name":"pymod_threading.py","file_ext":"py","file_size_in_byte":8645,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"29"} +{"seq_id":"16980563763","text":"from django import forms\n\nclass AdminUploadFileForm(forms.Form):\n\tfile = forms.FileField()\n\nclass AddOfficeHourForm(forms.Form):\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(AddOfficeHourForm, self).__init__(*args, **kwargs)\n\t\tchoices = []\n\t\tfor x in range(1,31):\n\t\t\tfield_str = str(x) + ' weeks'\n\t\t\tchoices.append((x,field_str))\n\t\tself.fields['recurring_times'].choices = choices\n\n\tTIMES = (('09:00', '09:00'),\n\t\t('09:30', '09:30'),\n\t\t('10:00', '10:00'),\n\t\t('10:30','10:30'),\n\t\t('11:00','11:00'),\n\t\t('11:30','11:30'),\n\t\t('12:00','12:00'),\n\t\t('12:30','12:30'),\n\t\t('13:00','13:00'),\n\t\t('13:30','13:30'),\n\t\t('14:00','14:00'),\n\t\t('14:30','14:30'),\n\t\t('15:00','15:00'),\n\t\t('15:30','15:30'),\n\t\t('16:00','16:00'),\n\t\t('16:30','16:30'),\n\t\t('17:00','17:00'),\n\t\t('17:30','17:30'),\n\t\t('18:00','18:00'))\n\n\tstart_time = forms.ChoiceField(choices=TIMES)\n\tend_time = forms.ChoiceField(choices=TIMES)\n\tlocation = forms.CharField()\n\trecurring_times = forms.ChoiceField(choices=())\n\toffice_hour_title = forms.CharField(initial=\"\")\n\nclass AddRequestForm(forms.Form):\n\trequest_title = forms.CharField(max_length=150)\n\trequest_description = forms.CharField(widget=forms.Textarea(attrs = {\"rows\":5, \"cols\":80}))\n\ttried_solutions = forms.CharField(widget=forms.Textarea(attrs = {\"rows\":5, \"cols\":80}))\n\nclass FeedbackForm(forms.Form):\n\tnext_steps = forms.CharField(required=False, widget=forms.Textarea(attrs = {\"rows\":5, \"cols\":80}))\n\tfoot_note = forms.CharField(required=False, widget=forms.Textarea(attrs = {\"rows\":5, \"cols\":80}))","repo_name":"ghitakouadri/digital_clerk","sub_path":"digitalclerk_app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"27693631264","text":"\"\"\"\n 무지의 먹방 라이브\n 왜 3번케이스?\n\"\"\"\nimport heapq\n\ndef solution(food_times, k):\n array = []\n if sum(food_times) <= k:\n return -1\n # 1. 힙큐에 삽입\n for i, time in enumerate(food_times):\n if time > 0:\n heapq.heappush(array, (time, (i + 1)))\n temp = 0 # 몇 바퀴 돌린지 변수\n # 한 번에 한 묶음 씩 제거하기\n while (len(array) * (array[0][0] - temp)) <= k: # (전체 길이에서 * 가장 작은 시간) <= 남은 시간\n length = len(array)\n now = heapq.heappop(array)\n k -= ((now[0] - temp) * length)\n temp = now[0]\n while array[0][0] == now[0]:\n heapq.heappop(array)\n\n result = sorted(array, key=lambda x: x[1]) # 다시 인덱스 기준으로 정렬\n return result[k % len(array)][1]","repo_name":"JUNGEEYOU/python-algorithm","sub_path":"11/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70169058959","text":"#!/usr/bin/env python\n# coding: utf-8\nimport os\nimport shutil\nimport subprocess\nfrom backend.utility import g_logger\nbase_path = os.path.dirname(os.path.realpath(__file__))\n\n\n# opensmile \ndef opensmiler(infile, outfold, config='emobase2010',toolfold=os.path.join(base_path, 'opensmile-2.3.0/'),extension='.txt', max_retry=10):\n '''\n infile: single input file to be extracted\n outfold: where to save the extracted file with the same name\n config: opensmile config file\n toolfold: opensmile tool folder\n extension: \".txt\" or \".csv\" \n '''\n # tool and config\n tool = '%sbin/linux_x64_standalone_libstdc6/SMILExtract' %toolfold\n config = '%sconfig/%s.conf' %(toolfold,config)\n \n # get infile and outfile names\n infilename = infile\n outfilename = '%s/%s%s' %(outfold, infile.split('/')[-1].split('.wav')[0], extension)\n cmd = '%s -C %s -I %s -O %s' %(tool,config,infilename,outfilename)\n # execute\n success = False\n retry = 0\n while not success and retry < max_retry:\n if retry > 0:\n g_logger.info(\"{}重试第{}次\".format(infile, retry))\n\n # if subprocess.call(cmd, shell=True) !=0:\n # g_logger.error('opensmile extract {} features fail'.format(infile))\n subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).communicate()\n\n success = os.path.exists(outfilename)\n retry += 1\n return outfilename\n\n \n# 批量提取文件夹下所有wav的opensmile特征\ndef batch_extract(input_wavs, output_path):\n \"\"\"\n :param input_wavs: dict. key-clip_name, value-clip_path\n :param output_path: temp_dir for txt file from opensmile\n :return: dict. key-clip_name, value-clip_features(1582-dims)\n \"\"\"\n\n results = {}\n g_logger.info('提取opensmile特征的音频数量: {}'.format(len(input_wavs)))\n # emobase2010\n outfold = os.path.join(output_path, 'opensmile_txt')\n if os.path.exists(outfold):\n shutil.rmtree(outfold)\n os.makedirs(outfold)\n\n for clip in input_wavs:\n f = input_wavs[clip]\n txt_file = opensmiler(f, outfold=outfold,config='emobase2010')\n if not os.path.exists(txt_file):\n g_logger.warning(\"提取{}的opensmile特征失败,使用全0特征。\".format(clip))\n results[clip] = [float(0)]*1582\n else:\n f = open(txt_file, 'r')\n last_line = f.readlines()[-1]\n f.close()\n features = last_line.split(',')\n features = features[1:-1]\n features = [float(x) for x in features]\n results[clip] = features\n\n g_logger.info(\"opensmile提取完成.\")\n return results\n\n \nif __name__ == '__main__': \n pass\n\n","repo_name":"tal-tech/video-analyse-emotion","sub_path":"emotion_model/opensmile_extraction.py","file_name":"opensmile_extraction.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"3529770143","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef plotLeGraph(arrays, avlCtr, bstCtr, type):\n plt.title(f'Comparaison des compteurs de type {type} des arbres')\n plt.xlabel(\"taille des arrays\")\n plt.ylabel(\"valeurs des compteurs\")\n plt.plot(arrays, avlCtr, color='r', label='AVL')\n plt.plot(arrays, bstCtr, color='b', label='BST')\n plt.legend()\n plt.show()\n\n\n\n\n\nif __name__ == \"__main__\":\n arraySizes = [0, 10, 100, 1000]\n AVLInsert = [0, 66, 1314, 19770]\n BSTInsert = [0, 36, 755, 11117]\n AVLSearch = [0, 2, 6, 7]\n BSTSearch = [0, 4, 11, 8]\n\n plotLeGraph(arraySizes, AVLSearch, BSTSearch, \"recherche\")\n\n\n","repo_name":"RayanFellah/TP-INF2010","sub_path":"TP3/INF2010-TP3/src/graph.py.py","file_name":"graph.py.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"36412421604","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python3\n\"\"\"\n ┯━━━━━━━━▧▣▧━━━━━━━━┯\n ━━━━━━━┛ ✠ ┗━━━━━━━━\n\n Author:\n @alderetebrian\n\n ━━━━━━━┓ ✠ ┏━━━━━━━━\n ┷━━━━━━━━▧▣▧━━━━━━━━┷\n\"\"\"\n\nfrom lxml import html\nimport requests\nimport json\n\nfrom json_db import json_db\n\n\ndef save_info(nombre, extension, data):\n with open(f'{nombre}.{extension}', 'w', encoding='utf-8') as f:\n f.write(data)\n\n\nMAIN_URL = \"http://www.pinktherapy.com\"\n\nHEADERS = {\n 'User-agent': \"Mozilla/5.0 (Android; Linux armv7l; rv:10.0.1) Gecko/20100101 Firefox/10.0.1 Fennec/10.0.1\"\n}\n\n#/([\\w\\.\\-]+)@([\\w\\-]+)((\\.(\\w){2,3})+)/g regex for match emails\n#page_number = 1\n\nlista = []\nwith open('pinktherapy_perfiles.log') as file:\n for line in file:\n lista.append(line.strip())\n\nlist_person = []\nPAGE_URL = f\"/en-us/findatherapist.aspx\"\nURL = MAIN_URL + PAGE_URL\npage = requests.get(URL, headers=HEADERS)\n\ntree = html.fromstring(page.content)\n\nprofiles = lista\n\nprint(f'Pagina actual: {URL}')\nprint(f'Perfiles encontrados: {str(len(profiles))}')\n\ncount = 1\nfor profile in profiles:\n print(f'Perfil Numero: {count}')\n try:\n page = requests.get(profile, headers=HEADERS)\n tree = html.fromstring(page.content)\n name = tree.xpath('//span[@id=\"dnn_ctr2027_dnnTITLE_lblTitle\"]/text()')\n email = tree.xpath('//a[starts-with(@href,\"mailto:\")]/text()')\n if not name or not email:\n pass\n else:\n count = count + 1\n name = name[0]\n email = email[0]\n data = {\n 'name': name,\n 'email': email,\n 'url': profile\n }\n\n json_db(data=data)\n #list_person.append(data)\n except:\n print(f'Rompio en la pagina: {profile}')\nprint(f'Perfiles con emails: {str(count)}')\n\n#save_info(nombre='pinktherapy_resultados', extension='json', data=json.dumps(list_person))\n","repo_name":"alderetebrian/scraping","sub_path":"pinktherapy.py","file_name":"pinktherapy.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"5387352331","text":"__author__ = 'Vas Vasiliadis '\n\nimport sys\nimport time\nimport driver\nimport boto3\nfrom botocore.exceptions import ClientError\nimport os\nimport time\n\n\n# Get configuration\nfrom configparser import ConfigParser\nconfig = ConfigParser()\nconfig.read('ann_config.ini')\n\n# Import helpers.py\n# https://blog.finxter.com/python-how-to-import-modules-from-another-folder/\nhelpers_path = config.get(\"util\", \"helpers_path\")\nsys.path.append(helpers_path)\nimport helpers\n#from helpers import get_user_profile\n\n\n\"\"\"A rudimentary timer for coarse-grained profiling\n\"\"\"\nclass Timer(object):\n def __init__(self, verbose=True):\n self.verbose = verbose\n\n def __enter__(self):\n self.start = time.time()\n return self\n\n def __exit__(self, *args):\n self.end = time.time()\n self.secs = self.end - self.start\n if self.verbose:\n print(f\"Approximate runtime: {self.secs:.2f} seconds\")\n\nif __name__ == '__main__':\n # Call the AnnTools pipeline\n if len(sys.argv) > 1:\n with Timer():\n driver.run(sys.argv[1], 'vcf')\n \n # extract args from config and sys.arg\n local_path = sys.argv[1]\n root_path = sys.argv[2]\n job_id = sys.argv[4]\n user_id = sys.argv[3]\n input_file_full_name = sys.argv[5]\n input_file_name = input_file_full_name.split(\".\")[0]\n local_results_file = f\"{root_path}/{job_id}~{input_file_name}.annot.vcf\"\n local_log_file = f\"{local_path}.count.log\"\n results_bucket = config.get(\"s3\", \"bucket_results\")\n cnetid = config.get(\"prefix\", \"cnetid\")\n\n # create results and log keys\n key_results = cnetid + user_id + f\"/{job_id}~{input_file_name}\" + \".annot.vcf\"\n key_log = cnetid + user_id + f\"/{job_id}~{input_file_full_name}\" + \".count.log\"\n\n # connect to s3 and upload results/log files\n s3_client = boto3.client('s3')\n # Boto3 documentation: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-uploading-files.html\n try:\n response_results = s3_client.upload_file(local_results_file, results_bucket, key_results)\n response_log = s3_client.upload_file(local_log_file, results_bucket, key_log)\n except ClientError as e:\n print(e)\n\n # connect to dynamodb and update job item\n region = config.get(\"aws\", \"AwsRegionName\")\n table_name = config.get(\"dynamodb\", \"db\")\n table = boto3.resource(\"dynamodb\", region_name=region).Table(table_name)\n complete_time = int(time.time())\n \n # Updating DB: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.UpdateItem.html\n try:\n table.update_item(Key={\"job_id\": job_id},\n UpdateExpression= \"set job_status = :r, s3_results_bucket = :b,\\\n s3_key_result_file = :kr, s3_key_log_file = :kl, complete_time = :cl\",\n ExpressionAttributeValues={\n \":r\": \"COMPLETED\", \":b\": results_bucket, \":kr\": key_results, \n \":kl\": key_log,\":cl\": complete_time}) \n except ClientError as e:\n print(e)\n \n ### NEW CODE FOR A14 ###\n\n topic_arn = config[\"sns\"][\"archive_topic\"]\n duration = config.get(\"aws\", \"duration\")\n \n # Create archive message to pass into step function\n # First answer that formats input: https://stackoverflow.com/questions/55379944/pass-variable-into-step-function-start-execution-input-parameter\n archive_message = \"{\\\"job_id\\\": \\\"\" + job_id + \"\\\", \\\"topic_arn\\\": \\\"\" + topic_arn + \"\\\", \\\"duration\\\": \\\n \\\"\" + duration + \"\\\", \\\"user_id\\\": \\\"\" + user_id + \"\\\"}\"\n \n # Initialize step function client and start execution\n # Step Function documentation: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/stepfunctions.html#SFN.Client.start_execution\n step_function_client = boto3.client('stepfunctions', region_name=region)\n machine_arn = config.get(\"step_function\", \"state_machine_arn\")\n try:\n machine_resp = step_function_client.start_execution(\n stateMachineArn=machine_arn,\n name=job_id,\n input= archive_message\n )\n except ClientError as e:\n print(e)\n print(\"Success: Starting state machine execution\")\n\n # Delete local copies of files\n os.remove(local_results_file)\n os.remove(local_log_file)\n os.remove(local_path)\nelse:\n print(\"A valid .vcf file must be provided as input to this program.\")\n\n### EOF","repo_name":"dhariniramaswamy/cloud_computing","sub_path":"ann/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33644925394","text":"\"\"\"定时任务设置\"\"\"\nfrom pydantic import BaseModel, Extra\n\n\nclass SchedulerConfig(BaseModel, extra=Extra.ignore):\n \"\"\"定时任务相关配置\"\"\"\n announce_push_switch: bool = False # 自动获取 & 推送舟舟最新公告开关\n announce_push_interval: int = 1 # 间隔多少分钟运行一次\n\n sanity_notify_switch: bool = False # 检测理智提醒开关\n sanity_notify_interval: int = 10 # 间隔多少分钟运行一次\n\n arknights_update_check_switch: bool = True # 检测更新开关\n\n maa_copilot_switch: bool = False # 查询 MAA 作业站订阅内容开关\n maa_copilot_interval: int = 60 # 间隔多少分钟运行一次\n\n\n__all__ = [\n \"SchedulerConfig\"\n]\n","repo_name":"NumberSir/nonebot_plugin_arktools","sub_path":"nonebot_plugin_arktools/src/configs/scheduler_config.py","file_name":"scheduler_config.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"29"} +{"seq_id":"12359275576","text":"import json\nimport os\nimport io\nimport requests\nimport torch\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nfrom PIL import Image, ExifTags\n\n\nJSON_CONTENT_TYPE = 'application/json'\nJPEG_CONTENT_TYPE = 'image/jpeg'\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass Net(nn.Module):\n \"\"\"\n Neural network architecture.\n The ResNet50 model from PyTorch's vision library is used as a feature extractor.\n A fully connected layer is added on top of the extracted features to do the classification.\n \"\"\"\n def __init__(self):\n super(Net, self).__init__()\n self.model = torch.hub.load('pytorch/vision:v0.9.0', 'resnet50', pretrained=True)\n for param in self.model.parameters():\n param.requires_grad = False\n self.fc = nn.Sequential(\n nn.Linear(2048, 128),\n nn.ReLU(inplace=True),\n nn.Linear(128, 5))\n\n def forward(self, x):\n x = self.model(x)\n x = self.fc(x)\n return x\n\n\ndef model_fn(model_dir):\n \"\"\"\n Load a trained model from disk.\n \"\"\"\n model = Net().to(device)\n model.load_state_dict(torch.load(os.path.join(model_dir, 'model.pth'), map_location=device))\n model.eval()\n return model\n\n\ndef input_fn(request_body, content_type=JPEG_CONTENT_TYPE):\n \"\"\"\n Deserialize and preprocess the input data.\n \"\"\"\n if content_type == JPEG_CONTENT_TYPE:\n image = Image.open(io.BytesIO(request_body)).convert('RGB')\n for orientation in ExifTags.TAGS.keys():\n if ExifTags.TAGS[orientation] == 'Orientation':\n break\n try:\n exif = dict(image._getexif().items())\n if exif[orientation] == 3:\n image = image.rotate(180, expand=True)\n elif exif[orientation] == 6:\n image = image.rotate(270, expand=True)\n elif exif[orientation] == 8:\n image = image.rotate(90, expand=True)\n except (AttributeError, KeyError, IndexError):\n pass\n return image\n elif content_type == JSON_CONTENT_TYPE:\n url = json.loads(request_body)['url']\n img_content = requests.get(url).content\n image = Image.open(io.BytesIO(img_content)).convert('RGB')\n return image\n else:\n raise Exception('Unsupported ContentType in content_type: {}'.format(content_type))\n\n\ndef predict_fn(input_object, model):\n \"\"\"\n Run the prediction on the preprocessed input data using the loaded model.\n \"\"\"\n input_tensor = transforms.ToTensor()(input_object)\n input_tensor = transforms.Resize((224, 224))(input_tensor)\n input_tensor = input_tensor.to(device).half()\n with torch.no_grad():\n output = model(input_tensor.unsqueeze(0))\n return output.cpu().numpy().astype('float16')\n\n\ndef output_fn(predictions, content_type):\n \"\"\"\n Serialize the model predictions and set the correct MIME type for the response payload.\n \"\"\"\n if content_type == \"application/json\":\n return json.dumps(predictions.tolist())\n else:\n raise Exception('Unsupported ContentType in content_type: {}'.format(content_type))\n","repo_name":"namnd00/inventory-monitoring-distribution-centers","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"9525086289","text":"class Address:\n street_name=\"Massachusetts Ave\"\n number=77\n def __init__(self,street,num):\n self.street_name=street\n self.number=num\nclass campusaddress(Address):\n def __init__(self,officeaddress):\n self.officeaddress=officeaddress\ns1=campusaddress(\"b8-401\")\nprint(s1.officeaddress)\nprint(s1.street_name)\nprint(s1.number)","repo_name":"shabbirkhan0015/python_programs","sub_path":"inheritance3.py","file_name":"inheritance3.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"28407974208","text":"from pathlib import Path\nfrom PyPDF2 import PdfFileReader, PdfFileWriter\n\npdf_path = (\n Path.home()\n / \"Downloads\"\n / \"Data Elements.pdf\"\n # / \"Virtual CreditCard - API\"\n # / \"Django\"\n # / \"AUSFB\"\n # / \"api_app\"\n # / \"test.pdf\"\n)\n# print(pdf_path)\npdf_reader = PdfFileReader(str(pdf_path))\nlast_page = pdf_reader.pages[-1] # Reading Last-page\n\npdf_writer = PdfFileWriter()\npdf_writer.addPage(last_page)\n\noutput_path = Path.home() / \"Downloads\" / \"last_page.pdf\"\nwith output_path.open(mode=\"wb\") as output_file:\n pdf_writer.write(output_file)\n","repo_name":"Viv2905/AUSFB_DEMO","sub_path":"AUSFB/pdfConversion.py","file_name":"pdfConversion.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"24315160801","text":"\"\"\"Event related potentials - averages time locked to an event\"\"\"\n\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nimport numpy as np\n\ndef plot_erp(epochs_dict, electrode):\n #colors = {}\n #colors['wb_Diode'] = 'b'\n #colors['bw_Diode'] = 'b'\n #colors['bw_Port'] = 'g'\n #colors['wb_Port'] = 'g'\n fig, axes = plt.subplots()\n\t\n sample_duration = 1000 / 497.975590198584\n time_line = np.arange(-100, 100, 1) * sample_duration\n\t#fig2, axes2 = plt.subplots()\n for key, value in epochs_dict[electrode].items():\n #g = sns.tsplot(data=value, time = time_line, color = colors[key], condition = key, ax = axes)\n g = sns.tsplot(data=value, time = time_line, condition = key, ax = axes)\n break\n\t\t#g2 = sns.tsplot(data=value, time = np.arange(0, len(value[0,:]), 1), color = colors[key], condition = key, ax = axes2, err_style = 'unit_traces')\n\t#axes.legend()\n axes.axvline(0, linestyle = '--', c = 'black', label = 'switch')\n\n axes.set_xlabel('Millieconds from event marker')\n axes.legend()","repo_name":"ryscet/pyseries","sub_path":"pyseries/Analysis/erp.py","file_name":"erp.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"12597227591","text":"import pygame as pg\nfrom src.const import *\nfrom src.editor import NodeEditor\n\n\npg.init()\nscreen = pg.display.set_mode(WIN_SIZE)\npg.display.set_caption(\"Node Editor\")\nfont = pg.font.SysFont(\"Calibri\", 20, True, False)\n\neditor = NodeEditor(font)\n\nadd_key_text = font.render(\"Shift + A: Add Node\", True, \"snow\")\nnumber_key_text = font.render(\"Shift + N: Number Node\", True, \"snow\")\n\n\ndef main() -> None:\n mouse_vec = pg.Vector2()\n while True:\n keys = pg.key.get_pressed()\n mouse_vec.xy = pg.mouse.get_pos()\n events = pg.event.get()\n for ev in events:\n if ev.type == pg.QUIT or (ev.type == pg.KEYDOWN and ev.key == pg.K_ESCAPE):\n pg.quit()\n return\n\n screen.fill((60, 60, 60))\n\n editor.update(events, mouse_vec, keys)\n editor.draw(screen)\n\n screen.blit(add_key_text, (10, 10))\n screen.blit(number_key_text, (10, 30))\n\n pg.display.flip()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"cool-dev-guy/Node-Editor-Durk","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"72114302158","text":"URL_GATEWAY = 'amqp://localhost'\n\nQUEUES = dict(\n LIGHT_QUEUE='light',\n\n SMOKE_QUEUE='smoke',\n\n TEMPERATURE_QUEUE='temperature'\n)\n\nGATEWAY_SERVICES = dict(\n Identificate='identificate',\n ReceiveStatus='ReceiveStatus',\n EquipmentDied='EquipmentDied'\n)\n\nEquipmentType = dict(\n BOTH='BOTH',\n SENSOR='SENSOR',\n ACTUATOR='ACTUATOR'\n)\n\nStatusType = dict(\n TURN_ON_OFF='TURN_ON_OFF',\n TEMPERATURE='TEMPERATURE',\n ENV_TEMPERATURE='ENV_TEMPERATURE',\n HAVE_SMOKE='HAVE_SMOKE',\n LIGHT_VALUE='LIGHT_VALUE'\n)\n\nPORT = '5672'\n","repo_name":"castelojb/SD_Trabalho3","sub_path":"sensors/rabbitMQ/models/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1738577319","text":"def possible(build) :\r\n for x, y, a in build :\r\n if a == 0 : # 기둥\r\n if y == 0 or [x, y - 1, 0] in build or [x, y, 1] in build or [x - 1, y, 1] in build :\r\n continue\r\n return False\r\n else: # 보\r\n if [x, y - 1, 0] in build or [x + 1, y - 1, 0] in build or ([x - 1, y, 1] in build and [x + 1, y, 1] in build) :\r\n continue\r\n return False\r\n return True\r\n\r\ndef solution(n, build_frame):\r\n build = []\r\n for frame in build_frame :\r\n x, y, a, b = frame\r\n if b == 0 :\r\n build.remove([x,y,a])\r\n if not possible(build) :\r\n build.append([x,y,a])\r\n else :\r\n build.append([x,y,a])\r\n if not possible(build) :\r\n build.remove([x,y,a])\r\n\r\n return sorted(build)\r\n\r\nn = 5\r\nbuild_frame = [[1,0,0,1],[1,1,1,1],[2,1,0,1],[2,2,1,1],[5,0,0,1],[5,1,0,1],[4,2,1,1],[3,2,1,1]]\r\n# build_frame = [[0,0,0,1],[2,0,0,1],[4,0,0,1],[0,1,1,1],[1,1,1,1],[2,1,1,1],[3,1,1,1],[2,0,0,0],[1,1,1,0],[2,2,0,1]]\r\nprint(solution(n, build_frame))","repo_name":"chahyoungseok/Algorithm","sub_path":"이것이 코딩테스트다/Avatar/install pillar and floor.py","file_name":"install pillar and floor.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"25735378510","text":"# -*- coding: utf-8 -*-\n\nimport os\n\nfrom pyspark.sql import SparkSession\n\nfrom common.logger_configuration import logger\n\n\ndef main():\n logger.info(u\"Exercise\")\n\n # Create Spark Session\n spark = SparkSession.builder.appName(\"Spark Course\").getOrCreate()\n\n # Read csv\n path = os.path.join(\"data\", \"income.csv\")\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except Exception as e:\n logger.error('Failed to execute process: {}'.format(e), exc_info=True)\n","repo_name":"santifinland/CursoTecnicasAnaliticasConSpark","sub_path":"ml/exercise/read_csv.py","file_name":"read_csv.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"29"} +{"seq_id":"4214622783","text":"# -*- coding: utf-8 -*-\n#\n# 模块路由文件\n# Author:\n# Email:\n# Created Time: 2023-06-10\n# from typing import Dict\nimport logging\n\nfrom fastapi import APIRouter, Body, Depends\nfrom sqlmodel import Session, SQLModel, create_engine, select\n\nfrom .model import User\n\n# from fastapi import Depends, HTTPException\nfrom .schema import MessageResp # 通用schema\n\nengine = create_engine(\"sqlite:///./test.db\", echo=True, future=True)\nSQLModel.metadata.create_all(engine)\nrouter = APIRouter(\n # dependencies=[Depends(get_token_header)],\n # responses={404: {\"description\": \"Not found\"}},\n)\n\n\ndef get_db():\n db = Session(engine)\n try:\n yield db\n finally:\n db.close()\n\n\n@router.get(\"/\", summary=\"模块测试API\", response_model=MessageResp)\nasync def test_api():\n \"\"\"模块测试API\"\"\"\n return {\"message\": \"ok\"}\n\n\n@router.get(\"/users\", summary=\"用户列表\")\ndef get_users(db=Depends(get_db)):\n \"\"\"用户列表\"\"\"\n stat = select(User)\n user = db.exec(stat)\n return {\"users\": user.all()}\n\n\n@router.post(\"/users\", summary=\"用户列表\")\ndef create_user(user: User = Body(), db=Depends(get_db)):\n \"\"\"用户列表\"\"\"\n db.add(user)\n logging.error(user.dict())\n db.commit()\n logging.error(user.username)\n return {\"data\": user.dict()}\n","repo_name":"heyhpython/fastApiProject","sub_path":"user_module/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"41798490244","text":"import os\nimport zipfile\nimport argparse\nimport requests\n\nfrom tqdm import tqdm\n\nparser = argparse.ArgumentParser(description='Download dataset, labels, model checkpoint for StarGAN')\n\nparser.add_argument('--type', choices=['dataset', 'labels', 'checkpoint'], default='labels',\n help='Available type: dataset, labels, checkpoint')\n\nparser.add_argument('--name', metavar='N', type=str, nargs='+', choices=['celebA'], default='celebA',\n help='name of dataset to download [celebA]')\n\n\ndef download_file_from_google_drive(id, destination):\n URL = \"https://docs.google.com/uc?export=download\"\n session = requests.Session()\n\n response = session.get(URL, params={'id': id}, stream=True)\n token = get_confirm_token(response)\n\n if token:\n params = {'id': id, 'confirm': token}\n response = session.get(URL, params=params, stream=True)\n\n save_response_content(response, destination)\n\n\ndef get_confirm_token(response):\n for key, value in response.cookies.items():\n if key.startswith('download_warning'):\n return value\n return None\n\n\ndef save_response_content(response, destination, chunk_size=32 * 1024):\n total_size = int(response.headers.get('content-length', 0))\n with open(destination, \"wb\") as f:\n for chunk in tqdm(response.iter_content(chunk_size), total=total_size,\n unit='B', unit_scale=True, desc=destination):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n\n\ndef prepare_data_dir(path='./dataset'):\n if not os.path.exists(path):\n os.makedirs(path)\n\n\ndef create_dir_if_not_exists(dir_path: str):\n if not os.path.exists(dir_path):\n os.makedirs(dir_path)\n\n\ndef download_labels(dataset_name: str):\n dataset_dir = os.path.join('dataset', dataset_name)\n create_dir_if_not_exists(dataset_dir)\n\n celebA_label_file, file_id = 'list_attr_celeba.txt', '1MzjafP6o7TRVtf-_tn-q4fj6C5903uaq'\n celebA_label_file_path = os.path.join(dataset_dir, celebA_label_file)\n\n if os.path.exists(celebA_label_file_path):\n print('[*] {} already exists'.format(celebA_label_file_path))\n else:\n download_file_from_google_drive(file_id, celebA_label_file_path)\n print('[*] Download {} complete.'.format(celebA_label_file))\n\n\ndef download_checkpoint():\n file_name = \"checkpoint.zip\"\n save_path = os.path.join(\".\", file_name)\n download_file_from_google_drive(\"1ezwtU1O_rxgNXgJaHcAynVX8KjMt0Ua-\", save_path)\n\n with zipfile.ZipFile(save_path) as zf:\n zf.extractall(\".\")\n\n os.remove(save_path)\n\n\ndef download_dataset(dataset_name: str):\n if not dataset_name == 'celebA':\n return\n\n dirpath = 'dataset'\n\n data_dir = 'celebA'\n celebA_dir = os.path.join(dirpath, data_dir)\n prepare_data_dir(celebA_dir)\n\n file_name, drive_id = \"img_align_celeba.zip\", \"1S2WCmNlNC2INXy2g8qf5vqgjqYmR0wvi\"\n save_path = os.path.join(dirpath, file_name)\n\n if os.path.exists(save_path):\n print('[*] {} already exists'.format(save_path))\n else:\n download_file_from_google_drive(drive_id, save_path)\n\n with zipfile.ZipFile(save_path) as zf:\n zf.extractall(celebA_dir)\n\n # os.remove(save_path)\n os.rename(os.path.join(celebA_dir, 'img_align_celeba'), os.path.join(celebA_dir, 'train'))\n\n custom_data_dir = os.path.join(celebA_dir, 'test')\n prepare_data_dir(custom_data_dir)\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n dataset_name = args.name\n\n if args.type == 'labels':\n download_labels(dataset_name)\n\n if args.type == 'checkpoint':\n download_checkpoint()\n\n if args.type == 'dataset':\n download_dataset(dataset_name)\n","repo_name":"aartisoft/magiccam","sub_path":"Source/stargan/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10366585537","text":"import sys\nfrom itertools import combinations\n\nn = int(sys.stdin.readline())\ndata = []\nfor _ in range(n):\n data.append(list(map(int, sys.stdin.readline().split())))\n\nmember = list(range(n))\nteam_list = list(combinations(member, n//2))\ngap = 999999\n\nfor team1 in team_list:\n team2 = list(set(member) - set(team1))\n team1_pair = list(combinations(team1, 2))\n team2_pair = list(combinations(team2, 2))\n # print(f'team1:{team1_pair}, team2:{team2_pair}') # team1:[(0, 3), (0, 4), (3, 4)], team2:[(1, 2), (1, 5), (2, 5)]\n stat1 = 0\n stat2 = 0\n for i in range(len(team1_pair)):\n stat1 += (data[team1_pair[i][0]][team1_pair[i][1]] + data[team1_pair[i][1]][team1_pair[i][0]])\n stat2 += (data[team2_pair[i][0]][team2_pair[i][1]] + data[team2_pair[i][1]][team2_pair[i][0]])\n if gap > abs(stat1 - stat2):\n gap = abs(stat1 - stat2)\nprint(gap)\n\n\n","repo_name":"kma7574/Algorithm","sub_path":"Baekjoon/14889_스타트와 링크.py","file_name":"14889_스타트와 링크.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31045223310","text":"class Solution:\n def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:\n l, r1, r2, ans = -1, -1, -1, 0\n for i in range(len(nums)):\n if nums[i] > maxK or nums[i] < minK:\n l = i\n if nums[i] == minK:\n r1 = i\n if nums[i] == maxK:\n r2 = i\n ans += max(0, min(r1, r2)-l)\n return ans","repo_name":"ColdCode0214/LeetCode_local","sub_path":"2444-统计定界子数组的数目.py","file_name":"2444-统计定界子数组的数目.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"5685197197","text":"from discord.ext import commands\nfrom datetime import datetime\nimport asyncio\nfrom constants import *\n\nDEFAULT_DURATION_MINUTES = 5\n\n\nclass MudaeScheduler(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_ready(self):\n print(f\"{self.bot.user.name} has connected to Discord!\")\n\n @commands.Cog.listener()\n async def on_message(self, message):\n if not message.author.bot and message.channel.id == MUDAE_CONTROL_CHANNEL_ID:\n await self.hide_channel()\n\n @commands.Cog.listener()\n async def on_message_delete(self, message):\n if not message.author.bot and message.channel.id == MUDAE_CONTROL_CHANNEL_ID:\n await self.hide_channel()\n\n async def hide_channel(self):\n channel = self.bot.get_channel(MUDAE_CONTROL_CHANNEL_ID)\n guild = channel.guild\n default_role = guild.default_role\n await channel.set_permissions(default_role, view_channel=False)\n self.bot.loop.create_task(self.restore_channel_visibility())\n\n async def restore_channel_visibility(self):\n \"\"\"Task to restore channel visibility after DEFAULT_DURATION_MINUTES.\"\"\"\n await asyncio.sleep(DEFAULT_DURATION_MINUTES * 60)\n channel = self.bot.get_channel(MUDAE_CONTROL_CHANNEL_ID)\n await channel.set_permissions(channel.guild.default_role, view_channel=True)\n print(f\"Channel visibility restored in {channel.name} at {datetime.now()}\")\n\n\nasync def setup(bot):\n await bot.add_cog(MudaeScheduler(bot))\n","repo_name":"Gstarmix/Divers-Bot-Discord","sub_path":"extensions/channel_visibility_manager.py","file_name":"channel_visibility_manager.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"11471623991","text":"# -*- coding: utf-8 -*-\n\"\"\"\nPlot of a spectrum of two charged dipoles.\n\"\"\"\nimport matplotlib.pyplot as plt\nfrom os.path import expanduser\nimport numpy as np\nimport sys\nsys.path.insert(0, expanduser('~')+'/ions/lib')\nfrom label_lines import *\n\n# latex font \nplt.rcParams.update({'font.size': 22})\nplt.rcParams.update({'font.family': 'serif'})\nplt.rcParams.update({'text.usetex': True})\n\n# =============================================================================\n# Universal set of functions which serve to read the program oputput and \n# prepare it for plotting\n# =============================================================================\ndef get_value(file, name):\n for line in file:\n if line[0] == '#':\n content = line.split()\n if content[1] == name+\":\":\n file.seek(0)\n return float(content[2])\n\ndef get_basis_truncation(file):\n truncation = {}\n for line in file:\n if line[0] == '#':\n content = line.split()\n if content[1] == 'Basis' and content[2] == 'truncation:':\n file.seek(0)\n # content[3] = \"|n1,n3,n5;j1,j2>\"\n data = content[3][1:-1]\n data = data.split(',')\n truncation['n1'] = int(data[0])\n truncation['n3'] = int(data[1])\n subdata = data[2].split(';')\n truncation['n5'] = int(subdata[0])\n truncation['j1'] = int(subdata[1])\n truncation['j2'] = int(data[3])\n return truncation\n\ndef get_descriptors(f):\n pack = {}\n pack['mass'] = get_value(f, 'mass')\n pack['charge'] = get_value(f, 'charge')\n pack['dipole'] = get_value(f, 'dipole')\n pack['B'] = get_value(f, 'B')\n pack['omega_rho'] = get_value(f, 'omega_rho')\n pack['omega_z'] = get_value(f, 'omega_z')\n pack['basis_truncation'] = get_basis_truncation(f)\n \n return pack\n\ndef get_spectrum(f):\n for line in f:\n if line[0] == '#' or line [0] == ' ' :\n content = line.split()\n if content[1] == '100' and content[2] == 'smallest' and\\\n content[3] == 'eigenvalues':\n eigenvalues = f.readline()\n f.seek(0)\n spectrum = [float(i) for i in eigenvalues.split()]\n return spectrum\n \n\ndef get_dataset(filenames, path):\n dataset = []\n \n for name in filenames:\n f = open(path+name, \"r\")\n if f.mode != \"r\":\n print(\"Problem with readipoleding \"+name+\".\\n\")\n continue\n \n descriptors = get_descriptors(f) \n spectrum = get_spectrum(f)\n f.close()\n dataset += [[descriptors,spectrum]]\n\n # integrity tests\n # checks if all spectrums have the same number of elements\n spectrum_length = len(dataset[0][1])\n for d in dataset:\n if len(d[1]) != spectrum_length:\n print(\"Error!\")\n print(\"Not all spectra have the same length.\")\n print(\"The different element is:\")\n print(d[0])\n exit( 0 )\n \n return dataset\n\ndef get_dipole(data):\n return data[0]['dipole']\n\ndef get_omega_z(data):\n return data[0]['omega_z']\n\ndef get_omega_rho(data):\n return data[0]['omega_rho']\n\ndef get_n3_truncations(data):\n return data[0]['basis_truncation']['n3']\n\n# =============================================================================\n# Plotting functions\n# =============================================================================\ndef get_truncation_string(dataset):\n# I skip here n_3/5 as it is the variable of the model\n truncation = dataset[0][0]['basis_truncation']\n n1 = truncation['n1']\n j1 = truncation['j1']\n out_string = f\"$n_1 = {n1}$\"+\", $j_{1/2} = $\"+f\"${j1}$\"\n return out_string\n\ndef get_parameters_string(dataset):\n omega_z = get_omega_z(dataset[0])\n omega_rho = get_omega_rho(dataset[0])\n out_string = f\"$\\omega_z = {omega_z}$ MHz, \"+\\\n f\"$\\omega_\\\\rho = {omega_rho}$ MHz\"\n return out_string\n\n\ndef change_of_energy_levels(dataset, lvl=10):\n ns = []\n spectra = []\n \n energy0 = dataset[0][1][0:lvl]\n for data in dataset:\n ns += [ get_n3_truncations(data) ]\n omegaz = get_omega_z(data)\n omega1 = omegaz*np.sqrt(3)\n omega1_2pi = omega1/2/np.pi\n MHzTOkHz = 1e3\n spectra += [ [(data[1][i] - energy0[i])*omega1_2pi*MHzTOkHz\n for i in range(lvl)] ]\n \n # present result\n for i in range(lvl):\n plt.plot(ns, [ sp[i] for sp in spectra ], label=f\"{i}\" )\n plt.title(\"Energy levels of SrYb, relative changes\\n\"+\n get_parameters_string(dataset)+\n \", \"+get_truncation_string(dataset))\n plt.xlabel(\"$n_3$ truncation\")\n plt.ylabel(\"$\\\\frac{E_{i}(5) - E_i(n_3)}{2\\pi\\hbar}$ (kHz)\")\n labelLines(plt.gca().get_lines(),zorder=2.5)\n return 0\n\n\n# =============================================================================\n# Main\n# =============================================================================\ndef main(): \n home = expanduser(\"~\")\n path = home+'/ions/SrYb/05.28-accuracy/'\n ns = np.arange(4)+5\n filenamesA = ['SrYb_n1_34_n35_'+str(n)+'_j1.out' for n in ns]\n dataset = get_dataset(filenamesA, path)\n dataset.sort(key=get_dipole)\n change_of_energy_levels(dataset, 10)\n\n return 0\n \nif __name__ == '__main__':\n main()","repo_name":"RoslawSzaybo/dipolar-ions","sub_path":"SrYb/05.28-accuracy/plot/n3.py","file_name":"n3.py","file_ext":"py","file_size_in_byte":5448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26751657817","text":"'''\nTHE DATA SERVER PROBLEM\nVersion A: Solving the problem using a condition variable\n'''\n\nfrom dataclasses import dataclass\nimport time\nimport threading\n\n\n\n@dataclass\nclass Counter:\n value: int = 0\n cond: threading.Condition = threading.Condition()\n\n\n\ndef check_auth_user():\n print('[ Auth ] Start')\n # Send request to authenticator, check permissions, encrypt, decrypt...\n time.sleep(20)\n print('[ Auth ] Done')\n\n\n\ndef process_files(lst_file_name: list[str], counter: Counter):\n for file_name in lst_file_name:\n # Read file\n print('[ ReadFile ] Start', file_name)\n time.sleep(10)\n print('[ ReadFile ] Done ', file_name)\n\n with counter.cond:\n counter.value -= 1\n counter.cond.notify()\n\n # Write log into disk\n time.sleep(5)\n print('[ WriteLog ]')\n\n\n\ndef process_request():\n lst_file_name = [ 'foo.html', 'bar.json' ]\n counter = Counter(value=len(lst_file_name))\n\n # The server checks auth user while reading files, concurrently\n threading.Thread(target=process_files, args=(lst_file_name, counter)).start()\n check_auth_user()\n\n # The server waits for completion of loading files\n with counter.cond:\n while counter.value > 0:\n counter.cond.wait(10) # timeout = 10 seconds\n\n print('\\nNow user is authorized and files are loaded')\n print('Do other tasks...\\n')\n\n\n\nprocess_request()\n","repo_name":"thanhit95/multi-threading","sub_path":"python/exer07a_data_server.py","file_name":"exer07a_data_server.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"29"} +{"seq_id":"19259903074","text":"import time\nimport unittest\nfrom unittest.mock import patch, Mock\n\nfrom numaprom.watcher import ConfigManager\nfrom tests import mock_configs\n\n\n@patch.object(ConfigManager, \"load_configs\", Mock(return_value=mock_configs()))\nclass TestConfigManager(unittest.TestCase):\n @classmethod\n def setUpClass(cls) -> None:\n cls.cm = ConfigManager()\n cls.payload = {\"name\": \"rollout_latency\", \"namespace\": \"sandbox_numalogic_demo1\"}\n cls.argocd_payload = {\n \"name\": \"namespace_app_http_server_requests_error_rate\",\n \"namespace\": \"abc\",\n }\n cls.rollouts_payload = {\n \"name\": \"namespace_app_rollouts_http_request_error_rate\",\n \"namespace\": \"abc\",\n }\n cls.random_payload = {\"name\": \"random\", \"namespace\": \"abc\"}\n\n def setUp(self) -> None:\n self.cm.get_app_config.cache_clear()\n\n def test_update_configs(self):\n config = self.cm.update_configs()\n self.assertTrue(len(config), 3)\n\n def test_load_configs(self):\n app_configs, default_configs, default_numalogic, pipeline_config = self.cm.load_configs()\n print(type(app_configs))\n print(type(default_configs))\n\n def test_get_app_config(self):\n # from given config\n app_config = self.cm.get_app_config(\n metric=self.payload[\"name\"], namespace=self.payload[\"namespace\"]\n )\n self.assertTrue(app_config)\n self.assertEqual(app_config.namespace, \"sandbox_numalogic_demo1\")\n\n # from given default config\n app_config = self.cm.get_app_config(\n metric=self.rollouts_payload[\"name\"], namespace=self.rollouts_payload[\"namespace\"]\n )\n self.assertTrue(app_config)\n self.assertEqual(app_config.namespace, \"default-argorollouts\")\n\n app_config = self.cm.get_app_config(\n metric=self.argocd_payload[\"name\"], namespace=self.argocd_payload[\"namespace\"]\n )\n self.assertTrue(app_config)\n self.assertEqual(app_config.namespace, \"default-argocd\")\n\n # default config\n service_config = self.cm.get_app_config(\n metric=self.random_payload[\"name\"], namespace=self.random_payload[\"namespace\"]\n )\n self.assertTrue(service_config)\n self.assertEqual(service_config.namespace, \"default\")\n\n def test_get_metric_config(self):\n # from given config\n metric_config = self.cm.get_metric_config(self.payload)\n self.assertTrue(metric_config)\n self.assertEqual(metric_config.metric, \"rollout_latency\")\n\n # from given default config\n metric_config = self.cm.get_metric_config(self.rollouts_payload)\n self.assertTrue(metric_config)\n self.assertEqual(metric_config.metric, \"namespace_app_rollouts_http_request_error_rate\")\n\n # default config\n metric_config = self.cm.get_metric_config(self.random_payload)\n self.assertTrue(metric_config)\n self.assertEqual(metric_config.metric, \"default\")\n\n def test_get_unified_config(self):\n # from given config\n unified_config = self.cm.get_unified_config(self.payload)\n self.assertTrue(unified_config)\n self.assertTrue(\"rollout_latency\" in unified_config.unified_metrics)\n\n # from given default config\n unified_config = self.cm.get_unified_config(self.rollouts_payload)\n self.assertTrue(unified_config)\n self.assertTrue(\n \"namespace_app_rollouts_http_request_error_rate\" in unified_config.unified_metrics\n )\n\n # default config - will not have unified config\n unified_config = self.cm.get_unified_config(self.random_payload)\n self.assertFalse(unified_config)\n\n def test_get_app_config_time(self):\n _start_time = time.perf_counter()\n ConfigManager().get_app_config(\n metric=self.payload[\"name\"], namespace=self.payload[\"namespace\"]\n )\n time1 = time.perf_counter() - _start_time\n self.assertTrue(ConfigManager().get_app_config.cache_info().currsize >= 1)\n _start_time = time.perf_counter()\n ConfigManager().get_app_config(\n metric=self.payload[\"name\"], namespace=self.payload[\"namespace\"]\n )\n time2 = time.perf_counter() - _start_time\n _start_time = time.perf_counter()\n self.assertTrue(ConfigManager().get_app_config.cache_info().hits >= 1)\n self.assertTrue(time2 <= time1)\n\n def test_get_metric_config_time(self):\n _start_time = time.perf_counter()\n ConfigManager().get_metric_config(self.payload)\n time1 = time.perf_counter() - _start_time\n _start_time = time.perf_counter()\n ConfigManager().get_metric_config(self.payload)\n time2 = time.perf_counter() - _start_time\n self.assertTrue(time2 <= time1)\n\n def test_get_unified_config_time(self):\n _start_time = time.perf_counter()\n ConfigManager().get_unified_config(self.payload)\n time1 = time.perf_counter() - _start_time\n _start_time = time.perf_counter()\n ConfigManager().get_unified_config(self.payload)\n time2 = time.perf_counter() - _start_time\n self.assertTrue(time2 < time1)\n","repo_name":"numaproj/numalogic-prometheus","sub_path":"tests/test_watcher.py","file_name":"test_watcher.py","file_ext":"py","file_size_in_byte":5181,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"29"} +{"seq_id":"27503625802","text":"from .car import Car\n\nclass Sink:\n def __init__(self):\n self.queue = []\n\n\n def moveCarsTo(self, newCar):\n if newCar is not None:\n self.queue.append(newCar)\n return None\n \n def getStuff(self):\n totalTime = 0\n for car in self.queue:\n totalTime += car.getTotalTime()\n l = len(self.queue)\n if l == 0:\n return [0,0]\n return [l, int(totalTime/l)]\n\n def __str__(self):\n totalTime = 0\n for car in self.queue:\n totalTime += car.getTotalTime()\n l = len(self.queue)\n if l == 0:\n return '0'\n return str(totalTime/l) + \" Cars: \" + str(l)","repo_name":"SeanSutherland/MTHE-493-TrafficLights","sub_path":"tools/sink.py","file_name":"sink.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"7279977222","text":"import datetime\nimport math\nimport os\nimport re\nimport logging\nfrom typing import Dict, List, Optional, Tuple, Union\nimport mailbox\nfrom mailbox import mboxMessage\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\nfrom bigbang.config import CONFIG\n\nfilepath_auth = CONFIG.config_path + \"authentication.yaml\"\ndirectory_project = str(Path(os.path.abspath(__file__)).parent.parent)\nlogging.basicConfig(\n filename=directory_project + \"/listserv.log\",\n filemode=\"w\",\n level=logging.INFO,\n format=\"%(asctime)s %(message)s\",\n)\nlogger = logging.getLogger(__name__)\n\n\ndef get_index_of_msgs_with_subject(\n df: pd.DataFrame,\n return_boolmask: bool = False,\n) -> np.array:\n boolmask = np.array(\n [\n True if (isinstance(sb, str)) and not pd.isna(sb) else False\n for sb in df.loc[:, \"subject\"].values\n ],\n dtype=\"bool\",\n )\n index = np.arange(len(boolmask))[boolmask]\n if return_boolmask:\n return boolmask\n else:\n index = df.loc[boolmask].index.values\n return index\n\n\ndef get_index_of_msgs_with_datetime(\n df: pd.DataFrame,\n return_boolmask: bool = False,\n) -> np.array:\n cond = lambda x: (\n True\n if (isinstance(x, str) and (len(x) > 10))\n or isinstance(x, datetime.datetime)\n and not pd.isna(x)\n else False\n )\n boolmask = np.array([cond(dt) for dt in df.loc[:, \"date\"].values], dtype=\"bool\")\n if return_boolmask:\n return boolmask\n else:\n index = df.loc[boolmask].index.values\n return index\n\n\ndef clean_addresses(df: pd.DataFrame) -> pd.DataFrame:\n index = np.array(\n [\n True if (isinstance(sb, str)) and not pd.isna(sb) else False\n for sb in df.loc[:, \"from\"].values\n ],\n dtype=\"bool\",\n )\n # 1 remove multiple white spaces\n # 2 remove leading and trailing white spaces\n # 3 all characters in lower case\n # 4 remove apostrophes and commas as they are not allowed in an atom- or obs-phrase\n df.loc[index, \"from\"] = [\n re.sub(\" +\", \" \", adrs).strip().lower().replace('\"', \"\").replace(\",\", \"\")\n for adrs in df.loc[index, \"from\"].values\n ]\n index = np.array(\n [\n True if (isinstance(sb, str)) and not pd.isna(sb) else False\n for sb in df.loc[:, \"comments-to\"].values\n ],\n dtype=\"bool\",\n )\n # 1 remove multiple white spaces\n # 2 remove leading and trailing white spaces\n # 3 all characters in lower case\n # 4 remove apostrophes and commas as they are not allowed in an atom- or obs-phrase\n df.loc[index, \"comments-to\"] = [\n re.sub(\" +\", \" \", adrs).strip().lower().replace('\"', \"\").replace(\",\", \"\")\n for adrs in df.loc[index, \"comments-to\"].values\n ]\n return df\n\n\ndef clean_subject(df: pd.DataFrame) -> pd.DataFrame:\n index = get_index_of_msgs_with_subject(df)\n # remove leading and trailing apostrophe\n # TODO: this step should not be necessary if it is corrected for in\n # bigbang.listserv.ListservMessageParser\n df.loc[index, \"subject\"] = [\n re.match(r\"^(?:')(.*)(?:')$\", sb)[1]\n if re.match(r\"^(?:')(.*)(?:')$\", sb) is not None\n else sb\n for sb in df.loc[index, \"subject\"].values\n ]\n # remove multiple spaces in string\n df.loc[index, \"subject\"] = [\n re.sub(\" +\", \" \", sb) for sb in df.loc[index, \"subject\"].values\n ]\n return df\n\n\ndef clean_datetime(df: pd.DataFrame) -> pd.DataFrame:\n # filter out messages with unrecognisable datetime\n index = get_index_of_msgs_with_datetime(df)\n # convert data type from string to datetime.datetime object\n df.loc[index, \"date\"] = [\n datetime.datetime.strptime(dt, \"%a, %d %b %Y %H:%M:%S %z\")\n for dt in df.loc[index, \"date\"].values\n ]\n return df\n\n\nemail_regex = r\"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+\"\ndomain_regex = r\"[@]([a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+)$\"\n\n\ndef extract_email(from_field):\n \"\"\"\n Returns an email address from a string.\n \"\"\"\n match = re.search(email_regex, from_field)\n\n if match is not None:\n return match[0].lower()\n\n else:\n return None\n\n\ndef extract_domain(from_field):\n \"\"\"\n Returns the domain of an email address from a string.\n \"\"\"\n match = re.search(email_regex, from_field)\n\n if match is not None:\n return re.search(domain_regex, match[0])[1]\n\n else:\n return None\n\n\ndef domain_entropy(domain, froms):\n \"\"\"\n Compute the entropy of the distribution of counts of email prefixes\n within the given archive.\n\n Parameters\n ---------------\n\n domain: string\n An email domain\n\n froms: pandas.DataFrame\n A pandas.DataFrame with From fields, email address, and domains.\n See the Archive method ``get_froms()``\n\n\n Returns\n --------\n\n entropy: float\n \"\"\"\n\n domain_messages = froms[froms[\"domain\"] == domain]\n\n n_D = domain_messages.shape[0]\n\n entropy = 0\n\n emails = domain_messages[\"email\"].unique()\n\n for em in emails:\n em_messages = domain_messages[domain_messages[\"email\"] == em]\n n_e = em_messages.shape[0]\n\n p_em = float(n_e) / n_D\n\n entropy = entropy - p_em * math.log(p_em)\n\n return entropy\n","repo_name":"datactive/bigbang","sub_path":"bigbang/analysis/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5252,"program_lang":"python","lang":"en","doc_type":"code","stars":139,"dataset":"github-code","pt":"29"} +{"seq_id":"71141089999","text":"from odoo import fields, models\n\n\nclass PurchaseOrderLine(models.Model):\n _inherit = \"purchase.order.line\"\n\n procurement_group_id = fields.Many2one(\"procurement.group\")\n\n def _find_candidate(\n self,\n product_id,\n product_qty,\n product_uom,\n location_id,\n name,\n origin,\n company_id,\n values,\n ):\n \"\"\"Do not merge PO lines if procurement group is different or not set.\"\"\"\n _self = self\n if \"group_id\" in values:\n pg_id = values.get(\"group_id\", False)\n if pg_id:\n pg_id = pg_id.id\n _self = self.filtered(lambda l: l.procurement_group_id.id == pg_id)\n return super(PurchaseOrderLine, _self)._find_candidate(\n product_id=product_id,\n product_qty=product_qty,\n product_uom=product_uom,\n location_id=location_id,\n name=name,\n origin=origin,\n company_id=company_id,\n values=values,\n )\n\n def _prepare_stock_moves(self, picking):\n res = super()._prepare_stock_moves(picking)\n if res and res[0] and \"group_id\" in res[0]:\n res[0][\"group_id\"] = (\n self.procurement_group_id.id or self.order_id.group_id.id\n )\n return res\n\n def _prepare_purchase_order_line_from_procurement(\n self, product_id, product_qty, product_uom, company_id, values, po\n ):\n \"\"\"Add procurement group to values\"\"\"\n res = super()._prepare_purchase_order_line_from_procurement(\n product_id, product_qty, product_uom, company_id, values, po\n )\n procurement_group = values.get(\"group_id\")\n if procurement_group:\n res[\"procurement_group_id\"] = procurement_group.id\n return res\n","repo_name":"OCA/purchase-workflow","sub_path":"purchase_line_procurement_group/models/purchase_order_line.py","file_name":"purchase_order_line.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"29"} +{"seq_id":"9858500934","text":"\"\"\"\nDjango settings for uno project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\n # Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\n#BASE_DIR = os.path.dirname(os.path.abspath(__file__))\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '*r_wm+f4_23%ax74%cyv9)%xf)iu1*!riw+$#aoa6qd=%=wpi_'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n 'django_markdown',\n 'main',\n 'gammaworks',\n 'gallery',\n 'storages',\n# 'lockdown',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n# 'lockdown.middleware.LockdownMiddleware',\n)\n\nROOT_URLCONF = 'uno.urls'\n\nWSGI_APPLICATION = 'uno.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.7/howto/static-files/\nSTATIC_ROOT = 'staticfiles'\n#STATIC_URL = '/static/'\nTEMPLATE_DIRS = (os.path.join(BASE_DIR, \"templates\"), )\nSTATICFILES_DIRS = (os.path.join(BASE_DIR, \"static\"), )\n\nDISQUS_WEBSITE_SHORTNAME = 'legionsofthought'\nDISQUS_API_KEY ='8YszMzg4SnmBWr2QiSbZIfhkH45o9UH7tSctUTnSPt2fyZpvmpED3HRDtMFGaMjd'\n\n##################HEROKU CONFIGURATION#################\n\n# Parse database configuration from $DATABASE_URL\n#import dj_database_url\n#DATABASES['default'] = dj_database_url.config()\n\n# Honor the 'X-Forwarded-Proto' header for request.is_secure()\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n# Allow all host headers\nALLOWED_HOSTS = ['*']\n\n# Static asset configuration\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n)\nSTATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'\n\n#Google analytics\nGOOGLE_ANALYTICS_PROPERTY_ID = 'UA-58541176-1'\nGOOGLE_ANALYTICS_DOMAIN = 'legionsofthought.com'\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'uno.context_processors.google_analytics',\n)\n\n#AWS S3 storage\nAWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']\nAWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']\nAWS_STORAGE_BUCKET_NAME = os.environ['S3_BUCKET_NAME']\nMEDIA_URL = 'http://s3.amazonaws.com/'+AWS_STORAGE_BUCKET_NAME+'/pics/' \nDEFAULT_FILE_STORAGE = \"storages.backends.s3boto.S3BotoStorage\"\n\n#Django Lockdown\n#LOCKDOWN_PASSWORDS = ('101legion101')\n","repo_name":"arjunrao87/legions-of-thought","sub_path":"uno/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"76668323","text":"#! /usr/bin/python3\n# @author Juan Cruz Mateos\nimport os\nimport re\nimport csv\n\n\ndef write_to_csv(filename: str, table: list, *titles: str):\n with open(filename, \"w\") as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(titles)\n for row in table:\n writer.writerow(row)\n\n\ndef print_table(title: str, table: list, *titles: str):\n print(title)\n count = 1\n print(\"|\", end=\"\")\n for tit in titles:\n print(f\"{tit:^20s}|\", end=\"\")\n count += 21\n print()\n print(\"-\" * count)\n for row in table:\n print(\"|\", end=\"\")\n for item in row:\n print(f\"{str(item):^20s}|\", end=\"\")\n print()\n print()\n\n\ndef parseo(base_path=\"./\") -> tuple:\n \"\"\"Retorna una tupla con dos elementos: t[0] = dict(id_doc, file); t[1] tuplas con los valores (palabra, id_doc)\"\"\"\n files_dic = {}\n parsed = []\n txt_files = []\n for root, _, files in os.walk(base_path):\n for file in files:\n if file[-4:] == \".txt\":\n full_path = os.path.join(root, file)\n txt_files.append(full_path)\n print(f\"{len(txt_files)} archivo(s) encontrado(s)\")\n if len(txt_files) > 0:\n print(\"Parseando...\", end=\"\")\n id_doc = 1\n for file in txt_files:\n files_dic[id_doc] = file\n with open(file, \"rt\") as txt:\n palabras = txt.read().split()\n procesadas = [re.sub(\"[\\W_]+\", \"\", palabra).lower()\n for palabra in palabras]\n for palabra in procesadas:\n parsed.append((palabra, id_doc))\n id_doc += 1\n print(\" 100% listo\")\n return files_dic, parsed\n\n\ndef ordenamiento(parsed: list) -> list:\n \"\"\"Retorna una lista de tuplas con los valores (palabra, id_doc) ordenada por palabra\"\"\"\n print(\"Ordenando... 100% listo\")\n return sorted(parsed, key=lambda palabra: palabra[0])\n\n\ndef agrupamiento(ordenado: list):\n \"\"\"Retorna una lista de tuplas con los valores (palabra, id_doc, frec)\"\"\"\n print(\"Agrupando...\", end=\"\")\n agrupado = []\n i = 0\n cant = 1\n while i < len(ordenado) - 1:\n if ordenado[i][0] == ordenado[i+1][0] and ordenado[i][1] == ordenado[i+1][1]:\n cant += 1\n else:\n agrupado.append((ordenado[i][0], ordenado[i][1], cant))\n cant = 1\n i += 1\n agrupado.append((ordenado[i][0], ordenado[i][1], cant))\n print(\" 100% listo\")\n return agrupado\n\n\ndef dic_posting(agrupado: list) -> tuple:\n \"\"\"Retona una tupla: (diccionario, posting) como listas -> para imprimier: sino usar dict\"\"\"\n print(\"Generando diccionario y posteando...\", end=\"\")\n dic = []\n post = []\n\n i = 0\n rr = 0\n rr_ptr = rr\n frec_tot = 0\n while i < len(agrupado) - 1:\n frec_tot += agrupado[i][2]\n if agrupado[i][0] == agrupado[i+1][0]:\n post.append((rr, agrupado[i][1], agrupado[i][2], rr + 1))\n # post[rr] = (agrupado[i][1], agrupado[i][2], rr + 1)\n rr += 1\n else:\n post.append((rr, agrupado[i][1], agrupado[i][2], -1))\n # post[rr] = (agrupado[i][1], agrupado[i][2], -1)\n dic.append((agrupado[i][0], agrupado[i][1], frec_tot, rr_ptr))\n # dic[agrupado[i][0]] = (agrupado[i][1], frec_tot, rr_ptr)\n rr += 1\n rr_ptr = rr\n frec_tot = 0\n i += 1\n if frec_tot == 0:\n frec_tot = agrupado[i][2]\n post.append((rr, agrupado[i][1], agrupado[i][2], -1))\n # post[rr] = (agrupado[i][1], agrupado[i][2], -1)\n dic.append((agrupado[i][0], agrupado[i][1], frec_tot, rr_ptr))\n print(\" 100% listo\\n\")\n return dic, post\n\n\ndef buscar(palabra: str, dic: list, post: list, files_id: list):\n i = 0\n while i < len(dic) and dic[i][0] != palabra:\n i += 1\n if i == len(dic):\n print(\"no hay coincidencias\")\n else:\n index = dic[i][3]\n while index != -1:\n _, d, f, index = post[index]\n print(f\"Encontrada en el archivo:{files_id[d]}, {f} veces.\")\n\n\ndef main(args):\n base = \"./\" if len(args) == 1 else args[1]\n files_id, parsed = parseo(base)\n # print_table(\"Parseo\", parsed, \"Termino\", \"D#\")\n # write_to_csv(\"parseo.csv\", parsed, \"Termino\", \"D#\")\n\n if len(files_id) > 0:\n ordered = ordenamiento(parsed)\n # print_table(\"Ordenamiento\", ordered, \"Termino\", \"D#\")\n # write_to_csv(\"ordenamiento.csv\", ordered, \"Termino\", \"D#\")\n\n grouped = agrupamiento(ordered)\n # print_table(\"Agrupamiento\", grouped, \"Termino\", \"D#\", \"F#\")\n # write_to_csv(\"agrupamiento.csv\", grouped, \"Termino\", \"D#\", \"F#\")\n\n dic, pos = dic_posting(grouped)\n # print_table(\"Diccionario\", dic, \"Termino\", \"TD#\", \"FT#\", \"#RR\")\n # write_to_csv(\"diccionario.csv\", dic, \"Termino\", \"TD#\", \"FT#\", \"#RR\")\n # print_table(\"Posting\", pos, \"#RR\", \"D#\", \"F#\", \"#PR\")\n # write_to_csv(\"posting.csv\", pos, \"#RR\", \"D#\", \"F#\", \"#PR\")\n\n res = 'y'\n while res == 'y':\n ask = input(\"palabra = \")\n buscar(ask, dic, pos, files_id)\n res = input(\"\\nBuscar otra palabra? (y/n) \")\n\n\nif __name__ == \"__main__\":\n import sys\n main(sys.argv)\n","repo_name":"JuanCruzMateos/OrgaDeDatos","sub_path":"Practica/Guia05/src/motor-poadp/motor.py","file_name":"motor.py","file_ext":"py","file_size_in_byte":5242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"41891801039","text":"#Keziah May\n#05/04/18\n#Assignment 4\n#CSC110\n\n######QUESTION TO DR.BODINE! Does this need to write to a file? question source(rubric)\n#This is a program that computes\n#the sum of the squares of numbers read from a file.\n\ndef main():\n #Explain the program function and parameters to the user\n print(\"This program computes the sum of the\")\n print(\"squares of numbers read from a file.\")\n print()\n print(\"NOTE: This file must be formatted such that\")\n print(\"each number is entered on a separate line.\")\n print()\n\n #Open file to read\n fname = input(\"Which file would you like me to process for you? \")\n print()\n infile = open(fname, \"r\")\n \n #Read File\n strList = infile.readlines()\n for line in range(len(strList)):\n strList[line] = strList[line].rstrip() #Remove '\\n' from each index\n\n #process file\n nums = toNumbers(strList) #convert string list to number list\n squares = squareEach(nums) #convert number list to squares of number list\n thesum = sumList(squares) #Find sum of squares of number list\n\n #Give result to user\n print(\"The sum of the squares of the numbers\")\n print(\"provided in the file \\\"\" + fname + \"\\\" is: \",thesum)\n \n #Close file\n infile.close()\n\n#A function that modifies a list (nums) of numbers by squaring each entry.\ndef squareEach(nums): \n for i in range(len(nums)):\n nums[i] = nums[i]**2 #modify list\n return nums #return modified list\n\n#A function that retutns the sum of a list (nums) of numbers.\ndef sumList(nums):\n thesum = 0\n for i in nums:\n thesum = i + thesum #Add values\n return thesum #Return final sum\n\n#A function that modifies a list (strList) of strings\n#(that represent numbers) into the same list of numbers.\ndef toNumbers(strList):\n for i in range(len(strList)):\n strList[i] = eval(strList[i])\n return strList\n \nmain()\n","repo_name":"MayKeziah/CSC110","sub_path":"assn4.py","file_name":"assn4.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"22207532353","text":"from rest_framework import serializers\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.generics import ListCreateAPIView, RetrieveAPIView, CreateAPIView, ListAPIView, RetrieveUpdateDestroyAPIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.permissions import IsAuthenticated\nfrom drf_yasg.utils import swagger_auto_schema\nfrom password_generator import PasswordGenerator\nfrom authentication.models import User\nfrom utils.permissions import IsPoliticianAdmin, IsCampaignManager, IsAgent\nfrom subject.models import Subject, County, SubCounty, Constituency, Ward, Location, PollingStation, Candidate\nfrom subject.serializers import SubjectSerializer, CountySerializer, CountyCreateSerializer, SubCountySerializer, SubCountyCreateSerializer, ConstituencySerializer, ConstituencyCreateSerializer, WardSerializer, WardCreateSerializer, LocationSerializer, LocationCreateSerializer, SubLocationSerializer, SubLocationCreateSerializer, PollingStationSerializer, PollingStationCreateSerializer, CandidateSerializer, CandidateCreateSerializer, CommonUserSerializer\n\n\nclass SubjectCreateListAPIView(ListCreateAPIView):\n serializer_class = SubjectSerializer\n permission_classes = (IsAuthenticated, IsAgent, IsCampaignManager, IsPoliticianAdmin)\n\n @swagger_auto_schema(operation_id=\"list_subjects\")\n def get_queryset(self):\n return Subject.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"create_subject\")\n def post(self, request, *args, **kwargs):\n data = request.data\n\n serializer = self.serializer_class(data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n data = serializer.data\n response = {\n \"subject\": data,\n \"message\": \"subject created successfully\"\n }\n\n return Response(response, status=status.HTTP_200_OK)\n\n\nclass SubjectDetailAPIView(RetrieveUpdateDestroyAPIView):\n serializer_class = SubjectSerializer\n lookup_field = 'un_id'\n permission_classes = (IsAuthenticated, IsPoliticianAdmin, IsCampaignManager)\n\n def get_queryset(self):\n \"\"\" \n return a different queryset depending on who is logged in\n \"\"\"\n\n return Subject.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"subject_detail\")\n def get(self, request, un_id):\n subject = self.get_object()\n serializer = self.serializer_class(\n subject\n )\n response = {\n \"data\": {\n \"subject\": serializer.data\n }\n }\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"update_subject_detail\")\n def update(self, request, un_id):\n subject = self.get_object()\n serializer = self.serializer_class(\n subject, data=request.data\n )\n serializer.is_valid(raise_exception=True)\n serializer.save()\n response = {\n \"data\": {\n \"subject\": dict(serializer.data),\n \"message\": \"subject updated successfully\"\n }\n }\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"destory_subject_detail\")\n def destroy(self, request, un_id):\n subject = self.get_object()\n subject.soft_delete()\n subject.is_deleted = True\n subject.save()\n\n response = {\n \"data\": {\n \"message\": \"subject deleted successfully\"\n }\n }\n return Response(response, status=status.HTTP_200_OK)\n\n\nclass CountyCreateListAPIView(ListAPIView):\n \"\"\" list counties\"\"\"\n serializer_class = CountySerializer\n\n @swagger_auto_schema(operation_id=\"list_counties\")\n def get_queryset(self):\n \"\"\" list counties \"\"\"\n return County.active_objects.all_objects()\n\n\nclass CountyCreateAPIView(CreateAPIView):\n \"\"\" create for counties \"\"\"\n serializer_class = CountyCreateSerializer\n\n @swagger_auto_schema(operation_id=\"create_county\")\n def post(self, request):\n\n data = request.data\n serializer = self.serializer_class(data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n data = serializer.data\n\n return Response(data)\n\n\nclass CountyRetrieveUpdateDestroyAPIVIew(RetrieveUpdateDestroyAPIView):\n \"\"\" retrieve and act on counties \"\"\"\n serializer_class = CountySerializer\n lookup_field = 'un_id'\n\n def get_queryset(self):\n \"\"\" return a specified queryset depending on the user \"\"\"\n return County.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"update_county_details\")\n def update(self, request, un_id):\n \"\"\" update a county \"\"\"\n\n county = self.get_object()\n data = request.data\n\n serializer = CountyCreateSerializer(\n county, data=data\n )\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n response = {\n \"county\": serializer.data,\n \"message\": \"county updated successfully\"\n }\n\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"destory_county_details\")\n def destroy(self, request, un_id):\n \"\"\" delete a county \"\"\"\n county = self.get_object()\n county.soft_delete()\n response = {\n \"message\": \"county deleted successfully\"\n }\n return Response(response, status=status.HTTP_200_OK)\n\n\nclass SubCountyCreateListAPIView(ListCreateAPIView):\n \"\"\" create and list a subcounty \"\"\"\n serializer_class = SubCountySerializer\n lookup_field = 'un_id'\n\n def get_queryset(self):\n \"\"\" set the queryset for the subcounty \"\"\"\n return SubCounty.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"list_subcounties\")\n def get(self, request):\n data = self.get_queryset()\n serializer = self.serializer_class(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"create_subcounty\")\n def post(self, request):\n \"\"\" create a subcounty \"\"\"\n data = request.data\n\n serializer = SubCountyCreateSerializer(data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\nclass SubCountyDetailAPIView(RetrieveUpdateDestroyAPIView):\n serializer_class = SubCountyCreateSerializer\n lookup_field = 'un_id'\n # permission_classes = (IsAuthenticated, )\n\n def get_queryset(self):\n \"\"\" \n return a different queryset depending on who is logged in\n \"\"\"\n\n return SubCounty.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"subcounty_detail\")\n def get(self, request, un_id):\n subcounty = self.get_object()\n serializer = self.serializer_class(\n subcounty\n )\n response = serializer.data\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"update_subcounty\")\n def update(self, request, un_id):\n subcounty = self.get_object()\n serializer = self.serializer_class(\n subcounty, data=request.data\n )\n serializer.is_valid(raise_exception=True)\n serializer.save()\n response = serializer.data\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"delete_subcounty\")\n def destroy(self, request, un_id):\n \"\"\" delete one subcounty \"\"\"\n subcounty = self.get_object()\n subcounty.soft_delete()\n\n response = {\n \"message\": \"subcounty deleted successfully\"\n }\n\n return Response(response, status=status.HTTP_200_OK)\n\n\nclass ConstituencyCreateListAPIView(ListCreateAPIView):\n \"\"\" create and list a constituency \"\"\"\n serializer_class = ConstituencySerializer\n lookup_field = 'un_id'\n\n def get_queryset(self):\n \"\"\" set the queryset for the constituency \"\"\"\n return Constituency.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"list_constituencies\")\n def get(self, request):\n data = self.get_queryset()\n serializer = self.serializer_class(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"create_constituency\")\n def post(self, request):\n \"\"\" create a constituency \"\"\"\n data = request.data\n\n serializer = ConstituencyCreateSerializer(data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\nclass ConstituencyDetailAPIView(RetrieveUpdateDestroyAPIView):\n serializer_class = ConstituencyCreateSerializer\n lookup_field = 'un_id'\n # permission_classes = (IsAuthenticated, )\n\n def get_queryset(self):\n \"\"\" \n return a different queryset depending on who is logged in\n \"\"\"\n\n return Constituency.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"constituency_detail\")\n def get(self, request, un_id):\n constituency = self.get_object()\n serializer = self.serializer_class(\n constituency\n )\n response = serializer.data\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"update_constituency\")\n def update(self, request, un_id):\n constituency = self.get_object()\n serializer = self.serializer_class(\n constituency, data=request.data\n )\n serializer.is_valid(raise_exception=True)\n serializer.save()\n response = serializer.data\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"delete_constituency\")\n def destroy(self, request, un_id):\n \"\"\" delete one constituency \"\"\"\n constituency = self.get_object()\n constituency.soft_delete()\n\n response = {\n \"message\": \"constituency deleted successfully\"\n }\n\n return Response(response, status=status.HTTP_200_OK)\n\n\nclass WardCreateListAPIView(ListCreateAPIView):\n \"\"\" create and list a Ward \"\"\"\n serializer_class = WardSerializer\n lookup_field = 'un_id'\n\n def get_queryset(self):\n \"\"\" set the queryset for the ward \"\"\"\n return Ward.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"list_wards\")\n def get(self, request):\n data = self.get_queryset()\n serializer = self.serializer_class(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"create_ward\")\n def post(self, request):\n \"\"\" create a ward \"\"\"\n data = request.data\n\n serializer = WardCreateSerializer(data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\nclass WardDetailAPIView(RetrieveUpdateDestroyAPIView):\n serializer_class = WardCreateSerializer\n lookup_field = 'un_id'\n # permission_classes = (IsAuthenticated, )\n\n def get_queryset(self):\n \"\"\" \n return a different queryset depending on who is logged in\n \"\"\"\n\n return Ward.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"ward_detail\")\n def get(self, request, un_id):\n ward = self.get_object()\n serializer = self.serializer_class(\n ward\n )\n response = serializer.data\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"update_ward\")\n def update(self, request, un_id):\n ward = self.get_object()\n serializer = self.serializer_class(\n ward, data=request.data\n )\n serializer.is_valid(raise_exception=True)\n serializer.save()\n response = serializer.data\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"delete_ward\")\n def destroy(self, request, un_id):\n \"\"\" delete one ward \"\"\"\n ward = self.get_object()\n ward.soft_delete()\n\n response = {\n \"message\": \"ward deleted successfully\"\n }\n\n return Response(response, status=status.HTTP_200_OK)\n\n\nclass LocationCreateListAPIView(ListCreateAPIView):\n \"\"\" create and list a Location \"\"\"\n serializer_class = LocationSerializer\n lookup_field = 'un_id'\n\n def get_queryset(self):\n \"\"\" set the queryset for the Location \"\"\"\n return Location.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"list_locations\")\n def get(self, request):\n data = self.get_queryset()\n serializer = self.serializer_class(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"create_location\")\n def post(self, request):\n \"\"\" create a location \"\"\"\n data = request.data\n\n serializer = LocationCreateSerializer(data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\nclass LocationDetailAPIView(RetrieveUpdateDestroyAPIView):\n serializer_class = LocationCreateSerializer\n lookup_field = 'un_id'\n # permission_classes = (IsAuthenticated, )\n\n def get_queryset(self):\n \"\"\" \n return a different queryset depending on who is logged in\n \"\"\"\n\n return Location.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"location_detail\")\n def get(self, request, un_id):\n location = self.get_object()\n serializer = self.serializer_class(\n location\n )\n response = serializer.data\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"update_location\")\n def update(self, request, un_id):\n location = self.get_object()\n serializer = self.serializer_class(\n location, data=request.data\n )\n serializer.is_valid(raise_exception=True)\n serializer.save()\n response = serializer.data\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"delete_location\")\n def destroy(self, request, un_id):\n \"\"\" delete one location \"\"\"\n location = self.get_object()\n location.soft_delete()\n\n response = {\n \"message\": \"location deleted successfully\"\n }\n\n return Response(response, status=status.HTTP_200_OK)\n\n\nclass SubLocationCreateListAPIView(ListCreateAPIView):\n \"\"\" create and list a sublocation \"\"\"\n serializer_class = SubLocationSerializer\n lookup_field = 'un_id'\n\n def get_queryset(self):\n \"\"\" set the queryset for the sublocation \"\"\"\n return SubLocation.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"list_sublocations\")\n def get(self, request):\n data = self.get_queryset()\n serializer = self.serializer_class(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"create_sublocation\")\n def post(self, request):\n \"\"\" create a sublocation \"\"\"\n data = request.data\n\n serializer = SubLocationCreateSerializer(data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\nclass SubLocationDetailAPIView(RetrieveUpdateDestroyAPIView):\n serializer_class = SubLocationCreateSerializer\n lookup_field = 'un_id'\n # permission_classes = (IsAuthenticated, )\n\n def get_queryset(self):\n \"\"\" \n return a different queryset depending on who is logged in\n \"\"\"\n\n return SubLocation.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"sublocation_detail\")\n def get(self, request, un_id):\n sublocation = self.get_object()\n serializer = self.serializer_class(\n location\n )\n response = serializer.data\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"update_sublocation\")\n def update(self, request, un_id):\n sublocation = self.get_object()\n serializer = self.serializer_class(\n location, data=request.data\n )\n serializer.is_valid(raise_exception=True)\n serializer.save()\n response = serializer.data\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"delete_sublocation\")\n def destroy(self, request, un_id):\n \"\"\" delete one sublocation \"\"\"\n sublocation = self.get_object()\n sublocation.soft_delete()\n\n response = {\n \"message\": \"sublocation deleted successfully\"\n }\n\n return Response(response, status=status.HTTP_200_OK)\n\n\nclass PollingStationCreateListAPIView(ListCreateAPIView):\n \"\"\" create and list a polling station \"\"\"\n serializer_class = PollingStationSerializer\n lookup_field = 'un_id'\n\n def get_queryset(self):\n \"\"\" set the queryset for the polling station \"\"\"\n return PollingStation.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"list_polling_stations\")\n def get(self, request):\n data = self.get_queryset()\n serializer = self.serializer_class(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"create_polling_station\")\n def post(self, request):\n \"\"\" create a polling station \"\"\"\n data = request.data\n\n serializer = PollingStationCreateSerializer(data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\nclass PollingStationDetailAPIView(RetrieveUpdateDestroyAPIView):\n serializer_class = PollingStationCreateSerializer\n lookup_field = 'un_id'\n # permission_classes = (IsAuthenticated, )\n\n def get_queryset(self):\n \"\"\" \n return a different queryset depending on who is logged in\n \"\"\"\n\n return PollingStation.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"polling_station_detail\")\n def get(self, request, un_id):\n polling_station = self.get_object()\n serializer = self.serializer_class(\n polling_station\n )\n response = serializer.data\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"update_polling_station\")\n def update(self, request, un_id):\n polling_station = self.get_object()\n serializer = self.serializer_class(\n polling_station, data=request.data\n )\n serializer.is_valid(raise_exception=True)\n serializer.save()\n response = serializer.data\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"delete_polling_station\")\n def destroy(self, request, un_id):\n \"\"\" delete one polling_station \"\"\"\n polling_station = self.get_object()\n polling_station.soft_delete()\n\n response = {\n \"message\": \"polling station deleted successfully\"\n }\n\n return Response(response, status=status.HTTP_200_OK)\n\n\nclass CandidateCreateListAPIView(ListCreateAPIView):\n \"\"\" create and list a Candidate \"\"\"\n serializer_class = CandidateSerializer\n lookup_field = 'un_id'\n\n def get_queryset(self):\n \"\"\" set the queryset for the Candidate \"\"\"\n return Candidate.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"list_candidates\")\n def get(self, request):\n data = self.get_queryset()\n serializer = self.serializer_class(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"create_candidate\")\n def post(self, request):\n \"\"\" create a candidate \"\"\"\n data = request.data\n\n serializer = CandidateCreateSerializer(data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\nclass CandidateDetailAPIView(RetrieveUpdateDestroyAPIView):\n serializer_class = CandidateCreateSerializer\n lookup_field = 'un_id'\n # permission_classes = (IsAuthenticated, )\n\n def get_queryset(self):\n \"\"\" \n return a different queryset depending on who is logged in\n \"\"\"\n\n return Candidate.active_objects.all_objects()\n\n @swagger_auto_schema(operation_id=\"candidate_detail\")\n def get(self, request, un_id):\n candidate = self.get_object()\n serializer = self.serializer_class(\n candidate\n )\n response = serializer.data\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"update_candidate\")\n def update(self, request, un_id):\n candidate = self.get_object()\n serializer = self.serializer_class(\n candidate, data=request.data\n )\n serializer.is_valid(raise_exception=True)\n serializer.save()\n response = serializer.data\n return Response(response, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(operation_id=\"delete_candidate\")\n def destroy(self, request, un_id):\n \"\"\" delete one candidate \"\"\"\n candidate = self.get_object()\n candidate.soft_delete()\n\n response = {\n \"message\": \"candidate deleted successfully\"\n }\n\n return Response(response, status=status.HTTP_200_OK)\n","repo_name":"bonaventureogeto/Samarithan","sub_path":"subject/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":21962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"4503364693","text":"## exemple path to first target of the first variable of the first driver.\n##ob.animation_data.drivers[0].driver.variables['var'].targets[0].id\nfor ob in objs:\n print('\\n'+ob.name, \"drivers\")\n for dr in ob.animation_data.drivers:\n for var in dr.driver.variables: \n if var.type == 'SINGLE_PROP':\n ## id : objet ou rig contenant la propertie, data_path : le chemin\n\n # direct datapath modification\n #var.targets[0].data_path == 'pose.bones[\"hide\"][\"hide\"]'\n\n #ex: change data_path if not good\n if var.targets[0].data_path == 'pose.bones[\"walk\"][\"hide\"]':\n print(var.name, \"changing data_path\")\n var.targets[0].data_path = 'pose.bones[\"walk\"][\"head\"]'\n\n if var.type == 'TRANSFORMS':\n ## change target according to previous\n ## with transform : id wait for an object, bone_target wait for str\n\n ##compare with previous target name\n #if var.targets[0].id.name == 'perso_special_rig':\n print(var.name)\n if var.targets[0].bone_target in ('head_slider','head_up_down_slider'):\n print(\"changing bone target\")\n var.targets[0].id = bpy.data.objects['perso_rig']","repo_name":"Pullusb/snippetsLibrary","sub_path":"snippets/rig/modifify_driver.py","file_name":"modifify_driver.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"29"} +{"seq_id":"40183228795","text":"import urllib\n\nfrom django.views.generic import TemplateView\nfrom django.conf import settings\nfrom django.shortcuts import get_object_or_404\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.http import HttpResponseRedirect\nfrom django.contrib import messages\nfrom django.contrib.admin.views.decorators import staff_member_required\n\nfrom ajax_forms.views import AjaxModelFormView\n\nfrom .forms import SubscribeForm\nfrom .models import Subscriber, UnsubscribeToken\nfrom .utils import mailer\nfrom .utils.generators import generate_unsubscribe_token\nfrom .helpers import send_newsletters\n\nfrom cerci_issue.models import Issue\n\n\nclass SubscribeFormView(AjaxModelFormView):\n template_name = \"newsletters/subscribe-form.html\"\n form_class = SubscribeForm\n model = Subscriber\n\n def valid_submit(self, form):\n \"\"\"Send an email here\"\"\"\n pass\n\n\nclass UnsubscribeView(TemplateView):\n template_name = \"newsletters/unsubscribe.html\"\n\n def get_context_data(self, **kwargs):\n context = super(UnsubscribeView, self).get_context_data(**kwargs)\n self.email = self.request.GET.get('email')\n if self.email:\n self.email = urllib.unquote_plus(self.email)\n context['email'] = self.email\n return context\n\n def get(self, request, *args, **kwargs):\n context = self.get_context_data(**kwargs)\n t = self.request.GET.get('token')\n if t:\n unsubscribe_token = get_object_or_404(UnsubscribeToken, token=t)\n unsubscribe_token.subscriber.delete()\n context['unsubscribed'] = True\n return self.render_to_response(context)\n else:\n if self.email:\n subscriber = get_object_or_404(Subscriber, email=self.email)\n try:\n unsubscribe_token = UnsubscribeToken.objects.get(\n subscriber=subscriber)\n t = unsubscribe_token.token\n except UnsubscribeToken.DoesNotExist:\n t = generate_unsubscribe_token()\n unsubscribe_token = UnsubscribeToken(subscriber=subscriber,\n token=t)\n unsubscribe_token.save()\n unsubscribe_link = (settings.SITE_URL +\n reverse('unsubscribe') +\n '?token=' + t)\n mailer.send_mail(\n request=request,\n template='newsletters/email/unsubscribe',\n subject=u'unsubscribe',\n context={'unsubscribe_link': unsubscribe_link},\n email=[self.email])\n return self.render_to_response(context)\n\n\n@staff_member_required\ndef email_template_debug(request, issue_number):\n issue = Issue.objects.get(number=issue_number)\n domain = settings.SITE_URL\n return render_to_response('emails/newsletters.html',\n {'issue': issue,\n 'domain': domain},\n context_instance=RequestContext(request))\n\n\n@staff_member_required\ndef test_sending(request, issue_number):\n send_newsletters(request, issue_number, test=True)\n messages.success(request, 'Test Newsletters sent')\n return HttpResponseRedirect(request.GET.get('next', '/'))\n\n\n@staff_member_required\ndef send(request, issue_number):\n send_newsletters(request, issue_number)\n messages.success(request, 'Newsletters sent')\n return HttpResponseRedirect(request.GET.get('next', '/'))\n","repo_name":"cercisanat/cercisanat.com","sub_path":"cerci_newsletters/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"11929857514","text":"from Trie import *\nfrom moon_utils import *\nimport graph\nfrom cfg import *\n\ndef search_form(request):\n return render(request, './app/sentiment.html')\n\n\nfrom django.shortcuts import render\n\n\ndef analyse(request):\n ctx = {}\n if request.POST:\n ctx['rlt'] = request.POST['q']\n print(request)\n article_arr = trie_utils().preprocess(request.POST['q'])\n\n trie = trie_utils().pickle_load_trie()\n sentiment = trie.sentiment_search(article_arr)\n score = trie_utils().get_score(sentiment)\n ctx['score'] = score\n ctx['positive'] = sentiment[1]\n ctx['negative'] = sentiment[-1]\n ctx['stop'] = sentiment[11]\n ctx['neutral'] = sentiment[0]\n print(score)\n return render(request, \"app/sentiment.html\", ctx)\n\ndef analyse_countries(request):\n ctx = {}\n if request.POST:\n top5 = pick_country(5)\n\n # build sentiment trie\n trie = trie_utils().pickle_load_trie()\n data_list = []\n res = []\n # sentiment analysis by words\n for country in articles.keys():\n article_arr = trie_utils().preprocess(articles[country])\n sentiment = trie.sentiment_search(article_arr)\n score = trie_utils().get_score(sentiment)\n\n data_list.append([country, sentiment[0], sentiment[-1], sentiment[1], sentiment[11], score])\n ctx[f\"{country}Score\"] = f\"{score:.05f}\"\n ctx[f\"{country}Pos\"] = sentiment[1]\n ctx[f\"{country}Neg\"] = sentiment[-1]\n ctx[f\"{country}Neutral\"] = sentiment[0]\n ctx[f\"{country}Stop\"] = sentiment[11]\n\n graph.bar_graph(data_list)\n graph.score_graph(data_list)\n\n return render(request, \"app/country.html\", ctx)","repo_name":"yyLeaves/MoonSite","sub_path":"example/sentiment.py","file_name":"sentiment.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1163288444","text":"from shipyard_blueprints import SftpClient\nfrom settings import SFTP\n\nhost = SFTP.HOST\nuser = SFTP.USER\npwd = SFTP.PWD\nport = SFTP.PORT\n\n\ndef test_connection():\n client = SftpClient(host=host, port=port, user=user, key=\"rsa_id\")\n\n def connection_helper():\n try:\n conn = client.connect()\n return 0\n except Exception as e:\n return 1\n\n assert connection_helper() == 0\n","repo_name":"shipyardapp/shipyard-blueprints","sub_path":"test/sftp_test.py","file_name":"sftp_test.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3786638245","text":"import pytorch_lightning as pl\nfrom pytorch_lightning.callbacks import (\n LearningRateMonitor,\n ModelCheckpoint,\n EarlyStopping,\n TQDMProgressBar,\n)\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport time\nfrom datetime import datetime\nimport os\nimport sys\nfrom utils import utils, scheduler, logger, custom_callbacks\nimport gc\n\nDEVICE = torch.device(str(os.environ.get(\"DEVICE\", \"cpu\")))\nNUM_GPUS = int(os.environ.get(\"NUM_GPUS\", 0))\n\n\nclass Compressor(pl.LightningModule):\n def __init__(\n self, model, lr, warmup, max_iters, weight_decay, resume_checkpoint, **kwargs\n ):\n \"\"\"\n Inputs:\n model: model to be trained\n lr - Learning rate in the optimizer\n warmup - Number of warmup steps. Usually between 50 and 500\n max_iters - Number of maximum iterations the model is trained for. This is needed for the CosineWarmup scheduler\n \"\"\"\n super().__init__()\n # Exports the hyperparameters to a YAML file, and create \"self.hparams\" namespace\n self.save_hyperparameters(ignore=[\"model\"])\n # Create model\n self.model = model\n # self.vq_weight = 0.5\n self.mse_weight = 3\n # Example input for visualizing the graph in Tensorboard\n self.example_input_array = torch.randn(tuple(self.model.input_shape))\n\n def forward(self, x):\n \"\"\"\n The forward function takes in an image and returns the reconstructed image\n \"\"\"\n loss, x_hat, perplexity = self.model(x)\n return loss, x_hat, perplexity\n\n def _get_fft_mse_loss(self, x, x_hat):\n dim = tuple(range(1, len(x.shape), 1))\n x_fft = torch.fft.fftn(x, dim=dim, norm=\"ortho\")\n x_fft_magnitude = torch.abs(x_fft)\n x_fft_angle = torch.angle(x_fft)\n\n x_hat_fft = torch.fft.fftn(x_hat, dim=dim, norm=\"ortho\")\n x_hat_fft_magnitude = torch.abs(x_hat_fft)\n x_hat_fft_angle = torch.angle(x_hat_fft)\n\n fft_magnitude_mse = F.mse_loss(x_fft_magnitude, x_hat_fft_magnitude)\n fft_angle_mse = F.mse_loss(x_fft_angle, x_hat_fft_angle)\n fft_mse_loss = fft_magnitude_mse + fft_angle_mse\n return fft_mse_loss\n\n def _get_loss(self, batch):\n \"\"\"\n Given a batch of data, this function returns the reconstruction loss (MSE in our case)\n \"\"\"\n x, mask = batch\n x = x.type(torch.float32)\n mask = mask.type(torch.float32)\n quantized_loss, x_hat, _ = self.forward(x)\n x_hat = x_hat.type(torch.float32)\n x = x * mask\n x_hat = x_hat * mask\n mse_loss = F.mse_loss(x, x_hat)\n # frequency domain mse loss\n fft_mse_loss = self._get_fft_mse_loss(x, x_hat)\n\n return mse_loss, quantized_loss, fft_mse_loss\n\n def configure_optimizers(self):\n if len(self.hparams.resume_checkpoint) > 0:\n optimizer = optim.AdamW(\n self.parameters(),\n lr=self.hparams.lr,\n betas=(0.9, 0.9999),\n eps=1e-08,\n weight_decay=1e-8,\n amsgrad=False,\n )\n else:\n optimizer = optim.AdamW(\n self.parameters(),\n lr=self.hparams.lr,\n betas=(0.9, 0.95),\n eps=1e-08,\n weight_decay=self.hparams.weight_decay,\n amsgrad=False,\n )\n # Apply lr scheduler per step\n lr_scheduler = scheduler.CosineWarmupScheduler(\n optimizer, warmup=self.hparams.warmup, max_iters=self.hparams.max_iters\n )\n return [optimizer], [{\"scheduler\": lr_scheduler, \"interval\": \"step\"}]\n\n def training_step(self, batch, batch_idx):\n mse_loss, quantized_loss, fft_mse_loss = self._get_loss(batch)\n # loss = mse_loss * self.mse_weight + quantized_loss + fft_mse_loss * 0.5\n loss = mse_loss * self.mse_weight + quantized_loss\n cur_lr = self.trainer.optimizers[0].param_groups[0][\"lr\"]\n\n self.log(\"mse_loss\", mse_loss, prog_bar=True)\n self.log(\"quantized_loss\", quantized_loss, prog_bar=True)\n self.log(\"fft_mse_loss\", fft_mse_loss, prog_bar=True)\n self.log(\"train_loss\", loss, on_epoch=True, sync_dist=True)\n self.log(\"lr\", cur_lr, prog_bar=True, on_step=True)\n self.log(\"hp/train_loss\", loss, sync_dist=True)\n self.log(\"hp/train_mse\", mse_loss, sync_dist=True)\n\n return loss\n\n def validation_step(self, batch, batch_idx):\n mse_loss, quantized_loss, fft_mse_loss = self._get_loss(batch)\n loss = mse_loss * self.mse_weight + quantized_loss\n self.log(\"val_mse_loss\", mse_loss, sync_dist=True)\n self.log(\"val_quantized_loss\", quantized_loss, sync_dist=True)\n # self.log(\"val_fft_mse_loss\", fft_mse_loss, sync_dist=True)\n self.log(\"val_loss\", loss, prog_bar=True, sync_dist=True)\n self.log(\"hp/val_loss\", loss, sync_dist=True)\n self.log(\"hp/val_mse\", mse_loss, sync_dist=True)\n\n def test_step(self, batch, batch_idx):\n mse_loss, quantized_loss, fft_mse_loss = self._get_loss(batch)\n loss = mse_loss * self.mse_weight + quantized_loss\n self.log(\"test_mse_loss\", mse_loss, sync_dist=True)\n self.log(\"test_quantized_loss\", quantized_loss, sync_dist=True)\n # self.log(\"test_fft_mse_loss\", fft_mse_loss, sync_dist=True)\n self.log(\"test_loss\", loss, on_epoch=True, sync_dist=True)\n\n def compress(self, x):\n return self.model.compress(x)\n\n def decompress(self, x):\n return self.model.decompress(x)\n\n def on_train_start(self):\n self.logger.log_hyperparams(\n self.hparams,\n {\"hp/train_loss\": 0, \"hp/train_mse\": 0, \"hp/val_loss\": 0, \"hp/val_mse\": 0},\n )\n\n\ndef train(\n model,\n train_ds,\n model_path,\n epochs,\n lr,\n warm_up_portion,\n weight_decay,\n log_interval,\n save_interval,\n resume_checkpoint,\n test_ds=None,\n train_verbose=False,\n args=None,\n dataio=None,\n):\n \"\"\"train the model\"\"\"\n compressor_args = dict(\n lr=lr,\n warmup=epochs * len(train_ds) * warm_up_portion,\n max_iters=epochs * len(train_ds),\n weight_decay=weight_decay,\n resume_checkpoint=resume_checkpoint,\n )\n\n (image, mask) = get_single_slice_test_ds(test_ds, dataio)\n\n # Save training parameters if we need to resume training in the future\n start_epoch = 0\n weight_filename = \"sst-{epoch:03d}-{val_mse_loss:.5f}-{val_loss:.5f}\"\n if \"resume_epoch\" in resume_checkpoint:\n start_epoch = resume_checkpoint[\"resume_epoch\"]\n weight_filename = f\"resume_start_{start_epoch}_\" + weight_filename\n version = \"resume\"\n else:\n version = \"pretrain\"\n summaries_dir, checkpoints_dir = utils.mkdir_storage(model_path, resume_checkpoint)\n _callbacks = get_callbacks(checkpoints_dir, weight_filename, train_verbose)\n _callbacks.append(custom_callbacks.GenerateCallback(image, mask, dataio))\n\n logger.log(f\"\\nStart Training...\")\n start_total_time = time.perf_counter()\n tfboard_logger = pl.loggers.tensorboard.TensorBoardLogger(\n summaries_dir, name=\"\", version=version, log_graph=True, default_hp_metric=False\n )\n limit_val_batches = 1.0\n limit_train_batches = 1.0\n limit_test_batches = 1.0\n # if args is not None:\n # if args.local_test == True:\n # limit_val_batches = 0.05\n # limit_train_batches = 0.05\n # limit_test_batches = 0.05\n\n trainer = pl.Trainer(\n fast_dev_run=False,\n default_root_dir=os.path.join(checkpoints_dir),\n accelerator=\"gpu\",\n devices=NUM_GPUS,\n max_epochs=epochs,\n log_every_n_steps=log_interval,\n logger=tfboard_logger,\n callbacks=_callbacks,\n # limit_val_batches=limit_val_batches,\n # limit_train_batches=limit_train_batches,\n # limit_test_batches=limit_test_batches,\n gradient_clip_algorithm=\"norm\",\n enable_progress_bar=train_verbose,\n )\n lightning_model = Compressor(\n model=model,\n **compressor_args,\n **utils.args_to_dict(args, utils.model_defaults().keys()),\n )\n trainer.fit(lightning_model, train_ds, test_ds)\n total_training_time = time.perf_counter() - start_total_time\n logger.log(f\"Training time: {total_training_time:0.2f} seconds\")\n\n # Test best model on validation and test set\n logger.log(f\"Loading best model from {_callbacks[1].best_model_path}\")\n lightning_model = Compressor.load_from_checkpoint(\n _callbacks[1].best_model_path, model=model\n )\n test_result = trainer.test(lightning_model, test_ds, verbose=train_verbose)\n logger.log(f\"\\n{test_result}\\n\")\n\n for i, (path, _) in enumerate(trainer.checkpoint_callback.best_k_models.items()):\n m = Compressor.load_from_checkpoint(path, model=model)\n torch.save(m.model.state_dict(), path.rpartition(\".\")[0] + \".pt\")\n model = model.to(DEVICE)\n\n gc.collect()\n logger.info(f\"\\nTraining completed!\\n\")\n\n return model\n\n\ndef get_callbacks(\n checkpoints_dir, weight_filename=\"{epoch:03d}-{train_loss:.2f}\", verbose=False\n):\n callbacks = [\n EarlyStopping(\"val_loss\", patience=25, mode=\"min\"),\n ModelCheckpoint(\n save_top_k=3,\n monitor=\"val_loss\",\n mode=\"min\",\n dirpath=checkpoints_dir,\n filename=weight_filename,\n save_weights_only=True,\n ),\n LearningRateMonitor(\"step\"),\n ]\n if verbose:\n callbacks.append(TQDMProgressBar(refresh_rate=100))\n return callbacks\n\n\ndef get_single_slice_test_ds(test_ds, dataio):\n \"\"\"Get a single slice from the test dataset\"\"\"\n num_batch_per_time_slice = dataio.params[\"test.num_batch_per_time_slice\"]\n image, mask = [], []\n for i, (da, tile_mask) in enumerate(test_ds):\n image.append(da.type(torch.float))\n mask.append(tile_mask.type(torch.float))\n if i >= num_batch_per_time_slice:\n break\n return image, mask\n","repo_name":"hieutrungle/data-slim","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":10066,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"34155987801","text":"from selenium import webdriver\nimport time\nimport unittest\n\n\nclass TestAbs(unittest.TestCase):\n def test_check_web_pages(self):\n \"\"\"\n Expected fail link 2\n \"\"\"\n links = [\n \"http://suninjuly.github.io/registration1.html\",\n \"http://suninjuly.github.io/registration2.html\"\n ]\n for link in links:\n self.browser = webdriver.Chrome()\n self.browser.get(link)\n\n div = self.browser.find_element_by_class_name('first_block')\n\n input1 = div.find_element_by_class_name('first')\n input1.send_keys(\"Ivan\")\n self.assertEqual(\n 'Ivan', input1.get_attribute('value'),\n 'checking the input \"first\" value'\n )\n\n input2 = div.find_element_by_class_name('second')\n input2.send_keys(\"Petrov\")\n self.assertEqual(\n 'Petrov', input2.get_attribute('value'),\n 'checking the input \"second\" value'\n )\n\n input3 = div.find_element_by_class_name('third')\n input3.send_keys(\"ivanpetrov@gmail.com\")\n self.assertEqual(\n 'ivanpetrov@gmail.com', input3.get_attribute('value'),\n 'checking the input \"third\" value'\n )\n\n button = self.browser.find_element_by_css_selector(\"button.btn\")\n button.click()\n\n time.sleep(1)\n\n welcome_text_elt = self.browser.find_element_by_tag_name(\"h1\")\n welcome_text = welcome_text_elt.text\n self.assertEqual(\n welcome_text, welcome_text_elt.text,\n 'welcome_text is equal welcome_text_elt.text'\n )\n self.assertEqual(\n \"Congratulations! You have successfully registered!\",\n welcome_text, 'text is equal welcome_text'\n )\n\n self.browser.quit()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"MisterLenivec/selenium_course","sub_path":"third_module/lesson3_2_step13.py","file_name":"lesson3_2_step13.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"42740439467","text":"#!/usr/bin/python3\n\"\"\"\n Declaration for database storage\n\"\"\"\nimport models\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, String, create_engine\nfrom models.base_model import Base\nfrom models.user import User\nfrom models.place import Place\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.review import Review\nfrom sqlalchemy.orm import sessionmaker, scoped_session, exc\nimport os\n\n\nclass DBStorage():\n \"\"\"\n Database storage class\n \"\"\"\n __engine = None\n __session = None\n\n def __init__(self):\n \"\"\"\n Creates engine connection\n \"\"\"\n username = os.getenv('HBNB_MYSQL_USER', default=None)\n password = os.getenv('HBNB_MYSQL_PWD', default=None)\n localhost = os.getenv('HBNB_MYSQL_HOST', default=None)\n db_name = os.getenv('HBNB_MYSQL_DB', default=None)\n con = f'mysql+mysqldb://{username}:{password}@{localhost}/{db_name}'\n self.__engine = create_engine(con, pool_pre_ping=True)\n if os.getenv('HBNB_ENV') == 'test':\n Base.metadata.drop_all(self.__engine)\n\n def all(self, cls=None):\n \"\"\"\n Queries current database session based on class.\n Returns a dictionary representation of the query.\n \"\"\"\n result = {}\n if cls:\n objects = self.__session.query(eval(cls)).all()\n else:\n classes = [User, State, City, Amenity, Place, Review]\n objects = []\n for cls in classes:\n objects += self.__session.query(cls).all()\n for obj in objects:\n key = f\"{obj.__class__.__name__}.{obj.id}\"\n result[key] = obj\n return result\n\n def new(self, obj):\n \"\"\"\n Adds the object to the current database session\n \"\"\"\n self.__session.add(obj)\n\n def save(self):\n \"\"\"\n Commits all changes of the current database session\n \"\"\"\n self.__session.commit()\n\n def delete(self, obj=None):\n \"\"\"\n Deletes from the current database session obj if not None\n \"\"\"\n if obj:\n self.__session.delete(obj)\n\n def reload(self):\n \"\"\"\n Creates all tables in the database and creates a new session\n \"\"\"\n Base.metadata.create_all(self.__engine)\n Session = scoped_session(sessionmaker(\n bind=self.__engine, expire_on_commit=False))\n self.__session = Session()\n\n def close(self):\n \"\"\"\n Closes the session\n \"\"\"\n self.__session.remove()\n","repo_name":"esmond-adjei/AirBnB_clone_v2","sub_path":"models/engine/db_storage.py","file_name":"db_storage.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71227036558","text":"import logging\n\nimport numpy as np\nimport scipy as sp\nimport pandas as pd\nimport pymc3 as pm\nimport theano.tensor as tt\nfrom sklearn.preprocessing import LabelEncoder\n\nfrom shm.distributions.binary_mrf import BinaryMRF\nfrom shm.distributions.categorical_mrf import CategoricalMRF\nfrom shm.family import Family\nfrom shm.globals import READOUT, GENE, CONDITION, INTERVENTION\nfrom shm.link import Link\nfrom shm.models.shm import SHM\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\nlogger.addHandler(logging.StreamHandler())\n\n\nclass SHLM(SHM):\n def __init__(self,\n data: pd.DataFrame,\n family=\"gaussian\",\n link_function=Link.identity,\n model=\"clustering\",\n n_states=2,\n graph=None,\n sampler=\"nuts\"):\n self._data = data\n self._data = self._data.sort_values([GENE, CONDITION, INTERVENTION])\n\n self._set_link(link_function)\n self._set_family(family)\n self._set_data()\n\n super().__init__(model=model,\n n_states=n_states,\n graph=graph,\n sampler=sampler)\n\n if graph:\n d_genes = sp.sort(sp.unique(self._data.gene.values))\n if not sp.array_equal(d_genes, self.node_labels):\n raise ValueError(\"Graph nodes != data genes\")\n\n @property\n def tau_g_alpha(self):\n return 5\n\n @property\n def tau_b_alpha(self):\n return 3\n\n @property\n def tau_iota_alpha(self):\n return 3\n\n @property\n def sd_alpha(self):\n return 2\n\n @property\n def edge_correction(self):\n return .5\n\n @property\n def gamma_means(self):\n if self.n_states == 2:\n return np.array([0., 0.])\n return np.array([-1, 0., 1.])\n\n @property\n def data(self):\n return self._data\n\n @property\n def family(self):\n return self._family\n\n @property\n def link(self):\n return self._link_function\n\n def _set_link(self, link_function):\n if isinstance(link_function, str):\n link_function = Link.from_str(link_function)\n self._link_function = link_function\n\n def _set_family(self, family):\n if isinstance(family, str):\n family = Family.from_str(family)\n self._family = family\n\n def _set_mrf_model(self):\n with pm.Model() as model:\n if self.n_states == 2:\n logger.info(\"Using binary-MRF\")\n z = BinaryMRF('z', G=self.graph, beta=self.edge_correction)\n else:\n logger.info(\"Using categorical-MRF with three states\")\n z = CategoricalMRF('z', G=self.graph, k=3)\n tau_g, mean_g, gamma = self._gamma_mix(model, z)\n param_hlm = self._hlm(model, gamma)\n\n self._set_steps(model, z, tau_g, mean_g, gamma, *param_hlm)\n return self\n\n def _set_clustering_model(self):\n with pm.Model() as model:\n logger.info(\"Using {} cluster centers\".format(self.n_states))\n p = pm.Dirichlet(\n \"p\", a=np.repeat(1, self.n_states), shape=self.n_states)\n pm.Potential(\"p_pot\", var=tt.switch(tt.min(p) < 0.05, -np.inf, 0.))\n z = pm.Categorical(\"z\", p=p, shape=self.n_genes)\n tau_g, mean_g, gamma = self._gamma_mix(model, z)\n param_hlm = self._hlm(model, gamma)\n\n self._set_steps(model, z, p, tau_g, mean_g, gamma, *param_hlm)\n return self\n\n def _set_simple_model(self):\n with pm.Model() as model:\n logger.info(\"Using tau_g_alpha: {}\".format(self.tau_g_alpha))\n tau_g = pm.InverseGamma(\n \"tau_g\", alpha=self.tau_g_alpha, beta=1., shape=1)\n mean_g = pm.Normal(\"mu_g\", mu=0, sd=1, shape=1)\n gamma = pm.Normal(\"gamma\", mean_g, tau_g, shape=self.n_genes)\n param_hlm = self._hlm(model, gamma)\n\n self._set_steps(model, None, tau_g, mean_g, gamma, *param_hlm)\n return self\n\n def _gamma_mix(self, model, z):\n with model:\n logger.info(\"Using tau_g_alpha: {}\".format(self.tau_g_alpha))\n tau_g = pm.InverseGamma(\n \"tau_g\", alpha=self.tau_g_alpha, beta=1., shape=self.n_states)\n\n logger.info(\"Using mean_g: {}\".format(self.gamma_means))\n if self.n_states == 2:\n logger.info(\"Building two-state model\")\n mean_g = pm.Normal(\n \"mu_g\", mu=self.gamma_means, sd=1, shape=self.n_states)\n pm.Potential(\n \"m_opot\",\n var=tt.switch(mean_g[1] - mean_g[0] < 0., -np.inf, 0.))\n else:\n logger.info(\"Building three-state model\")\n mean_g = pm.Normal(\n \"mu_g\", mu=self.gamma_means, sd=1, shape=self.n_states)\n pm.Potential(\n 'm_opot',\n tt.switch(mean_g[1] - mean_g[0] < 0, -np.inf, 0)\n + tt.switch(mean_g[2] - mean_g[1] < 0, -np.inf, 0))\n\n gamma = pm.Normal(\"gamma\", mean_g[z], tau_g[z], shape=self.n_genes)\n\n return tau_g, mean_g, gamma\n\n def _hlm(self, model, gamma):\n with model:\n logger.info(\"Using tau_b_alpha: {}\".format(self.tau_b_alpha))\n tau_b = pm.InverseGamma(\n \"tau_b\", alpha=self.tau_b_alpha, beta=1., shape=1)\n beta = pm.Normal(\"beta\", 0, sd=tau_b, shape=self.n_gene_condition)\n\n logger.info(\"Using tau_iota_alpha: {}\".format(self.tau_iota_alpha))\n l_tau = pm.InverseGamma(\n \"tau_iota\", alpha=self.tau_iota_alpha, beta=1., shape=1)\n l = pm.Normal(\"iota\", mu=0, sd=l_tau, shape=self.n_interventions)\n\n mu = (gamma[self._gene_data_idx] +\n beta[self._gene_cond_data_idx] +\n l[self._intervention_data_idx])\n\n if self.family == Family.gaussian:\n logger.info(\"Using sd_alpha: {}\".format(self.sd_alpha))\n sd = pm.InverseGamma(\"sd\", alpha=self.sd_alpha, beta=1., shape=1)\n pm.Normal(\"x\",\n mu=mu,\n sd=sd,\n observed=np.squeeze(self.data[READOUT].values))\n else:\n raise NotImplementedError(\"Only gaussian family so far\")\n\n return tau_b, beta, l_tau, l, sd\n\n @property\n def n_genes(self):\n return self.__len_genes\n\n @property\n def n_conditions(self):\n return self.__len_conds\n\n @property\n def n_interventions(self):\n return self.__len_intrs\n\n @property\n def _intervention_data_idx(self):\n return self.__intrs_data_idx\n\n @property\n def _gene_cond_data_idx(self):\n return self.__gene_cond_data_idx\n\n @property\n def _index_to_gene(self):\n return self.__index_to_gene\n\n @property\n def _gene_to_index(self):\n return self.__gene_to_index\n\n @property\n def _index_to_condition(self):\n return self.__index_to_con\n\n @property\n def _beta_index_to_gene(self):\n return self.__beta_idx_to_gene\n\n @property\n def _gene_to_beta_index(self):\n return self.__gene_to_beta_idx\n\n @property\n def _beta_idx_to_gene_cond(self):\n return self.__beta_idx_to_gene_cond\n\n @property\n def _gene_data_idx(self):\n return self.__gene_data_idx\n\n @property\n def n_gene_condition(self):\n return self.__len_gene_cond\n\n @property\n def _beta_idx(self):\n return self.__beta_idx\n\n def _set_data(self):\n data = self._data\n self._n, _ = data.shape\n le = LabelEncoder()\n\n self.__gene_data_idx = le.fit_transform(data[GENE].values)\n self.__index_to_gene = {i: e for i, e in zip(\n self.__gene_data_idx, data[GENE].values)}\n self.__gene_to_index = {e: i for i, e in zip(\n self.__gene_data_idx, data[GENE].values)}\n self.__genes = sp.unique(list(self.__index_to_gene.values()))\n self.__len_genes = len(self.__genes)\n\n self.__con_data_idx = le.fit_transform(data[CONDITION].values)\n self.__index_to_con = {i: e for i, e in zip(\n self.__con_data_idx, data[CONDITION].values)}\n self.__conditions = sp.unique(list(self.__index_to_con.values()))\n self.__len_conds = len(self.__conditions)\n\n self.__intrs_data_idx = le.fit_transform(data[INTERVENTION].values)\n self.__index_to_intervention = {i: e for i, e in zip(\n self.__intrs_data_idx, data[INTERVENTION].values)}\n self.__intrs = sp.unique(data[INTERVENTION].values)\n self.__len_intrs = len(self.__intrs)\n\n self.__beta_idx = sp.repeat(sp.unique(self.__gene_data_idx),\n len(self.__conditions))\n self.__beta_idx_to_gene = {i: self.__index_to_gene[i]\n for i in self.__beta_idx}\n self.__gene_to_beta_idx = {e: i for i, e in self.__beta_idx_to_gene.items()}\n\n self.__gene_cond_data = [\"{}-{}\".format(g, c)\n for g, c in zip(data[GENE].values, data[CONDITION].values)]\n self.__gene_cond_data_idx = le.fit_transform(self.__gene_cond_data)\n self.__len_gene_cond = len(sp.unique(self.__gene_cond_data))\n self.__beta_idx_to_gene_cond = {\n i: e for i, e in zip(self.__gene_cond_data_idx,\n self.__gene_cond_data)\n }\n\n","repo_name":"cbg-ethz/shm","sub_path":"examples/shlm.py","file_name":"shlm.py","file_ext":"py","file_size_in_byte":9470,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"207482954","text":"# -*- coding:utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\nfrom os import path\nimport re\nfrom code.my_modules import load_stop_words\nimport jieba\n\n\nwith open(path.join(path.dirname(__file__),'..','data','status_big.txt'),'r') as f:\n with open(path.join(path.dirname(__file__),'..','data','status_big_seg.txt'),'w') as fw:\n count = 0\n for sentence in f:\n count = count + 1\n outstr = ''\n sentence = re.findall(r'[\\u4e00-\\u9fa5\\s]', sentence) # become a char list\n sentence = ''.join(sentence)\n seg_list = jieba.cut(sentence, cut_all=False)\n stop_words = load_stop_words()\n for word in seg_list: # 清除停用词\n if word not in stop_words:\n if not word == '\\t':\n outstr = outstr + word.strip()\n outstr = outstr + \" \"\n if count%1000 == 0:\n print(str(count)+\" ==> \"+outstr)\n fw.write(outstr)\n\n\n","repo_name":"WUT-IDEA/SRL-MLP","sub_path":"code_pre/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"26041928222","text":"from django.urls import path, re_path\nfrom .views import * \nfrom django.conf.urls import url\n\napp_name = \"post\"\n\nurlpatterns = [\n path('index', post_index, name=\"index\"),\n path('create', post_create, name=\"create\"),\n url(r'^(?P[\\w-]+)/$', post_detail, name=\"detail\"),\n url(r'^(?P[\\w-]+)/update/$', post_update, name=\"update\"),\n url(r'^(?P[\\w-]+)/delete/$', post_delete , name=\"delete\"),\n url(r'^(?P[\\w-]+)/commentdelete/$', comment_delete , name=\"commentdelete\"),\n\n]","repo_name":"Rufet1/blog2","sub_path":"post/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"5685880457","text":"import os\nfrom lxml import etree\n\ndef mml2latex(equation, xslPath=\"mml-to-latex/lib/mmltex\", xslFilename=\"mmltex.xsl\"):\n \"\"\"MathML to LaTeX conversion with XSLT from Vasil Yaroshevich (http://xsltml.sourceforge.net/)\n\n We use an implementation at https://github.com/ets-interactive/mml-to-latex.\n The XSLT directory is assumed to be under the xslPath. It returns None if anything fails\n in the conversion. Also note that it retains the $ signs around the latex text.\n\n :param equation: a valid mathML string\n :param xslPath: the path to the XSLT files\n :param xslFilename: the name of the primary XSLT file\n :return: a string of latex, or None if anything fails\n \"\"\"\n\n assert(isinstance(equation, str))\n\n try:\n xslt_file = os.path.join(xslPath, xslFilename)\n dom = etree.fromstring(equation)\n xslt = etree.parse(xslt_file)\n transform = etree.XSLT(xslt)\n newdom = transform(dom)\n res = str(newdom)\n except:\n res = None\n return res\n\n# for unit testing\n\ndef test_mml2latex():\n mathml = \"\"\"\n sin-1x=cos-1x=tan-1x\n \"\"\"\n tex = mml2latex(mathml)\n assert(tex==\"${\\sin }^{-1}x={\\cos }^{-1}x={\\tan }^{-1}x$\")","repo_name":"gtojty/pdia-1","sub_path":"pdia/utils/mml2latex.py","file_name":"mml2latex.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20108248285","text":"import math\n\nMAX_MAP_SIZE = 60\nMAX_R2 = 13\nMAX_RUBBLE = 100\nPACKAGE_NAME = \"comm_explore_bot\"\n\nmax_radius = math.floor(math.sqrt(MAX_R2))\n\ndef get_r2(x, y):\n return x * x + y * y\n\nlocs = []\nfor i in range(-max_radius, max_radius + 1):\n for j in range(-max_radius, max_radius + 1):\n r2 = get_r2(i, j)\n if r2 <= MAX_R2:\n locs += [(i, j, r2)]\n\nlocs.sort(key=lambda x: x[2])\n# print(locs)\n\ndef get_loc_suffix(x, y):\n name = \"_\"\n if x >= 0:\n name += \"p\"\n else:\n name += \"n\"\n name += str(abs(x))\n if y >= 0:\n name += \"p\"\n else:\n name += \"n\"\n name += str(abs(y))\n return name\n\ndef get_method_name(xmin, ymin, xmax, ymax):\n return f\"bfs{get_loc_suffix(xmin, ymin)}{get_loc_suffix(xmax, ymax)}\"\n\n# for (x, y, r) in locs:\n# print(x, y, get_loc_suffix(x, y))\n\n\ndef in_range(x, y):\n return x * x + y * y <= MAX_R2\n\n# print()\nDIRS = {\n (1, 0): \"EAST\",\n (1, 1): \"NORTHEAST\",\n (0, 1): \"NORTH\",\n (-1, 1): \"NORTHWEST\",\n (-1, 0): \"WEST\",\n (-1, -1): \"SOUTHWEST\",\n (0, -1): \"SOUTH\",\n (1, -1): \"SOUTHEAST\"\n}\nprev_locs = {(x, y): [] for x, y, r in locs}\nfor (x, y, r) in locs:\n r2 = get_r2(x, y)\n # special case for adjacent tiles\n rel_locs = []\n for dx, dy in DIRS:\n nx = x + dx\n ny = y + dy\n nr2 = get_r2(nx, ny)\n if nr2 < r2:\n rel_locs += [(nx, ny)]\n rel_locs.sort(key=lambda x: get_r2(x[0], x[1]))\n prev_locs[(x, y)] = rel_locs\n\n# print(prev_locs)\n\nedge_locs = []\nfor (x, y, r) in locs:\n for dx, dy in DIRS:\n nx = x + dx\n ny = y + dy\n nr2 = get_r2(nx, ny)\n if nr2 > MAX_R2:\n edge_locs += [(x, y)]\n break\n\nprint(edge_locs)\n\n# ''' taken from stackoverflow '''\n# import numpy as np\n#\n# def unit_vector(vector):\n# return vector / np.linalg.norm(vector)\n#\n# def angle_between(v1, v2):\n# v1_u = unit_vector(v1)\n# v2_u = unit_vector(v2)\n# return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))\n#\n# dir2edges = {}\n# for dx, dy in DIRS:\n# edges = []\n# for x, y in edge_locs:\n# ang = angle_between((dx, dy), (x, y))\n# if abs(ang) <= math.pi / 2 + 0.00001:\n# edges += [(x, y)]\n# dir2edges[(dx, dy)] = edges\n# print(DIRS[(dx, dy)], len(edges), edges)\n# print(len(edge_locs))\n'''\nFILE GENERATION\n'''\n\n\n\ndef write_method(xmin, ymin, xmax, ymax):\n method_contents = \"\"\n\n method_contents += f\"public static Direction {get_method_name(xmin, ymin, xmax, ymax)}() throws GameActionException {{\\n\"\n\n # adjacent locations\n for (x, y), rel_locs in prev_locs.items():\n if not (xmin <= x <= xmax and ymin <= y <= ymax):\n continue\n\n suf = get_loc_suffix(x, y)\n if 1 <= get_r2(x, y) <= 2:\n dir_name = DIRS[(x, y)]\n#\n # method_contents += f\"if (rc.onTheMap(l{suf})) {{\\n\"\n method_contents += f\"if (!rc.canSenseRobotAtLocation(l{suf})) {{\\n\"\n method_contents += f\"v{suf} = 10 + rc.senseRubble(l{suf});\\n\"\n\n\n method_contents += f\"d{suf} = {dir_name};\\n\"\n\n\n method_contents += f\"}}\\n\"\n # method_contents += f\"}}\\n\"\n\n method_contents += \"\\n\"\n\n # non-adjacent locations\n for (x, y), rel_locs in prev_locs.items():\n if not (xmin <= x <= xmax and ymin <= y <= ymax):\n continue\n if get_r2(x, y) <= 2:\n continue\n\n suf = get_loc_suffix(x, y)\n\n method_contents += f\"p{suf} = 10 + rc.senseRubble(l{suf});\\n\"\n\n for px, py in rel_locs:\n if not (xmin <= px <= xmax and ymin <= py <= ymax):\n continue\n\n psuf = get_loc_suffix(px, py)\n\n method_contents += f\"if (v{suf} > v{psuf} + p{suf}) {{\\n\"\n\n method_contents += f\"v{suf} = v{psuf} + p{suf};\\n\"\n method_contents += f\"d{suf} = d{psuf};\\n\"\n\n method_contents += f\"}}\\n\"\n\n\n method_contents += \"\\n\"\n\n # for targets within vision\n method_contents += f'''\nint dx = target.x - here.x;\nint dy = target.y - here.y;\n '''\n\n method_contents += \"\\n\"\n\n method_contents += f\"switch (dx) {{\\n\"\n for x in range(-max_radius, max_radius + 1):\n if not (xmin <= x <= xmax):\n continue\n\n method_contents += f\"case {x}:\\n\"\n method_contents += f\"switch (dy) {{\\n\"\n for y in range(-max_radius, max_radius + 1):\n if not (ymin <= y <= ymax):\n continue\n\n if 0 < get_r2(x, y) <= MAX_R2:\n method_contents += f\"case {y}:\\n\"\n method_contents += f\"return d{get_loc_suffix(x, y)};\\n\"\n\n\n\n method_contents += f\"}}\\n\"\n method_contents += f\"break;\\n\"\n\n\n method_contents += f\"}}\\n\"\n\n method_contents += \"\\n\"\n\n # for target outside of vision\n method_contents += \"initialDist = Math.sqrt(here.distanceSquaredTo(target));\\n\"\n\n method_contents += \"\\n\"\n\n # calculate speeds\n for i, (x, y) in enumerate(edge_locs):\n if not (xmin <= x <= xmax and ymin <= y <= ymax):\n continue\n\n suf = get_loc_suffix(x, y)\n method_contents += f\"speed{suf} = (initialDist - Math.sqrt(l{suf}.distanceSquaredTo(target))) / v{suf};\\n\"\n\n # get best speed\n method_contents += f\"bestEstimation = \"\n\n total = 0\n for x, y in edge_locs:\n if not (xmin <= x <= xmax and ymin <= y <= ymax):\n continue\n total += 1\n\n count = 0\n for x, y in edge_locs:\n if not (xmin <= x <= xmax and ymin <= y <= ymax):\n continue\n if count == 0:\n count += 1\n continue\n suf = get_loc_suffix(x, y)\n if count + 1 == total:\n method_contents += f\"speed{suf}\"\n else:\n method_contents += f\"Math.max(speed{suf},\"\n count += 1\n method_contents += (\")\" * (count - 2)) + \";\\n\"\n\n # find best speed\n for i, (x, y) in enumerate(edge_locs):\n if not (xmin <= x <= xmax and ymin <= y <= ymax):\n continue\n\n suf = get_loc_suffix(x, y)\n method_contents += f\"if (bestEstimation == speed{suf}) {{\\n\"\n method_contents += f\"return d{suf};\\n\"\n method_contents += \"}\\n\";\n\n method_contents += \"\\n\"\n\n # return\n method_contents += \"return null;\\n\"\n\n method_contents += \"}\\n\"\n\n return method_contents\n\n''' FILE START '''\n\n\n\nfile_contents = \"\"\n\n# header\nfile_contents += f'''package {PACKAGE_NAME};\n\nimport battlecode.common.*;\nimport static battlecode.common.Direction.*;\n\nimport static {PACKAGE_NAME}.Debug.*;\nimport static {PACKAGE_NAME}.Map.*;\nimport static {PACKAGE_NAME}.Robot.*;\n\npublic class BFS{MAX_R2} {{\n\npublic static MapLocation target;\n'''\n\n\n\n\n# declare all variables\nfor (x, y), rel_locs in prev_locs.items():\n if not (x == 0 and y == 0):\n suf = get_loc_suffix(x, y)\n file_contents += f\"public static MapLocation l{suf};\\n\"\n file_contents += f\"public static double v{suf};\\n\"\n file_contents += f\"public static Direction d{suf};\\n\"\n file_contents += f\"public static int p{suf};\\n\"\n\nfile_contents += \"\\n\"\n\n# initialize all edge loc variables\nfile_contents += '''\npublic static double bestEstimation;\npublic static double initialDist;\n'''\n\nfile_contents += \"\\n\"\n\nfor i, (x, y) in enumerate(edge_locs):\n suf = get_loc_suffix(x, y)\n file_contents += f\"public static double speed{suf};\\n\";\nfile_contents += \"\\n\"\n\nfile_contents += '''\npublic static Direction getBestDir(MapLocation tar) throws GameActionException {\ntarget = tar;\n\n'''\n\n# initialize all standard loc variables\nfor (x, y), rel_locs in prev_locs.items():\n if not (x == 0 and y == 0):\n suf = get_loc_suffix(x, y)\n\n (px, py) = rel_locs[0]\n (dx, dy) = (x - px, y - py)\n prev_l = f\"l{get_loc_suffix(px, py)}\" if (px != 0 or py != 0) else \"here\"\n dir_name = DIRS[(dx, dy)]\n l = f\"{prev_l}.add({dir_name})\"\n v = \"1000000\"\n d = \"null\"\n\n file_contents += f\"l{suf} = {l};\\n\"\n file_contents += f\"v{suf} = {v};\\n\"\n file_contents += f\"d{suf} = {d};\\n\"\nfile_contents += \"\\n\"\n\n# PUT LARGE SWITCH HERE\nfile_contents += f'''\nint xmin = -Math.min(here.x, {max_radius});\nint ymin = -Math.min(here.y, {max_radius});\nint xmax = Math.min(XMAX - here.x, {max_radius});\nint ymax = Math.min(YMAX - here.y, {max_radius});\nlog(\"bounds \" + xmin + \" \" + ymin + \" \" + xmax + \" \" + ymax);\n'''\n\nfile_contents += f\"switch (xmin) {{\\n\"\nfor xmin in range(-max_radius, 1):\n file_contents += f\"case {xmin}: \\n\"\n\n file_contents += f\"switch (xmax) {{\\n\"\n for xmax in range(0, max_radius + 1):\n if xmin != -max_radius and xmax != max_radius:\n continue\n file_contents += f\"case {xmax}: \\n\"\n\n file_contents += f\"switch (ymin) {{\\n\"\n for ymin in range(-max_radius, 1):\n file_contents += f\"case {ymin}: \\n\"\n\n file_contents += f\"switch (ymax) {{\\n\"\n for ymax in range(0, max_radius + 1):\n if ymin != -max_radius and ymax != max_radius:\n continue\n file_contents += f\"case {ymax}: \\n\"\n file_contents += f\"return {get_method_name(xmin, ymin, xmax, ymax)}();\\n\";\n file_contents += \"}\\n\"\n file_contents += \"break;\"\n\n file_contents += \"}\\n\"\n file_contents += \"break;\"\n\n file_contents += \"}\\n\"\n file_contents += \"break;\"\n\nfile_contents += \"}\\n\"\n\n# file_contents += f\"switch (xmin * {(max_radius + 1)**3} + ymin * {(max_radius + 1)**2} + xmax * {(max_radius + 1)} + ymax) {{\\n\"\n# for xmin in range(0, max_radius + 1):\n# for ymin in range(0, max_radius + 1):\n# for xmax in range(0, max_radius + 1):\n# for ymax in range(0, max_radius + 1):\n# if xmin != max_radius and xmax != max_radius:\n# continue\n# if ymin != max_radius and ymax != max_radius:\n# continue\n# index = xmin * (max_radius + 1)**3 + ymin * (max_radius + 1)**2 + xmax * (max_radius + 1) + ymax\n# file_contents += f\"case {index}: \\n\"\n# file_contents += f\"return {get_method_name(-xmin, -ymin, xmax, ymax)}();\\n\";\n#\n# file_contents += \"}\\n\"\n\n\n\nfile_contents += f'''\nlogi(\"WARNING: 'Unexpected map offsets' \" + xmin + \" \" + ymin + \" \" + ymax + \" \" + ymax);\nreturn null;\n}}\n\n'''\n\n''' switch-methods '''\nmethod_arr = []\nfor xmin in range(-max_radius, 1):\n for ymin in range(-max_radius, 1):\n for xmax in range(0, max_radius + 1):\n for ymax in range(0, max_radius + 1):\n if xmin != -max_radius and xmax != max_radius:\n continue\n if ymin != -max_radius and ymax != max_radius:\n continue\n method_arr += [write_method(xmin, ymin, xmax, ymax)]\n\nfile_contents += \"\\n\\n\".join(method_arr)\n# file_contents += write_method(0, 0, 4, 4)\n\n# footer\nfile_contents += f'''\n}}\n'''\n\nwith open(f\"../src/{PACKAGE_NAME}/BFS{MAX_R2}.java\", \"w\") as f:\n f.write(file_contents)\n","repo_name":"rzhan11/Battlecode2022","sub_path":"gen_scripts/genBFS.py","file_name":"genBFS.py","file_ext":"py","file_size_in_byte":11016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"25926027043","text":"from collections.abc import Iterable\nfrom datetime import date\nfrom datetime import datetime\n\nfrom dateutil.relativedelta import relativedelta\nimport sqlalchemy as sa\n\nfrom pcapi import settings\nfrom pcapi.core.bookings import models as bookings_models\nfrom pcapi.core.external.sendinblue import add_contacts_to_list\nfrom pcapi.core.offerers import models as offerers_models\nfrom pcapi.core.offers import models as offers_models\nfrom pcapi.models import db\nfrom pcapi.models.offer_mixin import OfferValidationStatus\n\n\nYIELD_COUNT_PER_DB_QUERY = 1000\n\n\ndef get_inactive_venues_emails() -> Iterable[str]:\n # See request conditions in pro_inactive_venues_automation() below\n ninety_days_ago = datetime.combine(date.today() - relativedelta(days=90), datetime.min.time())\n\n venue_has_approved_offer_subquery = offers_models.Offer.query.filter(\n offers_models.Offer.venueId == offerers_models.Venue.id,\n offers_models.Offer.isActive.is_(True),\n offers_models.Offer.validation == OfferValidationStatus.APPROVED,\n ).exists()\n\n venue_has_no_booking_within_the_last_90_days_subquery = sa.not_(\n offers_models.Offer.query.filter(\n offers_models.Offer.venueId == offerers_models.Venue.id,\n offers_models.Offer.isActive.is_(True),\n offers_models.Offer.validation == OfferValidationStatus.APPROVED,\n )\n .join(offers_models.Stock)\n .join(bookings_models.Booking)\n .filter(\n bookings_models.Booking.status != bookings_models.BookingStatus.CANCELLED,\n bookings_models.Booking.dateCreated >= datetime.utcnow() - relativedelta(days=90),\n )\n .exists()\n )\n\n query = (\n db.session.query(offerers_models.Venue.bookingEmail)\n .join(offerers_models.Offerer)\n .filter(\n offerers_models.Offerer.dateValidated < ninety_days_ago,\n offerers_models.Venue.bookingEmail.is_not(None),\n sa.not_(\n offerers_models.Venue.venueTypeCode.in_(\n [offerers_models.VenueTypeCode.FESTIVAL, offerers_models.VenueTypeCode.DIGITAL]\n )\n ),\n venue_has_approved_offer_subquery,\n venue_has_no_booking_within_the_last_90_days_subquery,\n )\n .distinct()\n .yield_per(YIELD_COUNT_PER_DB_QUERY)\n )\n\n return (email for email, in query)\n\n\ndef pro_inactive_venues_automation() -> bool:\n \"\"\"\n Check venues which have no reservation for a long time (more than 90 days) on their offers and look inactive.\n\n Conditions:\n - parent offerer has been validated more than 90 days ago\n - venue has a bookingEmail address set\n - venue type is not digital nor festival\n - venue has at least one approved and active individual offer\n - there is no booking made with the last three months among currently active offers\n\n List: pros-inactivité-90j\n \"\"\"\n return add_contacts_to_list(get_inactive_venues_emails(), settings.SENDINBLUE_PRO_INACTIVE_90_DAYS_ID)\n","repo_name":"pass-culture/pass-culture-main","sub_path":"api/src/pcapi/core/external/automations/venue.py","file_name":"venue.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","stars":86,"dataset":"github-code","pt":"29"} +{"seq_id":"42590216497","text":"import numpy as np\nfrom problem5 import pagerank \n\n#-------------------------------------------------------------------------\n'''\n Problem 6: use PageRank (implemented in Problem 5) to compute the ranked list of nodes in a real-world network. \n In this problem, we import a real-world network and use pagerank algorithm to rank the nodes in the network.\n File `network.csv` contains a network adjacency matrix. \n (1) import the network from the file\n (2) compute the pagerank scores for the network\n You could test the correctness of your code by typing `nosetests test6.py` in the terminal.\n'''\n\n#--------------------------\ndef import_A(filename ='network.csv'):\n '''\n import the adjacency matrix A from a CSV file\n Input:\n filename: the name of csv file, a string \n Output: \n A: the ajacency matrix, a numpy matrix of shape (n by n)\n '''\n #########################################\n ## INSERT YOUR CODE HERE\n\n # Import csv using pure numpy:\n f = open(filename, \"rb\");\n # print(filename);\n A = np.loadtxt(f, delimiter=\",\");\n A = np.asmatrix(A); # Convert from type ndarray -> matrix\n # print(\"A:\\n%s\" % str(A));\n \n #########################################\n return A;\n\n\n#--------------------------\ndef score2rank(x):\n '''\n compute a list of node IDs sorted by descending order of pagerank scores in x.\n Note the node IDs start from 0. So the IDs of the nodes are 0,1,2,3, ...\n Input: \n x: the numpy array of pagerank scores, shape (n by 1) \n Output: \n sorted_ids: a python list of node IDs (starting from 0) in descending order of their pagerank scores, a python list of integer values, such as [2,0,1,3].\n '''\n #########################################\n ## INSERT YOUR CODE\n \n # Generate copy of x in descending order\n x_list = x.tolist();\n x_sorted = x_list.copy();\n x_sorted.sort(reverse=True);\n print(x_sorted);\n\n sorted_ids = []\n # Populate sorted_ids[] with descended sorted indices of x\n for index,elt in enumerate(x_sorted):\n sorted_ids.append(x_list.index(elt));\n\n\n #########################################\n return sorted_ids;\n\n#--------------------------\ndef node_ranking(filename = 'network.csv', alpha = 0.95):\n ''' \n Rank the nodes in the network imported from a CSV file.\n (1) import the adjacency matrix from `filename` file.\n (2) compute pagerank scores of all the nodes\n (3) return a list of node IDs sorted by descending order of pagerank scores \n\n Input: \n filename: the csv filename for the adjacency matrix, a string.\n alpha: a float scalar value, which is the probability of choosing option 1 (randomly follow a link on the node)\n\n Output: \n sorted_ids: the list of node IDs (starting from 0) in descending order of their pagerank scores, a python list of integer values, such as [2,0,1,3].\n \n '''\n A = import_A(filename) \n x = pagerank(A,alpha)\n sorted_ids = score2rank(x)\n return sorted_ids\n\n\n","repo_name":"AdamOCamilli/WPI-CS-Projects","sub_path":"CS_4445/HW1_PageRank/problem6.py","file_name":"problem6.py","file_ext":"py","file_size_in_byte":3148,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"72068448079","text":"from tkinter import N\nfrom trainer.trainer_base import TrainerBase\nimport torch.nn as nn\nimport torch\nimport numpy as np\nfrom torchvision import transforms\nfrom utils.loss import CustomLoss, SmoothL1Loss\nfrom tensorboardX import SummaryWriter\nimport matplotlib.pyplot as plt\n\nfrom utils.postprocess import non_max_suppression, compute_matches\n\nclass BaselineTrainer(TrainerBase):\n def __init__(self, config):\n super(BaselineTrainer, self).__init__()\n self.max_epoch = config['epoch']\n self.optimizer_config = config['optimizer']\n self.device = torch.device(config['device'])\n self.perception_loss_func = CustomLoss(config['loss_function'])\n self.prediction_loss_func = SmoothL1Loss()\n self.tensorboard_out_path = config['tensorboard_out_path']\n self.data_distributed = config['FP_distribution']\n self.actor_feature_size = config['actor_feature_size']\n self.optimizer = None\n self.data_loader = None\n \n pass\n\n def train_filter_pred(self, pred, decoded_pred):\n if len(pred.size()) == 4:\n if pred.size(0) == 1:\n pred = pred.squeeze(0)\n else:\n raise ValueError(\"Tensor dimension is not right\")\n\n cls_pred = pred[0, ...]\n activation = cls_pred > 0.2 # cls阈值\n num_boxes = int(activation.sum())\n\n if num_boxes == 0:\n #print(\"No bounding box found\")\n return [], []\n\n corners = torch.zeros((num_boxes, 8))\n for i in range(0, 8):\n corners[:, i] = torch.masked_select(decoded_pred[i, ...], activation)\n corners = corners.view(-1, 4, 2).numpy()\n scores = torch.masked_select(cls_pred, activation).cpu().numpy()\n\n # NMS\n selected_ids = non_max_suppression(corners, scores, 0.3) # iou阈值\n corners = corners[selected_ids]\n scores = scores[selected_ids]\n\n return corners, scores\n\n def get_batch_actor_features_and_match_list(self, pred, decoded_pred, features, label_list):\n pred_match_list = []\n aug_pred_match_list = []\n for batch_id in range(pred.shape[0]):\n per_pred = pred[batch_id].squeeze(0)\n per_decoded_pred = decoded_pred[batch_id].squeeze(0)\n per_label_list = label_list[batch_id]\n\n # Filter Predictions\n corners, scores = self.train_filter_pred(per_pred, per_decoded_pred)\n\n gt_boxes = np.array(per_label_list)\n gt_match, pred_match, overlaps = compute_matches(gt_boxes,\n corners, scores, iou_threshold=0.5) \n pred_match_list.append(list(pred_match))\n\n ##################\n ### No Augment ###\n ##################\n # if len(corners) == 0:\n # pass\n # else:\n # box_centers = np.mean(corners, axis=1)\n\n # center_index = - box_centers / 0.2 # 0.2为resolution\n # center_index[:, 0] += pred.shape[-2]\n # center_index[:, 1] += pred.shape[-1] / 2\n # center_index = np.round(center_index / 4).astype(int) # 4为input_size/feature_size,将坐标从原图转为特征图\n\n # center_index = np.swapaxes(center_index, 1, 0)\n # center_index[0] = np.clip(center_index[0], 0, features.shape[-2] - 1)\n # center_index[1] = np.clip(center_index[1], 0, features.shape[-1] - 1)\n\n # per_actor_features = features[batch_id, :, center_index[0], center_index[1]].permute(1, 0)\n\n # if 'batch_actor_features' not in locals().keys():\n # batch_actor_features = per_actor_features\n # else:\n # batch_actor_features = torch.cat((batch_actor_features, per_actor_features), 0)\n\n # if 'batch_actor_features' not in locals().keys(): # 说明该batch中没有检测出任何物体\n # return None, None\n # else:\n # return batch_actor_features, pred_match_list\n\n ###############\n ### Augment ###\n ###############\n aug_pred_match = []\n aug_per_actor_features = []\n \n for idx, corner in enumerate(corners):\n label_corner = self.dataset.transform_metric2label(corner)\n feature_corner = np.round(label_corner / 4).astype(int)\n points = self.dataset.get_points_in_a_rotated_box(feature_corner, list(features.shape[-2:]))\n aug_pred_match.extend(len(points) * [pred_match[idx]])\n\n for p in points: # 将特征图中bbox围住的每一个点都作为正样本\n label_x = min(p[0], features.shape[-2] - 1)\n label_y = min(p[1], features.shape[-1] - 1)\n per_actor_feature = features[batch_id, :, label_x, label_y][None,None,:]\n aug_per_actor_feature = nn.functional.interpolate(per_actor_feature, size=self.actor_feature_size, mode='linear').squeeze(0)\n\n aug_per_actor_features.append(aug_per_actor_feature)\n \n if len(aug_per_actor_features) == 0:\n pass\n else:\n aug_per_actor_features = torch.cat(aug_per_actor_features, dim=0)\n if 'aug_batch_actor_features' not in locals().keys():\n aug_batch_actor_features = aug_per_actor_features\n else:\n aug_batch_actor_features = torch.cat((aug_batch_actor_features, aug_per_actor_features), 0)\n\n aug_pred_match_list.append(list(aug_pred_match))\n\n if 'aug_batch_actor_features' not in locals().keys(): # 说明该batch中没有检测出任何物体\n return None, None\n else:\n return aug_batch_actor_features, aug_pred_match_list\n\n\n\n def set_optimizer(self, optimizer_config):\n optimizer_ref = torch.optim.__dict__[self.optimizer_config['type']]\n self.optimizer = optimizer_ref(self.model.parameters(), **optimizer_config['paras'])\n\n def run(self):\n if not self.check_ready():\n raise ModuleNotFoundError(\"The trainer not ready. Plz set model/dataset first\")\n torch.autograd.set_detect_anomaly(True)\n self.set_optimizer(self.optimizer_config)\n self.model.set_device(self.device)\n\n \n # # For test\n # pretext_model = torch.load(\"C:/Users/Sunyyyy/Desktop/Study/PJLAB/Code/ADModel_Pro/output/baseline_kitti_range/50.pt\")\n # model2_dict = self.model.state_dict()\n # state_dict = {k:v for k,v in pretext_model.items() if k in model2_dict.keys()}\n # model2_dict.update(state_dict)\n # self.model.load_model_paras(model2_dict)\n\n \n self.perception_loss_func.to(self.device)\n self.prediction_loss_func.to(self.device)\n self.data_loader = self.dataset.get_data_loader()\n # writer = SummaryWriter(log_dir=self.tensorboard_out_path)\n\n # Training Loop\n print(\"device: \", self.device)\n print(\"Start training!\")\n self.global_step = 0\n for epoch in range(self.max_epoch):\n self.epoch = epoch\n for step, data in enumerate(self.data_loader):\n self.step = step\n self.global_step += 1\n self.dataset.load_data_to_gpu(data)\n \n self.model.zero_grad()\n\n occupancy = data['occupancy'].permute(0, 3, 1, 2)\n occlusion = data['occlusion'].permute(0, 3, 1, 2)\n HDmap = data['HDmap'].permute(0, 3, 1, 2)\n label_map = data['label_map'].permute(0, 3, 1, 2)\n label_list = data['label_list']\n # waypoints = data['future_waypoints_st']\n\n ####################\n # Train perception #\n ####################\n input = torch.cat((occupancy, occlusion, HDmap), dim=1) # 将场景描述共同输入\n # input = torch.cat((occupancy, occlusion), dim=1) # 将场景描述共同输入\n pred, features = self.model(input)\n perc_loss, cls, loc, cls_loss = self.perception_loss_func(pred, label_map)\n\n if epoch < 30: # 为了助于收敛,前三轮只对cls分支进行参数回传\n loss = cls_loss\n else:\n loss = perc_loss\n\n ####################\n # Train pridiction #\n ####################\n # decoded_pred = self.model.corner_decoder(pred.detach()[:, 1:,...]) # 将pred_map解码为可获取corner的形式\n # batch_actor_features, pred_match_list = self.get_batch_actor_features_and_match_list(pred.detach(), decoded_pred, features.detach(), label_list)\n\n # if epoch < 2: # 为了助于收敛,前三轮只对cls分支进行参数回传\n # loss = cls_loss\n # pred_loss = np.NaN\n # else: \n # if pred_match_list == None or np.array(np.concatenate(pred_match_list, axis=0) >= 0).sum()==0: # 检测结果未匹配上GT\n # loss = perc_loss\n # pred_loss = np.NaN\n # else:\n # pred_mask = np.array(np.concatenate(pred_match_list, axis=0) >= 0) # 匹配上GT的mask\n\n # filter_batch_actor_features = batch_actor_features[pred_mask] # 只对匹配上GT的检测框中心点处的特征进行预测\n # pred_way_points = self.model.prediction(filter_batch_actor_features) # 预测6个点的waypoints(6*2)\n\n # gt_way_points = [] # 根据匹配结果获取对应的真值\n # for batch_id, one_match_list in enumerate(pred_match_list):\n # index = [i for i in one_match_list if i >= 0]\n # if len(index) == 0:\n # continue\n # one_gt_way_points = waypoints[batch_id][index]\n\n # gt_way_points.append(one_gt_way_points)\n \n # gt_way_points = torch.tensor(np.concatenate(gt_way_points, axis=0), dtype=torch.float32).view(-1, 12).cuda()\n\n # pred_loss = self.prediction_loss_func(pred_way_points, gt_way_points)\n # loss = perc_loss + pred_loss\n\n loss.backward()\n self.optimizer.step()\n\n # writer.add_scalar(\"loss_all\", loss, self.global_step)\n # writer.add_scalar(\"loss_perc\", perc_loss, self.global_step)\n # writer.add_scalar(\"cls\", cls, self.global_step)\n # writer.add_scalar(\"loc\", loc, self.global_step)\n # writer.add_scalar(\"loss_pred\", pred_loss, self.global_step)\n\n print(\n f'Epoch: [{epoch + 1:0>{len(str(epoch))}}/{self.max_epoch}]',\n f'Step: [{step}/{len(self.data_loader)}]',\n f'Loss-All: {loss.item():.4f}',\n f'Loss-cls: {cls:.4f}',\n f'Loss-loc: {loc:.4f}',\n # f'Loss-Prediction: {pred_loss:.4f}',\n )\n\n if epoch % 10 == 0:\n torch.save(self.model.state_dict(), \\\n './output/kitti/baseline_pp_pose/' + str(epoch) + \".pt\")\n\n\n\n","repo_name":"AkiraHero/perception_imitator","sub_path":"trainer/baseline_trainer.py","file_name":"baseline_trainer.py","file_ext":"py","file_size_in_byte":11611,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"32034365900","text":"from requests import Session as requests_session\nfrom requests.exceptions import ConnectionError\nfrom requests.adapters import HTTPAdapter\nfrom urllib3.util.retry import Retry\nimport re\nimport copy\nimport json\nfrom datetime import datetime, timedelta\nfrom secrets import token_urlsafe\n\nimport re\nctf_initial_data = {\n \"ctf_name\": (\"Event Name Here\",),\n \"ctf_description\": (\"Event Description here\",),\n \"user_mode\": (\"users\",),\n \"challenge_visibility\": (\"private\",),\n \"account_visibility\": (\"private\",),\n \"score_visibility\": (\"private\",),\n \"registration_visibility\": (\"private\",),\n \"verify_emails\": (\"false\",),\n \"team_size\": (\"\",),\n \"email\": (\"admin@localhost.com\",),\n \"ctf_logo\": (\"\",\"\",\"application/octet-stream\"),\n \"ctf_banner\": (\"\",\"\",\"application/octet-stream\"),\n \"ctf_small_icon\": (\"\",\"\",\"application/octet-stream\"),\n \"ctf_theme\": (\"core-beta\",),\n \"theme_color\": (\"\",),\n \"start\": (\"\",),\n \"end\": (\"\",),\n \"_submit\": (\"Finish\",),\n}\n\n#https://stackoverflow.com/questions/63974944/posting-multi-part-form-encoded-dict\n\n#https://stackoverflow.com/a/75695201\ndef dict_to_multipart(dict_data):\n file_data = []\n for key in dict_data.keys():\n value = dict_data[key][0]\n headers = None\n filename = None\n if len(dict_data[key]) >1:\n filename = dict_data[key][1]\n if len(dict_data[key]) >2:\n headers = dict_data[key][2]\n file_data.append((str(key),(filename,str(value),headers)))\n #trial and error: name={0}, filename={1}, Content-Type: {3}, Content:{2}\n return file_data\n\nDEFAULT_THEME_SETTINGS = {\n \"challenge_window_size\": \"xl\",\n \"challenge_category_order\": \"function compare(a, b) {\\r\\n if (a < b) {\\r\\n return -1;\\r\\n }\\r\\n if (a > b) {\\r\\n return 1;\\r\\n }\\r\\n return 0;\\r\\n}\",\n \"challenge_order\": \"function compare(a, b) {\\r\\n if (a.value < b.value) {\\r\\n return -1;\\r\\n }\\r\\n if (a.value > b.value) {\\r\\n return 1;\\r\\n }\\r\\n if (a < b) {\\r\\n return -1;\\r\\n }\\r\\n if (a > b) {\\r\\n return 1;\\r\\n }\\r\\n return 0;\\r\\n}\",\n \"use_builtin_code_highlighter\": True\n}\n\nclass CTFdHelper:\n\n def __init__(self,url_base,username=\"admin\", password=\"password123\", initial_data = ctf_initial_data):\n self.url_base = url_base\n self.password = password\n self.username = username\n self.session = requests_session()\n retry = Retry(connect=3, backoff_factor=0.5)\n adapter = HTTPAdapter(max_retries=retry)\n self.session.mount('http://', adapter)\n self.session.mount('https://', adapter)\n self.api_token = None\n self.csrf_nonce = None\n self.initial_data = initial_data\n #self.establish_session()\n\n def get(self, url, **args):\n return self.session.get(self.url_base + url, **args)\n\n def post(self, url, **args):\n return self.session.post(self.url_base + url, **args)\n\n def patch(self, url, **args):\n return self.session.patch(self.url_base + url, **args)\n\n def delete(self, url, **args):\n return self.session.delete(self.url_base + url, **args)\n\n def api_post(self, url, **args):\n return self.post('/api/v1' + url, **args)\n\n def api_get(self, url, **args):\n return self.get('/api/v1' + url, **args)\n\n def api_patch(self, url, **args):\n return self.patch('/api/v1' + url, **args)\n\n def api_delete(self, url, **args):\n return self.delete('/api/v1' + url, **args)\n\n def api_post_challenge(self,\n name, description, connection_info, value, category, chal_type, max_attempts=0, state=\"visible\"):\n blob = {\n \"name\" : name,\n \"description\": description,\n \"connection_info\": connection_info,\n \"max_attempts\": str(max_attempts),\n \"value\" : str(value),\n \"category\": category,\n \"type\": chal_type,\n \"state\": state,\n }\n return self.api_post('/challenges', json=blob)\n\n def api_get_scoreboard(self):\n return self.api_get('/scoreboard').json()[\"data\"]\n\n def api_get_submissions(self):\n response = self.api_get('/submissions').json()\n pagination = response[\"meta\"][\"pagination\"]\n pages = pagination[\"pages\"]\n results = []\n for page in range(1,int(pages)+1):\n page_response = self.api_get('/submissions?page='+str(page)).json()\n results += page_response[\"data\"]\n return results\n\n def get_backup(self):\n response = self.get(\"/admin/export\")\n return response\n\n def save_backup_to_disk(self,outfile):\n data = self.get_backup()\n f = open(outfile, \"wb\")\n f.write(data.content)\n f.close()\n\n def api_post_flag(self, challenge_id, flag_type, content, data=\"\"):\n blob = {\n \"challenge_id\": challenge_id,\n \"type\" : flag_type,\n \"content\" : content,\n \"data\": data\n }\n return self.api_post('/flags', json=blob)\n\n def api_post_hint(self, challenge_id, hint_type, content, cost=0, requirements={}):\n blob = {\n \"challenge_id\": challenge_id,\n \"type\" : hint_type,\n \"content\" : content,\n \"cost\": cost,\n \"requirements\": requirements\n }\n return self.api_post('/hints', json=blob)\n\n def api_post_user(self, username, password, email, verified=True):\n blob = {\n \"name\": username,\n \"password\" : password,\n \"email\" : email,\n \"verified\": verified\n }\n return self.api_post('/users', json=blob)\n\n def api_post_tag(self, challenge_id, value):\n blob = {\n \"challenge_id\": challenge_id,\n \"value\" : value\n }\n return self.api_post('/tags', json=blob)\n\n def api_post_page(self,\n route,\n title=None,\n content=\"\",\n draft = False,\n hidden=None,\n auth_required=True,\n format=\"markdown\"):\n blob = {\n \"route\" : route,\n \"content\": content,\n \"draft\" : draft,\n \"auth_required\" : auth_required,\n \"format\" : format,\n }\n if title:\n blob[\"title\"] = title\n if hidden != None:\n blob[\"hidden\"] = hidden\n return self.api_post('/pages', json=blob)\n\n def api_patch_page(self, pageid,\n route=None,\n title=None,\n content=None,\n draft=None,\n hidden=None,\n auth_required=None,\n format=\"markdown\"):\n blob = {}\n if route != None:\n blob[\"route\"] = route\n if title != None:\n blob[\"title\"] = title\n if content != None:\n blob[\"content\"] = content\n if draft != None:\n blob[\"draft\"] = draft\n if hidden != None:\n blob[\"hidden\"] = hidden\n if auth_required != None:\n blob[\"auth_required\"] = auth_required\n if format != None:\n blob[\"format\"] = format\n\n return self.api_patch('/pages/{}'.format(pageid), json=blob)\n \n def api_delete_page(self, pageid):\n return self.api_delete('/pages/{}'.format(pageid))\n\n def api_get_page(self, pageid):\n return self.api_get('/pages/{}'.format(pageid))\n\n def api_get_pages(self):\n return self.api_get('/pages')\n \n def api_get_config_list(self):\n return self.api_get('/configs')\n \n def api_get_config_key(self, key):\n return self.api_get('/configs/{}'.format(key))\n \n def api_patch_config_key(self, key, value):\n blob = {key : value}\n return self.api_patch('/configs', json=blob)\n \n def api_delete_config(self, key):\n return self.api_delete('/configs/{}'.format(key))\n \n def api_get_config_fields(self):\n return self.api_get('/configs/fields')\n\n def api_get_config_field(self, field_id):\n return self.api_get('/configs/fields/{}'.format(field_id))\n\n def set_new_theme(self, themename):\n return self.api_patch_config_key(\"ctf_theme\", themename)\n\n def pause_ctf(self):\n blob = {\n \"paused\": True\n }\n return self.api_patch('/configs', json=blob)\n\n def apply_theme_settings(self, settings=False):\n if not settings:\n settings = DEFAULT_THEME_SETTINGS\n blob = {\n \"theme_settings\" : json.dumps(settings)\n }\n return self.api_patch('/configs', json=blob)\n\n def get_challenge_list(self):\n challenges = self.api_get('/challenges')\n challenges_list = challenges.json()[\"data\"]\n return challenges_list\n\n def hide_all_challenges(self):\n challenges = self.get_challenge_list()\n for challenge in challenges:\n self.hide_challenge(challenge[\"id\"])\n\n def hide_challenge(self, challenge_id):\n blob = {\n \"state\": \"hidden\"\n }\n return self.api_patch('/challenges/{}'.format(challenge_id), json=blob)\n\n def show_challenge(self, challenge_id):\n blob = {\n \"state\": \"visible\"\n }\n return self.api_patch('/challenges/{}'.format(challenge_id), json=blob)\n\n def unpause_ctf(self):\n blob = {\n \"paused\": False\n }\n return self.api_patch('/configs', json=blob)\n\n def prep_api(self, force=False):\n if self.api_token == None or force:\n self.get_api_token()\n self.session.headers.update({'Authorization': 'Token ' + self.api_token})\n\n def get_csrf(self, force=False):\n if self.csrf_nonce == None or force:\n text = self.get('/settings').text\n self.csrf_nonce = self.get_csrf_nonce(text)\n self.session.headers.update({\"Csrf-Token\" : self.csrf_nonce})\n return self.csrf_nonce\n\n def get_api_token(self):\n expiration = (datetime.today()+ timedelta(hours=48)).strftime(\"%Y-%m-%d\")\n result = self.post('/api/v1/tokens',\n json={\n \"expiration\": expiration,\n \"description\": \"API Token for CTFdHelper\"\n }\n )\n self.api_token = result.json()['data']['value']\n\n def establish_session(self):\n try:\n resp = self.get('/setup')\n response_text = resp.text\n except ConnectionError as e:\n response_text = \"\"\n if \"SetupForm\" in response_text:\n nonce = self.get_nonce(response_text)\n self.initialize_ctf(nonce)\n else:\n self.login()\n self.get_csrf()\n self.prep_api()\n\n def remove_all_pages(self):\n response = self.api_get_pages().json()\n pages = response[\"data\"]\n for page in pages:\n self.api_delete_page(page[\"id\"])\n \n \n\n def login(self):\n resp = self.get('/login')\n nonce = self.get_nonce(resp.text)\n form_data = {\n \"name\" : (self.username,),\n \"password\" : (self.password,),\n \"nonce\" : (nonce,),\n \"_submit\": (\"Submit\",)\n }\n form_data = dict_to_multipart(form_data)\n resp = self.post('/login', files=form_data)\n\n def create_user(self,username, password):\n resp = self.api_post_user(username, password, username+\"@example.com\")\n return resp\n\n\n def get_nonce(self,pagetext):\n nonce = re.findall('.*name=\"nonce\"[^>]*value=\"([^\"]*)\".*', pagetext)\n if len(nonce) == 0:\n raise Exception('Could not find nonce. Is the CTFd instance actually running?')\n nonce = nonce[0]\n return nonce\n\n def get_csrf_nonce(self,pagetext):\n nonce = re.findall('.*\\'csrfNonce\\': \"([^\"]*)\",', pagetext)\n if len(nonce) == 0:\n raise Exception('Could not find CSRF nonce')\n nonce = nonce[0]\n return nonce\n\n def initialize_ctf(self,nonce):\n instance_data = self.initial_data\n resp = self.get('/setup')\n nonce = self.get_nonce(resp.text)\n instance_data['nonce'] = (nonce,)\n instance_data['password'] = (self.password,)\n instance_data['name'] = (self.username,)\n file_data = dict_to_multipart(instance_data)\n resp = self.post('/setup', files=file_data)\n","repo_name":"bja2142/CTFdHelper","sub_path":"CTFdHelper/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":12457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"23678429733","text":"\"\"\"Helpers for flagging unsafe movements to a Thermocycler Module.\"\"\"\n\n\nfrom typing import List, Optional\n\nfrom opentrons.hardware_control.modules.types import (\n # Renamed to avoid conflicting with ..types.ModuleModel.\n ModuleType as OpentronsModuleType,\n ThermocyclerModuleModel as OpentronsThermocyclerModuleModel,\n)\nfrom opentrons.drivers.types import ThermocyclerLidStatus\nfrom opentrons.hardware_control import HardwareControlAPI\nfrom opentrons.hardware_control.modules import (\n AbstractModule as AbstractHardwareModule,\n Thermocycler as HardwareThermocycler,\n)\n\nfrom ..types import ModuleLocation, ModuleModel as PEModuleModel\nfrom ..state import StateStore\nfrom ..errors import ThermocyclerNotOpenError\n\n\nclass ThermocyclerMovementFlagger:\n \"\"\"A helper for flagging unsafe movements to a Thermocycler Module.\n\n This is only intended for use by MovementHandler.\n It's a separate class for independent testability.\n \"\"\"\n\n def __init__(\n self, state_store: StateStore, hardware_api: HardwareControlAPI\n ) -> None:\n \"\"\"Initialize the ThermocyclerMovementFlagger.\n\n Args:\n state_store: The Protocol Engine state store interface. Used to figure out\n which Thermocycler a labware is in, if any.\n hardware_api: The underlying hardware interface. Used to query\n Thermocyclers' current lid states.\n \"\"\"\n self._state_store = state_store\n self._hardware_api = hardware_api\n\n async def raise_if_labware_in_non_open_thermocycler(self, labware_id: str) -> None:\n \"\"\"Flag unsafe movements to a Thermocycler.\n\n If the given labware is in a Thermocycler, and that Thermocycler's lid isn't\n currently open according to the hardware API, raises ThermocyclerNotOpenError.\n\n Otherwise, no-ops.\n\n Warning:\n Various limitations with our hardware API and Thermocycler firmware mean\n this method can't detect every case where the Thermocycler lid is non-open.\n\n 1. While the lid is in transit, the Thermocycler doesn't respond to status\n polls.\n 2. The Thermocycler doesn't report when the user presses its physical\n lid open button; we have to wait for the next poll to find out, which\n can be tens of seconds because of (1).\n 3. Nothing protects the Thermocycler hardware controller from being accessed\n concurrently by multiple tasks.\n And updating the Thermocycler state from one task doesn't guarantee that\n that update will be immediately visible from a different task.\n So, for example, if a legacy module control HTTP endpoint starts closing\n the Thermocycler, and then a Protocol Engine task quickly polls the\n Thermocycler through this method, this method may see the lid as open\n even though it's in transit.\n \"\"\"\n try:\n thermocycler = await self._find_containing_thermocycler(\n labware_id=labware_id\n )\n\n except self._HardwareThermocyclerMissingError as e:\n raise ThermocyclerNotOpenError(\n \"Thermocycler must be open when moving to labware inside it,\"\n \" but can't confirm Thermocycler's current status.\"\n ) from e\n\n if thermocycler is not None:\n lid_status = thermocycler.lid_status\n if lid_status != ThermocyclerLidStatus.OPEN:\n raise ThermocyclerNotOpenError(\n f\"Thermocycler must be open when moving to labware inside it,\"\n f' but Thermocycler is currently \"{lid_status}\".'\n )\n\n async def _find_containing_thermocycler(\n self,\n labware_id: str,\n ) -> Optional[HardwareThermocycler]:\n \"\"\"Find the hardware Thermocycler containing the given labware.\n\n Returns:\n If the labware was loaded into a Thermocycler,\n the interface to control that Thermocycler's hardware.\n Otherwise, None.\n\n Raises:\n _HardwareThermocyclerMissingError: If the labware was loaded into a\n Thermocycler, but we can't find that Thermocycler in the hardware API,\n so we can't fetch its current lid status.\n It's unclear if this can happen in practice...\n maybe if the module disconnects between when it was loaded into\n Protocol Engine and when this function is called?\n \"\"\"\n module_id = self._get_parent_module_id(labware_id=labware_id)\n if module_id is None:\n return None # Labware not on a module.\n\n module_model = self._state_store.modules.get_model(module_id=module_id)\n if module_model not in [\n PEModuleModel.THERMOCYCLER_MODULE_V1,\n PEModuleModel.THERMOCYCLER_MODULE_V2,\n ]:\n return None # Labware on a module, but not a Thermocycler.\n\n thermocycler_serial = self._state_store.modules.get_serial_number(\n module_id=module_id\n )\n thermocycler = await self._find_thermocycler_by_serial(\n serial_number=thermocycler_serial\n )\n if thermocycler is None:\n raise self._HardwareThermocyclerMissingError(\n f\"No Thermocycler found\" f' with serial number \"{thermocycler_serial}\".'\n )\n\n return thermocycler\n\n def _get_parent_module_id(self, labware_id: str) -> Optional[str]:\n labware_location = self._state_store.labware.get_location(labware_id=labware_id)\n if isinstance(labware_location, ModuleLocation):\n return labware_location.moduleId\n else:\n return None\n\n async def _find_thermocycler_by_serial(\n self, serial_number: str\n ) -> Optional[HardwareThermocycler]:\n \"\"\"Find the hardware Thermocycler with the given serial number.\n\n Returns:\n The matching hardware Thermocycler, or None if none was found.\n \"\"\"\n available_modules, simulating_module = await self._hardware_api.find_modules(\n by_model=OpentronsThermocyclerModuleModel.THERMOCYCLER_V1,\n # Hard-coding instead of using\n # opentrons.protocols.geometry.module_geometry.resolve_module_type(),\n # to avoid parsing a JSON definition every time a protocol moves to\n # something inside a Thermocycler.\n resolved_type=OpentronsModuleType.THERMOCYCLER,\n )\n\n modules_to_check: List[AbstractHardwareModule] = (\n available_modules if simulating_module is None else [simulating_module]\n )\n\n for module in modules_to_check:\n # Different module types have different keys under .device_info.\n # Thermocyclers should always have .device_info[\"serial\"].\n if (\n isinstance(module, HardwareThermocycler)\n and module.device_info[\"serial\"] == serial_number\n ):\n return module\n return None\n\n class _HardwareThermocyclerMissingError(Exception):\n pass\n","repo_name":"MichaelMulieri/opentrons","sub_path":"api/src/opentrons/protocol_engine/execution/thermocycler_movement_flagger.py","file_name":"thermocycler_movement_flagger.py","file_ext":"py","file_size_in_byte":7201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"18793946561","text":"\nfrom collections import deque\nimport math\n\ndef solution(s):\n\n # 문제 정의\n answer = math.inf\n string = s\n\n\n # 문제 풀이\n\n if len(s) == 1:\n return 1\n\n for i in range(1, len(string)//2+1):\n\n queue = deque()\n answerString = \"\"\n localString = \"\"\n\n # 중복 문자열 갯수\n count = 1\n\n # 첫 단위 queue 삽입\n queue.append((string[0 : i]))\n\n\n # 문자열 Index\n\n for j in range(i, len(string)+i, i):\n\n if j == len(string):\n\n if count > 1:\n answerString += str(count) + queue.popleft()\n\n else:\n answerString += queue.popleft()\n\n break\n\n\n if string[j : j+i] == queue[0]:\n count+=1\n\n else:\n\n localString = queue.popleft()\n\n if count > 1:\n answerString += str(count) + localString\n\n else:\n answerString += localString\n\n count = 1\n queue.append((string[j : j+i]))\n\n\n if answer > len(answerString):\n answer = len(answerString)\n\n\n return answer\n","repo_name":"ChiHyeongCho/Python","sub_path":"Algorithm/Algorithm Problems/[2020 카카오] 문자열 압축.py","file_name":"[2020 카카오] 문자열 압축.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"74766874639","text":"from sudoku_solver.timer import Timer\n\n\nclass Strategy:\n def __init__(self):\n self.num_usages = 0\n self.choosing_time = 0\n self.applying_time = 0\n self.type = None\n self.change = None\n\n def invoke(self, sudoku_board, choices):\n self.num_usages += 1\n timer = Timer()\n timer.startTimer()\n changes = self._findChanges(sudoku_board, choices)\n if self.type == \"solve\":\n self._applyChanges(sudoku_board, changes)\n elif self.type == \"choice\":\n self._applyChanges(choices, changes)\n self.applying_time += timer.stopTimer()\n return self.change\n\n def isAppropriate(self, sudoku_board, choices):\n \"\"\"Returns bool that indicates whether this strategy\n would work for a given sudoku board\"\"\"\n timer = Timer()\n timer.startTimer()\n if len(self._findChanges(sudoku_board, choices)) == 0:\n self.choosing_time += timer.stopTimer()\n return False\n self.choosing_time += timer.stopTimer()\n return True\n\n @staticmethod\n def undo(sudoku_board, change):\n if change is not None:\n sudoku_board.setCell(change['row'], change['column'], change['old'])\n\n def _findChanges(self, sudoku_board, choices):\n return {}\n\n def _applyChanges(self, target, changes):\n try:\n if self.type == \"choice\":\n target[changes['row']][changes['column']] = changes['choice_list']\n elif self.type == \"solve\":\n self.change = {'type': self.__class__.__name__, 'row': changes['row'], 'column': changes['column'],\n 'old': target.getCell(changes['row'], changes['column']), 'new': changes['cell']}\n target.setCell(changes['row'], changes['column'], changes['cell'])\n except KeyError:\n return\n","repo_name":"aaronmorgenegg/cs5700","sub_path":"assn4/sudoku/sudoku_solver/strategies/strategy.py","file_name":"strategy.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"43395750531","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport cv2\n\ncap = cv2.VideoCapture(0)\n\nwhile (True):\n ret, frame = cap.read()\n\n # gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\t\n\n cv2.imshow('Capture', frame) # or gray\n if cv2.waitKey(1) & 0xFF == ord('q'): #&0xFF is for 64bit sys\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"Crescent-Saturn/Python_OpenCV","sub_path":"video_test.py","file_name":"video_test.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14569699609","text":"from __future__ import annotations\nimport subprocess\nfrom collections import defaultdict\nfrom os.path import join as pjoin\nfrom tempfile import TemporaryDirectory\nfrom typing import Dict, Iterable, List, Optional, Set, Tuple\n\nfrom seedemu.core import Emulator, Layer, Node, ScionAutonomousSystem\nfrom seedemu.core.ScionAutonomousSystem import IA\nfrom seedemu.layers import ScionBase\n\n\nclass ScionIsd(Layer):\n \"\"\"!\n @brief SCION AS to ISD relationship layer.\n\n This layer configures the membership and status as core AS of SCION ASes in\n SCION Isolation Domains (ISDs). In principle a SCION AS can be a member of\n multiple ISDs simultaneously with different roles as core or non-core AS in\n each ISD. This layer's interface reflects that fact by allowing flexible\n assignment if ASNs to ISDs. In practice however, the current implementation\n of SCION treats the same ASN in different ISDs as entirely unrelated ASes\n [1]. Therefore, we restrict ASes to a single ISD for the moment. Assigning\n an AS to multiple ISDs is detected as an error during rendering.\n\n [1] [Issue #4293: Overlapping ISDs](https://github.com/scionproto/scion/issues/4293)\n \"\"\"\n\n __isd_core: Dict[int, Set[int]] # Core members (ASNs)\n __isd_members: Dict[int, Set[int]] # Non-core members (ASNs)\n __cert_issuer: Dict[IA, int]\n\n def __init__(self):\n super().__init__()\n self.__isd_core = defaultdict(set)\n self.__isd_members = defaultdict(set)\n self.__cert_issuer = {}\n self.addDependency('Routing', False, False)\n\n def getName(self) -> str:\n return \"ScionIsd\"\n\n def addIsdAs(self, isd: int, asn: int, is_core: bool = False) -> 'ScionIsd':\n \"\"\"!\n @brief Add an AS to an ISD.\n\n @param isd ID of the ISD.\n @param asn ASN of the AS which joins the ISD.\n @param is_core Whether the AS becomes a core AS of the ISD.\n\n @returns self\n \"\"\"\n if is_core:\n self.__isd_core[isd].add(asn)\n else:\n self.__isd_members[isd].add(asn)\n\n def addIsdAses(self, isd: int, core: Iterable[int], non_core: Iterable[int]) -> 'ScionIsd':\n \"\"\"!\n @brief Add multiple ASes to an ISD.\n\n @param isd ID of the ISD.\n @param core Set of ASes that will join as core ASes.\n @param non_core Set of ASes that will join as non-core ASes.\n\n @returns self\n \"\"\"\n for asn in core:\n self.__isd_core[isd].add(asn)\n for asn in non_core:\n self.__isd_members[isd].add(asn)\n\n def getAsIsds(self, asn: int) -> List[Tuple[int, bool]]:\n \"\"\"!\n @brief Get the ISDs an AS belongs to.\n\n @returns Pairs of ISD ids and status as core AS in that ISD.\n \"\"\"\n isds = [(isd, True) for isd, ases in self.__isd_core.items() if asn in ases]\n isds += [(isd, False) for isd, ases in self.__isd_members.items() if asn in ases]\n return isds\n\n def isCoreAs(self, isd: int, asn: int) -> bool:\n \"\"\"!\n @brief Check if an AS is a core AS in an ISD.\n\n @param isd ID of the ISD.\n @param asn ASN of the AS.\n\n @returns True if the AS is a core AS in the ISD.\n \"\"\"\n return asn in self.__isd_core[isd]\n\n def setCertIssuer(self, as_: IA|Tuple[int, int], issuer: int) -> 'ScionIsd':\n \"\"\"!\n @brief Set certificate issuer for a non-core AS. Ignored for core ASes.\n\n @param as_ AS for which to set the cert issuer.\n @param issuer ASN of a SCION core as in the same ISD.\n @return self\n \"\"\"\n self.__cert_issuer[IA(*as_)] = issuer\n return self\n\n def getCertIssuer(self, as_: IA|Tuple[int, int]) -> Optional[Tuple[int, int]]:\n \"\"\"!\n @brief Get the cert issuer for a SCION AS in a certain ISD.\n\n @param as_ for which to get the cert issuer.\n @return ASN of the cert issuer or None if not set.\n \"\"\"\n return self.__cert_issuer.get(IA(*as_))\n\n def configure(self, emulator: Emulator) -> None:\n \"\"\"!\n @brief Set SCION AS attributes.\n \"\"\"\n reg = emulator.getRegistry()\n base_layer: ScionBase = reg.get('seedemu', 'layer', 'Base')\n assert issubclass(base_layer.__class__, ScionBase)\n\n for isd, core in self.__isd_core.items():\n for asn in core:\n as_: ScionAutonomousSystem = base_layer.getAutonomousSystem(asn)\n as_.setAsAttributes(isd, ['core', 'voting', 'authoritative', 'issuing'])\n\n def render(self, emulator: Emulator) -> None:\n \"\"\"!\n @brief Generate crypto material and sign TRCs.\n \"\"\"\n reg = emulator.getRegistry()\n base_layer: ScionBase = reg.get('seedemu', 'layer', 'Base')\n assert issubclass(base_layer.__class__, ScionBase)\n\n with TemporaryDirectory(prefix=\"seed_scion\") as tempdir:\n self.__gen_scion_crypto(base_layer, tempdir)\n for ((scope, type, name), obj) in reg.getAll().items():\n if type in ['rnode', 'csnode', 'hnode']:\n node: Node = obj\n asn = node.getAsn()\n as_: ScionAutonomousSystem = base_layer.getAutonomousSystem(asn)\n isds = self.getAsIsds(asn)\n assert len(isds) == 1, f\"AS {asn} must be a member of exactly one ISD\"\n self.__provision_crypto(as_, *isds[0], node, tempdir)\n\n def print(self, indent: int = 0) -> str:\n out = ' ' * indent\n out += 'ScionIsdLayer:\\n'\n\n indent += 4\n for isd, core in self.__isd_core.items():\n out += ' ' * indent\n out += f'Core ASes of ISD{isd}: {core}\\n'\n\n for isd, core in self.__isd_members.items():\n out += ' ' * indent\n out += f'Non-Core ASes of ISD{isd}: {core}\\n'\n\n return out\n\n def __gen_scion_crypto(self, base_layer: ScionBase, tempdir: str):\n \"\"\"Generate cryptographic material in a temporary directory on the host.\"\"\"\n topofile = self.__gen_topofile(base_layer, tempdir)\n self._log(\"Calling scion-pki\")\n try:\n result = subprocess.run(\n [\"scion-pki\", \"testcrypto\", \"-t\", topofile, \"-o\", tempdir, \"--as-validity\", \"30d\"],\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True\n )\n except FileNotFoundError:\n assert False, \"scion-pki not found in PATH\"\n\n for line in result.stdout.split('\\n'):\n self._log(line)\n assert result.returncode == 0, \"scion-pki failed\"\n\n def __gen_topofile(self, base_layer: ScionBase, tempdir: str) -> str:\n \"\"\"Generate a standard SCION .topo file representing the emulated network.\"\"\"\n path = pjoin(tempdir, \"seed.topo\")\n\n with open(path, 'w') as f:\n f.write(\"ASes:\\n\")\n for asn in base_layer.getAsns():\n as_: ScionAutonomousSystem = base_layer.getAutonomousSystem(asn)\n isds = self.getAsIsds(asn)\n isd, is_core = isds[0]\n assert len(isds) == 1, f\"AS {asn} must be a member of exactly one ISD\"\n\n f.write(f' \"{isd}-{asn}\": ')\n attributes = [f\"'{attrib}': true\" for attrib in as_.getAsAttributes(isd)]\n if not is_core:\n assert (isd, asn) in self.__cert_issuer, f\"non-core AS{asn} does not have a cert issuer in ISD{isd}\"\n issuer = self.__cert_issuer[(isd, asn)]\n assert issuer in self.__isd_core[isd] and asn in self.__isd_members[isd]\n attributes.append(f\"'cert_issuer': {isd}-{issuer}\")\n\n f.write(\"{{{}}}\\n\".format(\", \".join(attributes)))\n\n return path\n\n def __provision_crypto(self, as_: ScionAutonomousSystem, isd: int, is_core: bool, node: Node, tempdir: str):\n basedir = \"/etc/scion\"\n asn = as_.getAsn()\n\n def copyFile(src, dst):\n # Tempdir will be gone when imports are resolved, therefore we must use setFile\n with open(src, 'rt', encoding='utf8') as file:\n content = file.read()\n # FIXME: The Docker compiler adds an extra newline in generated files\n # (https://github.com/seed-labs/seed-emulator/issues/125).\n # SCION does not accept PEM files with an extra newline, so we strip a newline here\n # that is later added again.\n if content.endswith('\\n'):\n content = content[:-1]\n node.setFile(dst, content)\n\n def myImport(name):\n copyFile(pjoin(tempdir, f\"AS{asn}\", \"crypto\", name), pjoin(basedir, \"crypto\", name))\n\n if is_core:\n for kind in [\"sensitive\", \"regular\"]:\n myImport(pjoin(\"voting\", f\"ISD{isd}-AS{asn}.{kind}.crt\"))\n myImport(pjoin(\"voting\", f\"{kind}-voting.key\"))\n myImport(pjoin(\"voting\", f\"{kind}.tmpl\"))\n for kind in [\"root\", \"ca\"]:\n myImport(pjoin(\"ca\", f\"ISD{isd}-AS{asn}.{kind}.crt\"))\n myImport(pjoin(\"ca\", f\"cp-{kind}.key\"))\n myImport(pjoin(\"ca\", f\"cp-{kind}.tmpl\"))\n myImport(pjoin(\"as\", f\"ISD{isd}-AS{asn}.pem\"))\n myImport(pjoin(\"as\", \"cp-as.key\"))\n myImport(pjoin(\"as\", \"cp-as.tmpl\"))\n\n #XXX(benthor): trcs need to be known for other isds as well\n for isd in self.__isd_core.keys():\n trcname = f\"ISD{isd}-B1-S1.trc\"\n copyFile(pjoin(tempdir, f\"ISD{isd}\", \"trcs\", trcname), pjoin(basedir, \"certs\", trcname))\n\n # Master keys are generated only once per AS\n key0, key1 = as_.getSecretKeys()\n node.setFile(pjoin(basedir, \"keys\", \"master0.key\"), key0)\n node.setFile(pjoin(basedir, \"keys\", \"master1.key\"), key1)\n","repo_name":"seed-labs/seed-emulator","sub_path":"seedemu/layers/ScionIsd.py","file_name":"ScionIsd.py","file_ext":"py","file_size_in_byte":9832,"program_lang":"python","lang":"en","doc_type":"code","stars":164,"dataset":"github-code","pt":"29"} +{"seq_id":"73926333839","text":"\"\"\"\n给定一个整数数组 nums和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那两整数,并返回它们的数组下标。\n你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。\n你可以按任意顺序返回答案。\n示例 1:\n输入:nums = [2,7,11,15], target = 9\n输出:[0,1]\n解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。\n\"\"\"\nfrom typing import List\n\n\n# class Solution:\n# def twoSum(self, nums: list, target: int) -> list:\n# for i in range(len(nums)):\n# for each in range(i+1,len(nums)):\n# if nums[i] + nums[each] == target:\n# return [i,each]\n# solution = Solution()\n# nums = [3,3]\n# target = 6\n# result = solution.twoSum(nums,target)\n# print(result)\n\n\nclass Solution():\n def twoSum(self, nums: list, target: int) -> list:\n dct = {}\n for i,n in enumerate(nums):\n cp = target - n\n if cp in dct:\n return [dct[cp],i]\n else:\n dct[n] = i\n\nsolution = Solution()\nnums = [2,15,11,7]\ntarget = 9\nresult = solution.twoSum(nums,target)\nprint(result)\n\n\n","repo_name":"stefanmc/Python_learning","sub_path":"leetcode/1. 两数之和.py","file_name":"1. 两数之和.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21829049282","text":"import collections\nimport json\n\nimport colour_conversions\n\nColourIsolationSpec = collections.namedtuple(\"ColourIsolationSpec\",\n ['colour_low', 'colour_high', 'dilations', 'erosions'])\n\n\ndef read_colour_isolation_specs(spec_dict: dict) -> ColourIsolationSpec:\n \"\"\"\n Reads a dict containing colour isolation info and returns a ColourIsolationSpec instance that contains the data\n :param spec_dict: the parameters to put in the specs\n :return:the outputted spec object containing the same data as the dict\n \"\"\"\n out = ColourIsolationSpec(\n colour_low=colour_conversions.hsv360_100_100_to_hsv180_255_255(spec_dict['low']),\n colour_high=colour_conversions.hsv360_100_100_to_hsv180_255_255(spec_dict['high']),\n erosions=spec_dict['erosions'],\n dilations=spec_dict['dilations']\n )\n return out\n\n\nclass DartProfile:\n \"\"\"\n DartProfiles hold the parameters that allow the dart finding algorithm to find a dart of a certian colour.\n A dart profile has two components of type ColourIsolationSpec:\n DartProfile.body and DartProfile.tip\n these contain the details required to extract a dart from the image\n \"\"\"\n def __init__(self, dart_name, tip_low=(0, 0, 0), tip_high=(0, 0, 0), body_low=(0, 0, 0), body_high=(0, 0, 0), tip_erosions=0,\n tip_dilations=0, body_erosions=0, body_dilations=0, identification_colour=(0, 0, 0)) -> None:\n \"\"\"\n Constructor for DartProfile\n :param tip_low: The lower limit for possible tip colours\n :param tip_high: The upper limit for possible tip colours\n :param body_low: The lower limit for possible body colours\n :param body_high: The upper limit for possible body colours\n \"\"\"\n self.identification_colour = identification_colour\n self.dart_name = dart_name\n self.body = ColourIsolationSpec(body_low, body_high, body_dilations, body_erosions)\n self.tip = ColourIsolationSpec(tip_low, tip_high, tip_dilations, tip_erosions)\n\n @staticmethod\n def read_from_file(json_file_in):\n json_info = json.load(json_file_in)\n disabled = json_info.get('disabled')\n\n if disabled:\n print('Disabled: ', json_info['name'])\n return\n\n out = DartProfile(json_info['name'])\n body_data = json_info['body']\n tip_data = json_info['tip']\n\n out.body = read_colour_isolation_specs(body_data)\n out.tip = read_colour_isolation_specs(tip_data)\n out.identification_colour = colour_conversions.hsv360_100_100_to_hsv180_255_255(json_info['id_colour'])\n\n return out\n\n def __str__(self) -> str:\n return f'\"{self.dart_name}\": colour: {self.identification_colour} {{body: {self.body.__str__()} tip: {self.tip.__str__()}}}'\n\n def __repr__(self) -> str:\n return f'{super().__repr__()}: {self.__str__()}'\n\n","repo_name":"AaronLi/Nerf-Dart-Detector","sub_path":"dart_profile.py","file_name":"dart_profile.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"19405604237","text":"#NO.1325 효율적인 해킹\nfrom collections import deque\nimport sys\ninput = sys.stdin.readline\n\ndef bfs(s):\n cnt = 1\n visited = [0] * (n+1)\n qu = deque()\n qu.append(s)\n visited[s] = 1\n while qu:\n a = qu.popleft()\n for i in computer[a]:\n if visited[i]:\n continue\n qu.append(i) \n visited[i] = 1\n cnt += 1\n return cnt\n\nn, m = map(int,input().split())\ncomputer = [[] for _ in range(n+1)]\nfor i in range(m):\n a,b = map(int,input().split())\n # a가 b를 신뢰한다 == b를 해킹하면 a도 해킹가능하다.\n computer[b].append(a)\n\nmaxx = 0\nind = []\nfor i in range(1,n+1):\n cnt = bfs(i)\n #최대값 몇인지 구하기\n if maxx < cnt and cnt > 0:\n maxx = cnt\n # 일단 모두 저장\n ind.append([i,cnt])\n\n#모두 저장한거에서 최대값과 같으면 출력\nfor i, cnt in ind:\n if cnt == maxx:\n print(i, end=' ')\n","repo_name":"iamjunhyeong/In_Python","sub_path":"이코테/DFS&BFS/baekjoon_1325.py","file_name":"baekjoon_1325.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"25799578217","text":"import Component\nimport Resource\nimport G\n\nentCounter = None\nrectCounter = None\nimageCounter = None\n\ndef init():\n\tglobal entCounter, rectCounter, imageCounter\n\tfrom itertools import count\n\tentCounter = count()\n\trectCounter = count()\n\timageCounter = count()\n\n@Resource.require(\"RectRes\")\n@Resource.require(\"ImageRes\")\n@Component.require(\"VelocityComp\")\n@Component.require(\"PositionComp\")\n@Component.require(\"RectComp\")\n@Component.require(\"ImageComp\")\n@Component.require(\"AllMove\")\n@Component.require(\"AllRects\")\n@Component.require(\"AllImages\")\n@Component.require(\"AllEnts\")\ndef create(E, I, R, M, IC, RC, PC, VC, IR, RR, image, rect, center, velocity):\n\trect.center = center\n\t\n\tglobal entCounter, rectCounter, imageCounter\n\tEntID = next(entCounter)\n\tRectID = next(rectCounter)\n\tImageID = next(imageCounter)\n\t\n\tG.CONN.execute(E.insert().values(EntID = EntID))\n\tG.CONN.execute(I.insert().values(ImageID = ImageID))\n\tG.CONN.execute(R.insert().values(RectID = RectID))\n\tG.CONN.execute(M.insert().values(EntID = EntID))\n\t\n\tG.CONN.execute(IC.insert().values(EntID = EntID, ImageID = ImageID))\n\tG.CONN.execute(RC.insert().values(EntID = EntID, RectID = RectID))\n\tG.CONN.execute(PC.insert().values(RectID = RectID, PosX = center[0], PosY = center[1]))\n\tG.CONN.execute(VC.insert().values(RectID = RectID, VelX = velocity[0], VelY = velocity[1]))\n\t\n\tIR[ImageID] = image\n\tRR[RectID] = rect\n\t\n\treturn EntID, RectID, ImageID\n\n@Component.require(\"PlayerComp\")\ndef createPlayer(PC, image, rect, center, velocity):\n\tEntID = create(image, rect, center, velocity)[0]\n\tG.CONN.execute(PC.insert().values(EntID = EntID))\n","repo_name":"strangeprogrammer/FruitPunch","sub_path":"spikes/velocityspike/Entity.py","file_name":"Entity.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"37884551000","text":"# third-party imports\nimport pytest\n\n# local imports\nfrom shpkpr.deployment.bluegreen.prepare import prepare_app_definition\n\n\n@pytest.fixture\ndef app_definition(json_fixture):\n \"\"\"Prepare an app definition for deployment.\n\n This fixture prepares an app and assumes that an existing stack is present\n on Marathon.\n \"\"\"\n new_app_definition_fixture = json_fixture(\"marathon/bluegreen_app_new\")\n old_app_definition_fixture = json_fixture(\"marathon/bluegreen_app_existing\")\n app_states_fixture = json_fixture(\"valid_apps\")\n info_definition_fixture = json_fixture(\"marathon/info\")\n return prepare_app_definition(new_app_definition_fixture,\n old_app_definition_fixture,\n app_states_fixture['apps'],\n info_definition_fixture)\n\n\ndef test_color(app_definition):\n \"\"\"Test that the app's color is set as a label\n \"\"\"\n actual = app_definition['labels']['HAPROXY_DEPLOYMENT_COLOUR']\n expected = \"green\"\n\n assert actual == expected\n\n\ndef test_id(app_definition):\n \"\"\"Test that the app's ID is correctly transformed\n \"\"\"\n actual = app_definition['id']\n expected = \"my-app-green\"\n\n assert actual == expected\n\n\ndef test_docker_service_port(app_definition):\n \"\"\"Test that the service port is set correctly when using docker\n \"\"\"\n actual = app_definition['container']['docker']['portMappings'][0]['servicePort']\n expected = 11091\n\n assert actual == expected\n\n\ndef test_labels_id(app_definition):\n \"\"\"Test that the app's original ID is preserved as a label\n \"\"\"\n actual = app_definition['labels']['HAPROXY_APP_ID']\n expected = \"my-app\"\n\n assert actual == expected\n\n\ndef test_labels_port(app_definition):\n \"\"\"Test that the app's original port is preserved as a label\n \"\"\"\n actual = app_definition['labels']['HAPROXY_0_PORT']\n expected = \"11090\"\n\n assert actual == expected\n\n\ndef test_labels_alt_port(app_definition):\n \"\"\"Test that the app's original port is preserved as a label\n \"\"\"\n actual = app_definition['labels']['HAPROXY_DEPLOYMENT_ALT_PORT']\n expected = \"11091\"\n\n assert actual == expected\n","repo_name":"shopkeep/shpkpr","sub_path":"tests/deployment/bluegreen/prepare/test_existing_deploy.py","file_name":"test_existing_deploy.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"29"} +{"seq_id":"15183124598","text":"from django.shortcuts import get_object_or_404, render,redirect\nfrom django.contrib import messages,auth\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import logout as auth_logout\nfrom django.http import JsonResponse\nimport json\nfrom django.contrib.auth import login, logout\n\nfrom .models import Product,Cart,Cartitems,Customer\n\n\n# Create your views here.\ndef index(request):\n beauty_healths = Product.objects.filter(product_item='Beauty_Health')[:4]\n confectionary = Product.objects.filter(product_item='Confectioneries')[:4]\n drinks = Product.objects.filter(product_item='Drinks')[:4]\n grain_flours = Product.objects.filter(product_item='Grain_Flour')[:4]\n meat_vegetables = Product.objects.filter(product_item='Meat_vegetable')[:4]\n species_oil = Product.objects.filter(product_item='Species_oil')[:4]\n tubers = Product.objects.filter(product_item='Tuber')[:4]\n untensiles = Product.objects.filter(product_item='Untensiles')[:4]\n\n # if request.user.is_authenticated:\n # customer = request.user.customer\n # cart, created = Cart.objects.get_or_create(customer = customer, completed = False)\n # cartitems = cart.cartitems_set.all()\n\n context = {\n 'beauty_healths':beauty_healths,\n 'confectionary':confectionary,\n 'drinks':drinks,\n 'grain_flours':grain_flours,\n 'meat_vegetables':meat_vegetables,\n 'species_oil':species_oil,\n 'tubers':tubers,\n 'untensiles':untensiles,\n # 'cart':cart\n }\n\n\n return render(request, 'screens/index.html',context)\n\ndef beauty_health_page(request):\n beauty_healths = Product.objects.filter(product_item='Beauty_Health')\n\n if request.user.is_authenticated:\n customer = request.user.customer\n cart, created = Cart.objects.get_or_create(customer = customer, completed = False)\n cartitems = cart.cartitems_set.all()\n else:\n cartitems = []\n cart = {\"get_cart_total\": 0, \"get_itemtotal\": 0}\n\n\n context={\n 'beauty_healths':beauty_healths,\n 'cart':cart\n }\n return render(request, 'screens/beauty_health/beauty_health.html',context)\n\ndef beauty(request, beauty_id):\n beautys =Product.objects.filter(product_item='Beauty_Health')\n beauty = get_object_or_404(beautys, pk=beauty_id)\n \n\n context = {\n 'beauty':beauty,\n 'beautys':beautys\n }\n return render(request, 'screens/beauty_health/single_beauty_health.html',context)\n\n\ndef confectioneries_page(request):\n confectioneries = Product.objects.filter(product_item='Confectioneries')\n\n if request.user.is_authenticated:\n customer = request.user.customer\n cart, created = Cart.objects.get_or_create(customer = customer, completed = False)\n cartitems = cart.cartitems_set.all()\n else:\n cartitems = []\n cart = {\"get_cart_total\": 0, \"get_itemtotal\": 0}\n\n\n context={\n 'confectioneries':confectioneries,\n 'cart':cart\n }\n return render(request, 'screens/confentioneries/confentioneries.html',context)\n\ndef confectionerie(request, confectionerie_id):\n confectioneries =Product.objects.filter(product_item='Confectioneries')\n confectionerie = get_object_or_404(confectioneries, pk=confectionerie_id)\n \n\n context = {\n 'confectionerie':confectionerie,\n 'confectioneries':confectioneries\n }\n return render(request, 'screens/confentioneries/single_confentioneries.html',context)\n\ndef drinks_page(request):\n if request.user.is_authenticated:\n customer = request.user.customer\n cart, created = Cart.objects.get_or_create(customer = customer, completed = False)\n cartitems = cart.cartitems_set.all()\n else:\n cartitems = []\n cart = {\"get_cart_total\": 0, \"get_itemtotal\": 0}\n drinks =Product.objects.filter(product_item='Drinks')\n\n\n context={\n 'drinks':drinks,\n 'cart':cart\n }\n return render(request, 'screens/drinks/drinks.html',context)\n\n\ndef drink(request, drink_id):\n drinks =Product.objects.filter(product_item='Drinks')\n drink = get_object_or_404(drinks, pk=drink_id)\n \n\n context = {\n 'drink':drink,\n 'drinks':drinks\n }\n return render(request, 'screens/drinks/single_drinks.html',context)\n\n\ndef grain_flour_page(request):\n grain_flours =Product.objects.filter(product_item='Grain_Flour')\n\n if request.user.is_authenticated:\n customer = request.user.customer\n cart, created = Cart.objects.get_or_create(customer = customer, completed = False)\n cartitems = cart.cartitems_set.all()\n else:\n cartitems = []\n cart = {\"get_cart_total\": 0, \"get_itemtotal\": 0}\n \n context={\n 'grain_flours':grain_flours,\n 'cart':cart\n }\n return render(request, 'screens/grain_flour/grain_flour.html',context)\n\n\ndef grain(request, grain_id):\n grains =Product.objects.filter(product_item='Grain_Flour')\n grain = get_object_or_404(grains, pk=grain_id)\n \n\n context = {\n 'grains':grains,\n 'grain':grain\n }\n return render(request, 'screens/grain_flour/single_grain_flour.html',context)\n\n\ndef meat_vegetable_page(request):\n meat_vegetables =Product.objects.filter(product_item='Meat_vegetable')\n\n if request.user.is_authenticated:\n customer = request.user.customer\n cart, created = Cart.objects.get_or_create(customer = customer, completed = False)\n cartitems = cart.cartitems_set.all()\n else:\n cartitems = []\n cart = {\"get_cart_total\": 0, \"get_itemtotal\": 0}\n\n context={\n 'meat_vegetables':meat_vegetables,\n 'cart':cart\n }\n return render(request, 'screens/meat_vegetable/meat_vegetable.html',context)\n\n\ndef meat(request, meat_id):\n meats =Product.objects.filter(product_item='Meat_vegetable')\n meat = get_object_or_404(meats, pk=meat_id)\n \n\n context = {\n 'meats':meats,\n 'meat':meat\n }\n return render(request, 'screens/meat_vegetable/single_meat_vegetable.html',context)\n\ndef species_oil_page(request):\n species_oils =Product.objects.filter(product_item='Species_oil')\n\n if request.user.is_authenticated:\n customer = request.user.customer\n cart, created = Cart.objects.get_or_create(customer = customer, completed = False)\n cartitems = cart.cartitems_set.all()\n else:\n cartitems = []\n cart = {\"get_cart_total\": 0, \"get_itemtotal\": 0}\n\n context={\n 'species_oils':species_oils,\n 'cart':cart\n }\n return render(request, 'screens/species_oil/species_oil.html',context)\n\n\ndef oil(request, oil_id):\n oils =Product.objects.filter(product_item='Species_oil')\n oil = get_object_or_404(oils, pk=oil_id)\n \n\n context = {\n 'oils':oils,\n 'oil':oil\n }\n return render(request, 'screens/species_oil/single_species_oil.html',context)\n\n\ndef tuber_page(request):\n tubers =Product.objects.filter(product_item='Tuber')\n\n if request.user.is_authenticated:\n customer = request.user.customer\n cart, created = Cart.objects.get_or_create(customer = customer, completed = False)\n cartitems = cart.cartitems_set.all()\n else:\n cartitems = []\n cart = {\"get_cart_total\": 0, \"get_itemtotal\": 0}\n\n\n context={\n 'tubers':tubers,\n 'cart':cart\n }\n return render(request, 'screens/tuber/tuber.html',context)\n\ndef tuber(request, tuber_id):\n tubers =Product.objects.filter(product_item='Tuber')\n tuber = get_object_or_404(tubers, pk=tuber_id)\n \n\n context = {\n 'tubers':tubers,\n 'tuber':tuber\n }\n return render(request, 'screens/tuber/single_tuber.html',context)\n\ndef untensils_page(request):\n untensiles = Product.objects.filter(product_item='Untensiles')\n\n \n \n if request.user.is_authenticated:\n customer = request.user.customer\n cart, created = Cart.objects.get_or_create(customer = customer, completed = False)\n cartitems = cart.cartitems_set.all()\n\n else:\n cartitems = []\n cart = {\"get_cart_total\": 0, \"get_itemtotal\": 0}\n\n context={\n 'untensiles':untensiles,\n 'cart':cart\n }\n\n \n return render(request, 'screens/utensiles/utensiles.html',context)\n\n\ndef africa(request, africa_id):\n africas =Product.objects.filter(product_item='Untensiles')\n africa = get_object_or_404(africas, pk=africa_id)\n \n\n context = {\n 'africas':africas,\n 'africa':africa\n }\n return render(request, 'screens/utensiles/single_utensiles.html',context)\n\n\ndef register_login(request):\n \n if request.method == 'POST':\n # Get from values\n first_name = request.POST['first_name']\n last_name = request.POST['last_name']\n username = request.POST['username']\n email = request.POST['email']\n password = request.POST['password']\n password2 = request.POST['password2']\n\n # check if passwords match\n if password == password2:\n \n # check Username\n if User.objects.filter(username=username).exists():\n messages.error(request, 'That username is taken')\n return redirect('register_login')\n else:\n if User.objects.filter(email=email).exists():\n messages.error(request, 'That email is been used')\n return redirect('register_login')\n else:\n # return\n\n \n user = User.objects.create_user(username=username, password=password, email=email,\n first_name=first_name, last_name=last_name)\n # Login after register\n # auth.login(request, user)\n # messages.success(request, 'You re now logged in')\n # return redirect('index')\n\n user.save()\n messages.success(request, 'you are now registered and can log in')\n return redirect('login')\n\n else:\n messages.error(request, 'passwords do not match')\n return redirect('register_login') \n else:\n return render(request, 'screens/register_login.html')\n \n\ndef login(request):\n if request.method == 'POST':\n # Login User\n username = request.POST['username']\n password = request.POST['password']\n\n user = auth.authenticate(username=username,password=password)\n\n if user is not None:\n auth.login(request, user)\n messages.success(request, 'you are now logged in')\n return redirect('index')\n \n else:\n messages.error(request, 'Invalid credentials')\n return redirect('login')\n else:\n return render(request, 'screens/login.html')\n\n\ndef logout(request):\n auth_logout(request)\n messages.success(request, 'you are now logged out..... Session expired')\n return redirect('login')\n\n\ndef cart(request):\n if request.user.is_authenticated:\n customer = request.user.customer\n cart, created = Cart.objects.get_or_create(customer = customer, completed = False)\n cartitems = cart.cartitems_set.all()\n else:\n cartitems = []\n cart = {\"get_cart_total\": 0, \"get_itemtotal\": 0}\n\n return render(request, 'screens/cart.html', {\n 'cartitems' : cartitems,\n 'cart':cart\n })\n\n\ndef updateCart(request):\n data = json.loads(request.body)\n productId = data[\"productId\"]\n action = data[\"action\"]\n product = Product.objects.get(id=productId)\n customer = request.user.customer\n cart, created = Cart.objects.get_or_create(customer = customer, completed = False)\n cartitem, created = Cartitems.objects.get_or_create(cart = cart, product=product)\n\n if action == \"add\":\n cartitem.quantity += 1\n cartitem.save()\n return JsonResponse(\"Cart Updated\", safe=False)\n\ndef updateQuantity(request):\n data = json.loads(request.body)\n quantityFieldValue = data['qfv']\n quantityFieldProduct = data['qfp']\n product = Cartitems.objects.filter(product__name = quantityFieldProduct).last()\n product.quantity = quantityFieldValue\n product.save()\n return JsonResponse(\"Quantity Updated\", safe=False)\n\ndef checkout(request):\n if request.user.is_authenticated:\n customer = request.user.customer\n cart, created = Cart.objects.get_or_create(customer = customer, completed = False)\n cartitems = cart.cartitems_set.all()\n return render(request, 'screens/checkout.html',{\n 'cartitems' : cartitems,\n 'cart':cart }\n )\n\n\n\ndef order(request):\n return render(request, 'screens/order_page.html')\n","repo_name":"ifekeyz/Follyjay-App","sub_path":"pages/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34433482751","text":"#!/usr/bin/env python3\n\"\"\"\n\tScript to convert files between yaml and json formats\n\"\"\"\nimport json\nimport yaml\nimport argparse\n\n\n# Lets setup the argument parser\nparser = argparse.ArgumentParser(description ='Convert files between JSON and YAML Formats')\n\n\n# Add Arguments\nparser.add_argument('to', metavar='To', choices=['json', 'yaml', 'yml'], help ='Format to convert to')\nparser.add_argument('file', metavar='File', help='Oringal file to convert from')\n\n# Parse the arguments\nargs = parser.parse_args()\n\n# Load the file data\nwith open(args.file, 'r', encoding='utf-8') as file:\n\tfile_data = file.read()\n\n# If JSON convert to YAML\nif args.to == 'json':\n\tsave_file = args.file.rstrip('yaml')\n\tfile_dict = yaml.safe_load(file_data)\n\twith open(f\"{save_file}json\", 'w', encoding ='utf8') as file_out:\n\t\tjson.dump(file_dict, file_out)\nelse:\n\tsave_file = args.file.rstrip('json')\n\tfile_dict = json.loads(file_data)\n\twith open(f\"{save_file}yaml\", 'w', encoding ='utf8') as file_out:\n\t\tyaml.dump(file_dict, file_out)\n","repo_name":"biggiebk/doc_mark_json_yaml","sub_path":"bin/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"11776860908","text":"# # 文件计数与文件中的行列计数\n# import csv\n# import glob # 通过glob模块定位匹配于某个特定模式的所有路径名\n# import os\n# import sys\n#\n# input_path = sys.argv[1]\n# file_counter = 0\n#\n# for input_file in glob.glob(os.path.join(input_path, 'sales_*')): # glob创建了输入文件的列表\n# row_counter = 1\n# with open(input_file, 'r', newline='') as csv_in_file:\n# filereader = csv.reader(csv_in_file)\n# header = next(filereader, None)\n# for row in filereader:\n# row_counter += 1\n# print('{0:s}: \\t{1:d} rows \\t{2:d} columns'.format(os.path.basename(input_file), row_counter, len(header)))\n# file_counter += 1\n# print('Number of files: {0:d}'.format(file_counter))\n\n# # 测试\n# import csv\n#\n# input_file = r'F:\\Coding\\PYTHON\\DataAnalysis\\data\\sales_march.csv'\n#\n# with open(input_file, 'r', newline='') as csv_in_file:\n# filereader = csv.reader(csv_in_file)\n# row_counter = 0\n# for row in filereader:\n# print(row)\n# row_counter += 1\n# print(row_counter)\n\n# # 从多个文件中连接数据\n# import csv\n# import glob\n# import os\n# import sys\n#\n# input_path = sys.argv[1]\n# output_file = sys.argv[2]\n#\n# first_file = True\n# for input_file in glob.glob(os.path.join(input_path, 'sales_*')):\n# print(os.path.basename(input_file)) # 打印文件的基本名\n# with open(input_file, 'r', newline='') as csv_in_file:\n# with open(output_file, 'a', newline='') as csv_out_file: # 采用追加模式写入,防止覆盖\n# filereader = csv.reader(csv_in_file)\n# filewriter = csv.writer(csv_out_file)\n# # 将标题仅写入一次\n# if first_file:\n# for row in filereader:\n# filewriter.writerow(row)\n# first_file = False\n# else:\n# header = next(filereader, None) # 将后续文件的第一行跳过\n# for row in filereader:\n# filewriter.writerow(row)\n\n# # pandas方法从多个CSV中连接数据\n# import pandas as pd\n# import sys\n# import os\n# import glob\n#\n# input_path = sys.argv[1]\n# output_file = sys.argv[2]\n#\n# all_files = glob.glob(os.path.join(input_path, 'sales_*'))\n# all_data_frames = []\n# for file in all_files:\n# data_frames = pd.read_csv(file, index_col=None)\n# all_data_frames.append(data_frames)\n# data_frame_concat = pd.concat(all_data_frames, axis=0, ignore_index=True) # 通过concat函数连接数据框,axis为0时垂直连接,为1时水平连接\n# data_frame_concat.to_csv(output_file, index=False)\n\n# # 计算每个文件中值的总和与均值\n# import csv\n# import glob\n# import os\n# import sys\n#\n# input_path = sys.argv[1]\n# output_file = sys.argv[2]\n#\n# output_header_list = ['file_name', 'total_sales', 'average_sales']\n# csv_out_file = open(output_file, 'a', newline='')\n# filewriter = csv.writer(csv_out_file)\n# filewriter.writerow(output_header_list)\n#\n# for input_file in glob.glob(os.path.join(input_path, 'sales_*')):\n# with open(input_file, 'r', newline='') as csv_in_file:\n# filereader = csv.reader(csv_in_file)\n# output_list = []\n# output_list.append(os.path.basename(input_file))\n# header = next(filereader)\n#\n# total_sales = 0.0\n# number_of_sales = 0.0\n# for row in filereader:\n# sale_amount = row[3]\n# total_sales += float(str(sale_amount).strip('$').replace(',', ''))\n# number_of_sales += 1\n# average_sales = '{0:.2f}'.format(total_sales / number_of_sales)\n# output_list.append(total_sales)\n# output_list.append(average_sales)\n# filewriter.writerow(output_list)\n#\n# csv_out_file.close()\n\n# pandas方法计算总和与均值\nimport pandas as pd\nimport sys\nimport os\nimport glob\n\ninput_path = sys.argv[1]\noutput_file = sys.argv[2]\n\nall_files = glob.glob(os.path.join(input_path, 'sales_*'))\nall_data_frames = []\nfor input_file in all_files:\n data_frame = pd.read_csv(input_file, index_col=None)\n total_cost = pd.DataFrame([float(str(value).strip('$').replace(',', '')) for value in data_frame.loc[:, 'Sale Amount']]).sum()\n average_cost = pd.DataFrame([float(str(value).strip('$').replace(',', '')) for value in data_frame.loc[:, 'Sale Amount']]).mean()\n data = {'file_name': os.path.basename(input_file),\n 'total_sales': total_cost,\n 'average_sales': average_cost}\n all_data_frames.append(pd.DataFrame(data, columns=['file_name', 'total_sales', 'average_sales']))\n\ndata_frames_concat = pd.concat(all_data_frames, axis=0, ignore_index=True)\ndata_frames_concat.to_csv(output_file, index=False)","repo_name":"sinoclover/python","sub_path":"Data-analysis/csv_union.py","file_name":"csv_union.py","file_ext":"py","file_size_in_byte":4701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"24392708218","text":"#!/usr/bin/python\n# coding=utf-8\nimport sys\nimport zipfile\nimport shutil\nimport os\nimport os.path\nimport time\nimport datetime\nimport json\nimport requests \n#include mainResource.py\n# sys.path.append('./common')\n\n# 当前工作目录 Common/PythonLaya/ProjectConfig/Script\nsys.path.append('../../') \nsys.path.append('./') \nfrom Config.Config import mainConfig\nfrom Common import Source \nfrom Config.AdConfig import mainAdConfig \nfrom Project.Resource import mainResource\n\nfrom xml.dom.minidom import parse\nfrom AppStore.AppVersionHuawei import mainAppVersionHuawei\nfrom AppStore.AppVersionApple import mainAppVersionApple\nfrom AppStore.Huawei.HuaweiAppGalleryApi import mainHuaweiAppGalleryApi\nfrom AppStore.AppStoreAcount import mainAppStoreAcount\n\nfrom AppInfo.AppInfoOld import AppInfoOld\nfrom AppInfo.AppInfoNew import AppInfoNew\nfrom Common.File.JsonUtil import JsonUtil \nfrom Common.File.FileUtil import FileUtil \n\nclass AppInfo(): \n versionCode = 100\n rootJson=None\n\n def GetUrl(self, url): \n r = requests.get(url)\n return r.content.decode('utf-8',\"ignore\")\n\n def GetSmsCode(self): \n # url = \"http://47.242.56.146:5000/GetSmsCode\" \n url = \"http://mooncore.cn:5000/GetSmsCode\" \n return self.GetUrl(url) \n\n def SetSmsCode(self,code): \n url = \"http://mooncore.cn:5000/SetSmsCode?code=\"+code\n return self.GetUrl(url) \n\n def SetCmdPath(self,cmdPath): \n mainResource.SetCmdPath(cmdPath)\n\n def GetJsonAppId(self,jsonData, channel): \n return jsonData[\"appid\"][channel] \n \n\n def GetPackage(self,osSrc,isHD): \n jsonData = self.loadJson(isHD) \n isOld = self.IsOldVersion(jsonData)\n ret = \"\"\n if isOld:\n key = \"PACKAGE_IOS\"\n if osSrc == Source.ANDROID:\n key = \"PACKAGE_ANDROID\" \n ret = jsonData[key]\n else: \n if osSrc == Source.ANDROID:\n ret = jsonData[\"apppackage\"][Source.ANDROID][\"default\"] \n if osSrc == Source.IOS:\n ret = jsonData[\"apppackage\"][Source.IOS][\"default\"]\n\n return ret\n\n def GetJsonFile(self,isHd):\n cur_path = mainResource.GetProjectConfigApp()+\"/appinfo\"\n jsonfile = cur_path+'/appinfo.json'\n if isHd:\n jsonfile = cur_path+'/appinfo_hd.json'\n return os.path.normpath(jsonfile)\n\n def loadJson(self,isHd): \n # if self.rootJson!=None:\n # return self.rootJson\n jsonfile = self.GetJsonFile(isHd) \n strfile = FileUtil.GetFileString(jsonfile)\n self.rootJson = json.loads(strfile)\n return self.rootJson\n \n # with open(jsonfile, 'rb') as json_file:\n # data = json.load(json_file)\n # return data\n\n\n def replaceString(self,strContent, strStart, strEnd, strReplace):\n idx = strContent.find(strStart)\n strHead = strContent[0:idx]\n\n idx = idx + len(strStart)\n strOther = strContent[idx:]\n # print \"strOther1:\"+strOther\n idx = strOther.find(strEnd)\n strOther = strOther[idx:]\n # print \"strOther2:\"+strOther\n strRet = strHead + strStart + strReplace + strOther\n return strRet\n\n\n def replaceFile(self,filePath, strOld, strReplace): \n strFile = FileUtil.GetFileString(filePath)\n strOut = strFile.replace(strOld, strReplace) \n self.saveString2File(strOut, filePath)\n\n\n def replaceStringOfFile(self,filePath, strStart, strEnd, strReplace):\n # f = open(filePath)\n # f = open(filePath,'r', encoding='UTF-8') \n strFile = FileUtil.GetFileString(filePath)\n # strFile.decode('utf-8')\n # print strFile\n strOut = self.replaceString(strFile, strStart, strEnd, strReplace)\n # print strOut\n # fp_name.seek(0)\n # fp_name.write(strOut) \n return strOut\n\n def replacePackage(self,filePath,package):\n strFile = FileUtil.GetFileString(filePath) \n strFile = strFile.replace(\"_PACKAGE_\", package)\n FileUtil.SaveString2File(strFile,filePath)\n\n def replaceFileForKey(self,filePath,key,content):\n # f = open(filePath, 'rb')\n # f = open(filePath,'r', encoding='utf-8')\n strFile = FileUtil.GetFileString(filePath) \n strFile = strFile.replace(key, content)\n FileUtil.SaveString2File(strFile,filePath)\n\n def replaceFile(self,filePath,key,value):\n strFile = FileUtil.GetFileString(filePath) \n strFile = strFile.replace(key, value)\n FileUtil.SaveString2File(strFile,filePath) \n\n def replaceScreenOrientation(self,filePath,isHd):\n strFile = FileUtil.GetFileString(filePath)\n\n str = \"sensorPortrait\"\n if isHd:\n str = \"sensorLandscape\"\n\n strFile = strFile.replace(\"_SCREENORIENTATION_\", str)\n\n FileUtil.SaveString2File(strFile,filePath)\n\n def replaceString2(self,strContent, strStart, strMid, strEnd, strReplace):\n idx = strContent.find(strStart)\n if idx<0:\n return strContent\n strHead = strContent[0:idx] + strStart\n\n idx = idx + len(strStart)\n strOther = strContent[idx:] \n idx = strOther.find(strMid)\n strHead2 = strOther[0:idx] + strMid\n strHead += strHead2\n\n # print \"strOther1=\"+strOther \n strOther = strOther[idx+len(strMid):]\n # print \"strOther2=\"+strOther\n\n idx = strOther.find(strEnd)\n strOther = strOther[idx:] \n strRet = strHead + strReplace + strOther\n return strRet\n\n\n def replaceStringOfFile2(self,filePath, strStart, strMid, strEnd, strReplace):\n strFile = FileUtil.GetFileString(filePath)\n # print strFile\n strOut = self.replaceString2(strFile, strStart, strMid, strEnd, strReplace)\n # print strOut\n # fp_name.seek(0)\n # fp_name.write(strOut) \n return strOut\n\n\n def saveString2File(self,str, file):\n FileUtil.SaveString2File(str, file)\n\n\n def replaceGoogleServiceFile(self,file, package):\n\n strStart = \"client_id\\\": \\\"android:\"\n strEnd = \"\\\"\"\n strOut = self.replaceStringOfFile(file, strStart, strEnd, package)\n self.saveString2File(strOut, file)\n\n strStart = \"package_name\\\": \\\"\"\n strEnd = \"\\\"\"\n strOut = self.replaceStringOfFile(file, strStart, strEnd, package)\n self.saveString2File(strOut, file)\n\n strStart = \"\\\"android_info\\\"\"\n strMid = \"package_name\\\": \\\"\"\n strEnd = \"\\\",\"\n strOut = self.replaceStringOfFile2(file, strStart, strMid, strEnd, package)\n self.saveString2File(strOut, file)\n\n def replaceXcodeUrlScheme(self,filePath, src, appid,idx):\n strFile = FileUtil.GetFileString(filePath)\n\n # WEIXIN_APPID\n if src==Source.WEIXIN or src==Source.WEIXINFRIEND:\n strOld = \"WEIXIN_APPID\"\n if src==Source.WEIBO:\n strOld = \"WEIBO_APPID\"\n if src==Source.QQ or src==Source.QQZONE:\n if idx==0:\n strOld = \"QQ_APPID0\"\n if idx==1:\n strOld = \"QQ_APPID1\"\n\n strNew = \"\"+mainConfig.XcodeUrlScheme(src,appid,idx)+\"\" \n\n strOut = strFile.replace(strOld, strNew) \n self.saveString2File(strOut,filePath)\n \n\n\n\n def updateXiaoASOkeyword(self,jsonData,isHd):\n jsonfile = self.GetJsonFile(isHd)\n isOld = self.IsOldVersion(jsonData)\n if isOld:\n APPSTORE_KEYWORD = jsonData[\"APPSTORE_KEYWORD\"]\n strStart = \"XIAOMI_KEYWORD\"\n else:\n APPSTORE_KEYWORD = jsonData[\"appstore\"][\"aso\"]\n strStart = \"aso_xiaomi\"\n\n \n cn = APPSTORE_KEYWORD[\"cn\"]\n en = APPSTORE_KEYWORD[\"en\"]\n cn = cn.replace(\",\",\" \")\n en = en.replace(\",\",\" \")\n\n \n strEnd = \"\\\"\"\n\n strFile = FileUtil.GetFileString(jsonfile)\n\n strMid = \"\\\"cn\\\": \\\"\"\n strFile = self.replaceString2(strFile, strStart, strMid, strEnd, cn)\n\n strMid = \"\\\"en\\\": \\\"\"\n strFile = self.replaceString2(strFile, strStart, strMid, strEnd, en)\n FileUtil.SaveString2File(strFile, jsonfile)\n\n def copyResFiles(self,str):\n dir_default = mainResource.GetProjectConfigDefault()\n # \"../../../default\"\n dir_to = mainResource.GetProjectConfigApp()\n\n dir1 = dir_default+\"/\"+str\n dir2 = dir_to + \"/\"+str\n print(dir2)\n flag = os.path.exists(dir2)\n if flag:\n shutil.rmtree(dir2)\n shutil.copytree(dir1,dir2)\n\n # def SaveJson(filePath,dataRoot): \n # oldvalue = \"\"\n # # \"huawei\": \"0\",\n # # str1 = \"\\\"\"+key+\"\\\"\"+\": \\\"\"+oldvalue+\"\\\"\"\n # # str2 = \"\\\"\"+key+\"\\\"\"+\": \\\"\"+value+\"\\\"\"\n # # replaceFile(filePath, str1, str2)\n\n # # 保存json\n # with open(filePath, 'w') as f:\n # json.dump(dataRoot, f, ensure_ascii=False,indent=4,sort_keys = True)\n\n\n def autoPlusVersion(self,isHd,jsonData): \n jsonfile = self.GetJsonFile(isHd) \n int_v = int(self.versionCode)\n int_v=int_v+1\n self.versionCode = str(int_v)\n dataCode = jsonData[\"appversion\"][Source.ANDROID]\n dataCode[\"code\"]=self.versionCode\n\n data = jsonData[\"appversion\"][Source.ANDROID]\n data[\"value\"]=self.versionCodeToVersion(self.versionCode)\n\n \n data = jsonData[\"appversion\"][Source.IOS]\n codeios = data[\"code\"]\n int_v = int(codeios)\n int_v=int_v+1\n codeios = str(int_v)\n data[\"code\"]=codeios\n # self.versionCode = codeios\n data[\"value\"]=self.versionCodeToVersion(codeios)\n\n # SaveJson(jsonfile,jsonData)\n JsonUtil.SaveJson(jsonfile,jsonData) \n # strnew_version_ios = \"\\\"APPVERSION_IOS\\\": \\\"\"+versionCodeToVersion()+\"\\\"\"\n\n\n\n \n\n\n # 161 to 1.6.1\n def versionCodeToVersion(self,value):\n print (\"versionCodeToVersion=\", value)\n code_v = int(value)\n # \n v0 = int(code_v/100)\n v1 =int((code_v-v0*100)/10)\n v2 = code_v-v0*100-v1*10\n ret = str(v0)+\".\"+str(v1)+\".\"+str(v2)\n return ret\n\n def updateAndroidManifest(self,filepath,package,appversion,appversioncode,isHd):\n # version \n self.replaceFileForKey(filepath,\"_VERSIONNAME_\",appversion) \n \n self.replaceFileForKey(filepath,\"_VERSIONCODE_\",appversioncode) \n\n # package \n self.replaceFileForKey(filepath,\"_PACKAGE_\",package) \n # ScreenOrientation\n self.replaceScreenOrientation(filepath,isHd) \n\n # baidu\n appid_baidu = mainAdConfig.GetAppId(Source.BAIDU,Source.ANDROID,isHd)\n self.replaceFileForKey(filepath,\"_BAID_AD_APPID_\",appid_baidu) \n \n\n\n def IsOldVersion(self,data):\n isOld = True\n if (\"appname\" in data) :\n isOld = False \n \n return isOld\n\n def GetCSVName(self,strContent,isHd): \n idxstart = strContent.find(\"APP_NAME\")\n if isHd:\n idxstart = strContent.find(\"APP_NAME_HD\")\n\n strContent = strContent[idxstart:] \n idxend = strContent.find(\"\\r\\n\")\n if idxend<0:\n idxend = strContent.find(\"\\n\")\n\n strContent = strContent[0:idxend] \n return strContent\n\n\n def UpdateLanguageName(self,csvfile,name_cn,name_en,ishd): \n strContent = FileUtil.GetFileString(csvfile)\n key_name = self.GetCSVName(strContent,ishd) \n\n head = \"APP_NAME\"\n if ishd:\n head = \"APP_NAME_HD\"\n\n str_new = head+\",\"+name_cn+\",\" +name_en\n # +\"\\n\"\n self.replaceFile(csvfile,key_name,str_new)\n\n\n def GetConfigDataAppId(self,os,chanel,ishd):\n dirconfig = mainResource.GetConfigDataDir()\n filepath = \"\"\n appid = \"\"\n if os==Source.ANDROID:\n filepath = dirconfig+\"/config/config_android.json\"\n if ishd:\n filepath = dirconfig+\"/config/config_android_hd.json\"\n \n if os==Source.IOS:\n filepath = dirconfig+\"/config/config_ios.json\"\n if ishd:\n filepath = dirconfig+\"/config/config_ios_hd.json\"\n \n\n with open(filepath) as json_file:\n data = json.load(json_file)\n appid = data[\"APPID\"][chanel] \n\n return appid\n\n def SetConfigDataAppId(self,os,chanel,appid,ishd):\n dirconfig = mainResource.GetConfigDataDir()\n filepath = \"\"\n if os==Source.ANDROID:\n filepath = dirconfig+\"/config/config_android.json\"\n if ishd:\n filepath = dirconfig+\"/config/config_android_hd.json\"\n \n if os==Source.IOS:\n filepath = dirconfig+\"/config/config_ios.json\"\n if ishd:\n filepath = dirconfig+\"/config/config_ios_hd.json\"\n \n\n with open(filepath) as json_file:\n data = json.load(json_file)\n data[\"APPID\"][chanel] = appid\n # SaveJson(filepath,data)\n JsonUtil.SaveJson(filepath,data)\n\n def GetAppUpdate(self,isHd,lan): \n data = self.loadJson(isHd) \n name = data[\"appstore\"][\"version_update\"][lan]\n return name \n\n def GetAppSubtitle(self,isHd,lan): \n data = self.loadJson(isHd) \n name = data[\"appstore\"][\"subtitle\"][lan]\n return name \n\n\n\n def GetAppDetail(self,isHd,lan): \n src = mainResource.GetProjectConfigApp()+\"/appinfo/app_description.xml\"\n if isHd:\n src = mainResource.GetProjectConfigApp()+\"/appinfo/app_description_hd.xml\"\n\n domTree = parse(src)\n # 文档根元素root = domTree.documentElement\n root = domTree.documentElement\n # print(root.nodeName)\n \n strret =\" \" \n key = lan\n # if lan==Source.LANGUAGE_CN:\n # key = \"cn\"\n\n list = root.getElementsByTagName(key)\n for item in list:\n strret = item.childNodes[0].data \n\n # print(strret)\n return strret\n # for customer in customers:\n # \tif customer.hasAttribute(\"ID\"):\n # \t\tprint(\"ID:\", customer.getAttribute(\"ID\"))\n # \t\t# name 元素\n # \t\tname = customer.getElementsByTagName(\"name\")[0]\n # \t\tprint(name.nodeName, \":\", name.childNodes[0].data)\n # \t\t# phone 元素\n # \t\tphone = customer.getElementsByTagName(\"phone\")[0]\n # \t\tprint(phone.nodeName, \":\", phone.childNodes[0].data)\n # \t\t# comments 元素\n # \t\tcomments = customer.getElementsByTagName(\"comments\")[0]\n # \t\tprint(comments.nodeName, \":\", comments.childNodes[0].data)\n\n\n\n def GetAppVersion(self,os,isHd): \n # loadJson\n data = self.loadJson(isHd) \n name = data[\"appversion\"][os][\"value\"]\n return name\n\n def GetAppVersionCode(self,os,isHd): \n # loadJson\n data = self.loadJson(isHd) \n name = data[\"appversion\"][os][\"code\"]\n return name\n\n def LoadJsonConfigCommon(self): \n jsonfile = mainResource.GetConfigDataDir()+\"/config/config_common.json\" \n jsonfile = os.path.normpath(jsonfile)\n strfile = FileUtil.GetFileString(jsonfile)\n return json.loads(strfile) \n\n def GetAppStoreAcount(self,isHd,appstore): \n data = self.LoadJsonConfigCommon()\n key = \"appstore_acount\"\n name = \"chyfemail163@163.com\"\n if appstore==Source.IOS:\n name = \"chyfemail163@163.com\"\n if key in data:\n name = data[key][appstore]\n print(\" GetAppStoreAcount name=\",name)\n\n return name \n\n def GetAppPromotion(self,isHd,lan): \n data = self.loadJson(isHd) \n name = data[\"appstore\"] [\"promotion\"][lan]\n return name \n \n def GetAppName(self,os,isHd,lan): \n # loadJson\n data = self.loadJson(isHd) \n name = data[\"appname\"][os][lan]\n return name \n\n def GetAppPackage(self,os,isHd): \n # loadJson\n data = self.loadJson(isHd) \n name = data[\"apppackage\"][os][\"default\"]\n return name \n\n def GetAppPrivacyUrl(self,isHd): \n # loadJson\n data = self.loadJson(isHd) \n name = data[\"privacy_url\"]\n return name \n\n def GetAppSKU(self,isHd): \n # loadJson\n data = self.loadJson(isHd) \n name = data[\"sku_app\"]\n return name \n\n def GetAppSoftwareUrl(self,isHd): \n # loadJson\n data = self.loadJson(isHd) \n name = data[\"software_url\"]\n return name \n\n def GetAppSupportUrl(self,isHd): \n # loadJson\n data = self.loadJson(isHd) \n name = data[\"support_url\"]\n return name \n\n def GetAppUrl(self,os,isHd,channel): \n # loadJson\n appid = self.GetAppId(isHd, channel)\n url = \"\"\n if os == Source.ANDROID:\n if channel == Source.TAPTAP:\n url = \"https://www.taptap.com/app/\"+appid\n else: \n url = \"https://appgallery1.huawei.com/#/app/C\"+appid \n\n if os == Source.IOS:\n appid = self.GetAppId(isHd, Source.APPSTORE)\n url = \"https://apps.apple.com/cn/app/id\"+appid\n\n return url \n\n \n \n def GetAppId(self,isHd,channel): \n # loadJson\n data = self.loadJson(isHd) \n appid = data[\"appid\"][channel] \n return appid \n \n def SetAppVersion(self,isHd,os,value): \n # loadJson\n data = self.loadJson(isHd) \n data[\"appversion\"][os][\"value\"] = value\n filePath = self.GetJsonFile(isHd)\n JsonUtil.SaveJson(filePath,data)\n\n def SetAppVersionCode(self,isHd,os,value): \n # loadJson\n data = self.loadJson(isHd) \n data[\"appversion\"][os][\"code\"] = value\n filePath = self.GetJsonFile(isHd)\n JsonUtil.SaveJson(filePath,data) \n\n def SetAppId(self,isHd,os,channel,appid):\n # loadJson\n data = self.loadJson(isHd) \n data[\"appid\"][channel] =appid\n filePath = self.GetJsonFile(isHd)\n JsonUtil.SaveJson(filePath,data)\n\n def SetAso(self,isHd,channel,lan,aso):\n # loadJson\n if len(aso)==0:\n return\n \n data = self.loadJson(isHd) \n key = \"aso\"\n data[\"appstore\"][key][lan] =aso\n filePath = self.GetJsonFile(isHd)\n JsonUtil.SaveJson(filePath,data) \n\n def GetAso(self,isHd,channel,lan): \n data = self.loadJson(isHd) \n key = \"aso\"\n ret = data[\"appstore\"][key][lan]\n if len(ret)>100:\n ret = ret[0:100]\n print(\" aso count =\",len(ret))\n return ret \n\n def ConvertOld2New(self,isHd,appinfoOld):\n appinfoNew = AppInfoNew(isHd)\n\n # appid\n appid = appinfoOld.GetAppId(Source.HUAWEI)\n appinfoNew.SetAppId(Source.HUAWEI,appid)\n\n appid = appinfoOld.GetAppId(Source.TAPTAP)\n appinfoNew.SetAppId(Source.TAPTAP,appid)\n\n appid = appinfoOld.GetAppId(Source.APPSTORE) \n appinfoNew.SetAppId(Source.APPSTORE,appid)\n\n appid = \"0\"\n appinfoNew.SetAppId(Source.XIAOMI,appid)\n\n # appname \n name = appinfoOld.GetAppName(Source.ANDROID,Source.LANGUAGE_CN)\n appinfoNew.SetAppName(Source.ANDROID,Source.LANGUAGE_CN,name)\n name = appinfoOld.GetAppName(Source.ANDROID,Source.LANGUAGE_EN)\n appinfoNew.SetAppName(Source.ANDROID,Source.LANGUAGE_EN,name)\n name = appinfoOld.GetAppName(Source.IOS,Source.LANGUAGE_CN)\n appinfoNew.SetAppName(Source.IOS,Source.LANGUAGE_CN,name)\n name = appinfoOld.GetAppName(Source.IOS,Source.LANGUAGE_EN)\n appinfoNew.SetAppName(Source.IOS,Source.LANGUAGE_EN,name)\n\n # apppackage\n name = appinfoOld.GetPackage(Source.ANDROID)\n appinfoNew.SetAppPackage(Source.ANDROID,name)\n name = appinfoOld.GetPackage(Source.IOS)\n appinfoNew.SetAppPackage(Source.IOS,name)\n\n\n # appstore\n aso = appinfoOld.APPSTORE_KEYWORD(Source.LANGUAGE_CN)\n aso_xiaomi = appinfoOld.APPSTORE_KEYWORD(Source.LANGUAGE_CN)\n promotion = appinfoOld.APPSTORE_PROMOTION(Source.LANGUAGE_CN)\n subtitle = appinfoOld.APPSTORE_SUBTITLE(Source.LANGUAGE_CN)\n title = appinfoOld.APPSTORE_TITLE(Source.LANGUAGE_CN)\n version_update = appinfoOld.APPSTORE_VERSION_UPDATE(Source.LANGUAGE_CN)\n appinfoNew.SetAppstore(Source.LANGUAGE_CN,aso,aso_xiaomi,promotion,subtitle,title,version_update)\n\n aso = appinfoOld.APPSTORE_KEYWORD(Source.LANGUAGE_EN)\n aso_xiaomi = appinfoOld.APPSTORE_KEYWORD(Source.LANGUAGE_EN)\n promotion = appinfoOld.APPSTORE_PROMOTION(Source.LANGUAGE_EN)\n subtitle = appinfoOld.APPSTORE_SUBTITLE(Source.LANGUAGE_EN)\n title = appinfoOld.APPSTORE_TITLE(Source.LANGUAGE_EN)\n version_update = appinfoOld.APPSTORE_VERSION_UPDATE(Source.LANGUAGE_EN)\n appinfoNew.SetAppstore(Source.LANGUAGE_EN,aso,aso_xiaomi,promotion,subtitle,title,version_update)\n\n\n # appversion\n version = appinfoOld.GetAppVersion(Source.ANDROID)\n code = appinfoOld.GetAppVersionCode(Source.ANDROID)\n appinfoNew.SetAppversion(Source.ANDROID,code,version)\n\n version = appinfoOld.GetAppVersion(Source.IOS)\n code = appinfoOld.GetAppVersionCode(Source.IOS)\n appinfoNew.SetAppversion(Source.IOS,code,version)\n\n\n appinfoNew.SetKeyVaule(\"need_upload_screenshot\",appinfoOld.need_upload_screenshot())\n\n appinfoNew.SetKeyVaule(\"email\",\"chyfemail163@163.com\")\n appinfoNew.SetKeyVaule(\"privacy_url\",\"https://6c69-lianlianle-shkb3-1259451541.tcb.qcloud.la/PrivacyPolicy.txt\")\n appinfoNew.SetKeyVaule(\"privacy_url2\",\"https://6d6f-moonma-dbb297-1258816908.tcb.qcloud.la/Moonma/privacyPolicy_kidsgame.txt\")\n appinfoNew.SetKeyVaule(\"privacy_url3\",\" http://www.mooncore.cn/index/privacyPolicy_kidsgame.shtml\")\n appinfoNew.SetKeyVaule(\"software_url\",\" http://www.mooncore.cn\")\n appinfoNew.SetKeyVaule(\"support_url\",\" http://blog.sina.com.cn/s/blog_1736372fb0102xb49.html\")\n appinfoNew.SetKeyVaule(\"sku_app\",appinfoOld.sku_app())\n \n appinfoNew.Save() \n\n def updateName(self,isHd,isAuto):\n\n name = mainAppInfo.GetAppStoreAcount(isHd,Source.HUAWEI)\n mainHuaweiAppGalleryApi.ClientId = mainAppStoreAcount.GetClientId(Source.HUAWEI,name)\n mainHuaweiAppGalleryApi.ClientSecret = mainAppStoreAcount.GetClientSecret(Source.HUAWEI,name) \n \n appinfoOld = AppInfoOld(isHd)\n if appinfoOld.IsOldVersion():\n # 转换\n self.ConvertOld2New(isHd,appinfoOld)\n\n\n rootConfig = mainResource.GetProjectConfigApp()\n strHD = \"HD\"\n\n project_ios = rootConfig + \"/ios/project\"\n project_android = rootConfig + \"/android/project\"\n\n if isHd:\n project_ios = rootConfig + \"/ios/project_hd\"\n project_android = rootConfig + \"/android/project_hd\"\n\n # android\n file_name_cn_android = project_android + \"/res/values/strings.xml\"\n file_name_en_android = project_android + \"/res/values-en/strings.xml\"\n file_AndroidManifest = project_android + \"/xml/AndroidManifest.xml\"\n file_AndroidManifest_GP = project_android + \"/xml_gp/AndroidManifest.xml\"\n \n\n file_google_service_android = project_android + \"/config/google-services.json\"\n\n # ios\n file_name_cn_ios = project_ios + \"/appname/zh-Hans.lproj/InfoPlist.strings\"\n file_name_en_ios = project_ios + \"/appname/en.lproj/InfoPlist.strings\"\n file_info_plist_ios = project_ios + \"/Info.plist\"\n\n # loadJson\n data = self.loadJson(isHd) \n\n \n appname = data[\"appname\"]\n \n APP_NAME_CN_ANDROID = appname[Source.ANDROID][\"cn\"]\n APP_NAME_EN_ANDROID = appname[Source.ANDROID][\"en\"]\n APP_NAME_CN_IOS = appname[Source.IOS][\"cn\"]\n APP_NAME_EN_IOS = appname[Source.IOS][\"en\"] \n PACKAGE_ANDROID = data[\"apppackage\"][Source.ANDROID][\"default\"]\n PACKAGE_IOS = data[\"apppackage\"][Source.IOS][\"default\"]\n self.versionCode = data[\"appversion\"][Source.ANDROID][\"code\"]\n APPVERSION_IOS = data[\"appversion\"][Source.IOS][\"value\"]\n \n #appid \n appid_ios = self.GetJsonAppId(data,Source.APPSTORE)\n appid_taptap = self.GetJsonAppId(data,Source.TAPTAP)\n appid_huawei = self.GetJsonAppId(data,Source.HUAWEI)\n self.SetConfigDataAppId(Source.IOS,Source.APPSTORE,appid_ios,isHd)\n self.SetConfigDataAppId(Source.ANDROID,Source.TAPTAP,appid_taptap,isHd)\n self.SetConfigDataAppId(Source.ANDROID,Source.HUAWEI,appid_huawei,isHd)\n\n csvfile = mainResource.GetConfigDataDir()+\"/language/language.csv\" \n self.UpdateLanguageName(csvfile,APP_NAME_CN_ANDROID,APP_NAME_EN_ANDROID,isHd)\n\n csvfile = mainResource.GetRootUnityAssetsResource()+\"/ConfigData/language/language.csv\" \n self.UpdateLanguageName(csvfile,APP_NAME_CN_ANDROID,APP_NAME_EN_ANDROID,isHd)\n\n \n # if data.has_key(\"PACKAGE_HD_ANDROID\"):\n # PACKAGE_HD_ANDROID = data[\"PACKAGE_HD_ANDROID\"]\n\n\n \n \n if isAuto==True: \n self.autoPlusVersion(isHd,data)\n # 重新加载\n data = self.loadJson(isHd)\n APPVERSION_IOS = data[\"appversion\"][Source.IOS][\"value\"]\n \n self.versionCode = data[\"appversion\"][Source.ANDROID][\"code\"]\n\n APPVERSION_ANDROID = self.versionCodeToVersion(self.versionCode)\n APPVERSION_CODE_ANDROID = self.versionCode\n \n\n # appversion.json\n if isAuto==False: \n src = mainResource.GetProjectConfigDefault()+\"/appinfo/appversion.json\"\n dst = mainResource.GetProjectConfigApp()+\"/appinfo/appversion.json\"\n flag = os.path.exists(dst)\n # \n if not isHd:\n shutil.copyfile(src,dst)\n\n strfile = FileUtil.GetFileString(dst)\n key = \"_VERSION_ANDROID_\"\n if isHd:\n key = \"_VERSION_HD_ANDROID_\"\n\n # 保存版本\n # android\n print(\"appid_huawei=\",appid_huawei+\" ishd=\",isHd)\n # if len(appid_huawei)>1: \n version_web = mainHuaweiAppGalleryApi.GetVersion(appid_huawei)\n strfile = strfile.replace(key,version_web) \n FileUtil.SaveString2File(strfile,dst)\n self.SetAppVersion(isHd,Source.ANDROID,version_web)\n strcode = version_web.replace(\".\",\"\")\n self.SetAppVersionCode(isHd,Source.ANDROID,strcode)\n \n \n \n\n # ios\n appid_apple = self.GetJsonAppId(data,Source.APPSTORE)\n version_web = mainAppVersionApple.ParseVersion(appid_apple)\n print(\"AppVersionApple=\",version_web+\" appid_apple=\",appid_apple)\n self.SetAppVersion(isHd,Source.IOS,version_web)\n strcode = version_web.replace(\".\",\"\")\n self.SetAppVersionCode(isHd,Source.IOS,strcode)\n\n filepath = mainResource.GetProjectConfigAppType()+\"/appversion.json\" \n flag = os.path.exists(filepath)\n strFileJson = \"{}\"\n if flag:\n strFileJson = FileUtil.GetFileString(filepath)\n dataRoot = json.loads(strFileJson)\n dataRoot[mainResource.getGameName()]= json.loads(strfile)\n JsonUtil.SaveJson(filepath,dataRoot)\n\n\n \n\n # 重新加载\n data = self.loadJson(isHd)\n APPVERSION_IOS = data[\"appversion\"][Source.IOS][\"value\"] \n self.versionCode = data[\"appversion\"][Source.ANDROID][\"code\"]\n APPVERSION_ANDROID = self.versionCodeToVersion(self.versionCode)\n APPVERSION_CODE_ANDROID = self.versionCode\n\n print (APP_NAME_CN_ANDROID)\n print (APP_NAME_EN_ANDROID)\n print (APP_NAME_CN_IOS)\n print (APP_NAME_EN_IOS)\n print (PACKAGE_ANDROID)\n\n print(\"android version:\"+APPVERSION_ANDROID)\n print(\"ios version:\"+APPVERSION_IOS)\n\n # android\n # name\n strStart = \"app_name\\\">\"\n strEnd = \"<\"\n # cn\n strOut = self.replaceStringOfFile(\n file_name_cn_android, strStart, strEnd, APP_NAME_CN_ANDROID)\n self.saveString2File(strOut, file_name_cn_android)\n # en\n strOut = self.replaceStringOfFile(\n file_name_en_android, strStart, strEnd, APP_NAME_EN_ANDROID)\n self.saveString2File(strOut, file_name_en_android)\n\n self.updateAndroidManifest(file_AndroidManifest,PACKAGE_ANDROID,APPVERSION_ANDROID,APPVERSION_CODE_ANDROID,isHd)\n self.updateAndroidManifest(file_AndroidManifest_GP,PACKAGE_ANDROID,APPVERSION_ANDROID,APPVERSION_CODE_ANDROID,isHd)\n\n # admob\n self.replaceGoogleServiceFile(file_google_service_android, PACKAGE_ANDROID)\n\n # ios\n\n #appname\n self.replaceFile(file_info_plist_ios,\"_APP_NAME_\",APP_NAME_CN_IOS)\n file_name_cn_ios = project_ios + \"/appname/zh-Hans.lproj/InfoPlist.strings\"\n file_name_en_ios = project_ios + \"/appname/en.lproj/InfoPlist.strings\" \n # cn\n self.replaceFile(file_name_cn_ios,\"_APP_NAME_\",APP_NAME_CN_IOS) \n # en\n self.replaceFile(file_name_en_ios,\"_APP_NAME_\",APP_NAME_EN_IOS) \n\n\n # package \n self.replaceFile(file_info_plist_ios,\"_APP_PACKAGE_\",PACKAGE_IOS)\n\n \n # version \n self.replaceFile(file_info_plist_ios,\"_APP_VERSION_\",APPVERSION_IOS) \n\n #admob appid \n appid = mainAdConfig.GetCommonAppId(Source.ADMOB,Source.IOS,isHd)\n self.replaceFile(file_info_plist_ios,\"_APP_ID_ADMOB_\",appid) \n\n # CFBundleURLSchemes\n src = Source.WEIBO\n appid = mainConfig.GetShareAppId(src,Source.IOS,isHd)\n self.replaceXcodeUrlScheme(file_info_plist_ios,src,appid,0)\n\n src = Source.WEIXIN\n appid = mainConfig.GetShareAppId(src,Source.IOS,isHd)\n self.replaceXcodeUrlScheme(file_info_plist_ios,src,appid,0)\n\n src = Source.QQ\n appid = mainConfig.GetShareAppId(src,Source.IOS,isHd)\n self.replaceXcodeUrlScheme(file_info_plist_ios,src,appid,0)\n self.replaceXcodeUrlScheme(file_info_plist_ios,src,appid,1)\n\n # xiaomi aso keyword\n self.updateXiaoASOkeyword(data,isHd)\n\n\n\n # win\n self.updateNameWin(isHd,isAuto)\n\n\n def updateNameWin(self,isHd,isAuto):\n strOld = \"_APP_NAME_\"\n rootConfig = mainResource.GetProjectConfigApp()\n project = rootConfig + \"/win/project\"\n if isHd:\n project = rootConfig + \"/win/project_hd\"\n\n file_name_cn = project + \"/strings/zh-cn/resources.resw\"\n file_name_en= project + \"/strings/en-us/resources.resw\"\n\n data = self.loadJson(isHd)\n isOld = self.IsOldVersion(data)\n \n if not isOld : \n appname = data[\"appname\"]\n\n if isOld:\n APP_NAME_CN= data[\"APP_NAME_CN_ANDROID\"]\n APP_NAME_EN = data[\"APP_NAME_EN_ANDROID\"]\n PACKAGE = data[\"PACKAGE_ANDROID\"]\n else:\n APP_NAME_CN = appname[\"android\"][\"cn\"]\n APP_NAME_EN = appname[\"android\"][\"en\"]\n PACKAGE = data[\"apppackage\"][\"android\"][\"default\"]\n \n # cn\n self.replaceFile(file_name_cn, strOld, APP_NAME_CN)\n # en\n self.replaceFile(file_name_en, strOld, APP_NAME_EN)\n\n \n \n filepath= project + \"/strings/mainResource.resw\"\n if os.path.exists(filepath):\n self.replaceFile(filepath, \"_APP_PACKAGE_\", PACKAGE)\n \n # # 1000:\n self.__OurAtt = 1000\n else:\n self.__OurAtt = val\n\n\nx = OurClass(10)\nprint(x.OurAtt)\nx.OurAtt = 1001 # When setting an attribute the setter method is called automatically\nprint(x.OurAtt) # 1000\nx.OurAtt = -10\nprint(x.OurAtt) # 0\n","repo_name":"IoC-Sunderland/Properties-Vs-Getters-and-Setters","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"25475029711","text":"import argparse\nimport json\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport re\nfrom copy import deepcopy\nfrom glob import glob\nfrom tqdm import tqdm\nfrom mmdet3d.core.bbox import box_np_ops as box_np_ops\n\n\ndef get_anno_files(selected_timestamps=None, norm=False):\n anno_files = glob(os.path.join(anno_dir, \"*/*/*.json\"))\n valid_anno_files = []\n for anno_file in anno_files:\n # 0720 is the old annotation version\n if \"20220720\" in anno_file:\n continue\n if norm is False:\n if \"norm\" in anno_file:\n continue\n else:\n if \"norm\" not in anno_file:\n continue\n if selected_timestamps is not None:\n is_valid = False\n for timestamp in selected_timestamps:\n if timestamp in anno_file:\n is_valid = True\n break\n if not is_valid:\n continue\n valid_anno_files.append(anno_file)\n return valid_anno_files\n\n\ndef get_points_in_box(points, box):\n box_min_xyz = box.min(axis=0).reshape(-1)\n box_max_xyz = box.max(axis=0).reshape(-1)\n\n val_flag_x = np.logical_and(points[:, 0] >= box_min_xyz[0], points[:, 0] < box_max_xyz[0])\n val_flag_y = np.logical_and(points[:, 1] >= box_min_xyz[1], points[:, 1] < box_max_xyz[1])\n val_flag_z = np.logical_and(points[:, 2] >= box_min_xyz[2], points[:, 2] < box_max_xyz[2])\n val_flag_merge = np.logical_and(np.logical_and(val_flag_x, val_flag_y), val_flag_z)\n\n box_points = points[val_flag_merge]\n\n return box_points\n\n\ndef corners2xyzwlhr(corners):\n \"\"\"\n 1 -------- 0\n /| /|\n 2 -------- 3 .\n | | | |\n . 5 -------- 4\n |/ |/\n 6 -------- 7\n\n Args:\n corners (np.array): (8, 3), [x, y, z] in lidar coords.\n\n Returns:\n box (np.array): (7,), [x, y, z, w, l, h, r] in lidar coords.\n \"\"\"\n corners = np.array(corners)\n height_group = [(4, 0), (5, 1), (6, 2), (7, 3)]\n width_group = [(4, 5), (7, 6), (0, 1), (3, 2)]\n length_group = [(4, 7), (5, 6), (0, 3), (1, 2)]\n vector_group = [(4, 7), (5, 6), (0, 3), (1, 2)]\n height, width, length = 0.0, 0.0, 0.0\n vector = np.zeros(2, dtype=np.float32)\n for index_h, index_w, index_l, index_v in zip(\n height_group, width_group, length_group, vector_group\n ):\n height += np.linalg.norm(corners[index_h[0], :] - corners[index_h[1], :])\n width += np.linalg.norm(corners[index_w[0], :] - corners[index_w[1], :])\n length += np.linalg.norm(corners[index_l[0], :] - corners[index_l[1], :])\n vector[0] += (corners[index_v[0], :] - corners[index_v[1], :])[0]\n vector[1] += (corners[index_v[0], :] - corners[index_v[1], :])[1]\n\n height, width, length = height * 1.0 / 4, width * 1.0 / 4, length * 1.0 / 4\n rotation_y = -np.arctan2(vector[1], vector[0]) - np.pi / 2\n\n center_point = corners.mean(axis=0)\n box = np.concatenate([center_point, np.array([width, length, height, rotation_y])])\n\n return box\n\n\ndef get_points_in_rbox(points, box_corners):\n box = corners2xyzwlhr(box_corners)\n idxs = box_np_ops.points_in_rbbox(points, box[None, :], origin=(0.5, 0.5, 0.5)).squeeze()\n box_points = points[idxs]\n return box_points\n\n\ndef cal_norm_offset():\n nid2offsets = {}\n anno_files = get_anno_files()\n for anno_file in tqdm(anno_files):\n anno = json.load(open(anno_file))\n nid = anno[\"nid\"]\n\n if len(anno[\"lidar_objs\"]) == 0:\n continue\n\n gt_boxes_corners = [\n np.asarray(obj[\"3d_box\"], dtype=np.float64) for obj in anno[\"lidar_objs\"]\n ]\n # (N, 8, 3) -> (Nx8, 3)\n gt_boxes_corners = np.asarray(gt_boxes_corners).reshape(-1, 3)\n\n boxes_min_xyz = gt_boxes_corners.min(axis=0).reshape(-1)\n boxes_max_xyz = gt_boxes_corners.max(axis=0).reshape(-1)\n\n offset = (\n (boxes_min_xyz[0] + boxes_max_xyz[0]) / 2, # center x\n (boxes_min_xyz[1] + boxes_max_xyz[1]) / 2, # center y\n boxes_min_xyz[2], # min z\n )\n\n if nid not in nid2offsets:\n nid2offsets[nid] = [offset]\n else:\n nid2offsets[nid].append(offset)\n\n ret_offsets = {}\n for nid, offsets in nid2offsets.items():\n x_offset = round(0 - np.mean([offset[0] for offset in offsets]), 2)\n y_offset = round(0 - np.mean([offset[1] for offset in offsets]), 2)\n z_offset = round(-5 - np.mean([offset[2] for offset in offsets]), 2)\n ret_offsets[nid] = (x_offset, y_offset, z_offset)\n print(json.dumps(ret_offsets, indent=4))\n\n\ndef norm_coord(selected_timestamps=None):\n print(\">>> Normalize coordinates...\")\n anno_files = get_anno_files(selected_timestamps)\n invalid_files = []\n for anno_file in tqdm(anno_files):\n anno = json.load(open(anno_file))\n nid = anno[\"nid\"]\n norm_offset = norm_offsets[nid]\n\n if len(anno[\"lidar_objs\"]) == 0:\n invalid_files.append(anno_file)\n continue\n\n pcd_relative_path = re.search(\n \"[^/?]+/[^/?]+/[^/?]+npy\", anno[\"pcd_path\"].replace(\"pcd\", \"npy\")\n ).group()\n pcd_path = os.path.join(data_dir, pcd_relative_path)\n points = np.load(pcd_path)\n\n # normalize the coordinates of gt boxes\n norm_anno = deepcopy(anno)\n for i, obj in enumerate(anno[\"lidar_objs\"]):\n box_corners = np.asarray(obj[\"3d_box\"], dtype=np.float64)\n norm_corners = box_corners + norm_offset\n obj[\"3d_box\"] = norm_corners.tolist()\n points_in_box = get_points_in_rbox(points, box_corners)\n obj[\"num_pts\"] = points_in_box.shape[0]\n norm_anno[\"lidar_objs\"][i] = obj\n\n save_path = anno_file.replace(\".json\", \"_norm.json\")\n json.dump(norm_anno, open(save_path, \"w\"), indent=4)\n\n # normalize the coordinates of point cloud\n points += norm_offset + [0.0]\n save_path = pcd_path.replace(\".npy\", \"_norm.npy\")\n np.save(save_path, points)\n print(f\"{len(invalid_files)} invalid files: {invalid_files[:20]}\")\n\n\ndef fix_cid(selected_timestamps=None):\n print(\">>> Fixing incorrect cid...\")\n anno_files = get_anno_files(selected_timestamps)\n cid_err_files = []\n for anno_file in tqdm(anno_files):\n anno = json.load(open(anno_file))\n # check cid correctness\n for cam_info in anno[\"cams\"]:\n cid = cam_info[\"cid\"]\n img_url = cam_info[\"img_path\"]\n res = re.search(\"[^/?]+/([^/?]+)/([^/?]+)-[^/?]+jpg\", img_url)\n img_path = os.path.join(args.dataset_dir, \"data\", res.group())\n assert os.path.exists(img_path)\n nid, kid = res.group(1), res.group(2)\n assert int(nid) <= 35 and int(kid) <= 4\n if cid != f\"{nid}-{kid}\":\n cid_err_files.append(anno_file)\n break\n print(f\"{len(cid_err_files)} files, cid is incorrect: {cid_err_files[:20]}\")\n for anno_file in cid_err_files:\n anno = json.load(open(anno_file))\n for i, cam_info in enumerate(anno[\"cams\"]):\n cid = cam_info[\"cid\"]\n img_url = cam_info[\"img_path\"]\n res = re.search(\"[^/?]+/([^/?]+)/([^/?]+)-[^/?]+jpg\", img_url)\n img_path = os.path.join(args.dataset_dir, \"data\", res.group())\n assert os.path.exists(img_path)\n nid, kid = res.group(1), res.group(2)\n assert int(nid) <= 35 and int(kid) <= 4\n correct_cid = f\"{nid}-{kid}\"\n if cid != correct_cid:\n anno[\"cams\"][i][\"cid\"] = correct_cid\n with open(anno_file, \"w\") as f:\n json.dump(anno, f, indent=4)\n\n\ndef remove_cam_lidar_mismatch(selected_timestamps=None):\n print(\">>> Fixing cam LiDAR mismatch...\")\n anno_files = get_anno_files(selected_timestamps)\n mismatch_files = []\n for anno_file in tqdm(anno_files):\n anno = json.load(open(anno_file))\n\n # check cam-lidar mismatch\n pcd_relative_path = re.search(\n \"[^/?]+/[^/?]+/[^/?]+npy\", anno[\"pcd_path\"].replace(\".pcd\", \".npy\")\n ).group()\n pcd_path = os.path.join(data_dir, pcd_relative_path)\n points = np.load(pcd_path)\n assert points.shape[0] % 24000 == 0\n lidar_num = points.shape[0] / 24000\n cam_num = len(anno[\"cams\"])\n if cam_num != lidar_num:\n mismatch_files.append(anno_file)\n\n print(f\"{len(mismatch_files)} files, cam num is mismatch with LiDAR num: {mismatch_files[:20]}\")\n for anno_file in mismatch_files:\n os.remove(anno_file)\n\n\ndef attach_min_camz(selected_timestamps=None, plot=False, plot_minz=10, plot_maxz=150):\n print(\">>> Attaching min camz...\")\n anno_files = get_anno_files(selected_timestamps, norm=True)\n nid_set = set()\n for anno_file in tqdm(anno_files):\n anno = json.load(open(anno_file))\n nid_set.add(anno[\"nid\"])\n norm_offset = norm_offsets[anno[\"nid\"]]\n for i, obj in enumerate(anno[\"lidar_objs\"]):\n box_corners = np.asarray(obj[\"3d_box\"], dtype=np.float64)\n box_corners -= norm_offset\n min_camz = 1e5\n for camera_info in anno[\"cams\"]:\n intrinsic = np.float32(camera_info[\"intrinsic\"])\n extrinsic = np.float32(camera_info[\"extrinsic\"])\n l2c_R, l2c_t = extrinsic[:3, :3], extrinsic[:3, 3:]\n # (3, 8)\n cam_points = l2c_R @ box_corners.T + l2c_t\n\n # check if the box is in the front of camera\n _, _, camz = cam_points.mean(axis=1)\n if camz <= 0:\n continue\n\n # (8, 3)\n img_points = (intrinsic @ cam_points).T\n img_points[:, :2] /= img_points[:, 2:]\n\n # check if the box is visible in image\n h, w = 1080, 1920\n min_x, min_y = img_points[:, :2].min(axis=0)\n max_x, max_y = img_points[:, :2].min(axis=0)\n if min_x >= w or max_x < 0 or min_y >= h or max_y < 0:\n continue\n\n # import cv2\n # img_relative_path = re.search(\n # \"[^/?]+/[^/?]+/[^/?]+jpg\", camera_info[\"img_path\"]\n # ).group()\n # img_path = os.path.join(data_dir, img_relative_path)\n # img = cv2.imread(img_path)\n # for img_point in img_points:\n # img_point = img_point.astype(np.int)\n # cv2.circle(img, img_point[:2], 10, (0, 255, 255), -1)\n # cv2.imwrite(\"test.png\", img)\n # print(camz)\n # input()\n\n min_camz = min(min_camz, camz)\n min_camz = -1 if min_camz == 1e5 else min_camz\n anno[\"lidar_objs\"][i][\"min_camz\"] = min_camz\n with open(anno_file, \"w\") as f:\n json.dump(anno, f, ensure_ascii=False, indent=4)\n\n if not plot:\n return\n\n nid_cnt = len(nid_set)\n print(f\"Total nid num: {nid_cnt}\")\n\n cols = 3\n rows = math.ceil(nid_cnt / cols)\n fig, axs = plt.subplots(rows, cols, figsize=(9, 15))\n\n for i, nid in enumerate(nid_set):\n row_idx = i // cols\n col_idx = i % cols\n cnt = 0\n print(f\"Processing nid: {nid}...\")\n for anno_file in tqdm(anno_files):\n anno = json.load(open(anno_file))\n if anno[\"nid\"] != nid:\n continue\n for obj in anno[\"lidar_objs\"]:\n if obj[\"min_camz\"] < plot_minz or obj[\"min_camz\"] > plot_maxz:\n continue\n box = np.array(obj[\"3d_box\"])\n cnt += 1\n center_x, center_y, _ = box.mean(axis=0)\n axs[row_idx, col_idx].plot(center_x, center_y, \"o\", color=\"blue\", markersize=0.1)\n axs[row_idx, col_idx].set_title(f\"nid {nid}: {cnt}\")\n fig.tight_layout()\n fig.savefig(\"cam_train_bboxes.png\")\n\n\ndef remove_invalid_samples(selected_timestamps=None):\n print(\">>> Remove invalid samples...\")\n anno_files = get_anno_files(selected_timestamps)\n delete_files = []\n for anno_file in anno_files:\n assert \"norm\" not in anno_file\n norm_anno_file = anno_file.replace(\".json\", \"_norm.json\")\n if not os.path.exists(norm_anno_file):\n anno = json.load(open(anno_file))\n assert len(anno[\"lidar_objs\"]) == 0\n delete_files.append(anno_file)\n\n pcd_files = glob(os.path.join(data_dir, \"*/*/*.pcd\"))\n for pcd_file in pcd_files:\n norm_npy_file = pcd_file.replace(\".pcd\", \"_norm.npy\")\n # There may be several reasons why a pcd file does not have a corresponding _norm.npy file:\n # 1. The pcd file is not labeled.\n # 2. The annotation of the pcd file is invalid, e.g., cam-LiDAR mismatch, empty LiDAR objs.\n if not os.path.exists(norm_npy_file):\n delete_files.append(pcd_file)\n delete_files.append(pcd_file.replace(\".pcd\", \".npy\"))\n\n path_prefix = \"/\".join(pcd_file.split(\"/\")[:-1])\n token = pcd_file.split(\"/\")[-1].replace(\".pcd\", \"\")\n img_files = [\n os.path.join(path_prefix, f\"1-{token}.jpg\"),\n os.path.join(path_prefix, f\"2-{token}.jpg\"),\n os.path.join(path_prefix, f\"3-{token}.jpg\"),\n os.path.join(path_prefix, f\"4-{token}.jpg\"),\n ]\n has_valid_img = False\n for img_file in img_files:\n if os.path.exists(img_file):\n has_valid_img = True\n delete_files.append(img_file)\n assert has_valid_img\n print(f\"{len(delete_files)} delete files: {delete_files[:20]}\")\n for delete_file in delete_files:\n os.remove(delete_file)\n\n\ndef remove_null_type_boxes(selected_timestamps=None):\n print(\">>> Remove null type boxes...\")\n anno_files = get_anno_files(selected_timestamps)\n num_null_boxes = 0\n for anno_file in tqdm(anno_files):\n anno = json.load(open(anno_file))\n delete_idxs = []\n for i, obj in enumerate(anno[\"lidar_objs\"]):\n if obj[\"type\"] is None:\n num_null_boxes += 1\n delete_idxs.append(i)\n if len(delete_idxs) == 0:\n continue\n new_objs = []\n for i, obj in enumerate(anno[\"lidar_objs\"]):\n if i in delete_idxs:\n continue\n new_objs.append(obj)\n anno[\"lidar_objs\"] = new_objs\n with open(anno_file, \"w\") as f:\n json.dump(anno, f, ensure_ascii=False, indent=4)\n print(f\"Total {num_null_boxes} null boxes\")\n\n\ndef _parse_anno_file(anno_file):\n res = re.search(\"/([0-9-]+)/([0-9]+)/([0-9]+)\\.([0-9]+)_norm.json\", anno_file)\n date, nid, seconds, nanoseconds = res.group(1), res.group(2), res.group(3), res.group(4)\n assert int(nid) <= 35\n assert len(seconds) == 10 and len(nanoseconds) == 9\n return date, nid, int(seconds), int(nanoseconds)\n\n\ndef _is_continuous(anno_file1, anno_file2):\n date1, nid1, seconds1, nanoseconds1 = _parse_anno_file(anno_file1)\n date2, nid2, seconds2, nanoseconds2 = _parse_anno_file(anno_file2)\n if date1 != date2 or nid1 != nid2:\n return False\n if seconds2 != seconds1:\n assert seconds2 > seconds1\n else:\n assert nanoseconds2 > nanoseconds1\n if seconds2 - seconds1 <= 1:\n return True\n return False\n\n\ndef add_temporal_info(selected_timestamps=None, max_sweeps=10):\n print(\">>> Add temporal info...\")\n anno_files = sorted(get_anno_files(selected_timestamps, norm=True))\n sweeps = []\n scene_idx = 0\n for i, anno_file in tqdm(enumerate(anno_files)):\n _, _, seconds, nanoseconds = _parse_anno_file(anno_file)\n\n anno = json.load(open(anno_file))\n anno[\"timestamp\"] = f\"{seconds}.{nanoseconds}\"\n anno[\"sweeps\"] = sweeps\n anno[\"scene_idx\"] = scene_idx\n\n with open(anno_file, \"w\") as f:\n json.dump(anno, f, indent=4)\n\n if i + 1 < len(anno_files) and _is_continuous(anno_file, anno_files[i + 1]):\n sweeps.append(anno_file)\n if len(sweeps) > max_sweeps:\n sweeps = sweeps[1:]\n else:\n sweeps = []\n scene_idx += 1\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--cal-norm-offset\", action=\"store_true\")\n parser.add_argument(\"--norm-coord\", action=\"store_true\")\n parser.add_argument(\"--remove-cam-lidar-mismatch\", action=\"store_true\")\n parser.add_argument(\"--fix-cid\", action=\"store_true\")\n parser.add_argument(\"--attach-min-camz\", action=\"store_true\")\n parser.add_argument(\"--remove-invalid-samples\", action=\"store_true\")\n parser.add_argument(\"--remove-null-type-boxes\", action=\"store_true\")\n parser.add_argument(\"--add-temporal-info\", action=\"store_true\")\n parser.add_argument(\"--full-process\", action=\"store_true\")\n parser.add_argument(\"--incremental-process\", nargs=\"+\", type=str, default=None)\n parser.add_argument(\"--dataset-dir\", default=\"data/xdq\")\n args = parser.parse_args()\n\n anno_dir = os.path.join(args.dataset_dir, \"annotation\")\n data_dir = os.path.join(args.dataset_dir, \"data\")\n\n # Used to normalize point cloud to origin-centered, z=-5 grounded.\n norm_offsets = {\n \"1\": [22, -70, 45.75],\n \"2\": [-23.32, 35.89, 45.75],\n \"3\": [-25, 98, 45.34],\n \"5\": [30, -110, 45.56],\n \"7\": [-65, -31, 45.19],\n \"12\": [290, -120, 45.99],\n \"16\": [-50, 62, 46.91],\n \"17\": [8, -8, 45.41],\n \"19\": [39, -68, 46.21],\n \"21\": [19, 73, 45.6],\n \"32\": [55, 12, 45.93],\n \"33\": [-75, 1, 45.97],\n \"34\": [-9, -5, 45.71],\n \"35\": [55, 55, 46.03],\n }\n\n if args.full_process or args.incremental_process:\n selected_timestamps = args.incremental_process if args.incremental_process else None\n # 1. Remove those samples whose cam num != LiDAR num,\n # which may be caused by the bug of our data processing script.\n remove_cam_lidar_mismatch(selected_timestamps)\n # 2. Fix the incorrect cid, which is caused by a longmao bug.\n fix_cid(selected_timestamps)\n # 3. Remove those boxes whose type=null, which is caused by a longmao bug.\n remove_null_type_boxes(selected_timestamps)\n # 4. Normalize LiDAR points and annotated bboxes by\n # the calculated or hand-crafted norm_offsets.\n norm_coord(selected_timestamps)\n # 5. Remove invalid samples to save disk usage.\n remove_invalid_samples(selected_timestamps)\n # 6. Calculate the shortest distance from each box to all cameras,\n # and attach the distance to annotation file.\n attach_min_camz(selected_timestamps)\n exit(0)\n\n if args.add_temporal_info:\n add_temporal_info()\n exit(0)\n\n if args.cal_norm_offset:\n cal_norm_offset()\n exit(0)\n\n if args.norm_coord:\n norm_coord()\n exit(0)\n\n if args.remove_cam_lidar_mismatch:\n remove_cam_lidar_mismatch()\n exit(0)\n\n if args.fix_cid:\n fix_cid()\n exit(0)\n\n if args.remove_invalid_samples:\n remove_invalid_samples()\n exit(0)\n\n if args.remove_null_type_boxes:\n remove_null_type_boxes()\n exit(0)\n\n if args.attach_min_camz:\n attach_min_camz()\n exit(0)\n","repo_name":"serend1p1ty/bevfusion-pku","sub_path":"tools/xdq/preprocess_xdq_dataset.py","file_name":"preprocess_xdq_dataset.py","file_ext":"py","file_size_in_byte":19449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32923669212","text":"#Bradley\r\n#Alex\r\n#TCP Client\r\n\r\nfrom socket import *\r\nimport random\r\n\r\n#server variables\r\nserverName = 'localhost'\r\nserverPort = 12000\r\n\r\n#setup connection\r\nclientSocket = socket(AF_INET, SOCK_STREAM)\r\nclientSocket.connect((serverName,serverPort))\r\n\r\n#name for the client\r\nname = input('Input client name: ')\r\n#random client number\r\nnum = random.randint(0,99)\r\n#messgae to send to server\r\nclientMsg = \"Client \" + num + \": \" + name\r\n\r\n#send message to server\r\nclientSocket.send(clientMsg.encode())\r\n\r\n#recieve message from server\r\nserverMsg = clientSocket.recv(1024)\r\n\r\n#Print recieved message\r\nprint (serverMsg.decode())\r\n\r\n#close the socket\r\nclientSocket.close()\r\n\r\n\r\n","repo_name":"bwernick/cst311-fall2018","sub_path":"HW2/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"40440161457","text":"def dfs(node, graph, visited):\n if visited[node]:\n return\n visited[node] = True\n for child in graph[node]:\n dfs(child, graph, visited)\n\n\nnodes_count = int(input())\nedges_count = int(input())\n\ngraph = []\n[graph.append([]) for _ in range(nodes_count)]\n\nedges = set()\nfor _ in range(edges_count):\n source, destination = [int(x) for x in input().split(\" - \")]\n graph[source].append(destination)\n graph[destination].append(source)\n edges.add((min(source, destination), max(source, destination)))\n\nimportant_streets = []\n\nfor source, destination in edges:\n graph[source].remove(destination)\n graph[destination].remove(source)\n\n visited = [False] * nodes_count\n dfs(0, graph, visited)\n\n if not all(visited):\n important_streets.append((source, destination))\n\n graph[source].append(destination)\n graph[destination].append(source)\n\nprint(\"Important streets:\")\nfor source, destination in important_streets:\n print(source, destination, sep=\" \")\n","repo_name":"yavor-gornalov/softuni_algorithms_with_python","sub_path":"algorithms_fundamentals/05_graph_theory_traversal_and_topological_sorting_exercise/05_road_reconstruction_ver2.py","file_name":"05_road_reconstruction_ver2.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"72668238479","text":"import time\nimport ast\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.views import generic\nfrom django.http import HttpResponse\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\n\nfrom .message import Message\nfrom rest.serializers import MessageSerializer\nfrom lib.dynamo import Dynamo\n\n\ndef message_view(request):\n if request.user.is_authenticated():\n user = get_object_or_404(User, username=request.user.username)\n messages = Dynamo.get_messages_by_recipient(user.username)\n if request.user.is_staff:\n return render(request,'createMessage.html', {\"message_list\": messages})\n else:\n return render(request, 'userMessages.html', {\"message_list\": messages})\n return redirect(\"../\")\n\n\ndef send_message(request):\n try:\n user = User.objects.get(username=str(request.POST['username'])).username\n to_send = Message(\n sender='test',\n recipient=user,\n urgency=int(request.POST['urgency']),\n content=str(request.POST['message']),\n timestamp=int(time.time()),\n read=False\n )\n\n Dynamo.initialize().send_message(MessageSerializer(to_send).data)\n Dynamo.get_messages_by_recipient(user)\n\n return redirect(message_view)\n except Exception as e:\n print(\"\\tERROR\\tFailed to create message: \" + str(e))\n return redirect(error_message)\n\ndef sent_message_view(request):\n if request.user.is_authenticated():\n return render(request,'sentMessage.html')\n return redirect(\"../\")\n\n\ndef error_message(request):\n html = \"Error creating message\"\n return HttpResponse(html)\n\n\ndef message(request):\n message = dict()\n message['recipient'] = request.POST['messageRecipient']\n message['timestamp'] = int(request.POST['messageTimestamp'])\n\n message = Dynamo.get_message(message)\n return render(request, 'message.html', {\"msg\": message})\n\n\n\n\n\n","repo_name":"couragepaul/COMP4350","sub_path":"apartment/messaging/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1445848738","text":"from pyspark.ml.feature import VectorAssembler\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.dataframe import DataFrame\nfrom pyspark.sql.functions import column, expr, from_json, udf\nfrom pyspark.sql.types import *\nfrom pyspark.ml.classification import MultilayerPerceptronClassificationModel, MultilayerPerceptronClassifier\nfrom kafka import KafkaProducer\nimport json\nfrom pyhive import hive\nimport time\nimport random\nimport base64\nimport shutil\nimport os\n\n\nspark = SparkSession.builder.appName('BDAModel').getOrCreate()\nspark.sparkContext.setLogLevel('WARN')\nlogger = spark.sparkContext._jvm.org.apache.log4j.LogManager.getLogger(\n __name__)\n\nmodel = None\ndb_model_weights = None\nfor i in range(100):\n logger.warn(f'Attempting to connect for {i}th time to hive...')\n try:\n conn = hive.Connection(host='hive-server')\n cursor = conn.cursor()\n cursor.execute(\n 'SELECT * FROM modelweights ORDER BY ts DESC')\n row = cursor.fetchone()\n if row:\n # Index dependent on table schema\n weights_data = row[-1]\n archive_path = './db_model_weights.tar.gz'\n folder_path = './db_model_weights'\n with open(archive_path, 'wb+') as f:\n f.write(base64.b64decode(weights_data))\n shutil.unpack_archive(archive_path, folder_path)\n model = MultilayerPerceptronClassificationModel.load(folder_path)\n db_model_weights = model.weights\n shutil.rmtree(folder_path)\n os.remove(archive_path)\n logger.warn(f'Read model weights: {db_model_weights}')\n cursor.close()\n conn.close()\n break\n except Exception as ex:\n logger.error(f'{ex}')\n logger.warn('Connect failed. Trying again in 5 seconds...')\n time.sleep(5)\n\nstream_schema = StructType([\n StructField('lon', DoubleType(), False),\n StructField('lat', DoubleType(), False),\n StructField('measured', IntegerType(), False),\n StructField('id', StringType(), False),\n StructField('ts', TimestampType(), False),\n StructField('kafkatopic', StringType(), False),\n StructField('aqi', IntegerType(), True),\n StructField('temp', DoubleType(), True),\n StructField('pressure', DoubleType(), True),\n StructField('humidity', DoubleType(), True),\n StructField('clouds', IntegerType(), True),\n StructField('windspeed', DoubleType(), True),\n StructField('winddeg', DoubleType(), True),\n])\n\n\ndef aqi_category(aqi):\n if aqi <= 50:\n return 0 # Good\n if aqi <= 100:\n return 1 # Moderate\n if aqi <= 150:\n return 2 # Unhealthy for sensitive groups\n if aqi <= 200:\n return 3 # Unhealthy\n if aqi <= 300:\n return 4 # Very Unhrealthy\n return 5 # Hazardous\n\n\n# TODO: Set initial offset to earliest\ndf = spark.readStream \\\n .format('kafka') \\\n .option('kafka.bootstrap.servers', 'kafka:9092') \\\n .option('subscribe', 'spark') \\\n .option('startingOffsets', 'earliest') \\\n .load()\n\ndf_json = df \\\n .select(from_json(df.value.cast('string'), stream_schema).alias('v')) \\\n .select('v.*') \\\n .withWatermark('ts', '20 seconds')\n\npollution_df = df_json \\\n .filter(column('kafkatopic').startswith('pollution')) \\\n .select('aqi', 'ts', 'kafkatopic', 'id') \\\n .withColumnRenamed('id', 'pollutionid') \\\n .alias('pollution')\n\nweather_df = df_json \\\n .filter(column('kafkatopic').startswith('weather')) \\\n .select('lon', 'lat', 'temp', 'pressure', 'humidity', 'clouds', 'windspeed', 'winddeg', 'ts', 'kafkatopic', 'id') \\\n .withColumnRenamed('id', 'weatherid') \\\n .withColumn('weatherts', column('ts')) \\\n .alias('weather')\n\n\nweather_with_pollution = weather_df.join(\n pollution_df,\n expr(\"\"\"\n REPLACE(weather.kafkatopic, 'weather', '') = REPLACE(pollution.kafkatopic, 'pollution', '') AND\n weather.ts + interval 10 seconds > pollution.ts AND\n weather.ts < pollution.ts + interval 10 seconds\n \"\"\"),\n \"inner\") \\\n .withColumn('city', udf(lambda s: s.replace('weather', ''), StringType())('weather.kafkatopic')) \\\n .select('weather.*', 'pollution.*', 'city') \\\n .drop('ts', 'kafkatopic') \\\n .withColumnRenamed('weatherts', 'ts')\n\ninput_cols = list(\n set(weather_with_pollution.columns) - set(['aqi', 'pollutionid', 'weatherid', 'city', 'ts']))\n\nlayers = [len(input_cols), 50, 6]\nasm = VectorAssembler(inputCols=input_cols, outputCol='features')\nweather_with_pollution = asm \\\n .transform(weather_with_pollution) \\\n .withColumn('label', udf(aqi_category, IntegerType())('aqi'))\n\nkafka_producer = KafkaProducer(bootstrap_servers='kafka:9092')\ntrainer = MultilayerPerceptronClassifier(layers=layers)\nif db_model_weights is not None:\n num_weights = sum(map(lambda p: (p[0]+1)*p[1], zip(layers, layers[1:])))\n if num_weights != len(db_model_weights):\n logger.warn('Weight data is outdated!')\n model = None\n db_model_weights = None\n\n\ndef train(batch: DataFrame, batchId):\n global model\n rows = batch.collect()\n rows.sort(key=lambda r: r.ts)\n for i, row in enumerate(rows):\n params = {trainer.initialWeights: db_model_weights,\n trainer.stepSize: 0.03}\n logger.warn(\n f'Processing row {i}/{len(rows)} of batch {batchId}. City: {row.city}')\n if model is not None:\n kafka_producer.send(f'modelpredictions{row.city}',\n json.dumps({\n 'prediction': int(model.predict(row.features)),\n 'actual': row.label,\n 'weatherid': row.weatherid,\n 'pollutionid': row.pollutionid,\n 'city': row.city,\n 'ts': row.ts.strftime('%Y-%m-%d %H:%M:%S.%f'),\n }).encode())\n params[trainer.initialWeights] = model.weights\n model = trainer.fit(spark.createDataFrame([row]), params=params)\n if random.randint(0, 40) == 0:\n fname = f'/models/model_{batchId}_{i}_{random.randint(0, 999999)}'\n logger.warn(f'Saving model data to {fname}')\n model.write().overwrite().save(fname)\n\n\nweather_with_pollution.writeStream \\\n .outputMode('append') \\\n .trigger(processingTime='20 seconds') \\\n .format('console') \\\n .start()\nweather_with_pollution.writeStream \\\n .foreachBatch(train) \\\n .start().awaitTermination()\n","repo_name":"Zackere/bda","sub_path":"spark/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1357778134","text":"# from google.cloud import vision\n# from google.cloud.vision import types\nimport os\nimport time\nimport sys\nimport cv2\nsys.path.append('..')\nfrom utils.app_utils import *\nimport numpy as np\nimport tensorflow as tf\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import visualization_utils as vis_util\n\nimport io\n#from google.cloud import vision\n#from google.cloud.vision import types\n#client = vision.ImageAnnotatorClient()\n\n\n# Path to frozen detection graph. This is the actual model that is used for the object detection.\nPATH_TO_CKPT = '/home/frosted007/Documents/Cargo_Scan/model/cargo.pb'\n\n# List of the strings that is used to add correct label for each box.\nPATH_TO_LABELS = '/home/frosted007/Documents/Cargo_Scan/model/cargo.pbtxt'\n\nNUM_CLASSES = 90\n\n# Loading label map\nlabel_map = label_map_util.load_labelmap(PATH_TO_LABELS)\ncategories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES,\n use_display_name=True)\ncategory_index = label_map_util.create_category_index(categories)\n\ni_image=-1\n\ndef detect_objects(image_np, sess, detection_graph, crop_q):\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n\n # Each box represents a part of the image where a particular object was detected.\n boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n\n # Each score represent how level of confidence for each of the objects.\n # Score is shown on the result image, together with the class label.\n scores = detection_graph.get_tensor_by_name('detection_scores:0')\n classes = detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n\n # Actual detection.\n (boxes, scores, classes, num_detections) = sess.run(\n [boxes, scores, classes, num_detections],\n feed_dict={image_tensor: image_np_expanded})\n\n # Visualize coordinates of the results of a detection.\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n np.squeeze(boxes),\n np.squeeze(classes).astype(np.int32),\n np.squeeze(scores),\n category_index,\n use_normalized_coordinates=True,\n line_thickness=4)\n\n coordinates = vis_util.return_coordinates(\n image_np,\n np.squeeze(boxes),\n np.squeeze(classes).astype(np.int32),\n np.squeeze(scores),\n category_index,\n use_normalized_coordinates=True,\n line_thickness=8,\n min_score_thresh=0.20) \n \n if (coordinates):\n global i_image\n i_image=i_image+1\n xmin = coordinates[0][2] \n ymin = coordinates[0][0]\n xmax = coordinates[0][3]\n ymax = coordinates[0][1]\n if(True):\n cropped = image_np[int(ymin):int(ymax), int(xmin):int(xmax)]\n print(\"type of image is \", type(cropped))\n # cv2.imshow(\"cropped\", cropped)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n # print('cropped')\n\n crop_q.put(cropped)\n '''\n #write to file if file does not exist\n # path1 = \"/home/mohak/Desktop/image/c1.jpg\"\n # path2 = \"/home/mohak/Desktop/image/c2.jpg\"\n # path3 = \"/home/mohak/Desktop/image/c3.jpg\"\n path = \"/home/mohak/Desktop/image/img\"+str(i_image)+\".jpg\"\n\n if(not os.path.exists(path)):\n cv2.imwrite(path, cropped)\n # elif(not os.path.exists(path2)):\n # cv2.imwrite('/home/mohak/Desktop/image/c2.jpg', cropped)\n # elif(not os.path.exists(path1)):\n # cv2.imwrite('/home/mohak/Desktop/image/c1.jpg', cropped)\n else:\n pass\n\n #cv2.imwrite('/home/mohak/Desktop/image/cropped.jpg', cropped) \n # cv2.imwrite('/home/mohak/Desktop/image/cropped'+str(i_image)+'.jpg', cropped)\n # print(\"size of queue is\", L.qsize())\n '''\n return image_np\n\n\ndef worker(input_q, output_q, crop_q):\n # Load a (frozen) Tensorflow model into memory.\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n sess = tf.Session(graph=detection_graph)\n\n fps = FPS().start()\n while True:\n print(\"inside worker!\")\n fps.update()\n frame = input_q.get()\n\n # Check frame object is a 2-D array (video) or 1-D (webcam)\n if len(frame) == 2:\n frame_rgb = cv2.cvtColor(frame[1], cv2.COLOR_BGR2RGB)\n #Thread(target=output_q.put, args=(frame[0], detect_objects(frame_rgb, sess, detection_graph)),daemon=True).start()\n output_q.put((frame[0], detect_objects(frame_rgb, sess, detection_graph, crop_q)))\n else:\n frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n #Thread(target=output_q.put, args=(detect_objects(frame_rgb, sess, detection_graph)),daemon=True).start()\n output_q.put(detect_objects(frame_rgb, sess, detection_graph, crop_q))\n fps.stop()\n sess.close()\n\n\n\ndef crop_worker(crop_q):\n i = 0\n while True:\n frame = crop_q.get()\n print(\"size of the crop queue is \", crop_q.qsize())\n cv2.imwrite(\"cropped_Image\"+str(i)+\".png\", frame)\n print(\"the text is .....\")\n #cv2.imshow(\"cropped image\", frame)\n #your OCR function goes here \n\n #write to file if file does not exist\n #path1 = \"/home/mohak/Desktop/image/c1.jpg\"\n # path2 = \"/home/mohak/Desktop/image/c2.jpg\"\n # path3 = \"/home/mohak/Desktop/image/c3.jpg\"\n #path = \"/home/mohak/Desktop/image/img\"+str(i_image)+\".jpg\"\n #if(not os.path.exists(path1)):\n # cv2.imwrite(path1, frame)\n # elif(not os.path.exists(path2)):\n # cv2.imwrite('/home/mohak/Desktop/image/c2.jpg', cropped)\n # elif(not os.path.exists(path1)):\n # cv2.imwrite('/home/mohak/Desktop/image/c1.jpg', cropped)\n #else:\n # pass\n\n #with io.open(path1, 'rb') as image_file:\n # content = image_file.read()\n \n #frame = cv2.imencode('.jpg', frame)[1].tostring()\n #image = vision.types.Image(content=frame)\n #response = client.text_detection(image=image)\n #texts = response.text_annotations\n #print(\"GOT RESPONSE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n #for text in texts:\n # print(\"description\",text.description)\n # File_object = open(r\"/home/mohak/Desktop/image/text.txt\",\"a+\")\n # File_object.write(text.description)\n # File_object.close()\n","repo_name":"shubhankarbis007/cargo-scan-for-conveyer-belts","sub_path":"utils/objDet_utils.py","file_name":"objDet_utils.py","file_ext":"py","file_size_in_byte":7186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"18541826313","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom pyrevolve.sdfbuilder import SDF, Model, Link, Element\nfrom pyrevolve.sdfbuilder.physics import Friction\nfrom pyrevolve.sdfbuilder.structure import Mesh, Visual, Collision\nfrom pyrevolve.sdfbuilder.math import Vector3\nfrom pyrevolve.sdfbuilder.util import number_format as nf\nfrom ...custom_logging.logger import logger\n\nfrom .. import constants\n\n# Radius and height without scaling\nMESH_DIAMETER = 4.0\nMESH_HEIGHT = 4.4\nSLICE_FRACTION = 0.7\n\n\nclass BirthClinic(Model):\n \"\"\"\n Birth clinic model, consists of two cylinders, one of which is rotated.\n \"\"\"\n\n def __init__(self, diameter=3.0, height=3.0, name=\"birth_clinic\"):\n \"\"\"\n\n :param diameter: Intended diameter of the birth clinic\n :param name:\n :return:\n \"\"\"\n super(BirthClinic, self).__init__(name=name, static=True)\n\n self.diameter = diameter\n scale = diameter / MESH_DIAMETER\n\n # Cannot go higher than mesh height, or lower than the bottom\n # of the slice.\n scaled_height = scale * MESH_HEIGHT\n self.height = max(arg1=min(height, scaled_height),\n arg2=(SLICE_FRACTION * scaled_height))\n\n mesh = Mesh(\"model://tol_arena/meshes/BirthClinic.dae\", scale=scale)\n\n col = Collision(\"bc_col\", mesh)\n surf = Element(tag_name=\"surface\")\n friction = Friction(\n friction=0.01,\n friction2=0.01,\n slip1=1.0,\n slip2=1.0\n )\n contact = \"\" \\\n \"\" \\\n \"%s\" \\\n \"%s\" \\\n \"\" \\\n \"\" % (\n nf(constants.SURFACE_KD), nf(constants.SURFACE_KP)\n )\n surf.add_element(friction)\n surf.add_element(contact)\n col.add_element(surf)\n\n vis = Visual(\"bc_vis\", mesh.copy())\n self.link = Link(\"bc_link\", elements=[col, vis])\n\n # By default the model has 0.5 * scale * MESH_HEIGHT below\n # and above the surface. Translate such that we have exactly\n # the desired height instead.\n self.link.translate(Vector3(0, 0, self.height - (0.5 * scaled_height)))\n self.add_element(self.link)\n\n\nif __name__ == '__main__':\n sdf = SDF(elements=[BirthClinic()])\n logger.info(sdf)\n","repo_name":"braj29/robo_swimmers","sub_path":"pyrevolve/tol/scenery/birth_clinic.py","file_name":"birth_clinic.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"73259583118","text":"# 查找数组中的逆序对\n# 修改归并排序的 merge 函数即可\ndef reverse_pairs(nums):\n temp = [0] * len(nums)\n return merge_sort(nums, 0, len(nums) - 1, temp)\n\n\ndef merge_sort(nums, left, right, temp):\n if left >= right:\n return 0\n mid = left + ((right - left) >> 1)\n res = 0\n res += merge_sort(nums, left, mid, temp)\n res += merge_sort(nums, mid + 1, right, temp)\n if nums[mid] > nums[mid + 1]:\n res += merge(nums, left, mid, right, temp)\n return res\n\n\ndef merge(nums, left, mid, right, temp):\n index = 0\n res = 0\n l_p = left\n r_p = mid + 1\n while l_p <= mid and r_p <= right:\n if nums[l_p] <= nums[r_p]:\n temp[index] = nums[l_p]\n l_p += 1\n else:\n res += mid - l_p + 1\n temp[index] = nums[r_p]\n r_p += 1\n index += 1\n while l_p <= mid:\n temp[index] = nums[l_p]\n index += 1\n l_p += 1\n while r_p <= right:\n temp[index] = nums[r_p]\n index += 1\n r_p += 1\n for i in range(index):\n nums[left] = temp[i]\n left += 1\n return res\n","repo_name":"Mountain-w/Algorithm-system","sub_path":"05归并排序/ReversePairs.py","file_name":"ReversePairs.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6982522410","text":"import os\n\nfrom flask import Response, request, current_app\nfrom flask_restful import Resource\nfrom flask_restful_swagger import swagger\nfrom database.models import Attendance\nfrom resources.azureface import compare_faces_azure\nfrom resources.rekognition import compare_faces_rekognition\nfrom resources.geofence import validateVicinity\nfrom resources.user import User\nfrom resources.producer import publish_message\nfrom resources.facenet import compare_faces_facenet\nfrom resources.module import check_module_active\nfrom resources.school import check_school_active\nimport datetime\nimport json\nimport logging\n\nlog = logging.getLogger(\"root\")\n\n\nclass AllAttendanceApi(Resource):\n @swagger.operation()\n def get(self):\n log.info(\"Inside get all attendance method ----->>\")\n allAttendance = Attendance.objects().to_json()\n return Response(allAttendance, mimetype=\"application/json\", status=200)\n\n @swagger.operation()\n def post(self):\n u = User()\n try:\n log.info(\"Inside create attendance method for student ----->>\")\n azure_face_enabled = os.getenv(\"AZURE_FACE_ENABLED\")\n aws_rekog_enabled = os.getenv(\"AWS_REKOG_ENABLED\")\n facenet_enabled = os.getenv(\"FACENET_ENABLED\")\n\n if azure_face_enabled is None:\n log.info(\"AZURE_FACE_ENABLED not set, falling back to config\")\n azure_face_enabled = current_app.config[\"AZURE_FACE_ENABLED\"]\n if aws_rekog_enabled is None:\n log.info(\"AWS_REKOG_ENABLED not set, falling back to config\")\n aws_rekog_enabled = current_app.config[\"AWS_REKOG_ENABLED\"]\n if facenet_enabled is None:\n log.info(\"FACENET_ENABLED not set, falling back to config\")\n facenet_enabled = current_app.config[\"FACENET_ENABLED\"]\n\n body = request.get_json()\n attendance = Attendance(**body)\n self.check_if_attendance_marked(attendance)\n school = check_school_active(attendance.school)\n check_module_active(attendance.moduleId, school.get(\"timeZone\"))\n validateVicinity(body)\n user = u.fetchStudent(username=attendance.username)\n if str(facenet_enabled) == \"1\" and (\n user.get(\"imageId\") is None or len(user.get(\"imageId\")) < 1\n ):\n attendance.recognitionSource = \"facenet\"\n attendance.recognitionConfidence = compare_faces_facenet(\n attendance.capturedImageId, attendance.username\n )\n else:\n if str(azure_face_enabled) == \"1\":\n attendance.recognitionSource = \"azure\"\n attendance.recognitionConfidence = compare_faces_azure(\n attendance.capturedImageId, user.get(\"imageId\")[0]\n )\n if str(aws_rekog_enabled) == \"1\":\n attendance.recognitionSource = \"aws\"\n attendance.recognitionConfidence = compare_faces_rekognition(\n attendance.capturedImageId, user.get(\"imageId\")[0]\n )\n attendance.save()\n publish_message(data=json.loads(attendance.to_json()), recorded=True)\n except Exception as ex:\n log.error(\"error from post attendance method \" + str(ex))\n return {\"message\": str(ex)}, 400\n return {\"id\": str(attendance.id)}, 200\n\n def check_if_attendance_marked(self, attendance):\n midnight_date = datetime.datetime.now().replace(\n hour=0, minute=0, second=0, microsecond=0\n )\n try:\n Attendance.objects().get_or_404(\n username=attendance.username,\n moduleId=attendance.moduleId,\n date_captured=midnight_date,\n )\n except Exception as ex:\n log.info(\"no attendance marked for today\")\n else:\n log.error(\"attendance has already been marked for today\")\n raise Exception(\"Attendance either marked already or has been revoked\")\n\n\nclass AttendanceApi(Resource):\n @swagger.operation()\n def put(self, id):\n log.info(\"Inside update attendance method for student by id ----->>\")\n body = request.get_json()\n Attendance.objects.get(id=id).update(**body)\n return \"\", 200\n\n @swagger.operation()\n def delete(self, id):\n log.info(\"Inside delete attendance method for student by id ---->>\")\n try:\n u = User()\n username = request.headers.get(\"Username\")\n if username is None:\n raise Exception(\"Username header missing in delete request\")\n else:\n user = u.fetchAdmin(username=username)\n attendance = Attendance.objects.get(id=id)\n attendance.status = \"REVOKED\"\n attendance.save()\n publish_message(\n data={\n \"username\": attendance.username,\n \"revokedBy\": username,\n \"moduleId\": attendance.moduleId,\n },\n recorded=False,\n )\n except Exception as ex:\n log.error(\"error from delete attendance method \" + str(ex))\n return {\"message\": str(ex)}, 400\n return \"\", 200\n\n @swagger.operation()\n def get(self, id):\n log.info(\"Inside get attendance method for student by username ----->>\")\n attendance = Attendance.objects(username=id).to_json()\n return Response(attendance, mimetype=\"application/json\", status=200)\n","repo_name":"rajan123456/uPresent","sub_path":"attendance/resources/attendance.py","file_name":"attendance.py","file_ext":"py","file_size_in_byte":5659,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"29939353554","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^add$', views.add_todo, name='add_todo'),\n url(r'^about$', views.about, name='about'),\n url(r'^delete/(?P\\d+)/$', views.delete_todo, name='delete_todo'),\n url(r'^complete/(?P\\d+)/$', views.complete_todo, name='complete_todo'),\n url(r'^incomplete/(?P\\d+)/$', views.incomplete_todo, name='incomplete_todo'),\n url(r'^edit_todo/(?P\\d+)/$', views.edit_todo, name='edit_todo'),\n\n]\n","repo_name":"esafb52/TodoProject","sub_path":"TodoApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"17425427988","text":"import nest\nimport numpy\nimport pylab\n\ndef extract_events(data, time=None, sel=None):\n \"\"\"\n Extracts all events within a given time interval or are from a\n given set of neurons.\n - data is a matrix such that\n data[:,0] is a vector of all gids and\n data[:,1] a vector with the corresponding time stamps.\n - time is a list with at most two entries such that\n time=[t_max] extracts all events with t< t_max\n time=[t_min, t_max] extracts all events with t_min <= t < t_max\n - sel is a list of gids such that\n sel=[gid1, ... , gidn] extracts all events from these gids.\n All others are discarded.\n Both time and sel may be used at the same time such that all\n events are extracted for which both conditions are true.\n \"\"\"\n\n val = []\n\n if time:\n t_max = time[-1]\n if len(time) > 1:\n t_min = time[0]\n else:\n t_min = 0\n\n for v in data:\n t = v[1]\n gid = v[0]\n if time and (t < t_min or t >= t_max):\n continue\n if not sel or gid in sel:\n val.append(v)\n\n return numpy.array(val)\n\ndef from_data(data, title=None, hist=False, hist_binwidth=5.0, grayscale=False, sel=None):\n \"\"\"\n Plot raster from data array\n \"\"\"\n\n ts = data[:, 1]\n d = extract_events(data, sel=sel)\n ts1 = d[:, 1]\n gids = d[:, 0]\n\n return _make_plot(ts, ts1, gids, data[:, 0], hist, hist_binwidth, grayscale, title)\n\ndef from_file(fname, title=None, hist=False, hist_binwidth=5.0, grayscale=False):\n \"\"\"\n Plot raster from file\n \"\"\"\n\n if nest.is_iterable(fname):\n data = None\n for f in fname:\n if data is None:\n data = numpy.loadtxt(f)\n else:\n data = numpy.concatenate((data, numpy.loadtxt(f)))\n else:\n data = numpy.loadtxt(fname)\n\n return from_data(data, title, hist, hist_binwidth, grayscale)\n\ndef from_device(detec, title=None, hist=False, hist_binwidth=5.0, grayscale=False, plot_lid=False):\n \"\"\"\n Plot raster from spike detector\n \"\"\"\n\n if not nest.GetStatus(detec)[0][\"model\"] == \"spike_detector\":\n raise nest.NESTError(\"Please provide a spike_detector.\")\n\n if nest.GetStatus(detec, \"to_memory\")[0]:\n\n ts, gids = _from_memory(detec)\n\n if not len(ts):\n raise nest.NESTError(\"No events recorded!\")\n\n if plot_lid:\n gids = [nest.GetLID([x]) for x in gids]\n\n if title is None:\n title = \"Raster plot from device '%i'\" % detec[0]\n\n if nest.GetStatus(detec)[0][\"time_in_steps\"]:\n xlabel = \"Steps\"\n else:\n xlabel = \"Time (ms)\"\n\n return _make_plot(ts, ts, gids, gids, hist, hist_binwidth, grayscale, title, xlabel)\n\n elif nest.GetStatus(detec, \"to_file\")[0]:\n fname = nest.GetStatus(detec, \"filenames\")[0]\n return from_file(fname, title, hist, hist_binwidth, grayscale)\n\n else:\n raise nest.NESTError(\"No data to plot. Make sure that either to_memory or to_file are set.\")\n\ndef _from_memory(detec):\n ev = nest.GetStatus(detec, \"events\")[0]\n return ev[\"times\"], ev[\"senders\"]\n\ndef _make_plot(ts, ts1, gids, neurons, hist, hist_binwidth, grayscale, title, xlabel=None):\n \"\"\"\n Generic plotting routine that constructs a raster plot along with\n an optional histogram (common part in all routines above)\n \"\"\"\n\n pylab.figure()\n\n if grayscale:\n color_marker = \".k\"\n color_bar = \"gray\"\n else:\n color_marker = \".\"\n color_bar = \"blue\"\n\n color_edge = \"black\"\n\n if xlabel is None:\n xlabel = \"Time (ms)\"\n\n ylabel = \"Neuron ID\"\n\n if hist:\n ax1 = pylab.axes([0.1, 0.3, 0.85, 0.6])\n plotid = pylab.plot(ts1, gids, color_marker)\n pylab.ylabel(ylabel)\n pylab.xticks([])\n xlim = pylab.xlim()\n\n pylab.axes([0.1, 0.1, 0.85, 0.17])\n t_bins = numpy.arange(numpy.amin(ts), numpy.amax(ts), float(hist_binwidth))\n n, bins = _histogram(ts, bins=t_bins)\n num_neurons = len(numpy.unique(neurons))\n heights = 1000 * n / (hist_binwidth * num_neurons)\n pylab.bar(t_bins, heights, width=hist_binwidth, color=color_bar, edgecolor=color_edge)\n pylab.yticks([int(x) for x in numpy.linspace(0.0, int(max(heights) * 1.1) + 5, 4)])\n pylab.ylabel(\"Rate (Hz)\")\n pylab.xlabel(xlabel)\n pylab.xlim(xlim)\n pylab.axes(ax1)\n else:\n plotid = pylab.plot(ts1, gids, color_marker)\n pylab.xlabel(xlabel)\n pylab.ylabel(ylabel)\n\n if title is None:\n pylab.title(\"Raster plot\")\n else:\n pylab.title(title)\n\n pylab.draw()\n\n return plotid\n\n\ndef _histogram(a, bins=10, bin_range=None, normed=False):\n from numpy import asarray, iterable, linspace, sort, concatenate\n\n a = asarray(a).ravel()\n\n if bin_range is not None:\n mn, mx = bin_range\n if mn > mx:\n raise ValueError(\"max must be larger than min in range parameter\")\n\n if not iterable(bins):\n if bin_range is None:\n bin_range = (a.min(), a.max())\n mn, mx = [mi + 0.0 for mi in bin_range]\n if mn == mx:\n mn -= 0.5\n mx += 0.5\n bins = linspace(mn, mx, bins, endpoint=False)\n else:\n if (bins[1:] - bins[:-1] < 0).any():\n raise ValueError(\"bins must increase monotonically\")\n\n # best block size probably depends on processor cache size\n block = 65536\n n = sort(a[:block]).searchsorted(bins)\n for i in range(block, a.size, block):\n n += sort(a[i:i + block]).searchsorted(bins)\n n = concatenate([n, [len(a)]])\n n = n[1:] - n[:-1]\n\n if normed:\n db = bins[1] - bins[0]\n return 1.0 / (a.size * db) * n, bins\n else:\n return n, bins\n\ndef show():\n \"\"\"\n Call pylab.show() to show all figures and enter the GUI main loop.\n Python will block until all figure windows are closed again.\n You should call this function only once at the end of a script.\n\n See also: http://matplotlib.sourceforge.net/faq/howto_faq.html#use-show\n \"\"\"\n\n pylab.show()\n","repo_name":"oist/NEST","sub_path":"pynest/nest/raster_plot.py","file_name":"raster_plot.py","file_ext":"py","file_size_in_byte":6125,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"70581657358","text":"\"\"\"\nProg 1\nW05\nP04, Aufgabe 1.2 Caesar cipher\nAuthor: Jonas Bratschi (bratsjon)\nDate: 04.11.2023\n\"\"\"\n\ndef encrypt(message: str):\n shift = user_shift\n encrypt_message = ''\n for char in message:\n # iterates throug every character\n if 97 <= ord(char.lower()) <= 122:\n # checks if its a lower character, if yes then it gets transformed\n encrypted_value = ord(char.lower()) + shift\n if shift > 0:\n if 122 < encrypted_value <= 122+shift:\n # checks if the end of the alphabet is reached in positive direction\n encrypted_value -= 26\n encrypt_message += chr(encrypted_value)\n else:\n encrypt_message += chr(encrypted_value)\n elif shift < 0:\n if 97 > encrypted_value >= 97+shift:\n # checks if the end of the alphabet is reached in negative direction\n encrypted_value += 26\n encrypt_message += chr(encrypted_value)\n else:\n encrypt_message += chr(encrypted_value)\n else:\n encrypt_message += str(char)\n\n return encrypt_message\n\n# get user information\nuser_shift = int(input(\"Enter a positive or negative number for transformation:\"))\nuser_input = input(\"Enter a text:\")\n# do whatever you want with the function response\nprint(\"\\nYour encripted text:\\n\" + encrypt(user_input))\n","repo_name":"Sunkarr/ZHAW","sub_path":"Semester 1/Prog 1/P/W7/caesar_cipher_encrypt.py","file_name":"caesar_cipher_encrypt.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"40948638707","text":"import _lib\nimport _transfers\nimport _blocks\nimport _sql\nimport re\nimport time\nimport startnode\nimport _node\nimport _complex\nimport blocksbasic\nimport blocksnodes\nimport managenodes\nimport initblockchain\nimport transactions\nimport random\n\ndatadir1 = \"\"\ndatadir2 = \"\"\ndatadir3 = \"\"\n\ndef aftertest(testfilter):\n global datadir1\n global datadir2\n global datadir3\n \n if datadir1 != \"\" or datadir2 != \"\" or datadir3 != \"\":\n _lib.StartTestGroup(\"Ending After failure of the test\")\n \n if datadir1 != \"\":\n startnode.StopNode(datadir1,\"Server 1\")\n if datadir2 != \"\": \n startnode.StopNode(datadir2,\"Server 2\")\n if datadir3 != \"\": \n startnode.StopNode(datadir3,\"Server 3\")\n \ndef test(testfilter):\n global datadir1\n global datadir2\n global datadir3\n \n _lib.StartTestGroup(\"Blocks exhange between nodes\")\n \n _lib.CleanTestFolders()\n \n inf = MakeBlockchainWithBlocks('30000')\n datadir = inf[0]\n address1 = inf[1]\n address1_2 = inf[2]\n address1_3 = inf[3]\n \n #_node.StartNodeInteractive(datadir, address1,'30000', \"Server 1\")\n _complex.AddProxyToConfig(datadir, \"localhost:40001\")\n _complex.AddInternalKeyToConfig(datadir, address1) # init internal signing\n \n startnode.StartNode(datadir, address1,'30000', \"Server 1\")\n datadir1 = datadir\n managenodes.RemoveAllNodes(datadir1)\n \n d = blocksnodes.StartNodeAndImport('30001', '30000', \"Server 2\", 40002 ,'_2_')\n datadir2 = d[0]\n address2 = d[1]\n \n d = blocksnodes.StartNodeAndImport('30002', '30000', \"Server 3\", 40003 ,'_3_')\n datadir3 = d[0]\n address3 = d[1]\n \n time.sleep(1)\n nodes = managenodes.GetNodes(datadir1)\n _lib.FatalAssert(len(nodes) == 2,\"Should be 2 nodes on server 1\")\n nodes = managenodes.GetNodes(datadir2)\n _lib.FatalAssert(len(nodes) == 2,\"Should be 2 nodes on server 2\")\n nodes = managenodes.GetNodes(datadir3)\n _lib.FatalAssert(len(nodes) == 2,\"Should be 2 nodes on server 3\")\n \n # get balance \n _sql.ExecuteSQLOnProxy(datadir1,\"CREATE TABLE test (a INT auto_increment PRIMARY KEY, b VARCHAR(20))\")\n _sql.ExecuteSQLOnProxy(datadir1,\"INSERT INTO test SET b='row1'\")\n _sql.ExecuteSQLOnProxy(datadir1,\"INSERT INTO test SET a=2,b='row2'\")\n _sql.ExecuteSQLOnProxy(datadir1,\"INSERT INTO test (b) VALUES ('row3')\")\n \n blocks = _blocks.WaitBlocks(datadir1, 5)\n _lib.FatalAssert(len(blocks) == 5,\"Should be 5 blocks on server 1\")\n blocks = _blocks.WaitBlocks(datadir2, 5)\n _lib.FatalAssert(len(blocks) == 5,\"Should be 5 blocks on server 2\")\n blocks = _blocks.WaitBlocks(datadir3, 5)\n _lib.FatalAssert(len(blocks) == 5,\"Should be 5 blocks on server 3\")\n \n time.sleep(1)# while all caches are cleaned\n \n managenodes.RemoveAllNodes(datadir1)\n managenodes.RemoveAllNodes(datadir2)\n managenodes.RemoveAllNodes(datadir3)\n \n rows = _lib.DBGetRows(datadir1,\"SELECT * FROM test\",True)\n _lib.FatalAssert(len(rows) == 3, \"Must be 3 rows in a table on node 1\")\n rows = _lib.DBGetRows(datadir2,\"SELECT * FROM test\",True)\n _lib.FatalAssert(len(rows) == 3, \"Must be 3 rows in a table on node 2\")\n rows = _lib.DBGetRows(datadir3,\"SELECT * FROM test\",True)\n _lib.FatalAssert(len(rows) == 3, \"Must be 3 rows in a table on node 3\")\n \n _sql.ExecuteSQLOnProxy(datadir1,\"INSERT INTO test (b) VALUES ('row4')\")\n \n time.sleep(1)# while all caches are cleaned\n \n rows = _lib.DBGetRows(datadir1,\"SELECT * FROM test\",True)\n _lib.FatalAssert(len(rows) == 4, \"Must be 4 rows in a table on node 1\")\n rows = _lib.DBGetRows(datadir2,\"SELECT * FROM test\",True)\n _lib.FatalAssert(len(rows) == 3, \"Must be 3 rows in a table on node 2\")\n rows = _lib.DBGetRows(datadir3,\"SELECT * FROM test\",True)\n _lib.FatalAssert(len(rows) == 3, \"Must be 3 rows in a table on node 3\")\n \n startnode.StopNode(datadir1,\"Server 1\")\n datadir1 = \"\"\n \n startnode.StopNode(datadir2,\"Server 2\")\n datadir2 = \"\"\n \n startnode.StopNode(datadir3,\"Server 3\")\n datadir3 = \"\"\n \n #_lib.RemoveTestFolder(datadir)\n _lib.EndTestGroupSuccess()\n\n\ndef MakeBlockchainWithBlocks(port):\n \n datadir = _lib.CreateTestFolder()\n \n r = blocksbasic.PrepareBlockchain(datadir,port)\n address = r[0]\n\n # create another 3 addresses\n address2 = transactions.CreateWallet(datadir)\n address3 = transactions.CreateWallet(datadir)\n\n _lib.StartTestGroup(\"Do _transfers\")\n\n transactions.GetUnapprovedTransactionsEmpty(datadir)\n \n amount1 = '1'\n amount2 = '2'\n amount3 = '3'\n \n txid1 = _transfers.Send(datadir,address,address2,amount1)\n txlist = transactions.GetUnapprovedTransactions(datadir)\n _lib.FatalAssert(len(txlist) == 1,\"Should be 1 unapproved transaction\")\n \n txid2 = _transfers.Send(datadir,address,address3,amount2)\n \n txlist = transactions.GetUnapprovedTransactions(datadir)\n _lib.FatalAssert(len(txlist) == 2,\"Should be 2 unapproved transaction\")\n txid3 = _transfers.Send(datadir,address,address3,amount3)\n \n # node needs some time to make a block, so transaction still will be in list of unapproved\n txlist = transactions.GetUnapprovedTransactions(datadir)\n \n _lib.FatalAssert(len(txlist) == 3,\"Should be 3 unapproved transaction\")\n \n txid4 = _transfers.Send(datadir,address3,address2,amount1)\n \n # node needs some time to make a block, so transaction still will be in list of unapproved\n txlist = transactions.GetUnapprovedTransactions(datadir)\n \n _lib.FatalAssert(len(txlist) == 4,\"Should be 4 unapproved transaction\")\n \n if txid1 not in txlist.keys():\n _lib.Fatal(\"Transaction 1 is not in the list of transactions\")\n \n if txid2 not in txlist.keys():\n _lib.Fatal(\"Transaction 2 is not in the list of transactions\")\n \n if txid3 not in txlist.keys():\n _lib.Fatal(\"Transaction 3 is not in the list of transactions\")\n \n if txid4 not in txlist.keys():\n _lib.Fatal(\"Transaction 4 is not in the list of transactions\")\n \n _lib.FatalAssertFloat(amount1, txlist[txid1][3], \"Amount of transaction 1 is wrong\")\n \n _lib.FatalAssertFloat(amount2, txlist[txid2][3], \"Amount of transaction 2 is wrong\")\n \n _lib.FatalAssertFloat(amount3, txlist[txid3][3], \"Amount of transaction 3 is wrong\")\n \n _lib.FatalAssertFloat(amount1, txlist[txid4][3], \"Amount of transaction 4 is wrong\")\n \n blockchash = _blocks.MintBlock(datadir,address)\n \n transactions.GetUnapprovedTransactionsEmpty(datadir)\n \n blockshashes = _blocks.GetBlocks(datadir)\n \n _lib.FatalAssert(len(blockshashes) == 2,\"Should be 2 blocks in blockchain\")\n \n _lib.StartTestGroup(\"Send 3 transactions\")\n \n microamount = 0.01\n \n txid1 = _transfers.Send(datadir,address,address2,microamount)\n txid2 = _transfers.Send(datadir,address2,address3,microamount)\n txid3 = _transfers.Send(datadir,address3,address,microamount)\n \n txlist = transactions.GetUnapprovedTransactions(datadir)\n \n _lib.FatalAssert(len(txlist) == 3,\"Should be 3 unapproved transaction\")\n \n if txid1 not in txlist.keys():\n _lib.Fatal(\"Transaction 1 is not in the list of transactions after iteration \"+str(i))\n\n if txid2 not in txlist.keys():\n _lib.Fatal(\"Transaction 2 is not in the list of transactions after iteration \"+str(i))\n\n if txid3 not in txlist.keys():\n _lib.Fatal(\"Transaction 3 is not in the list of transactions after iteration \"+str(i))\n \n blockchash = _blocks.MintBlock(datadir,address)\n transactions.GetUnapprovedTransactionsEmpty(datadir)\n \n blockshashes = _blocks.GetBlocks(datadir)\n \n _lib.FatalAssert(len(blockshashes) == 3,\"Should be 3 blocks in blockchain\")\n \n _lib.StartTestGroup(\"Send 3 transactions. Random value\")\n \n microamountmax = 0.01\n microamountmin = 0.0095\n \n a1 = round(random.uniform(microamountmin, microamountmax),8)\n a2 = round(random.uniform(microamountmin, microamountmax),8)\n a3 = round(random.uniform(microamountmin, microamountmax),8)\n txid1 = _transfers.Send(datadir,address,address2,a1)\n txid2 = _transfers.Send(datadir,address2,address3,a2)\n txid3 = _transfers.Send(datadir,address3,address,a3)\n \n txlist = transactions.GetUnapprovedTransactions(datadir)\n \n _lib.FatalAssert(len(txlist) == 3,\"Should be 3 unapproved transaction\")\n \n if txid1 not in txlist.keys():\n _lib.Fatal(\"Transaction 1 is not in the list of transactions after iteration \"+str(i))\n\n if txid2 not in txlist.keys():\n _lib.Fatal(\"Transaction 2 is not in the list of transactions after iteration \"+str(i))\n\n if txid3 not in txlist.keys():\n _lib.Fatal(\"Transaction 3 is not in the list of transactions after iteration \"+str(i))\n \n blockchash = _blocks.MintBlock(datadir,address)\n transactions.GetUnapprovedTransactionsEmpty(datadir)\n \n blockshashes = _blocks.GetBlocks(datadir)\n \n _lib.FatalAssert(len(blockshashes) == 4,\"Should be 4 blocks in blockchain\")\n \n return [datadir, address, address2, address3]\n","repo_name":"Gelembjuk/oursql","sub_path":"tests/blocksnodessql.py","file_name":"blocksnodessql.py","file_ext":"py","file_size_in_byte":9129,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"29"} +{"seq_id":"11312152816","text":"from django.shortcuts import render\nfrom rest_framework import viewsets\nfrom stolovka.models import *\nfrom stolovka.serializers import *\n\nclass FoodViewSet(viewsets.ModelViewSet):\n queryset = Food.objects.all().order_by('food_id')\n serializer_class = FoodSerializer # Сериализатор для модели\n\nclass FoodTypeViewSet(viewsets.ModelViewSet):\n queryset = FoodType.objects.all()\n serializer_class = FoodTypeSerializer\n\nclass DormViewSet(viewsets.ModelViewSet):\n queryset = Dorm.objects.all()\n serializer_class = DormSerializer\n\nclass MenuViewSet(viewsets.ModelViewSet):\n serializer_class = FoodSerializer\n def get_queryset(self):\n return Food.objects.filter(id_food_type=self.kwargs['list_pk'])\n","repo_name":"ArinaHABA/Lab2_3","sub_path":"stolovka/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"72238542159","text":"from django.conf.urls import url\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\n\nurlpatterns = [\n url(r'^$', views.home, name='home'),\n url(r'^team/$', views.team, name='team'),\n url(r'^event/$', views.event, name='event'),\n\turl(r'^event_detail/(?P[0-9]+)$',views.event_detail,name='event_detail'),\n url(r'^project/$', views.project, name='project'),\n url(r'^subscribe$', views.subscribe, name='subscribe'),\n url(r'^comment$', views.comment, name='comment'),\n url(r'^reply$', views.reply, name='reply'),\n \n\n]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n\n\n","repo_name":"DSC-JSS-NOIDA/gdg_website","sub_path":"gdg_website/app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"36269033918","text":"import os\nimport sys\nimport glob\nimport logging\nimport psycopg2\nimport pandas as pd\nfrom sql_queries import *\nfrom typing import Callable\nimport psycopg2.extensions as psycopg2Ext\n\nlogger = logging.getLogger(__name__)\n\n\ndef process_song_file(cur: psycopg2Ext.cursor, filepath: str) -> None:\n \"\"\"\n Description: This method reads each song file to get the artist and\n song observations and populate the `artists` and `songs` dim\n tables.\n\n Arguments:\n cur (psycopg2Ext.cursor): the cursor object.\n filepath (str): log data file path.\n\n Returns:\n None\n \"\"\"\n # open song file\n try:\n df = pd.read_json(filepath, lines=True)\n except Exception:\n msg = f\"Error: Could not read JSON content of {filepath}\"\n logger.warning(msg)\n return\n\n # extract artist record from df\n try:\n artist_data = (\n df[\n [\n \"artist_id\",\n \"artist_name\",\n \"artist_location\",\n \"artist_latitude\",\n \"artist_longitude\",\n ]\n ]\n .values[0]\n .tolist()\n )\n except Exception:\n msg = \"Error: Could not extract artist columns from df\"\n logger.warning(msg)\n return\n\n # insert artist record into artist table\n try:\n cur.execute(artist_table_insert, artist_data)\n except psycopg2.Error as e:\n msg = f\"Error: Could not insert artist record in artist table\"\n logger.warning(msg, e)\n return\n\n # extract song record from df\n try:\n song_data = (\n df[[\"song_id\", \"title\", \"artist_id\", \"year\", \"duration\"]].values[0].tolist()\n )\n except Exception:\n msg = \"Error: Could not extract song columns from df\"\n logger.warning(msg)\n return\n\n # insert song record into song table\n try:\n cur.execute(song_table_insert, song_data)\n except psycopg2.Error as e:\n msg = f\"Error: Could not insert song record in song table\"\n logger.warning(msg, e)\n return\n\n\ndef process_log_file(cur: psycopg2Ext.cursor, filepath: str) -> None:\n \"\"\"\n Description: This method reads each log file to extract the\n time and user observations and populate the `time` and\n `users` dim tables. It then, queries `song_id` and\n `artist_id` from `songs` and `artists` tables to insert\n with other relevant information into the `songplays`\n fact table.\n\n Arguments:\n cur (psycopg2Ext.cursor): the cursor object.\n filepath (str): log data file path.\n\n Returns:\n None\n \"\"\"\n # open log file\n try:\n df = pd.read_json(filepath, lines=True)\n except Exception:\n msg = f\"Error: Could not read JSON content of {filepath}\"\n logger.warning(msg)\n return\n\n # convert timestamp column to datetime\n df[\"ts\"] = pd.to_datetime(df[\"ts\"], unit=\"ms\")\n\n # filter by specific page action\n page = \"NextSong\"\n t = df[df[\"page\"] == page]\n\n # insert time data records\n time_data = (\n t.ts,\n t.ts.dt.hour,\n t.ts.dt.isocalendar().day,\n t.ts.dt.isocalendar().week,\n t.ts.dt.month,\n t.ts.dt.isocalendar().year,\n t.ts.dt.weekday,\n )\n column_labels = (\"start_time\", \"hour\", \"day\", \"week\", \"month\", \"year\", \"weekday\")\n data = {column_labels[i]: time_data[i] for i in range(len(column_labels))}\n time_df = pd.DataFrame(data)\n\n # insert time records into time table\n for i, row in time_df.iterrows():\n try:\n cur.execute(time_table_insert, list(row))\n except psycopg2.Error as e:\n msg = f\"Error: Could not insert following record in time table: {row}\"\n logger.warning(msg, e)\n continue\n\n # load user table\n try:\n user_df = df[[\"userId\", \"firstName\", \"lastName\", \"gender\", \"level\"]]\n except Exception:\n msg = \"Error: Could not extract song columns from dataframe\"\n logger.warning(msg, sys.exc_info()[0])\n return\n # filter user_df data if userId is not an empty string\n try:\n user_df = user_df[user_df[\"userId\"] != \"\"]\n except Exception:\n msg = \"Error: Could not drop empty string values from user_df.userId.\"\n logger.warning(msg)\n return\n\n # insert user records\n for i, row in user_df.iterrows():\n try:\n cur.execute(user_table_insert, row)\n except psycopg2.Error as e:\n msg = f\"Error: Could not insert following record in user table: {row}\"\n logger.warning(msg, e)\n continue\n\n df.dropna(axis=0, subset=[\"artist\", \"song\", \"length\"], inplace=True)\n\n # insert songplay records\n for index, row in df.iterrows():\n # get songid and artistid from song and artist tables\n try:\n cur.execute(song_select, (row.song, row.artist, row.length))\n except psycopg2.Error as e:\n msg = f\"Error: Could not get song_id and artist_id \\\n from song and artist tables\"\n logger.warning(msg, e)\n continue\n\n results = cur.fetchone()\n if results:\n songid, artistid = results\n else:\n songid, artistid = None, None\n\n # insert songplay record\n songplay_data = (\n row.ts,\n row.userId,\n row.level,\n songid,\n artistid,\n row.sessionId,\n row.location,\n row.userAgent,\n )\n\n try:\n cur.execute(songplay_table_insert, songplay_data)\n except psycopg2.Error as e:\n msg = f\"Error: Could not insert songplay record.\"\n logger.warning(msg, e)\n continue\n\n\ndef process_data(\n cur: psycopg2Ext.cursor,\n conn: psycopg2Ext.connection,\n filepath: str,\n func: Callable[[None], None],\n) -> None:\n \"\"\"\n Describe: This method collects all files under\n filepath and while iterating over these files\n it will call the `func` input method.\n\n Arguments:\n cur (psycopg2Ext.cursor): the cursor object.\n conn (psycopg2Ext.connection): the connection object.\n filepath (str): data file path.\n func (Callable[[None], None])): method which returns None.\n\n Returns:\n None\n \"\"\"\n # get all files matching extension from directory\n all_files = []\n for root, dirs, files in os.walk(filepath):\n files = glob.glob(os.path.join(root, \"*.json\"))\n for f in files:\n all_files.append(os.path.abspath(f))\n\n # get total number of files found\n num_files = len(all_files)\n print(f\"{num_files} files found in {filepath}\")\n\n # iterate over files and process\n for i, datafile in enumerate(all_files, 1):\n func(cur, datafile)\n conn.commit()\n print(f\"{i}/{num_files} files processed.\")\n\n\ndef main() -> None:\n \"\"\"\n Description: This method establishes a connection with\n sparkifydb and calls `process_data` method on song\n and log files.\n\n Returns:\n None\n \"\"\"\n try:\n conn = psycopg2.connect(\n \"host=127.0.0.1 dbname=sparkifydb user=student password=student\"\n )\n except psycopg2.Error as e:\n msg = \"ERROR: Could not make connection to sparkify database.\"\n logger.warning(msg, e)\n return\n\n try:\n cur = conn.cursor()\n except psycopg2.Error as e:\n msg = \"ERROR: Could not get cursor to sparkify database.\"\n logger.warning(msg, e)\n return\n\n # process song files\n process_data(cur, conn, filepath=\"data/song_data\", func=process_song_file)\n\n # process log files\n process_data(cur, conn, filepath=\"data/log_data\", func=process_log_file)\n\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"najuzilu/DM-PostgreSQL","sub_path":"etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":7861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"11079529517","text":"import logging\nfrom typing import TextIO\nfrom sortedcontainers import SortedDict\n\nDEBUG = logging.DEBUG\nINFO = logging.INFO\nWARNING = logging.WARNING\nERROR = logging.ERROR\nCRITICAL = logging.CRITICAL\nCRUCIAL = 60\n\n\nclass Logger:\n def __init__(self, log_level: int = DEBUG, forced: bool = False, fake_logger: bool = False):\n if log_level not in [DEBUG, INFO, WARNING, ERROR, CRITICAL, CRUCIAL]:\n raise RuntimeError(f'Unknown log level: {log_level}')\n self._log_level = log_level\n self._log: SortedDict = SortedDict()\n self._previous_ts = 0\n self._last_ts = 0\n self._sim_time = 0\n self._file: TextIO | None = None\n self._forced = forced\n self._fake_logger = fake_logger\n # logging.basicConfig(level=log_level)\n\n def set_log_level(self, log_level: int) -> None:\n if log_level not in [DEBUG, INFO, WARNING, ERROR, CRITICAL, CRUCIAL]:\n raise RuntimeError(f'Unknown log level: {log_level}')\n\n self._log_level = log_level\n\n def set_file(self, file_path: str) -> None:\n self._file = open(file_path, \"w\", encoding='utf-8')\n\n def close_file(self) -> None:\n if self._file is not None:\n self._file.close()\n\n def debug(self, t: int, msg: str) -> None:\n if self._fake_logger:\n new_entry = f\"{int((t - t % 1000) / 1000):10,}.{t % 1000:03d}s\\t{msg}\"\n print(new_entry)\n return\n\n if self._log_level <= DEBUG:\n self._print(t, msg)\n # logging.debug(msg)\n\n def info(self, t: int, msg: str) -> None:\n if self._log_level <= INFO:\n self._print(t, msg)\n # logging.info(msg)\n\n def warning(self, t: int, msg: str) -> None:\n if self._log_level <= WARNING:\n self._print(t, msg)\n # logging.warning(msg)\n\n def error(self, t: int, msg: str) -> None:\n if self._log_level <= ERROR:\n self._print(t, msg)\n # logging.error(msg)\n\n def critical(self, t: int, msg: str) -> None:\n if self._log_level <= CRITICAL:\n self._print(t, msg)\n # logging.critical(msg)\n\n def crucial(self, t: int, msg: str) -> None:\n if self._log_level <= CRUCIAL:\n self._print(t, msg)\n\n def set_sim_time(self, sim_time: int) -> None:\n self._sim_time = sim_time\n\n def _flush(self) -> None:\n # log_list = list(self._log)\n # log_list.sort()\n\n for x in self._log:\n for y in self._log[x]:\n if self._file is not None:\n self._file.write(f\"{y}\\n\")\n print(y)\n\n self._log.clear()\n\n def _print(self, t: int, msg: str) -> None:\n new_entry = f\"{int((t - t % 1000) / 1000):10,}.{t % 1000:03d}s\\t{msg}\"\n if t not in self._log:\n self._log[t] = []\n\n self._log[t].append(new_entry)\n\n if t - self._last_ts >= 10000 or t == self._sim_time or self._forced:\n # log_list = list(self._log)\n # log_list.sort()\n\n for x in self._log:\n for y in self._log[x]:\n if self._file is not None:\n self._file.write(f\"{y}\\n\")\n print(y)\n\n self._log.clear()\n\n self._last_ts = t\n\n\nlogger = Logger(log_level=INFO, forced=True)\n","repo_name":"sergiuszm/loralite2","sub_path":"loralite/simulator/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"33655432609","text":"import tensorflow as tf\n\n\nclass MAC(tf.keras.layers.Layer):\n \"\"\"Global max pooling (MAC) layer.\n\n Maximum Activations of Convolutions (MAC) is simply constructed by\n max-pooling over all dimensions per feature map. See\n https://arxiv.org/abs/1511.05879 for a reference.\n \"\"\"\n\n def call(self, x, axis=None):\n \"\"\"Invokes the MAC pooling instance.\n\n Args:\n x: [B, H, W, D] A float32 Tensor.\n axis: Dimensions to reduce. By default, dimensions [1, 2] are reduced.\n\n Returns:\n output: [B, D] A float32 Tensor.\n \"\"\"\n if axis is None:\n axis = [1, 2]\n return mac(x, axis=axis)\n\n\nclass SPoC(tf.keras.layers.Layer):\n \"\"\"Average pooling (SPoC) layer.\n\n Sum-pooled convolutional features (SPoC) is based on the sum pooling of the\n deep features. See https://arxiv.org/pdf/1510.07493.pdf for a reference.\n \"\"\"\n\n def call(self, x, axis=None):\n \"\"\"Invokes the SPoC instance.\n\n Args:\n x: [B, H, W, D] A float32 Tensor.\n axis: Dimensions to reduce. By default, dimensions [1, 2] are reduced.\n\n Returns:\n output: [B, D] A float32 Tensor.\n \"\"\"\n if axis is None:\n axis = [1, 2]\n return spoc(x, axis)\n\n\nclass GeM(tf.keras.layers.Layer):\n \"\"\"Generalized mean pooling (GeM) layer.\n\n Generalized Mean Pooling (GeM) computes the generalized mean of each\n channel in a tensor. See https://arxiv.org/abs/1711.02512 for a reference.\n \"\"\"\n\n def __init__(self, power=3.):\n \"\"\"Initialization of the generalized mean pooling (GeM) layer.\n\n Args:\n power: Float power > 0 is an inverse exponent parameter, used during the\n generalized mean pooling computation. Setting this exponent as power > 1\n increases the contrast of the pooled feature map and focuses on the\n salient features of the image. GeM is a generalization of the average\n pooling commonly used in classification networks (power = 1) and of\n spatial max-pooling layer (power = inf).\n \"\"\"\n super(GeM, self).__init__()\n self.power = power\n self.eps = 1e-6\n\n def call(self, x, axis=None):\n \"\"\"Invokes the GeM instance.\n\n Args:\n x: [B, H, W, D] A float32 Tensor.\n axis: Dimensions to reduce. By default, dimensions [1, 2] are reduced.\n\n Returns:\n output: [B, D] A float32 Tensor.\n \"\"\"\n if axis is None:\n axis = [1, 2]\n return gem(x, power=self.power, eps=self.eps, axis=axis)\n\n\nclass GeMPooling2D(tf.keras.layers.Layer):\n \"\"\"Generalized mean pooling (GeM) pooling operation for spatial data.\"\"\"\n\n def __init__(self,\n power=20.,\n pool_size=(2, 2),\n strides=None,\n padding='valid',\n data_format='channels_last'):\n \"\"\"Initialization of GeMPooling2D.\n\n Args:\n power: Float, power > 0. is an inverse exponent parameter (GeM power).\n pool_size: Integer or tuple of 2 integers, factors by which to downscale\n (vertical, horizontal)\n strides: Integer, tuple of 2 integers, or None. Strides values. If None,\n it will default to `pool_size`.\n padding: One of `valid` or `same`. `valid` means no padding. `same`\n results in padding evenly to the left/right or up/down of the input such\n that output has the same height/width dimension as the input.\n data_format: A string, one of `channels_last` (default) or\n `channels_first`. The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape `(batch, height, width,\n channels)` while `channels_first` corresponds to inputs with shape\n `(batch, channels, height, width)`.\n \"\"\"\n super(GeMPooling2D, self).__init__()\n self.power = power\n self.eps = 1e-6\n self.pool_size = pool_size\n self.strides = strides\n self.padding = padding.upper()\n data_format_conv = {\n 'channels_last': 'NHWC',\n 'channels_first': 'NCHW',\n }\n self.data_format = data_format_conv[data_format]\n\n def call(self, x):\n tmp = tf.pow(x, self.power)\n tmp = tf.nn.avg_pool(tmp, self.pool_size, self.strides, self.padding,\n self.data_format)\n out = tf.pow(tmp, 1. / self.power)\n return out\n\n\ndef mac(x, axis=None):\n \"\"\"Performs global max pooling (MAC).\n\n Args:\n x: [B, H, W, D] A float32 Tensor.\n axis: Dimensions to reduce. By default, dimensions [1, 2] are reduced.\n\n Returns:\n output: [B, D] A float32 Tensor.\n \"\"\"\n if axis is None:\n axis = [1, 2]\n return tf.reduce_max(x, axis=axis, keepdims=False)\n\n\ndef spoc(x, axis=None):\n \"\"\"Performs average pooling (SPoC).\n\n Args:\n x: [B, H, W, D] A float32 Tensor.\n axis: Dimensions to reduce. By default, dimensions [1, 2] are reduced.\n\n Returns:\n output: [B, D] A float32 Tensor.\n \"\"\"\n if axis is None:\n axis = [1, 2]\n return tf.reduce_mean(x, axis=axis, keepdims=False)\n\n\ndef gem(x, axis=None, power=3., eps=1e-6):\n \"\"\"Performs generalized mean pooling (GeM).\n\n Args:\n x: [B, H, W, D] A float32 Tensor.\n axis: Dimensions to reduce. By default, dimensions [1, 2] are reduced.\n power: Float, power > 0 is an inverse exponent parameter (GeM power).\n eps: Float, parameter for numerical stability.\n\n Returns:\n output: [B, D] A float32 Tensor.\n \"\"\"\n if axis is None:\n axis = [1, 2]\n tmp = tf.pow(tf.maximum(x, eps), power)\n out = tf.pow(tf.reduce_mean(tmp, axis=axis, keepdims=False), 1. / power)\n return out\n","repo_name":"tensorflow/models","sub_path":"research/delf/delf/python/pooling_layers/pooling.py","file_name":"pooling.py","file_ext":"py","file_size_in_byte":5402,"program_lang":"python","lang":"en","doc_type":"code","stars":76227,"dataset":"github-code","pt":"29"} +{"seq_id":"75026978639","text":"import random\n\nimport numpy\nimport torch\n\n\ndef batch_loss(\n pred_xh,\n embeddings_xh,\n bbox_coords,\n mean=True\n):\n \"\"\"Contrastive loss for learning to differentiate between bounding boxes.\n \n Parameters :\n ============\n pred_xh : torch.FloatTensor of size (N, 2, W, H). Pixel-wise bounding box\n prediction by the model, using its final layer on the pixel embeddings.\n embeddings_xh : embeddings prior to the model's final layer.\n bbox_coords : list of list of (x, y, w, h) of bounding boxes. Corresponds\n to the indices of pred_xh and embeddings_xh.\n mean : bool indicator of whether to use mean of batch or not.\n\n Output :\n ========\n loss : single tensor value that can backpropogate gradient in respect to loss\n \"\"\"\n assert len(pred_xh) == len(embeddings_xh) == len(bbox_coords)\n\n sum_loss = n = 0.0\n for n, args in enumerate(zip(pred_xh, embeddings_xh, bbox_coords), 1):\n sum_loss += _single_bounding_box_contrastive_loss(*args)\n return sum_loss / n**int(mean)\n\n\n# === PRIVATE ===\n\n\ndef _single_bounding_box_contrastive_loss(\n pred_xh,\n embeddings_xh,\n bbox_coords\n):\n if not bbox_coords:\n return 0\n elif len(bbox_coords) == 1:\n return _bounding_box_similarity_loss(\n pred_xh,\n embeddings_xh,\n bbox_coords[0]\n )\n else:\n i, j = _obtain_two_rand_diff_bbox_coords(bbox_coords)\n sim_loss = _bounding_box_similarity_loss(\n pred_xh,\n embeddings_xh,\n bbox_coords[i]\n )\n dif_loss = _bounding_box_difference_loss(\n pred_xh,\n embeddings_xh,\n bbox_coords[i],\n bbox_coords[j]\n )\n return sim_loss + dif_loss\n\n\ndef _obtain_two_rand_diff_bbox_coords(bbox_coords):\n i = random.randint(0, len(bbox_coords) - 1)\n j = i\n while j == i:\n j = random.randint(0, len(bbox_coords) - 1)\n return i, j\n\n\ndef _extract_avg_embedding_select(emb, select):\n d, w, h = emb.size()\n select = select.unsqueeze(0).repeat(d, 1, 1)\n data = emb[select].view(d, -1).T\n numpy.random.shuffle(data)\n return data\n\n\ndef _extract_avg_embedding_selections(emb, select1, select2):\n emb1 = _extract_avg_embedding_select(emb, select1)\n emb2 = _extract_avg_embedding_select(emb, select2)\n n = min(len(emb1), len(emb2))\n assert n > 0\n return emb1[:n], emb2[:n]\n\n\ndef cosine_sim(m1, m2, eps=1e-12):\n return ((m1*m2).sum(dim=1)/(m1.norm(dim=1)*m2.norm(dim=1) + eps)).mean()\n\n\ndef _bounding_box_similarity_loss(\n pred_xh,\n embeddings_xh,\n bbox_coord\n):\n selection = pred_xh[1] > pred_xh[0]\n mask = torch.zeros_like(selection)\n x, y, w, h = bbox_coord\n mask[x:x+w, y:y+h] = 1\n correct_selection = selection & mask\n\n emb_part1, emb_part2 = _extract_avg_embedding_selections(\n embeddings_xh, correct_selection, correct_selection\n )\n\n # we wish to maximize their average cosine similarity\n return -cosine_sim(emb_part1, emb_part2)\n\n\ndef _bounding_box_difference_loss(\n pred_xh,\n embeddings_xh,\n bbox_coord1,\n bbox_coord2\n):\n selection = pred_xh[1] > pred_xh[0]\n mask1 = torch.zeros_like(selection)\n mask2 = torch.zeros_like(selection)\n x1, y1, w1, h1 = bbox_coord1\n x2, y2, w2, h2 = bbox_coord2\n mask1[x1:x1+w1, y1:y1+h1] = 1\n mask2[x2:x2+w2, y2:y2+h2] = 1\n select_part1 = selection & mask1\n select_part2 = selection & mask2\n\n emb_part1, emb_part2 = _extract_avg_embedding_selections(\n embeddings_xh, select_part1, select_part2\n )\n\n # we wish to minimize their average cosine similarity\n return cosine_sim(emb_part1, emb_part2)\n","repo_name":"yuzhihu1/Vision-AI","sub_path":"vision_ai/models/bounding_box_contrast.py","file_name":"bounding_box_contrast.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"32912129203","text":"from __future__ import print_function, division\nimport os\nimport argparse\nimport torch\nfrom environment import make_atari, wrap_deepmind, wrap_pytorch, make_atari_cart\nfrom utils import read_config\nfrom model import DuelingCnnDQN\nfrom train import train\n\n#undo_logger_setup()\nparser = argparse.ArgumentParser(description='DQN')\nparser.add_argument(\n '--lr',\n type=float,\n default=0.000125,\n metavar='LR',\n help='learning rate (default: 0.000125)')\nparser.add_argument(\n '--gamma',\n type=float,\n default=0.99,\n metavar='G',\n help='discount factor for rewards (default: 0.99)')\nparser.add_argument(\n '--seed',\n type=int,\n default=None,\n metavar='S',\n help='random seed (default: None)')\nparser.add_argument(\n '--total-frames',\n type=int,\n default=6000000,\n metavar='TS',\n help='How many frames to train with')\nparser.add_argument(\n '--max-episode-length',\n type=int,\n default=10000,\n metavar='M',\n help='maximum length of an episode (default: 10000)')\nparser.add_argument(\n '--env',\n default='PongNoFrameskip-v4',\n metavar='ENV',\n help='environment to train on (default: PongNoFrameskip-v4)')\nparser.add_argument(\n '--env-config',\n default='config.json',\n metavar='EC',\n help='environment to crop and resize info (default: config.json)')\n\nparser.add_argument(\n '--optimizer',\n default='Adam',\n metavar='OPT',\n help='optimizer to use, one of {Adam, RMSprop}')\nparser.add_argument(\n '--save-model-dir',\n default='trained_models/',\n metavar='SMD',\n help='folder to save trained models')\nparser.add_argument(\n '--log-dir', default='logs/', metavar='LG', help='folder to save logs')\nparser.add_argument(\n '--gpu-id',\n type=int,\n default=0,\n help='GPUs to use [-1 CPU only] (default: -1)')\nparser.add_argument(\n '--amsgrad',\n default=False,\n metavar='AM',\n help='Adam optimizer amsgrad parameter')\n\nparser.add_argument(\n '--skip-rate',\n type=int,\n default=4,\n metavar='SR',\n help='frame skip rate (default: 4)')\nparser.add_argument(\n '--kappa-end',\n type=float,\n default=0.8,\n metavar='SR',\n help='final value of the variable controlling importance of standard loss (default: 0.5)')\nparser.add_argument('--robust',\n dest='robust',\n action='store_true',\n help='train the model to be verifiably robust')\nparser.add_argument(\n '--load-path',\n type=str,\n default=None,\n help='Path to load a model from. By default starts training a new model, use this for loading only model params')\nparser.add_argument(\n '--resume-training',\n type=str,\n default=None,\n help='''Path to resume training from. This argument also loads optimizer params and training step in addition to model.\n Dont use together with load-path''')\n\nparser.add_argument(\n '--attack-epsilon-end',\n type=float,\n default=1/255,\n metavar='EPS',\n help='max size of perturbation trained on')\nparser.add_argument(\n '--attack-epsilon-schedule',\n type=int,\n default=4000000,\n help='The frame by which to reach final perturbation')\nparser.add_argument(\n '--exp-epsilon-end',\n type=float,\n default=0.01,\n help='for epsilon-greedy exploration')\nparser.add_argument(\n '--exp-epsilon-decay',\n type=int,\n default=500000,\n help='controls linear decay of exploration epsilon')\nparser.add_argument(\n '--replay-initial',\n type=int,\n default=50000,\n help='How many frames of experience to collect before starting to learn')\nparser.add_argument(\n '--batch-size',\n type=int,\n default=128,\n help='Batch size for updating agent')\nparser.add_argument(\n '--updates-per-frame',\n type=int,\n default=32,\n help='How many gradient updates per new frame')\nparser.add_argument(\n '--buffer-size',\n type=int,\n default=200000,\n help='How frames to store in replay buffer')\n\nparser.add_argument(\n '--loss-fn',\n type=str,\n default = 'approach_2',\n help='Which loss function to use for robust training, one of [approach_1, approach_2]'\n)\nparser.add_argument('--decay-zero',\n dest='decay_zero',\n action='store_true',\n help='whether to decay exploration epsilon down to zero')\nparser.add_argument('--no-smoothed',\n dest='smoothed',\n action='store_false',\n help='whether to use linear attack epsilon schedule instead of default smoothed one')\nparser.add_argument(\"--adam-eps\",\n type = float,\n default = 1e-8,\n help = 'the epsilon parameter for adam optimizer')\nparser.add_argument('--linear-kappa',\n dest='constant_kappa',\n action='store_false',\n help='whether to use a linear kappa schedule instead of default constant kappa')\n\nparser.set_defaults(robust=False, decay_zero=False, smoothed=True, constant_kappa = True)\n\nif __name__ == '__main__':\n args = parser.parse_args()\n assert (args.loss_fn in ('approach_1', 'approach_2'))\n if args.seed:\n torch.manual_seed(args.seed)\n if args.gpu_id>=0:\n torch.cuda.manual_seed(args.seed)\n\n setup_json = read_config(args.env_config)\n env_conf = setup_json[\"Default\"]\n for i in setup_json.keys():\n if i in args.env:\n env_conf = setup_json[i]\n if \"NoFrameskip\" not in args.env:\n env = make_atari_cart(args.env)\n else:\n env = make_atari(args.env)\n env = wrap_deepmind(env, central_crop=True, clip_rewards=False, episode_life=False, **env_conf)\n env = wrap_pytorch(env)\n \n curr_model = DuelingCnnDQN(env.observation_space.shape[0], env.action_space)\n target_model = DuelingCnnDQN(env.observation_space.shape[0], env.action_space)\n \n if not os.path.exists(args.log_dir):\n os.mkdir(args.log_dir)\n if not os.path.exists(args.save_model_dir):\n os.mkdir(args.save_model_dir)\n \n if args.load_path:\n saved_state = torch.load(\n args.load_path,\n map_location=lambda storage, loc: storage)\n if \"model_state_dict\" in saved_state.keys():\n saved_state = saved_state['model_state_dict']\n curr_model.load_state_dict(saved_state)\n \n target_model.load_state_dict(curr_model.state_dict())\n if args.gpu_id >= 0:\n with torch.cuda.device(args.gpu_id):\n curr_model.cuda()\n target_model.cuda()\n \n train(curr_model, target_model, env, args)\n \n","repo_name":"tuomaso/radial_rl_v2","sub_path":"Atari/DQN/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6607,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"29"} +{"seq_id":"20178820528","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nfrom turtle import delay\nimport turtle\nimport actionlib\nfrom actionlib_msgs.msg import *\nimport rospy\nfrom move_base_msgs.msg import MoveBaseAction, MoveBaseGoal, MoveBaseFeedback, MoveBaseResult\nfrom std_msgs.msg import Int16\n\nfrom nav_msgs.msg import Odometry\nfrom tf.transformations import euler_from_quaternion\nfrom geometry_msgs.msg import Point, Twist\n\n\n\nimport sys\nimport rospy\nimport math\nimport moveit_commander\nfrom geometry_msgs.msg import PoseStamped, Pose\nimport tf\nfrom std_msgs.msg import String, Int16, Float32\nimport os\n\n\nmoveit_commander.roscpp_initialize(sys.argv) \n\ngroup = [moveit_commander.MoveGroupCommander(\"ur5_manipulator\")]\npose_goal = Pose()\n\n\nclass TestMove():\n\n def __init__(self):\n \n self.scene = moveit_commander.PlanningSceneInterface()\n self.robot_cmd = moveit_commander.RobotCommander()\n\n #robot_gripper = Mo\n self.robot_arm = group[0]\n self.robot_arm.set_goal_orientation_tolerance(0.005)\n self.robot_arm.set_planning_time(5)\n self.robot_arm.set_num_planning_attempts(5)\n\n rospy.sleep(2)\n # Allow replanning to increase the odds of a solution\n self.robot_arm.allow_replanning(True) \n\n def move_code(self):\n global tm_count\n\n # #planning 1\n self.robot_arm.set_named_target(\"front_view\") # moveit setup assistant에서 설정한 동작\n self.robot_arm.go(wait=True)\n print(\"====== move plan go to front_view ======\") \n rospy.sleep(1)\n\n def move_code2(self):\n global tm_count\n\n # #planning 1\n self.robot_arm.set_named_target(\"button_view\") # moveit setup assistant에서 설정한 동작\n self.robot_arm.go(wait=True)\n print(\"====== move plan go to button_view ======\") \n rospy.sleep(1)\n\n\n\n\n\ndef newOdom (msg):\n global x\n global y\n global theta\n\n x = msg.pose.pose.position.x\n y = msg.pose.pose.position.y\n\n rot_q = msg.pose.pose.orientation\n (roll, pitch, theta) = euler_from_quaternion([rot_q.x, rot_q.y, rot_q.z, rot_q.w])\n\ndef move_go(Int16):\n global state\n state = Int16.data\n\n if state == 1:\n print(\"AR no, Turn\")\n if state == 0:\n print(\"AR find!!\")\n\ndef rotation():\n global state\n global x, y, theta\n if state == 1:\n while x < 2.6:\n print(x)\n speed.linear.x = 0.3\n pub.publish(speed)\n \n while theta >-1.6:\n speed.linear.x = 0.0\n speed.angular.z = -0.3\n pub.publish(speed)\n print(theta)\n \n while y >-0.07:\n speed.linear.x = 0.1\n speed.angular.z = 0.0\n pub.publish(speed)\n print(y)\n pub2.publish(1)\n\n state = state +1\n tm.move_code2()\n\n \n\nif __name__=='__main__': \n\n\n rospy.init_node('send_client_goal2')\n sub = rospy.Subscriber(\"/odometry/filtered\", Odometry, newOdom)\n pub = rospy.Publisher(\"/cmd_vel\", Twist, queue_size=1)\n pub2 = rospy.Publisher(\"/talk_class\", Int16, queue_size=1)\n speed = Twist()\n state = 0\n state_count =0\n x=0\n y=0\n i=0\n r = rospy.Rate(4)\n\n sub1 = rospy.Subscriber('/state', Int16, move_go)\n tm = TestMove()\n tm.__init__()\n tm.move_code()\n while not rospy.is_shutdown():\n rotation()","repo_name":"petterdu/melodic_deeplearning_setting","sub_path":"elevator_simulation/scripts/mobile_rotation.py","file_name":"mobile_rotation.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16979017105","text":"import logging\nfrom logging_config import configure_logging\nimport utils\nimport logging_tree\n\nlogger = logging.getLogger(\"app\")\n\nconfigure_logging()\n\n\ndef calculate():\n logger.debug(\"ÎŒØ∏‡°⁄·°€йцукен\")\n logger.debug(\"should be visible in logs\")\n operation = input(\"Выберите операцию: '+', '-', '*', '/': \")\n operations = {\n \"+\": utils.plus,\n \"-\": utils.subtract,\n \"*\": utils.multiply,\n \"/\": utils.divide,\n }\n if operation not in operations:\n logger.error(f\"Выбрана неверная операция: {operation}\")\n exit()\n\n a = utils.get_number()\n logger.debug(f\"Число 1: {a}\")\n b = utils.get_number()\n logger.debug(f\"Число 2: {b}\")\n\n result = operations[operation](a, b)\n logger.info(f\"a={a}, b={b}, операция: '{operation}', результат: {result}\")\n return result\n\n\nif __name__ == \"__main__\":\n print(calculate())\n\n with open(\"logging_tree.txt\", \"w\") as file:\n file.write(logging_tree.format.build_description())\n","repo_name":"dndrheadof/urfu-python-advanced","sub_path":"urfu_python_advanced/module7/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"69854652558","text":"# -*- encoding: utf-8 -*-\n'''\n@File : 剑指 Offer 68 - II. 二叉树的最近公共祖先.py\n@Time : 2022/05/24 20:53:46\n@Author : henfy\n@Diffi : Easy\n@Method : 搜索与回溯算法(中等)\n\n题目:https://leetcode.cn/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/\n'''\n\n# Definition for a binary tree node.\n\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:\n # DFS\n if not root or root == p or root == q:\n return root\n left = self.lowestCommonAncestor(root.left, p, q)\n right = self.lowestCommonAncestor(root.right, p, q)\n if not left:\n return right\n if not right:\n return left\n return root\n","repo_name":"henfy233/leetcode","sub_path":"剑指Offer/剑指 Offer 68 - II. 二叉树的最近公共祖先.py","file_name":"剑指 Offer 68 - II. 二叉树的最近公共祖先.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"39777350833","text":"import json\n\nimport attr\n\nfrom klein import Klein\n\nfrom twisted.application.service import MultiService\nfrom twisted.application.internet import TimerService\nfrom twisted.internet.interfaces import IReactorTime\nfrom twisted.logger import Logger\n\n\nclass NotSettled(Exception):\n \"\"\"\n Raised when getting index of a member when group is not settled\n \"\"\"\n\n\n@attr.s\nclass SettlingGroup(object):\n \"\"\"\n A group that \"settles\" down when there is no activity for `settle` seconds.\n\n :param clock: A twisted time provider that implements :obj:`IReactorTime`\n :param float settle: Number of seconds to wait before settling\n \"\"\"\n clock = attr.ib(validator=attr.validators.provides(IReactorTime))\n settle = attr.ib(convert=float)\n _members = attr.ib(default=attr.Factory(dict))\n _settled = attr.ib(default=False)\n _timer = attr.ib(default=None)\n _log = Logger()\n\n def _reset_timer(self):\n if self._timer is not None and self._timer.active():\n self._timer.cancel()\n self._timer = self.clock.callLater(self.settle, self._do_settling)\n self._settled = False\n self._log.info('reset timer')\n\n def _do_settling(self):\n self._members = {p: i + 1 for i, p in enumerate(self._members.keys())}\n self._settled = True\n self._log.info('settled with {n} members', n=len(self._members))\n\n def add(self, member):\n \"\"\"\n Add member to the group\n \"\"\"\n if member in self._members:\n return\n self._members[member] = None\n self._reset_timer()\n\n def remove(self, member):\n \"\"\"\n Remove member from the group.\n\n :raises: ``KeyError` if member is not in the group\n \"\"\"\n del self._members[member]\n self._reset_timer()\n\n def index_of(self, member):\n \"\"\"\n Return index allocated for the given member if group has settled\n\n :raises: :obj:`NotSettled` if group is not settled\n \"\"\"\n if not self._settled:\n raise NotSettled(member)\n return self._members[member]\n\n def __len__(self):\n return len(self._members)\n\n def __contains__(self, member):\n return member in self._members\n\n @property\n def settled(self):\n \"\"\"\n Is it settled?\n \"\"\"\n return self._settled\n\n\n@attr.s\nclass HeartbeatingClients(MultiService):\n \"\"\"\n Group of clients that will heartbeat to remain active\n \"\"\"\n clock = attr.ib(validator=attr.validators.provides(IReactorTime))\n timeout = attr.ib(convert=float)\n interval = attr.ib(convert=float)\n _remove_cb = attr.ib()\n _clients = attr.ib(default=attr.Factory(dict))\n log = Logger()\n\n def __attrs_post_init__(self):\n super(HeartbeatingClients, self).__init__()\n timer = TimerService(self.interval, self._check_clients)\n timer.clock = self.clock\n self.addService(timer)\n\n def remove(self, client):\n del self._clients[client]\n\n def _check_clients(self):\n # This is O(n). May have issues when n is large. See if a heap can be used instead\n now = self.clock.seconds()\n clients_to_remove = []\n for client, last_active in self._clients.items():\n inactive = now - last_active\n if inactive > self.timeout:\n self.log.info('Client {c} timed out after {t} seconds', c=client, t=inactive)\n clients_to_remove.append(client)\n for client in clients_to_remove:\n self.remove(client)\n self._remove_cb(client)\n\n def heartbeat(self, client):\n if client not in self._clients:\n self.log.info('Adding client {c}', c=client)\n self._clients[client] = self.clock.seconds()\n\n def __contains__(self, client):\n return client in self._clients\n\n\ndef extract_client(request):\n \"\"\"\n Return session id from the request\n \"\"\"\n _id = request.requestHeaders.getRawHeaders('Bloc-Session-ID', None)\n return _id[0] if _id is not None else None\n\n\nclass Bloc(MultiService):\n \"\"\"\n Main server object that clients talk to\n \"\"\"\n\n app = Klein()\n\n def __init__(self, clock, timeout, settle, interval=1):\n \"\"\"\n Create Bloc object\n\n :param clock: A twisted time provider that implements :obj:`IReactorTime`. Typically main\n twisted reactor object.\n :param float timeout: Maximum number of seconds to wait for a client to hearbeat before\n removing it from the group and change it to SETTLING.\n :param float settle: Number of seconds to wait before settling. Ensures that all clients\n are settled for this much time before marking the group as SETTLED\n :param float interval: Internal interval to check all clients heartbeat status. Defaults to\n 1 second. Mostly, this doesn't need to be changed.\n \"\"\"\n self._group = SettlingGroup(clock, settle)\n self._clients = HeartbeatingClients(clock, timeout, interval, self._group.remove)\n super(Bloc, self).__init__()\n self.addService(self._clients)\n\n @app.route('/session', methods=['DELETE'])\n def cancel_session(self, request):\n client = extract_client(request)\n self._clients.remove(client)\n self._group.remove(client)\n return \"{}\".encode(\"utf-8\")\n\n @app.route('/index', methods=['GET'])\n def get_index(self, request):\n client = extract_client(request)\n self._clients.heartbeat(client)\n self._group.add(client)\n if self._group.settled:\n return json.dumps(\n {'status': 'SETTLED',\n 'index': self._group.index_of(client),\n 'total': len(self._group)}).encode(\"utf-8\")\n else:\n return json.dumps({'status': 'SETTLING'}).encode(\"utf-8\")\n","repo_name":"manishtomar/bloc","sub_path":"src/bloc/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5821,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"34432936676","text":"# 다음 큰 숫자 Level 3\n# 어떤 수 N(1≤N≤1,000,000) 이 주어졌을 때, N의 다음 큰 숫자는 다음과 같습니다.\n\n# N의 다음 큰 숫자는 N을 2진수로 바꾸었을 때의 1의 개수와 같은 개수로 이루어진 수입니다.\n# 1번째 조건을 만족하는 숫자들 중 N보다 큰 수 중에서 가장 작은 숫자를 찾아야 합니다.\n# 예를 들어, 78을 2진수로 바꾸면 1001110 이며, 78의 다음 큰 숫자는 83으로 2진수는 1010011 입니다.\n# N이 주어질 때, N의 다음 큰 숫자를 찾는 nextBigNumber 함수를 완성하세요.\n\ndef nextBigNumber(n):\n count = str(bin(n)).count('1')\n n += 1\n while count != str(bin(n)).count('1'):\n n += 1\n return n\n\n#아래 코드는 테스트를 위한 출력 코드입니다.\nprint(nextBigNumber(78))","repo_name":"Team-AiK/TT-Thinking-Training","sub_path":"Week05/groovypark/2_nextBigNumber.py","file_name":"2_nextBigNumber.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"23454941841","text":"import sys\nsys.setrecursionlimit(10**6)\nn, m = map(int, input().split())\n\nspace = []\nfor _ in range(n):\n space.append(list(map(int,input().split())))\nans =0\ncnt = 0\ntot_cnt = 0\ndef dfs(x, y):\n global cnt\n if(x <= -1 or x>=n or y<=-1 or y>= m):\n return False\n if(space[x][y] == 1):\n cnt += 1\n space[x][y] = 0\n # 상하좌우 재귀 호출\n dfs(x-1, y)\n dfs(x, y+1)\n dfs(x+1, y)\n dfs(x, y-1)\n return True\n return False\n\nfor i in range(n):\n for j in range(m):\n if(dfs(i, j) == True):\n tot_cnt += 1\n ans = max(cnt, ans)\n cnt = 0\nprint(tot_cnt)\nprint(ans)\n","repo_name":"sdm6410/algorithm-study","sub_path":"Shin/[BOJ]-1926.py","file_name":"[BOJ]-1926.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"21470601401","text":"import os\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nplt.style.use('seaborn')\r\n\r\n#Leemos.\r\ndef leer_archivo(nombre_archivo):\r\n with open(nombre_archivo, 'r') as archivo:\r\n lineas = archivo.readlines()\r\n valores = [abs(float(linea.strip())) for linea in lineas[-4:]]\r\n solapamiento_final = np.mean(valores)\r\n error = 3.0*np.std(valores)/(len(valores))\r\n temperatura = float(nombre_archivo.split('_T')[1][:-4])\r\n return solapamiento_final, temperatura, error\r\n\r\ndef graficar_solapamiento(carpeta):\r\n carpeta = os.path.join(os.path.dirname(__file__),carpeta)\r\n solapamientos = []\r\n temperaturas = []\r\n errores = []\r\n for archivo in os.listdir(carpeta):\r\n ruta_archivo = os.path.join(carpeta, archivo)\r\n if os.path.isfile(ruta_archivo):\r\n solapamiento_final, temperatura, error = leer_archivo(ruta_archivo)\r\n solapamientos.append(solapamiento_final)\r\n temperaturas.append(temperatura)\r\n errores.append(error)\r\n\r\n # Se coloca el punto con su barra de error.\r\n plt.errorbar(temperaturas, solapamientos, errores, marker='o', linestyle='None', color='black', capsize=3.0, capthick=2, markersize = 3)\r\n\r\n plt.vlines(temperaturas, 0, solapamientos, linestyle=(0, (1, 3)))\r\n plt.xlabel('Temperatura')\r\n plt.ylabel('Solapamiento Final (Promedio últimos 4 valores)')\r\n plt.title('Solapamiento Final frente a la Temperatura')\r\n plt.grid(True)\r\n\r\n #Se muestra la escala logarítmica, al aumentar las temperaturas en múltiplos de 2.\r\n plt.xscale('log')\r\n \r\n plt.savefig(\"Solapamientos_Frente_a_T.png\")\r\n plt.show()\r\n \r\n\r\ncarpeta_salida = 'Solapamientos'\r\ngraficar_solapamiento(carpeta_salida)","repo_name":"Kai16Quantum/FisicaComputacional","sub_path":"OpcionalHopfield/representa_solapamiento_funcion.py","file_name":"representa_solapamiento_funcion.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"24809593657","text":"instruments = (\n \"_system\",\n \"_general\",\n # \"_trigger\",\n # \"_sensitivity\",\n # \"_pitch\",\n # \"_decay\",\n # \"_sweep\",\n # \"_lforate\",\n # \"_lfodepth\",\n)\n\n\nmapping = {\n\n # 00 - int/ext\n \"_system/int_ext\":(\n (\"digital\", {\"channel\":0, \"function\": \"digital\", \"bool\":1})\n ),\n #02 - clock\n \"_system/timing_clock\":(\n (\"square_wave\", {\"channel\":14, \"function\": \"square_wave\", \"frequency\":40, \"duty\":50.0})\n ),\n\n #03 - master vol\n \"_system/master_volume\":(\n (\"square_wave\", {\"channel\":3, \"function\": \"square_wave\", \"frequency\":30000, \"duty\":50.0})\n ),\n\n #04 - kick\n \"_general/sound/bass_drum/bang\":(\n (\"signal\", {\"channel\":4, \"function\": \"digital\", \"bool\":1 })\n ),\n\n \"_general/sound/bass_drum/off\":(\n (\"signal\", {\"channel\":4, \"function\": \"digital\", \"bool\":0 })\n ),\n\n #05 - snare\n \"_general/sound/snare/bang\":(\n (\"signal\", {\"channel\":5, \"function\": \"digital\", \"bool\":1 })\n ),\n\n \"_general/sound/snare/off\":(\n (\"signal\", {\"channel\":5, \"function\": \"digital\", \"bool\":0 })\n ),\n\n #06 - hi hat\n \"_general/sound/hi_hat/bang\":(\n (\"signal\", {\"channel\":6, \"function\": \"digital\", \"bool\":1 })\n ),\n\n \"_general/sound/hi_hat/off\":(\n (\"signal\", {\"channel\":6, \"function\": \"digital\", \"bool\":0 })\n ),\n #07 - sensitivity\n \"_general/control_change/sensitivity\":(\n (\"signal\", {\"channel\":7, \"function\": \"square_wave\", \"frequency\":30000, \"duty cycle\":0, \"freq_min_max\":(1,1), \"duty_min_max\":(0,100), \"variable_key\":\"duty_cycle\"})\n ),\n \n #08 - pitch\n\n \"_general/control_change/pitch\":(\n (\"signal\", {\"channel\":8, \"function\": \"square_wave\", \"frequency\":30000, \"duty cycle\":0, \"freq_min_max\":(1,1), \"duty_min_max\":(0,100), \"variable_key\":\"duty_cycle\"})\n ),\n\n #09 - decay\n \"_general/control_change/decay\":(\n (\"signal\", {\"channel\":9, \"function\": \"square_wave\", \"frequency\":30000, \"duty cycle\":0, \"freq_min_max\":(1,1), \"duty_min_max\":(0,100), \"variable_key\":\"duty_cycle\"})\n ),\n\n #10 - sweep\n \"_general/control_change/sweep\":(\n (\"signal\", {\"channel\":10, \"function\": \"square_wave\", \"frequency\":30000, \"duty cycle\":0, \"freq_min_max\":(1,1), \"duty_min_max\":(0,100), \"variable_key\":\"duty_cycle\"})\n ),\n\n\n #11 - lfo rate\n \"_general/control_change/lfo_rate\":(\n (\"signal\", {\"channel\":11, \"function\": \"square_wave\", \"frequency\":30000, \"duty cycle\":0, \"freq_min_max\":(1,1), \"duty_min_max\":(0,100), \"variable_key\":\"duty_cycle\"})\n ),\n\n #12 - lfo depth\n \"_general/control_change/lfo_depth\":(\n (\"signal\", {\"channel\":12, \"function\": \"square_wave\", \"frequency\":30000, \"duty cycle\":0, \"freq_min_max\":(1,1), \"duty_min_max\":(0,100), \"variable_key\":\"duty_cycle\"})\n ),\n\n\n #14 - trig 1\n \"_general/sound/trigger_1/bang\":(\n (\"signal\", {\"channel\":14, \"function\": \"digital\", \"bool\":1 })\n ),\n\n \"_general/sound/trigger_1/off\":(\n (\"signal\", {\"channel\":14, \"function\": \"digital\", \"bool\":0 })\n ),\n\n # 16 - trig 2\n \"_general/sound/trigger_2/bang\":(\n (\"signal\", {\"channel\":16, \"function\": \"digital\", \"bool\":1 })\n ),\n\n \"_general/sound/trigger_2/off\":(\n (\"signal\", {\"channel\":16, \"function\": \"digital\", \"bool\":0 })\n ),\n\n #18 - trig 3\n \"_general/sound/trigger_3/bang\":(\n (\"signal\", {\"channel\":18, \"function\": \"digital\", \"bool\":1 })\n ),\n\n \"_general/sound/trigger_3/off\":(\n (\"signal\", {\"channel\":18, \"function\": \"digital\", \"bool\":0 })\n ),\n\n #20 - trig 4\n \"_general/sound/trigger_4/bang\":(\n (\"signal\", {\"channel\":20, \"function\": \"digital\", \"bool\":1 })\n ),\n\n \"_general/sound/trigger_4/off\":(\n (\"signal\", {\"channel\":20, \"function\": \"digital\", \"bool\":0 })\n ),\n}\n\n\n\n \n","repo_name":"andycavatorta/RBK","sub_path":"client/devices/Amdek/mapping.py","file_name":"mapping.py","file_ext":"py","file_size_in_byte":3751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"30851823234","text":"import pytest\r\nfrom python_9_2 import SingleList\r\nfrom python_9_2 import Node\r\n\r\ndef test_add():\r\n list = SingleList()\r\n assert list.head == None\r\n list.add(1)\r\n assert list.head.data == 1\r\n list.add(2)\r\n assert list.tail.data == 2\r\n\r\ndef test_remove_tail():\r\n list = SingleList()\r\n list.add(1)\r\n list.add(2)\r\n list.add(3)\r\n assert list.tail.data == 3\r\n assert list.remove_tail().data == 3\r\n assert list.tail.data == 2\r\n \r\ndef test_join():\r\n list1 = SingleList()\r\n list1.add(1)\r\n list1.add(2)\r\n list1.add(3)\r\n list2 = SingleList()\r\n list2.add(6)\r\n list2.add(5)\r\n list2.add(4)\r\n assert list1.tail.data == 3\r\n list1.join(list2)\r\n assert list1.tail.data == 4\r\n assert list2.head == None\r\n \r\ndef test_search():\r\n list1 = SingleList()\r\n list1.add(1)\r\n list1.add(2)\r\n list1.add(3)\r\n a = list1.search(4)\r\n assert a == None\r\n assert list1.search(2).data == 2\r\n \r\ndef test_find_min(): \r\n list1 = SingleList()\r\n assert list1.find_min() == None\r\n list1.add(1)\r\n list1.add(2)\r\n list1.add(3)\r\n assert list1.find_min().data == 1\r\n \r\ndef test_find_max():\r\n list1 = SingleList()\r\n assert list1.find_max() == None\r\n list1.add(1)\r\n list1.add(2)\r\n list1.add(3)\r\n assert list1.find_max().data == 3\r\n\r\ndef test_reverse(): \r\n list1 = SingleList()\r\n list1.add(1)\r\n list1.add(2)\r\n list1.add(3)\r\n assert list1.head.data == 1 and list1.tail.data == 3\r\n list1.reverse()\r\n assert list1.head.data == 3 and list1.tail.data == 1\r\n\r\nif __name__ == \"__main__\":\r\n pytest.main()\r\n","repo_name":"Armillion/Exercises","sub_path":"Python/python-cwiczenia/test_singlelist.py","file_name":"test_singlelist.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"5707392469","text":"import requests\n# 위도, 경도 url : https://www.latlong.net/\n# 현재는 OnecallAPI가 유료로 바뀌어 사용하려면 구독을 해야함.\n\nOWN_Endpoint = \"https://api.openweathermap.org/data/3.0/onecall\"\napi_key = \"your_api_key\"\n\nweather_params = {\n \"lat\" : 37.484001,\n \"lon\" : 126.929776,\n \"appid\" : api_key,\n}\n\nresp = requests.get(OWN_Endpoint, params = weather_params)\n\nprint(resp.status_code)\nprint(resp.text)","repo_name":"dja1369/Udemy_python","sub_path":"day-35/weather_alert/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"30006210811","text":"import json\n\n\ndef getTimes():\n times = []\n with open(\"data.json\", 'r') as json_obj:\n data = dict(json.load(json_obj))\n times = list(data.values())\n return times\n\n\ndef getDict():\n with open(\"data.json\", 'r') as json_obj:\n data = dict(json.load(json_obj))\n return data\n\n\ndef get_interrupt_times():\n start_time = []\n for i in getTimes():\n times = i.split(\",\")\n if len(times) > 1:\n for j in times:\n temp_time = j.split('-')\n start_time.append(temp_time[0])\n else:\n temp_time = times[0].split('-')\n start_time.append(temp_time[0])\n return list(set(start_time))\n\n\ndef get_groups_by_time(time):\n groups = []\n dict_ = dict(getDict())\n for grp, t in dict_.items():\n times = t.split(\",\")\n if len(times) > 1:\n for j in times:\n temp_time = j.split('-')\n start_time = temp_time[0]\n if start_time == time:\n groups.append(grp)\n else:\n temp_time = times[0].split('-')\n start_time = temp_time[0]\n if start_time == time:\n groups.append(grp)\n return groups\n\n\nif __name__ == \"__main__\":\n times = get_interrupt_times()\n groups = get_groups_by_time('6:00PM')\n print(groups)\n","repo_name":"imshaaz21/powercut_bot","sub_path":"controller/json_controller.py","file_name":"json_controller.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"16772422415","text":"#!/usr/bin/env python\nimport subprocess\nimport sys\nfrom time import sleep\n\nfrom dnslib import QTYPE, RR, dns\nfrom dnslib.proxy import ProxyResolver\nfrom dnslib.server import DNSServer\nfrom dnslib.server import DNSRecord\n\nclass Resolver(ProxyResolver):\n # Do nothing init, but defined so it doesn't call the super class'\n def __init__(self):\n pass\n\n # Resolve\n def resolve(self, request, handler):\n # Build a request reply.\n reply = request.reply()\n # If it is of type A, IPv4:\n if request.q.qtype == QTYPE.A:\n addr = \"-4\"\n ip_cls = dns.A # Class to wrap the ip string with.\n # If it is of type AAAA, IPv6:\n elif request.q.qtype == QTYPE.AAAA:\n addr = \"-6\"\n ip_cls = dns.AAAA # Class to wrap the ip string with.\n else:\n # Return nothing.\n return reply\n\n # Strip trailing period.\n host = str(request.q.qname).rstrip(\".\")\n \n if not host.endswith(\".local\"):\n a = DNSRecord.parse(DNSRecord.question(host).send(\"8.8.8.8\", 53))\n for rr in a.rr:\n if rr.rtype == request.q.qtype:\n reply.add_answer(rr)\n return reply\n\n try:\n # Use avahi-resolve to determine the .local host IP address.\n result = subprocess.check_output(\n [\"avahi-resolve\", \"--name\", addr, host], timeout=1)\n # Parse output.\n [host, ip] = result.decode(\"UTF-8\").strip(\"\\n\").split(\"\\t\")\n # Build a result and add the answer to the reply.\n rr = RR(\n rname=request.q.qname,\n rtype=request.q.qtype,\n rdata=ip_cls(ip),\n ttl=300,\n )\n reply.add_answer(rr)\n except subprocess.TimeoutExpired:\n # Time out == host not found.\n pass\n except BaseException:\n raise\n # Return the reply.\n return reply\n\n\n# Get a resolver instance\nresolver = Resolver()\n# Create a local server on port 5053 listening on TCP and UDP.\nservers = [\n DNSServer(resolver=resolver, port=5053, address='localhost', tcp=True),\n DNSServer(resolver=resolver, port=5053, address='localhost', tcp=False),\n]\n\n# If this file is called\nif __name__ == '__main__':\n for s in servers:\n s.start_thread()\n try:\n while True:\n # Twiddle thumbs.\n sleep(10)\n # Flush stderr and stdout.\n sys.stderr.flush()\n sys.stdout.flush()\n except KeyboardInterrupt:\n pass\n finally:\n for s in servers:\n s.stop()\n","repo_name":"dapperfu/python_mDNServer","sub_path":"mdnserver.py","file_name":"mdnserver.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"13044375458","text":"\r\n\r\n# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\nMaster's Degree Final Project\r\nTheme: Clinical Data Mining and Classification\r\nPython version: 3.7.8\r\n\r\n@author: Adara Nogueira\r\n\"\"\"\r\n\r\n#==============================================================================#\r\n#==============================================================================#\r\n# # MODULES # #\r\n#==============================================================================#\r\n#==============================================================================#\r\n\r\nimport numpy as np\r\n\r\nimport load_data\r\nimport split_data\r\n\r\n#==============================================================================#\r\n#==============================================================================#\r\n# # METHODS # #\r\n#==============================================================================#\r\n#==============================================================================#\r\n\r\n#.................................. MAIN METHOD ...............................#\r\n\r\ndef calculate(name, confusion_matrix):\r\n \"\"\"\r\n Calculate evaluation metrics given a confusion matrix\r\n\r\n Arguments:\r\n confusion_matrix -- confusion matrix\r\n \r\n Returns:\r\n evaluation -- evaluation metrics calculated\r\n \"\"\"\r\n\r\n # Count true positive, false positive, true negative, and false negative\r\n tn, fp, fn, tp = count_pos_neg(confusion_matrix)\r\n\r\n # All evaluation metrics\r\n evaluation = {\"name\":name,\r\n \"accuracy\":accuracy(confusion_matrix),\r\n \"fnr\":fnr(fn, tp),\r\n \"tnr\":tnr(tn, fp),\r\n \"tpr\":tpr(tp, fn),\r\n \"fpr\":fpr(fp, tn),\r\n \"error\":error(confusion_matrix),\r\n \"precision\":precision(tp, fp),\r\n \"f_measure\":f_measure(precision(tp, fp), tpr(tp, fn)),\r\n \"confusion_matrix\":confusion_matrix,\r\n \"tn\":tn,\r\n \"fp\":fp,\r\n \"fn\":fn,\r\n \"tp\":tp}\r\n return evaluation\r\n\r\n#................................ NEGATIVE RATES ..............................#\r\n\r\ndef tnr(tn, fp):\r\n \"\"\"\r\n True negative rate (specificity)\r\n\r\n Arguments:\r\n fp -- number of false positives\r\n tn -- number of true negatives\r\n \r\n Returns:\r\n tnr\r\n \"\"\"\r\n \r\n return tn / (tn + fp)\r\n\r\ndef fnr(fn, tp):\r\n \"\"\"\r\n False negative rate (miss rate)\r\n\r\n Arguments:\r\n tp -- number of true positives\r\n fn -- number of false negatives\r\n \r\n Returns:\r\n fnr\r\n \"\"\"\r\n \r\n return fn / (fn + tp) # 1 - tpr\r\n\r\n#................................ POSITIVE RATES ..............................#\r\n\r\ndef tpr(tp, fn):\r\n \"\"\"\r\n True positive rate (hit rate or recall)\r\n\r\n Arguments:\r\n tp -- number of true positives\r\n fn -- number of false negatives\r\n \r\n Returns:\r\n tpr\r\n \"\"\"\r\n \r\n return tp / (tp + fn)\r\n\r\ndef fpr(fp, tn):\r\n \"\"\"\r\n False positive rate (false alarm rate)\r\n\r\n Arguments:\r\n fp -- number of false positives\r\n tn -- number of true negatives\r\n \r\n Returns:\r\n fpr\r\n \"\"\"\r\n \r\n return fp / (fp + tn)\r\n\r\n#............................... CONFUSION MATRIX .............................#\r\n\r\ndef map_label_index(y):\r\n \"\"\"\r\n Map class label to index\r\n Make all (0,0) position in the confusion matrix be non-cancerous (where applicable)\r\n (true negative)\r\n\r\n Arguments:\r\n y -- class label vector\r\n \r\n Returns:\r\n dictionary where the key is a class label and the value is an index\r\n \"\"\"\r\n \r\n unique = np.unique(y)\r\n if unique[0] == 'Cancer':\r\n # Dataset: Ovarian\r\n y = unique[::-1]\r\n elif len(unique) == 5:\r\n # Dataset: Lung\r\n y = np.array([2.0, 1.0, 3.0, 4.0, 5.0])\r\n else:\r\n # Dataset: all others\r\n y = unique\r\n return dict(zip(y, range(len(y))))\r\n \r\ndef initiate_confusion_matrix(y):\r\n \"\"\"\r\n Apply the feature selection technique to the data\r\n\r\n Arguments:\r\n y -- class label vector\r\n \r\n Returns:\r\n confusion matrix initialized with all values set to zero\r\n \"\"\"\r\n\r\n number_of_classes = len(np.unique(y))\r\n return np.zeros((number_of_classes, number_of_classes)), map_label_index(y)\r\n\r\ndef count_pos_neg(confusion_matrix):\r\n \"\"\"\r\n Calculate the number of true positive, false positive, true negative, and false negative\r\n\r\n Arguments:\r\n confusion_matrix -- confusion matrix\r\n \r\n Returns:\r\n tn -- number of negative instances classified as negative\r\n fp -- number of negative instances classified as positive (error)\r\n fn -- number of positive instances classified as negative (error)\r\n tp -- number of positive instances classified as positive\r\n \"\"\"\r\n\r\n tn = np.sum(confusion_matrix[:1,0]) # (0,0)\r\n fp = np.sum(confusion_matrix[:1,1:]) # (0,1)\r\n fn = np.sum(confusion_matrix[1:,0]) # (1,0)\r\n tp = np.sum(confusion_matrix[1:,1:]) # (1,1)\r\n return tn, fp, fn, tp\r\n\r\n#................................... OTHERS ...................................#\r\n\r\ndef accuracy(confusion_matrix):\r\n \"\"\"\r\n Calculate the accuracy of a classifier\r\n\r\n Arguments:\r\n confusion_matrix -- confusion matrix\r\n \r\n Returns:\r\n accuracy\r\n \"\"\"\r\n\r\n # Number of correct classifications\r\n diagonal = sum(confusion_matrix.diagonal())\r\n\r\n # Total number of classifications\r\n total = confusion_matrix.sum()\r\n\r\n # Compute accuracy\r\n return diagonal/total\r\n\r\ndef error(confusion_matrix):\r\n \"\"\"\r\n Calculate the error rate\r\n\r\n Arguments:\r\n confusion_matrix -- confusion matrix\r\n \r\n Returns:\r\n error\r\n \"\"\"\r\n\r\n # Compute error\r\n return 1 - accuracy(confusion_matrix)\r\n\r\ndef precision(tp, fp):\r\n \"\"\"\r\n Calculate the precision (proportion of positive instances that actually are postive)\r\n\r\n Arguments:\r\n tp -- number of true positives\r\n fp -- number of false positives\r\n \r\n Returns:\r\n precision\r\n \"\"\"\r\n\r\n # Compute precision\r\n return tp / (tp + fp)\r\n\r\ndef f_measure(precision, recall):\r\n \"\"\"\r\n The F-measure is the harmonic mean of precision and recall\r\n\r\n Arguments:\r\n precision\r\n recall\r\n \r\n Returns:\r\n F-measure\r\n \"\"\"\r\n\r\n # Compute F-measure\r\n return 2 / ((1/precision) + (1/recall))\r\n\r\nif __name__ == \"__main__\":\r\n # Load data\r\n files_names = load_data.data_files_names\r\n datas, names = load_data.apply(files_names)\r\n \r\n # Go through all datasets\r\n for d, (data, data_name) in enumerate(zip(datas, names)):\r\n print(\">> Dataset: \" + str(data_name) + \" <<\\n\")\r\n \r\n # Split the dataset into features and class\r\n _, y = split_data.features_class_split(data)\r\n\r\n mapping = map_label_index(y)\r\n\r\n print(\"y\", np.unique(y))\r\n print(\"mapping\", mapping, \"\\n\")\r\n","repo_name":"adaranogueira/cancer-diagnosis-ml","sub_path":"evaluation_metrics.py","file_name":"evaluation_metrics.py","file_ext":"py","file_size_in_byte":6962,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"34776595106","text":"from PIL import Image\nimport face_recognition\nimport numpy\nimport os\n\ndef find_faces(image, pictureName):\n # Load the jpg file into a numpy array\n #image = face_recognition.load_image_file(\"queue/\" + temporary)\n\n #os.remove(\"queue/\" + temporary)\n\n\n # Find all the faces in the image using a pre-trained convolutional neural network.\n # This method is more accurate than the default HOG model, but it's slower\n # unless you have an nvidia GPU and dlib compiled with CUDA extensions. But if you do,\n # this will use GPU acceleration and perform well.\n # See also: find_faces_in_picture.py\n\n print(\"Scanning picture....\")\n face_locations = face_recognition.face_locations(image, number_of_times_to_upsample=0, model=\"cnn\")\n\n rotation = 0\n\n if len(face_locations) == 0:\n print(\"No face found, rotating picture\")\n print(\"Scanning picture....\")\n fullpic = Image.fromarray(image)\n fullpic = fullpic.rotate(90)\n rotation += 90\n pix = numpy.array(fullpic)\n face_locations = face_recognition.face_locations(pix, number_of_times_to_upsample=0, model=\"cnn\")\n\n if len(face_locations) == 0:\n print(\"No face found, rotating picture\")\n print(\"Scanning picture....\")\n fullpic = Image.fromarray(image)\n fullpic = fullpic.rotate(90)\n rotation += 90\n pix = numpy.array(fullpic)\n face_locations = face_recognition.face_locations(pix, number_of_times_to_upsample=0, model=\"cnn\")\n\n if len(face_locations) == 0:\n print(\"No face found, rotating picture\")\n print(\"Scanning picture....\")\n fullpic = Image.fromarray(image)\n fullpic = fullpic.rotate(90)\n rotation += 90\n pix = numpy.array(fullpic)\n face_locations = face_recognition.face_locations(pix, number_of_times_to_upsample=0, model=\"cnn\")\n\n\n\n print(\"Found {} face(s) in this photograph.\".format(len(face_locations)))\n\n if len(face_locations) > 1:\n print(\"found more than one face. Cannot save it\")\n return\n\n for face_location in face_locations:\n\n # Print the location of each face in this image\n top, right, bottom, left = face_location\n\n # You can access the actual face itself like this:\n face_image = image[top:bottom, left:right]\n pil_image = Image.fromarray(face_image)\n print(\"Rotation {}\".format(rotation))\n pil_image = pil_image.rotate(rotation)\n\n splittedPictureName = str.split(pictureName, '.')\n\n splittedPictureName.remove(splittedPictureName[len(splittedPictureName) - 1])\n\n username = str.join('.', splittedPictureName)\n\n print(\"Le nom d'utilisateur : \")\n print(username)\n\n if not os.path.exists(\"pictures/\" + username):\n os.mkdir(\"pictures/\" + username)\n\n\n files = os.listdir(\"pictures/\" + username)\n\n\n pil_image.save(\"pictures/\" + username + '/' + str(len(files) + 1) + pictureName)\n\n\n","repo_name":"psyycker/face_recognition_api","sub_path":"opencv/find_faces_in_picture_cnn.py","file_name":"find_faces_in_picture_cnn.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14215216866","text":"from celery import shared_task\nfrom enrollments.models import Enrollment, EnrollmentStatus\nfrom datetime import datetime, timedelta\n\n\n@shared_task\ndef auto_delete_pending_enrollment():\n \"\"\"Delete pending enrollments after a day without payment\"\"\"\n yesterday = datetime.now() - timedelta(days=1)\n enrollments = Enrollment.objects.filter(\n status=EnrollmentStatus.PENDING, created_at__lte=yesterday\n )\n enrollments.delete()\n return f\"{enrollments.count()} pending enrollments deleted\"\n","repo_name":"mohamad-liyaghi/AcademyMaster","sub_path":"backend/apps/enrollments/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"29"} +{"seq_id":"3701545550","text":"import re\nimport datetime\nfrom bs4 import BeautifulSoup\nfrom logging import getLogger, basicConfig, DEBUG\nfrom urllib.parse import urljoin\nfrom urllib.request import Request, urlopen\nfrom feedgen.feed import FeedGenerator\n\n# Constants\nfakeauthor = {'name': 'FGO Gamepress', 'email': 'contact@gamepress.gg', 'uri': 'https://gamepress.gg'}\nbaseurl = 'https://gamepress.gg'\ntargeturl = baseurl + '/c/fategrand-order'\nlogourl = 'https://gamepress.gg/grandorder/sites/grandorder/files/fgo-icon.jpg'\nfalseagent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246'\nrequest = Request('https://gamepress.gg/c/fategrand-order')\nrequest.add_header('User-Agent', falseagent)\nlog = getLogger('FGO-Feed-Generator')\n# log.setLevel(DEBUG) # uncomment to get DEBUG logs\nbasicConfig()\n\nclass NoFeedTitleError(RuntimeError): pass\nclass NoFeedIDError(RuntimeError): pass\nclass NoFeedDateError(RuntimeError): pass\n\nclass FeedItem:\n def __init__(self, item):\n candidate_titles = item.find_all('div', 'feed-item-title')\n\n if len(candidate_titles) <= 0:\n raise NoFeedTitleError('Unable to find title for a feed item.')\n\n self.title = candidate_titles[0].a.get_text()\n log.debug('Currently working on: \\\"%s\\\"', self.title)\n\n path = candidate_titles[0].a['href']\n self.href = urljoin(baseurl, path)\n log.debug('\\\"%s\\\" URL: %s', self.title, self.href)\n\n candidate_id = re.search(r'(\\d+)', candidate_titles[0].a['href'])\n if candidate_id == None:\n raise NoFeedIDError('Unable to find ID for a feed item.')\n\n self.id = candidate_id[0]\n log.debug('\\\"%s\\\" ID: %s', self.title, self.id)\n\n candidate_lang = re.search(r'(\\d+)', candidate_titles[0].a['hreflang'])\n if candidate_lang == None:\n self.lang = 'en'\n else:\n self.lang = candidate_lang[0]\n log.debug('\\\"%s\\\" Language: %s', self.title, self.lang)\n\n candidate_images = item.find_all('div', 'feed-item-right')\n self.img = ''\n if len(candidate_images) >= 0:\n self.img = urljoin(baseurl, candidate_images[0].img['src'])\n log.debug('\\\"%s\\\" Image: %s', self.title, self.img)\n\n article_request = Request(self.href)\n article_request.add_header('User-Agent', falseagent)\n with urlopen(article_request) as response:\n # special case: if the link leads to a gamepress login page, we withdraw\n if '/cas/login' in response.url:\n log.debug('\\\"%s\\\" Login page special case triggered. Trying special case parsing', self.title)\n likely_match = re.search('\\/sites\\/default\\/files\\/styles\\/600x315\\/public\\/(\\d+)', candidate_images[0].img['src'])\n if likely_match == None:\n raise NoFeedDateError('Unable to find feed date, variant 3.1')\n\n self.date = datetime.datetime.strptime(likely_match[1], '%Y%m%d')\n self.authors = [fakeauthor]\n return\n\n soup = BeautifulSoup(response.read().decode(), features='lxml')\n date_candidates = soup.find_all('div', 'last-updated-date')\n\n if len(date_candidates) <= 0:\n # special case: even more learning with manga. images are usually labelled with their dates\n log.debug('\\\"%s\\\" No date found. Trying special case parsing', self.title)\n content_body = soup.find(id='block-gamepressbase-content')\n if content_body == None:\n raise NoFeedDateError('Unable to find feed date, variant 1')\n\n probable_candidate = content_body.find('img').find_next_sibling('img')\n if probable_candidate == None:\n raise NoFeedDateError('Unable to find feed date, variant 2')\n\n likely_match = re.search('\\/grandorder\\/sites\\/grandorder\\/files\\/(\\d+-\\d+)', probable_candidate['src'] )\n if likely_match == None:\n raise NoFeedDateError('Unable to find feed date, variant 3')\n\n self.date = datetime.datetime.strptime(likely_match[1], '%Y-%m')\n log.debug('\\\"%s\\\" Guessed Inaccurate Date: %s', self.title, self.date)\n else:\n self.date = datetime.datetime.strptime(date_candidates[0].time['datetime'], '%Y-%m-%dT%H:%M:%S')\n log.debug('\\\"%s\\\" Date: %s', self.title, self.date)\n\n author_candidates = soup.find_all('div', 'article-credit-top')\n self.authors = []\n if len(author_candidates) > 0:\n for author in author_candidates[0].find_all('a'):\n self.authors.append({'name': author.get_text(), 'uri': author['href'], 'email': fakeauthor['email']})\n else:\n self.authors = [fakeauthor]\n log.debug('\\\"%s\\\" Authors: %s', self.title, self.authors)\n\n def generate_feedentry(self, fg):\n fe = fg.add_entry()\n\n fe.id(self.href)\n fe.title(self.title)\n fe.content(content=''.format(self.img), type='html')\n fe.link(href=self.href, hreflang=self.lang)\n fe.updated(self.date.astimezone(tz=None))\n fe.author(self.authors)\n\n return fe\n\nlog.debug('Opening connection to %s', targeturl)\nwith urlopen(request) as response:\n log.debug('Feeding page into BeautifulSoup')\n soup = BeautifulSoup(response.read().decode(), features='lxml')\n\n log.debug('Getting all items in feed-item-container')\n items = soup.find_all('div', class_='feed-item-container')\n fg = FeedGenerator()\n fg.id(targeturl)\n fg.link(href=targeturl, rel='alternate')\n fg.title('Fate/GO Gamepress')\n fg.subtitle('Fate/Grand Order gamepress feed')\n fg.logo(logourl)\n fg.language('en')\n\n for item in items:\n fi = FeedItem(item)\n log.debug('\\\"%s\\\": Generating feed entry', fi.title)\n fi.generate_feedentry(fg)\n\n log.debug('Finishing up, generating atom.xml')\n fg.atom_file('atom.xml')\n","repo_name":"jameshi16/fgo-gamepress-feed-generator","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":5614,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"9861863364","text":"import argparse\nimport sys\nfrom pathlib import Path\n\nparser = argparse.ArgumentParser(prog=\"ccwc\",description=\"Counts number of bytes,characters,words and lines\",epilog=\"Thanks for using ccwc\")\n\nparser.add_argument(\"files\",nargs=\"*\",default=sys.stdin, type=argparse.FileType('r'))\n\nparser.add_argument(\"-c\",\"--bytes\",action=\"store_true\")\n\nparser.add_argument(\"-w\",\"--words\",action=\"store_true\")\n\nparser.add_argument(\"-m\",\"--chars\",action=\"store_true\")\n\nparser.add_argument(\"-l\",\"--lines\",action=\"store_true\")\n\nargs = parser.parse_args()\n\n\ndef printResult(content,file_name=\"\"):\n chars = words = lines =bytes_count = 0\n for line in content:\n lines += 1\n words += len(line.split())\n chars += len(line)+1\n bytes_count += len(line.encode('utf-8')) + len(\"\\n\".encode('utf-8'))\n\n res = [\" \"]\n if args.bytes:\n res.append(bytes_count)\n if args.words:\n res.append(words)\n if args.chars:\n res.append(chars)\n if args.lines:\n res.append(lines)\n res.append(file_name)\n if len(res) > 2:\n for i in res:\n print(i, end=\" \")\n print()\n else:\n print(lines,words,bytes_count,file_name)\n\nif args.files:\n if(type(args.files) is list):\n for file in args.files:\n target_file = Path(file.name)\n if not target_file.exists():\n print(\"The target file does not exists\")\n raise SystemExit(1)\n\n if target_file.is_dir():\n print(\"The target file is a directory\")\n raise SystemExit(1) \n content = open(str(target_file), 'r')\n printResult(content,file.name)\n else:\n # print(files)\n content = args.files.read().splitlines()\n printResult(content)\n \n\n \n\n \n\n\n\n \n\n\n ","repo_name":"rnharshee/wc-cli","sub_path":"wc.py","file_name":"wc.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"24280766558","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n# Created by AndresD at 4/01/19\n\nFeatures:\n + Add structure to ODM2 database to fit colombian government agencies data\n\n@author: Andres Felipe Duque Perez\nEmail: andresfduque@gmail.com\n\"\"\"\n\nimport os\nimport sys\nimport uuid\nimport argparse\nimport pandas as pd\nfrom odm2api import models\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nimport numpy as np\nfrom datetime import date\nimport os, calendar, pickle, time\n\n\n# ======================================================================================================================\n# handles customizing the error messages from ArgParse\n# ======================================================================================================================\nclass MyParser(argparse.ArgumentParser):\n def error(self, message):\n sys.stderr.write(\"------------------------------\\n\")\n sys.stderr.write('error: %s\\n' % message)\n sys.stderr.write(\"------------------------------\\n\")\n self.print_help()\n sys.exit(2)\n\n\n# handle argument parsing\ninfo = \"A simple script that loads up ODM2COL basic structure into the ODM2 database\"\nparser = MyParser(description=info, add_help=True)\nparser.add_argument(\n help=\"Format: {engine}+{driver}://{user}:{pass}@{address}/{db}\\n\"\n \"mysql+pymysql://ODM:odm@localhost/odm2\\n\"\n \"mssql+pyodbc://ODM:123@localhost/odm2\\n\"\n \"postgresql+psycopg2://postgres:postgres@localhost/odm2col\\n\"\n \"sqlite+pysqlite:///path/to/file\",\n default=True, type=str, dest='conn_string')\nparser.add_argument('-d', '--debug', help=\"Debugging program without committing anything to remote database\",\n action=\"store_true\")\nargs = parser.parse_args()\n\n\n# ======================================================================================================================\n# Start database session\n# ======================================================================================================================\ndef start_db_session(connection_string):\n # Bind the engine to the metadata of the Base class so that the declarative can be accessed through a DBSession\n # instance\n try:\n engine = create_engine(connection_string, encoding='unicode_escape')\n models.setSchema(engine)\n db_session = sessionmaker(bind=engine)()\n # A DBSession() instance establishes all conversations with the database and represents a \"staging zone\" for all\n # the objects loaded into the database session object. Any change made against the objects in the session won't\n # be persisted into the database until you call session.commit(). If you're not happy about the changes, you can\n # revert all of them back to the last commit by calling session.rollback()\n except Exception as e:\n print(e)\n sys.exit(0)\n return db_session\n\n\n\n\n\n# ======================================================================================================================\n# Script Begin\n# ======================================================================================================================\nconn_string = args.conn_string\nsession = start_db_session(conn_string)\n\nprint(\"Loading ODM2COL structure using connection string: %s\" % conn_string)\n\nodm2_structure = os.path.dirname(os.getcwd()) + '/data/odm2col_structure/'\n\n\ndef ideam_txt_to_csv(source_folder, destiny_folder):\n # start timing\n startTime = time.time()\n\n # # Get first header line\n # f = open('/media/andres/ADATA AFDP/GE/GE/BD Hidrología/Caudal/00-Originales/TODAS IDEAM/ANDRESD1.txt', 'r')\n # first_line = f.readline()\n # first_line = ' '.join(first_line.split())\n # f.close()\n first_line = 'I D E A M - INSTITUTO DE HIDROLOGIA, METEOROLOGIA Y ESTUDIOS AMBIENTALES'\n\n # Define files to be read\n source_file_list = os.listdir(source_folder)\n source_file_list = [source_folder + i for i in source_file_list]\n\n # Create dictionary were data is going to be stored temporally]\n station_db = {}\n\n # Read each text file where data is stored and read each station header\n for files in source_file_list:\n f = open(files, 'r')\n i = 0\n code = 0\n years = [] # register period vector (in years)\n for line in f:\n\n # Get station basic parameters\n if i == 4:\n year = int(line[59:64]) # register year\n code1 = int(line[104:113]) # station code\n name = line[114:] # station name\n name = ' '.join(name.split())\n years.append(year)\n\n if i == 6: # get latitude and \"departamento\"\n lat = int(line[15:17]) + int(line[17:19]) / 60.\n lat_dir = line[20:22] # latitude direction (North [N]; South [S])\n tipo = line[48:51]\n departamento = line[80:104]\n departamento = ' '.join(departamento.split())\n\n if lat_dir == 'S': # correct value by latitude direction\n lat = -lat\n\n if i == 7: # get longitude and \"municipio\"\n lon = int(line[15:17]) + int(line[17:19]) / 60.\n lon = -lon\n municipio = line[80:104]\n municipio = ' '.join(municipio.split())\n\n if i == 8: # get elevation and river name\n elevation = int(line[15:20])\n river_name = line[80:104]\n river_name = ' '.join(river_name.split())\n\n if i >= 8:\n # Create station in dictionary and add parameters\n if code != code1:\n station_db[code1] = {'nombre': name, 'lat-lon': [lat, lon], 'municipio': municipio,\n 'departamento': departamento, 'elevacion': elevation, 'corriente': river_name,\n 'registros': [year], 'tipo': tipo, 'codigo': code1}\n\n # add register period vector to station\n if code != 0:\n station_db[code]['registros'] = years[:-1]\n\n # add empty timeseries - to be filled later in this script\n first_year = station_db[code]['registros'][0]\n last_year = station_db[code]['registros'][-1]\n start_date = date(first_year, 1, 1)\n end_date = date(last_year, 12, 31)\n date_range_daily = pd.date_range(start_date, end_date)\n date_range_monthly = pd.date_range(start_date, end_date, freq='M')\n data_daily = np.zeros([len(date_range_daily)])\n data_daily[:] = np.nan\n data_max = np.zeros([len(date_range_monthly)])\n data_max[:] = np.nan\n data_min = np.zeros([len(date_range_monthly)])\n data_min[:] = np.nan\n station_timeseries_daily = pd.TimeSeries(data_daily, date_range_daily)\n station_timeseries_max = pd.TimeSeries(data_max, date_range_monthly)\n station_timeseries_min = pd.TimeSeries(data_min, date_range_monthly)\n station_db[code]['caudales_diarios'] = station_timeseries_daily\n station_db[code]['maximos_mensuales'] = station_timeseries_max\n station_db[code]['minimos_mensuales'] = station_timeseries_min\n\n years = [year] # register period vector\n\n code = code1 # code pass for stations change\n\n # check if line is header (new year of data)\n if ' '.join(line.split()) == first_line:\n i = 0\n\n i += 1 # count\n\n # add data to the last station\n station_db[code]['registros'] = years # period of register from last station\n first_year = station_db[code]['registros'][0]\n last_year = station_db[code]['registros'][-1]\n start_date = date(first_year, 1, 1)\n end_date = date(last_year, 12, 31)\n date_range_daily = pd.date_range(start_date, end_date)\n date_range_monthly = pd.date_range(start_date, end_date, freq='M')\n data_daily = np.zeros([len(date_range_daily)])\n data_daily[:] = np.nan\n data_max = np.zeros([len(date_range_monthly)])\n data_max[:] = np.nan\n data_min = np.zeros([len(date_range_monthly)])\n data_min[:] = np.nan\n station_timeseries_daily = pd.TimeSeries(data_daily, date_range_daily)\n station_timeseries_max = pd.TimeSeries(data_max, date_range_monthly)\n station_timeseries_min = pd.TimeSeries(data_min, date_range_monthly)\n station_db[code]['caudales_diarios'] = station_timeseries_daily\n station_db[code]['maximos_mensuales'] = station_timeseries_max\n station_db[code]['minimos_mensuales'] = station_timeseries_min\n\n f.close()\n\n # Read each text file where data is stored and read discharges data\n for files in source_file_list:\n f = open(files, 'r')\n i = 0\n for line in f:\n\n # Get station basic parameters\n if i == 4:\n year = int(line[59:64]) # register year\n code = int(line[104:113]) # station code\n\n j = 1\n\n if 14 <= i <= 44:\n day = int(line[11:13])\n day_line = split_ideam_line(line) # month line of daily data\n\n # check leap year\n leap_year = calendar.isleap(year)\n if not leap_year:\n if day <= 28:\n station_db[code]['caudales_diarios'][date(year, 2, day)] = day_line[1]\n elif day <= 29:\n station_db[code]['caudales_diarios'][date(year, 2, day)] = day_line[1]\n\n if day <= 30:\n station_db[code]['caudales_diarios'][date(year, 1, day)] = day_line[0]\n station_db[code]['caudales_diarios'][date(year, 3, day)] = day_line[2]\n station_db[code]['caudales_diarios'][date(year, 4, day)] = day_line[3]\n station_db[code]['caudales_diarios'][date(year, 5, day)] = day_line[4]\n station_db[code]['caudales_diarios'][date(year, 6, day)] = day_line[5]\n station_db[code]['caudales_diarios'][date(year, 7, day)] = day_line[6]\n station_db[code]['caudales_diarios'][date(year, 8, day)] = day_line[7]\n station_db[code]['caudales_diarios'][date(year, 9, day)] = day_line[8]\n station_db[code]['caudales_diarios'][date(year, 10, day)] = day_line[9]\n station_db[code]['caudales_diarios'][date(year, 11, day)] = day_line[10]\n station_db[code]['caudales_diarios'][date(year, 12, day)] = day_line[11]\n else:\n station_db[code]['caudales_diarios'][date(year, 1, day)] = day_line[0]\n station_db[code]['caudales_diarios'][date(year, 3, day)] = day_line[2]\n station_db[code]['caudales_diarios'][date(year, 5, day)] = day_line[4]\n station_db[code]['caudales_diarios'][date(year, 7, day)] = day_line[6]\n station_db[code]['caudales_diarios'][date(year, 8, day)] = day_line[7]\n station_db[code]['caudales_diarios'][date(year, 10, day)] = day_line[9]\n station_db[code]['caudales_diarios'][date(year, 12, day)] = day_line[11]\n\n if 47 == i: # line where max discharge data is supposed to be located\n\n if line[0:3] == 'MAX': # if \"MAXIMO ABSOLUTO\" exists\n month_line = split_ideam_line(line) # max daily instantaneous month flow\n station_db[code]['maximos_mensuales'][date(year, 1, calendar.monthrange(year, 1)[1])] = month_line[0]\n station_db[code]['maximos_mensuales'][date(year, 2, calendar.monthrange(year, 2)[1])] = month_line[1]\n station_db[code]['maximos_mensuales'][date(year, 3, calendar.monthrange(year, 3)[1])] = month_line[2]\n station_db[code]['maximos_mensuales'][date(year, 4, calendar.monthrange(year, 4)[1])] = month_line[3]\n station_db[code]['maximos_mensuales'][date(year, 5, calendar.monthrange(year, 5)[1])] = month_line[4]\n station_db[code]['maximos_mensuales'][date(year, 6, calendar.monthrange(year, 6)[1])] = month_line[5]\n station_db[code]['maximos_mensuales'][date(year, 7, calendar.monthrange(year, 7)[1])] = month_line[6]\n station_db[code]['maximos_mensuales'][date(year, 8, calendar.monthrange(year, 8)[1])] = month_line[7]\n station_db[code]['maximos_mensuales'][date(year, 9, calendar.monthrange(year, 9)[1])] = month_line[8]\n station_db[code]['maximos_mensuales'][date(year, 10, calendar.monthrange(year, 10)[1])] = month_line[9]\n station_db[code]['maximos_mensuales'][date(year, 11, calendar.monthrange(year, 11)[1])] = month_line[10]\n station_db[code]['maximos_mensuales'][date(year, 12, calendar.monthrange(year, 12)[1])] = month_line[11]\n elif line[0:3] == 'MIN': # if \"MINIMA MEDIA\" exists:\n month_line = split_ideam_line(line) # min daily instantaneous month flow\n station_db[code]['minimos_mensuales'][date(year, 1, calendar.monthrange(year, 1)[1])] = month_line[0]\n station_db[code]['minimos_mensuales'][date(year, 2, calendar.monthrange(year, 2)[1])] = month_line[1]\n station_db[code]['minimos_mensuales'][date(year, 3, calendar.monthrange(year, 3)[1])] = month_line[2]\n station_db[code]['minimos_mensuales'][date(year, 4, calendar.monthrange(year, 4)[1])] = month_line[3]\n station_db[code]['minimos_mensuales'][date(year, 5, calendar.monthrange(year, 5)[1])] = month_line[4]\n station_db[code]['minimos_mensuales'][date(year, 6, calendar.monthrange(year, 6)[1])] = month_line[5]\n station_db[code]['minimos_mensuales'][date(year, 7, calendar.monthrange(year, 7)[1])] = month_line[6]\n station_db[code]['minimos_mensuales'][date(year, 8, calendar.monthrange(year, 8)[1])] = month_line[7]\n station_db[code]['minimos_mensuales'][date(year, 9, calendar.monthrange(year, 9)[1])] = month_line[8]\n station_db[code]['minimos_mensuales'][date(year, 10, calendar.monthrange(year, 10)[1])] = month_line[9]\n station_db[code]['minimos_mensuales'][date(year, 11, calendar.monthrange(year, 11)[1])] = month_line[10]\n station_db[code]['minimos_mensuales'][date(year, 12, calendar.monthrange(year, 12)[1])] = month_line[11]\n\n if 48 == i: # line where min discharge data is suposed to be located\n if line[0:3] == 'MIN': # if \"MINIMA MEDIA\" exists:\n month_line = split_ideam_line(line) # min daily instantaneous month flow\n station_db[code]['minimos_mensuales'][date(year, 1, calendar.monthrange(year, 1)[1])] = month_line[0]\n station_db[code]['minimos_mensuales'][date(year, 2, calendar.monthrange(year, 2)[1])] = month_line[1]\n station_db[code]['minimos_mensuales'][date(year, 3, calendar.monthrange(year, 3)[1])] = month_line[2]\n station_db[code]['minimos_mensuales'][date(year, 4, calendar.monthrange(year, 4)[1])] = month_line[3]\n station_db[code]['minimos_mensuales'][date(year, 5, calendar.monthrange(year, 5)[1])] = month_line[4]\n station_db[code]['minimos_mensuales'][date(year, 6, calendar.monthrange(year, 6)[1])] = month_line[5]\n station_db[code]['minimos_mensuales'][date(year, 7, calendar.monthrange(year, 7)[1])] = month_line[6]\n station_db[code]['minimos_mensuales'][date(year, 8, calendar.monthrange(year, 8)[1])] = month_line[7]\n station_db[code]['minimos_mensuales'][date(year, 9, calendar.monthrange(year, 9)[1])] = month_line[8]\n station_db[code]['minimos_mensuales'][date(year, 10, calendar.monthrange(year, 10)[1])] = month_line[9]\n station_db[code]['minimos_mensuales'][date(year, 11, calendar.monthrange(year, 11)[1])] = month_line[10]\n station_db[code]['minimos_mensuales'][date(year, 12, calendar.monthrange(year, 12)[1])] = month_line[11]\n\n # check if line is header (new year of data)\n if ' '.join(line.split()) == first_line:\n i = 0\n\n i += 1 # count\n\n f.close()\n\n output_path = destiny_folder\n pickle.dump(station_db, open(output_path, 'w'))\n\n print\n ''\n print\n '*********************************************************************'\n print\n '!Discharges database succesfully created!'\n\n # figure out how long the script took to run\n endTime = time.time()\n\n print\n 'Execution time: ' + str(round(endTime - startTime, 1)) + ' seconds'\n print\n '*********************************************************************\\n'\n","repo_name":"andresfduque/HydroClimaT","sub_path":"scripts/ImportITimeSeriesIDEAM.py","file_name":"ImportITimeSeriesIDEAM.py","file_ext":"py","file_size_in_byte":17420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"72401614477","text":"'''\nGiven 2 ints, a and b, return True if one if them is 10 or if their sum is 10.\n\n\nmakes10(9, 10) → True\nmakes10(9, 9) → False\nmakes10(1, 9) → True\n'''\n\ndef makes10(a, b):\n tenner = False\n sum = a + b\n#check if a is 10 or if b is 10\n if a == 10 or b == 10:\n # return true\n tenner = True\n# add the two\n# if sum is 10 return true\n elif sum == 10:\n tenner = True\n return tenner\n\nprint(\"{}, {}, {}\".format(makes10(9, 10),\nmakes10(9, 9),\nmakes10(1, 9)))","repo_name":"kenna1/Python-Projects","sub_path":"CodingPractice/WarmUp1/makes10.py","file_name":"makes10.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"17104045528","text":"from network.data_transform.data_transformation_train import Data_Transform_Train\nfrom network.data_type_valid.data_type_valid_train import DB_Operation_Train\nfrom network.raw_data_validation.train_data_validation import Raw_Train_Data_Validation\nfrom utils.logger import App_Logger\nfrom utils.read_params import get_log_dic, read_params\n\n\nclass Train_Validation:\n \"\"\"\n Description : This class is used for validating all the training batch files\n Written by : iNeuron Intelligence\n \n Version : 1.2\n Revisions : Moved to setup to cloud \n \"\"\"\n\n def __init__(self):\n self.config = read_params()\n\n self.log_writer = App_Logger()\n\n self.train_main_log = self.config[\"log\"][\"train_main\"]\n\n self.good_data_db_name = self.config[\"mongodb\"][\"network_db_name\"]\n\n self.good_data_collection_name = self.config[\"mongodb\"][\n \"network_train_data_collection\"\n ]\n\n self.raw_data = Raw_Train_Data_Validation()\n\n self.data_transform = Data_Transform_Train()\n\n self.db_operation = DB_Operation_Train()\n\n def train_validation(self):\n \"\"\"\n Method Name : training_validation\n Description : This method is responsible for converting raw data to cleaned data for training\n \n Output : Raw data is converted to cleaned data for training\n On Failure : Write an exception log and then raise an exception\n \n Version : 1.2\n Revisions : moved setup to cloud\n \"\"\"\n log_dic = get_log_dic(\n self.__class__.__name__,\n self.train_validation.__name__,\n __file__,\n self.train_main_log,\n )\n\n self.log_writer.start_log(\"start\", **log_dic)\n\n try:\n self.log_writer.log(\"Train Raw Validation started\", **log_dic)\n\n (\n LengthOfDateStampInFile,\n LengthOfTimeStampInFile,\n _,\n noofcolumns,\n ) = self.raw_data.values_from_schema()\n\n regex = self.raw_data.get_regex_pattern()\n\n self.raw_data.validate_raw_fname(\n regex, LengthOfDateStampInFile, LengthOfTimeStampInFile,\n )\n\n self.raw_data.validate_col_length(NumberofColumns=noofcolumns)\n\n self.raw_data.validate_missing_values_in_col()\n\n self.log_writer.log(\"Train Raw Data Validation completed\", **log_dic)\n\n self.log_writer.log(\"Train Data Transformation started\", **log_dic)\n\n self.data_transform.add_quotes_to_string_values_in_column()\n\n self.log_writer.log(\"Train Data Transformation completed\", **log_dic)\n\n self.log_writer.log(\"Train Data Type Validation started\", **log_dic)\n\n self.db_operation.insert_good_data_as_record(\n self.good_data_db_name, self.good_data_collection_name\n )\n\n self.db_operation.export_collection_to_csv(\n self.good_data_db_name, self.good_data_collection_name\n )\n\n self.log_writer.log(\"Train Data Type Validation completed\", **log_dic)\n\n self.log_writer.start_log(\"exit\", **log_dic)\n\n except Exception as e:\n self.log_writer.exception_log(e, **log_dic)\n","repo_name":"vishalsingh17/Network-Security-with-Machine-Learning","sub_path":"network/validation_insertion/train_validation_insertion.py","file_name":"train_validation_insertion.py","file_ext":"py","file_size_in_byte":3302,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"23695632287","text":"#!/usr/bin/python3\n\"\"\"\nFunction queries the Reddit API\nPrints the titles of the first 10 hot posts listed\n\"\"\"\n\nfrom requests import get\n\n\ndef top_ten(subreddit):\n \"\"\"Prints the titles of the first 10 host posts listed\"\"\"\n url = 'https://www.reddit.com/r/{}/hot/.json'.format(subreddit)\n headers = {\n 'User-Agent': '0x16-api_advanced:project:v1.0.0'\n }\n params = {\n \"limit\": 10\n }\n response = get(\n url, headers=headers, params=params,\n allow_redirects=False)\n\n if response.status_code == 404:\n print('None')\n return\n\n results = response.json().get(\"data\")\n [print(c.get(\"data\").get(\"title\")) for c in results.get(\"children\")]\n","repo_name":"madokscharles/alx-system_engineering-devops","sub_path":"0x16-api_advanced/1-top_ten.py","file_name":"1-top_ten.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"72033753359","text":"from Classes import *\nimport matplotlib.pyplot as pb\n\npath='/Users/bellrancurel/Desktop/Jo_mesures_son/'\ndossier='data'\ndata=Dossier(path+dossier)\nfreq, mag, phase=data.calcul()\n\npb.figure()\npb.plot(freq, phase, label='Phase')\npb.plot(freq, mag, label='Magnitude')\npb.xscale('log')\npb.title('Resultat')\npb.savefig('resultat.png')\npb.show()\n","repo_name":"bellrancurel/SoundCorrection","sub_path":"Affichage.py","file_name":"Affichage.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"25802986353","text":"import numpy as np\nimport scipy.sparse as sp\nimport torch\n\n\ndef get_khop_indices(k, view):\n view = (view.A > 0).astype(\"int32\")\n view_ = view\n for i in range(1, k):\n view_ = (np.matmul(view_, view.T)>0).astype(\"int32\")\n view_ = torch.tensor(view_).to_sparse()\n return view_.indices()\n \ndef topk(k, adj):\n pos = np.zeros(adj.shape)\n for i in range(len(adj)):\n one = adj[i].nonzero()[0]\n if len(one)>k:\n oo = np.argsort(-adj[i, one])\n sele = one[oo[:k]]\n pos[i, sele] = adj[i, sele]\n else:\n pos[i, one] = adj[i, one]\n return pos\n\n#####################\n## get k-hop scope ##\n## take citeseer ##\n#####################\nadj = sp.load_npz(\"./citeseer/v1_adj.npz\")\nindice = get_khop_indices(2, adj)\ntorch.save(indice, \"./citeseer/v1_2.pt\")\n\n#####################\n## get top-k scope ##\n## take citeseer ##\n#####################\nadj = sp.load_npz(\"./citeseer/v2_diff.npz\")\nkn = topk(40, adj)\nkn = sp.coo_matrix(kn)\nindice = get_khop_indices(1, kn)\ntorch.save(indice, \"./citeseer/v2_40.pt\")\n","repo_name":"liun-online/CoGSL","sub_path":"dataset/generate_scope.py","file_name":"generate_scope.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"29"} +{"seq_id":"22135042323","text":"# -*- coding: utf-8 -*-\n\"\"\" Test case to check the app manager daemon\n\"\"\"\n__author__ = \"Ben Tsui \"\n\n# std modules\nimport sys\nimport re\n# platform modules\nfrom middleware.arguments import GodzillaInputArgumentParser\nfrom middleware.godzilla_test_case import GodzillaTestCase\n\n\nclass LoadAPPManager(GodzillaTestCase):\n\n TEST_SUITE = 'Godzilla BAT'\n TEST_NAME = 'Load APP Manager Check'\n # Popcorn\n PROJECT = 'Godzilla'\n TEST_TYPE = 'Functional'\n TEST_JIRA_ID = 'Disabled'\n PRIORITY = 'Blocker'\n COMPONENT = 'PLATFORM'\n ISSUE_JIRA_ID = None\n\n SETTINGS = {\n 'uut_owner': False\n }\n\n def test(self):\n self.log.info(\"Checking app manager daemon\")\n app_manager = self.ssh_client.get_app_manager_service()\n if \"/usr/sbin/wdappmgr\" not in app_manager:\n raise self.err.TestFailure('Cannot find APP manager service!')\n\n\nif __name__ == '__main__':\n parser = GodzillaInputArgumentParser(\"\"\"\\\n *** Load APP Manager Check test for Godzilla devices ***\n Examples: ./run.sh godzilla_scripts/bat_scripts/load_app_manager.py --uut_ip 10.136.137.159 -model PR2100\\\n \"\"\")\n\n test = LoadAPPManager(parser)\n resp = test.main()\n if resp:\n sys.exit(0)\n sys.exit(1)\n","repo_name":"ben-tsui-wdc/bentsuiwdc","sub_path":"app/godzilla_scripts/bat_scripts/load_app_manager.py","file_name":"load_app_manager.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13281714236","text":"import numpy as np\nimport pandas as pd\nfrom math import e\n\ndef sigmoid(t):\n return 1 / (1 + e**(-t))\n\n# Evaluación del modelo dadas las entradas xs y coeficientes bs\ndef h(xs, bs):\n return sigmoid(np.dot(xs, bs))\n\n# Cálculo de gradiente, esto se transcribió directamente desde la fórmula\ndef grad(xs, ys, bs):\n return np.dot(h(xs, bs) - ys, xs)\n\n# Implementación de descenso de gradiente\ndef grad_desc(xs, ys, alpha):\n xs = np.insert(xs, 0, 1, axis=1) # Valor para la intersección\n gs = bs = np.ones(xs.shape[1])\n steps = 0\n\n while np.linalg.norm(gs) > 0.01 and steps < 10_000:\n gs = grad(xs, ys, bs)\n bs -= alpha * gs\n steps += 1\n\n return bs[0], bs[1:] # intersección, coeficientes\n\n#Gráfica para Género\ndef scatterGenero(figurenum,xs, ys):\n x_male = []\n y_male = []\n x_female = []\n y_female = []\n\n for x, y in zip(xs, ys):\n if y == 1:\n x_male.append(x[0])\n y_male.append(x[1])\n else:\n x_female.append(x[0])\n y_female.append(x[1])\n\n plt.figure(figurenum)\n plt.scatter(x_male, y_male, color='blue')\n plt.scatter(x_female, y_female, color='red')\n\n# Script principal\nif __name__ == '__main__':\n\n df = pd.read_csv(\"Default.txt\", sep=\"\\t\", header=0)\n\n binaryNum = {'Yes':1, 'No':0}\n\n df.default = [binaryNum[item] for item in df.default]\n df.student = [binaryNum[item] for item in df.student]\n\n X = np.array(df[['student', 'balance', 'income']])\n y = np.array(df[['default']]).flatten()\n\n intercept, bs = grad_desc(X, y, 1e-15)\n\n print(\"========Default.txt==============\")\n print('intercept value:', intercept)\n print('coeffiecients:', bs)\n\n df = pd.read_csv(\"genero.txt\", header=0)\n\n gender = {'Male':1, 'Female':0}\n\n df.Gender = [gender[item] for item in df.Gender]\n\n X = np.array(df[['Height','Weight']])\n y = np.array(df[['Gender']]).flatten()\n\n intercept, bs = grad_desc(X, y, 1e-15)\n\n print('=== genero.txt ===')\n print('intercept value:', intercept)\n print('coeffiecients:', bs)\n\n\n\n\n\n\n\n\n\n\ndef genero():\n df = pd.read_csv(\"genero.txt\", header=0)\n\n gender = {'Male':1, 'Female':0}\n\n df.Gender = [gender[item] for item in df.Gender]\n\n X = np.array(df[['Height','Weight']])\n y = np.array(df[['Gender']])\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n\n\n print(\"========genero.txt==============\")\n\n # Training the model\n b0, b1 = grad_desc_Genero(X_train, y_train)\n\n # Making predictions\n X_test_norm = normalizar(X_test)\n y_pred = predict(X_test_norm, b0, b1)\n y_pred = [1 if p >= 0.5 else 0 for p in y_pred]\n\n scatterGenero(1,X_train,y_train)\n\n scatterGenero(2,X_test, y_pred)\n plt.show()\n\n accuracy = 0\n\n for i in range(len(y_pred)):\n if y_pred[i] == y_test.iloc[i]:\n accuracy += 1\n\n print(\"Confusion Matrix:\\n\", confusion_matrix(y_test,y_pred))\n print('Classification Report: \\n', classification_report(y_test,y_pred))\n print(f\"Accuracy = {accuracy / len(y_pred)}\")\n","repo_name":"JairAntonio22/Labs-AprendizajeAutomatico","sub_path":"Prácticas/Práctica_2/scripts/gradDescLogistic.py","file_name":"gradDescLogistic.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"30329642957","text":"#!/usr/bin/python\n# Env: python3\n# Rewrite by afei_0and1\n\n'''\n2、格式化字符串进阶\n 给定一个字符串string,检查是否可以重新排列组合成新的字符串,使其满足如下条件:相邻的字符不相同。\n如果可以,则返回任意可行的结果即可,如果不可,则返回False。例如:输入字符串:AABBCC,返回:ABCABC\n其中一种可行的答案即可。\n解题思路:只需找出字符串中字母个数最多的那个,如果其满足:不大于字符串长度+1除以2,则说明可以组成相邻\n字符不相同的新的字符串;否则返回False即可。\n步骤:\n(1)将原字符串中的每个字符个数分别统计出来。将统计完成的结果按照字符串出现的次数从大到小进行排序,\n组成数据源列表;\n(2)从数据源列表中依次取值填充到新的空列表中,填充列表时:先将偶数位全部填充完成,再填充奇数位;\n(3)将新的列表重新组合成最终的结果字符串即可。\n'''\n\ndef formatString_adv(string):\n dic = {}\n #结果列表先用0填充\n res = [\"0\" for i in range(len(string))]\n for i in string:\n #从字典中依次取出元素\n if i in dic.keys():\n dic[i] += 1\n else:\n dic[i] = 1\n #dic.item()方法将字典元素返回列表,并以lambda表达式以元素个数返回子列表\n #s=\"AAABBCC\":[[A:3], [B:2], [C:2]]\n l = sorted(dic.items(), key=lambda x : x[1])\n #最多字符串大于字符串长度+1除以2的情况\n if len(l[-1]) > (len(string)+1) / 2:\n return False\n\n tempCount = 0 #插入字符个数\n tempItem = None #插入的字符\n #偶数位填充\n for i in range(0, len(string), 2):\n if tempItem == None:\n tempItem = l.pop() #取出最后一个字符\n #填充偶数位第一个元素\n if tempCount == 0:\n tempCount= tempItem[1]\n res[i] = tempItem[0]\n tempCount -= 1\n #循环插入元素\n if tempCount == 0:\n tempItem = None\n #奇数位填充\n for i in range(1, len(string), 2):\n if tempItem == None:\n tempItem = l.pop()\n if tempCount == 0:\n tempCount = tempItem[1]\n res[i] = tempItem[0]\n tempCount -= 1\n if tempCount == 0:\n tempItem = None\n return \"\".join(res)\n\nprint(formatString_adv(\"AAABBCCCDDFFF\"))\n'''\nOutput result:\n FAFAFDCDCBCBA\n'''","repo_name":"ltfafei/py_Leetcode_study","sub_path":"Strings/2.formatStrings_adv.py","file_name":"2.formatStrings_adv.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"10335437858","text":"\"\"\"\npy.test and pylib: rapid testing and development utils\n\nthis module uses apipkg.py for lazy-loading sub modules\nand classes. The initpkg-dictionary below specifies\nname->value mappings where value can be another namespace\ndictionary or an import path. \n\n(c) Holger Krekel and others, 2004-2010\n\"\"\"\n__version__ = version = \"1.3.1\"\n\nimport py.apipkg\n\npy.apipkg.initpkg(__name__, dict(\n # access to all standard lib modules\n std = '._std:std',\n # access to all posix errno's as classes\n error = '._error:error',\n\n _pydir = '.__metainfo:pydir',\n version = 'py:__version__', # backward compatibility\n\n cmdline = {\n 'pytest': '._cmdline.pytest:main',\n 'pylookup': '._cmdline.pylookup:main',\n 'pycountloc': '._cmdline.pycountlog:main',\n 'pylookup': '._cmdline.pylookup:main',\n 'pycountloc': '._cmdline.pycountloc:main',\n 'pycleanup': '._cmdline.pycleanup:main',\n 'pywhich' : '._cmdline.pywhich:main',\n 'pysvnwcrevert' : '._cmdline.pysvnwcrevert:main',\n 'pyconvert_unittest' : '._cmdline.pyconvert_unittest:main',\n },\n\n test = {\n # helpers for use from test functions or collectors\n '__onfirstaccess__' : '._test.config:onpytestaccess',\n '__doc__' : '._test:__doc__',\n # configuration/initialization related test api\n 'config' : '._test.config:config_per_process',\n 'ensuretemp' : '._test.config:ensuretemp',\n 'collect': {\n 'Collector' : '._test.collect:Collector',\n 'Directory' : '._test.collect:Directory',\n 'File' : '._test.collect:File',\n 'Item' : '._test.collect:Item',\n 'Module' : '._test.pycollect:Module',\n 'Class' : '._test.pycollect:Class',\n 'Instance' : '._test.pycollect:Instance',\n 'Generator' : '._test.pycollect:Generator',\n 'Function' : '._test.pycollect:Function',\n '_fillfuncargs' : '._test.funcargs:fillfuncargs',\n },\n 'cmdline': {\n 'main' : '._test.cmdline:main', # backward compat\n },\n },\n\n # hook into the top-level standard library\n process = {\n '__doc__' : '._process:__doc__',\n 'cmdexec' : '._process.cmdexec:cmdexec',\n 'kill' : '._process.killproc:kill',\n 'ForkedFunc' : '._process.forkedfunc:ForkedFunc',\n },\n\n path = {\n '__doc__' : '._path:__doc__',\n 'svnwc' : '._path.svnwc:SvnWCCommandPath',\n 'svnurl' : '._path.svnurl:SvnCommandPath',\n 'local' : '._path.local:LocalPath',\n 'SvnAuth' : '._path.svnwc:SvnAuth',\n },\n\n # some nice slightly magic APIs\n magic = {\n 'invoke' : '._code.oldmagic:invoke',\n 'revoke' : '._code.oldmagic:revoke',\n 'patch' : '._code.oldmagic:patch',\n 'revert' : '._code.oldmagic:revert',\n 'autopath' : '._path.local:autopath',\n 'AssertionError' : '._code.oldmagic2:AssertionError',\n },\n\n # python inspection/code-generation API\n code = {\n '__doc__' : '._code:__doc__',\n 'compile' : '._code.source:compile_',\n 'Source' : '._code.source:Source',\n 'Code' : '._code.code:Code',\n 'Frame' : '._code.code:Frame',\n 'ExceptionInfo' : '._code.code:ExceptionInfo',\n 'Traceback' : '._code.code:Traceback',\n 'getfslineno' : '._code.source:getfslineno',\n 'getrawcode' : '._code.code:getrawcode',\n 'patch_builtins' : '._code.code:patch_builtins',\n 'unpatch_builtins' : '._code.code:unpatch_builtins',\n '_AssertionError' : '._code.assertion:AssertionError',\n '_reinterpret_old' : '._code.assertion:reinterpret_old',\n '_reinterpret' : '._code.assertion:reinterpret',\n },\n\n # backports and additions of builtins\n builtin = {\n '__doc__' : '._builtin:__doc__',\n 'enumerate' : '._builtin:enumerate',\n 'reversed' : '._builtin:reversed',\n 'sorted' : '._builtin:sorted',\n 'set' : '._builtin:set',\n 'frozenset' : '._builtin:frozenset',\n 'BaseException' : '._builtin:BaseException',\n 'GeneratorExit' : '._builtin:GeneratorExit',\n 'print_' : '._builtin:print_',\n '_reraise' : '._builtin:_reraise',\n '_tryimport' : '._builtin:_tryimport',\n 'exec_' : '._builtin:exec_',\n '_basestring' : '._builtin:_basestring',\n '_totext' : '._builtin:_totext',\n '_isbytes' : '._builtin:_isbytes',\n '_istext' : '._builtin:_istext',\n '_getimself' : '._builtin:_getimself',\n '_getfuncdict' : '._builtin:_getfuncdict',\n '_getcode' : '._builtin:_getcode',\n 'builtins' : '._builtin:builtins',\n 'execfile' : '._builtin:execfile',\n 'callable' : '._builtin:callable',\n },\n\n # input-output helping\n io = {\n '__doc__' : '._io:__doc__',\n 'dupfile' : '._io.capture:dupfile',\n 'TextIO' : '._io.capture:TextIO',\n 'BytesIO' : '._io.capture:BytesIO',\n 'FDCapture' : '._io.capture:FDCapture',\n 'StdCapture' : '._io.capture:StdCapture',\n 'StdCaptureFD' : '._io.capture:StdCaptureFD',\n 'TerminalWriter' : '._io.terminalwriter:TerminalWriter',\n 'ansi_print' : '._io.terminalwriter:ansi_print', \n 'get_terminal_width' : '._io.terminalwriter:get_terminal_width',\n 'saferepr' : '._io.saferepr:saferepr',\n },\n\n # small and mean xml/html generation\n xml = {\n '__doc__' : '._xmlgen:__doc__',\n 'html' : '._xmlgen:html',\n 'Tag' : '._xmlgen:Tag',\n 'raw' : '._xmlgen:raw',\n 'Namespace' : '._xmlgen:Namespace',\n 'escape' : '._xmlgen:escape',\n },\n\n log = {\n # logging API ('producers' and 'consumers' connected via keywords)\n '__doc__' : '._log:__doc__',\n '_apiwarn' : '._log.warning:_apiwarn',\n 'Producer' : '._log.log:Producer',\n 'setconsumer' : '._log.log:setconsumer',\n '_setstate' : '._log.log:setstate',\n '_getstate' : '._log.log:getstate',\n 'Path' : '._log.log:Path',\n 'STDOUT' : '._log.log:STDOUT',\n 'STDERR' : '._log.log:STDERR',\n 'Syslog' : '._log.log:Syslog',\n },\n\n # compatibility modules (deprecated)\n compat = {\n '__doc__' : '._compat:__doc__',\n 'doctest' : '._compat.dep_doctest:doctest',\n 'optparse' : '._compat.dep_optparse:optparse',\n 'textwrap' : '._compat.dep_textwrap:textwrap',\n 'subprocess' : '._compat.dep_subprocess:subprocess',\n },\n))\n","repo_name":"thepian/pypy","sub_path":"py/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7200,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"75034177679","text":"# contador de adultos\nfrom datetime import date\nadulto = []\nmenor = []\nind = []\nfor c in range(0, 7):\n ano = int(input('Ano de nascimento: '))\n if date.today().year - ano > 18:\n adulto.append(c)\n elif date.today().year - ano < 18:\n menor.append(c)\n else:\n ind.append(c)\nprint('O número de adultos é: {}'.format(len(adulto)))\nprint('O número de menores de idade é: {}'.format(len(menor)))\nprint('O número de pessoas que fazem 18 anos esse ano é: {}'.format(len(ind)))\n","repo_name":"Artur-UF/CursoPythonemVideo","sub_path":"Exercícios/ex054.py","file_name":"ex054.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"8412122828","text":"import os\nfrom Tools.HardwareInfo import HardwareInfo\nfrom Tools.Directories import SCOPE_SKIN, resolveFilename\n\n\nclass RcModel:\n\tRcModels = {}\n\n\tdef __init__(self):\n\t\tself.model = HardwareInfo().get_device_model()\n\t\t# cfg files has modelname rcname entries.\n\t\t# modelname is boxname optionally followed by .rctype\n\t\tfor line in open((resolveFilename(SCOPE_SKIN, 'rc_models/rc_models.cfg')), 'r'):\n\t\t\tif line.startswith(self.model):\n\t\t\t\tm, r = line.strip().split()\n\t\t\t\tself.RcModels[m] = r\n\n\tdef rcIsDefault(self):\n\t\t# Default RC can only happen with DMM type remote controls...\n\t\treturn self.model.startswith('dm')\n\n\tdef getRcFile(self, ext):\n\t\t# check for rc/type every time so rctype changes will be noticed\n\t\tif os.path.exists('/proc/stb/ir/rc/type'):\n\t\t\trc = open('/proc/stb/ir/rc/type').read().strip()\n\t\t\tmodeltype = '%s.%s' % (self.model, rc)\n\t\telse:\n\t\t\tmodeltype = None\n\n\t\tif modeltype is not None and modeltype in self.RcModels.keys():\n\t\t\tremote = self.RcModels[modeltype]\n\t\telif self.model in self.RcModels.keys():\n\t\t\tremote = self.RcModels[self.model]\n\t\telse:\n\t\t\tremote = 'dmm'\t# default. Assume files for dmm exists\n\t\tf = resolveFilename(SCOPE_SKIN, 'rc_models/' + remote + '.' + ext)\n\t\tif not os.path.exists(f):\n\t\t\tf = resolveFilename(SCOPE_SKIN, 'rc_models/dmm.' + ext)\n\t\treturn f\n\n\tdef getRcImg(self):\n\t\treturn self.getRcFile('png')\n\n\tdef getRcPositions(self):\n\t\treturn self.getRcFile('xml')\n\n\nrc_model = RcModel()\n","repo_name":"OpenPLi/enigma2","sub_path":"lib/python/Components/RcModel.py","file_name":"RcModel.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","stars":145,"dataset":"github-code","pt":"29"} +{"seq_id":"2925144299","text":"#coding: utf-8\nimport evaluate\nimport gene\nimport random\n\n'''\ndef __init__ (self,baseprenum,parameter,popsize,baseusingnum,choosenum,crosspro,mutepro,iterationtime):\n#parameter = [basex,basey,baseh,x,y,h,fc,Tx,G,htb,hre,Noise,rsrpthre,sinrthre,coverthre,nbaseallx,nbaseally,ncost,ocost]\nTERM_HEIGHT = 1.5\nTX_POWER = 38.2\nFREQ = 2600\nNOISE = -110.0\ncenter_x = 103.75 # 兰州的中心点(保留2位小数)\ncenter_y = 36.09\n'''\n\nx=[0]*100\nfor i in range(10):\n\tfor j in range(10):\n\t\tx[i*10+j] = j\n\ny=[0]*100\t\t\nfor i in range(10):\n\tfor j in range(10):\n\t\ty[i*10+j] = i\n\t\t\n \nbasex=[]\nbasey=[]\nfor i in range(30):\n basex.append(random.randint(0,9))\n basey.append(random.randint(0,9))\n#print(\"basex is %r\"%basex)\nbaseh = [10]*30\nh = [1.7]*100\nfc = 2900\nTx = 80.2\n#TX = 38.2 ...\nG = 16.34\nhtb = 10\nhre = 1.7\nNoise = -110\nrsrpthre = -88\nsinrthre = -3\ncoverthre = 0.7\nobaseallx = []\nobaseally = []\nobaseallx.extend(random.sample(basex,10))\nobaseally.extend(random.sample(basey,10))\nncost = 300\nocost = 100\nparameter1 = [basex,basey,baseh,x,y,h,fc,Tx,G,htb,hre,Noise,rsrpthre,sinrthre,coverthre,obaseallx,obaseally,ncost,ocost]\nbaseprenum = 30\nparameter = parameter1\npopsize = 8\nbaseusingnum = 4\nchoosenum =6\ncrosspro = 0.9\nmutepro = 0.1\niterationtime = 10\n#print(\"a's basex is %r\"%parameter[0])\na = gene.Gene(baseprenum,parameter,popsize,baseusingnum,choosenum,crosspro,mutepro,iterationtime)\nmaxfit, bestindividual, cost = a.Gene_main()\n","repo_name":"bearwangcai/gene_algorithm","sub_path":"gene_test.py","file_name":"gene_test.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"73326115918","text":"import numpy as np\nfrom scipy import sparse as sp\n\nCONFI_AMOUNT = 0.5\n\ntx_to_addr = sp.load_npz('../data/daily_graphs/months_1_to_12_btc_transactions_tx_to_addr.npz').astype('uint64')\naddr_to_tx = sp.load_npz('../data/daily_graphs/months_1_to_12_btc_transactions_addr_to_tx.npz').astype('uint64')\n\n# 2 features: summed amounts of inputs and summed amounts of outputs\ninput_sum = addr_to_tx.sum(axis = 1).A[:,0]\noutput_sum = tx_to_addr.sum(axis = 0).A[0,:]\n\ninput_sum_sq = addr_to_tx.power(2).sum(axis = 1).A[:,0]\noutput_sum_sq = tx_to_addr.power(2).sum(axis = 0).A[0,:]\n\n# 2 features: number of outputs received and outputs spent\ninput_count = (addr_to_tx != 0).sum(axis = 1).A[:,0]\noutput_count = (tx_to_addr != 0).sum(axis = 0).A[0,:]\n\n# 2 features: getting the average amounts for received and spent outputs for each address\ninput_mean = input_sum/input_count\noutput_mean = np.nan_to_num(output_sum/output_count)\n\ninput_mean_sq = input_mean**2\noutput_mean_sq = output_mean**2\n\ninput_sq_mean = input_sum_sq/input_count\noutput_sq_mean = np.nan_to_num(output_sum_sq/output_count)\n\n# 2 features: the standard deviation for the amounts of the received outputs and also the spent outputs\ninput_std = np.nan_to_num((input_sq_mean - input_mean_sq)**CONFI_AMOUNT)\noutput_std = np.nan_to_num((output_sq_mean - output_mean_sq)**CONFI_AMOUNT)\n\n# feature: the ratio between number of outputs received and number of outputs spent\ninput_to_output_ratio = np.nan_to_num(input_count/output_count)\n\n# concatenating each feature list into one matrix and then saving that matrix\nfeatures = np.stack([input_sum,output_sum,input_count,output_count,input_mean,output_mean,input_std,output_std,input_to_output_ratio],axis = 1)\n\nnp.save('../data/grams/features.npy',features)\n","repo_name":"jeeerdin/COMP7570-Group-Project","sub_path":"Step2/extract_features.py","file_name":"extract_features.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31188301723","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nburden_estimate = np.load(\"SIR.npy\")\nprint(\"Data Shape :\", burden_estimate.shape)\nSIR_list = []\n\nfor i in range(100):\n np.random.seed(i)\n rand = np.random.randn(18,3) * 0.1\n rand[[0], :] = 0\n #rand[-1, :] = 0\n obs_SIR = burden_estimate + rand\n SIR_list.append(obs_SIR)\n np.save(arr=obs_SIR, file=\"SIR_{}\".format(i))\n\n#SIR_0 = np.load(\"SIR_0.npy\")\n#SIR_49 = np.load(\"SIR_49.npy\")\nSIR = np.asarray(SIR_list)\nSIR_0 = np.percentile(SIR, 97.5, axis=0)\nSIR_95 = np.percentile(SIR, 2.5, axis=0)\nfig, ax = plt.subplots(2, 1)\nax[0].plot(SIR_0, \"--\", color = \"red\")\nax[0].plot(SIR_95, \"--\", color = \"red\")\nax[0].plot(burden_estimate, color=\"green\")\nfig.delaxes(ax[1])\nplt.show()\n\nprint(SIR_0)","repo_name":"CrawlingKiming/AdVI","sub_path":"experiments/calibration/data/SIR/GenerateData.py","file_name":"GenerateData.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"32912887788","text":"import datetime\n\nimport yara\n\nfrom lvfs import db, tq\n\nfrom lvfs.components.models import Component, ComponentShard\nfrom lvfs.firmware.models import Firmware\nfrom lvfs.metadata.models import Remote\n\nfrom .models import YaraQuery, YaraQueryResult\n\n@tq.task(max_retries=3, default_retry_delay=60, task_time_limit=6000)\ndef _async_query_run(yara_query_id):\n query = db.session.query(YaraQuery)\\\n .filter(YaraQuery.yara_query_id == yara_query_id)\\\n .first()\n if not query:\n return\n _query_run(query)\n\ndef _query_run_shard(query: YaraQuery, md: Component, shard: ComponentShard):\n if not shard.blob:\n return\n matches = query.rules.match(data=shard.blob)\n for match in matches:\n msg = match.rule\n for string in match.strings:\n if len(string) == 3:\n try:\n msg += ': found {}'.format(string[2].decode())\n except UnicodeDecodeError as _:\n pass\n query.results.append(YaraQueryResult(md=md, shard=shard, result=msg))\n\n # unallocate the cached blob as it's no longer needed\n shard.blob = None\n\ndef _query_run_component(query: YaraQuery, md: Component):\n if not md.blob:\n return\n matches = query.rules.match(data=md.blob)\n for match in matches:\n msg = match.rule\n for string in match.strings:\n if len(string) == 3:\n try:\n msg += ': found {}'.format(string[2].decode())\n except UnicodeDecodeError as _:\n pass\n query.results.append(YaraQueryResult(md=md, result=msg))\n\n # unallocate the cached blob as it's no longer needed\n md.blob = None\n\ndef _query_run(query: YaraQuery):\n print('processing query {}: {}...'.format(query.yara_query_id, query.title))\n try:\n query.rules = yara.compile(source=query.value)\n except yara.SyntaxError as e:\n query.error = 'Failed to compile rules: {}'.format(str(e))\n db.session.commit()\n return\n query.started_ts = datetime.datetime.utcnow()\n db.session.commit()\n component_ids = [x[0] for x in db.session.query(Component.component_id)\\\n .join(Firmware)\\\n .join(Remote)\\\n .filter(Remote.name == 'stable').all()]\n for component_id in component_ids:\n md = db.session.query(Component)\\\n .filter(Component.component_id == component_id)\\\n .one()\n for shard in md.shards:\n _query_run_shard(query, md, shard)\n _query_run_component(query, md)\n query.total += len(md.shards)\n query.found = len(query.results)\n query.ended_ts = datetime.datetime.utcnow()\n db.session.commit()\n\ndef _query_run_all():\n\n # get all pending queries\n pending = db.session.query(YaraQuery).\\\n filter(YaraQuery.started_ts == None).\\\n filter(YaraQuery.error == None)\n for query in pending:\n _query_run(query)\n","repo_name":"ChenglinZheng/lvfs-website-archived","sub_path":"lvfs/queries/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"21767940625","text":"import io\nimport os\nimport time\n\n\"\"\"\n2 pipes\n1 para que escriba el padre y lean los hijos\n1 para que escriban los hijos y lea el padre\n\"\"\"\n# Crear pipes\npipe_padre_hijo_r, pipe_padre_hijo_w = os.pipe()\npipe_hijo_padre_r, pipe_hijo_padre_w = os.pipe()\n\n# os.close(pipe_padre_hijo_r)\npipe = os.fdopen(pipe_padre_hijo_w, 'a')\nfor i in range(5):\n mensaje_padre = \"Mensaje del padre \"+str(i+1)+\"\\n\"\n pipe.write(mensaje_padre)\n # pipe.flush()\n #os.write(pipe_padre_hijo_w, mensaje_padre.encode())\n # time.sleep(1)\npipe.close()\n# os.close(pipe_padre_hijo_w)\nprint(\"termina\")\nfor i in range(5):\n print(\"entra\")\n # time.sleep(2)\n pid = os.fork()\n if pid == 0: # si es un hijo\n # os.close(pipe_padre_hijo_w)\n os.close(pipe_hijo_padre_r)\n while True:\n mensaje_padre = os.read(pipe_padre_hijo_r, 500).decode()\n if (mensaje_padre != \"\"):\n print(\"si\")\n\n print(f\"Hijo {os.getpid()} recibió: {mensaje_padre}\")\n primeraLinea = \"\"\n for caracter in mensaje_padre:\n if (caracter != \"\\n\"):\n primeraLinea = primeraLinea+caracter\n else:\n print(\"texto: \", primeraLinea)\n mensaje_padre = mensaje_padre.replace(\n primeraLinea+\"\\n\", \"\", 1)\n print(\"mensaje quedo: \", mensaje_padre)\n pipe = os.fdopen(pipe_padre_hijo_w, 'w')\n pipe.write(mensaje_padre)\n pipe.close()\n print(\"sale\")\n break\n print(\"termina hijo\")\n break\n\n mensaje_hijo = \"soy el hijo: \"+str(mensaje_padre)\n os.write(pipe_hijo_padre_w, mensaje_hijo.encode())\n # os.close(pipe_padre_hijo_r)\n os.close(pipe_hijo_padre_w)\n\n os._exit(0)\n\nfor i in range(5):\n os.wait()\nos.close(pipe_hijo_padre_w)\n\nfor i in range(5):\n #pipe = io.open(pipe_hijo_padre_r, 'r')\n #mensaje_hijo = pipe.readline()\n mensaje_hijo = os.read(pipe_hijo_padre_r, 100)\n print(f\"Padre {os.getpid()} recibió: {mensaje_hijo}\")\n\n\nos.close(pipe_hijo_padre_r)\n","repo_name":"fisaguirre/UM-Computacion2-2023","sub_path":"Trabajos/TP1/prueba2.py","file_name":"prueba2.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34780439116","text":"import os\nimport time\nimport numpy as np\nimport pickle\nimport processing\n\n\ndef save_pickle(variable, fileName):\n with open(fileName, 'wb') as f:\n pickle.dump(variable, f)\n\n\ndef load_pickle_file(fileName):\n with open(fileName, 'rb') as f:\n return pickle.load(f)\n\n\ndef processing_for_training(train_A_dir, cache_folder):\n num_mcep = 128\n sampling_rate = 16000\n frame_period = 10.0\n\n print(\"Starting to prepocess data.......\")\n start_time = time.time()\n\n wavs_A , labels = processing.load_wavs(wav_dir=train_A_dir, sr=sampling_rate)\n\n open(os.path.join(cache_folder,'texts.txt'),'w',encoding='utf8').write('\\n'.join([lbl.replace('\\n','') for lbl in labels]))\n\n f0s_A, timeaxes_A, sps_A, aps_A, coded_sps = processing.world_encode_data(\n wave=wavs_A, fs=sampling_rate, frame_period=frame_period, coded_dim=num_mcep)\n\n log_f0s_mean, log_f0s_std = processing.logf0_statistics(f0s=f0s_A)\n\n print(\"Log Pitch A\")\n print(\"Mean: {:.4f}, Std: {:.4f}\".format(log_f0s_mean, log_f0s_std))\n\n\n coded_sps_A_transposed = processing.transpose_in_list(lst=coded_sps)\n\n\n coded_sps_norm, coded_sps_A_mean, coded_sps_A_std = processing.coded_sps_normalization_fit_transform(\n coded_sps=coded_sps_A_transposed)\n\n\n if not os.path.exists(cache_folder):\n os.makedirs(cache_folder)\n\n np.savez(os.path.join(cache_folder, 'logf0s_normalization.npz'),\n mean = log_f0s_mean,\n std = log_f0s_std)\n\n np.savez(os.path.join(cache_folder, 'mcep_normalization.npz'),\n mean=coded_sps_A_mean,\n std=coded_sps_A_std)\n\n save_pickle(variable=coded_sps_norm,\n fileName=os.path.join(cache_folder, \"coded_sps_norm.pickle\"))\n \n open(os.path.join(cache_folder,'texts.txt'),'w',encoding='utf8').write('\\n'.join([lbl.replace('\\n','') for lbl in labels]))\n\n end_time = time.time()\n print(\"processinging finsihed!! see your directory ../cache for cached processinged data\")\n\n print(\"Time taken for processinging {:.4f} seconds\".format(\n end_time - start_time))\n\n\nif __name__ == '__main__':\n processing_for_training('./data', 'cache')","repo_name":"psyxusheng/text2music","sub_path":"processing_files.py","file_name":"processing_files.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31893202936","text":"# Задача 1. Напишите программу, которая принимает на вход вещественное число и показывает сумму его цифр.\n# Пример:\n# - 6782 -> 23\n# - 0,56 -> 11\n\n\nnum = int(input('Введите целое значение: '))\nsum = 0\nwhile (num != 0):\n sum = sum + num % 10\n num = num // 10\nprint(\"Сумма цифр числа равна: \", sum)\n \n\n# Задача 2. Напишите программу, которая принимает на вход число N и выдает набор произведений чисел от 1 до N.\n# Пример:\n# - пусть N = 4, тогда [ 1, 2, 6, 24 ] (1, 1*2, 1*2*3, 1*2*3*4)\n\n\ndef func (x):\n factorial = 1\n for i in range (1,x + 1):\n factorial = factorial * i\n print(factorial, end = ' ')\n \nn = int(input('Введите любое значение: '))\nfunc(n)\n\n#Задача 3. Задайте список из n чисел последовательности (1+1/n)^n и выведите на экран их сумму.\n#Пример:\n#- Для n = 6: {1: 4, 2: 7, 3: 10, 4: 13, 5: 16, 6: 19}\n\n\ndef Calculation(n,amount = 0):\n amount += (1 + 1/(n))**(n)\n return amount\n\nn = int(input('Введите любое целое число:'))\nspisok = range(n)\nspList = ' '\nsumSpisok = 0\nfor i in range ( 1, n + 1):\n sumSpisok += Calculation(i)\n spList += ' ' + str(Calculation(i))\nprint(f\"Cумма последовательности чисел {spList} = {sumSpisok}\")\n\n#Задача 4. Задайте список из N элементов, заполненных числами из промежутка [-N, N]. Найдите произведение элементов \n# на указанных позициях. Позиции хранятся в файле file.txt в одной строке одно число.\n\n#Реализуйте алгоритм перемешивания списка.\n\nn = int(input('Введите любое целое число:'))\nmy_list = []\nimport random\n\n\nfor i in range(-n,n+1):\n \n my_list.append(i)\nprint(my_list)\n\nrandom.shuffle(my_list)\nprint(my_list)\n\n\ndef multiply(n):\n total = -n\n for i in range(-n, n+1):\n total *= i \n print(f\"Произведение чисел в списке равно {total}\")\nmultiply(4)\n\nprint(\"\\n\".join(map(str,my_list)))\n\n##Дополнительный вариант хранения в txt в форме списка\n#with open(\"file.txt\", \"w\") as f:\n # for s in my_list:\n # f.write(str(s) +\"\\n\")\n\n#with open(\"file.txt\", \"r\") as f:\n #for line in f:\n #my_list.append(int(line.strip()))\n","repo_name":"VioLife/Learning_python","sub_path":"Learn_Python/Task2.py","file_name":"Task2.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6868046853","text":"import torch as ch\nimport os.path\nfrom torch import optim\nfrom torch import nn\nfrom torch.utils import data\nimport torch.autograd as autograd\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.optim.lr_scheduler import StepLR\n#from models import Classifier\n\nch.set_default_tensor_type('torch.cuda.FloatTensor')\n\nBIG_BATCH_SIZE = 10#100\nBATCH_SIZE = 1\nR = 10 # number of restarts in defense-gan\nL = 200 # number of projection steps in defense-gan\nI = int(L*0.8) # in defense-gan, learning rate is decayed after these many steps\nLAM = 0.00025\nCRIT = nn.CrossEntropyLoss(reduce=False)\nRANGE = ch.range(0,BIG_BATCH_SIZE*R-1).long()\nSGD_LR = 10. #learning rate for sgd in defense-gan\nMOMENTUM = 0.7 #momentum for defense-gan\n\n# folder with different robustness norms for our attack\nfolder_list = ['./intermediates_2.5','./intermediates_3.0','./intermediates_3.5', './intermediates_3.0_200', './intermediates_3.0_300']\nNUM_FOLDERS = len(folder_list)\n\ngan = nn.DataParallel(ch.load(\"ckpts/netG\")).cuda()\nfor p in gan.parameters():\n p.requires_grad_(False)\ncla = nn.DataParallel(ch.load(\"ckpts/classifier\")).cuda()\nfor p in cla.parameters():\n p.requires_grad_(False)\n\ntestloader = data.DataLoader(\n\tdatasets.MNIST('../data', download=True, train=False, transform=transforms.Compose([\n\t\t transforms.ToTensor(),\n\t ])), batch_size=BIG_BATCH_SIZE, shuffle=False)\n\n# recreate defense-gan\ndef latent_space_opt(ims, labels, num_steps=L):\n ims = ims.view(-1, 784)\n zhat = ch.randn(R*ims.shape[0], 128)\n targets = ims.repeat(R, 1)\n zhat.requires_grad_()\n opt = optim.SGD([zhat], lr=SGD_LR, momentum=MOMENTUM)\n lr_maker = StepLR(opt, step_size=I)\n\n for i in range(num_steps):\n opt.zero_grad()\n loss_mat = ((gan(zhat) - targets)**2).mean(-1)\n total_loss = loss_mat.clone()\n if (i+1) % 100 == 0:\n print(\"Iteration %d | Distance Loss %f\" % (i, loss_mat.mean()))\n total_loss.mean().backward()\n opt.step()\n lr_maker.step()\n\n # take the big loss matrix and reshape it as\n # (R, BIG_BATCH_SIZE*NUM_FOLDERS)\n distance_mat = ch.stack(loss_mat.chunk(R, 0), 0) \n image_mat = ch.stack(gan(zhat).chunk(R, 0), 0)\n zh_mat = ch.stack(zhat.chunk(R, 0), 0)\n # find index of the restart which gives smallest reconstruction error\n ind = (-distance_mat).argmax(0)\n # for each image, select the best restart\n im_range = ch.range(0,ims.shape[0]-1).long()\n best_ims = image_mat[ind,im_range,:]\n best_zhs = zh_mat[ind,im_range,:]\n\n return best_ims.clone().detach(), best_zhs.clone().detach()\n\ndef accuracy(): \n total_correct = 0.0\n total_incorrect_inbds = 0.0\n total = 0.0\n i = 0\n try:\n for ims_, labels in testloader:\n labels = labels.cuda()\n all_ints = []\n all_orig = []\n # attack for the i-th image is stored as batch_i_attack\n # load the i-th image, which is given by \n # i = k*BIG_BATCH_SIZE+j , where k is the batch number, and j is the index within the batch\n for j in range(BIG_BATCH_SIZE//BATCH_SIZE):\n for folder in folder_list: \n intermediates = ch.load(\"%s/batch_%d_attack\" % (folder,i,))\n originals = ch.load(\"%s/batch_%d_orig\" % (folder,i,))\n all_ints.append(intermediates)\n all_orig.append(originals)\n i += 1\n intermediates = ch.cat(all_ints, 0)\n originals = ch.cat(all_orig, 0)\n # get results from defense-gan projection\n images, _ = latent_space_opt(intermediates.view(-1, 784).cuda(), labels, num_steps=L)\n with ch.no_grad():\n out = cla(images.view(-1,1,28,28).cuda())\n \n preds = out.argmax(1)\n # reshape predictions as (BIG_BATCH_SIZE, NUM_FOLDERS)\n preds_repeat = ch.stack(preds.chunk(BIG_BATCH_SIZE),0)\n # reshape labels as (BIG_BATCH_SIZE, NUM_FOLDERS)\n labels_repeat = ch.stack(labels.repeat(NUM_FOLDERS).chunk(NUM_FOLDERS),1)\n correct = preds_repeat == labels_repeat\n # for each image, check if the predictions are correct across all attack folders\n total_correct += ch.all(correct,1).float().sum()\n total += preds_repeat.shape[0]\n # find norm of difference between the attack and original\n norms = (intermediates-originals.view(originals.shape[0], -1)).float().pow(2).sum(-1).pow(0.5)\n # reshape as (BIG_BATCH_SIZE, NUM_FOLDERS)\n norms = ch.stack(norms.chunk(BIG_BATCH_SIZE),0)\n # only count the attacks which are within the norm budget\n total_incorrect_inbds += ch.any((1-correct)*(norms<4),1).float().sum()\n print(total_correct/total, total_incorrect_inbds/total)\n \n except:\n return total, total_correct/total, total_incorrect_inbds/total\n\ntotal, a,b = accuracy()\nprint(\"Total %f | Adversarial accuracy %f | Adversarial in-bounds accuracy %f\" % (total,a.item(), 1-b.item()))\n","repo_name":"ajiljalal/manifold-defense","sub_path":"defense-gan-break/break/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":5170,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"29"} +{"seq_id":"32945119199","text":"# Final Project: Quiz Application with Microservices\n# Date: 29-May-2023\n# Authors:\n# A01746664 Eduardo Joel Cortez Valente\n# A01751587 Paulo Ogando Gulias \n# A01745865 José Ángel García Gómez \n# A01745419 José Luis Madrigal Sánchez\n\n\n'''\nThis file consists of the definition of the UserModel class that has all the functions that are used to interact with the User database.\nIt also consists of the code needed to connect to the dynamoDB database using the\nconfigurations set in config.py file.\n'''\n\n\n# Importing libraries\nfrom boto3 import resource\nimport config as config\nimport time\nfrom decimal import Decimal\nfrom operator import itemgetter\n\n\nAWS_ACCESS_KEY_ID = config.AWS_ACCESS_KEY_ID\nAWS_SECRET_ACCESS_KEY = config.AWS_SECRET_ACCESS_KEY\nAWS_SESSION_TOKEN = config.AWS_SESSION_TOKEN\nREGION_NAME = config.REGION_NAME\n\n\nclass UserModel ():\n __tablename__ = 'UserQuizzApp'\n dynamodb_client = resource(\n service_name='dynamodb',\n aws_access_key_id=AWS_ACCESS_KEY_ID,\n aws_secret_access_key=AWS_SECRET_ACCESS_KEY,\n aws_session_token=AWS_SESSION_TOKEN,\n region_name=REGION_NAME\n )\n\n\n def __init__(self):\n self.UserTable = self.create_table_user()\n\n\n def create_table_user(self):\n if (not self.dynamodb_client.Table(self.__tablename__)):\n self.dynamodb_client.create_table(\n TableName=self.__tablename__, \n KeySchema=[\n {\n 'AttributeName': 'id',\n 'KeyType': 'HASH'\n }\n ],\n AttributeDefinitions=[\n {\n 'AttributeName': 'id',\n 'AttributeType': 'N' \n }\n ],\n ProvisionedThroughput={\n 'ReadCapacityUnits': 10,\n 'WriteCapacityUnits': 10\n }\n )\n return self.dynamodb_client.Table(self.__tablename__)\n\n\n def read_users(self):\n response = self.UserTable.response = self.UserTable.scan()\n return response\n\n\n def write_to_user(self, name, points):\n id = Decimal(str(time.time()).replace('.', ''))\n response = self.UserTable.put_item(\n Item={\n # id generated is a timestamp kind of id. \n # So, numbers with higher values are newer\n 'id': id, \n 'name': name,\n 'points': points,\n }\n )\n return response\n\n\n def get_top_10_users(self):\n response = self.UserTable.scan()\n items = response['Items']\n # Sort the items in the list descending by id. (The id itself is a timestamp)\n items.sort(key=itemgetter('id'), reverse=True)\n # Sort the items in the list descending by points\n items.sort(key=itemgetter('points'), reverse=True)\n # Get the top 10 items\n top_10_items = items[:10]\n response['Items'] = top_10_items\n return response\n","repo_name":"EduardoCorVal/QuizzApp","sub_path":"backend/UserModel.py","file_name":"UserModel.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31270083178","text":"import numpy as np\nimport os\nimport csv\nimport psutil\nfrom PIL import Image\n\n\nclass TrainsetGenerator:\n def __init__(self):\n pass\n\n\nclass ImagesetGenerator(TrainsetGenerator):\n # Booleans Variables\n # To show image or not while processing the imagefile\n __image_show = True\n # To reshape image or not\n __image_reshape = True\n\n # Reshaping Configurations\n # New shape of Reshaping\n __image_std_length = 256\n __image_std_width = 256\n __image_std_channel = 3\n __image_std_shape = (__image_std_length, __image_std_width)\n\n # File directory\n __image_dir_root = str()\n __image_dir_ref = str()\n __csv_dir_root = str()\n\n # Record all the folders detected\n __classes_names = list()\n # Record all the image files detected in the folder\n __classes_images = dict()\n\n # Inner-work Variables\n __channel_r_name = ['R', 'r', 'RED', 'Red']\n __channel_g_name = ['G', 'g', 'GREEN', 'Green']\n __channel_b_name = ['B', 'b', 'BLUE', 'Blue']\n\n def __int__(self):\n pass\n\n ####################################################################################################################\n ''' User functions '''\n # Directory Setting #\n # Set the image root directory\n # Args : image_dir = a abspath to define where is your root folder of all image files\n # Return : None\n def set_image_root_dir(self, image_dir):\n if self.__ispath_valid(image_dir):\n self.__image_dir_root = image_dir\n return None\n\n # Set the csv output root directory\n # Args : dataset_dir = a abspath to define where is your root folder of csv output target folder\n # Return : None\n def set_csv_root_dir(self, dataset_dir):\n if self.__ispath_valid(dataset_dir):\n self.__csv_dir_root = dataset_dir\n return None\n\n # Set the standard shape in the image reshaping process\n # Args : length = the length of the image\n # width = the width of the image\n # channel = the number of color channel\n # Return : None\n def set_image_std(self, length, width, channel):\n if length > 0 and width > 0 and channel >= 1:\n self.__image_std_length = length\n self.__image_std_width = width\n self.__image_std_channel = channel\n else:\n raise Exception('ERROR : Invalid Standard Image Shape!')\n\n # Main process of the generator\n # Args : None\n # REturn : None\n def generate(self):\n if self.__isconfig_valid() is True:\n\n self.__get_all_folder()\n print(self.__classes_names)\n try:\n os.makedirs(self.__csv_dir_root)\n except FileExistsError:\n print('INFO : CSV Folder already exit. Continue.')\n for class_name in self.__classes_names:\n print(class_name)\n try:\n os.makedirs(self.__csv_dir_root + '/' + class_name)\n except FileExistsError:\n print('INFO : CSV Folder already exit. Continue.')\n '''\n for image_name in self.__classes_images[class_name]:\n self.__image_dir_ref = '/' + class_name + '/' + image_name + '.jpg'\n data = self.__read_rgb_from_image(self.__image_dir_root + self.__image_dir_ref)\n self.__data_to_csv(data)\n '''\n\n\n ####################################################################################################################\n ''' Inner-work functions '''\n # Read a single pixel data (RGB) from a image file\n # Return : numpy.array(shape=[3])\n def __read_pixel_from_image(self, image_dir, x, y):\n if self.__ispath_valid(image_dir):\n with Image.open(image_dir) as tempimage:\n if self.__image_show is True:\n tempimage.show()\n if self.__image_reshape is True:\n tempimage = tempimage.resize(self.__image_std_shape)\n r, g, b = tempimage.getpixel((x, y))\n result = np.array([r, g, b])\n return result\n\n # Read a single channel from a image file\n # Return : numpy.matrix(shape=[imagelength, imagewidth])\n def __read_channel_from_image(self, image_dir, channel_name):\n if self.__ispath_valid(image_dir):\n with Image.open(image_dir) as tempimage:\n\n if self.__image_show is True:\n tempimage.show()\n if self.__image_reshape is True:\n tempimage = tempimage.resize(self.__image_std_shape)\n\n if channel_name in self.__channel_r_name:\n r, g, b = tempimage.split()\n data = np.matrix(r)\n return data\n elif channel_name in self.__channel_g_name:\n r, g, b = tempimage.split()\n data = np.matrix(g)\n return data\n elif channel_name in self.__channel_b_name:\n r, g, b = tempimage.split()\n data = np.matrix(b)\n return data\n else:\n raise Exception('ERROR : Invalid Image Channel Name!')\n\n # Read image data from jpeg file\n # Return : numpy.matrix(shape=[imagelength, imagewidth, 3])\n def __read_rgb_from_image(self, image_dir):\n if self.__ispath_valid(image_dir):\n with Image.open(image_dir) as tempimage:\n if self.__image_show is True:\n tempimage.show()\n if self.__image_reshape is True:\n tempimage = tempimage.resize(self.__image_std_shape)\n\n if self.__image_reshape is True:\n data = np.zeros(shape=[self.__image_std_length, self.__image_std_width, self.__image_std_channel])\n for x in range(self.__image_std_length):\n for y in range(self.__image_std_width):\n r, g, b = tempimage.getpixel((x, y))\n data[x, y, 0] = r\n data[x, y, 1] = g\n data[x, y, 2] = b\n return data\n else:\n length, width = tempimage.size()\n data = np.zeros(shape=[length, width, 3])\n for x in range(length):\n for y in range(width):\n r, g, b = tempimage.getpixel((x, y))\n data[x, y, 0] = r\n data[x, y, 1] = g\n data[x, y, 2] = b\n return data\n\n # Save image to a csv file\n def __image_to_csv(self, image_dir):\n data = self.__read_rgb_from_image(image_dir)\n with open(self.__csv_dir_root + '/' + str(123) + '.csv', 'w', newline='') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=' ', quotechar='\\'', quoting=csv.QUOTE_MINIMAL)\n # Loop traverse all pixels\n\n def __data_to_csv(self, data):\n with open(self.__csv_dir_root + '/' + str(123) + '.csv', 'w', newline=''):\n pass\n\n\n\n ####################################################################################################################\n ''' Inner-tool functions '''\n # Check if it is a valid path\n # Return : Boolean\n @staticmethod\n def __ispath_valid(path):\n if os.path.exists(path):\n return True\n else:\n raise Exception('ERROR : Invalid Image Diration!')\n\n # Check if all configurations have been set correctly\n # Args : None\n # Return : None\n def __isconfig_valid(self):\n if self.__image_dir_root is str():\n raise Exception('ERROR : Directory remain unset! : Image root directory')\n elif self.__csv_dir_root is str():\n raise Exception('ERROR : Directory remain unset! : CSV root directory')\n else:\n return True\n\n # Get all the folder in the root folder\n # Args : None\n # Return : None\n def __get_all_folder(self):\n root = self.__image_dir_root\n dir_list = [item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item))]\n print(dir_list)\n self.__classes_name = dir_list\n\n # Get all image files in the folder\n # Args : None\n # Return : None\n def __get_all_image(self):\n root = self.__image_dir_root\n\n # Close the window built by Image.show() method (Pillow package)\n # Args : None\n # Return : None\n def __kill_image_window(self):\n if self.__image_show is True:\n for proc in psutil.process_iter():\n if proc.name() == \"display\":\n proc.kill()\n\n\n# Debug Script\nif __name__ == '__main__':\n ImagesetGen = ImagesetGenerator()\n ImagesetGen.set_image_root_dir('/home/celestial/Documents/PythonProject/ImagesetGenerator/TestImages')\n ImagesetGen.set_csv_root_dir('/home/celestial/Documents/PythonProject/ImagesetGenerator/TestCSV')\n ImagesetGen.set_image_std(256, 256, 3)\n ImagesetGen.generate()\n\n\n\n\n\n\n\n\n","repo_name":"CelestialPaler/ImagesetGenerator","sub_path":"ImagesetGenerator.py","file_name":"ImagesetGenerator.py","file_ext":"py","file_size_in_byte":9138,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"29"} +{"seq_id":"12340149680","text":"#!/usr/bin/env python3\n\n\"\"\"Get the latest stable version number of Python from FTP site.\"\"\"\n\nimport requests\nimport re\nfrom bs4 import BeautifulSoup\n\n\ndef parse(content):\n \"\"\"Find the Download Widget class.\"\"\"\n soup = BeautifulSoup(content, \"html.parser\")\n ftp_links = [a.text for a in soup.select('a')]\n regex = re.compile(r'(? Union[MindCard, None]:\n try:\n return mind_card.get(pk=pk)\n except MindCard.DoesNotExist:\n return None\n\n @staticmethod\n def change_position(card: MindCard, x: int, y: int):\n card.x_coord = x\n card.y_coord = y\n card.save()\n\n def connect_cards(self, mind_map: MindMap, edges: List[OrderedDict]):\n mind_edges = mind_map.mindedges_set.select_related('mind_map').all()\n mind_edges.delete()\n\n mind_cards = mind_map.mindcard_set.all()\n\n for edge in edges:\n # Получаем карточку из mind_map\n source = self.get_mind_card(mind_cards, edge['source'])\n if not source:\n continue\n\n # Проверка карты на Target(Таргет не имеет родителя)\n if source.type_card == 'T':\n # Если имеет то пропустить\n continue\n else:\n # Если не имеет то\n # Получить родительскую карточку\n target = self.get_mind_card(mind_cards, edge['target'])\n if target:\n # если родитель сущетсвует то имезменить\n source.mindedges_set.create(mind_map=mind_map, source=source, target=target.pk)\n else:\n # Иначе пропустить\n continue\n return\n","repo_name":"NoNameCompanyUniverse/right-tools-project","sub_path":"backend/src/rt_app/mind_maps/map/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"9087552404","text":"import os\nfrom socket import *\nimport _thread as th\ndef sendit():\n while True:\n data=bytes(input(),'utf-8')\n send.sendto(data,('192.168.1.7',13003))\ndef receive():\n while True:\n print('\\nhe: '+str(rec.recvfrom(1024)[0])[2:-1])\nsend=socket(AF_INET,SOCK_DGRAM)\nrec=socket(AF_INET,SOCK_DGRAM)\nrec.bind(('',13001))\nth.start_new_thread(receive,())\nsendit()\nrec.close()\nsend.close()\nos._exit(0)\n\n\n","repo_name":"Trevahok/CheatChat","sub_path":"multithreaded chat.py","file_name":"multithreaded chat.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35368021198","text":"import os\nimport sys\nimport daos_build\n\nImport('prereqs', 'env')\n\n# Keep versioned libs for now to avoid any conflict with 1.0\nCART_VERSION = \"4.7.0\"\n\ndef scons():\n \"\"\"Scons function\"\"\"\n\n env.Alias('install', '$PREFIX')\n\n env.Append(CCFLAGS=['-DCART_VERSION=\\\\\"' + CART_VERSION + '\\\\\"'])\n\n Export('env', 'prereqs', 'CART_VERSION')\n # generate targets in specific build dir to avoid polluting the source code\n SConscript('src/SConscript')\n SConscript('test/SConscript')\n\n env.Install('$PREFIX/etc', ['utils/memcheck-cart.supp',\n 'utils/fault-inject-cart.yaml'])\n\nif __name__ == \"SCons.Script\":\n scons()\n","repo_name":"21e8-ltd/daos","sub_path":"src/cart/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"7520490216","text":"from statistics import median\n\ndef nota(*num,sit=False):\n notas = {} \n notas[\"Maior\"] = max(num)\n notas[\"Menor\"] = min(num)\n notas[\"Total\"] = len(num) \n notas[\"Média\"] = sum(num)/len(num)\n if sit:\n if notas[\"Média\"] >= 7:\n notas[\"Situação\"] = 'Aprovado'\n else:\n notas[\"Situação\"] = 'Reprovado'\n return notas\n \n\nprint(nota(5.6, 4.2,5.3,6.4))\n\n\n\n","repo_name":"ursarah/projects_python","sub_path":"python_exercicios/questao105.py","file_name":"questao105.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"26757960487","text":"import os\nimport shutil\n\ndef create_folder_structure():\n base_directory = '/home/pi'\n folders = [\n 'cst8254/backup',\n 'cst8254/python',\n 'Linux/Labs/Lab1',\n 'Linux/Labs/Lab2',\n 'Linux/Labs/Lab3',\n 'Linux/Lectures/Week1',\n 'Linux/Lectures/Week2',\n 'Linux/Lectures/Week3'\n ]\n\n for folder in folders:\n full_path = os.path.join(base_directory, folder)\n os.makedirs(full_path, exist_ok=True)\n\n print(\"Folder structure created successfully!\")\n\nif __name__ == '__main__':\n create_folder_structure()\n","repo_name":"saltabasnihat/PixelForge","sub_path":"linux-folder-creation.py","file_name":"linux-folder-creation.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3641617652","text":"from django.shortcuts import render, HttpResponse, get_object_or_404\nfrom .models import Artist, Music, Comment\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom .serializers import ArtistSerializer, MusicSerializer, ArtistDetailSerializer, CommentSerializer, MusicDetailSerializer\n\nfrom IPython import embed\n\n# import json\n\n# 달라 써라 수정 삭제\n# Read Create Update Delete\n# GET POST PATCH DELETE\n\n\n\n# @api_view(['GET'])\n# def artist_lists(request):\n# artists = Artist.objects.all()\n# res_data = []\n# for artist in artists:\n# d = {\n# \"id\": artist.id, \n# \"name\": artist.name\n# }\n# res_data.append(d)\n \n# return HttpResponse(res_data)\n\n# # res_data: {'id': 1, 'name': 'Coldplay'}{'id': 2, 'name': 'Maroon5'}\n# # python 언어인 dict를 공용어 data로 만들어주어야 함\n# # 공용어로 바꾸다(직렬화, Serialization)\n# # 공용어 == string 으로 바꿔서 내보내는 것 => import json \n\n# @api_view(['GET'])\n# def artist_list(request):\n# artists = Artist.objects.all()\n# dataset = []\n# for artist in artists:\n# d = {\n# \"id\": artist.id, \n# \"name\": artist.name\n# }\n# dataset.append(d)\n# res_data = json.dumps(dataset)\n# return HttpResponse(res_data)\n\n# # 근데 데이터 많고 넘겨줄거 많고 하면 답이 없음\n# # model form과 유사하게 -> serializers.py\n\n@api_view(['GET'])\ndef artist_list(request):\n artists = Artist.objects.all()\n serializer = ArtistSerializer(artists, many=True)\n # embed()\n return Response(serializer.data)\n\n# In [1]: artists\n# Out[1]: , ]>\n# In [1]: serializer\n# Out[1]:\n# ArtistSerializer(, ]>):\n# name = CharField(style={'base_template': 'textarea.html'})\n\n\n@api_view(['GET'])\ndef artist_detail(request, artist_id):\n artist = get_object_or_404(Artist, id=artist_id)\n serializer = ArtistDetailSerializer(artist)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef music_list(request):\n musics = Music.objects.all()\n serializer = MusicSerializer(musics, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef music_detail(request, music_id):\n music = get_object_or_404(Music, id=music_id)\n serializer = MusicDetailSerializer(music)\n return Response(serializer.data)\n\n\n@api_view(['POST'])\ndef create_comment(request, music_id):\n music = get_object_or_404(Music, id=music_id)\n ser = CommentSerializer(data=request.data)\n if ser.is_valid(raise_exception=True):\n ser.save(music_id=music.id) # 저장완료. form과 유사하지만 다름, commit 아님\n return Response(ser.data) # 저장한 데이터를 보낸다\n\n\n# Postman -> POST : http://127.0.0.1:8001/api/v1/musics/1/comments/\n# => body - form-data - key: comment, value: blah\n# {\n# \"id\": 9,\n# \"content\": \"hihi\",\n# \"music_id\": 1\n# }\n# html은 사용자를 위한 것이지 서버에서는 사실 상관 없는 것.","repo_name":"JJayeee/TIL","sub_path":"01_HelloWorld/06_DJANGO_ADVANCED/05_API_SERVER/musics/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"25907315237","text":"from aws_cdk import aws_cognito as cognito\nfrom aws_cdk import aws_iam as iam\nfrom constructs import Construct\n\ndef construct_identity_pool(\n scope: Construct,\n resource_id_prefix: str,\n cognito_identity_providers: list = [],\n supported_login_providers: dict = {},\n developer_provider_name: str = None,\n **kwargs\n) -> (cognito.CfnIdentityPool, iam.Role, iam.Role):\n\n identity_pool = cognito.CfnIdentityPool(\n scope,\n resource_id_prefix + \"_identity_pool\",\n allow_unauthenticated_identities=True,\n cognito_identity_providers=cognito_identity_providers,\n supported_login_providers=supported_login_providers,\n developer_provider_name=developer_provider_name,\n )\n\n unauth_role = kwargs.get(\n \"unauth_role\",\n get_default_role_for_identity_pool(\n scope=scope,\n identity_pool_id=identity_pool.ref,\n role_resource_id_prefix=resource_id_prefix,\n auth=False,\n kwargs=kwargs,\n ),\n )\n\n auth_role = kwargs.get(\n \"auth_role\",\n get_default_role_for_identity_pool(\n scope=scope,\n identity_pool_id=identity_pool.ref,\n role_resource_id_prefix=resource_id_prefix,\n auth=True,\n kwargs=kwargs,\n ),\n )\n\n cognito.CfnIdentityPoolRoleAttachment(\n scope,\n resource_id_prefix + \"identity_pool_role_attach\",\n identity_pool_id=identity_pool.ref,\n roles={\"unauthenticated\": unauth_role.role_arn, \"authenticated\": auth_role.role_arn},\n )\n\n return identity_pool, auth_role, unauth_role\n\n\ndef get_default_role_condition(identity_pool_id: str, auth: bool = True,) -> dict:\n return {\n \"StringEquals\": {\"cognito-identity.amazonaws.com:aud\": identity_pool_id},\n \"ForAnyValue:StringLike\": {\n \"cognito-identity.amazonaws.com:amr\": \"authenticated\" if auth else \"unauthenticated\"\n },\n }\n\n\ndef get_default_role_policy(auth: bool = True, kwargs={}) -> iam.PolicyStatement:\n return kwargs.get(\n \"identity_pool_{}_role_policy\".format(\"auth\" if auth else \"unauth\"),\n iam.PolicyStatement(\n effect=iam.Effect.ALLOW,\n actions=[\"mobileanalytics:PutEvents\", \"cognito-sync:*\", \"cognito-idenity:*\"],\n resources=[\"*\"],\n ),\n )\n\n\ndef get_default_role_for_identity_pool(\n scope: Construct,\n identity_pool_id: str,\n role_resource_id_prefix: str,\n auth: bool = True,\n kwargs={},\n) -> iam.Role:\n role_policy = get_default_role_policy(auth=auth, kwargs=kwargs)\n role_condition = get_default_role_condition(identity_pool_id=identity_pool_id, auth=auth)\n role = iam.Role(\n scope,\n role_resource_id_prefix + (\"auth\" if auth else \"unauth\"),\n assumed_by=iam.FederatedPrincipal(\n \"cognito-identity.amazonaws.com\", role_condition, \"sts:AssumeRoleWithWebIdentity\"\n ),\n )\n role.add_to_policy(role_policy)\n return role\n","repo_name":"aws-amplify/amplify-ci-support","sub_path":"src/integ_test_resources/common/auth_utils.py","file_name":"auth_utils.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"29"} +{"seq_id":"15657212883","text":"import discord\r\nfrom discord.ext import commands\r\n\r\nimport sys\r\nsys.path.insert(0, 'D:/Python Coding/Discord Bots/Discord Tea/')\r\nfrom utils import rating_data\r\n\r\nclass FeedbackCog:\r\n\r\n def __init__(self, client):\r\n self.client = client\r\n\r\n @commands.command()\r\n async def feedback(self, ctx, *, comment):\r\n feedback_log = discord.utils.get(self.client.get_all_channels(), id=524769713214062612)\r\n\r\n await ctx.send(\":white_check_mark: **| Your feedback has been sent. Thanks, {}!**\".format(ctx.author.name))\r\n await feedback_log.send(\":star: **| Received feedback from `{}`: `{}`**\".format(ctx.author, comment))\r\n\r\n @commands.command()\r\n async def rate(self, ctx, rating):\r\n feedback_log = discord.utils.get(self.client.get_all_channels(), id=524769713214062612)\r\n stars = ''\r\n\r\n try:\r\n rating = int(rating)\r\n except:\r\n await ctx.send(\":no_entry_sign: **| Your rating must be between 1 and 5 and cannot be a decimal!**\")\r\n return\r\n\r\n if rating > 5 or rating < 1:\r\n await ctx.send(\":no_entry_sign: **| Your rating must be between 1 and 5 and cannot be a decimal!**\")\r\n return\r\n\r\n for i in range (0, rating):\r\n stars += ':star:'\r\n await ctx.send(\":star: **| You rated this service {}! Thanks for your feedback!**\".format(stars))\r\n await feedback_log.send(\":star: **| Received rating from `{}`: {}**\".format(ctx.author, stars))\r\n rating_data.add_rating(rating)\r\n\r\n\r\ndef setup(client):\r\n client.add_cog(FeedbackCog(client))\r\n","repo_name":"Lumiobyte/DiscordTea1","sub_path":"Discord Tea/cogs/feedback.py","file_name":"feedback.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20596825003","text":"#\r\n# LINMA2990 - Master Thesis\r\n# The mathematics of Tennis Ranking: Game outcome prediction by low-rank methods\r\n#\r\n# Experiment: Comparison between all methods (Chapter 4)\r\n# \r\n# Bastien Massion\r\n# Created on 06/06/2022\r\n#\r\n# Last version on 06/06/2022\r\n#\r\n\r\n\r\nimport numpy as np\r\n\r\n#Import data\r\nfrom Data_thesis import *\r\n\r\n#Select data\r\nfrom Selection_thesis import *\r\nfrom Selection_tensor_thesis import *\r\n\r\n#Manipulate data\r\nfrom Statistics_thesis import *\r\n\r\n#Solving optimization problem\r\nfrom Optimization_thesis import *\r\nfrom Optimization_levels_thesis import *\r\n\r\n#Compute error metrics\r\nfrom Error_thesis import *\r\nfrom Error_tensor_thesis import *\r\n\r\n#Plotting\r\nfrom Plotting_thesis import *\r\n\r\n\r\n######## IMPORTING DATA FROM DATASET\r\n\r\n(data, header, data_types, data_values, data_categories, players, n_players, players_indices) = manageData('../Data/Data.csv')\r\n\r\n\r\n######## DATA SELECTION\r\n\r\nextra_dimension_name = 'Tournament'\r\nnumber_players = 50\r\ntesting_percentage = 30.0\r\nsorting_criterion = \"activity\"\r\n\r\n\r\n######## COMPARISON EXPERIMENT\r\n\r\n# CONSTRAINTS PARAMETERS\r\n\r\nin_range = True\r\nadd_to_one = True\r\ndiagonal_half = True\r\nclipping = True\r\n\r\nprobability_model = (\"uniform\", None)\r\nrating_model = (\"logistic\", 1)\r\n\r\n# METHODS TO COMPARE\r\n\r\nto_compare_completion = [(\"SDP_NNM\",), (\"SoftImpute\", 5.0), (\"iterative_SVD\", 2), (\"lmafit\", 2),\r\n (\"kNN\", 10), (\"LASSO\", 5.0), (\"WLASSO\", 5.0), (\"columns_mean\",), (\"rows_mean\",)]\r\nto_compare_MAP_P = [(\"MAP_NNM\", 5.0)]\r\nto_compare_MAP_E = [(\"Eratings\", 2, 10, None, 20)]\r\nto_compare = to_compare_completion + to_compare_MAP_P + to_compare_MAP_E\r\n\r\n\r\nn_comparisons_completion = len(to_compare_completion)\r\nn_comparisons_MAP_P = len(to_compare_MAP_P)\r\nn_comparisons_MAP_E = len(to_compare_MAP_E)\r\nn_comparisons = len(to_compare)\r\n\r\n# SEASONS TO COMPARE ON\r\n\r\nseasons = ['2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013','2014','2015','2016']\r\nn_seasons = len(seasons)\r\n\r\ncompletion_time = np.zeros((n_comparisons, n_seasons))\r\naccuracy = np.zeros((n_comparisons, n_seasons))\r\n\r\nfor i in range(n_seasons):\r\n season = seasons[i]\r\n limit_dates = ['01/01/' + season, '31/12/' + season]\r\n \r\n j_tot = 0\r\n \r\n ######## MATRIX COMPLETION TECHNIQUES ########\r\n \r\n train_data, test_data, train_confrontation_matrix, test_confrontation_matrix, train_selected_omega, test_selected_omega, selected_players, selected_players_indices, selected_n_players = selectingData(data, players, players_indices, header, testing_percentage = testing_percentage, sorting_criterion = sorting_criterion, number_players = number_players, limit_dates = limit_dates)\r\n \r\n # TRAIN PROBABILITY MATRIX\r\n p_bar_train = createProbabilityMatrix(train_confrontation_matrix,\r\n estimator = \"MAP\", probability_model = (\"uniform\", None), \r\n unknown_values = np.nan, diagonal_values = np.nan)\r\n \r\n # TEST PROBABILITY MATRIX\r\n p_bar_test = createProbabilityMatrix(test_confrontation_matrix, \r\n estimator = \"MAP\", probability_model = (\"uniform\", None), \r\n unknown_values = np.nan, diagonal_values = np.nan)\r\n\r\n \r\n for j in range(n_comparisons_completion):\r\n \r\n completion_method = to_compare_completion[j]\r\n print(\"METHOD \", completion_method[0])\r\n p_matrix, completion_time[j_tot][i] = complete(p_bar_train, train_selected_omega, train_confrontation_matrix,\r\n completion_method,\r\n in_range = in_range, add_to_one = add_to_one, diagonal_half = diagonal_half, clipping = clipping)\r\n \r\n _,_,_, accuracy[j_tot][i], _,_,_, _,_,_,_ = errorMetrics(p_matrix, p_bar_test, test_selected_omega, test_confrontation_matrix, completion_method, in_range = in_range, add_to_one = add_to_one, diagonal_half = diagonal_half, clipping = clipping)\r\n \r\n j_tot += 1\r\n \r\n ######## MAXIMUM A POSTERIORI ON P TECHNIQUES ########\r\n \r\n # NO MATRICES TO COMPLETE \r\n p_bar_train = None\r\n p_bar_test = None\r\n \r\n for j in range(n_comparisons_MAP_P):\r\n \r\n creation_method = to_compare_MAP_P[j]\r\n print(\"METHOD\", creation_method[0])\r\n p_matrix, completion_time[j_tot][i] = create(train_confrontation_matrix, creation_method, \r\n estimator = \"MAP\", probability_model = (\"uniform\", None), \r\n in_range = in_range, add_to_one = add_to_one, diagonal_half = diagonal_half, clipping = clipping)\r\n \r\n _,_,_, accuracy[j_tot][i], _,_,_, _,_,_,_ = errorMetrics(p_matrix, p_bar_test, test_selected_omega, test_confrontation_matrix, completion_method, in_range = in_range, add_to_one = add_to_one, diagonal_half = diagonal_half, clipping = clipping)\r\n \r\n j_tot += 1\r\n \r\n ######## MAXIMUM A POSTERIORI ON E TECHNIQUES ######## \r\n \r\n train_data, test_data, train_confrontation_tensor, test_confrontation_tensor, train_selected_omega, test_selected_omega, selected_players, selected_players_indices, selected_n_players, selected_extra_dimension_values, selected_extra_dimension_indices, selected_n_extra_dimension = selectingDataTensor(data, players, players_indices, extra_dimension_name, header, data_values, testing_percentage = testing_percentage, sorting_criterion = sorting_criterion, number_players = number_players, limit_dates = limit_dates)\r\n \r\n # NO MATRICES TO COMPLETE \r\n p_bar_train = None\r\n p_bar_test = None\r\n \r\n for j in range(n_comparisons_MAP_E):\r\n creation_method = to_compare_MAP_E[j]\r\n print(\"METHOD \", creation_method[0])\r\n \r\n p_tensor, e_matrix, _, _, completion_time[j_tot][i] = createTensor(train_confrontation_tensor, creation_method, \r\n rating_model = rating_model, \r\n in_range = in_range, add_to_one = add_to_one, diagonal_half = diagonal_half, clipping = clipping)\r\n \r\n _,_,_, accuracy[j_tot][i], _,_,_,_,_,_,_ = errorMetricsTensor(p_tensor, e_matrix, p_bar_test, test_confrontation_tensor, creation_method, in_range = in_range, add_to_one = add_to_one, diagonal_half = diagonal_half, clipping = clipping)\r\n \r\n j_tot += 1\r\n\r\n\r\nplotComparisonSeasons(seasons, accuracy, to_compare) \r\n\r\n","repo_name":"massionb/Master_thesis_Bastien_Massion","sub_path":"Experiment_4_Comparison.py","file_name":"Experiment_4_Comparison.py","file_ext":"py","file_size_in_byte":6616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"42371452166","text":"\"\"\"\nGreedy Approach\n\nWe will do the two-pointer approach, Initialize the first pointer to the start of str1 and \nthe second pointer to the start of the str2.\n\nNow increase the first pointer till the character pointed by the first pointer in str1 matches \nthe character at the second pointer in str2. And the number of character which did not match should \nbe placed at the end of str1. Therefore increase our answer by how many times we needed to \nincrease the first pointer.\n\nNow character pointed by both the pointer is the same so simply increase both pointers as they are same. \nAnd perform this while both the pointer do not exhaust the str1 and str2 respectively.\n\nOne thing to note is that all the characters which did not match would be placed at the end optimally so \nthat the cost will be equal to the unmatched characters with the prefix of str2.\n\nTime Complexity:\n O(N+M) where N is the size of the first string and M is the size of the second string.\n\nWe are traversing both the strings only once.Thus time complexity is O(N+M). \n\"\"\"\nfrom sys import stdin,setrecursionlimit\nsetrecursionlimit(10**7)\nfrom collections import defaultdict\n\ndef minCostToGivenString(str1, str2) :\n\n freq_map = defaultdict(int)\n\n # check if chars in str1 match str2\n\n for char in str1:\n freq_map[char] += 1\n\n for char in str2:\n freq_map[char] -= 1\n\n for key in freq_map.keys():\n if freq_map[key] != 0:\n return -1\n\n # Initialize two pointers\n i,j = 0,0\n moves = 0\n\n while i < len(str1) and j < len(str2):\n\n # If both chars are equal move both pointers ahead\n if str1[i] == str2[j]:\n i += 1\n j += 1\n \n # both char not equal move i till it's equal to j\n else:\n i += 1\n moves += 1\n \n return moves\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#taking inpit using fast I/O\ndef takeInput() :\n str1 = input().strip()\n str2 = input().strip()\n \n return str1, str2\n\n\n#main\nt = int(input().strip())\nfor i in range(t) :\n\n str1, str2 = takeInput()\n print(minCostToGivenString(str1,str2))","repo_name":"S1LV3RJ1NX/CodingNinjas-DSA","sub_path":"03 - Basic Algorithms/09 - convert_string.py","file_name":"09 - convert_string.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"20065141032","text":"# general imports\nimport gradio as gr\nfrom PIL import Image\n\n# helper files\nfrom src.auto_blurring import groundedSAM, maskRCNN\n\n# link to the example images\nexample_images = [\n \"examples/entrance/0a01ffc9b28020381ca7396a57bcca3f_image_entrance_1.jpg\",\n \"examples/parking/0a73189e6a9160bfb31434117b793fba_image_parking_1.jpg\",\n \"examples/parking/0b730c20b8a40e2e0bac3213b6cc3088_image_parking_1.jpg\",\n]\n\n# load models\nmethod1 = maskRCNN()\nmethod2 = groundedSAM()\n\n\ndef process_image(img: str, model_choice: str = \"maskRCNN\") -> Image.Image:\n \"\"\"Wrapper function to process the image with the chosen anonimization model.\n\n Input:\n - img : the image\n - model_choice : the chosen model (either groundedSAM or maskRCNN)\n \"\"\"\n if model_choice == \"groundedSAM\":\n output_img = method2(img)\n elif model_choice == \"maskRCNN\":\n output_img = method1(img)\n else:\n output_img = Image.open(img)\n return output_img\n\n\n# Gradio interface of the demo\nwith gr.Blocks(\n title=\"Auto-blurring\",\n theme=gr.themes.Soft(primary_hue=\"emerald\"),\n css=\"body {background-image: \\\n url('https://dataroots.io/assets/logo/symbol-green.png'); \\\n background-size: 120px; background-repeat: round;}\",\n) as demo:\n gr.Markdown(\n \"\"\"\n

Demo of the first project: Auto-blurring

\n

developed by Dataroots

\n

for more info: Sophie De Coppel \\\n (sophie.decoppel@dataroots.io)
\n \"\"\"\n )\n\n # Radio button to choose the anonimization model\n model_choice = gr.Radio(\n [\"maskRCNN\", \"groundedSAM\"], value=\"maskRCNN\", label=\"Model\"\n )\n\n # Input and output block for the images\n with gr.Column():\n input_img = gr.Image(type=\"filepath\", label=\"Image\")\n go_bttn = gr.Button(\"Anonymize\")\n output_img = gr.Image(label=\"Anonimized image\")\n\n go_bttn.click(\n process_image, inputs=[input_img, model_choice], outputs=output_img\n )\n\n # Example images\n gr.Examples(\n examples=example_images,\n inputs=input_img,\n outputs=output_img,\n fn=process_image,\n cache_examples=True,\n )\n\nif __name__ == \"__main__\":\n demo.launch(server_name=\"0.0.0.0\", server_port=7860)\n","repo_name":"onwheelsapp/Amai-","sub_path":"autoblurring/docker/frontend/gradio_app.py","file_name":"gradio_app.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13671078373","text":"from typing import TYPE_CHECKING\n\nfrom pyconnectwise.endpoints.base.connectwise_endpoint import ConnectWiseEndpoint\nfrom pyconnectwise.endpoints.manage.ServiceLocationsCountEndpoint import ServiceLocationsCountEndpoint\nfrom pyconnectwise.endpoints.manage.ServiceLocationsIdEndpoint import ServiceLocationsIdEndpoint\nfrom pyconnectwise.endpoints.manage.ServiceLocationsInfoEndpoint import ServiceLocationsInfoEndpoint\nfrom pyconnectwise.interfaces import IGettable, IPaginateable, IPostable\nfrom pyconnectwise.models.manage import ServiceLocation\nfrom pyconnectwise.responses.paginated_response import PaginatedResponse\nfrom pyconnectwise.types import JSON, ConnectWiseManageRequestParams\n\nif TYPE_CHECKING:\n from pyconnectwise.clients.connectwise_client import ConnectWiseClient\n\n\nclass ServiceLocationsEndpoint(\n ConnectWiseEndpoint,\n IGettable[list[ServiceLocation], ConnectWiseManageRequestParams],\n IPostable[ServiceLocation, ConnectWiseManageRequestParams],\n IPaginateable[ServiceLocation, ConnectWiseManageRequestParams],\n):\n def __init__(self, client: \"ConnectWiseClient\", parent_endpoint: ConnectWiseEndpoint = None) -> None:\n ConnectWiseEndpoint.__init__(self, client, \"locations\", parent_endpoint=parent_endpoint)\n IGettable.__init__(self, list[ServiceLocation])\n IPostable.__init__(self, ServiceLocation)\n IPaginateable.__init__(self, ServiceLocation)\n\n self.count = self._register_child_endpoint(ServiceLocationsCountEndpoint(client, parent_endpoint=self))\n self.info = self._register_child_endpoint(ServiceLocationsInfoEndpoint(client, parent_endpoint=self))\n\n def id(self, _id: int) -> ServiceLocationsIdEndpoint:\n \"\"\"\n Sets the ID for this endpoint and returns an initialized ServiceLocationsIdEndpoint object to move down the chain.\n\n Parameters:\n _id (int): The ID to set.\n Returns:\n ServiceLocationsIdEndpoint: The initialized ServiceLocationsIdEndpoint object.\n \"\"\"\n child = ServiceLocationsIdEndpoint(self.client, parent_endpoint=self)\n child._id = _id\n return child\n\n def paginated(\n self, page: int, page_size: int, params: ConnectWiseManageRequestParams | None = None\n ) -> PaginatedResponse[ServiceLocation]:\n \"\"\"\n Performs a GET request against the /service/locations endpoint and returns an initialized PaginatedResponse object.\n\n Parameters:\n page (int): The page number to request.\n page_size (int): The number of results to return per page.\n params (dict[str, int | str]): The parameters to send in the request query string.\n Returns:\n PaginatedResponse[ServiceLocation]: The initialized PaginatedResponse object.\n \"\"\"\n if params:\n params[\"page\"] = page\n params[\"pageSize\"] = page_size\n else:\n params = {\"page\": page, \"pageSize\": page_size}\n return PaginatedResponse(\n super()._make_request(\"GET\", params=params), ServiceLocation, self, page, page_size, params\n )\n\n def get(\n self, data: JSON | None = None, params: ConnectWiseManageRequestParams | None = None\n ) -> list[ServiceLocation]:\n \"\"\"\n Performs a GET request against the /service/locations endpoint.\n\n Parameters:\n data (dict[str, Any]): The data to send in the request body.\n params (dict[str, int | str]): The parameters to send in the request query string.\n Returns:\n list[ServiceLocation]: The parsed response data.\n \"\"\"\n return self._parse_many(ServiceLocation, super()._make_request(\"GET\", data=data, params=params).json())\n\n def post(self, data: JSON | None = None, params: ConnectWiseManageRequestParams | None = None) -> ServiceLocation:\n \"\"\"\n Performs a POST request against the /service/locations endpoint.\n\n Parameters:\n data (dict[str, Any]): The data to send in the request body.\n params (dict[str, int | str]): The parameters to send in the request query string.\n Returns:\n ServiceLocation: The parsed response data.\n \"\"\"\n return self._parse_one(ServiceLocation, super()._make_request(\"POST\", data=data, params=params).json())\n","repo_name":"HealthITAU/pyconnectwise","sub_path":"src/pyconnectwise/endpoints/manage/ServiceLocationsEndpoint.py","file_name":"ServiceLocationsEndpoint.py","file_ext":"py","file_size_in_byte":4302,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"29"} +{"seq_id":"6570643053","text":"from lambda_decorators import (\n load_json_body, json_schema_validator,\n cors_headers, json_http_resp, dump_json_body)\nfrom src.entities.responses import Response\nfrom src.data.create_response import create_response\n\nrequest_schema = {\n 'type': 'object',\n 'properties': {\n 'body': {\n 'type': 'object',\n 'properties': {\n 'survey_id': {'type': 'string'},\n 'response_data': {'type': 'object'}\n },\n 'required': ['survey_id', 'response_data']\n }\n },\n 'required': ['body'],\n}\n\n\n@load_json_body # Doing this first is required for the schema to validate\n@json_schema_validator(request_schema=request_schema)\n@cors_headers\n@json_http_resp\n@dump_json_body\ndef handler(event, context):\n response = Response(**event['body'])\n result = create_response(response)\n if hasattr(result, 'error'):\n raise Exception(result['error'])\n return result.to_result()\n","repo_name":"fernando-mc/serverless-surveys","sub_path":"src/handlers/create_response_handler.py","file_name":"create_response_handler.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"29"} +{"seq_id":"71521233678","text":"# coding: utf-8\n\n\"\"\"\n NRF NFDiscovery Service\n\n NRF NFDiscovery Service. © 2020, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved. # noqa: E501\n\n The version of the OpenAPI document: 1.1.0.alpha-4\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom openapi_client.configuration import Configuration\n\n\nclass AfEventExposureData(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'af_events': 'list[AfEvent]',\n 'af_ids': 'list[str]',\n 'app_ids': 'list[str]'\n }\n\n attribute_map = {\n 'af_events': 'afEvents',\n 'af_ids': 'afIds',\n 'app_ids': 'appIds'\n }\n\n def __init__(self, af_events=None, af_ids=None, app_ids=None, local_vars_configuration=None): # noqa: E501\n \"\"\"AfEventExposureData - a model defined in OpenAPI\"\"\" # noqa: E501\n if local_vars_configuration is None:\n local_vars_configuration = Configuration()\n self.local_vars_configuration = local_vars_configuration\n\n self._af_events = None\n self._af_ids = None\n self._app_ids = None\n self.discriminator = None\n\n self.af_events = af_events\n if af_ids is not None:\n self.af_ids = af_ids\n if app_ids is not None:\n self.app_ids = app_ids\n\n @property\n def af_events(self):\n \"\"\"Gets the af_events of this AfEventExposureData. # noqa: E501\n\n\n :return: The af_events of this AfEventExposureData. # noqa: E501\n :rtype: list[AfEvent]\n \"\"\"\n return self._af_events\n\n @af_events.setter\n def af_events(self, af_events):\n \"\"\"Sets the af_events of this AfEventExposureData.\n\n\n :param af_events: The af_events of this AfEventExposureData. # noqa: E501\n :type: list[AfEvent]\n \"\"\"\n if self.local_vars_configuration.client_side_validation and af_events is None: # noqa: E501\n raise ValueError(\"Invalid value for `af_events`, must not be `None`\") # noqa: E501\n\n self._af_events = af_events\n\n @property\n def af_ids(self):\n \"\"\"Gets the af_ids of this AfEventExposureData. # noqa: E501\n\n\n :return: The af_ids of this AfEventExposureData. # noqa: E501\n :rtype: list[str]\n \"\"\"\n return self._af_ids\n\n @af_ids.setter\n def af_ids(self, af_ids):\n \"\"\"Sets the af_ids of this AfEventExposureData.\n\n\n :param af_ids: The af_ids of this AfEventExposureData. # noqa: E501\n :type: list[str]\n \"\"\"\n\n self._af_ids = af_ids\n\n @property\n def app_ids(self):\n \"\"\"Gets the app_ids of this AfEventExposureData. # noqa: E501\n\n\n :return: The app_ids of this AfEventExposureData. # noqa: E501\n :rtype: list[str]\n \"\"\"\n return self._app_ids\n\n @app_ids.setter\n def app_ids(self, app_ids):\n \"\"\"Sets the app_ids of this AfEventExposureData.\n\n\n :param app_ids: The app_ids of this AfEventExposureData. # noqa: E501\n :type: list[str]\n \"\"\"\n\n self._app_ids = app_ids\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, AfEventExposureData):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, AfEventExposureData):\n return True\n\n return self.to_dict() != other.to_dict()\n","repo_name":"H21lab/5GC_build","sub_path":"Examples/python_client/openapi_client/com/h21lab/TS29510_Nnrf_NFDiscovery/handler/af_event_exposure_data.py","file_name":"af_event_exposure_data.py","file_ext":"py","file_size_in_byte":4988,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"29"} +{"seq_id":"9354553570","text":"#!/usr/bin/env python2.7\n# -*- coding: utf-8 -*-\n# Run this with python2.7 or python3.\n##############################################################################\n\"\"\"Customizer Python Installer\"\"\"\n##############################################################################\n# Welcome to Customizer. This installer should execute on all platforms.\n# However, it only supports linux. Windows and Apple users will be warded off.\nfrom __future__ import print_function # Python3 behavior by default\nimport os\nimport sys\nimport errno\nimport platform\nimport webbrowser\nimport argparse\nimport json\n# We need to get the DEVNULL object from somewhere.\n# first we'll try python2 with subprocess32, then python3's subprocess,\n# finally resorting to python2's subprocess and simply opening devnull.\ntry:\n import subprocess32 as subprocess # python2 with subprocess32\n from subprocess32 import DEVNULL\nexcept ImportError:\n subprocess32 = None\ntry:\n from subprocess import DEVNULL # python3\nexcept ImportError:\n DEVNULL = open(os.devnull, 'wb') # python2 closes descriptor on exit.\nif subprocess32 is None:\n import subprocess # python2 without subprocess32 package\n# Using the python bindings, apt can do everything in one operation.\ntry:\n import apt # direct package manager access\nexcept ImportError:\n apt = None # Not a recent ubuntu?\n\n\nTHIS_TITLE = \"Customizer - Installer\"\nTHIS_VERSION = \"0.1.0\"\n\nINTRO = (\"=====================================\\n\"\n \"{0} {1}\\n\"\n \"=====================================\\n\")\n\nIS_WINDOWS = os.name == \"nt\" # Detect if we're running on windows.\nIS_MAC = sys.platform == \"darwin\" # Detect if we're running on apple.\nIS_64BIT = platform.machine().endswith(\"64\") # Detect if we're 64-bit.\nINTERACTIVE_MODE = not len(sys.argv) > 1 # CLI flags = non-interactive\nPYTHON2_OK = sys.version_info >= (2, 7) # Minimum version requirement\nPYTHON3_OK = sys.version_info >= (3, 3) # If python3 runs us\n\nGITHUB_ROOT = \"https://github.com\"\nGITHUB_RAW = \"https://raw.githubusercontent.com\"\n\nBUILD_DEPS = [\"build-essential\", \"debhelper\"]\n\nRUNTIME_DEPS = [\"squashfs-tools\", \"xorriso\", \"x11-xserver-utils\",\n \"xserver-xephyr\", \"qemu-kvm\", \"policykit-1\",\n \"hicolor-icon-theme\", \"isolinux\"]\n\nGIT_REPOS = {\n \"development\" : \"kamilion/customizer/tree/development\",\n \"stable\" : \"kamilion/customizer/tree/stable\",\n \"precise\" : \"kamilion/customizer/tree/precise\",\n \"master\" : \"kamilion/customizer\",\n \"oldstable\" : \"clearkimura/Customizer\"\n}\n\nDEFAULT_REPO = \"master\" # a key from the dict above.\n\nif not os.path.isfile('installer.json'):\n with open('installer.json', 'w') as CONFIG_FILE:\n CONFIGURATION_DATA = {}\n CONFIGURATION_DATA[\"current_repo\"] = DEFAULT_REPO\n json.dump(CONFIGURATION_DATA, CONFIG_FILE)\n\nwith open('installer.json', 'r') as CONFIG_FILE:\n CONFIGURATION_DATA = json.load(CONFIG_FILE)\n\n\ndef switch_branch(branchname):\n \"\"\"\n Switches branches on a git-based install.\n \"\"\"\n try:\n code = subprocess.call((\"git\", \"checkout\", branchname))\n except OSError as errmsg:\n if errmsg.errno == errno.ENOENT:\n print(\"\\nError: Git not found. It's either not installed or \"\n \"not in the PATH environment variable like expected.\")\n return\n if code == 0:\n print(\"\\nBranch has been switched to: {0}\".format(branchname))\n else:\n print(\"\\nCustomizer could not update properly. If this is caused\"\n \" by edits you have made to the code you can try the repair\"\n \" option from the Maintenance submenu\")\n\n\ndef perform_git_install(use_pyqt5):\n \"\"\"\n Performs a git-based install.\n \"\"\"\n if not IS_ROOT:\n root_warning()\n if use_pyqt5:\n if PYTHON3_OK:\n run_cmd = (\"make\", \"PYQT=5\", \"PYTHON=python3\")\n else:\n run_cmd = (\"make\", \"PYQT=5\")\n else:\n if PYTHON3_OK:\n run_cmd = (\"make\", \"PYTHON=python3\")\n else:\n run_cmd = (\"make\")\n try:\n code = subprocess.call(run_cmd)\n except OSError as errmsg:\n if errmsg.errno == errno.ENOENT:\n print(\"\\nError: 'make' not found. It's either not installed or \"\n \"not in the PATH environment variable like expected.\")\n return\n if code == 0:\n print(\"\\nCustomizer has been built from git.\")\n else:\n print(\"\\nCustomizer could not build properly. If this is caused\"\n \" by edits you have made to the code you can try the repair\"\n \" option from the Maintenance submenu\")\n if not IS_ROOT:\n code = subprocess.call((\"sudo\", \"make\", \"install\"))\n if code == 0:\n print(\"\\nCustomizer has been installed from git.\")\n else:\n print(\"The installation has failed.\")\n\n\ndef update_install():\n \"\"\"\n Updates a git-based install.\n \"\"\"\n try:\n code = subprocess.call((\"git\", \"pull\", \"--ff-only\"))\n except OSError as errmsg:\n if errmsg.errno == errno.ENOENT:\n print(\"\\nError: Git not found. It's either not installed or \"\n \"not in the PATH environment variable like expected.\")\n return\n if code == 0:\n print(\"\\nCustomizer has been updated\")\n else:\n print(\"\\nCustomizer could not update properly. If this is caused\"\n \" by edits you have made to the code you can try the repair\"\n \" option from the Maintenance submenu\")\n\n\ndef reset_install(config=False, git_reset=False):\n \"\"\"\n Resets the git-based install.\n \"\"\"\n if config:\n try:\n os.unlink(\"/etc/customizer.conf\")\n print(\"config file has been wiped.\")\n except OSError as errmsg:\n if errmsg.errno == errno.ENOENT:\n pass\n except Exception as errmsg:\n print(\"An error occured when trying to remove the config file: \"\n \"{}\".format(errmsg))\n\n if git_reset:\n code = subprocess.call((\"git\", \"reset\", \"--hard\"))\n if code == 0:\n print(\"Customizer has been restored to the last local commit.\")\n else:\n print(\"The repair has failed.\")\n\n\ndef build_apt_reqs(compat=False, build_deps=True):\n \"\"\"\n Returns a list of apt requirements given conditions.\n \"\"\"\n to_install = []\n to_install.extend(RUNTIME_DEPS)\n if compat:\n if PYTHON3_OK:# We were run from python3, prefer newer packages.\n to_install.append(\"python3-pyqt4\") # python3, pyqt4\n else:\n to_install.append(\"python-qt4\") # python2, classic qt4\n if build_deps:\n to_install.extend(BUILD_DEPS)\n to_install.extend([\"pyqt4-dev-tools\", \"qt4-linguist-tools\"])\n else:\n if PYTHON3_OK: # We were run from python3, prefer newer packages.\n to_install.append(\"python3-pyqt5\") # python3, pyqt5\n else:\n to_install.append(\"python-pyqt5\") # python2, pyqt5\n if build_deps:\n to_install.extend(BUILD_DEPS)\n to_install.extend([\"pyqt5-dev-tools\", \"qttools5-dev-tools\"])\n return to_install\n\n\ndef install_apt_reqs(compat=False, build_deps=True):\n \"\"\"\n Builds a list of requirements, then installs them.\n \"\"\"\n install_requirements = build_apt_reqs(compat, build_deps)\n install_apt_list(install_requirements)\n\n\ndef install_apt_list(package_names):\n \"\"\"\n Installs a list of packages via apt.\n \"\"\"\n cache = apt.cache.Cache()\n if IS_ROOT:\n cache.update()\n cache.open()\n for pkg_name in package_names:\n try:\n cache = install_apt_package(cache, cache[pkg_name])\n except KeyError as errmsg:\n print(\"Sorry, package installation failed [{0}]\".format(errmsg))\n # do packagey things\n if IS_ROOT:\n try:\n cache.commit()\n except Exception as errmsg:\n print(\"Sorry, package installation failed [{0}]\".format(errmsg))\n else:\n code = subprocess.call((\"sudo\", \"apt\", \"install\", package_names))\n if code == 0:\n print(\"\\nCustomizer requirements have been installed from apt.\")\n else:\n print(\"Sorry, we won't be able to manage packages unless\\n\"\n \"the installer is run as root. (perhaps with 'sudo !!' )\")\n cache.close()\n\n\ndef install_apt_package(cache, pkg):\n \"\"\"\n Marks a package for installation in the apt cache.\n \"\"\"\n if pkg.is_installed:\n print(\"{0} already installed\".format(pkg.fullname))\n return cache\n else:\n pkg.mark_install()\n return cache\n\n\ndef is_pyqt5_available():\n \"\"\"\n Verifies PyQt5 availability. Returns bool or None.\n \"\"\"\n try: # to import this empty module if installed.\n import PyQt4 # Contains a copyright notice for QT4.\n except ImportError:\n PyQt4 = None # PyQt4 is not currently installed.\n try: # to import this empty module if installed.\n import PyQt5 # Contains a copyright notice for QT5.\n except ImportError:\n PyQt5 = None # PyQt5 is not currently installed.\n if not PyQt4:\n return None\n elif not PyQt5:\n return False\n else:\n return True\n\n\ndef requirements_menu():\n \"\"\"\n Prints a apt requirements menu.\n \"\"\"\n clear_screen()\n while True:\n print(INTRO.format(THIS_TITLE, THIS_VERSION))\n print(\"Main requirements:\\n\")\n print(\"1. Try installing PyQt4 from apt\")\n print(\"2. Try installing PyQt5 from apt\")\n print(\"\\n0. Go back\")\n choice = user_choice()\n if choice == \"1\":\n install_apt_reqs(compat=True)\n wait()\n elif choice == \"2\":\n install_apt_reqs(compat=False)\n wait()\n elif choice == \"0\":\n break\n clear_screen()\n\n\ndef update_menu():\n \"\"\"\n Prints a update menu.\n \"\"\"\n clear_screen()\n while True:\n print(INTRO.format(THIS_TITLE, THIS_VERSION))\n root_warning()\n reqs = is_pyqt5_available()\n if reqs is None:\n status = \"No requirements installed\"\n elif reqs is False:\n status = \"GUI requirements installed (PyQT4)\"\n else:\n status = \"GUI requirements installed (PyQT5)\"\n print(\"Status: \" + status + \"\\n\")\n print(\"Update:\\n\")\n print(\"Customizer:\")\n print(\"1. Update Customizer (recommended)\")\n print(\"2. Update Customizer + update apt requirements\")\n print(\"\\nOthers:\")\n print(\"3. Update requirements\")\n print(\"\\n0. Go back\")\n choice = user_choice()\n if choice == \"1\":\n update_install()\n wait()\n elif choice == \"2\":\n update_install()\n print(\"Updating requirements...\")\n reqs = is_pyqt5_available()\n if reqs is not None:\n install_apt_reqs(compat=reqs)\n else:\n print(\"The requirements haven't been installed yet.\")\n wait()\n elif choice == \"3\":\n reqs = is_pyqt5_available()\n if reqs is not None:\n install_apt_reqs(compat=reqs)\n else:\n print(\"The requirements haven't been installed yet.\")\n wait()\n elif choice == \"0\":\n break\n clear_screen()\n\n\ndef repo_menu():\n \"\"\"\n Prints a repo menu.\n \"\"\"\n clear_screen()\n while True:\n print(INTRO.format(THIS_TITLE, THIS_VERSION))\n print(\"Current Repo: \" + CONFIGURATION_DATA[\"current_repo\"])\n current_repo_url = GITHUB_ROOT + \"/\" + GIT_REPOS[CONFIGURATION_DATA[\"current_repo\"]]\n print(\"Current Repo URL: \" + current_repo_url)\n reqs = is_pyqt5_available()\n if reqs is None:\n status = \"No requirements found to be installed\"\n elif reqs is False:\n status = \"GUI requirements installed (PyQT4)\"\n else:\n status = \"GUI requirements installed (PyQT5)\"\n print(\"Status: \" + status + \"\\n\")\n print(\"Update:\\n\")\n print(\"Customizer:\")\n print(\"1. Change Repository (A list will be printed)\")\n print(\"2. Visit repo in web browser\")\n print(\"3. Switch to selected repository\")\n print(\"\\n0. Go back\")\n choice = user_choice()\n if choice == \"1\":\n CONFIGURATION_DATA[\"current_repo\"] = change_repo_menu()\n with open('installer.json', 'w') as config_file:\n json.dump(CONFIGURATION_DATA, config_file)\n elif choice == \"2\":\n webbrowser.open(current_repo_url)\n elif choice == \"3\":\n print(\"Switching currently checked out branch...\")\n switch_branch(CONFIGURATION_DATA[\"current_repo\"])\n wait()\n elif choice == \"0\":\n break\n clear_screen()\n\n\ndef change_repo_menu():\n \"\"\"\n Prints a list of repos to choose from.\n \"\"\"\n clear_screen()\n while True:\n print(INTRO.format(THIS_TITLE, THIS_VERSION))\n repo = CONFIGURATION_DATA[\"current_repo\"]\n print(\"Current Repo: \" + repo)\n current_repo_url = GITHUB_ROOT + \"/\" + GIT_REPOS[repo]\n print(\"Current Repo URL: \" + current_repo_url)\n reqs = is_pyqt5_available()\n if reqs is None:\n status = \"No requirements found to be installed\"\n elif reqs is False:\n status = \"GUI requirements installed (PyQT4)\"\n else:\n status = \"GUI requirements installed (PyQT5)\"\n print(\"Status: \" + status + \"\\n\")\n print(\"Update:\\n\")\n print(\"Customizer:\")\n print(\"1. Switch to stable repo (recommended)\")\n print(\"2. Switch to master repo\")\n print(\"3. Switch to devel repo\")\n print(\"\\nOthers:\")\n print(\"4. Switch to ubuntu precise repo (Compatibility)\")\n print(\"5. Switch to old stable repo (Compatibility)\")\n print(\"\\n0. Go back\")\n choice = user_choice()\n if choice == \"1\":\n return \"stable\"\n elif choice == \"2\":\n return \"master\"\n elif choice == \"3\":\n return \"development\"\n elif choice == \"4\":\n return \"precise\"\n elif choice == \"5\":\n return \"oldstable\"\n else:\n return repo\n clear_screen()\n\n\ndef maintenance_menu():\n \"\"\"\n Prints a maintinence menu.\n \"\"\"\n clear_screen()\n while True:\n print(INTRO.format(THIS_TITLE, THIS_VERSION))\n root_warning()\n print(\"Maintenance:\\n\")\n print(\"1. Repair Customizer (discards code changes, keeps data intact)\")\n print(\"2. Wipe config file (all settings removed, keeps data intact)\")\n print(\"3. Factory reset (all of the above)\")\n print(\"\\n0. Go back\")\n choice = user_choice()\n if choice == \"1\":\n print(\"Any code modification you have made will be lost. Data/\"\n \"project settings will be left intact. Are you sure?\")\n if user_pick_yes_no():\n reset_install(git_reset=True)\n wait()\n elif choice == \"2\":\n print(\"Are you sure? This will wipe the config file, which \"\n \"contains all your project settings.\")\n if user_pick_yes_no():\n reset_install(config=True)\n wait()\n elif choice == \"3\":\n print(\"Are you sure? This will remove your installation \"\n \"data.\\nYou'll lose any modifications you have made.\\n\"\n \"There is no going back.\")\n if user_pick_yes_no():\n reset_install(config=True, git_reset=True)\n wait()\n elif choice == \"0\":\n break\n clear_screen()\n\n\ndef unix_which(program):\n \"\"\"\n Locates an installed tool on the filesystem if it's in the path.\n \"\"\"\n def is_exe(fpath):\n \"\"\"Is this executable?\"\"\"\n return os.path.isfile(fpath) and os.access(fpath, os.X_OK)\n\n fpath, fname = os.path.split(program)\n if fpath:\n if is_exe(program):\n return program\n else:\n for path in os.environ[\"PATH\"].split(os.pathsep):\n path = path.strip('\"')\n exe_file = os.path.join(path, program)\n if is_exe(exe_file):\n return exe_file\n\n return None\n\n\ndef run_app(interpreter):\n \"\"\"\n Starts the installed application with the interpreter specified.\n \"\"\"\n if interpreter is None: # This should never realistically happen\n raise RuntimeError(\"Couldn't find specified Python interpreter\")\n\n if is_pyqt5_available() is None:\n print(\"You don't have the requirements to start Customizer.\\n\"\n \"Install them from the interactive menu.\")\n if not INTERACTIVE_MODE:\n exit(1)\n\n cmd = (interpreter, unix_which(\"customizer-gui\"))\n\n print(\"Starting Customizer with {0}...\".format(cmd))\n while True:\n try:\n code = subprocess.call(cmd)\n except KeyboardInterrupt:\n code = 0\n break\n else:\n if code == 0:\n break\n\n print(\"Customizer has terminated. Exit code: %d\" % code)\n\n if INTERACTIVE_MODE:\n wait()\n\n\ndef clear_screen():\n \"\"\"\n Clears the screen before printing an interactive menu.\n \"\"\"\n if IS_WINDOWS:\n os.system(\"cls\")\n else:\n os.system(\"clear\")\n\n\ndef wait():\n \"\"\"\n Waits for a user to press a key to continue.\n \"\"\"\n if INTERACTIVE_MODE:\n user_choice_compat(\"Press enter to continue.\")\n\n\ndef user_choice_compat(prompt):\n \"\"\"\n Requests a alphanumeric response from the user.\n This function will hide python3's changing of input\n from raw_input in python2. The semantics are the same.\n \"\"\"\n if PYTHON3_OK:\n return input(prompt).strip()\n else:\n return raw_input(prompt).strip()\n\n\ndef user_choice(prompt=\"> \", lower=True):\n \"\"\"\n Requests a alphanumeric response from the user.\n This function will hide python3's changing of input\n from raw_input in python2. The semantics are the same.\n \"\"\"\n if lower:\n return user_choice_compat(prompt).lower()\n else:\n return user_choice_compat(prompt)\n\n\ndef user_pick_yes_no():\n \"\"\"\n Requests an affirmative or negative from the user.\n This function will hide python3's changing of input\n from raw_input in python2. The semantics are the same.\n Returns the user's choice.\n \"\"\"\n choice = None\n pick_yes = (\"yes\", \"y\")\n pick_no = (\"no\", \"n\")\n while choice not in pick_yes and choice not in pick_no:\n choice = user_choice(\"Yes/No > \")\n return choice in pick_yes\n\n\ndef remove_readonly(func, path):\n \"\"\"\n Attempt to remove read only flags before unlink with broad perms.\n Returns nothing.\n \"\"\"\n os.chmod(path, 0o755)\n func(path)\n\n\nif not IS_WINDOWS:\n if os.geteuid() != 0:\n IS_ROOT = False\n else:\n IS_ROOT = True\nelse:\n IS_ROOT = False\n\n\ndef root_warning():\n \"\"\"\n Print a helpful message when root access is unavailable.\n Returns nothing.\n \"\"\"\n if IS_ROOT:\n print(u\"Root account: is available.\")\n else:\n print(u\"Root account: is not available.\")\n print(\"Sorry, we won't be able to directly manage packages unless\\n\"\n \"the installer is run as root. (perhaps with 'sudo !!')\\n\"\n \"\\nHowever we'll try to sudo commands if possible.\\n\")\n\n\ndef platform_warning():\n \"\"\"\n Print a helpful message when an unsupported platform is used.\n Returns nothing.\n \"\"\"\n if IS_MAC:\n print(\"Sorry, your Macintosh platform isn't supported.\\n\\n\")\n elif IS_WINDOWS:\n print(\"Sorry, your Windows platform isn't supported.\\n\\n\")\n\n\ndef tool_check(tool, was_found=False, critical=False):\n \"\"\"\n Print a message when a tool is missing. Returns nothing.\n \"\"\"\n if was_found:\n print(u\"Tool: '{0}' is available.\".format(tool))\n else:\n tool_warning(tool, critical)\n\n\ndef tool_warning(tool, critical=False):\n \"\"\"\n Print a message when a tool is missing. Returns nothing.\n \"\"\"\n if not critical:\n print(u\"Tool: '{0}' is not available.\".format(tool))\n else:\n print(\"WARNING: '{0}' not found. This means that it's either not \"\n \"installed\\nor not in the PATH environment variable like \"\n \"requested in the guide.\\n\".format(tool))\n\n\ndef is_tool_installed(tool):\n \"\"\"\n Checks if a tool is installed. Returns bool.\n \"\"\"\n try:\n subprocess.call([tool, \"--version\"], stdout=DEVNULL,\n stdin=DEVNULL, stderr=DEVNULL)\n except OSError as errmsg:\n if errmsg.errno == errno.ENOENT:\n return False\n else:\n raise\n else:\n return True\n\n\nGIT_INSTALLED = is_tool_installed(\"git\") # We need git.\nPIP_INSTALLED = is_tool_installed(\"pip\") # pip is nice.\nAPT_INSTALLED = is_tool_installed(\"apt\") # New ubuntu?\nAPTGET_INSTALLED = is_tool_installed(\"apt-get\") # Ubuntu?\nDPKG_INSTALLED = is_tool_installed(\"dpkg\") # Debian-derived?\nRPM_INSTALLED = is_tool_installed(\"rpm\") # Redhat\n\n\ndef main_menu():\n \"\"\"\n Prints the main interactive menu.\n \"\"\"\n print(\"Verifying git installation...\")\n is_git_installation = os.path.isdir(\".git\")\n clear_screen()\n\n while True:\n print(INTRO.format(THIS_TITLE, THIS_VERSION))\n root_warning()\n if apt is None: # This will be printed users lacking apt.\n print(\"Customizer installer cannot interact with the\\n\"\n \"ubuntu package manager without the apt module!\\n\")\n if not is_git_installation:\n print(\"WARNING: It doesn't look like Customizer has been \"\n \"installed with git.\\nThis means that you won't \"\n \"be able to use this script to update or change\\n\"\n \"which repository you're currently using.\\n\")\n platform_warning()\n\n print(\"\\nTool status:\")\n tool_check(\"git\", GIT_INSTALLED) # Always check git.\n if not IS_WINDOWS or IS_MAC: # no further tools are needed.\n tool_check(\"dpkg\", DPKG_INSTALLED, critical=True)\n tool_check(\"apt-get\", APTGET_INSTALLED, critical=True)\n tool_check(\"apt\", APT_INSTALLED)\n tool_check(\"rpm\", RPM_INSTALLED, critical=False)\n\n print(\"\\n\")\n if not IS_WINDOWS or IS_MAC:\n print(\"1. Run Customizer\")\n print(\"2. Install Customizer\")\n print(\"3. Install GUI requirements with apt\")\n if GIT_INSTALLED and is_git_installation:\n print(\"4. Update from Github\")\n if GIT_INSTALLED:\n print(\"5. Change Repo or branch\")\n print(\"6. Maintenance (repair, reset...)\")\n print(\"\\n0. Quit\")\n choice = user_choice()\n\n if choice == \"1\":\n run_app(interpreter=sys.executable)\n elif choice == \"2\":\n perform_git_install(is_pyqt5_available())\n wait()\n elif choice == \"3\":\n requirements_menu()\n elif choice == \"4\":\n update_menu()\n elif choice == \"5\":\n repo_menu()\n elif choice == \"6\":\n maintenance_menu()\n elif choice == \"0\":\n break\n clear_screen()\n\n\ndef parse_cli_arguments():\n \"\"\"\n Parses CLI arguments and returns them.\n \"\"\"\n parser = argparse.ArgumentParser(description=\"Customizer's Installer\")\n parser.add_argument(\"--start\", \"-s\",\n help=\"Starts Customizer-gui\",\n action=\"store_true\")\n parser.add_argument(\"--update-customizer\",\n help=\"Updates customizer (git)\",\n action=\"store_true\")\n parser.add_argument(\"--update-build-reqs\",\n help=\"Updates build requirements\",\n action=\"store_true\")\n parser.add_argument(\"--update-reqs\",\n help=\"Updates runtime requirements\",\n action=\"store_true\")\n parser.add_argument(\"--repair\",\n help=\"Issues a git reset --hard\",\n action=\"store_true\")\n return parser.parse_args()\n\n\n# Functions from this file may be imported or executed from python.\n# The status of tools may be found after import by examining the module.\n# If we're executed as the main file, the following code is ran.\nif __name__ == '__main__':\n SCRIPT_PATH = os.path.abspath(__file__)\n SCRIPT_DIRNAME = os.path.dirname(SCRIPT_PATH)\n # Sets current directory to the script's\n os.chdir(SCRIPT_DIRNAME)\n CLI_ARGS = parse_cli_arguments()\n if not (PYTHON2_OK or PYTHON3_OK):\n print(\"Fatal Error: Customizer needs Python 2.7 or superior.\\n\"\n \"Installation of the minimum version is required.\\n\"\n \"Press enter to continue.\") # Really old pythons?\n if INTERACTIVE_MODE:\n wait()\n exit(1)\n if CLI_ARGS.repair:\n reset_install(git_reset=True)\n if CLI_ARGS.update_customizer:\n update_install()\n if CLI_ARGS.update_reqs:\n install_apt_reqs(compat=True)\n elif CLI_ARGS.update_build_reqs:\n install_apt_reqs(compat=False)\n if INTERACTIVE_MODE:\n main_menu()\n elif CLI_ARGS.start:\n run_app(interpreter=sys.executable)\n","repo_name":"kamilion/customizer","sub_path":"installer.py","file_name":"installer.py","file_ext":"py","file_size_in_byte":25313,"program_lang":"python","lang":"en","doc_type":"code","stars":298,"dataset":"github-code","pt":"29"} +{"seq_id":"24647954247","text":"class Product:\n def __init__(self):\n self.name=\"Iphone\"\n self.description=\"Its awesome\"\n self.amount = 700\n\n def __del__(self):\n print(\"Inside the destructor\")\n\n def display(self):\n print(self.name)\n print(self.description)\n print(self.amount)\n\np1=Product()\np1.display()\np1=None\n\np2=Product()\np2.display()\np2=None","repo_name":"SijoArun/leetcode","sub_path":"pythonProject/oopsconcept/oopsbasics.py","file_name":"oopsbasics.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34178226122","text":"def choosingProfession():\r\n jobs = []\r\n\r\n name = str(input('Hoşgeldiniz, lütfen isminizi giriniz : '))\r\n print(50*'*')\r\n print(f'Merhaba, {name} \\nSorulara Evet veya Hayır şeklinde cevap veriniz...')\r\n print(50*'*')\r\n pcEngineer = str(input('Donanım ve yazılım bilginiz var mı ? :'))\r\n print(50 * '*')\r\n softwareEngineer = str(input('Program yazmayı seviyormusunuz ? :'))\r\n print(50 * '*')\r\n electricEngineer = str(input('Elektrik ile uğraşmayı seviyormusunuz ? :'))\r\n print(50 * '*')\r\n teacher = str(input('Çocuklar / gençlerle vakit geçirmeyi ve birşeyler öğretmeyi seviyormusunuz ? :'))\r\n print(50 * '*')\r\n architect = str(input('Mimari eserler ile uğraşmayı seviyormusunuz ? :'))\r\n print(50 * '*')\r\n\r\n if pcEngineer == 'evet' :\r\n jobs.append('Bilgisayar Mühendisliği')\r\n if softwareEngineer == 'evet' :\r\n jobs.append('Yazılım Mühendisliği')\r\n if electricEngineer == 'evet' :\r\n jobs.append('Elektrik Mühendisliği')\r\n if teacher == 'evet' :\r\n jobs.append('Öğretmenlik')\r\n if architect == 'evet' :\r\n jobs.append('Mimarlık')\r\n\r\n print(f'Yatkın olabileceğiniz meslekler : {jobs}')\r\n\r\nchoosingProfession()","repo_name":"eymenyilmazturk/PythonCourseFinalProject","sub_path":"Career Choice Program.py","file_name":"Career Choice Program.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"7472608049","text":"from django.conf import settings\nfrom django.views.decorators.cache import cache_page\nfrom django.core.cache.backends.base import DEFAULT_TIMEOUT\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.views.generic import TemplateView\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import JsonResponse, HttpResponse\nfrom django.core.paginator import Paginator\nfrom django.views.decorators.csrf import ensure_csrf_cookie\nfrom django.db.models import Q\n\nfrom .models import Board, Topic, Post, Comment, IpModel, TopicRequest\nfrom .forms import (\n PostCreationForm,\n CommentCreationForm,\n PostSearchFormInTopic,\n TopicRequestForm,\n)\n\nCACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT)\n# @cache_page(CACHE_TTL)\n\ndef index(request):\n # Display all boards(higher Categories) with linked Topics.\n # to create cards according to the number of baords.\n \n boards = Board.objects.all()\n context = {\n 'boards': boards,\n 'range': range(boards.count())\n }\n return render(request, 'home.html', context)\n\n\ndef topic_view(request, slug):\n # This topic view might be better with generic ListView.\n # Display all posts from specific topic.\n # there is also 3rd party packages for pagination.\n \n topic = Topic.objects.get(slug=slug)\n posts = topic.post_set.all()\n \n post_search = PostSearchFormInTopic()\n \n if 'search' in request.GET:\n \n search = request.GET.get('search')\n select = request.GET.get('select')\n\n if select == 'title_post':\n queried_posts = posts.filter(\n Q(title__icontains=search) | Q(post__icontains=search))\n \n elif select == 'writer':\n queried_posts = posts.filter(Q(writer__username__icontains=search))\n \n else:\n pass\n \n # limit the posts objects to queried post from post search section\n posts = queried_posts \n \n paginator = Paginator(posts, 20)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n \n context = {\n 'topic': topic,\n 'posts': posts,\n 'page_obj': page_obj,\n 'post_search': post_search,\n }\n return render(request, 'boards/topic_view.html', context)\n\n\n@ensure_csrf_cookie\ndef topic_favorite_view(request):\n \n if not request.user.is_authenticated:\n return JsonResponse({'result': 'false'})\n \n if request.is_ajax():\n topic = get_object_or_404(Topic, slug=request.POST.get('topic_slug'))\n \n response = ''\n if topic.favorites.filter(id=request.user.id).exists():\n topic.favorites.remove(request.user)\n topic.save()\n response = {'result': 'removed'}\n\n else:\n topic.favorites.add(request.user)\n topic.save()\n response = {'result': 'added'}\n\n return JsonResponse(response, status=200)\n\n\ndef get_client_ip(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n return ip\n\n\ndef post_view(request, pk):\n \n # display specific post and comment form which will be dealt in add-comment function by ajax.\n post = Post.objects.get(id=pk)\n comments = post.comments.all()\n form = CommentCreationForm()\n \n # Check if request user ip already exists in Post model.\n # get_or_create returns tuple, (object and boolean(created or not))\n ip = get_client_ip(request)\n visitor, created = IpModel.objects.get_or_create(ip=ip)\n \n if not visitor.post.filter(id=post.id).exists():\n print('there\\'s no post in this ip')\n visitor.post.add(post)\n visitor.save()\n post.view_count += 1\n post.save()\n \n context = {\n 'post': post,\n 'form': form, \n 'comments': comments,\n 'topic': post.topic,\n }\n return render(request, 'boards/post_view.html', context)\n\n\n@login_required(login_url='account_login')\ndef create_post_view(request, slug):\n \n topic = Topic.objects.get(slug=slug)\n form = PostCreationForm()\n \n if request.method == 'POST':\n form = PostCreationForm(request.POST)\n \n if form.is_valid():\n new_post = form.save(commit=False)\n new_post.topic = Topic.objects.get(slug=slug)\n new_post.writer = request.user # getting current user from request.\n new_post.save()\n return redirect('boards:topic', slug)\n \n context = {'form': form, 'topic': topic}\n return render(request, 'boards/create_post_view.html', context)\n\n\n@login_required(login_url='account_login')\ndef edit_post_view(request, pk):\n \n post = Post.objects.get(id=pk)\n previous_page = request.META.get('HTTP_REFERER', '/')\n \n if request.user != post.writer:\n return redirect('boards:post', pk)\n \n else:\n form = PostCreationForm(instance=post)\n \n if request.method == 'POST':\n form = PostCreationForm(request.POST, instance=post)\n \n if form.is_valid():\n form.save()\n return redirect('boards:post', pk)\n \n context = {\n 'form': form,\n 'post': post, \n 'topic': post.topic,\n 'previous_page': previous_page,\n }\n return render(request, 'boards/edit_post_view.html', context)\n\n\n@login_required(login_url='account_login')\ndef delete_post_view(request, pk):\n \n post = Post.objects.get(id=pk)\n slug = post.topic.slug\n previous_page = request.META.get('HTTP_REFERER')\n \n if request.user != post.writer:\n return redirect('boards:post', pk)\n \n else:\n if request.method == 'POST':\n post.delete()\n return redirect('boards:topic', slug)\n \n context = {'post': post, 'topic': post.topic, 'previous_page': previous_page}\n return render(request, 'boards/delete_post_view.html', context)\n\n\ndef post_likes_view(request):\n \n if not request.user.is_authenticated:\n return JsonResponse({'result': 'false'})\n \n if request.is_ajax():\n post = get_object_or_404(Post, id=request.POST.get('post_id'))\n \n response = ''\n if post.likes.filter(id=request.user.id).exists():\n post.likes.remove(request.user)\n post.like_count -= 1\n post.save()\n response = {'result': 'minus', 'count': post.like_count}\n\n else:\n post.likes.add(request.user)\n post.like_count += 1\n post.save()\n response = {'result': 'plus', 'count': post.like_count}\n\n return JsonResponse(response, status=200)\n \n\ndef add_comment_view(request, pk):\n # getting a request from front ajax and response.\n \n data = {}\n if request.is_ajax():\n if not request.user or not request.user.is_authenticated:\n data['success'] = 'false'\n data['url'] = 'http://127.0.0.1:8000/accounts/login/'\n return JsonResponse(data, status=404)\n \n form = CommentCreationForm(request.POST)\n \n if form.is_valid():\n new_comment = form.save(commit=False)\n new_comment.writer = request.user\n new_comment.post = Post.objects.get(id=pk)\n new_comment.save()\n \n # Since data from views can not be rendered dynamically in html,\n # django should send rendered data in response to ajax call.\n data['username'] = new_comment.writer.username\n data['comment'] = new_comment.comment\n data['id'] = new_comment.id\n \n return JsonResponse(data, status=200)\n \n return redirect('boards:post', pk)\n\n\ndef delete_comment_view(request, pk):\n \n comment = Comment.objects.get(id=pk)\n post = comment.post\n \n if request.user.is_authenticated and request.user == comment.writer:\n comment.delete()\n return redirect('boards:post', post.id)\n\n return redirect('boards:post', post.id)\n\n\ndef topic_request(request):\n \n requests = TopicRequest.objects.all()\n \n paginator = Paginator(requests, 20)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n \n context = {'request_obj': page_obj}\n return render(request, 'boards/topic_request_list.html', context)\n\n\n@login_required(login_url='account_login')\ndef topic_request_create(request):\n \n form = TopicRequestForm()\n \n if request.method == 'POST':\n form = TopicRequestForm(request.POST)\n \n if form.is_valid():\n new_request = form.save(commit=False)\n new_request.writer = request.user\n new_request.save()\n return redirect('boards:request_list')\n\n \n context = {'form': form}\n return render(request, 'boards/topic_request_create.html', context)\n\n\ndef request_recommendation(request):\n \n if not request.user.is_authenticated:\n return JsonResponse({'result': 'false'})\n \n if request.is_ajax():\n request_id = request.POST.get('request_id')\n requested_topic = get_object_or_404(TopicRequest, id=request_id) \n \n response = {\n 'request_id': requested_topic.id,\n }\n if requested_topic.recommendations.filter(id=request.user.id).exists():\n requested_topic.recommendations.remove(request.user)\n requested_topic.like_count -= 1\n requested_topic.save()\n response['result'] = 'minus'\n \n \n else:\n requested_topic.recommendations.add(request.user)\n requested_topic.like_count += 1\n requested_topic.save()\n response['result'] = 'plus'\n \n return JsonResponse(response, status=200)\n\n\n\nclass AboutView(TemplateView):\n template_name = 'about.html'","repo_name":"JhunK-SK/deutsch-klatsch","sub_path":"boards/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"8591306424","text":"\"\"\"Evaluation of the model.\"\"\"\n\nimport os\nimport time\nfrom typing import Dict\nfrom typing import List\nfrom typing import Union\n\nimport pandas as pd\nimport torch\nfrom datasets import Dataset\nfrom datasets import load_dataset\nfrom dotenv import load_dotenv\nfrom huggingface_hub import InferenceClient\nfrom tqdm import tqdm\nfrom transformers import AutoConfig\nfrom transformers import AutoTokenizer\nfrom transformers import pipeline\n\nfrom social_llama.config import DATA_DIR_EVALUATION_SOCIAL_DIMENSIONS\nfrom social_llama.config import DATA_DIR_EVALUATION_SOCKET\nfrom social_llama.config import LlamaConfigs\nfrom social_llama.data_processing.social_dimensions import SocialDimensions\nfrom social_llama.evaluation.helper_functions import label_check\nfrom social_llama.evaluation.helper_functions import label_finder\nfrom social_llama.utils import get_device\nfrom social_llama.utils import save_json\n\n\nload_dotenv()\n\n\nclass Evaluator:\n \"\"\"Evaluator for our tasks dataset.\"\"\"\n\n def __init__(self, model_id: str) -> None:\n \"\"\"Initialize the evaluator.\"\"\"\n self.socket_tasks: List[str] = [\"CLS\", \"REG\", \"PAIR\", \"SPAN\"]\n self.model_id = model_id\n self.social_dimensions = SocialDimensions(\n task=\"zero-shot\", model=\"meta-llama/Llama-2-7b-chat-hf\"\n )\n self.social_dimensions.get_data()\n self.llama_config = LlamaConfigs()\n self.socket_prompts: pd.DataFrame = pd.read_csv(\n DATA_DIR_EVALUATION_SOCKET / \"socket_prompts.csv\"\n )\n self.generation_kwargs = {\n \"max_new_tokens\": 50,\n \"temperature\": 0.9,\n \"truncate\": 4096,\n # \"stop_sequences\": self.social_dimensions.config.labels,\n }\n self.generation_kwargs_local = {\n \"max_new_tokens\": 20,\n \"temperature\": 0.9,\n }\n self.tokenizer = AutoTokenizer.from_pretrained(\"meta-llama/Llama-2-7b-chat-hf\")\n if model_id in [\"meta-llama/Llama-2-7b-chat-hf\"]:\n self.inference_client = InferenceClient(\n model=model_id, token=os.environ[\"HUGGINGFACEHUB_API_TOKEN\"]\n )\n self.use_inference_client = True\n else:\n self.config = AutoConfig.from_pretrained(model_id)\n self.llama_config = LlamaConfigs()\n self.device = get_device()\n self.llm = pipeline(\n \"text-generation\",\n model=model_id,\n tokenizer=self.tokenizer,\n # device=self.device,\n device_map=\"auto\",\n )\n self.use_inference_client = False\n\n def predict(self, task: str = \"social-dimensions\") -> None:\n \"\"\"Predict the labels for the test data.\"\"\"\n if task == \"social-dimensions\":\n task_data = self._prepare_social_dim_test_data()\n predictions = []\n\n for sample in tqdm(task_data):\n prediction = self._predict(sample)\n\n prediction_processed = label_check(\n prediction=prediction,\n labels=self.social_dimensions.config.labels,\n )\n prediction_finder = label_finder(\n prediction=prediction,\n labels=self.social_dimensions.config.labels,\n )\n predictions.append(\n {\n \"idx\": sample[\"idx\"],\n \"prompt\": sample[\"prompt\"],\n \"prediction\": prediction,\n \"prediction_processed\": prediction_processed,\n \"prediction_finder\": prediction_finder,\n \"label\": sample[\"label\"],\n }\n )\n save_json(\n DATA_DIR_EVALUATION_SOCIAL_DIMENSIONS\n / f\"{self.model_id}_predictions_empty_prompt_prefix.json\",\n predictions,\n )\n elif task == \"socket\":\n cls_tasks = self.socket_prompts[self.socket_prompts[\"type\"] == \"CLS\"][\n \"task\"\n ]\n for task in cls_tasks:\n task_data, labels = self._prepare_socket_test_data(task=task)\n predictions = []\n\n for sample in tqdm(task_data):\n prediction = self._predict(sample)\n\n prediction_processed = label_check(\n prediction=prediction,\n labels=labels,\n )\n prediction_finder = label_finder(\n prediction=prediction,\n labels=labels,\n )\n predictions.append(\n {\n \"idx\": sample[\"idx\"],\n \"prompt\": sample[\"prompt\"],\n \"prediction\": prediction,\n \"prediction_processed\": prediction_processed,\n \"prediction_finder\": prediction_finder,\n \"label\": sample[\"label\"],\n }\n )\n save_json(\n DATA_DIR_EVALUATION_SOCKET\n / f\"{task}/{self.model_id}_predictions_v3.json\",\n predictions,\n )\n\n else:\n raise ValueError(\"Task not recognized.\")\n\n def _predict(self, sample) -> str:\n if self.use_inference_client:\n has_output = False\n while not has_output:\n try:\n prediction = self.inference_client.text_generation(\n sample[\"prompt\"], **self.generation_kwargs\n )\n except Exception:\n time.sleep(2)\n continue\n has_output = True\n\n else:\n prediction: str = self.llm(sample[\"prompt\"])[0][\"generated_text\"]\n prediction: str = prediction.replace(sample[\"prompt\"], \"\")\n\n return prediction\n\n def _prepare_social_dim_test_data(self) -> List[Dict[str, str]]:\n \"\"\"Prepare the test data for the social dimension task.\"\"\"\n test_data: Dataset = self.social_dimensions.test_data\n\n test_data_formatted = {}\n\n # Loop through each JSON object and group by 'idx'\n for obj in test_data:\n idx = obj[\"idx\"]\n response_good = obj[\"response_good\"]\n\n if idx not in test_data_formatted:\n test_data_formatted[idx] = {\n \"label\": [],\n \"idx\": idx,\n \"prompt\": self.social_dimensions._prompt_function(obj, is_q_a=True),\n }\n\n test_data_formatted[idx][\"label\"].append(response_good)\n\n # Return a list of all the values in the dictionary\n return list(test_data_formatted.values())\n\n def _prepare_socket_test_data(self, task: str) -> List[Dict[str, Union[str, int]]]:\n test_data_formatted: List[Dict[str, str]] = []\n\n # Get all the socket prompts with type CLS\n prompt = self.socket_prompts[self.socket_prompts[\"task\"] == task][\n \"question\"\n ].iloc[0]\n\n dataset: Dataset = load_dataset(\"Blablablab/SOCKET\", task, split=\"test\")\n\n # if length is more than 2000, randomly sample 2000\n if len(dataset) > 2000:\n dataset = dataset.shuffle(seed=42).select(range(2000))\n\n labels: List[str] = dataset.features[\"label\"].names\n labels_formatted = [f'\"{label}\"' for label in labels]\n labels_mapping: Dict[int, str] = {i: label for i, label in enumerate(labels)}\n\n for idx, sample in enumerate(dataset):\n test_data_formatted.append(\n {\n \"idx\": idx,\n \"prompt\": self._prompt_socket(sample, prompt, labels_formatted),\n \"label\": labels_mapping[sample[\"label\"]],\n }\n )\n\n return test_data_formatted, labels\n\n def _prompt_socket(\n self, sample: Dict[str, str], prompt: str, labels: List[str]\n ) -> str:\n chat: List[Dict[str, str]] = self.llama_config.get_chat_template()\n\n chat[0][\"content\"] = chat[0][\"content\"].format(prompt_prefix=\"\")\n\n task_prompt = (\n prompt.format(\n text=sample[\"text\"],\n )\n + f\" You can choose from the following labels: {', '.join(labels)}\\nAnswer:\"\n )\n\n chat.append(\n {\n \"role\": \"user\",\n \"content\": task_prompt,\n }\n )\n\n return self.tokenizer.apply_chat_template(\n chat, tokenize=False, add_generation_prompt=True\n )\n\n\nif __name__ == \"__main__\":\n models = [\n \"AGMoller/social_llama_7b_zero-shot\",\n \"AGMoller/social_llama_7b_few-shot\",\n \"AGMoller/social_llama_7b_cot\",\n ]\n\n for model in models:\n torch.cuda.empty_cache()\n\n evaluator = Evaluator(model)\n\n evaluator.predict(task=\"social-dimensions\")\n\n a = 1\n","repo_name":"AGMoller/social-llama","sub_path":"src/social_llama/evaluation/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":9062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"13091789475","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def __init__(self):\n self.x_dep = None\n self.x_p_val = None\n self.y_dep = None\n self.y_p_val = None\n \n def traversal(self, node, p_val, x, y, dep):\n if node is None:\n return\n \n if node.val == x:\n self.x_dep = dep\n self.x_p_val = p_val\n elif node.val == y:\n self.y_dep = dep\n self.y_p_val = p_val\n \n self.traversal(node.left, node.val, x, y, dep + 1)\n self.traversal(node.right, node.val, x, y, dep + 1) \n \n def isCousins(self, root: TreeNode, x: int, y: int) -> bool:\n self.traversal(root, None, x, y, 0)\n \n return self.x_dep == self.y_dep and self.x_p_val != self.y_p_val\n","repo_name":"hg-pyun/algorithm","sub_path":"leetcode/cousins-in-binary-tree.py","file_name":"cousins-in-binary-tree.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"6441660175","text":"import tkinter\n\nFONT = (\"Letters for Learners\", 16, \"bold\")\nwindow = tkinter.Tk()\nwindow.title(\"My First GUI Program\")\nwindow.minsize(width=500, height=300)\n\nlabel = tkinter.Label(text=\"I am a Label\", font=FONT)\nlabel.pack()\n\nlabel[\"text\"] = \"I am still a Label\"\nlabel.config(text=\"Nope. Still a Label\")\n\n\ndef button_clicked():\n print(\"I got clicked\")\n\n\nbutton = tkinter.Button(text=\"Click Me\", command=button_clicked)\nbutton.pack()\n\nwindow.mainloop()\n","repo_name":"pullynnhah/100DaysOfCode","sub_path":"Day027/Lectures/lec08.py","file_name":"lec08.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"29"} +{"seq_id":"8941566020","text":"import boto3\nimport os\nimport sys\nimport uuid\nfrom urllib.parse import unquote_plus\nfrom PIL import Image\nimport PIL.Image\n\ns3_client = boto3.client('s3')\n\ndef resize_image(image_path, resized_path):\n with Image.open(image_path) as image:\n image.thumbnail(tuple(x / 2 for x in image.size))\n image.save(resized_path)\n \ndef resize_image2(image_path, resized_path):\n with Image.open(image_path) as image:\n image.thumbnail(tuple(x / 4 for x in image.size))\n image.save(resized_path)\n \ndef lambda_handler(event, context):\n for record in event['Records']:\n #recuperamos el bucket\n bucket = record['s3']['bucket']['name']\n key = unquote_plus(record['s3']['object']['key'])\n tmpkey = key.replace('/', '')\n #se baja el objeto\n download_path = '/tmp/{}{}'.format(uuid.uuid4(), tmpkey)\n #creamos un path para cada imagen que vamos a reducir\n upload_path2 = '/tmp/reducido-{}'.format(tmpkey)\n upload_path = '/tmp/minuatura-{}'.format(tmpkey)\n #bajamos el objeto que vamos a reducir\n s3_client.download_file(bucket, key, download_path)\n #cabiamos el tamnio de las fotos\n resize_image(download_path, upload_path)\n resize_image2(download_path, upload_path2)\n #subimos las fotos a sus bucket\n s3_client.upload_file(upload_path, 'size-o-reducido', key)\n s3_client.upload_file(upload_path2, 'size-o-miniatura', key)\n # s3_client.upload_file(upload_path, '{}-reducido'.format(bucket), key)\n #s3_client.upload_file(upload_path2, '{}-miniatura'.format(bucket), key)","repo_name":"jorgeBallesterosDiezma/modifica-tamanioeee","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"2190855000","text":"'''\nFacilitates the plotting of variables versus the the fit range iteration.\n Usage: python -i plotScaleVsFitRangeIter.py\n'''\nimport JPsi.MuMu.common.canvases as canvases\nimport JPsi.MuMu.escale.fitResultPlotter as frp\n\ncanvases.wwidth = 400\ncanvases.wheight = 400\ncanvases.yperiod = 10\n\n## Plot the Delta s vs iteration number\ncanvases.next()\nfrp.filenames = ('mc_mmMass85_EB_lowR9_PhoEt12-15.root',) * 8\nfrp.wsnames = ('ws1',) * 8\nname = 'sFit_strue_mc_mmMass85_EB_lowR9_PhoEt12-15_gamma_iter%d'\nfrp.snapshots = [name % i for i in range(8)]\n\nfrp.yname = '#Deltas'\nfrp.ytitle = '#Deltas'\n\nfrp.name = None\nfrp.xtitle = 'Fit Range Iteration'\nfrp.xdata = range(8)\nfrp.exdata = [0] * 8\n\nfrp.main()\n\n## Plot sigma vs iteration number for the same fit\ncanvases.next()\nfrp.yname = '#sigma'\nfrp.ytitle = '#sigma'\nfrp.main()\n\n\n## Swtich the parameter set\nfrp.snapshots = ['chi2' + name[4:] for name in frp.snapshots]\n\n## Plot chi2/ndof vs iteration number for the same fit\nfrp.yname = 'reducedChi2'\nfrp.ytitle = '#chi^{2}/ndof'\ncanvases.next()\nfrp.main()\n\n## Plot chi2/ndof vs iteration number for the same fit\nfrp.yname = 'ndof'\nfrp.ytitle = 'ndof'\ncanvases.next()\nfrp.main()\n\n## Plot chi2 prob vs iteration number for the same fit\nfrp.yname = 'chi2Prob'\nfrp.ytitle = 'P(#chi^{2}, ndof)'\nfrp.logy = True\ncanvases.next().SetLogy()\nfrp.main()\n\ncanvases.canvases[-1].Update()\n\nif __name__ == '__main__':\n import user\n","repo_name":"janveverka/JPsi","sub_path":"MuMu/test/escale/plotXvsFitRangeIter.py","file_name":"plotXvsFitRangeIter.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35571713208","text":"\"\"\"\nPURPOSE:\n A script for downloading the probability of tweets being toxic maping each tweet ID\n to it's toxicity probability. This script utilizes the Perspective API to gather\n this data.\n - Ref: https://developers.perspectiveapi.com/s/about-the-api\n This file also stores the tweet IDs for language errors* that the API cannot handle\n and can be restarted if the script falls over midway through data collection,\n without re-querying the same tweet IDs again. It does this by creating a file\n that contains the tweet ID for tweets where language errors were encountered\n and reading previously recorded data files tweet IDs. The language error\n and previously recorded tweet IDs are then removed from the full list of tweet\n IDs to query.\n * Language errors are either:\n 1. The API does not handle the language in the tweet (e.g. Japanese is not supported)\n 2. The API cannot recognize the language in the tweet\n\nINPUT:\n Project `config.ini` file with the following details included:\n ~~~~\n [VARS]\n\n [PATHS]\n TOXICITY_DIR = /data_volume/super-spreaders/intermediate_files/toxicity\n\n [FILES]\n IFFYP_TOXICITY_PROBS = iffyp_tweet_toxicity_probabilities.csv\n ~~~\n\nOUTPUT:\n Files containing all toxicity probabilities for each tweet.\n - iffyp_tweet_toxicity_probabilities{int}.csv\n - Integers are included in the fname for restarts\n - rows contain one tweet per row\n - columns = [\"tweet_id\", \"toxicity_score\"]\n language_error_tweets.txt - file where each line contains a single tweet ID\n and each represents a previously queried tweet ID that caused the Perspective\n API to throw a language error.\n\nAuthor: Matthew DeVerna\n\"\"\"\n\n### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Load Packages ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nimport csv\nimport os\nimport glob\nimport httplib2\nimport json\nimport random\nimport time\nimport sys\n\nimport numpy as np\nimport pandas as pd\n\nfrom googleapiclient import discovery\nfrom utils import parse_config_file, parse_cl_args, Loader\n\n\n### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Create Functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ndef switch_api_keys(api_key=str, all_keys=list):\n \"\"\"\n Return the next api key from the provided list\n\n Parameters:\n - api_key (str) : the last used api_key\n - all_keys (list) : a list of all available\n api keys\n\n Returns:\n - the next api key in the string. If the\n last used key was the last key in the\n list, return the first key in the list.\n \"\"\"\n print(\"Switching keys...\")\n\n idx = all_keys.index(api_key) + 1\n\n # If the next api key is the last one,\n # Change the index to 0 to select the first key\n if idx == len(all_keys):\n idx = 0\n return all_keys[idx]\n\n\ndef get_toxicity(tweet_text=str, api_key=str, tries=int, all_keys=list):\n \"\"\"\n Query the Perspective API for toxicity scores, implement exponentially\n larger and larger wait periods based on number of retries, and\n cycle through provided keys when being rate limited.\n - Ref: https://developers.perspectiveapi.com/s/about-the-api\n\n Parameters:\n - tweet_text (str) : full tweet text\n - api_key (str) : the API key to utilize for the current call\n - tries (int) : how many attempts have been made already. This\n controls how long the exponential back-off function will wait\n - all_keys (list) : all possible keys to use. This still works if\n only one key is provided, but it must be placed into a list.\n\n Returns:\n - 'AnalyzeComment' response (dict) : a response from the\n Perspective API including only a toxicity probability\n \"\"\"\n\n client = discovery.build(\n \"commentanalyzer\",\n \"v1alpha1\",\n developerKey=api_key,\n discoveryServiceUrl=\"https://commentanalyzer.googleapis.com/$discovery/rest?version=v1alpha1\",\n )\n\n analyze_request = {\n \"comment\": {\"text\": tweet_text},\n \"requestedAttributes\": {\"TOXICITY\": {}},\n }\n\n try:\n # If we get a successful request, set switch to False.\n # This will break the while loop in the main script and go\n # to the next tweet\n response = client.comments().analyze(body=analyze_request).execute()\n switch = False\n\n # A server error we hit when `commentanalyzer.googleapis.com`\n # is not available\n except httplib2.error.ServerNotFoundError as e:\n print(e)\n print(\"Can't find server, waiting 15 seconds...\")\n time.sleep(15)\n\n response = None\n tries += 1\n switch = True\n\n # Switch to the next API key, just in case\n api_key = switch_api_keys(api_key=api_key, all_keys=all_keys)\n\n # A server error we hit when the network is unreachable\n except OSError as e:\n print(e)\n print(\"Handling OS ERROR, waiting 15 seconds...\")\n time.sleep(15)\n\n response = None\n tries += 1\n switch = True\n\n # Switch to the next API key, just in case\n api_key = switch_api_keys(api_key=api_key, all_keys=all_keys)\n\n # For other errors, we check the status code\n except Exception as e:\n # 429 = \"rate limiting\"\n # Employ an exponential backoff procedure\n if e.status_code == 429:\n secs_2_wait = (2**tries) + (random.uniform(0, 1))\n\n # We shouldn't have to wait more than two minutes\n if secs_2_wait > 120:\n secs_2_wait = 120\n\n print(f\"Waiting {secs_2_wait} seconds...\")\n time.sleep(secs_2_wait)\n response = None\n tries += 1\n switch = True # Ensures we try the same tweet again\n\n # Switch to the next API key, to minimize wait period\n api_key = switch_api_keys(api_key=api_key, all_keys=all_keys)\n\n # 400 = \"bad request\"\n # This catches queries that break because the tweet contains a\n # language not covered by the API\n elif (e.status_code == 400) and (\"language\" in e._get_reason()):\n response = \"language_error\"\n switch = False # We can't fix this, so we move to the next tweet\n\n # Sometimes the language is undetectable, this handles that\n elif (e.status_code == 400) and (\"language\" in e.error_details):\n response = \"language_error\"\n switch = False # We can't fix this, so we move to the next tweet\n\n else:\n # If none of the above, we are getting some weird error\n # wait 30 seconds and try again.\n print(\"UNKNOWN ERROR!! Waiting for 30 seconds...\")\n print(\"~~STATUS CODE~~\", e.status_code)\n print(\"~~ERROR DETAILS~~\", e.error_details)\n print(e)\n response = None\n time.sleep(30)\n switch = False\n\n api_key = switch_api_keys(api_key=api_key, all_keys=all_keys)\n\n return response, switch, tries, api_key\n\n\n### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Create Functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nif __name__ == \"__main__\":\n # Load API Keys\n comma_separated_api_keys = os.environ.get(\"PERSPECTIVE_API_KEY\")\n if comma_separated_api_keys is None:\n raise Exception(\"YOU FORGOT TO SET YOUR API KEY AS AN ENVIRONMENT VARIABLE!!\")\n\n # Separate keys into a list and take the first one\n # NOTE: We utilize multiple API keys at once to reduce wait times. The waiting\n # strategy employed here may not work if you only utilize one key.\n list_of_api_keys = comma_separated_api_keys.split(\",\")\n print(f\"You are working with {len(list_of_api_keys)} different keys.\")\n api_key = list_of_api_keys[0]\n\n # Load the config file variables\n args = parse_cl_args()\n config = parse_config_file(args.config_file)\n\n # Initialize our Loader class and load the necessary data\n l = Loader()\n data = l.load_iffyp_tweets_jan_2_oct()\n\n # Retweets have the same text as the original tweet\n # Drop duplicates to reduce the number of tweets to query\n data = data.drop_duplicates(\"original_tweet_id\").reset_index(drop=True)\n\n # Set output filename\n out_dir = config[\"PATHS\"][\"TOXICITY_DIR\"]\n out_name = config[\"FILES\"][\"IFFYP_TOXICITY_PROBS\"]\n\n # Get all data files in output directory\n existing_files = glob.glob(os.path.join(out_dir, \"*.csv\"))\n\n # If files already exists, append an integer to the end of the file name\n # to create a new output file name\n num_existing_files = len(existing_files)\n if num_existing_files > 0:\n out_name = f\"{num_existing_files}.\".join(out_name.split(\".\"))\n\n output_file_name = os.path.join(out_dir, out_name)\n\n # Double check it doesn't exist...\n if os.path.exists(output_file_name):\n raise Exception(\n \"ERROR: file name already exists. Breaking script to not over write already pulled data.\"\n )\n\n # Now we gather all tweet_ids that we've already pulled or for which\n # we encountered a language issue\n prev_checked_t_ids = []\n\n # Check if there is a language error file and add all tweet ids in there to the list\n language_error_fname = os.path.join(out_dir, \"language_error_tweets.txt\")\n if os.path.exists(language_error_fname):\n with open(language_error_fname, \"r\") as error_f:\n _ = [prev_checked_t_ids.append(t_id.strip(\"\\n\")) for t_id in error_f]\n\n # Check completed files and add those tweet ids as well\n if num_existing_files > 0:\n for file in existing_files:\n prev_pulled_data = pd.read_csv(file, dtype={\"tweet_id\": str})\n prev_tweet_ids = list(prev_pulled_data[\"tweet_id\"])\n prev_checked_t_ids.extend(prev_tweet_ids)\n\n # Remove rows from our data frame with those tweet ids\n data = data[~data[\"original_tweet_id\"].isin(prev_checked_t_ids)]\n\n # Create zipper to iterate over only what we need\n tweetId_tweetText_zipper = zip(data[\"original_tweet_id\"], data[\"text\"])\n\n # Some helpful numbers for printing loop progress\n number_of_queries = len(data)\n update_chunk_size = 5000 # Print updates after this many tweets\n total_chunks = np.ceil(number_of_queries / update_chunk_size)\n count = 0\n chunk = 0\n\n print(f\"Pulling data on {number_of_queries} tweets...\")\n\n # We open an output file to save data as we go because\n # the script will take a long time to complete\n with open(output_file_name, \"w\") as f_out:\n csv_out = csv.writer(f_out)\n csv_out.writerow([\"tweet_id\", \"toxicity_score\"])\n\n # Loop through each tweet ID and it's full text\n for t_id, text in tweetId_tweetText_zipper:\n # Print updates\n count += 1\n if count % update_chunk_size == 0:\n chunk += 1\n print(\n f\"5k tweets processed || {chunk} chunks completed out of {int(total_chunks)}\"\n )\n\n switch = True\n tries = 1\n while switch:\n # Wait 50 milliseconds before each call\n time.sleep(0.05)\n\n # If this query is successful, `switch` is returned False.\n # Otherwise, it returns True and waits exponentially longer\n # after each try.\n try:\n response, switch, tries, api_key = get_toxicity(\n tweet_text=text,\n api_key=api_key,\n tries=tries,\n all_keys=list_of_api_keys,\n )\n except OSError as e:\n print(e)\n print(\"Handling OS ERROR, wait 10 seconds...\")\n time.sleep(10)\n\n # Handle errors by skipping to next tweet id\n if response is None:\n continue\n # If we get a language error, save that tweet ID\n elif response == \"language_error\":\n with open(language_error_fname, \"a\") as error_f:\n error_f.write(f\"{t_id}\\n\")\n continue\n # Save tweet id and score if request successful\n else:\n toxicity_score = response[\"attributeScores\"][\"TOXICITY\"][\n \"summaryScore\"\n ][\"value\"]\n csv_out.writerow((t_id, toxicity_score))\n\n print(\"~~~ Script Complete ~~~\")\n","repo_name":"osome-iu/fib-index","sub_path":"src_clean/get_toxicity.py","file_name":"get_toxicity.py","file_ext":"py","file_size_in_byte":12438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"69936376400","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\n\n\"\"\"\n练习post用法\n\"\"\"\n\n\nimport requests \nfrom bs4 import BeautifulSoup\n\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36\"\n } \n\ndef get_soup(url, method=\"GET\", **kwargs):\n \n if method == \"GET\":\n response = requests.get(url, headers=headers, **kwargs)\n elif method == \"POST\":\n response = requests.post(url, headers=headers, **kwargs)\n \n try:\n soup = BeautifulSoup(response.content, 'lxml')\n except Exception as e:\n soup = BeautifulSoup(response.content, 'html.parser')\n \n return soup\n\ndef get_gene_mutation(gene):\n url = \"http://hgmdtrial.biobase-international.com/hgmd/pro/all.php/\"\n url = url\n data ={\n \"gene\": gene,\n \"sort\": \"location\",\n \"database\": \"Get all mutations\"\n }\n \n soup = get_soup(url, method=\"POST\", data=data)\n \n # tables = soup.select('table.gene')\n tables = soup.find('table', class_='gene').find_all('tr')\n \n for i in tables:\n print(i)\n \n \n return tables\n \n\nif __name__ == \"__main__\":\n \n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"gene\", help=\"请输入基因名称\")\n \n args = vars(parser.parse_args())\n \n gene = args[\"gene\"]\n \n mutation = get_gene_mutation(gene)\n \n print(mutation)\n\n","repo_name":"lvmt/spider","sub_path":"beautifulsoup/requests/demo_post.py","file_name":"demo_post.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"10291658113","text":"import uuid\nfrom django.db import models\nfrom cleaners.models import cleaners\nfrom ckeditor.fields import RichTextField\nfrom datetime import datetime\n\n\n\nNAME_OF_DAY=[\n('MON', 'Monday'),\n('TUE', 'Tuesday'),\n('WED','Wednesday'),\n('THU', 'Thursday'),\n('FRI', 'Friday'),\n('SAT', 'Saturday'),\n('SUN', 'Sunday')\n]\n#regular or one-off\nTYPE = [\n ('RE', 'Regular'),\n ('O-F', 'One Off')\n]\n#Weekly, monthly, fortnightly\nFREQUENCY = [\n ('Weekly','Weekly'),\n ('Monthly','Monthly'),\n ('Fortnightly','Fortnightly')\n]\n#Question\nARE_THEY_PAYING = [\n ('Yes','Yes'),\n ('No', 'No')\n]\n\n#DD, Standing Order(SO), Card \nTYPES_PAYING_METHODS = [\n ('DD', 'DD'),\n ('SO', 'Standing Order(SO)'),\n ('CA', 'Card')\n]\n\n\n\nclass clients(models.Model):\n id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)\n\n #Mr, Ms, Mrs\n #One Field is Fine\n name = models.CharField(max_length=50)\n \n #Three Line and A Zip code at the end\n address_line_1 = models.CharField(max_length=30)\n address_line_2 = models.CharField(max_length=30)\n address_line_3 = models.CharField(max_length=30)\n \n post_code = models.CharField(max_length=8, default=\"0\")\n\n \n\n # 11 digits in the number\n# 1 mobile and 1 landline.\n\n landline_number = models.CharField(max_length=11, null=True, blank=True)\n mobile_number = models.CharField(max_length=13, null=True, blank=True)\n\n email = models.EmailField(unique=True, blank=False)\n\n #22-06-28 13:44\n date_added = models.DateField()\n\n #Notes in a text form\n \n # tba to be allocated, int interviewing cleaner, ncp cleaner accepted, dc dead client\n status = models.ForeignKey('status', on_delete = models.CASCADE)\n\n #Notes fields is missing, date stamp and description\n \n # Any day of week\n # Text field\n preferred_day = models.CharField(max_length=8, choices=NAME_OF_DAY)\n\n #regular or one-off\n type = models.CharField(max_length=6, choices=TYPE)\n\n #Weekly, monthly, fortnightly\n frequency = models.CharField(max_length=11, choices=FREQUENCY)\n\n #digits, 1-10\n number_of_hours = models.IntegerField()\n\n #Yes or No\n paying = models.CharField(max_length=3, choices=ARE_THEY_PAYING)\n \n #DD, Standing Order(SO), Card \n paying_methods = models.CharField(max_length=13, choices=TYPES_PAYING_METHODS)\n \n # Every cleaner that is available in the postcode, existing cleaner status, available for work\n cleaner_allocated = models.ForeignKey(cleaners, on_delete=models.PROTECT, null = True, blank = True)\n \n \n #Surname of the client, reference to see the payments, text field\n payment_reference = models.CharField(max_length=40)\n \n \n #sms_to_client = models.CharField(max_length=1)\n\n notes = models.TextField()\n\n def __str__(self):\n return self.email\n \n #Notes in a text form\n# tba to be allocated, int interviewing cleaner, ncp cleaner accepted, dc dead client\nclass status(models.Model):\n id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)\n abber_of_notes = models.CharField(max_length=4, default='tba')\n full_form = models.CharField(max_length=30, default='to be allocated')\n def __str__(self):\n return self.abber_of_notes\n\n\nclass ex_cleaner(models.Model):\n id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)\n client_id = models.UUIDField(default=uuid.uuid4)\n client_email = models.EmailField()\n cleaner = models.ForeignKey(cleaners, on_delete = models.PROTECT, null = True, blank = True)\n\n def __str__(self):\n return self.cleaner.name\n\nclass EmailsSentToClient(models.Model):\n id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)\n email_recipient = models.ForeignKey('clients', on_delete = models.PROTECT) \n email_subject = models.CharField(max_length = 50)\n email_content = RichTextField(blank = True, default=\"None\")\n","repo_name":"ticTechtoee/django_crm","sub_path":"clients/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"11366385908","text":"import numpy as np\n\nfrom util.readFile import readCSV\n\n\nclass ConfusionMatrix:\n\n def __init__(self, audio):\n self.audio = audio\n\n def showConfusionMatrix(self):\n\n path = './files/results/' + \\\n str(self.audio) + '_P/confusionMatrix.csv'\n\n file = readCSV(path, \",\")\n\n self.TN = file[0, 0].astype(np.int)\n self.FP = file[0, 1].astype(np.int)\n self.FN = file[0, 2].astype(np.int)\n self.TP = file[0, 3].astype(np.int)\n self.total = file[0, 4].astype(np.int)\n\n\n\"\"\"\n print(\"Total = \" + str(self.total))\n print(\"TP = \" + str(self.TP))\n print(\"FP = \" + str(self.FP))\n print(\"TN = \" + str(self.TN))\n print(\"FN = \" + str(self.FN))\n\"\"\"\n","repo_name":"inigoferr/tfm","sub_path":"classes/ConfusionMatrix.py","file_name":"ConfusionMatrix.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14343551381","text":"\"\"\"\nСлужебный файл для photoviewer\n\"\"\"\nfrom PIL import Image, ExifTags, ImageDraw, ImageFont\nimport io\nfrom pathlib import Path\nimport facesstore\nfrom xmpfaces import get_face_rect, xmpfaces\n\n\nclass FolderPhoto:\n\n json_file = 'exif.json'\n faces = facesstore.FacesStore.load(json_file)\n # fnt = ImageFont.truetype(\"Pillow/Tests/fonts/FreeMono.ttf\", 40)\n fnt = ImageFont.truetype(\"fonts/Absolut Pro Light Condensed.ttf\", 14, encoding='UTF-8')\n # fnt = ImageFont.truetype(\"Zekton Condensed Book.ttf\", 12, encoding='UTF-8')\n\n def __init__(self, folder_name):\n self.MASK = '*.jpg'\n self.folder = Path(folder_name).resolve()\n self.photos = self.get_photos()\n self.dirs = self.get_dirs()\n self.count = len(self.photos)\n self.num = None # текущий номер файла, сейчас отображается\n self.name = None\n self.img = None\n self.need_refresh: bool = True\n self.maxsize = (1530, 850)\n if len(self.photos):\n self.refresh(0)\n # self.need_refresh: bool = True\n\n def refresh(self, n: int):\n \"\"\" новй файл из списка. меняем имя и загружаем \"\"\"\n self.num = n\n self.name = self.photos[self.num]\n self.get_img()\n self.need_refresh = True\n\n def get_num_by_name(self, name: str) -> int:\n return self.photos.index(name)\n\n def next_img(self):\n \"\"\" следующий файл циклически становится текущим \"\"\"\n self.num = self.num + 1 if self.num < self.count - 1 else 0\n self.refresh(self.num)\n return\n\n def prev_img(self):\n \"\"\" предыдущий файл циклически становится текущим \"\"\"\n self.num = self.num - 1 if self.num > 0 else self.count - 1\n self.refresh(self.num)\n return\n\n def get_photos(self):\n \"\"\" получить список фотографий \"\"\"\n return [str(p.name) for p in Path(self.folder).glob(self.MASK) if p.is_file()]\n\n def get_dirs(self):\n \"\"\" получить список поддиректорий, добавив .. \"\"\"\n return ['..'] + [str(d.name) for d in Path(self.folder).glob(\"*\") if d.is_dir()]\n\n def get_img(self):\n \"\"\" загрузить файл; проверить по exif, если необходимо - повернуть; промасштабировать \"\"\"\n self.img = Image.open(Path(self.folder) / self.name)\n\n photo_file = self.faces.get_photo(str(self.folder), str(self.name))\n color = 'green'\n if photo_file:\n face_exif = self.faces.photos[str(self.folder)][str(self.name)].faces_exif\n if len(face_exif):\n color = 'yellow'\n else:\n face_exif = [facesstore.FaceInfo(**f) for f in xmpfaces(self.img)]\n\n tag_orientation = 274\n exif = self.img._getexif()\n if exif and exif.get(tag_orientation, None):\n rotate = exif[tag_orientation]\n if rotate == 3:\n self.img = self.img.rotate(180, expand=True)\n elif rotate == 6:\n self.img = self.img.rotate(270, expand=True)\n elif rotate == 8:\n self.img = self.img.rotate(90, expand=True)\n else:\n rotate = None\n\n self.img.thumbnail(self.maxsize)\n if len(face_exif):\n self.draw_faces(face_exif, color=color, rotate=rotate)\n\n def draw_faces(self, faces: list[facesstore.FaceInfo], color: str, rotate=None):\n draw = ImageDraw.Draw(self.img)\n for face in faces:\n xy = get_face_rect(xywh=(face.x, face.y, face.w, face.h), im_wh=self.img.size, rotate=rotate)\n draw.rectangle(xy, fill=None, width=1, outline=color)\n if face.name:\n draw.text((xy[0], xy[1]-14), face.name, font=self.fnt, fill=color)\n\n def get_img_data(self):\n \"\"\" Вернуть img в формате png (из-за ограничений tkinter) \"\"\"\n if not self.img:\n return None\n bio = io.BytesIO()\n self.img.save(bio, format=\"PNG\")\n return bio.getvalue()\n\n def status(self) -> str:\n return f' {self.num + 1}/{self.count} ' + str(Path(self.folder) / self.name) if self.name else ''\n","repo_name":"rejgan318/fctests","sub_path":"folderphoto.py","file_name":"folderphoto.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"29048578951","text":"from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton\n\n\ndef get_url_button(text: str, url: str) -> InlineKeyboardMarkup:\n \"\"\"\n Сгенерировать клавиатуру с одной кнопкой, с приклепленной к ней ссылкой\n :param text: Текст на кнопке\n :param url: Ссылка\n :return: Клавиатура с кнопкой\n \"\"\"\n keyboard = InlineKeyboardMarkup()\n button = InlineKeyboardButton(text=text, url=url)\n keyboard.add(button)\n return keyboard\n","repo_name":"BolatMukashev/bot_pay","sub_path":"keyboards/inline/button_with_url.py","file_name":"button_with_url.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"7136102575","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.service import Service\n\n# Create Service class Object\nserv_obj = Service(\"G:\\INFOSYS Lectures & Codes\\Stream Training\\JAR Files\\CD.exe\")\n\ndriver = webdriver.Chrome(service=serv_obj)\n\ndriver.get(\"https://testautomationpractice.blogspot.com/\")\ndriver.maximize_window()\n\n# 1) Count number of Rows and Columns\n\nnoOfrows = len(driver.find_elements(By.XPATH, \"//table[@name='BookTable']//tr\"))\nprint(\"No of Rows are : \", noOfrows)\n\nnofOfcolumns = len(driver.find_elements(By.XPATH, \"//table[@name='BookTable']//tr/th\"))\nprint(\"No of Columns are: \", nofOfcolumns)\n\nprint(\"-----------------------------------------------------------------------\")\n# 2) Read specific row and column data\n\n# a = driver.find_element(By.XPATH, \"//table[@name='BookTable']//tr[5]/td[1]\").text\n# print(a)\n#\n# b = driver.find_element(By.XPATH, \"//table[@name='BookTable']//tr[3]/td[3]\").text\n# print(b)\n\nprint(\"-----------------------------------------------------------------------\")\n\n# 3) Read all the rows & column data\n\"\"\"\nprint(\"------------Printing all the rows and columns --------------------------\")\n\nfor r in range(2, noOfrows + 1):\n for c in range(1, nofOfcolumns + 1):\n data = driver.find_element(By.XPATH, \"//table[@name='BookTable']//tr[\" + str(r) + \"]/td[\" + str(c) + \"]\").text\n print(data, end=\" \")\n print()\n \n \"\"\"\nprint(\"------------------Read data based on condition----------------------------------------\")\n# 4) Read data based on condition\n\nfor r in range(2, noOfrows + 1):\n authorName = driver.find_element(By.XPATH, \"//table[@name='BookTable']/tbody/tr[\" + str(r) + \"]/td[2]\").text\n\n if authorName == \"Mukesh\":\n bookName = driver.find_element(By.XPATH, \"//table[@name='BookTable']/tbody/tr[\" + str(r) + \"]/td[1]\").text\n price = driver.find_element(By.XPATH, \"//table[@name='BookTable']/tbody/tr[\" + str(r) + \"]/td[4]\").text\n print(bookName, \" \", authorName, \" \" , price)\n\ndriver.close()\n","repo_name":"Brijesh-Singh-git/Python","sub_path":"WebElement Interactions Part 2/1-Web_Tables-STATIC_TABLES.py","file_name":"1-Web_Tables-STATIC_TABLES.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"74830533198","text":"from django.contrib.auth.models import User, Group\nfrom observations_manager.serializers import TargetSerializer, ObservationSerializer\nfrom observations_manager.models import Target, Observation\nfrom rest_framework import viewsets, renderers\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import authentication, permissions, generics\nfrom rest_framework.decorators import api_view, renderer_classes\nfrom django.utils.dateparse import parse_date\nfrom fastkml import kml\nfrom shapely.geometry import Point, LineString, Polygon\n\n\nclass TargetViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows target to be viewed or edited.\n \"\"\"\n queryset = Target.objects.all()\n serializer_class = TargetSerializer\n\n\nclass ObservationViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows target to be viewed or edited.\n \"\"\"\n queryset = Observation.objects.all()\n serializer_class = ObservationSerializer\n\n\nclass TargetViewList(generics.ListAPIView):\n serializer_class = TargetSerializer\n\n def get_queryset(self):\n \"\"\"\n This view should return a list of all the targets\n by filtering against a `bounding_box` query parameter.\n \"\"\"\n queryset = Target.objects.all()\n bounding_box = self.request.query_params.get('bounding_box', None)\n if bounding_box is not None:\n queryset = queryset.filter(coordinates__coveredby=bounding_box)\n return queryset\n\n\nclass ObservationViewList(generics.ListAPIView):\n serializer_class = ObservationSerializer\n\n def get_queryset(self):\n \"\"\"\n This view should return a list of all the targets\n by filtering against a `bounding_box`, `start_timestamp`,\n `end_timestamp` query parameters.\n \"\"\"\n\n queryset = Observation.objects.all()\n\n bounding_box = self.request.query_params.get('bounding_box', None)\n\n start_timestamp = str(\n self.request.query_params.get('start_timestamp', None))\n end_timestamp = str(\n self.request.query_params.get('end_timestamp', None))\n\n if bounding_box is not None:\n queryset = queryset.filter(image_polygon__coveredby=bounding_box,\n timestamp__range=(start_timestamp, end_timestamp))\n return queryset\n\n\n@api_view(['GET'])\n@renderer_classes([renderers.StaticHTMLRenderer])\ndef search_target_kml(request, format=None):\n \"\"\"\n A view that returns a kml file for targets given a bounding box\n \"\"\"\n queryset = Target.objects.all()\n\n bounding_box = request.query_params['bounding_box']\n\n if bounding_box == '':\n bounding_box = None\n\n if bounding_box is not None:\n queryset = queryset.filter(coordinates__coveredby=bounding_box)\n\n k = kml.KML()\n ns = '{http://www.opengis.net/kml/2.2}'\n d = kml.Document(ns, 'docid', 'GHGSat Document', 'Display GHGSat targets')\n k.append(d)\n f = kml.Folder(ns, 'folder1', 'Targets', 'Targets features')\n d.append(f)\n\n for target in queryset:\n p = kml.Placemark(ns, str(target.id), str(target.name), 'description')\n p.geometry = Point(target.coordinates.x,\n target.coordinates.y, target.elevation)\n f.append(p)\n\n return Response(k.to_string(prettyprint=True))\n\n\n@api_view(['GET'])\n@renderer_classes([renderers.StaticHTMLRenderer])\ndef search_observations_kml(request, format=None):\n \"\"\"\n A view that returns a kml file for observations given a bounding box and time period\n \"\"\"\n queryset = Observation.objects.all()\n\n bounding_box = request.query_params['bounding_box']\n start_timestamp = request.query_params['start_timestamp']\n end_timestamp = request.query_params['end_timestamp']\n\n if bounding_box == '':\n bounding_box = None\n\n if bounding_box is not None:\n queryset = queryset.filter(image_polygon__coveredby=bounding_box,\n timestamp__range=(\n start_timestamp, end_timestamp))\n\n output = \"\"\"\n \n \n GHGSat Document\n Display GHGSat overlays\n 1\n \n Ground Overlays\n Bouding box Ground overlays\n 1\n \"\"\"\n\n for observation in queryset:\n output = output + \"\"\"\n \n \"\"\" + str(observation.target.name) + \"\"\"\n 1\n Overlay Description.\n \n \"\"\" + str(observation.image_url) + \"\"\"\n \n \n \"\"\" + str(observation.image_polygon.extent[0]) + \"\"\"\n \"\"\" + str(observation.image_polygon.extent[2]) + \"\"\"\n \"\"\" + str(observation.image_polygon.extent[1]) + \"\"\"\n \"\"\" + str(observation.image_polygon.extent[3]) + \"\"\"\n \n \n\t\t\t\t \"\"\" + str(observation.timestamp) + \"\"\"\n\t\t\t\t\n \n \"\"\"\n\n output = output + \"\"\"\n \n \n \n \"\"\"\n\n return Response(output)\n","repo_name":"lgharib/ghgsat-challenge","sub_path":"observation-management-api/app/observations_manager/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1422787362","text":"votantes = int(input(\"Número total de votantes: \"))\ncandidato_1 = candidato_2 = candidato_3 = 0\n\nfor i in range(votantes):\n while True:\n voto = int(input(\"Número do seu candidato (1, 2, 3): \"))\n if voto in [1, 2, 3]:\n if voto == 1:\n candidato_1 += 1\n elif voto == 2:\n candidato_2 += 1\n else:\n candidato_3 += 1\n break\n else:\n print(\"Digite um voto válido\")\n\nprint(f\"O candidato 1 teve {candidato_1} voto(s)\")\nprint(f\"O candidato 2 teve {candidato_2} voto(s)\")\nprint(f\"O candidato 3 teve {candidato_3} voto(s)\")\n","repo_name":"JoseRoberto1506/Faculdade","sub_path":"FPC-1/00 - Python/Slide 03 - Algoritmos/03 - Ex 07.py","file_name":"03 - Ex 07.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"73891494158","text":"\"\"\" \r\nCanvasHeatmap: Module to create heatmap canvas\r\n---------------------------------------------------\r\nPRLEC Framework for OCT Processing and Visualization \r\n\"\"\"\r\n# This framework evolved from a collaboration of:\r\n# - Research Laboratory of Electronics, Massachusetts Institute of Technology, Cambdrige, MA, US\r\n# - Pattern Recognition Lab, Friedrich-Alexander-Universitaet Erlangen-Nuernberg, Germany\r\n# - Department of Biomedical Engineering, Peking University, Beijing, China\r\n# - New England Eye Center, Tufts Medical Center, Boston, MA, US\r\n# v1.0: Updated on Mar 20, 2019\r\n# @author: Daniel Stromer - EMAIL:daniel.stromer@fau.de\r\n# Copyright (C) 2018-2019 - Daniel Stromer\r\n# PRLE is developed as an Open Source project under the GNU General Public License (GPL) v3.0.\r\nimport numpy as np\r\nimport PIL.Image, PIL.ImageTk\r\nfrom tkinter import *\r\nfrom matplotlib import cm\r\nfrom Visualization import Heatmap\r\nfrom Tooltips.TipHandler import CreateToolTip\r\n\r\ndef createCanvasHeatmap(self):\r\n \"\"\" \r\n Creation of heatmap and event handlers.\r\n \r\n The colormap is configured by Image Menu-> Colormap Dropdown.\r\n \r\n Events:\r\n Right-click on canvas: show intensity at position (x,y)\r\n Mouse-wheel: Threshold slider up/down\r\n \r\n Parameters:\r\n ----------\r\n self: object\r\n Framework\r\n \"\"\"\r\n def mousewheelHeatmap(event):\r\n if event.num == 5 or event.delta == -120:\r\n self.heat_slider_min.set(self.heat_slider_min.get()-1)\r\n if event.num == 4 or event.delta == 120:\r\n self.heat_slider_min.set(self.heat_slider_min.get()+1)\r\n \r\n def rightclickHeatmap(event):\r\n if self.SMALLWINDOW is True:\r\n self.LabelIntensityHM.configure(text = str(int(self.heatmapThreshed[int(event.y*2/self.scale_img),int(event.x*2/self.scale_img)])))\r\n else:\r\n self.LabelIntensityHM.configure(text = str(int(self.heatmapThreshed[int(event.y/self.scale_img),int(event.x/self.scale_img)])))\r\n \r\n self.heatmapThreshed = 0\r\n self._job_HM = None\r\n #calculate heatmap and set all heatmaps\r\n self.heatmap_rpe_bruchs = Heatmap.calculateHeatmap(self.segmentation)\r\n self.heatmap = self.heatmap_rpe_bruchs \r\n self.heatmapThreshed = self.heatmap_rpe_bruchs \r\n \r\n #setup frame\r\n self.heightHM, self.widthHM = self.heatmap.shape\r\n if(self.SMALLWINDOW is True):\r\n self.FrameHeatmap = Frame(self.master, width = 1, height = 1, relief=SUNKEN, bg=self.canvasbackground)\r\n else:\r\n self.FrameHeatmap = Frame(self.master, width = 1, height = 1, bg=self.canvasbackground,relief=SUNKEN)\r\n self.FrameHeatmap.grid(row= 0, column = 3,sticky ='nw')\r\n \r\n #Plane and Label for heatmap\r\n if(self.SMALLWINDOW is True):\r\n self.LabelIntensityHM = Label(self.FrameHeatmap, text = 'Right click on pixel',width =31, font=self.clrbarFont, bg=self.canvasbackground,fg =self.canvasforeground)\r\n else:\r\n self.LabelIntensityHM = Label(self.FrameHeatmap, text = 'Right click on pixel',width =62, font=self.clrbarFont, bg=self.canvasbackground,fg =self.canvasforeground)\r\n \r\n self.LabelIntensityHM.grid(row = 0, column = 0)\r\n CreateToolTip(self.LabelIntensityHM, self.ttip_dict['heatmapIntensity'])\r\n if(self.SMALLWINDOW is True):\r\n self.canvas_heat = Canvas(self.FrameHeatmap, width = self.widthHM//2, height = self.heightHM//2, bg=self.canvasbackground,highlightthickness=2,highlightbackground=self.hlghtbg)\r\n else:\r\n self.canvas_heat = Canvas(self.FrameHeatmap, width = self.widthHM, height = self.heightHM, bg=self.canvasbackground,highlightthickness=2,highlightbackground=self.hlghtbg)\r\n self.canvas_heat.grid(row=1,column=0, rowspan=3)\r\n \r\n #mousebindings\r\n self.canvas_heat.bind(\"\", rightclickHeatmap)\r\n self.canvas_heat.bind(\"\", mousewheelHeatmap)\r\n\r\n #scrollbars\r\n self.sbarV_HM = Scrollbar(self.FrameHeatmap, orient=VERTICAL,command=self.getTopYMotion)\r\n self.sbarH_HM = Scrollbar(self.FrameHeatmap, orient=HORIZONTAL,command=self.getTopXMotion)\r\n self.canvas_heat.config(yscrollcommand=self.sbarV_HM.set)\r\n self.canvas_heat.config(xscrollcommand=self.sbarH_HM.set)\r\n self.sbarV_HM.grid(row=1, column = 1, sticky=N+S, rowspan=3)\r\n self.sbarH_HM.grid(row=4, column = 0, sticky=W+E)\r\n self.canvas_heat.configure(scrollregion = self.canvas_heat.bbox(\"all\"))\r\n # Colorbar\r\n self.heatmap_max = np.maximum(10,np.max(self.heatmap))\r\n \r\n self.label_top_HM = Label(self.FrameHeatmap, width = 20,height= 1, text=' '+str(int(self.heatmap_max)),font=self.clrbarFont,anchor=\"nw\", bg=self.canvasbackground, fg =self.canvasforeground)\r\n self.label_top_HM.grid(row=1,column=2)\r\n if(self.SMALLWINDOW == True):\r\n self.canvas_cbar_HM = Canvas(self.FrameHeatmap, width = 18, height = self.heightHM//2 - 50, bg=self.canvasbackground)\r\n else:\r\n self.canvas_cbar_HM = Canvas(self.FrameHeatmap, width=18, height = self.heightHM - 50, bg=self.canvasbackground)\r\n self.canvas_cbar_HM.grid(row=2,column=2,padx=(3, 0),pady = (0,0),sticky=\"nw\")\r\n self.label_bottom_HM = Label(self.FrameHeatmap, width = 20, height= 1, text=\" 0\",font=self.clrbarFont,anchor=\"nw\", bg=self.canvasbackground, fg =self.canvasforeground)\r\n self.label_bottom_HM.grid(row=3,column=2)\r\n \r\n self.cmap_own= cm.get_cmap(self.COLORMAP, self.heatmap_max)\r\n \r\n if(self.SMALLWINDOW == True):\r\n \r\n cmap_std= cm.get_cmap(self.COLORMAP, 256)\r\n \r\n self.cbar_arr = np.array([range(0,self.heightHM//2)[::-1] for i in range(20)]).T.astype('uint8')\r\n self.heatmapThreshedPil = PIL.Image.fromarray(self.cmap_own(self.heatmap[::2,::2], bytes=True))\r\n else:\r\n cmap_std= cm.get_cmap(self.COLORMAP, 256)\r\n\r\n self.cbar_arr = np.zeros((self.heightHM, 20)).astype('uint8')\r\n \r\n for i in range (256):\r\n self.cbar_arr[i*2:i*2+2,:] = i\r\n self.cbar_arr = self.cbar_arr[::-1]\r\n self.heatmapThreshedPil = PIL.Image.fromarray(self.cmap_own(self.heatmap, bytes=True))\r\n \r\n #update canvas with images\r\n self.photo_heat = PIL.ImageTk.PhotoImage(image = self.heatmapThreshedPil)\r\n self.photo_cbar = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(cmap_std(self.cbar_arr, bytes=True)))\r\n \r\n self.image_on_canvas_heat = self.canvas_heat.create_image(0, 0, image=self.photo_heat, anchor=NW)\r\n self.image_on_canvas_cbar = self.canvas_cbar_HM.create_image(0, 0, image=self.photo_cbar, anchor=NW)\r\n \r\n if(self.SMALLWINDOW == True):\r\n self.heat_slider_min = Scale(self.FrameHeatmap, from_=0, to=self.heatmap_max, orient=HORIZONTAL, length = self.widthHM//2, command=self.updateHeatSlice,bg=self.canvasbackground, fg =self.canvasforeground)\r\n else:\r\n self.heat_slider_min = Scale(self.FrameHeatmap, from_=0, to=self.heatmap_max, orient=HORIZONTAL, length = self.widthHM, command=self.updateHeatSlice,bg=self.canvasbackground, fg =self.canvasforeground)\r\n self.heat_slider_min.grid(row=5,column=0)\r\n self.heat_slider_min.set(0)\r\n CreateToolTip(self.heat_slider_min, self.ttip_dict['heatmapThresh'])","repo_name":"RLEMITandPRLFAU/PRLEC","sub_path":"GUI_Classes/CanvasHeatmap.py","file_name":"CanvasHeatmap.py","file_ext":"py","file_size_in_byte":7186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"23197336772","text":"import requests\n\nfrom bs4 import BeautifulSoup\n\nfor i in range(111):\n #print(i + 1)\n j = i + 1\n downloadPage = requests.get(\"https://magpi.raspberrypi.com/issues/\"+ str(j) +\"/pdf/download\")\n detailsPage = requests.get(\"https://magpi.raspberrypi.com/issues/\"+ str(j))\n downloadSoup = BeautifulSoup(downloadPage.content, \"html.parser\")\n detailsSoup = BeautifulSoup(detailsPage.content, \"html.parser\")\n\n links = downloadSoup.find(class_=\"c-link\")\n link_url = links[\"href\"]\n\n print(str(j) +\" : \" + link_url)\n pdf = requests.get(\"https://magpi.raspberrypi.com\" + link_url)\n with open('MagPi' + str(j) + \".pdf\", \"wb\") as file:\n file.write(pdf.content)\n\n details = detailsSoup.find(class_=\"rspec-issue__description\")\n listItems = details.find_all(\"li\")\n\n detailsFile = open('MagPi'+ str(j) + \".txt\", 'a')\n for listItem in listItems:\n detailsFile.write(listItem.prettify())\n #print(listItem.prettify())\n\n detailsFile.close()\n #quit()\n\n \n \n","repo_name":"manicmoddin/magPiDownloader","sub_path":"downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"72347438799","text":"## tcpclient\n## developed by arpbadger with assistance from Justic Seitz, \"Black Hat Python\"\n\nimport socket\n\ntarget_host = \"\" # trying to make this literal a bytes like stirng\ntarget_port = 0\n\n# Pring title page\ndef title_sequence():\n\n\tprint('''\n\t\t\t__ _ _ ___ _\n\t\t/\\ \\ \\___| |___ _____ _ __| | __ / __\\ __ _ __| | __ _ ___ _ __\n\t\t/ \\/ / _ \\ __\\ \\ /\\ / / _ \\| '__| |// /__\\/// _` |/ _` |/ _` |/ _ \\ '__|\n\t\t/ /\\ / __/ |_ \\ V V / (_) | | | < / \\/ \\ (_| | (_| | (_| | __/ |\n\t\t\\_\\ \\/ \\___|\\__| \\_/\\_/ \\___/|_| |_|\\_\\ \\_____/\\__,_|\\__,_|\\__, |\\___|_|\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t|___/\n\t\t\t\t\t\t\t\t\t\t\t\t\t''')\n\treturn\n\n# get domain or target IP and port from the user\ndef get_target():\n\n\tglobal target_host\n\tglobal target_port\n\n\tprint(\"enter target host\")\n\ttarget_host = input()\n\n\tprint(\"enter target port\")\n\ttarget_port = int(input())\n\n\treturn target_host,target_port\n\n# Request http connection\ndef connect(target_host,target_port):\n\n\t#edit target_host variable. I.E cut of www\n\tftarget_host = target_host[2:]\n\t# target_host = int(ftarget_host)\n\toutput = (ftarget_host.encode('utf-8'))\n\n\t#create a socket object\n\tclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n\t#connect the client\n\tclient.connect((target_host,target_port))\n\n\t#send some data\n\t#client.send(\"GET / HTTP/1.1\\r\\nHost: \"+ftarget_host+\"\\r\\n\\r\\n\")\n\toutput = \"GET / HTTP/1.1\\r\\nHost: \"+ftarget_host+\"\\r\\n\\r\\n\"\n\tclient.sendall(output.encode('utf-8'))\n\t#client.send(\"GET / HTTP/1.1\\r\\nHost: 10.0.0.1\\r\\n\\r\\n\")\n\n\n\n\t#receive some data\n\tresponse = client.recv(4096)\n\n\tprint(response)\n\n# Main sequence\ndef main():\n\ttitle_sequence()\n\tget_target()\n\tconnect(target_host,target_port)\n\n# Run the program\nmain()","repo_name":"arpbadger/Library","sub_path":"Python/Black-Hat-Python/chapter 2/tcpclient.py","file_name":"tcpclient.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"37539797986","text":"import unittest\nfrom typing import Callable\n\nfrom pyioc3.builder import BuilderBase\nfrom pyioc3.interface import ProviderBinding, ConstantBinding, FactoryBinding\n\n\nGreeterFactory = Callable[[str], str]\n\n\nclass Foo:\n ...\n\n\nclass FooBuilder(BuilderBase[Foo]):\n def __init__(self, *args, **kwargs):\n super().__init__(Foo, *args, **kwargs)\n\n\ndef eng_greeter_factory(ctx) -> GreeterFactory:\n def greeter_factory(name: str) -> str:\n return f\"Hello, {name}!\"\n\n return greeter_factory\n\n\nclass BuilderTest(unittest.TestCase):\n def test_builder(self):\n foo = FooBuilder().build()\n assert isinstance(foo, Foo)\n\n def test_builder_with_provider_and_constant_defaults(self):\n class Foo_Test(Foo):\n def __init__(self, c: str):\n self.c = c\n\n foo = FooBuilder(\n [\n ProviderBinding(Foo, Foo_Test),\n ConstantBinding(\"bar\", str),\n ]\n ).build()\n assert foo.c == \"bar\"\n\n def test_builder_with_provider_and_constant_and_factory_defaults(self):\n class Foo_Test(Foo):\n def __init__(self, name: str, greet: GreeterFactory):\n self.greeting = greet(name)\n\n foo = FooBuilder(\n [\n ProviderBinding(Foo, Foo_Test),\n ConstantBinding(\"world\", str),\n FactoryBinding(eng_greeter_factory, GreeterFactory),\n ]\n ).build()\n\n assert foo.greeting == \"Hello, world!\"\n\n def test_builder_with_provider_override(self):\n foo = FooBuilder().using_provider(Foo).build()\n assert isinstance(foo, Foo)\n\n def test_builder_with_provider_and_constant(self):\n class Foo_Test(Foo):\n def __init__(self, name: str):\n self.name = name\n\n foo = (\n FooBuilder()\n .using_provider(Foo, Foo_Test)\n .using_constant(str, \"World\")\n .build()\n )\n\n assert foo.name == \"World\"\n\n def test_builder_with_provider_and_constant_and_factory_override(self):\n class Foo_Test(Foo):\n def __init__(self, name: str, greet: GreeterFactory):\n self.greeting = greet(name)\n\n foo = (\n FooBuilder()\n .using_provider(Foo, Foo_Test)\n .using_constant(str, \"World\")\n .using_factory(GreeterFactory, eng_greeter_factory)\n .build()\n )\n\n assert foo.greeting == \"Hello, World!\"\n\n def test_mixed(self):\n class Bar(Foo):\n def __init__(self, name: str, greet: GreeterFactory):\n self.greeting = greet(name)\n\n class FooTestBuilder(BuilderBase[Bar]):\n def __init__(self):\n super().__init__(Bar)\n\n bar = (\n FooTestBuilder()\n .using_constant(str, \"World\")\n .using_factory(GreeterFactory, eng_greeter_factory)\n .build()\n )\n\n assert isinstance(bar, Bar)\n assert bar.greeting == \"Hello, World!\"\n","repo_name":"en0/pyioc3","sub_path":"tests/test_builder_base.py","file_name":"test_builder_base.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"36664488129","text":"from pytube import Playlist\n\nplaylist_url = 'https://www.youtube.com/watch?v=5q3crAMieVU&list=PLPip5lOh2Z5BY936bUdHF8uU0JOK-R5qG'\n\nplaylist = Playlist(playlist_url)\n\n# get the lenth of playlist video\nprint(len(playlist.video_urls))\n\n\n# Get last 3 video url from playlist\n\nfor video in playlist.video_urls[:3]:\n print(video)\n\n# Download Playlist video in High Resolution\n\nfor video in playlist.videos[:10]:\n video.streams.get_highest_resolution().download()\n\nprint('downloaded') \n","repo_name":"GaziAdib/python-youtube-analyser-scrapper","sub_path":"yt_playlist.py","file_name":"yt_playlist.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"30688967944","text":"# This file is part of TRS (http://math.kompiler.org)\n#\n# TRS is free software: you can redistribute it and/or modify it under the\n# terms of the GNU Affero General Public License as published by the Free\n# Software Foundation, either version 3 of the License, or (at your option) any\n# later version.\n#\n# TRS is distributed in the hope that it will be useful, but WITHOUT ANY\n# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\n# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more\n# details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with TRS. If not, see .\nfrom itertools import combinations\n\nfrom .utils import greatest_common_divisor, is_numeric_node\nfrom ..node import ExpressionLeaf as Leaf, Scope, OP_ADD, OP_DIV, OP_MUL, \\\n OP_POW\nfrom ..possibilities import Possibility as P, MESSAGES\nfrom ..translate import _\n\n\ndef match_add_numerics(node):\n \"\"\"\n Combine two constants to a single constant in an n-ary addition.\n\n Example:\n 2 + 3 -> 5\n 2 + -3 -> -1\n -2 + 3 -> 1\n -2 + -3 -> -5\n 0 + 3 -> 3\n 0 + -3 -> -3\n \"\"\"\n assert node.is_op(OP_ADD)\n\n p = []\n scope = Scope(node)\n numerics = []\n\n for n in scope:\n if n == 0:\n p.append(P(node, remove_zero, (scope, n)))\n elif n.is_numeric():\n numerics.append(n)\n\n for c0, c1 in combinations(numerics, 2):\n p.append(P(node, add_numerics, (scope, c0, c1)))\n\n return p\n\n\ndef remove_zero(root, args):\n \"\"\"\n 0 + a -> a\n \"\"\"\n scope, n = args\n scope.remove(n)\n\n return scope.as_nary_node()\n\n\nMESSAGES[remove_zero] = _('Remove addition of zero.')\n\n\ndef add_numerics(root, args):\n \"\"\"\n 2 + 3 -> 5\n 2 + -3 -> -1\n -2 + 3 -> 1\n -2 + -3 -> -5\n \"\"\"\n scope, c0, c1 = args\n scope.replace(c0, Leaf(c0.actual_value() + c1.actual_value()))\n scope.remove(c1)\n\n return scope.as_nary_node()\n\n\nMESSAGES[add_numerics] = _('Add the constants {2} and {3}.')\n\n\ndef match_divide_numerics(node):\n \"\"\"\n Combine two constants to a single constant in a division, if it does not\n lead to a decrease in precision.\n\n Example:\n 6 / 2 -> 3\n 3 / 2 -> 3 / 2 # 1.5 would mean a decrease in precision\n 3.0 / 2 -> 1.5\n 3 / 2.0 -> 1.5\n 3.0 / 2.0 -> 1.5\n 3 / 1.0 -> 3 # Exceptional case: division of integer by 1.0\n # keeps integer precision\n 2 / 4 -> 1 / 2 # 1 < greatest common divisor <= nominator\n 4 / 3 -> 1 + 1 / 3 # nominator > denominator\n \"\"\"\n assert node.is_op(OP_DIV)\n\n n, d = node\n\n if n.negated or d.negated:\n return []\n\n nv, dv = n.value, d.value\n\n if n.is_int() and d.is_int():\n mod = nv % dv\n\n if not mod:\n # 6 / 2 -> 3\n # 3 / 2 -> 3 / 2\n return [P(node, divide_numerics)]\n\n gcd = greatest_common_divisor(nv, dv)\n\n if 1 < gcd <= nv:\n # 2 / 4 -> 1 / 2\n return [P(node, reduce_fraction_constants, (gcd,))]\n\n #if nv > dv:\n # # 4 / 3 -> 1 + 1 / 3\n # return [P(node, fraction_to_int_fraction,\n # ((nv - mod) / dv, mod, dv))]\n elif n.is_numeric() and d.is_numeric():\n if d == 1.0:\n # 3 / 1.0 -> 3\n dv = 1\n\n # 3.0 / 2 -> 1.5\n # 3 / 2.0 -> 1.5\n # 3.0 / 2.0 -> 1.5\n return [P(node, divide_numerics)]\n\n return []\n\n\ndef divide_numerics(root, args):\n \"\"\"\n Combine two divided constants into a single constant.\n\n Examples:\n 6 / 2 -> 3\n 3.0 / 2 -> 1.5\n 3 / 2.0 -> 1.5\n 3.0 / 2.0 -> 1.5\n 3 / 1.0 -> 3\n \"\"\"\n n, d = root\n\n return Leaf(n.value / d.value, negated=root.negated)\n\n\nMESSAGES[divide_numerics] = _('Constant division {0} reduces to a number.')\n\n\ndef reduce_fraction_constants(root, args):\n \"\"\"\n Reduce the nominator and denominator of a fraction with a given greatest\n common divisor.\n\n Example:\n 2 / 4 -> 1 / 2\n \"\"\"\n gcd = args[0]\n a, b = root\n\n return Leaf(a.value / gcd) / Leaf(b.value / gcd)\n\n\nMESSAGES[reduce_fraction_constants] = \\\n _('Divide the nominator and denominator of fraction {0} by {1}.')\n\n\ndef match_multiply_numerics(node):\n \"\"\"\n 3 * 2 -> 6\n 3.0 * 2 -> 6.0\n 3 * 2.0 -> 6.0\n 3.0 * 2.0 -> 6.0\n \"\"\"\n assert node.is_op(OP_MUL)\n\n p = []\n scope = Scope(node)\n numerics = filter(is_numeric_node, scope)\n\n for n in numerics:\n if n.value == 0:\n p.append(P(node, multiply_zero, (n,)))\n\n if not n.negated and n.value == 1:\n p.append(P(node, multiply_one, (scope, n)))\n\n for c0, c1 in combinations(numerics, 2):\n p.append(P(node, multiply_numerics, (scope, c0, c1)))\n\n return p\n\n\ndef multiply_zero(root, args):\n \"\"\"\n 0 * a -> 0\n -0 * a -> -0\n \"\"\"\n return args[0].negate(root.negated)\n\n\nMESSAGES[multiply_zero] = _('Multiplication with zero yields zero.')\n\n\ndef multiply_one(root, args):\n \"\"\"\n 1 * a -> a\n -1 * a -> -a\n \"\"\"\n scope, one = args\n scope.remove(one)\n\n return scope.as_nary_node().negate(one.negated)\n\n\nMESSAGES[multiply_one] = _('Multiplication with one yields the multiplicant.')\n\n\ndef multiply_numerics(root, args):\n \"\"\"\n Combine two constants to a single constant in an n-ary multiplication.\n\n Example:\n 2 * 3 -> 6\n \"\"\"\n scope, c0, c1 = args\n\n # Replace the left node with the new expression\n substitution = Leaf(c0.value * c1.value, negated=c0.negated + c1.negated)\n scope.replace(c0, substitution)\n\n # Remove the right node\n scope.remove(c1)\n\n return scope.as_nary_node()\n\n\nMESSAGES[multiply_numerics] = _('Multiply constant {2} with {3}.')\n\n\ndef match_raise_numerics(node):\n \"\"\"\n 2 ^ 3 -> 8\n (-2) ^ 3 -> -8\n (-2) ^ 2 -> 4\n \"\"\"\n assert node.is_op(OP_POW)\n\n r, e = node\n\n if r.is_numeric() and e.is_numeric() and not e.negated:\n return [P(node, raise_numerics, (r, e, node.negated))]\n\n return []\n\n\ndef raise_numerics(root, args):\n \"\"\"\n 2 ^ 3 -> 8\n (-2) ^ 3 -> -8\n (-2) ^ 2 -> 4\n \"\"\"\n r, e, negated = args\n\n return Leaf(r.value ** e.value, negated=r.negated * e.value + negated)\n\n\nMESSAGES[raise_numerics] = _('Raise constant {1} with {2}.')\n","repo_name":"smvv/trs","sub_path":"src/rules/numerics.py","file_name":"numerics.py","file_ext":"py","file_size_in_byte":6480,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"20923353184","text":"import random\nclass ramalan:\n def __init__(self, harga, pilihan = 0):\n self.cost = harga\n self.pilih = pilihan\n self.ramalan1 = {1: 'Menganggur', \n 2: 'Kerja gajinya kecil', \n 3: 'Kerja cukup nyaman', \n 4: 'Kerja gajinya besar tapi ga nyaman', \n 5: 'Kerja gajinya besar dan nyaman'}\n self.ramalan2 = {1: 'Terkena sakit kronis', \n 2: 'Gejala sakit kronis', \n 3: 'Badan lemes', \n 4: 'Terserang Flu, Demam', \n 5: 'Sehat Jasmani Rohani'}\n self.ramalan3 = {1: 'Jomblo seumur hidup', \n 2: 'Nembak gebetan ditolak', \n 3: 'Dapet Pacar', \n 4: 'Menikah dengan pasangan idaman', \n 5: 'Menikah dan hidup bahagia selamanya'}\n \n def result_ramalan(self):\n list_Ramalan = {}\n list_Prob = []\n if self.pilih == 1:\n list_Ramalan = self.ramalan1\n elif self.pilih == 2:\n list_Ramalan = self.ramalan2\n elif self.pilih == 3:\n list_Ramalan = self.ramalan3\n \n if self.cost > 10000 and self.cost < 50000:\n for i in range(80):\n list_Prob.append(list_Ramalan[random.randint(3, 5)])\n for i in range(10):\n list_Prob.append(list_Ramalan[2])\n for i in range(10):\n list_Prob.append(list_Ramalan[1])\n elif self.cost == 10000:\n for i in range(10):\n list_Prob.append(list_Ramalan[5])\n for i in range(80):\n list_Prob.append(list_Ramalan[random.randint(2, 4)])\n for i in range(10):\n list_Prob.append(list_Ramalan[1])\n elif self.cost < 10000:\n for i in range(10):\n list_Prob.append(list_Ramalan[5])\n for i in range(10):\n list_Prob.append(list_Ramalan[4])\n for i in range(80):\n list_Prob.append(list_Ramalan[random.randint(1, 3)])\n print('\\n Hasil Ramalan: ' + list_Prob[random.randint(0,99)])\n\n def menu(self):\n print('\\nPilih ramalan Anda: \\n1. Ramalan Pekerjaan \\n2. Ramalan Kesehatan \\n3. Ramalan Percintaan \\n4. Keluar')\n pilihan = int(input('Masukkan Pilihan: '))\n if pilihan > 0 and pilihan < 4:\n self.pilih = pilihan\n self.result_ramalan()\n elif pilihan == 4:\n print('Terima Kasih')\n\nAsril = ramalan(15000)\nAsril.menu()","repo_name":"asrilirsadi/Python_Exercises","sub_path":"Ramalan_Terkini.py","file_name":"Ramalan_Terkini.py","file_ext":"py","file_size_in_byte":2625,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"43814551091","text":"class Solution:\n def areNumbersAscending(self, s: str) -> bool:\n s = s.split(\" \")\n prev = 0\n for i in s:\n if i.isnumeric():\n print(prev, int(i))\n if prev!=-1 and prev < int(i):\n prev = int(i)\n else:\n return False\n return True\n","repo_name":"CaptAlpha/Leety","sub_path":"2168-check-if-numbers-are-ascending-in-a-sentence/check-if-numbers-are-ascending-in-a-sentence.py","file_name":"check-if-numbers-are-ascending-in-a-sentence.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"71609039758","text":"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom app01 import views\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^login/', views.login),\n url(r'^index/', views.index),\n url(r'^return_goods/', views.return_goods),\n url(r'^add_goods/', views.add_goods),\n url(r'^del_goods/', views.del_goods),\n url(r'^exchange/', views.exchange),\n]\n","repo_name":"Fangqihan/perssion_sys","sub_path":"perssion_sys/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34523893817","text":"from typing import AsyncIterator, AsyncIterable\n\nimport pytest\nfrom grpclib.testing import ChannelFor\n\nfrom tests.output_betterproto.example_service.example_service import (\n TestBase,\n TestStub,\n ExampleRequest,\n ExampleResponse,\n)\n\n\nclass ExampleService(TestBase):\n async def example_unary_unary(\n self, example_string: str, example_integer: int\n ) -> \"ExampleResponse\":\n return ExampleResponse(\n example_string=example_string,\n example_integer=example_integer,\n )\n\n async def example_unary_stream(\n self, example_string: str, example_integer: int\n ) -> AsyncIterator[\"ExampleResponse\"]:\n response = ExampleResponse(\n example_string=example_string,\n example_integer=example_integer,\n )\n yield response\n yield response\n yield response\n\n async def example_stream_unary(\n self, request_iterator: AsyncIterator[\"ExampleRequest\"]\n ) -> \"ExampleResponse\":\n async for example_request in request_iterator:\n return ExampleResponse(\n example_string=example_request.example_string,\n example_integer=example_request.example_integer,\n )\n\n async def example_stream_stream(\n self, request_iterator: AsyncIterator[\"ExampleRequest\"]\n ) -> AsyncIterator[\"ExampleResponse\"]:\n async for example_request in request_iterator:\n yield ExampleResponse(\n example_string=example_request.example_string,\n example_integer=example_request.example_integer,\n )\n\n\n@pytest.mark.asyncio\nasync def test_calls_with_different_cardinalities():\n test_string = \"test string\"\n test_int = 42\n\n async with ChannelFor([ExampleService()]) as channel:\n stub = TestStub(channel)\n\n # unary unary\n response = await stub.example_unary_unary(\n example_string=\"test string\",\n example_integer=42,\n )\n assert response.example_string == test_string\n assert response.example_integer == test_int\n\n # unary stream\n async for response in stub.example_unary_stream(\n example_string=\"test string\",\n example_integer=42,\n ):\n assert response.example_string == test_string\n assert response.example_integer == test_int\n\n # stream unary\n request = ExampleRequest(\n example_string=test_string,\n example_integer=42,\n )\n\n async def request_iterator():\n yield request\n yield request\n yield request\n\n response = await stub.example_stream_unary(request_iterator())\n assert response.example_string == test_string\n assert response.example_integer == test_int\n\n # stream stream\n async for response in stub.example_stream_stream(request_iterator()):\n assert response.example_string == test_string\n assert response.example_integer == test_int\n","repo_name":"girtsf/python-betterproto","sub_path":"tests/inputs/example_service/test_example_service.py","file_name":"test_example_service.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"13091388667","text":"class Board:\n board = list(range(1, 10))\n\n def take_input(self, symbol):\n valid = False\n while not valid:\n answer = input(\"Куда поставим \" + symbol + \"? \")\n try:\n answer = int(answer)\n except:\n print(\"Некорректный ввод. Вы уверены, что ввели число?\")\n continue\n if 1 <= answer <= 9:\n if str(self.board[answer - 1]) not in \"XO\":\n self.board[answer - 1] = symbol\n valid = True\n else:\n print(\"Эта клетка уже занята!\")\n else:\n print(\"Некорректный ввод. Введите чис��о от 1 до 9.\")\n\n def draw_board(self):\n print(\"-\" * 13)\n for i in range(3):\n print(\"|\", self.board[0 + i * 3], \"|\", self.board[1 + i * 3], \"|\", self.board[2 + i * 3], \"|\")\n print(\"-\" * 13)\n\n def check_win(self):\n win_coord = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))\n for each in win_coord:\n if self.board[each[0]] == self.board[each[1]] == self.board[each[2]]:\n return self.board[each[0]]\n return False\n\n\nboard = Board()\ntoken_1 = 'X'\ntoken_2 = 'O'\n\nstep = 1\nwhile step != 10:\n\n board.draw_board()\n if step % 2 != 0:\n player_token = token_1\n else:\n player_token = token_2\n board.take_input(player_token)\n if step > 4:\n if board.check_win():\n print(board.check_win(), 'победил!')\n break\n step += 1\n\nelse:\n print('НИЧЬЯ!')\n","repo_name":"chingizmalyukov/python","sub_path":"Module24/09_tic-tac-toe/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34465994167","text":"\"\"\"View a 3D mesh of SRTM1 data in PNG format at various mesh resolutions\"\"\"\nfrom meshmaker.plt import *\nfrom meshmaker.mgl import show\nfrom meshmaker.vec3 import vec3\nfrom meshmaker.mesh import Mesh\nfrom meshmaker.model import Model\nfrom meshmaker.tform import TForm\nfrom meshmaker.field import scalar_field\nfrom pyglet.window import key\nimport cv2\nimport argparse\n\n\nclass ProgressiveTerrain:\n \"\"\"Class which represents grayscale heightmaps with a mesh\n that can be progressively subdivided for better resolution\"\"\"\n\n @staticmethod\n def height_field(img):\n pixels = len(img)\n origin = vec3(pixels / 2, pixels / 2, 0)\n radius = pixels // 2\n deltaz = radius\n wtoi = TForm(t=vec3(pixels / 2, pixels / 2, 0) - origin,\n s=vec3(pixels / (2 * radius), pixels / (2 * radius), 1))\n field = scalar_field.topography(img, wtoi, 1.0)\n field.origin = origin\n field.radius = radius\n field.deltaz = deltaz\n field.z0, field.dz = img.min(), img.max() - img.min()\n return field\n\n def __init__(self, height_img, sealevel=0.25):\n self.height = self.height_field(height_img)\n self.sealevel = sealevel\n self.divisions = 0\n\n self.dlevel = 0.1\n self.parameters = {\n key.RIGHT: self.divide,\n key.LEFT: self.undivide,\n key.UP: self.increase_sealevel,\n key.DOWN: self.decrease_sealevel,\n key.K: self.increase_deltaz,\n key.J: self.decrease_deltaz,\n }\n\n print('Controls:')\n for button, func in self.parameters.items():\n name = func.__name__[func.__name__.rfind('.'):]\n print(f'Key: {button} -> {name}')\n\n def divide(self, *ags):\n self.divisions += 1\n\n def undivide(self, *ags):\n self.divisions = max(0, self.divisions - 1)\n\n def increase_deltaz(self, *ags):\n self.height.deltaz *= 1.1\n\n def decrease_deltaz(self, *ags):\n self.height.deltaz /= 1.1\n\n def increase_sealevel(self, *ags):\n self.sealevel += 0.05\n\n def decrease_sealevel(self, *ags):\n self.sealevel -= 0.05\n\n def scene(self):\n \"\"\"Remake the land/sea meshes and return them in a scenegraph\n (NOTE: This method is called by the rendering window)\"\"\"\n height = self.height\n land, sea = Mesh(), Mesh()\n for u, v, w in height.origin.fan(height.radius, 6, True):\n sea.af((u.cp(), v.cp(), w.cp()))\n land.af((u.cp(), v.cp(), w.cp()))\n for i in range(self.divisions):\n land = land.subdivide()\n print(f'Triangles: {len(land.faces) + len(sea.faces)}')\n sealevel = (height.z0 + self.sealevel * height.dz)\n for v in sea.vertices:\n if v is not None:\n v.z = sealevel * height.deltaz\n for v in land.vertices:\n if v is not None:\n v.z = height(v) * height.deltaz\n land.uvs = land.project_uvs_xy(0.1)\n sea.uvs = sea.project_uvs_xy(0.1)\n land.normals = land.vertex_normals(smooth=True)\n root = TForm(s=vec3.U(20.0 / 3600.0))\n root.add(TForm(models=[Model(meshes={'generic_13': [land]})]))\n root.add(TForm(models=[Model(meshes={'generic_10': [sea]})]))\n return root\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='View SRTM1 data in PNG format')\n parser.add_argument('--png', type=str,\n default='./srtm1/N38W112.png',\n help='Which PNG to visualize')\n args = parser.parse_args()\n\n height = cv2.imread(args.png, cv2.IMREAD_GRAYSCALE)\n height = height / height.max()\n #height = height[400:600, 400:600]\n height = height[600:1000, 200:600]\n\n f, ax = plot()\n im = ax.imshow(height, origin='lower')\n plt.show()\n\n show(ProgressiveTerrain(height),\n texture_directory='../../resources/textures')\n","repo_name":"ctogle/meshmaker","sub_path":"examples/progressive_terrain/view_terrain.py","file_name":"view_terrain.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"35345893251","text":"import os\n\nimport StockAnalysisSystem.api as sas_api\nfrom StockAnalysisSystem.core.Utility.time_utility import *\n\nfrom StockAnalysisSystem.core.Trader.Market import MarketBackTesting\nfrom StockAnalysisSystem.core.Trader.TradeStrategy import *\nfrom StockAnalysisSystem.core.Trader.Broker import Broker\n\n\nproject_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nsas_api.config_set('NOSQL_DB_HOST', 'localhost')\nsas_api.config_set('NOSQL_DB_PORT', '27017')\nsas_api.config_set('TS_TOKEN', 'xxxxxxxxxxxx')\n\nif not sas_api.init(project_path, True):\n print('sas init fail.')\n print('\\n'.join(sas_api.error_log()))\n quit(1)\n\nmarket = MarketBackTesting(sas_api.get_data_hub_entry(), text_auto_time('2018-01-01'), text_auto_time('2020-01-01'))\nbroker = Broker(market)\ntrader = GridTrader(market, broker, '000001.SZSE', 7.0, 4.0, 5)\n\nmarket.load_back_testing_data('000001.SZSE', True)\nmarket.watch_security('000001.SZSE', broker)\nmarket.watch_security('000001.SZSE', trader)\n# market.run()\nmarket.back_testing_entry()\n\nprint('Finally total position:\\n' + str(broker.position().statistics(market)))\n\n\n\n\n\n\n\n\n\n\n","repo_name":"SleepySoft/StockAnalysisSystem","sub_path":"Test/manual/test_trader.py","file_name":"test_trader.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":138,"dataset":"github-code","pt":"29"} +{"seq_id":"73953562637","text":"from sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.model_selection import GridSearchCV\nimport preprocess as pp\nimport evaluate as evl\nimport feature_selection as fs\n\n\ndef grid_search(classifier):\n param_dict = {\n \"n_estimators\": [50, 100, 150, 200, 250],\n \"criterion\": [\"friedman_mse\", \"mse\"],\n \"learning_rate\": [0.1, 0.2, 0.3, 0.4, 0.5],\n \"max_depth\": range(3, 6)\n }\n\n rfc_gs = GridSearchCV(estimator=classifier, param_grid=param_dict, scoring=\"accuracy\",\n cv=5, verbose=True,\n n_jobs=-1)\n rfc_gs.fit(x_train, y_train)\n\n print(\"Best estimator:\\n\", rfc_gs.best_params_)\n print(\"Best score: \", rfc_gs.best_score_)\n\n return rfc_gs.best_estimator_\n\n\n# get data\ndata = pp.import_data()\nx_train, x_test, y_train, y_test = pp.preprocess(data, hnd_outliers=True, var_threshold=False)\n\n# pca feature selection\n# x_train, x_test = fs.pca_selection(x_train, x_test, 9)\n#\n\n# random forest classifier\nrfc = GradientBoostingClassifier(random_state=20, n_estimators=200, max_depth=5,\n learning_rate=0.2, criterion=\"mse\")\n\n# recursive elimination feature selection\nx_train, x_test = fs.recursive_f_elimination(estimator=rfc, x_train=x_train, y_train=y_train, x_test=x_test)\n#\n\nmodel = rfc.fit(x_train, y_train)\ny_pred = rfc.predict(x_test)\n#\n\n# cross validation score\nevl.cross_val_eval(rfc, x_train, y_train, 5)\n\n# accuracy, recall, precision, f1\nevl.evaluate_model(y_test, y_pred)\n\n# confusion matrix\nevl.confusion_matrix(y_test, y_pred, data, True, \"gradient_boost\")\n","repo_name":"LastChanceKatze/ml_wine_quality","sub_path":"scipts/gradient_boost.py","file_name":"gradient_boost.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"6886572722","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.urls import reverse\nfrom django.views import View\nfrom django.views.generic import DetailView, ListView, FormView\nfrom django.views.generic.base import View\nfrom django.views.generic.detail import SingleObjectMixin\nfrom django.views.generic.edit import CreateView, UpdateView\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\nfrom django.db.models import Exists, OuterRef, Subquery\nfrom prompts.models import Prompt, PromptStory\nfrom prompts.forms import PromptSubmissionForm\nfrom prompts.mixins import CSVResponseMixin\nfrom unfold_studio.models import Story, Book\nfrom reversion.models import Version\nimport logging\nfrom literacy_events.models import LiteracyEvent\nfrom literacy_groups.models import LiteracyGroup\nfrom literacy_groups.mixins import LiteracyGroupContextMixin\nfrom collections import defaultdict\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib import messages\n\nlog = logging.getLogger(__name__) \n\ndef u(request):\n \"Helper to return username\"\n return request.user.username if request.user.is_authenticated else \"\"\n\nclass ShowPromptView(LiteracyGroupContextMixin, DetailView):\n model = Prompt\n context_object_name = 'prompt'\n\n def get_queryset(self):\n return self.group.prompts.filter(deleted=False)\n\n def get_context_data(self, **kwargs):\n self.object = self.get_object()\n context = super().get_context_data(**kwargs)\n form = PromptSubmissionForm()\n form.fields['story'].choices = [(s.id, s.title) for s in self.request.user.stories.all()]\n context['form'] = form\n context['group'] = self.group\n context['submission'] = self.get_object().submissions.filter(author=self.request.user).first()\n if self.user_is_leader:\n context = self.get_context_data_for_leader(context)\n return context\n\n def get_context_data_for_leader(self, context):\n submissions = self.object.submissions.prefetch_related('author').all()\n submissions_by_member = {s.author : s for s in submissions}\n context['member_submissions'] = [\n (m, submissions_by_member.get(m), self.has_new_material(submissions_by_member.get(m)))\n for m in self.group.members.all()\n ]\n return context\n\n # TODO slow. Should be done with a subquery.\n def has_new_material(self, story):\n \"\"\"\n Returns a boolean indicating whether or not the story has something new the prompt owner may\n want to respond to.\n \"\"\"\n if story is None: \n return False\n if not story.comments.filter(author__in=self.group.leaders.all()).exists():\n return True\n latestTeacherComment = story.comments.filter(author__in=self.group.leaders.all()).order_by(\n '-creation_date').first()\n return (\n story.comments.filter(\n author=story.author, \n creation_date__gt=latestTeacherComment.creation_date\n ).exists() or \n Version.objects.get_for_object(story).filter(\n revision__date_created__gt=latestTeacherComment.creation_date\n ).exclude(\n revision__comment__exact=''\n ).exists()\n )\n \n def get_template_names(self):\n if self.user_is_leader:\n return [\"prompts/show_prompt_as_leader.html\"]\n else:\n return [\"prompts/show_prompt.html\"]\n\n def post(self, *args, **kwargs):\n \"Handle submission to a prompt\"\n form = PromptSubmissionForm(self.request.POST)\n form.fields['story'].choices = [(s.id, s.title) for s in self.request.user.stories.all()]\n if form.is_valid():\n prompt = self.get_object()\n story = Story.objects.get_editable_for_request_or_404(self.request, pk=form.cleaned_data['story'])\n version = Version.objects.get_for_object(story).last()\n PromptStory.objects.create(prompt=self.get_object(), story=story, \n submitted_story_version=version)\n log.info(\"{} submitted story {} to prompt {}\".format(u(self.request), story, self.get_object()))\n LiteracyEvent.objects.create(\n event_type=LiteracyEvent.SUBMITTED_TO_PROMPT,\n subject=self.request.user,\n story=story,\n prompt=self.get_object(),\n literacy_group=self.get_object().literacy_group,\n )\n if prompt.book:\n prompt.book.stories.add(story)\n return redirect('show_prompt', self.group.id, self.get_object().id)\n else:\n context = self.get_context_data()\n context['form'] = form\n return render(request, self.template_name, context)\n\nclass CreatePromptView(LiteracyGroupContextMixin, CreateView):\n model = Prompt\n url_group_key = \"pk\"\n fields = ['name', 'description', 'due_date']\n\n def post(self, request, *args, **kwargs):\n prompt = Prompt(\n author = self.request.user,\n literacy_group=self.group,\n creation_date=timezone.now()\n )\n form = self.get_form_class()(request.POST, instance=prompt)\n if form.is_valid():\n prompt = form.save()\n log.info(\"{} created prompt {} (id: {})\".format(request.user, prompt.name, prompt.id))\n return redirect('show_prompt', self.group.id, prompt.id)\n else:\n context = self.get_context_data(form=form)\n return render('prompts/prompt_form.html', context=context)\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['title'] = \"Create new prompt\"\n context['group'] = self.group\n return context\n\n\nclass UpdatePromptView(LiteracyGroupContextMixin, UpdateView):\n model = Prompt\n fields = ['name', 'description', 'due_date']\n\n def get_queryset(self):\n return self.group.prompts\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['title'] = \"Edit prompt\"\n context['group'] = self.group\n return context\n\n def get_success_url(self):\n return reverse('show_prompt', args=(self.group.id, self.get_object().id))\n\nclass DeletePromptView(LiteracyGroupContextMixin, SingleObjectMixin, View):\n require_leader = True\n\n def post(self, request, *args, **kwargs):\n prompt = self.get_object()\n prompt.deleted = True\n prompt.save()\n messages.success(request, \"Deleted {}\".format(prompt.name))\n return redirect('show_group', self.group.id)\n\n def get_queryset(self):\n return self.group.prompts.filter(deleted=False)\n\nclass ExportPromptAsCsvView(LiteracyGroupContextMixin, CSVResponseMixin, DetailView):\n queryset = Prompt.objects\n\n def get_csv_filename(self):\n return timezone.now().strftime(\"unfold-studio-group-{}-prompt-{}-%Y-%m-%d.csv\".format(\n self.group.id, self.get_object().id))\n\n def get(self, request, *args, **kwargs):\n submissions_by_user = {s.author: s for s in self.get_object().submissions.all()}\n member_submissions = [(m, submissions_by_user.get(m)) for m in self.group.members.all()]\n values = [(m.username, s.title if s else None, s.id if s else None, reverse('show_story', args=(s.id,)) if s else None) for m, s in member_submissions]\n fields = ['username', 'story_title', 'story_id', 'story_url']\n log.info(\"{} downloaded prompt {} (group {}) as CSV\".format(request.user, self.get_object().id, self.group.id))\n return self.render_to_csv(values, fieldnames=fields)\n\nclass ClearPromptSubmissionView(LiteracyGroupContextMixin, SingleObjectMixin, View):\n http_method_names = ['post']\n def post(self, *args, **kwargs):\n prompt = self.get_object()\n ps = PromptStory.objects.get(\n prompt=prompt, \n story__author=self.request.user\n )\n story = ps.story\n ps.delete()\n log.info(\"{} cleared submitted story {} from prompt {}\".format(u(self.request), story, self.get_object()))\n LiteracyEvent.objects.create(\n event_type=LiteracyEvent.UNSUBMITTED_FROM_PROMPT,\n subject=self.request.user,\n story=story,\n prompt=self.get_object(),\n literacy_group=self.get_object().literacy_group,\n )\n if prompt.book:\n prompt.book.stories.remove(story)\n return redirect('show_prompt', self.group.id, prompt.id)\n\n def get_queryset(self):\n return self.group.prompts\n\nclass PublishAsBookView(LiteracyGroupContextMixin, SingleObjectMixin, View):\n http_method_names = ['post']\n require_leader = True\n\n def post(self, request, *args, **kwargs):\n prompt = self.get_object()\n if prompt.book:\n messages.warning(request, \"{} is already published as a book\".format(prompt.name))\n log.warning(\"{} tried to re-publish {} as a book\".format(request.user), prompt.name)\n return redirect('show_prompt', prompt.id)\n book_desc = \"This automatically-generated book contains stories submitted to @prompt:{}\".format(prompt.id)\n book = Book.objects.create(\n owner=request.user, \n title=\"Submissions to {}\".format(prompt.name),\n description=book_desc\n )\n book.sites.add(prompt.literacy_group.site)\n prompt.book = book\n prompt.save()\n for story in prompt.submissions.all():\n book.stories.add(story)\n log.info(\"{} published {} as a book\".format(request.user, prompt.name))\n LiteracyEvent.objects.create(\n event_type=LiteracyEvent.PUBLISHED_PROMPT_AS_BOOK,\n subject=self.request.user,\n prompt=prompt,\n book=book,\n literacy_group=prompt.literacy_group,\n )\n return redirect('show_book', book.id)\n \n def get_queryset(self):\n return self.group.prompts.filter(deleted=False)\n\nclass UnpublishBookView(LiteracyGroupContextMixin, SingleObjectMixin, View):\n http_method_names = ['post']\n require_leader = True\n\n def post(self, request, *args, **kwargs):\n prompt = self.get_object()\n if not prompt.book:\n messages.warning(request, \"{} is not published as a book\".format(prompt.name))\n log.warning(\"{} tried to unpublish {} when it was not published\".format(request.user, prompt.name))\n return redirect('show_prompt', self.group.id, prompt.id)\n prompt.book.deleted = True\n prompt.book.save()\n prompt.book = None\n prompt.save()\n log.info(\"{} unpublished {} as a book\".format(request.user, prompt.name))\n LiteracyEvent.objects.create(\n event_type=LiteracyEvent.UNPUBLISHED_PROMPT_AS_BOOK,\n subject=self.request.user,\n prompt=prompt,\n literacy_group=prompt.literacy_group,\n )\n return redirect('show_prompt', self.group.id, prompt.id)\n \n def get_queryset(self):\n return self.group.prompts.filter(deleted=False)\n\n","repo_name":"cproctor/unfold_studio","sub_path":"prompts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11224,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"29"} +{"seq_id":"36552939128","text":"#!/usr/bin/env python\n\n#import parsl\n#import os\n#from parsl.app.app import python_app, bash_app\n#from config.bluewaters import config\n#import sys\n#sys.exit()\n\nimport os\nimport numpy as np\nimport netCDF4 as nc\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as tck\n\ngridname = '/scratch/eot/torres/smol_lat_-20_kn_01/ann_grid.nc'\ndirpath = '/scratch/eot/torres/smol_lat_-20_kn_01/Results/'\nimdest = '/scratch/eot/torres/vis/'\nD = [d for d in os.listdir(dirpath) if d.startswith(\"ocean_avg_ann\")];\nD.sort()\n\n#Grid Variables\nG = nc.Dataset(gridname)\nlon = np.array(G.variables['x_rho'][:,:])/1e3\nlat = np.array(G.variables['y_rho'][:,:])/1e3\nlon_u = np.array(G.variables['x_u'][:,:])/1e3\nlat_u = np.array(G.variables['y_u'][:,:])/1e3\nlon_v = np.array(G.variables['x_v'][:,:])/1e3\nlat_v = np.array(G.variables['y_v'][:,:])/1e3\n\nt = np.squeeze(np.arctan2(lat[0,:],lon[0,:]))\nt = (t[1:]+t[0:-1])/2\n\ndef axinit(ax,title):\n \n #pc.set_array(z[:-1,:-1].ravel()) \n #lp = ax.plot(r,r*0,'w.')\n ax.set_title(title,color = 'w')\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n \n #Dark mode \n ax.set_facecolor('k')\n ax.spines['left'].set_color('w')\n ax.spines['bottom'].set_color('w') \n #ax.xaxis.label.set_color('w')\n #ax.yaxis.label.set_color('w')\n ax.tick_params(axis='x', colors= 'w')\n ax.tick_params(axis='y', colors= 'w')\n return\n\ndef roms_plot(filename): #,imdest,ax,lon,lat,lon_u,lat_u,lon_v,lat_v):\n\n A = nc.Dataset(filename)\n time = np.array(A.variables['ocean_time'][:])\n vrt = np.squeeze(np.array(A.variables['rvorticity'][:,-1,79:,:]))\n #u_e = np.array(A.variables['u'][:,-1,:,:])\n #v_e = np.array(A.variables['v'][:,-1,:,:])\n #u_s = np.array(A.variables['u_stokes'][:,-1,:,:])\n #v_s = np.array(A.variables['v_stokes'][:,-1,:,:])\n #u = np.squeeze(u_e + u_s)\n #v = np.squeeze(v_e + v_s)\n \n #pcv = ax2.pcolormesh(lon_v,lat_v,lon_v*0, vmin = -.25, vmax = .25, cmap = 'RdBu_r')\n #var = np.squeeze(np.mean(vrt**2,axis = 1))\n dy = abs(np.diff(lat[80:,:],axis=1))*1e3\n var = np.trapz( abs(vrt**2)*dy, x = lon[80:,0]*1e3, axis = 1)\n \n #ax.plot(t,vrt_var.T,'w-',linewidth = .1)\n #F.savefig(imdest+\"ann_{:04}.png\".format(int(ind)), dpi=100, facecolor='k', edgecolor = 'none')\n #plt.close(F)\n return var, time\n\nplt.style.use(\"dark_background\")\nF,ax = plt.subplots(1,facecolor = 'k')\naxinit(ax,\"$(\\mathcal{E}')$\")\nax.set_xlabel('Days')\nax.set_ylabel(r'$\\theta$')\n#ax.yaxis.set_major_formatter(tck.FuncFormatter(\n# lambda val,pos: '{:.0g}$\\pi$'.format(val/np.pi) if val !=0 else '0'\n#))\n#ax.yaxis.set_major_locator(tck.MultipleLocator(base=np.pi/12))\n\n\nvar = np.empty( (0,len(t)) ) \ntime = np.empty(0)\nfor f in D:\n print(f)\n filename = dirpath+f\n var_add, time_add = roms_plot(filename) #,lon,lat,lon_u,lat_u,lon_v,lat_v)\n #print(var.shape, var_add.shape)\n var = np.concatenate( (var,var_add), axis = 0)\n time = np.concatenate( (time,time_add) )\n\nT, Time = np.meshgrid(t,time)\n\ndev = var - np.tile( var.mean(axis=0), (len(time),1) )\npc = ax.pcolormesh(Time/3600/24, T, abs(dev), cmap = 'magma', vmin = 0, vmax =.1)\ncb = F.colorbar(pc, ax = ax)\ncb.set_label(r'$\\frac{m^2}{s^2}$', color = 'w')\n#cb.ax.yaxis.set_tick_params(color='w')\n#cb.outline.set_edgecolor('w')\n\nplt.tight_layout()\nF.savefig(\"/u/eot/torres/COAWST/Scripts/varplt.pdf\", facecolor = 'k', edgecolor = None)\nplt.close(F)\n","repo_name":"wingtorres/hpc-tools","sub_path":"bluewaters/arc_vis.py","file_name":"arc_vis.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"31062807837","text":"def chicken(k, cnt):\n global answer\n if cnt == M:\n dis = distance()\n if dis < answer:\n answer = dis\n return\n if k >= len(store):\n return\n if cnt > M:\n return\n visit[k] = 1\n chicken(k +1, cnt + 1)\n visit[k] = 0\n chicken(k+1, cnt)\n\ndef distance():\n dis = 0\n for i in house:\n hy, hx = i[0], i[1]\n dis_min = 1000\n for j in range(len(visit)):\n if visit[j] == 1:\n\n sy, sx = store[j][0], store[j][1]\n temp = abs(hy - sy) + abs(hx - sx)\n if temp < dis_min:\n dis_min = temp\n else:\n continue\n dis += dis_min\n return dis\n\n\n\nN, M = map(int, input().split())\nmatrix = [list(map(int, input().split())) for _ in range(N)]\n\nanswer = 238378489293328989\nhouse = []\nstore = []\nfor i in range(N):\n for j in range(N):\n if matrix[i][j] == 2 :\n store.append([i, j])\n elif matrix[i][j] == 1 :\n house.append([i, j])\n\nvisit= [0]* len(store)\nchicken(0, 0)\n\nprint(answer)","repo_name":"Park-Dasol/Algorithm","sub_path":"SAMSUNG_SW_TEST/15686.py","file_name":"15686.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"70330849999","text":"from openbabel import OBMol, OBConversion, pybel\n\nimport re\n\ninchi_validator = re.compile('InChI=[0-9]S?\\\\/')\n\n\n# This function only validates the first part. It does not guarantee\n# that the entire InChI is valid.\ndef validate_start_of_inchi(inchi):\n if not inchi_validator.match(inchi):\n raise Exception('Invalid InChI: \"' + inchi + '\"')\n\n\n# gen3d should be true for 2D input formats such as inchi or smiles\ndef convert_str(str_data, in_format, out_format, gen3d=False,\n add_hydrogens=False, perceive_bonds=False, out_options=None,\n gen3d_forcefield='mmff94', gen3d_steps=100):\n\n # Make sure that the start of InChI is valid before passing it to\n # Open Babel, or Open Babel will crash the server.\n if in_format.lower() == 'inchi':\n validate_start_of_inchi(str_data)\n\n if out_options is None:\n out_options = {}\n\n obMol = OBMol()\n conv = OBConversion()\n conv.SetInFormat(in_format)\n conv.SetOutFormat(out_format)\n conv.ReadString(obMol, str_data)\n\n if add_hydrogens:\n obMol.AddHydrogens()\n\n if gen3d:\n # Generate 3D coordinates for the input\n mol = pybel.Molecule(obMol)\n mol.make3D(gen3d_forcefield, gen3d_steps)\n\n if perceive_bonds:\n obMol.ConnectTheDots()\n obMol.PerceiveBondOrders()\n\n for option, value in out_options.items():\n conv.AddOption(option, conv.OUTOPTIONS, value)\n\n return (conv.WriteString(obMol), conv.GetOutFormat().GetMIMEType())\n\n\ndef to_inchi(str_data, in_format):\n mol = OBMol()\n conv = OBConversion()\n conv.SetInFormat(in_format)\n conv.ReadString(mol, str_data)\n\n conv.SetOutFormat('inchi')\n inchi = conv.WriteString(mol).rstrip()\n conv.SetOptions('K', conv.OUTOPTIONS)\n inchikey = conv.WriteString(mol).rstrip()\n\n return (inchi, inchikey)\n\n\ndef to_smiles(str_data, in_format):\n # The smiles has returns at the end of it, and may contain\n # a return in the middle with a common name. Get rid of\n # all of these.\n # Use canonical smiles\n smiles, mime = convert_str(str_data, in_format, 'can')\n smiles = smiles.strip().split()[0]\n return (smiles, mime)\n\n\ndef atom_count(str_data, in_format):\n mol = OBMol()\n conv = OBConversion()\n conv.SetInFormat(in_format)\n conv.ReadString(mol, str_data)\n\n return mol.NumAtoms()\n\n\ndef get_formula(str_data, in_format):\n # Inchi must start with 'InChI='\n if in_format == 'inchi' and not str_data.startswith('InChI='):\n str_data = 'InChI=' + str_data\n validate_start_of_inchi(str_data)\n # Get the molecule using the \"Hill Order\" - i. e., C first, then H,\n # and then alphabetical.\n mol = OBMol()\n conv = OBConversion()\n conv.SetInFormat(in_format)\n conv.ReadString(mol, str_data)\n\n return mol.GetFormula()\n\n\ndef properties(str_data, in_format, add_hydrogens=False):\n # Returns a dict with the atom count, formula, heavy atom count,\n # mass, and spaced formula.\n if in_format == 'inchi' and not str_data.startswith('InChI='):\n # Inchi must start with 'InChI='\n str_data = 'InChI=' + str_data\n validate_start_of_inchi(str_data)\n mol = OBMol()\n conv = OBConversion()\n conv.SetInFormat(in_format)\n conv.ReadString(mol, str_data)\n\n if add_hydrogens:\n mol.AddHydrogens()\n\n props = {}\n props['atomCount'] = mol.NumAtoms()\n props['formula'] = mol.GetFormula()\n props['heavyAtomCount'] = mol.NumHvyAtoms()\n props['mass'] = mol.GetMolWt()\n props['spacedFormula'] = mol.GetSpacedFormula()\n\n return props\n\n\ndef to_svg(str_data, in_format):\n out_options = {\n 'b': 'none', # transparent background color\n 'B': 'black' # black bonds color\n }\n return convert_str(str_data, in_format, 'svg', out_options=out_options)\n","repo_name":"OpenChemistry/mongochemserver","sub_path":"flask/openbabel/src/openbabel_api.py","file_name":"openbabel_api.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"29"} +{"seq_id":"27257168168","text":"import random\nimport copy\nimport numpy as np\nimport pandas as pd\nimport os\nfrom inferringAncestorGenomeStructure.MatchingOptimization import MatchingOptimization\nfrom inferringAncestorGenomeStructure.GGAP import GGAP\nfrom util.transformToAdjacency import transformToAdjacency\nfrom inferringAncestorGenomeStructure.GMP import GMP\n\ndef readSequence(file):\n chr = []\n with open(file,'r') as rf:\n while True:\n line = rf.readline()[:-2]\n if not line:\n break\n itemset = line.split(' ')\n header = itemset[0]\n new_itemset = [header]\n for i in itemset[1:]:\n item = i.split('_')\n new_itemset.append(item[0])\n chr.append(new_itemset)\n return chr\n\ndef outSequence(sequence,outfile):\n outfile = open(outfile,'w')\n for i in sequence:\n for j in i:\n outfile.write(j+' ')\n outfile.write('\\n')\n outfile.close()\n\ndef sequence2adjacency(sequence):\n adjacency = []\n for i in sequence:\n block = i[0]\n if block.startswith('-'):\n adjacency.append(['$',block[1:] + 'b'])\n start = block[1:] + 'a'\n else:\n adjacency.append(['$', block + 'a'])\n start = block + 'b'\n for j in range(len(i)-1):\n block = i[j+1]\n if block.startswith('-'):\n adjacency.append([start, block[1:] + 'b'])\n start = block[1:] + 'a'\n else:\n adjacency.append([start, block + 'a'])\n start = block + 'b'\n adjacency.append([start,'$'])\n return adjacency\n\ndef reverse(item):\n if item[-1] == 'a':\n return item[:-1] + 'b'\n else:\n return item[:-1] + 'a'\n\ndef assemble(adjacency_list):\n # build adj M\n matrix_items = []\n for i in adjacency_list:\n for j in i:\n if j not in matrix_items:\n matrix_items.append(j)\n matrix_items = sorted(matrix_items)\n adjacency_matrix = {}\n for i in matrix_items:\n adjacency_matrix[i] = {}\n for j in matrix_items:\n adjacency_matrix[i][j] = 0\n for i in adjacency_list:\n adjacency_matrix[i[0]][i[1]] = 1\n adjacency_matrix[i[1]][i[0]] = 1\n adjacency_matrix = pd.DataFrame(adjacency_matrix)\n index = adjacency_matrix.index.tolist()\n columns = adjacency_matrix.columns.tolist()\n np_adjacency_matrix = np.asarray(adjacency_matrix)\n adjacencies = {}\n for i in range(len(index)):\n for j in range(len(index)):\n if int(np_adjacency_matrix[i][j]) == 1:\n if '$' == index[i] or '$' == index[j]:\n continue\n pair = sorted([index[i], index[j]])\n key = pair[0] + '@' + pair[1]\n if key not in adjacencies.keys():\n adjacencies[key] = 1\n else:\n adjacencies[key] += 1\n adjs = {}\n for i in adjacencies.keys():\n itemset = i.split('@')\n if itemset[0] not in adjs.keys():\n adjs[itemset[0]] = itemset[1]\n if itemset[1] not in adjs.keys():\n adjs[itemset[1]] = itemset[0]\n startpoint = []\n\n for j in range(len(columns)):\n if np_adjacency_matrix[0][j] == 1:\n startpoint.append(columns[j])\n markerstartpoint = []\n chr = []\n for i in startpoint:\n if i not in markerstartpoint:\n path = []\n if i[-1] == 'a':\n path.append(i[:-1])\n else:\n path.append('-' + i[:-1])\n start = reverse(i)\n if start in startpoint:\n markerstartpoint.append(start)\n chr.append(path)\n else:\n while True:\n next = adjs[start]\n if next[-1] == 'a':\n path.append(next[:-1])\n else:\n path.append('-' + next[:-1])\n start = reverse(next)\n if start in startpoint:\n markerstartpoint.append(start)\n break\n chr.append(path)\n vector = []\n for i in chr:\n for j in i:\n if j.startswith('-'):\n vector.append(j[1:])\n else:\n vector.append(j)\n cyclepoint = []\n for i in adjs.keys():\n if i[:-1] not in vector:\n cyclepoint.append(i)\n cyclechr = []\n markercycle = []\n for i in cyclepoint:\n if i not in markercycle:\n startpoint = i\n cycle = []\n markercycle.append(i)\n start = i\n while True:\n next = adjs[start]\n if next[-1] == 'a':\n cycle.append(next[:-1])\n else:\n cycle.append('-' + next[:-1])\n markercycle.append(start)\n markercycle.append(next)\n start = reverse(next)\n if start == startpoint:\n break\n cyclechr.append(cycle)\n return chr,cyclechr\n\ndef changeAdj(adj_list):\n change = copy.deepcopy(adj_list)\n endpoints = []\n for j in change:\n for k in j:\n endpoints.append(k)\n random.shuffle(endpoints)\n change_part = []\n for j in range(int(len(endpoints) / 2)):\n change_part.append([endpoints[j * 2], endpoints[2 * j + 1]])\n return change_part\n\ndef buildISSimulations(prefix_adjacencies,\n suffix_adjacencies, save_final_species_adjacencies, change_adjacency_number,\n divergence_level, current_level):\n split_adjacency = []\n divergence_change_adjacencies_group_number = len(suffix_adjacencies) * 2\n for i in suffix_adjacencies:\n one_change_adjacencies = []\n for j in range(divergence_change_adjacencies_group_number):\n one_change_adjacencies.append(copy.deepcopy(i[j * change_adjacency_number:(j + 1) * change_adjacency_number]))\n one_change_adjacencies.append(copy.deepcopy(i[divergence_change_adjacencies_group_number * change_adjacency_number:]))\n split_adjacency.append(one_change_adjacencies)\n\n sub_species_1 = []\n sub_species_2 = []\n copy_number = 0\n\n for i in split_adjacency:\n sp1_copy = []\n sp2_copy = []\n sp1_change = copy_number\n sp2_change = copy_number+len(split_adjacency)\n for j in range(len(i)):\n # change different part, no CRBs\n if j == sp1_change:\n change = copy.deepcopy(i[j])\n change_part = changeAdj(change)\n sp1_copy.append(change_part)\n else:\n sp1_copy.append(copy.deepcopy(i[j]))\n if j == sp2_change:\n change = copy.deepcopy(i[j])\n change_part = changeAdj(change)\n sp2_copy.append(change_part)\n else:\n sp2_copy.append(copy.deepcopy(i[j]))\n\n sub_species_1.append(sp1_copy)\n sub_species_2.append(sp2_copy)\n copy_number += 1\n\n species_1 = []\n for i in range(len(sub_species_1)):\n one_copy = []\n one_copy += copy.deepcopy(prefix_adjacencies[i])\n for j in copy.deepcopy(sub_species_1[i]):\n one_copy += j\n species_1.append(one_copy)\n # save first species\n save_final_species_adjacencies.append(species_1)\n species_2 = []\n for i in range(len(sub_species_2)):\n one_copy = []\n one_copy += copy.deepcopy(prefix_adjacencies[i])\n for j in copy.deepcopy(sub_species_2[i]):\n one_copy += j\n species_2.append(one_copy)\n # save second species\n save_final_species_adjacencies.append(species_2)\n\n # duplication\n dup_flag = 1\n species_2_dup = []\n if dup_flag == 1:\n for i in range(len(sub_species_2)):\n change_list = copy.deepcopy(sub_species_2[i][:-1])\n unchange = copy.deepcopy(sub_species_2[i][-1])\n\n split_unchange = []\n for j in range(len(sub_species_2)*2):\n split_unchange.append(copy.deepcopy(unchange[j * change_adjacency_number:(j + 1) * change_adjacency_number]))\n split_unchange.append(unchange[len(sub_species_2) * 2 * change_adjacency_number:])\n # change adjacencies\n change_1 = i*len(sub_species_2)\n change_2 = i*len(sub_species_2) + 1\n new_change_list_copy1 = []\n new_change_list_copy2 = []\n for j in range(len(split_unchange)):\n if j == change_1:\n change = copy.deepcopy(split_unchange[j])\n change_part = changeAdj(change)\n new_change_list_copy1.append(change_part)\n else:\n new_change_list_copy1.append(copy.deepcopy(split_unchange[j]))\n if j == change_2:\n change = copy.deepcopy(split_unchange[j])\n change_part = changeAdj(change)\n new_change_list_copy2.append(change_part)\n else:\n new_change_list_copy2.append(copy.deepcopy(split_unchange[j]))\n final_change_list_1 = copy.deepcopy(change_list) + new_change_list_copy1\n final_change_list_2 = copy.deepcopy(change_list) + new_change_list_copy2\n species_2_dup.append(final_change_list_1)\n species_2_dup.append(final_change_list_2)\n\n if current_level == divergence_level:\n species_2_dup_sequence = []\n for i in range(len(species_2_dup)):\n one_copy = []\n one_copy += copy.deepcopy(prefix_adjacencies[int(i / 2)])\n for j in copy.deepcopy(species_2_dup[i]):\n one_copy += j\n species_2_dup_sequence.append(one_copy)\n save_final_species_adjacencies.append(species_2_dup_sequence)\n\n else:\n species_2_dup_sequence = []\n for i in range(len(species_2_dup)):\n one_copy = []\n one_copy += copy.deepcopy(prefix_adjacencies[int(i / 2)])\n for j in copy.deepcopy(species_2_dup[i]):\n one_copy += j\n species_2_dup_sequence.append(one_copy)\n # save duplicated species\n save_final_species_adjacencies.append(species_2_dup_sequence)\n new_prefix_adjacency = []\n new_suffix_adjacency = []\n for i in range(len(species_2_dup)):\n one_copy = copy.deepcopy(prefix_adjacencies[int(i / 2)])\n change_part = species_2_dup[i][:-1]\n unchange_part = species_2_dup[i][-1]\n for j in change_part:\n one_copy += copy.deepcopy(j)\n new_prefix_adjacency.append(one_copy)\n new_suffix_adjacency.append(copy.deepcopy(unchange_part))\n # recursion build next level species, level += 1\n buildISSimulations(new_prefix_adjacency, new_suffix_adjacency,\n save_final_species_adjacencies, change_adjacency_number,\n divergence_level, current_level + 1)\n\ndef simulateIS(workdir):\n chromosome_number = 5\n block_number = 100\n ancestor_sequence = []\n one_chromosome = int(block_number / chromosome_number)\n block = 100\n for i in range(chromosome_number):\n sequence = []\n for j in range(one_chromosome):\n if block % 2 == 0:\n sequence.append('-' + str(block))\n else:\n sequence.append(str(block))\n block += 1\n ancestor_sequence.append(sequence)\n ancestor_adjacency = sequence2adjacency(ancestor_sequence)\n random.shuffle(ancestor_adjacency)\n print('ancestor adjacency number:')\n print(len(ancestor_adjacency))\n divergence_level = 1\n change_adjacency_number = 5\n save_final_species_adjacencies = []\n buildISSimulations([[]], [ancestor_adjacency],\n save_final_species_adjacencies, change_adjacency_number, divergence_level, current_level=0)\n species_count = 1\n # output species\n for i in save_final_species_adjacencies:\n copy_count = 1\n outfile = workdir + 'species.sequence.' + str(species_count)\n outfile = open(outfile,'w')\n for j in i:\n filter_tel2tel = []\n for k in j:\n # filter ($,$)\n if k[0] == '$' and k[1] == '$':\n continue\n else:\n if k[0] != '$':\n newendpoint1 = k[0][:-1]+'_'+str(copy_count)+k[0][-1]\n else:\n newendpoint1 = '$'\n if k[1] != '$':\n newendpoint2 = k[1][:-1]+'_'+str(copy_count)+k[1][-1]\n else:\n newendpoint2 = '$'\n filter_tel2tel.append([newendpoint1,newendpoint2])\n chrs,cycles = assemble(filter_tel2tel)\n for k in chrs:\n outfile.write('s ')\n for l in k:\n outfile.write(l+' ')\n outfile.write('\\n')\n for k in cycles:\n outfile.write('c ')\n min_index = -1\n min_value = 1000000\n for l in range(len(k)):\n if k[l].startswith('-'):\n item = k[l][1:].split('_')\n block = int(item[0])\n else:\n item = k[l].split('_')\n block = int(item[0])\n if block < min_value:\n min_index = l\n min_value = block\n if k[min_index].startswith('-'):\n half1 = k[min_index + 1:]\n half2 = k[:min_index + 1]\n new_string = half1 + half2\n else:\n half1 = k[min_index:]\n half2 = k[:min_index]\n new_string = half1 + half2\n for l in new_string:\n outfile.write(l+' ')\n outfile.write('\\n')\n copy_count += 1\n outfile.close()\n species_count += 1\n\ndef doubled(infile, outfile):\n outfile = open(outfile, 'w')\n sequence = []\n with open(infile, 'r') as f:\n while True:\n line = f.readline()\n if not line:\n break\n sequence.append(line)\n for i in sequence:\n outfile.write(i)\n for i in sequence:\n outfile.write(i)\n\ndef transformToAdjacency_for_distance(file):\n adjacency_list = []\n with open(file) as df:\n while True:\n line = df.readline()[:-2]\n if not line:\n break\n item = line.split(' ')\n chr_type = item[0]\n last = ''\n start = ''\n sequence = item[1:]\n for j in range(len(sequence)):\n if j == 0:\n if chr_type == 's':\n if sequence[j].startswith('-'):\n adjacency_list.append(['$', sequence[j][1:] + 'b'])\n last = sequence[j][1:] + 'a'\n else:\n adjacency_list.append(['$', sequence[j] + 'a'])\n last = sequence[j] + 'b'\n else:\n if sequence[j].startswith('-'):\n last = sequence[j][1:] + 'a'\n start = sequence[j][1:] + 'b'\n else:\n last = sequence[j] + 'b'\n start = sequence[j] + 'a'\n else:\n if sequence[j].startswith('-'):\n adjacency_list.append([last, sequence[j][1:] + 'b'])\n last = sequence[j][1:] + 'a'\n else:\n adjacency_list.append([last, sequence[j] + 'a'])\n last = sequence[j] + 'b'\n if chr_type == 's':\n adjacency_list.append([last, '$'])\n else:\n adjacency_list.append([last, start])\n\n new_adjacency_list = []\n for j in adjacency_list:\n new_adjacency_list.append(j[0]+'@'+j[1])\n return new_adjacency_list\n\ndef calculateDistance(sequence1file, sequence2file, duptype1, duptype2,copy_number):\n\n filelist = [sequence1file,sequence2file]\n outcandidatefile = sequence1file + '.matchingforCD'\n outguidedfile = sequence2file + '.matchingforCD'\n mo = MatchingOptimization(filelist, matching_dim1=copy_number, matching_dim2=copy_number,\n relation1=1, relation2=1)\n mo.optimization()\n mo.matching_relation()\n mo.output_new_sequence(outcandidatefile, outguidedfile)\n\n sp1adj = transformToAdjacency_for_distance(outcandidatefile)\n sp1matrix = {}\n matrix_item = ['$']\n for i in sp1adj:\n item = i.split('@')\n for j in item:\n if j not in matrix_item:\n matrix_item.append(j)\n matrix_item = sorted(matrix_item)\n for i in matrix_item:\n sp1matrix[i] = {}\n for j in matrix_item:\n sp1matrix[i][j] = 0\n\n for i in sp1adj:\n item = i.split('@')\n sp1matrix[item[0]][item[1]] += 1\n sp1matrix[item[1]][item[0]] += 1\n sp2adj = transformToAdjacency_for_distance(outguidedfile)\n sp2matrix = {}\n for i in matrix_item:\n sp2matrix[i] = {}\n for j in matrix_item:\n sp2matrix[i][j] = 0\n for i in sp2adj:\n item = i.split('@')\n sp2matrix[item[0]][item[1]] += 1\n sp2matrix[item[1]][item[0]] += 1\n\n SCoJ = 0\n all = len(sp1adj) + len(sp2adj)\n for i in sp1matrix.keys():\n for j in sp1matrix[i].keys():\n SCoJ += abs(sp1matrix[i][j]*duptype1 - sp2matrix[i][j]*duptype2)\n return 1-((SCoJ/2)/all)\n\n\ndir = 'D:/InferAncestorGenome/DCW_HN1_YMR_newpair/IAG/simulatedData/ISSimulation/split5/'\nresultfile = open(dir + 'result.xls', 'w')\nresultfile.write('Ancestor\\tConsistency\\n')\n# simulated with infinite sites assumption\nfor i in range(200):\n if not os.path.exists(dir + str(i+1) + '/'):\n os.makedirs(dir + str(i+1) + '/')\n simulateIS(dir + str(i+1) + '/')\n workdir = dir + str(i + 1) + '/'\n filelist = ['species.sequence.1', 'species.sequence.2', 'species.sequence.3',\n 'species.sequence.4', 'species.sequence.5', 'species.sequence.6']\n for j in filelist:\n sequence = readSequence(workdir + j)\n outSequence(sequence,workdir + j +'.noBar')\n # 1. inferred Species 5\n file = ['species.sequence.6.noBar', 'species.sequence.4.noBar']\n outcandidatefile = workdir + 'species.sequence.6.noBar.matching'\n outguidedfile = workdir + 'species.sequence.4.noBar.matching'\n outmatching = workdir + 'matching_6_4.txt'\n filelist = []\n for j in file:\n filelist.append(workdir + j)\n mo = MatchingOptimization(filelist, matching_dim1=4, matching_dim2=2,\n relation1=1, relation2=2)\n mo.optimization()\n mo.matching_relation()\n mo.output_matching_relation(outmatching)\n mo.output_new_sequence(outcandidatefile, outguidedfile)\n\n adj_file = workdir + '6_4.adj'\n filelist = [outcandidatefile, outguidedfile]\n transformToAdjacency(filelist, adj_file)\n output_sequence_file = workdir + 'species.sequence.5.inferred'\n\n output_matrix_file = workdir + 'species.sequence.5.inferred.xls'\n species_list = ['6', '4']\n ggap = GGAP(adj_file, species_list, duptype=2)\n ggap.optimization()\n adjacency_matrix = ggap.ancestor_adjacency_matrix()\n adjacency_matrix.output(output_matrix_file)\n adjacency_matrix.assemble()\n output_sequence_file_with_bar = workdir + 'species.sequence.5.inferred.withbar'\n adjacency_matrix.out_assembly(output_sequence_file_with_bar, remove_bar=False)\n adjacency_matrix.out_assembly(output_sequence_file, remove_bar=True)\n\n # 2. inferred Species 3\n doubled(workdir + 'species.sequence.1.noBar', workdir + 'species.sequence.1.noBar.double')\n\n outcandidatefile = workdir + 'species.sequence.1.noBar.double.matching'\n outguidedfile = workdir + 'species.sequence.4.noBar.matching'\n outmatching = workdir + 'matching_1double_4.txt'\n\n filelist = [workdir + 'species.sequence.1.noBar.double', workdir + 'species.sequence.4.noBar']\n\n mo = MatchingOptimization(filelist, matching_dim1=2, matching_dim2=2,\n relation1=1, relation2=1)\n mo.optimization()\n mo.matching_relation()\n mo.output_matching_relation(outmatching)\n mo.output_new_sequence(outcandidatefile, outguidedfile)\n\n adj_file = workdir + '5_4_1double.adj'\n filelist = [workdir + 'species.sequence.5.inferred.withbar',\n workdir + 'species.sequence.4.noBar.matching',\n workdir + 'species.sequence.1.noBar.double.matching']\n\n transformToAdjacency(filelist, adj_file)\n output_sequence_file = workdir + 'species.sequence.3.inferred'\n output_matrix_file = workdir + 'species.sequence.3.inferred.xls'\n species_list = ['5', '4', '1double']\n gmp = GMP(adj_file, species_list)\n gmp.optimization()\n adjacency_matrix = gmp.ancestor_adjacency_matrix()\n\n adjacency_matrix.assemble()\n output_sequence_file_with_bar = workdir + 'species.sequence.3.inferred.withbar'\n adjacency_matrix.out_assembly(output_sequence_file_with_bar, remove_bar=False)\n adjacency_matrix.out_assembly(output_sequence_file, remove_bar=True)\n\n # 3. inferred Species 2\n adj_file = workdir + '3_1.adj'\n filelist = [workdir + 'species.sequence.3.inferred',\n workdir + 'species.sequence.1.noBar']\n\n transformToAdjacency(filelist, adj_file)\n output_sequence_file = workdir + 'species.sequence.2.inferred'\n\n species_list = ['3', '1']\n ggap = GGAP(adj_file, species_list, duptype=2)\n ggap.optimization()\n adjacency_matrix = ggap.ancestor_adjacency_matrix()\n adjacency_matrix.output(output_matrix_file)\n adjacency_matrix.assemble()\n adjacency_matrix.out_assembly(output_sequence_file, remove_bar=False)\n\n # validation\n bias = calculateDistance(workdir + 'species.sequence.5.inferred', workdir + 'species.sequence.5.noBar',\n 1, 1, 2)\n\n resultfile.write('Ancestor5\\t' + str(bias) + '\\n')\n\n bias = calculateDistance(workdir + 'species.sequence.3.inferred', workdir + 'species.sequence.3.noBar',\n 1, 1, 2)\n\n resultfile.write('Ancestor3\\t' + str(bias) + '\\n')\n\n bias = calculateDistance(workdir + 'species.sequence.2.inferred', workdir + 'species.sequence.2.noBar',\n 1, 1, 1)\n\n resultfile.write('Ancestor2\\t' + str(bias) + '\\n')\n resultfile.flush()\nresultfile.close()\n\n\n\n\n\n\n\n","repo_name":"865699871/IAG","sub_path":"simulationTestForPapaver/simulatedWithISAssumption.py","file_name":"simulatedWithISAssumption.py","file_ext":"py","file_size_in_byte":22974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"73312026958","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef log(tensor):\n print('{}'.format(list(tensor.size())))\n return tensor\n\ndef log_empty(tensor):\n return tensor\n\ndef log_img(tensor):\n to_pil = torchvision.transforms.ToPILImage()\n img = tensor.clone().detach()\n\n if len(list(img.size())) == 4:\n img = img.squeeze(0)\n\n img = to_pil(img)\n plt.imshow(img)\n plt.title(list(tensor.size()))\n plt.show()\n return tensor\n\n\"\"\"\nD\n[2, 16, 96, 96]\n[2, 16, 9216]\n[2, 16, 256]\n[2, 4096]\n[2, 2048]\nG\n[2, 128]\n[2, 4096]\n[2, 16, 256]\n[2, 16, 2048]\n[2, 16, 9216]\n[2, 16, 96, 96]\n\"\"\"\n\n\nclass TimeDistributedLinear(nn.Module):\n \"\"\"\n [Batch, Seq, Word] -> [Batch * Seq, Word] -> [Batch, Seq, Word]\n \"\"\"\n def __init__(self, in_features, out_features, bn=True, activation=nn.LeakyReLU):\n super(TimeDistributedLinear, self).__init__()\n self.in_features, self.out_features = in_features, out_features\n self.bn, self.activation = bn, activation\n self.fc = nn.Linear(in_features, out_features)\n if bn:\n self.bn = nn.BatchNorm1d(out_features)\n if activation is not None:\n self.act = activation()\n\n def forward(self, x):\n input_shape = x.size()\n\n assert len(input_shape) == 3, \"expected dim=3\"\n\n bs = x.size(0)\n seq_len = x.size(1)\n word_len = x.size(2)\n\n assert word_len == self.in_features, \"expected input_shape[-1] == in_features\"\n\n x = x.view(-1, word_len)\n x = self.fc(x)\n\n if self.bn:\n x = self.bn(x)\n if self.activation is not None:\n x = self.act(x)\n\n x = x.view(bs, seq_len, self.out_features)\n\n return x\n\n\nclass LinearBlock(nn.Module):\n \"\"\"\n [Batch, Seq, Word] -> [Batch * Seq, Word] -> [Batch, Seq, Word]\n \"\"\"\n def __init__(self, in_features, out_features, bn=True, activation=nn.LeakyReLU):\n super(LinearBlock, self).__init__()\n self.in_features, self.out_features = in_features, out_features\n self.bn, self.activation = bn, activation\n self.fc = nn.Linear(in_features, out_features)\n if bn:\n self.bn = nn.BatchNorm1d(out_features)\n if activation is not None:\n self.act = activation()\n\n def forward(self, x):\n x = self.fc(x)\n\n if self.bn:\n x = self.bn(x)\n if self.activation is not None:\n x = self.act(x)\n\n return x\n\n\nclass Encoder(nn.Module):\n def __init__(self, n=16, h=96, w=96):\n super(Encoder, self).__init__()\n self.n, self.h, self.w = n, h, w\n self.encoder1 = nn.Sequential(TimeDistributedLinear(96*96, 2048),\n TimeDistributedLinear(2048, 256))\n self.encoder2 = nn.Sequential(LinearBlock(256 * n, 2048))\n\n def forward(self, x, log=log_empty):\n log(x) # [2, 16, 96, 96]\n x = log(x.view(-1, self.n, self.h*self.w))\n x = log(self.encoder1(x))\n x = log(x.view(-1, self.n * x.size(-1)))\n x = log(self.encoder2(x))\n\n return x\n\nclass Decoder(nn.Module):\n def __init__(self, n=16, h=96, w=96, z_dim=128):\n super(Decoder, self).__init__()\n self.n, self.h, self.w = n, h, w\n self.decoder1 = nn.Sequential(LinearBlock(z_dim, 2048),\n LinearBlock(2048, 256*n))\n self.decoder2 = nn.Sequential(TimeDistributedLinear(256, 2048))\n\n def forward(self, x, log=log_empty):\n log(x) # [2, 128]\n x = log(self.decoder1(x)) # [2, 4096]\n x = log(x.view(-1, self.n, x.size(-1)//self.n)) # [2, 16, 256]\n x = log(self.decoder2(x)) # [2, 16, 2048]\n\n return x\n\nclass Discriminator(nn.Module):\n def __init__(self, n=16, h=96, w=96):\n super(Discriminator, self).__init__()\n self.encoder = Encoder(n, h, w)\n self.fc = LinearBlock(2048, 1, activation=nn.Sigmoid)\n\n def forward(self, x, log=log_empty):\n x = self.encoder(x, log)\n x = self.fc(x)\n return x\n\nclass Generator(nn.Module):\n def __init__(self, n=16, h=96, w=96):\n super(Generator, self).__init__()\n self.n, self.h, self.w = n, h, w\n self.decoder = Decoder(n, h, w)\n self.fc = TimeDistributedLinear(2048, self.h*self.w, activation=nn.Tanh)\n\n def forward(self, x, log=log_empty):\n x = self.decoder(x, log)\n x = log(self.fc(x))\n x = log(x.view(-1, self.n, self.h, self.w))\n\n return x\n\n\n\"\"\"\nEncoder\n[2, 16, 96, 96]\n[2, 16, 9216]\n[2, 16, 256]\n[2, 4096]\n[2, 2048]\nDecoder\n[2, 128]\n[2, 4096]\n[2, 16, 256]\n[2, 16, 2048]\n\"\"\"\n\nclass VAE(nn.Module):\n def __init__(self, n=16, h=96, w=96, h_dim=2048, z_dim=128):\n super(VAE, self).__init__()\n self.n, self.h, self.w = n, h, w\n self.fc1 = Encoder(n, h, w)\n self.fc2 = nn.Linear(h_dim, z_dim)\n self.fc3 = nn.Linear(h_dim, z_dim)\n self.fc4 = Decoder(n, h, w, z_dim=z_dim)\n self.fc5 = TimeDistributedLinear(h_dim, h*w, bn=False, activation=nn.Sigmoid)\n\n def encode(self, x):\n h = self.fc1(x)\n return self.fc2(h), self.fc3(h)\n\n def reparameterize(self, mu, log_var):\n std = torch.exp(log_var / 2)\n eps = torch.randn_like(std)\n return mu + eps * std\n\n def decode(self, z):\n h = self.fc4(z)\n h = self.fc5(h)\n h = h.view(-1, self.n, self.h, self.w)\n return h\n\n def forward(self, x):\n mu, log_var = self.encode(x)\n z = self.reparameterize(mu, log_var)\n x_reconst = self.decode(z)\n return x_reconst, mu, log_var\n\n\nif __name__ == \"__main__\":\n device = torch.device('cpu')\n # En = Encoder().to(device)\n # De = Decoder().to(device)\n # D = Discriminator().to(device)\n # G = Generator().to(device)\n vae = VAE().to(device)\n\n # print('Encoder')\n # out = En(torch.randn(2, 16, 96, 96), log)\n # print('Decoder')\n # out = De(torch.randn(2, 128), log)\n\n print('VAE')\n out = vae(torch.randn(2, 16, 96, 96))\n","repo_name":"YoongiKim/pytorch-music-composer","sub_path":"modules/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6103,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"29"} +{"seq_id":"4471106214","text":"\"\"\"\nRead through the raw doc-composition files, spit out one text file for each document\nthat lists the top 5 topics for that document\n\"\"\"\n\nimport csv\n\ndata_dir = \"/Users/jchan/Desktop/Dropbox/Research/Dissertation/OpenIDEO/Pipeline/Validation/FINAL_malletLDA/TopicCompositions/\"\ndoccompfile = \"/Users/jchan/Desktop/Dropbox/Research/Dissertation/OpenIDEO/Pipeline/Validation/FINAL_malletLDA/CF0_DF0_400_ASP_optim_composition-6_formatted.txt\"\nkeysfile = \"/Users/jchan/Desktop/Dropbox/Research/Dissertation/OpenIDEO/Pipeline/Validation/FINAL_malletLDA/CF0_DF0_400_ASP_optim_keys-6.txt\"\nnamesfile = \"/Users/jchan/Desktop/Dropbox/Research/Dissertation/OpenIDEO/PythonCode/master_IDmappings.csv\"\n\n# get the doc-topic compositions\ndoccomps = {}\ndocnames = []\nwith open(doccompfile,'rU') as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='|')\n for row in filereader:\n docname = row[1]\n doctop5topics = row[2:12]\n doccomps[docname] = doctop5topics\n docnames.append(docname)\ncsvfile.close()\n\n# get the topic keys\ntopics = {}\nwith open(keysfile,'rU') as csvfile:\n filereader = csv.reader(csvfile, delimiter='\\t', quotechar='|')\n for row in filereader:\n topics[row[0]] = row[2]\n \n# get the fullname mappings\nname_hash = {}\nwith open(namesfile,'rU') as csvfile:\n filereader = csv.reader(csvfile, delimiter=',', quotechar='|')\n for row in filereader:\n name_hash[row[1]] = row[0]\n\n# do the real work\nindices = [0,2,4,6,8]\nfor docname in docnames:\n docfilename = data_dir + \"topwords_\" + docname + \".txt\"\n f = open(docfilename,'w')\n if \"challenge\" in docname:\n f.write(docname + \"\\n\")\n else:\n f.write(name_hash[docname] + \"\\n\")\n for index in indices:\n topicnum = doccomps[docname][index]\n topicweight = doccomps[docname][index+1]\n topicwords = topics[topicnum]\n towrite = \"%s\\t%.3f\\n\" %(topicnum, float(topicweight))\n f.write(towrite)\n f.write(topicwords + \"\\n\")\n f.close()","repo_name":"joelchan/openideo-data-processing-pipeline","sub_path":"validation/top_words.py","file_name":"top_words.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"40695783924","text":"import json\nimport pandas as pd\nimport logging\nimport time\nimport sys\nimport os\n\nimport gspread\nfrom gspread.exceptions import APIError\nfrom pydrive.auth import GoogleAuth\nfrom pydrive.drive import GoogleDrive\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom tqdm import tqdm\nfrom expworkup.devconfig import lab_vars\nfrom utils.file_handling import get_experimental_run_lab\nfrom utils import globals\n\nfrom expworkup.devconfig import cwd\n\nmodlog = logging.getLogger(f'mainlog.{__name__}')\nwarnlog = logging.getLogger(f'warning.{__name__}')\n\n# Disable super spam from api code\nlogging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR)\n\ndef get_gdrive_auth():\n '''returns instance of the gdrive authentication\n\n Requires client_secrets.json to generate see:\n https://github.com/darkreactions/ESCALATE_report/wiki/ONBOARDING-LABS\n '''\n gauth = GoogleAuth(settings_file='./expworkup/settings.yaml')\n\n google_cred_file = \"./mycred.txt\"\n if not os.path.exists(google_cred_file):\n modlog.info(f'Temp authentication file {google_cred_file} created')\n open(google_cred_file, 'w+').close()\n\n gauth.LoadCredentialsFile(google_cred_file)\n if gauth.credentials is None or gauth.access_token_expired:\n modlog.info(f'Temp authentication file {google_cred_file} required refresh')\n gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication.\n else:\n gauth.Authorize() # Just run because everything is loaded properly\n gauth.SaveCredentialsFile(google_cred_file)\n drive = GoogleDrive(gauth)\n return(drive)\n\n### General Setup Information ###\n##GSpread Authorization information\ndef get_gdrive_client():\n '''\n returns instance of gspread client based on credentials in creds.json file\n different scope than googlio.py in ESCALATE_Capture\n\n requires creds.json to generate see:\n https://github.com/darkreactions/ESCALATE_report/wiki/ONBOARDING-LABS\n '''\n scope = ['https://www.googleapis.com/auth/spreadsheets.readonly']\n #scope = ['https://spreadsheets.google.com/feeds']\n credentials = ServiceAccountCredentials.from_json_keyfile_name('creds.json', scope)\n gc = gspread.authorize(credentials)\n return gc\n\ndef ChemicalData(lab):\n \"\"\"\n Uses google api to gather the chemical inventory targeted by labsheet 'chemsheetid' in dev config\n\n Parameters\n ----------\n lab : abbreviation of the lab\n lab is specified as the suffix of a folder and the available\n options are included in the lab_vars of the devconfig.py file\n\n Returns \n --------\n chemdf : pandas df of the chemical inventory\n \"\"\"\n sleep_timer = 0\n chemdf = 0 #just create a 'blank' object\n while not isinstance(chemdf, pd.DataFrame):\n try:\n gc = get_gdrive_client()\n chemsheetid = globals.lab_safeget(lab_vars, lab, 'chemsheetid')\n ChemicalBook = gc.open_by_key(chemsheetid)\n chemicalsheet = ChemicalBook.get_worksheet(0)\n chemical_list = chemicalsheet.get_all_values()\n chemdf=pd.DataFrame(chemical_list, columns=chemical_list[0])\n chemdf=chemdf.iloc[1:]\n chemdf=chemdf.reset_index(drop=True)\n chemdf=chemdf.set_index(['InChI Key (ID)'])\n except APIError as e:\n modlog.info(e.response)\n modlog.info(sys.exc_info())\n modlog.info('During download of {} chemical inventory sever request limit was met'.format(lab))\n sleep_timer = 15.0\n time.sleep(sleep_timer)\n modlog.info(f'Successfully loaded the chemical inventory from {lab}')\n return(chemdf)\n\ndef save_prep_interface(prep_UID, local_data_dir, experiment_name):\n \"\"\" Download the hardcoded TSV backend of the preparation interface\n \n Parameters\n ---------\n prep_UID : gdrive UID of the target prep interface\n\n local_data_dir : folder to store gdrive files\n report default: {target_naming_scheme}/gdrive_files/\n\n experiment_name : name of gdrive folder containing the experiment\n aka. runUID, e.g. 2019-09-18T20_27_33.741387+00_00_LBL\n\n Returns\n -------\n None\n\n Notes\n -----\n Suffix 'ExpDataEntry.json' is a holdover from original development. This\n suffix is not viewed by any USER level interactions, the name is irrelevant\n except for internal code\n\n DEVNOTE: the suffix _ExpDataEntry.json CANNOT be changed without breaking\n ECL suppoort\n\n ECL data is stored in a JSON file rendered at ECL, all other labs\n are parsed from the TSV backend of the interface. Example here:\n https://drive.google.com/open?id=1kVVbijwRO_kFeXO74vtIgpEyLenha4ek7n35yp6vxvY\n \"\"\"\n drive = get_gdrive_auth()\n if 'ECL' in experiment_name:\n #TODO: Local Copy of JSON logic for testing / comparison\n prep_file = drive.CreateFile({'id': prep_UID})\n prep_file.GetContentFile(os.path.join(local_data_dir, prep_file['title']))\n else:\n gc = get_gdrive_client()\n prep_workbook = gc.open_by_key(prep_UID)\n tsv_ready_lists = prep_workbook.get_worksheet(1)\n json_in_tsv_list = tsv_ready_lists.get_all_values()\n json_file = local_data_dir + '/' + experiment_name + '_ExpDataEntry.json' \n modlog.info(f'Parsing TSV to JSON from gdrive. RunID: {json_file}')\n with open(json_file, 'w') as f:\n for i in json_in_tsv_list:\n print('\\t'.join(i), file=f)\n f.close()\n\ndef parse_gdrive_folder(remote_directory, local_directory):\n ''' Handle the download and local management of files when interacting with gdrive\n\n Parameters\n ----------\n remote_directory : Gdrive UID\n UID of the Gdrive parent directory containing ESCALATE runs to process. ESCALATE \n runs are the child folders of the parent directory.\n\n local_directory : folder to store gdrive files\n report default: {target_naming_scheme}/gdrive_files/\n\n Returns\n -----------\n data_directories : dict { : folder_children uids}\n dict keyed on the child foldernames with values being all of the grandchildren \n gdrive objects (these objects are dictionaries as well with defined structure)\n\n '''\n drive = get_gdrive_auth()\n\n data_directories = {}\n print('(1/6) Retrieving Directory Structure...')\n remote_directory_children = drive.ListFile({'q': \"'%s' in parents and trashed=false\" % remote_directory}).GetList()\n for child in tqdm(remote_directory_children):\n if child['mimeType'] == 'application/vnd.google-apps.folder':\n modlog.info('downloaded file structure for {} from google drive'.format(child['title']))\n grandchildren = \\\n drive.ListFile({'q': \"'{}' in parents and trashed=false\".format(child['id'])}).GetList()\n data_directories[child['title']] = grandchildren\n\n return data_directories\n\ndef gdrive_download(local_directory, experiment_name, experiment_files):\n \"\"\" Download specific, hard coded files locally\n Only grabs observation interface, preparation interface, and\n experiment specification interfaces (v1.0). Additional will need to be\n manually added. Parsing of the files happens upstream\n \n Parameters\n ----------\n local_directory : folder to store gdrive files\n report default: {target_naming_scheme}/gdrive_files/\n \n experiment_name : name of gdrive folder containing the experiment\n aka. runUID e.g. 2019-09-18T20_27_33.741387+00_00_LBL\n\n experiment_files : list of gdrive objects (files) in experiment_name\n my_file (object in experiment_files) is a gdrive object\n (these objects are dictionaries as with defined structure)\n\n Returns\n -------\n None\n\n Notes\n -----\n Though this function returns no objects, the files are in \n a local directory for manipulation. Due to the structure of the files\n as well as how finicky google drive API can be, downloading locally \n was determined to be the best decision. \n The downloaded files are assessed later. \n\n TODO: generalize/broaden this function to grab additional files\n Trick in this case will be that not all runs will have all files\n \"\"\"\n\n drive = get_gdrive_auth()\n modlog.info(f\"Starting on {experiment_name} files, saving to {local_directory}\")\n for my_file in experiment_files:\n if \"CrystalScoring\" in my_file['title']\\\n or '_observation_interface' in my_file['title']:\n observation_file = drive.CreateFile({'id': my_file['id']})\n observation_file_title = os.path.join(local_directory, f\"{observation_file['title']}.csv\")\n observation_file.GetContentFile(observation_file_title,mimetype='text/csv')\n\n if \"ExpDataEntry\" in my_file['title']\\\n or \"preparation_interface\" in my_file['title']:\n save_prep_interface(my_file['id'], local_directory, experiment_name)\n\n if \"RobotInput\" in my_file['title']\\\n or \"ExperimentSpecification\" in my_file['title']:\n vol_file = drive.CreateFile({'id': my_file['id']})\n vol_file.GetContentFile(os.path.join(local_directory, vol_file['title']))\n return ","repo_name":"darkreactions/ESCALATE_report","sub_path":"expworkup/googleio.py","file_name":"googleio.py","file_ext":"py","file_size_in_byte":9260,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"29"} +{"seq_id":"36074961099","text":"from study_control import study_control_func\nfrom study_data import study_data_func\nfrom study_file import study_file_func\nfrom study_lib import study_lib_func\nimport sys\n\ndef help():\n print('0 -- control')\n print('1 -- data')\n print('2 -- file')\n print('3 -- lib')\n\nif __name__ == '__main__':\n print('study main')\n help()\n\n #arg = int(sys.argv[1])\n #print('arg:', arg)\n choice = int(input(\"Please enter an integer: \"))\n if choice == 0:\n study_control_func()\n elif choice == 1:\n study_data_func()\n elif choice == 2:\n study_file_func()\n elif choice == 3:\n study_lib_func()\n else:\n help()\n\n\n","repo_name":"thomas-coding/python_study","sub_path":"general/study.py","file_name":"study.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"8856099336","text":"f = open(\"inputTest.txt\", \"r\")\ngrid = [[j for j in i] for i in f.read().split(\"\\n\")]\nprint(grid)\n\n\nclass lightBeam:\n def __init__(self, pos: list, direction: list, history) -> None:\n self.pos = pos\n self.direction = direction\n self.history = history\n\n def move(self):\n self.pos = [sum(i for i in j) for j in zip(self.pos, self.direction)]\n \n if min(self.pos) < 0 or max(self.pos) >= len(grid[0]):\n return True #delete beam\n \n if tuple(zip(self.pos, self.direction)) in self.history:\n # print(\"Repeat\")\n # print([i for i in zip(self.pos, self.direction)])\n return True\n else:\n self.history[tuple(zip(self.pos, self.direction))] = 1\n \n tile = grid[self.pos[0]][self.pos[1]]\n # print(tile, f\"Tile at {self.pos}\")\n\n if tile == \"/\":\n self.direction = [-1*i for i in self.direction[::-1]]\n # print(self.direction, \"new direction\")\n\n elif tile == \"\\\\\":\n self.direction = self.direction[::-1]\n # print(self.direction, \"new direction\")\n \n elif tile == \"|\":\n if self.direction[1] != 0:\n self.direction = self.direction[::-1]\n newDirection = [-1 * i for i in self.direction]\n newBeam = lightBeam(self.pos, newDirection, self.history)\n return newBeam\n \n elif tile == \"-\":\n if self.direction[0] != 0:\n self.direction = self.direction[::-1]\n newDirection = [-1 * i for i in self.direction]\n newBeam = lightBeam(self.pos, newDirection, self.history)\n return newBeam\n \n elif tile == \".\":\n pass\n\n def moveReverse(self):\n self.pos = [sum(i for i in j) for j in zip(self.pos, [-1 * i for i in self.direction])]\n\n if min(self.pos) < 0 or max(self.pos) >= len(grid[0]):\n return True #delete beam\n \n if tuple(zip(self.pos, self.direction)) in self.history:\n # print(\"Repeat\")\n # print([i for i in zip(self.pos, self.direction)])\n return True\n else:\n self.history[tuple(zip(self.pos, self.direction))] = 1\n \n tile = grid[self.pos[0]][self.pos[1]]\n # print(tile, f\"Tile at {self.pos}\")\n\n if tile == \"/\":\n self.direction = [-1*i for i in self.direction[::-1]]\n # print(self.direction, \"new direction\")\n\n elif tile == \"\\\\\":\n self.direction = self.direction[::-1]\n # print(self.direction, \"new direction\")\n \n elif tile == \"|\":\n if self.direction[1] != 0:\n self.direction = self.direction[::-1]\n newDirection = [-1 * i for i in self.direction]\n newBeam = lightBeam(self.pos, newDirection, self.history)\n return newBeam\n \n elif tile == \"-\":\n if self.direction[0] != 0:\n self.direction = self.direction[::-1]\n newDirection = [-1 * i for i in self.direction]\n newBeam = lightBeam(self.pos, newDirection, self.history)\n return newBeam\n \n elif tile == \".\":\n pass\n \n\n \n def __str__(self) -> str:\n return f\"beam at {self.pos} moving {self.direction}\"\n \n\nclass allBeams:\n def __init__(self, pt1 = True, history = {}) -> None:\n self.history = history\n if pt1:\n self.beams = [lightBeam([0,-1], [0,1], self.history)]\n else:\n self.beams = []\n\n def moveAll(self):\n for beam in self.beams:\n value = beam.move()\n if value == True:\n self.beams.remove(beam)\n elif value == None:\n pass\n else:\n self.beams.append(value)\n\n def moveAllReverse(self):\n for beam in self.beams:\n value = beam.moveReverse()\n if value == True:\n self.beams.remove(beam)\n elif value == None:\n pass\n else:\n self.beams.append(value)\n\n\n def getPosAll(self):\n for beam in self.beams:\n print(beam.pos, \"beam pos\")\n\n def getHistory(self):\n return self.history\n \n def done(self):\n if len(self.beams) > 0:\n return False\n return True\n \n def addBeam(self, pos:list, direction: list):\n self.beams.append(lightBeam(pos, direction, self.history))\n \n\n\n\nb = allBeams()\n# for i in range(50):\n# b.moveAll()\n# b.getPosAll()\n# print()\n\nwhile not b.done():\n b.moveAll()\n # b.getPosAll()\n # print()\n\nhist = b.getHistory()\nprint(hist)\npossss = [[i[0][0], i[1][0]] for i in hist]\nnewPosss = []\n[newPosss.append(i) for i in possss if i not in newPosss]\nprint(len(newPosss), \"answer\")\n\n\nprint([i for i in hist if i[0][0] == 7 and i[1][0] == 3])\n\nlength = len(grid)\nfor i in range(length):\n for j in range(length):\n tile = grid[i][j]\n if tile == \"-\":\n if tuple(zip([i, j], [1,0])) not in hist and (tuple(zip([i, j], [0,1])) in hist or tuple(zip([i, j], [0,-1])) in hist):\n reverseBeams1 = allBeams(False, hist)\n\n reverseBeams1.addBeam([i,j], [1, 0])\n print(\"adding beam pos:\", [i, j])\n\n while not reverseBeams1.done():\n reverseBeams1.moveAllReverse()\n \n added1 = [[i[0][0], i[1][0]] for i in reverseBeams1.getHistory() if [i[0][0], i[1][0]] not in newPosss]\n print(len(added1), \"1\")\n elif tuple(zip([i, j], [-1,0])) not in hist and (tuple(zip([i, j], [0,1])) in hist or tuple(zip([i, j], [0,-1])) in hist):\n reverseBeams2 = allBeams(False, hist)\n\n reverseBeams2.addBeam([i,j], [-1, 0])\n print(\"adding beam pos:\", [i, j])\n\n while not reverseBeams2.done():\n reverseBeams2.moveAllReverse()\n \n added2 = [[i[0][0], i[1][0]] for i in reverseBeams2.getHistory() if [i[0][0], i[1][0]] not in newPosss]\n print(len(added2), \"2\")\n elif tile == \"|\":\n if tuple(zip([i, j], [0,1])) not in hist and (tuple(zip([i, j], [1,0])) in hist or tuple(zip([i, j], [-1,0])) in hist):\n reverseBeams3 = allBeams(False, hist)\n\n reverseBeams3.addBeam([i,j], [0, 1])\n print(\"adding beam pos:\", [i, j])\n\n while not reverseBeams3.done():\n reverseBeams3.moveAllReverse()\n reverseBeams3.getPosAll()\n \n added3 = [[i[0][0], i[1][0]] for i in reverseBeams3.getHistory() if [i[0][0], i[1][0]] not in newPosss]\n print(len(added3), \"3\")\n elif tuple(zip([i, j], [0,1])) not in hist and (tuple(zip([i, j], [1,0])) in hist or tuple(zip([i, j], [-1,0])) in hist):\n reverseBeams4 = allBeams(False, hist)\n\n reverseBeams4.addBeam([i,j], [0, -1])\n print(\"adding beam pos:\", [i, j])\n\n while not reverseBeams4.done():\n reverseBeams4.moveAllReverse()\n \n added4 = [[i[0][0], i[1][0]] for i in reverseBeams4.getHistory() if [i[0][0], i[1][0]] not in newPosss]\n print(len(added4), \"4\")\n\n# reverseBeams.getPosAll()\n\n# while not reverseBeams.done():\n# reverseBeams.moveAllReverse()\n# # reverseBeams.getPosAll()\n# # print()\n\n# newHist = reverseBeams.getHistory()\n# # print(newHist)\n# possss2 = [[i[0][0], i[1][0]] for i in newHist]\n# newPosss2 = []\n# [newPosss2.append(i) for i in possss2 if i not in newPosss2]\n# # print(newPosss2)\n# print(len(newPosss2), \"answer\")\n\n\n# testingPos = []\n# [testingPos.append(i) for i in possss2 if i not in newPosss]\n# print(testingPos)\n","repo_name":"pwmarshall/Advent-of-Codes","sub_path":"AOC 2023/Day 16/Day 16 pt2.py","file_name":"Day 16 pt2.py","file_ext":"py","file_size_in_byte":7964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"24065690132","text":"import json, urllib\n\n#(url) -> Python object\n#receive URL then sed request to get JSON data\n#conver JSON to return Python objects\ndef request_data(url):\n response = urllib.request.urlopen(url)\n return json.loads(response.read())\n#To-do: fix bug \"Unknown symbol\"\n\n#Receive quote symbol\n#return symbol\n# name\n# price\ndef get_quote_info(symbol):\n if not symbol:\n return None\n else:\n url = \"https://sandbox.iexapis.com/stable/stock/\"+symbol+\"/quote?token=Tsk_f8cd285ba22642d18133f27bd86c9671\"\n data = request_data(url)\n return {\n \"symbol\" : data[\"symbol\"],\n \"name\" : data[\"companyName\"],\n \"price\" : data[\"latestPrice\"]\n }\n\n\ndef get_quote_list_info(userQuoteList):\n quote_list = []\n for userQuote in userQuoteList:\n company_quote = get_quote_info(userQuote[\"symbol\"])\n company_quote[\"share\"] = userQuote[\"share\"]\n company_quote[\"total\"] = round(userQuote[\"share\"] * company_quote[\"price\"], 2)\n quote_list.append(company_quote)\n print(company_quote)\n return quote_list\n\ndef get_quote_list(chart):\n url = get_url_for_list(chart)\n data = request_data(url)\n quote_list = []\n for quote in data:\n reduced_quote = {}\n reduced_quote[\"symbol\"] = quote[\"symbol\"]\n reduced_quote[\"name\"] = quote[\"companyName\"]\n reduced_quote[\"price\"] = quote[\"latestPrice\"]\n\n quote_list.append(reduced_quote)\n return quote_list\n\ndef get_url_for_list(chart):\n return \"https://sandbox.iexapis.com/stable/stock/market/list/\"+chart+\"?token=Tsk_f8cd285ba22642d18133f27bd86c9671\"\n","repo_name":"maingockien01/Finance","sub_path":"controllers/quote_request.py","file_name":"quote_request.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"42571241156","text":"\"\"\"Code generator: Lab3 in Compiler development course \"\"\"\n\nfrom scanner import scanner\nfrom parser import parser\n\nOP_STACK = []\nINS_STACK = []\nVAR_TABLE = {}\nCONS_TABLE = {}\nLABLES_TABLE = []\nERROR_LOG = []\nPR_NAME = None\nINSTR = [\"OR\", \"AND\", \"NOT\", \"[\", \"]\"]\nFILE = None\nJUMPS = {\n \"<>\": \"jne\",\n \"<\" : \"jl\",\n \">\" : \"jg\",\n \">=\": \"jge\",\n \"<=\": \"jle\",\n \"=\" : \"je\",\n}\n\nREG = {\n 1: \"eax\",\n 2: \"ebx\",\n 3: \"ecx\",\n 4: \"edx\",\n}\n\n\nPRIORITY = {\n \"OR\" : 0,\n \"AND\": 1,\n \"NOT\": 2\n}\n\nCURR_REG = 1\nLABLE_NUM = 1\n\ndef is_valid(operand):\n if operand != PR_NAME and operand in VAR_TABLE.keys() and VAR_TABLE[operand][-1] == 1:\n return True\n return False\n\ndef generate_text():\n global FILE\n FILE.write(\"\\nsegment .text\\n\\tglobal _start\\n_start:\\n\")\n LABLES_TABLE.append(\"_start\")\n\ndef generate_bss(subtree):\n global FILE\n variable = subtree.child[0].data\n if variable[-1] in VAR_TABLE.keys() or variable[-1] == PR_NAME:\n ERROR_LOG.append(variable)\n else:\n VAR_TABLE[variable[-1]] = [variable, 0]\n FILE.write(\"\\t{} resd 1\\n\".format(variable[-1]))\n\ndef generate_cond(first_operand, condition, second_operand):\n global CURR_REG\n global LABLE_NUM\n global FILE\n register = first_operand.child[0]\n operand = second_operand.child[0]\n if register.rule == \"\" and register.data[-1] not in CONS_TABLE.keys():\n CONS_TABLE[register.data[-1]] = register.data\n elif register.rule == \"\":\n if not is_valid(register.child[0].data[-1]):\n ERROR_LOG.append(register.child[0].data)\n register = register.child[0]\n\n if operand.rule == \"\" and operand.data[-1] not in CONS_TABLE.keys():\n CONS_TABLE[operand.data[-1]] = operand.data\n elif operand.rule == \"\":\n if not is_valid(operand.child[0].data[-1]):\n ERROR_LOG.append(operand.child[0].data)\n operand = operand.child[0]\n\n FILE.write(\"\\tmov {}, {}\\n\".format(REG[CURR_REG], register.data[-1]))\n FILE.write(\"\\tcmp {}, {}\\n\\t{} label{}\\n\".format(REG[CURR_REG], operand.data[-1],\n JUMPS[condition.data[-1]], LABLE_NUM))\n\n FILE.write(\"\\t\\tmov {}, 0\\n\\t\\tjmp label{}\\n\".format(REG[CURR_REG], LABLE_NUM + 1))\n FILE.write(\"\\tlabel{}:\\n\\t\\tmov {}, 1\\n\".format(LABLE_NUM, REG[CURR_REG]))\n FILE.write(\"\\tlabel{}:\\n\\n\".format(LABLE_NUM + 1))\n OP_STACK.append(REG[CURR_REG])\n LABLE_NUM += 2\n CURR_REG += 1\n\n\ndef clean_up_stack(variable):\n global CURR_REG\n global FILE\n #print(OP_STACK)\n #print(INS_STACK)\n while INS_STACK != []:\n if INS_STACK[-1] == \"NOT\":\n FILE.write(\"\\t{} {}\\n\".format(INS_STACK.pop(), OP_STACK[-1]))\n else:\n operand = OP_STACK.pop()\n result = OP_STACK[-1]\n FILE.write(\"\\t{} {}, {}\\n\".format(INS_STACK.pop(), result, operand))\n\n FILE.write(\"\\tmov [{}], {}\\n\".format(variable.data[-1], OP_STACK[-1]))\n CURR_REG = 1\n OP_STACK.pop()\n if variable.data[-1] in VAR_TABLE.keys():\n VAR_TABLE[variable.data[-1]][-1] = 1\n else:\n ERROR_LOG.append(variable.data)\n\n\ndef switch(subtree):\n \"\"\" generates code which is depends on condition \"\"\"\n global PR_NAME\n global CURR_REG\n global FILE\n if subtree.rule == \"\":\n PR_NAME = subtree.child[0].data[-1]\n return True\n elif subtree.rule == \"\":\n FILE.write(\"segment .bss\\n\")\n return False\n elif subtree.rule == \"\":\n generate_bss(subtree.child[0])\n return True\n elif subtree.rule == \"\" and subtree.data[0] == 101:\n generate_text()\n return False\n elif subtree.rule == \"\" and subtree.data[0] == 102:\n FILE.write(\"\\tmov eax, 1\\n\\tint 0x80\\n\")\n return False\n elif subtree.rule == \"\":\n FILE.write(\"\\n\\tnop\\n\\n\")\n return False\n\n elif subtree.rule == \"\":\n code_generator(subtree.child[2])\n clean_up_stack(subtree.child[0].child[0])\n return True\n\n elif subtree.rule == \"\" and subtree.child[0].rule == \"\":\n generate_cond(subtree.child[0], subtree.child[1], subtree.child[2])\n return True\n\n elif (subtree.rule == \"\" or subtree.rule == \"\")\\\n and subtree.data[-1] in INSTR:\n if INS_STACK == [] or subtree.data[-1] == \"[\" or INS_STACK[-1] == \"[\":\n INS_STACK.append(subtree.data[-1])\n\n elif subtree.data[-1] == \"]\":\n while INS_STACK[-1] != \"[\":\n if INS_STACK[-1] == \"NOT\":\n while INS_STACK[-1] == \"NOT\":\n FILE.write(\"\\t{} {}\\n\".format(INS_STACK.pop(), OP_STACK[-1]))\n else:\n operand = OP_STACK.pop()\n result = OP_STACK[-1]\n FILE.write(\"\\t{} {}, {}\\n\".format(INS_STACK.pop(), result, operand))\n CURR_REG -= 1\n INS_STACK.pop()\n\n elif PRIORITY[subtree.data[-1]] > PRIORITY[INS_STACK[-1]] or subtree.data[-1] == \"NOT\":\n INS_STACK.append(subtree.data[-1])\n\n else:\n if INS_STACK[-1] == \"NOT\":\n while INS_STACK[-1] == \"NOT\":\n FILE.write(\"\\t{} {}\\n\".format(INS_STACK.pop(), OP_STACK[-1]))\n if PRIORITY[subtree.data[-1]] <= PRIORITY[INS_STACK[-1]]:\n operand = OP_STACK.pop()\n result = OP_STACK[-1]\n FILE.write(\"\\t{} {}, {}\\n\".format(INS_STACK.pop(), result, operand))\n CURR_REG -= 1\n else:\n operand = OP_STACK.pop()\n result = OP_STACK[-1]\n FILE.write(\"\\t{} {}, {}\\n\".format(INS_STACK.pop(), result, operand))\n CURR_REG -= 1\n INS_STACK.append(subtree.data[-1])\n else:\n return False\n\n\ndef code_generator(tree):\n \"\"\" Generate assembly code with black jack and sluts \"\"\"\n #print(tree.rule)\n if switch(tree):\n return\n for item in tree.child:\n code_generator(item)\n\ndef cgenerator(tree, filename):\n \"\"\" main function \"\"\"\n global FILE\n with open(filename, \"w\") as FILE:\n code_generator(tree)\n\n\n\nif __name__ == \"__main__\":\n lexems = scanner(\"t.txt\")\n tree, tokens = parser(lexems)\n cgenerator(tree, \"out.asm\")\n print(ERROR_LOG)\n\n","repo_name":"VladPodilnyk/signal-compiler","sub_path":"legacy/codegen.py","file_name":"codegen.py","file_ext":"py","file_size_in_byte":6494,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"8246792739","text":"from Downloader_base import DownloaderBase\nimport requests\nfrom datetime import datetime\nimport time\nimport sys, getopt,os\noutpath = 'D:\\\\MY_DownLoad\\\\'\nkind_dict_link=[\n {\n 'key_word':'live_panda/',\n 'start_str':'live_panda/',\n 'end_str':'?sign',\n 'type':'panda'\n },\n {\n 'key_word':'huyalive/',\n 'start_str':'huyalive/',\n 'end_str':'?wsSecret',\n 'type':'huya'\n },\n {\n 'key_word':'panda-xingxiu/',\n 'start_str':'panda-xingxiu/',\n 'end_str':'?',\n 'type':'panda'\n },\n {\n 'key_word':'lzlive/',\n 'start_str':'lzlive/',\n 'end_str':'?',\n 'type':'longzhu'\n },\n {\n 'key_word':'panda-xingyan/',\n 'start_str':'panda-xingyan/',\n 'end_str':'?',\n 'type':'panda'\n },\n {\n 'key_word':'onlive/',\n 'start_str':'onlive/',\n 'end_str':'?',\n 'type':'HUYA'\n },\n {\n 'key_word':'live.panda.tv/p2p/flv/hint?sign=',\n 'start_str':'&rid=',\n 'end_str':'&stream=',\n 'type':'panda'\n },\n]\n\nclass DownloaderStableLink(DownloaderBase):\n def __init__(self, link):\n self.link = link\n self.fileName = self.analysisFileName()\n self.is_valid = True\n \n def get_valid(self):\n return self.is_valid\n \n def analysisFileName(self):\n for type_record in kind_dict_link:\n if self.link.find(type_record['key_word']) != -1:\n print('it is a '+type_record['type']+'tv link')\n index1 = self.link.find(type_record['start_str']) + len(type_record['start_str'])\n index2 = self.link.find(type_record['end_str'])\n break\n try:\n file_name = self.link[index1:index2]\n outfile = outpath+file_name\n date = datetime.now().__str__()\n date = date.replace(' ', '').replace('-', '').replace(':', '').replace('.', '')\n outfile = outfile.split('.')[0]+'_'+date+'.flv'\n return outfile\n except Exception as e:\n self.is_valid = False\n \n def get_next_file_name(self):\n if self.is_valid == False:\n print(\"link is invalid\")\n return \"\"\n index1 = self.fileName.split('.')[0]\n index2 = index1.find('##')\n index3 = 1\n if index2 == -1:\n index2 = len(index1)\n else:\n index3 = self.fileName[index2+2:len(index1)]\n index3 = int(index3) + 1\n self.fileName = self.fileName[:index2]+'##'+str(index3)+'.flv'\n return self.fileName\n \n def get_next_link(self):\n return self.link\n \nif __name__==\"__main__\":\n tester = DownloaderStableLink(\"https://3grauymtt8rzdnqb1fahdn.ourdvsss.com/pl3.live.panda.8686c.com/live_panda/e900b5f1420886d08fe60acb82d6cec7_4000.flv?sign=fcd87c307001eb7fe60a8f47d236791f&ts=5b894f55&rid=27836296&add_index_info=1&wshc_tag=0&wsts_tag=5b894f59&wsid_tag=72f4bb6a&wsiphost=ipdbm\")\n print(tester.fileName)\n print(tester.get_next_file_name()) \n \n ","repo_name":"ckdkambh/python_collection","sub_path":"REPO/downloadstream/src/Downloader_stable_link.py","file_name":"Downloader_stable_link.py","file_ext":"py","file_size_in_byte":3107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15279929715","text":"lst1 = [\"a\", \"b\", \"c\"]\nlst2 = [\"b\", \"c\", \"a\"]\nlst3 = [\"c\", \"a\"]\nlambdaMix = list(map(lambda x, y, z: x + y + z, lst1, lst2, lst3))\n# print(lambdaMix)\n\nstring1 = \"A-yo man!\"\nstring2 = \"What's up?\"\nstring3 = \"How to survive jungle?\"\nlamdaString = \"\".join(list(map(lambda x, y, z: x + y + z, string1, string2, string3)))\n# print(lamdaString)\n\nnumbers = list(range(1, 100))\n*a, b, c = numbers\n# print(a, b, c)\na, *b, c = numbers\n# print(a, b, c)\na, b, *c = numbers\n# print(a, b, c)\n\n\nlambdaSum = list(map(lambda x, y: x + y, numbers[::2], numbers[1::2]))\n# print(lambdaSum)\n\ntplLst = [(1, 2), (3, 4), (5, 6)]\n# try:\n# a, c, e = tplLst\n# print(a, c, e)\n# except:\n# print(\"try1: error\")\n\n\n\"\"\" unpack from 2D list \"\"\"\n# try:\n# a, b, c, d, e, f = tplLst\n# print(a, b, c, d, e, f)\n# except:\n# print(\"try2: error\")\n\n\"\"\" unpack from tuples \"\"\"\n# try:\n# a, c, e = tplLst\n# a, b, c, d, e, f = a, c, e\n# print(a, b, c, d, e, f)\n# except:\n# print(\"try3: error\")\n\n\"\"\" unpack from unpacked tuple\"\"\"\n# try:\n# a, c, e = tplLst\n# a, b, c, d, e, f = *a, *c, *e\n# print(a, b, c, d, e, f)\n# except:\n# print(\"try4: error\")\n\n\"\"\" list comprehension \"\"\"\n# try:\n# a, b, c, d, e, f = [element for sublst in tplLst for element in sublst]\n# print(a, b, c, d, e, f)\n# except:\n# print(\"try5: error\")\n# tmp = [tplLst]\n# try:\n# tmp = [tplLst]\n# a, b, c, d, e, f = [element for sublst in tmp for subtpl in sublst for element in subtpl]\n# print(a, b, c, d, e, f)\n# except:\n# print(\"try5.1: error\")\n\n\"\"\" sum ??? \"\"\"\n# try:\n# a, b, c, d, e, f = sum(tplLst, ())\n# print(a, b, c, d, e, f)\n# except:\n# print(\"try6: error\")\n\n\n\"\"\" itertools.chain - unpack 1D\"\"\"\n# from itertools import chain\n\n# tmp = [tplLst]\n# print(tmp)\n# print(list(chain.from_iterable(tmp)))\n# print(list(chain.from_iterable(chain.from_iterable(tmp))))\n# test = [1, 2, 3, tplLst]\n# print(test)\n# print(list(chain.from_iterable(test)))\n","repo_name":"Hamsik2rang/Krafton-Jungle-Whiteboard-Algorithm","sub_path":"이현홍/old/etc.py","file_name":"etc.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"29"} +{"seq_id":"17557574235","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8])\ny = np.array([1, 2, 3, 5, 4, 6, 8, 7, 9])\n\ncoeffs = np.polyfit(x, y, 1)\n\nprint(coeffs)\n\na = coeffs[0]\nb = coeffs[1]\nest_y = (a * x) + b\n\nplt.plot(x, est_y)\nplt.scatter(x, y)\nplt.show()\n","repo_name":"eocode/Software-development-and-Data-Science","sub_path":"learn/Algoritmos/Programacion Dinamica y estocastica/Regresión lineal/regresion.py","file_name":"regresion.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"551162802","text":"\nimport pandas as pd\nimport numpy as np\nfrom services.api_calls import time_series_fun_monthly\nimport pickle\n\ndef load_and_preprocess_data(API_KEY, ticker):\n \n # Load the data\n data = time_series_fun_monthly(API_KEY, ticker)\n return data # assuming coords is the preprocessed data\n\n\ndef calculate_dca_return(stock_data, monthly_investment, months_to_invest):\n \"\"\"\n Dollar Cost Averaging (DCA) Monte Carlo Sitmulation Implementation\n Invest $1000 per month in ETF. Once every month, randomly choose one day to purchase the maximum number of shares allowed with available buying power\n Calculate the return of dollar-cost averaging on a stock.\n\n Parameters:\n stock_data (DataFrame): Historical stock data.\n monthly_investment (float): Amount invested each month.\n months_to_invest (int): Number of months over which investments are made.\n\n Returns:\n float: ROI (Return on Investment)\n \"\"\"\n # Ensure 'Date' column is in datetime format\n stock_data['Date'] = pd.to_datetime(stock_data['Date'])\n\n # Generate a range of dates for analysis\n start_date = stock_data['Date'].min()\n end_date = stock_data['Date'].max() - pd.DateOffset(months=months_to_invest)\n date_range = pd.date_range(start=start_date, end=end_date, freq='M')\n\n # Randomly select a start month for investing\n invest_start_date = np.random.choice(date_range)\n\n # Initialize investment tracking variables\n total_investment = 0\n total_value = 0\n shares_owned = 0\n\n # Loop over each month to calculate investment progress\n for month_count in range(months_to_invest):\n current_date = invest_start_date + pd.DateOffset(months=month_count)\n current_stock_data = stock_data[stock_data['Date'].dt.to_period('M') == current_date.to_period('M')]\n\n if not current_stock_data.empty:\n # Randomly select a trading day in the month\n random_trading_day = current_stock_data.sample()\n\n # Get closing price and calculate number of shares bought\n closing_price = float(random_trading_day['close'].iloc[0])\n shares_bought = monthly_investment / closing_price\n\n # Update investment totals\n total_investment += monthly_investment\n shares_owned += shares_bought\n total_value = shares_owned * closing_price\n\n # Calculate ROI\n roi = (total_value - total_investment) / total_investment\n\n return roi\n\n\ndef apply_model(stock_data, num_iter, dollars, num_months):\n # dca_simulation SPY 12-month simulation\n stock_data = stock_data\n num_iter = int(num_iter)\n dollars = float(dollars)\n num_months = int(num_months)\n ticker_sim_dat = []\n\n for k in range(num_iter):\n # caluations for simulation\n x = calculate_dca_return(stock_data, dollars, num_months)\n ticker_sim_dat.append(100*x)\n # print(\"iterating\", k)\n \n return ticker_sim_dat\n\n\ndef save_data(new_results):\n \n # we take raw data and save its as \n \n # SERALIAZAIION \n pickled_data = pickle.dumps(new_results)\n print(\"successfully saved\")\n\n\ndef call_model(API_KEY, form_data):\n # Step 1: Preprocess the messy data\n data_for_model = load_and_preprocess_data(API_KEY, form_data['ticker'])\n \n # Step 2: we load model and predict & rearrage the data\n new_results = apply_model(data_for_model, \n form_data['num_iter'], \n form_data['dollars'], \n form_data['num_months'])\n\n # Step 3: Save the organized data to data base\n save_data(new_results)\n return new_results","repo_name":"Gresliebear/Nittany-AI-Rapid-Prototyping-Code","sub_path":"back-end-prototype/models/model_call.py","file_name":"model_call.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"1184219425","text":"import mock\nfrom kombu import Connection, Exchange, Queue\n\nfrom st2common.transport import consumers\nfrom st2common.transport import utils as transport_utils\nfrom st2tests.base import DbTestCase\nfrom tests.unit.base import FakeModelDB\n\n\nFAKE_XCHG = Exchange('st2.tests', type='topic')\nFAKE_WORK_Q = Queue('st2.tests.unit', FAKE_XCHG)\n\n\nclass FakeMessageHandler(consumers.MessageHandler):\n message_type = FakeModelDB\n\n def process(self, payload):\n pass\n\n\ndef get_handler():\n with Connection(transport_utils.get_messaging_urls()) as conn:\n return FakeMessageHandler(conn, [FAKE_WORK_Q])\n\n\nclass QueueConsumerTest(DbTestCase):\n\n @mock.patch.object(FakeMessageHandler, 'process', mock.MagicMock())\n def test_process_message(self):\n payload = FakeModelDB()\n handler = get_handler()\n handler._queue_consumer._process_message(payload)\n FakeMessageHandler.process.assert_called_once_with(payload)\n\n @mock.patch.object(FakeMessageHandler, 'process', mock.MagicMock())\n def test_process_message_wrong_payload_type(self):\n payload = 100\n handler = get_handler()\n handler._queue_consumer._process_message(payload)\n self.assertFalse(FakeMessageHandler.process.called)\n","repo_name":"lu-chi/st2","sub_path":"st2common/tests/unit/test_queue_consumer.py","file_name":"test_queue_consumer.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"29"} +{"seq_id":"41229383082","text":"\"\"\"All constants for structure sizing are stored here.\nBy I. Maes, N. Ricker\"\"\"\n\n\n\naxial_freq_falcon = 25 # [Hz] Axial freq of the Falcon Heavy\nlateral_freq_falcon = 10 # [Hz] Lateral freq of the Falcon Heavy\ng_axial = 8.5 # [g] Axial load factor\ng_lateral = 3 # [g] Lateral load factor\ng_tensile = 4 # [g] Tensile load factor (negative g)\ng = 9.80665\ntemperatures = [0, 40]\n\nmaterial_properties = {\n \"Aluminium_6061-T6\": {\n \"density\": 2710, # [kg/m^3]\n \"yield_strength\": 276e6, # [Pa]\n \"ultimate_strength\": 310e6, # [Pa]\n \"E\": 68.9e9, # [Pa]\n \"thermal_coefficient\": 23.6e-6, # [m/m]\n },\n \"Aluminium_7075-T73\": {\n \"density\": 2800, # [kg/m^3]\n \"yield_strength\": 435e6, # [Pa]\n \"ultimate_strength\": 505e6, # [Pa]\n \"shear_strength\": 300e6,\n \"E\": 72e9, # [Pa]\n \"thermal_coefficient\": 23.6e-6, # [m/m]\n },\n \"Aluminium_2219-T851\": {\n \"density\": 2850, # [kg/m^3]\n \"yield_strength\": 352e6, # [Pa]\n \"ultimate_strength\": 455e6, # [Pa]\n \"E\": 73.1e9, # [Pa]\n \"thermal_coefficient\": 22.3e-6, # [m/m]\n },\n \"Ti-6AL-4V\": {\n \"density\": 4430, # [kg/m^3]\n \"yield_strength\": 880e6, # [Pa]\n \"ultimate_strength\": 950e6, # [Pa]\n \"E\": 113.8e9, # [Pa]\n \"thermal_coefficient\": 8.6e-6, # [m/m]\n },\n \"Magnesium\": {\n \"density\": 1770, # [kg/m^3]\n \"yield_strength\": 220e6, # [Pa]\n \"ultimate_strength\": 290e6, # [Pa]\n \"E\": 45e9, # [Pa]\n \"thermal_coefficient\": 26e-6, # [m/m]\n },\n \"Heat-res_alloy_A-286\": {\n \"density\": 7940, # [kg/m^3]\n \"yield_strength\": 720e6, # [Pa]\n \"ultimate_strength\": 1000e6, # [Pa]\n \"E\": 201e9, # [Pa]\n \"thermal_coefficient\": 0, # [m/m]\n },\n \"Heat-res_alloy_inconel_718\": {\n \"density\": 8220, # [kg/m^3]\n \"yield_strength\": 1034e6, # [Pa]\n \"ultimate_strength\": 1241e6, # [Pa]\n \"E\": 200e9, # [Pa]\n \"thermal_coefficient\": 0, # [m/m]\n },\n \"Steel_17-4PH_H1150\": {\n \"density\": 7860, # [kg/m^3]\n \"yield_strength\": 862e6, # [Pa]\n \"ultimate_strength\": 1000e6, # [Pa]\n \"E\": 196e9, # [Pa]\n \"thermal_coefficient\": 0 # [m/m]\n },\n \"Beryllium\": {\n \"density\": 1850, # [kg/m^3]\n \"yield_strength\": 241e6, # [Pa]\n \"ultimate_strength\": 324e6, # [Pa]\n \"E\": 290e9, # [Pa]\n \"thermal_coefficient\": 11.3 # [m/m]\n }}\n\ncomponents = {\n \"cmg1\": {\n \"subsystem\": \"ADCS\",\n \"mass\": 10, # [kg]\n \"cg\": [0, 0.37, 0] # [m]\n },\n \"cmg2\": {\n \"subsystem\": \"ADCS\",\n \"mass\": 10, # [kg]\n \"cg\": [0, -0.37, 0] # [m]\n },\n \"star_sensors\": {\n \"subsystem\": \"ADCS\",\n \"mass\": 4*0.47, # [kg]\n \"cg\": [0, 0, 0] # [m]\n },\n \"sun_sensors\": {\n \"subsystem\": \"ADCS\",\n \"mass\": 15*0.05, # [kg]\n \"cg\": [0, 0, 0] # [m]\n },\n \"ring_laser_gyros\": {\n \"subsystem\": \"ADCS\",\n \"mass\": 4*0.454, # [kg]\n \"cg\": [0, 0, 0] # [m]\n },\n \"computer\": {\n \"subsystem\": \"CDH\",\n \"mass\": 9, # [kg]\n \"cg\": [-.35, -0.3, .375] # [m]\n },\n \"Galileo_PCDU\": {\n \"subsystem\": \"EPS\",\n \"mass\": 18.2, # [kg]\n \"cg\": [-.175, 0.400, -.200] # [m]\n },\n \"NSGU\": {\n \"subsystem\": \"Navigation\",\n \"mass\": 12, # [kg]\n \"cg\": [0.35, 0, .360] # [m]\n },\n \"FGUU\": {\n \"subsystem\": \"Navigation\",\n \"mass\": 7.6, # [kg]\n \"cg\": [-0.1, 0, .360] # [m]\n },\n \"Clock_Monitor\": {\n \"subsystem\": \"Navigation\",\n \"mass\": 5.2, # [kg]\n \"cg\": [0.05, -.400, -0.4] # [m]\n },\n \"Clock1\": {\n \"subsystem\": \"Navigation\",\n \"mass\": 15.9, # [kg]\n \"cg\": [.350, -0.3, 0.36] # [m]\n },\n \"Clock2\": {\n \"subsystem\": \"Navigation\",\n \"mass\": 15.9, # [kg]\n \"cg\": [.350, 0.3, 0.36] # [m]\n },\n \"Clock3\": {\n \"subsystem\": \"Navigation\",\n \"mass\": 15.9, # [kg]\n \"cg\": [-.350, 0.3, 0.36] # [m]\n },\n \"Battery1\": {\n \"subsystem\": \"EPS\",\n \"mass\": 48, # [kg]\n \"cg\": [0, 0, -0.38] # [m]\n },\n \"Battery2\": {\n \"subsystem\": \"EPS\",\n \"mass\": 29.64, # [kg]\n \"cg\": [0, 0.4, -0.37] # [m]\n },\n \"Cables\": {\n \"subsystem\": \"EPS\",\n \"mass\": 100, # [kg]\n \"cg\": [0, 0, 0] # [m]\n },\n \"GR1_Thrusters\": {\n \"subsystem\": \"Propulsion\",\n \"mass\": 12*0.29, # [kg]\n \"cg\": [0, 0, 0] # [m]\n },\n \"GR22_Thruster\": {\n \"subsystem\": \"Propulsion\",\n \"mass\": 0.59*2, # [kg]\n \"cg\": [0, 0, 0] # [m]\n },\n \"Filters_Valves\": {\n \"subsystem\": \"Propulsion\",\n \"mass\": 4.4, # [kg]\n \"cg\": [0, 0, 0] # [m]\n },\n \"TTC_User\": {\n \"subsystem\": \"TTC\",\n \"mass\": 4*0.6278, # [kg]\n \"cg\": [0, 0, 0.5] # [m]\n },\n \"TTC_Relay\": {\n \"subsystem\": \"TTC\",\n \"mass\": 0.19085, # [kg]\n \"cg\": [0, 0, 0] # [m]\n },\n \"TTC_ISL\": {\n \"subsystem\": \"TTC\",\n \"mass\": 4, # [kg]\n \"cg\": [-0.6, 0, -0.27] # [m]\n },\n \"TTC_Reflector\": {\n \"subsystem\": \"TTC\",\n \"mass\": 12.43, # [kg]\n \"cg\": [-0.6, 0, 0.23] # [m]\n },\n \"Radiator1\": {\n \"subsystem\": \"TCS\",\n \"mass\": 11.85/2, # [kg]\n \"cg\": [0.45, 0, -0.2] # [m]\n },\n \"Radiator2\": {\n \"subsystem\": \"TCS\",\n \"mass\": 11.85/2, # [kg]\n \"cg\": [-0.45, 0, 0.2] # [m]\n },\n \"Heaters\": {\n \"subsystem\": \"TCS\",\n \"mass\": 1, # [kg]\n \"cg\": [0, 0, 0] # [m]\n },\n \"Phase_Change_Material\": {\n \"subsystem\": \"TCS\",\n \"mass\": 35, # [kg]\n \"cg\": [0, 0, 0] # [m]\n },\n \"Antenna_Support\": {\n \"subsystem\": \"Structures\",\n \"mass\": 3, # [kg]\n \"cg\": [0, 0, 0] # [m]\n },\n \"Mechanisms\": {\n \"subsystem\": \"Structures\",\n \"mass\": 10, # [kg]\n \"cg\": [0, 0, 0] # [m]\n },\n \"Tank_Support\": {\n \"subsystem\": \"Structures\",\n \"mass\": 10, # [kg]\n \"cg\": [0, 0, 0] # [m]\n }\n}\n","repo_name":"POTN1K/LunarNavigation","sub_path":"subsystems_design/structures_sub/structures_constants.py","file_name":"structures_constants.py","file_ext":"py","file_size_in_byte":6195,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"2179661829","text":"# this program is given a start set of values in a list and instructions to be worked on\n\nentry = [8,9,10] # initial set of values\n\nentry[1] = 17 # set index 1 to 17\n\nentry += [4,5,6] # add 4,5,6 to the end of the list\n\nentry.remove(entry[0]) # remove the first entry from the list\n\nentry.sort() # sort the list\n\nentry *= 2 # Double the list\n\nentry.insert(3,25) # insert 25 at index 3\n\nprint(entry)\n\n# the final list should equal [4,5,6,25,10,17,4,5,6,10,17]","repo_name":"princesslisa/automatetxtbk","sub_path":"Assessment 4/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"879533887","text":"import pprint as pp\nimport sys as s\n\ntotal_gastado = 0.0\niniciar_compra = \"\"\ncontinuar_comprando = \"\"\nindex = 0\n\ncompras_realizadas = []\n\n# version.bug\nversion = 1.0\n\ndef alta(compras_realizadas_local, total_gastado_local):\n producto = input(\"Ingresar el producto comprado: \")\n cantidad = input(\"ingrese el peso en kg: \")\n precio = input(\"Ingrese el precio en pesos: \")\n total_gastado_local += float(precio)\n cliente = [producto, cantidad, precio] \n compras_realizadas_local.append(cliente)\n return \"Y\", total_gastado_local\n\ndef baja(compras_realizadas_local, total_gastado_local):\n producto = input(\"Ingrese el producto de la compra que desea dar de baja: \")\n for compra in compras_realizadas_local:\n if compra[0] == producto:\n total_gastado_local -= float(compra[2])\n compras_realizadas_local.remove([compra[0], compra[1], compra[2]]) \n return \"Y\", total_gastado_local\n\ndef consulta(compras_realizadas_local):\n index = 0\n print(\"Las compras realizadas hasta el momento son la siguientes: \")\n for compra in compras_realizadas_local:\n index += 1\n print(f\"El producto {index} comprado es {compra[0]}, la cantidad comprada es {compra[1]} y el precio es {compra[2]}\")\n return \"Y\"\n\ndef modificar(compras_realizadas_local, total_gastado_local):\n producto = input(\"Ingrese el producto de la compra que desea modificar: \")\n for compra in compras_realizadas_local:\n if compra[0] == producto:\n total_gastado_local -= float(compra[2])\n\n producto_aux = input(\"Ingresar el nuevo producto: \")\n cantidad = input(\"ingrese el nuevo peso en kg: \")\n precio = input(\"Ingrese el nuevo precio en pesos: \")\n\n total_gastado_local += float(precio)\n compra[0] = producto_aux\n compra[1] = cantidad\n compra[2] = precio\n \n return \"Y\", total_gastado_local\n\ndef menu():\n print(\"----------- MENU --------------\")\n print(\"1- Alta de compra\")\n print(\"2- Baja de compra\")\n print(\"3- Consulta de productos comprados hasta el momento\")\n print(\"4- Modificar compra\")\n print(\"5- Finalizar compra\")\n\nprint(f\"Version de programa {version}\")\n\nwhile iniciar_compra != \"Y\" and iniciar_compra != \"N\":\n iniciar_compra = input(\"Desea iniciar una compra Y/N: \")\n\nif(iniciar_compra == \"Y\"):\n while continuar_comprando != \"N\":\n menu()\n tarea = input(\"Ingrese el numero de tarea que desea llevar a cabo: \")\n if tarea == \"1\":\n aux = alta(compras_realizadas, total_gastado)\n continuar_comprando = aux[0]\n total_gastado = aux[1]\n elif tarea == \"2\":\n aux = baja(compras_realizadas, total_gastado)\n continuar_comprando = aux[0]\n total_gastado = aux[1]\n elif tarea == \"3\":\n continuar_comprando = consulta(compras_realizadas)\n elif tarea == \"4\":\n aux = modificar(compras_realizadas, total_gastado)\n continuar_comprando = aux[0]\n total_gastado = aux[1]\n elif tarea == \"5\":\n continuar_comprando = \"N\"\n else:\n continuar_comprando = \"Y\"\n\n print(f\"El precio total e la compra es {total_gastado} pesos\")\n print(compras_realizadas)\n print(\"Programa finalizado\")\n s.exit()\nelse:\n #No desea iniciar una compra entonces termino el programa con sys.exit()\n print(\"Programa finalizado\")\n s.exit()\n","repo_name":"gastonvallasciani/Diplomatura-Python3","sub_path":"python_inicial/modulo_1/unidad_3/unidad_3_ejercicio_8.py","file_name":"unidad_3_ejercicio_8.py","file_ext":"py","file_size_in_byte":3450,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"15402018057","text":"# 7. Напишите программу, доказывающую или проверяющую, что для множества натуральных чисел\n# выполняется равенство: 1+2+...+n = n(n+1)/2, где n - любое натуральное число.\n\nn = int(input('Введите любое натуральное число: '))\ndef prove_equality(n):\n left_part = 0\n for i in range(1, n + 1):\n left_part += i\n right_part = n * (n + 1) // 2\n print(f'Левая часть равенства = {left_part}')\n print(f'Правая часть равенства = {right_part}')\n if left_part == right_part:\n print(f'{left_part} = {right_part}, что и требовалось доказать.')\n\nprove_equality(n)","repo_name":"phocaman/geekbrains.homework","sub_path":"intro_to_data_structures_and_algorithms/lesson2/lesson2.task7.py","file_name":"lesson2.task7.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3339057208","text":"secs = 0\r\nmin = 0\r\nhour = 0\r\n\r\nfrom time import sleep as sd\r\nfrom os import system as lk\r\nlk(\"color a\")\r\nwhile True:\r\n lk(\"cls\")\r\n\r\n print(str(hour).zfill(2) + \":\" + str(min).zfill(2) + \":\" + str(secs).zfill(2))\r\n secs += 1\r\n sd(1)\r\n if secs == 60:\r\n secs = 0\r\n min += 1\r\n if min == 60:\r\n min = 0\r\n hour += 1\r\n if min == 25: # Burada 25. dakikaya gelince Windows Bildirim sesi çalıyor\r\n print(\"\\a\")\r\n break\r\n","repo_name":"ssevban/Python","sub_path":"Python Sayaç/python_sayac.py","file_name":"python_sayac.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"21501797331","text":"#สร้างfunction\ndef hello():\n print(\"hello function\")\n \n#เรียกใช้function\nhello()\n#ฟังก์ชั่นแบบส่งค่าผ่าน parameter\ndef helloName(name):\n print(\"hello\",name)\nhelloName(\"Wisanu\")\ndef grade(name,score):\n if score>=80:\n print(name,\"grade A\")\n elif score>=70:\n print(name,\"grade B\")\n elif score>=60:\n print(name,\"grade C\")\n elif score>=50:\n print(name,\"grade D\")\n else:\n print(name,\"grade F\")\ngrade(\"wisanu\",80)\ngrade(\"soranun\",49)\ngrade(\"weerapat\",70)\n#returnค่ากลับ\ndef sumScore(score1,score2,score3,score4,score5):\n sum =score1+score2+score3+score4+score5\n return sum\ngrade(\"wisanu\",sumScore(20,18,17,19,15))","repo_name":"Krustack/python01","sub_path":"function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14705754435","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import datetime, timedelta\nfrom celery.decorators import periodic_task\n\nfrom django.db.models import Q\nfrom django.contrib.auth.models import User\nfrom django.utils.translation import ugettext as _\nfrom django.core.urlresolvers import reverse\nfrom django.conf import settings\n\nfrom ecs.core.models import Vote\nfrom ecs.meetings.models import Meeting\nfrom ecs.utils.common_messages import send_submission_message\n\ndef send_vote_expired(vote):\n recipients_q = Q(username=settings.ECSMAIL['postmaster'])\n if vote.submission_form.submitter:\n recipients_q |= Q(pk=vote.submission_form.submitter.pk)\n if vote.submission_form.submitter_email:\n recipients_q |= Q(email=vote.submission_form.submitter_email)\n\n recipients = User.objects.filter(recipients_q)\n\n url = reverse('ecs.core.views.readonly_submission_form', kwargs={ 'submission_form_pk': vote.submission_form.pk })\n text = _(u'Das Votum für die Studie EK-Nr. %(ec_number)s vom %(meeting_date)s ist abgelaufen.\\n') % {\n 'url': url,\n 'ec_number': vote.submission_form.submission.get_ec_number_display(),\n 'meeting_date': vote.top.meeting.start.strftime('%d.%m.%Y'),\n }\n\n subject = _(u'Ablauf des Votums für die Studie EK-Nr. %s') % vote.submission_form.submission.get_ec_number_display()\n send_submission_message(vote.submission_form.submission, subject, text, recipients, username='root')\n\ndef send_vote_reminder_submitter(vote):\n recipients = User.objects.none()\n if vote.submission_form.submitter:\n recipients |= User.objects.filter(pk=vote.submission_form.submitter.pk)\n if vote.submission_form.submitter_email:\n recipients |= User.objects.filter(email=vote.submission_form.submitter_email)\n\n url = reverse('ecs.core.views.readonly_submission_form', kwargs={ 'submission_form_pk': vote.submission_form.pk })\n text = _(u'Das Votum für die Studie EK-Nr. %(ec_number)s vom %(meeting_date)s läuft in drei Wochen ab.\\n') % {\n 'url': url,\n 'ec_number': vote.submission_form.submission.get_ec_number_display(),\n 'meeting_date': vote.top.meeting.start.strftime('%d.%m.%Y'),\n }\n\n subject = _(u'Ablauf des Votums für die Studie EK-Nr. %s') % vote.submission_form.submission.get_ec_number_display()\n send_submission_message(vote.submission_form.submission, subject, text, recipients, username='root')\n \ndef send_vote_reminder_office(vote):\n recipients = User.objects.filter(username=settings.ECSMAIL['postmaster'])\n\n url = reverse('ecs.core.views.readonly_submission_form', kwargs={ 'submission_form_pk': vote.submission_form.pk })\n text = _(u'Das Votum für die Studie EK-Nr. %(ec_number)s vom %(meeting_date)s läuft in einer Woche ab.\\n') % {\n 'url': url,\n 'ec_number': vote.submission_form.submission.get_ec_number_display(),\n 'meeting_date': vote.top.meeting.start.strftime('%d.%m.%Y'),\n }\n\n subject = _(u'Ablauf des Votums für die Studie EK-Nr. %s') % vote.submission_form.submission.get_ec_number_display()\n send_submission_message(vote.submission_form.submission, subject, text, recipients, username='root')\n\n\n@periodic_task(run_every=timedelta(days=1))\ndef send_reminder_messages(today=None):\n if today is None:\n today = datetime.today().date()\n\n votes = Vote.objects.filter(Q(_currently_pending_for__isnull=False, _currently_pending_for__current_for_submission__isnull=False)|Q(_currently_published_for__isnull=False, _currently_published_for__current_for_submission__isnull=False), result='2')\n for vote in votes:\n try:\n until_meeting = Meeting.objects.filter(start__gt=vote.top.meeting.start).order_by('start')[2]\n except IndexError:\n continue\n \n if vote.submission_form.submission.thesis or not vote.submission_form.project_type_education_context is None:\n deadline = until_meeting.deadline_diplomathesis.date()\n else:\n deadline = until_meeting.deadline.date()\n\n if today < deadline:\n days_until_deadline = (deadline - today).days\n else:\n days_until_deadline = 0 - (today - deadline).days\n\n if days_until_deadline == 21:\n send_vote_reminder_submitter(vote)\n elif days_until_deadline == 7:\n send_vote_reminder_office(vote)\n elif days_until_deadline == -1:\n send_vote_expired(vote)\n else:\n continue\n\n\n","repo_name":"ethikkom/ecs","sub_path":"ecs/core/task_queue.py","file_name":"task_queue.py","file_ext":"py","file_size_in_byte":4668,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"29"} +{"seq_id":"34936703738","text":"from cloudify.manager import get_rest_client\nfrom cryptography.hazmat.primitives.serialization import (\n load_pem_private_key,\n load_pem_public_key,\n load_ssh_public_key,\n)\nfrom cryptography.hazmat.primitives.asymmetric.rsa import (\n RSAPrivateKey,\n RSAPrivateNumbers,\n RSAPublicKey,\n RSAPublicNumbers,\n rsa_crt_dmp1,\n rsa_crt_dmq1,\n rsa_crt_iqmp,\n rsa_recover_prime_factors,\n)\nfrom cryptography.hazmat.primitives.asymmetric import padding\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.exceptions import InvalidSignature\nfrom cloudify import ctx\nimport requests\nimport datetime\nimport calendar\nimport base64\nimport json\nfrom cloudify.exceptions import NonRecoverableError\nimport sys\nsys.tracebacklimit = -1\n\n\ndef base64url_encode(input):\n return base64.urlsafe_b64encode(input).replace(b\"=\", b\"\")\n\n\ndef from_base64url_uint(val):\n data = base64.base64url_decode(force_bytes(val))\n return int.from_bytes(data, byteorder=\"big\")\n\n\ndef bytes_from_int(val):\n remaining = val\n byte_length = 0\n\n while remaining != 0:\n remaining >>= 8\n byte_length += 1\n\n return val.to_bytes(byte_length, \"big\", signed=False)\n\n\ndef to_base64url_uint(val):\n if val < 0:\n raise ValueError(\"Must be a positive integer\")\n\n int_bytes = bytes_from_int(val)\n\n if len(int_bytes) == 0:\n int_bytes = b\"\\x00\"\n\n return base64url_encode(int_bytes)\n\n\ndef force_bytes(value):\n if isinstance(value, str):\n return value.encode(\"utf-8\")\n elif isinstance(value, bytes):\n return value\n else:\n raise TypeError(\"Expected a string value\")\n\n\nclass Algorithm:\n def compute_hash_digest(self, bytestr):\n hash_alg = getattr(self, \"hash_alg\", None)\n if hash_alg is None:\n raise NotImplementedError\n\n if (\n True\n and isinstance(hash_alg, type)\n and issubclass(hash_alg, hashes.HashAlgorithm)\n ):\n digest = hashes.Hash(hash_alg(), backend=default_backend())\n digest.update(bytestr)\n return bytes(digest.finalize())\n else:\n return bytes(hash_alg(bytestr).digest())\n\n def prepare_key(self, key):\n raise NotImplementedError\n\n def sign(self, msg, key):\n raise NotImplementedError\n\n def verify(self, msg, key, sig):\n raise NotImplementedError\n\n @staticmethod\n def to_jwk(key_obj):\n raise NotImplementedError\n\n @staticmethod\n def from_jwk(jwk):\n raise NotImplementedError\n\n\nclass RSAAlgorithm(Algorithm):\n SHA256 = hashes.SHA256\n\n def __init__(self, hash_alg):\n self.hash_alg = hash_alg\n\n def prepare_key(self, key):\n if isinstance(key, (RSAPrivateKey, RSAPublicKey)):\n return key\n\n if not isinstance(key, (bytes, str)):\n raise TypeError(\"Expecting a PEM-formatted key.\")\n\n key_bytes = force_bytes(key)\n\n try:\n if key_bytes.startswith(b\"ssh-rsa\"):\n return load_ssh_public_key(key_bytes)\n else:\n return load_pem_private_key(key_bytes, password=None)\n except ValueError:\n return load_pem_public_key(key_bytes)\n\n @staticmethod\n def to_jwk(key_obj):\n obj = None\n\n if getattr(key_obj, \"private_numbers\", None):\n # Private key\n numbers = key_obj.private_numbers()\n\n obj = {\n \"kty\": \"RSA\",\n \"key_ops\": [\"sign\"],\n \"n\": to_base64url_uint(numbers.public_numbers.n).decode(),\n \"e\": to_base64url_uint(numbers.public_numbers.e).decode(),\n \"d\": to_base64url_uint(numbers.d).decode(),\n \"p\": to_base64url_uint(numbers.p).decode(),\n \"q\": to_base64url_uint(numbers.q).decode(),\n \"dp\": to_base64url_uint(numbers.dmp1).decode(),\n \"dq\": to_base64url_uint(numbers.dmq1).decode(),\n \"qi\": to_base64url_uint(numbers.iqmp).decode(),\n }\n\n elif getattr(key_obj, \"verify\", None):\n # Public key\n numbers = key_obj.public_numbers()\n\n obj = {\n \"kty\": \"RSA\",\n \"key_ops\": [\"verify\"],\n \"n\": to_base64url_uint(numbers.n).decode(),\n \"e\": to_base64url_uint(numbers.e).decode(),\n }\n else:\n raise Exception(\"Not a public or private key\")\n\n return json.dumps(obj)\n\n @staticmethod\n def from_jwk(jwk):\n try:\n if isinstance(jwk, str):\n obj = json.loads(jwk)\n elif isinstance(jwk, dict):\n obj = jwk\n else:\n raise ValueError\n except ValueError:\n raise Exception(\"Key is not valid JSON\")\n\n if obj.get(\"kty\") != \"RSA\":\n raise Exception(\"Not an RSA key\")\n\n if \"d\" in obj and \"e\" in obj and \"n\" in obj:\n # Private key\n if \"oth\" in obj:\n raise Exception(\n \"Unsupported RSA private key: > 2 primes not supported\"\n )\n\n other_props = [\"p\", \"q\", \"dp\", \"dq\", \"qi\"]\n props_found = [prop in obj for prop in other_props]\n any_props_found = any(props_found)\n\n if any_props_found and not all(props_found):\n raise Exception(\n \"RSA key must include all parameters if any are present besides d\"\n )\n\n public_numbers = RSAPublicNumbers(\n from_base64url_uint(obj[\"e\"]),\n from_base64url_uint(obj[\"n\"]),\n )\n\n if any_props_found:\n numbers = RSAPrivateNumbers(\n d=from_base64url_uint(obj[\"d\"]),\n p=from_base64url_uint(obj[\"p\"]),\n q=from_base64url_uint(obj[\"q\"]),\n dmp1=from_base64url_uint(obj[\"dp\"]),\n dmq1=from_base64url_uint(obj[\"dq\"]),\n iqmp=from_base64url_uint(obj[\"qi\"]),\n public_numbers=public_numbers,\n )\n else:\n d = from_base64url_uint(obj[\"d\"])\n p, q = rsa_recover_prime_factors(\n public_numbers.n, d, public_numbers.e\n )\n\n numbers = RSAPrivateNumbers(\n d=d,\n p=p,\n q=q,\n dmp1=rsa_crt_dmp1(d, p),\n dmq1=rsa_crt_dmq1(d, q),\n iqmp=rsa_crt_iqmp(p, q),\n public_numbers=public_numbers,\n )\n\n return numbers.private_key()\n elif \"n\" in obj and \"e\" in obj:\n # Public key\n return RSAPublicNumbers(\n from_base64url_uint(obj[\"e\"]),\n from_base64url_uint(obj[\"n\"]),\n ).public_key()\n else:\n raise Exception(\"Not a public or private key\")\n\n def sign(self, msg, key):\n return key.sign(msg, padding.PKCS1v15(), self.hash_alg())\n\n def verify(self, msg, key, sig):\n try:\n key.verify(sig, msg, padding.PKCS1v15(), self.hash_alg())\n return True\n except InvalidSignature:\n return False\n\n\ndef get_bearer_token(jwt_token):\n url = \"https://www.googleapis.com/oauth2/v4/token\"\n data = {\n 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',\n 'assertion': jwt_token\n }\n ctx.logger.info('data {0}'.format(data))\n response = requests.post(url, data=data)\n return response.json().get('access_token', None)\n\n\ndef list_machine_types(token, project_id):\n url = \"https://compute.googleapis.com/compute/v1/projects/{project_id}/zones/us-west1-a/machineTypes\".format(\n project_id=project_id,\n )\n headers = {\n 'Authorization': 'Bearer {0}'.format(token),\n 'Content-Type': 'application/json'\n }\n response = requests.get(url, headers=headers)\n return response.status_code, response.json()\n\n\ndef validate_gcp():\n client = get_rest_client()\n gcp_credentials = client.secrets.get('gcp_credentials').get('value', None)\n\n if gcp_credentials is None:\n msg = \"Missing credentials for GCP cloud provider: gcp_credentials\"\n ctx.logger.error(msg)\n raise NonRecoverableError(msg)\n else:\n gcp_credentials_json = json.loads(gcp_credentials)\n\n issuer = subject = gcp_credentials_json.get('client_email', None)\n private_key = gcp_credentials_json.get('private_key', None)\n private_key_id = gcp_credentials_json.get('private_key_id', None)\n project_id = gcp_credentials_json.get('project_id', None)\n\n ctx.logger.info('issuer {0}, private_key {1}, private_key_id {2}, project_id {3}'.format(\n issuer, private_key, private_key_id, project_id\n ))\n\n if issuer is None or private_key is None or private_key_id is None or project_id is None:\n msg = \"Invalid credentials for GCP cloud provider, check your issuer, private key and project id\"\n ctx.logger.error(msg)\n raise NonRecoverableError(msg)\n else:\n\n now = datetime.datetime.utcnow()\n lifetime = datetime.timedelta(seconds=3600)\n expiry = now + lifetime\n iat = calendar.timegm(now.utctimetuple())\n exp = calendar.timegm(expiry.utctimetuple())\n aud = 'https://www.googleapis.com/oauth2/v4/token'\n scope = 'https://www.googleapis.com/auth/cloud-platform'\n\n segments = []\n\n payload = {\n \"iss\": issuer,\n \"sub\": subject,\n \"iat\": iat,\n \"exp\": exp,\n \"aud\": aud,\n \"scope\": scope,\n }\n\n json_payload = json.dumps(\n payload,\n separators=(\",\", \":\"),\n cls=None,\n ).encode(\"utf-8\")\n\n headers = {\n \"typ\": \"JWT\",\n \"alg\": \"RS256\",\n \"kid\": private_key_id\n }\n\n json_header = json.dumps(\n headers, separators=(\",\", \":\"), cls=None, sort_keys=True\n ).encode()\n\n segments.append(base64url_encode(json_header))\n msg_payload = base64url_encode(json_payload)\n segments.append(msg_payload)\n signing_input = b\".\".join(segments)\n alg_obj = RSAAlgorithm(RSAAlgorithm.SHA256)\n key = alg_obj.prepare_key(private_key)\n signature = alg_obj.sign(signing_input, key)\n segments.append(base64url_encode(signature))\n encoded_string = b\".\".join(segments)\n jwt_token = encoded_string.decode(\"utf-8\")\n\n ctx.logger.info('jwt_token {0}'.format(jwt_token))\n\n bearer_token = get_bearer_token(jwt_token)\n\n ctx.logger.info('bearer_token {0}'.format(bearer_token))\n\n status_code, response_content = list_machine_types(bearer_token, project_id)\n\n if status_code != 200:\n ctx.logger.error(\n \"Invalid GCP credentials : {}\".format(response_content))\n raise NonRecoverableError(\n \"Invalid GCP credentials : {}\".format(response_content))\n","repo_name":"cloudify-community/cloudify-catalog","sub_path":"tabs/other/secrets_validation/scripts/check_connection/gcp.py","file_name":"gcp.py","file_ext":"py","file_size_in_byte":11366,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"29"} +{"seq_id":"3904366169","text":"'''This module defines the overall page layout, and the content of static page elements\nsuch as the nav bar. When called, it will serve the dashboard on port 8080'''\n\nimport dash_core_components as dcc\nimport dash_daq as daq\nimport dash_html_components as html\nimport plotly.graph_objects as go\nimport waitress\nfrom dash.dependencies import Input, Output, State\nfrom dash.exceptions import PreventUpdate\n\n# pylint: disable=unused-import\n# Tokenizer import needed to unpickle the classifier (needs to be in __main__)\nfrom App import app\nfrom models.train_classifier import Tokenizer\nfrom Utilities import cat_names, cat_counts\nfrom Utilities import gen_jumbotron, create_plot_network, generate_word_cloud\n\n\n####################################################################################################\n# Page Header #\n####################################################################################################\n\n# URL Bar ##########################################################################################\n\n# Set up the element which allows the report to determine\n# which page the user is attempting to access.\nurl_bar_content = html.Div(\n [\n # Represents the URL bar, doesn't render anything\n dcc.Location(id='url', refresh=False)\n ]\n)\n\n\n# Page Header ######################################################################################\n\npage_header = html.Nav(\n [\n html.A(\n [\n html.Img(\n src='./assets/udacity_logo.png',\n style={'height': '48px', 'width': '48px'},\n className=\"d-inline-block mr-2 rounded align-top\"),\n html.P(\n 'Disaster Response Project',\n id='page-title',\n className='m-0 p-0 d-inline-block align-top')\n ],\n className='navbar-brand align-middle',\n style={'font-size': '32px'},\n href='/'\n ),\n html.A(\n html.Img(\n src='./assets/github_logo.png',\n style={'height': '48px', 'width': '48px'},\n className=\"d-inline-block mr-2\"\n ),\n className='align-middle my-0',\n href=\"https://github.com/rp13g10/\"\n )\n ],\n className='navbar navbar-dark bg-dark py-1 my-0'\n)\n\n\n\n####################################################################################################\n# Page Content #\n####################################################################################################\n\n# Headline text ####################################################################################\n\npage_title = html.Div(\n [\n html.H1(\n \"Disaster Response Project\",\n className=\"display-3 text-center w-100\"\n ),\n html.H2(\n \"Analyzing message data for disaster response\",\n className=\"text-muted text-center w-100\"\n )\n ],\n className='row pb-4'\n)\n\n\n# User input #######################################################################################\n\nmsg_control = html.Div(\n [\n html.Div(\n dcc.Input(\n id='msg-input',\n type='text',\n className='w-100 h-100 m-0 p-0'\n ),\n className='col-11 m-0 p-0'\n ),\n html.Div(\n dcc.Link(\n html.Button(\n 'Go',\n id='go-button',\n className='btn btn-default w-100 h-100',\n n_clicks=0\n ),\n id='go-button-link',\n className='w-100 h-100 m-0 p-0'\n ),\n className='col-1 m-0 p-0'\n )\n ],\n className='row p-0 m-0 h-100'\n)\n\nmsg_input = html.Div(\n html.Div(\n [\n html.Div(\n html.Div(\n 'Classify Message',\n className='input-group-text'\n ),\n className='input-group-prepend'\n ),\n html.Div(\n msg_control,\n className='form-control h-100 p-0'\n )\n ],\n className='input-group col-10 offset-1'\n ),\n className='row mb-3'\n)\n\n\n# Category display #################################################################################\n\ncat_display = html.Div(\n html.Div(\n dcc.Loading(\n html.Div(id='jumbotron'),\n ),\n className='col-10 offset-1'\n ),\n className='row mb-3'\n)\n\n\n# Charts ###########################################################################################\n\nchart_header = html.Div(\n [\n html.H1(\n \"Training Data Summary\",\n className=\"display-4 text-center w-100\"\n )\n ],\n className='row pb-4'\n)\n\nblank_figure = go.Figure(\n layout=go.Layout(\n showlegend=False,\n margin=dict(b=0, l=0, r=0, t=0),\n xaxis=dict(\n showgrid=False,\n zeroline=False,\n showticklabels=False\n ),\n yaxis=dict(\n showgrid=False,\n zeroline=False,\n showticklabels=False,\n scaleanchor=\"x\"\n ),\n autosize=True,\n height=None,\n width=None,\n plot_bgcolor='#f7f7f7'\n )\n)\n\n\n# Word Cloud ---------------------------------------------------------------------------------------\n\ncloud_desc = \"Select a category to view the words which most commonly appeared \\\nwithin it. The larger the word, the more common it was in the training dataset.\"\n\ncloud_controls = html.Div(\n [\n html.Div(\n \"Word Cloud\",\n className='card-header'\n ),\n html.Div(\n [\n html.P(\n cloud_desc,\n className='card-text'),\n ],\n className='card-body'\n ),\n html.Div(\n dcc.Dropdown(\n id='cloud-category',\n options=[\n {'label': x, 'value': x}\n for x in cat_names\n if cat_counts[x] > 1\n ],\n value=cat_names[0]\n ),\n className='card-footer text-center'\n )\n ],\n className='card'\n)\n\n\nword_cloud = html.Div(\n [\n html.Div(\n dcc.Loading(\n html.Img(\n style={'align-self': 'center'},\n className='img-fluid mx-auto rounded border border-light',\n id='word-cloud'\n )\n ),\n className='col-7 offset-1 text-center'\n ),\n html.Div(\n cloud_controls,\n className='col-3'\n )\n ],\n className='row mb-3'\n)\n\n\n# Network Graph ------------------------------------------------------------------------------------\n\nnetwork_desc = \"This network graph shows how frequently different categories appeared \\\ntogether in the same message. The closer together two categories are, the more frequently \\\nthey appeared together. For example, 'buildings' and 'earthquake' are commonly reported \\\ntogether.\"\n\n\nnetwork_controls = html.Div(\n [\n html.Div(\n \"Network Graph\",\n className='card-header'\n ),\n html.Div(\n [\n html.P(\n network_desc,\n className='card-text'),\n html.P(\n \"Activate the toggle below to enable an exciting 3D plot!\",\n className='card-text'\n )\n ],\n className='card-body'\n ),\n html.Div(\n [\n html.Div(\n [\n html.Div(\n # pylint: disable=not-callable\n # False positive error raised on BooleanSwitch\n daq.BooleanSwitch(\n id='network-dims',\n on=False,\n className='d-inline'\n ),\n className='col-6'\n ),\n html.Div(\n html.Button(\n 'Draw',\n id='network-update',\n className='btn btn-primary h-100 px-3 mx-1 d-inline',\n n_clicks=0\n ),\n className='col-6'\n )\n ],\n className='row'\n )\n ],\n className='card-footer text-center'\n )\n ],\n className='card'\n)\n\nnetwork_graph = html.Div(\n [\n html.Div(\n dcc.Loading(\n dcc.Graph(figure=blank_figure, id='network-graph'),\n ),\n className='col-7 offset-1'\n ),\n html.Div(\n network_controls,\n className='col-3'\n )\n ],\n className='row mb-3'\n)\n\n\n# Content Layout ###################################################################################\n\n# Set the order in which each element is displayed\npage_content = html.Div(\n [\n page_title,\n msg_input,\n cat_display,\n chart_header,\n word_cloud,\n network_graph\n ],\n id='page-content'\n)\n\n\n\n####################################################################################################\n# App Configuration #\n####################################################################################################\n\n# Page Initialization ##############################################################################\n\ndef serve_layout():\n '''Defines the macro-level page layout (nav bar, page content, etc)'''\n layout = html.Div(\n [\n url_bar_content,\n page_header,\n html.Div(\n page_content,\n className='container-fluid pb-5 pt-3'\n ),\n html.Div(className='row m-0 p-0 w-100', style={'height': '100px'})\n ],\n className='container-fluid p-0 m-0'\n )\n\n return layout\n\napp.layout = serve_layout\n\n\n# Callbacks ########################################################################################\n\n# pylint: disable=no-member, unused-argument\n@app.callback(\n [Output('msg-input', 'value'), Output('jumbotron', 'children')],\n [Input('go-button', 'n_clicks')],\n [State('msg-input', 'value')])\ndef display_input(btn_clicks, usr_input):\n '''Displays the input text, tagged with named entities and sentiment'''\n if not usr_input:\n return \"\", html.Div()\n else:\n jumbotron = gen_jumbotron(usr_input)\n return \"\", jumbotron\n\n@app.callback(\n Output('network-graph', 'figure'),\n [Input('network-update', 'n_clicks')],\n [State('network-dims', 'on')])\ndef update_network_graph(btn_clicks, excitement_flag):\n '''Generates a network graph which helps to visualize the categories which\n most frequently appear together in the training dataset'''\n\n if not btn_clicks:\n raise PreventUpdate\n n_dims = 3 if excitement_flag else 2\n figure = create_plot_network(n_dims)\n return figure\n\n@app.callback(\n Output('word-cloud', 'src'),\n [Input('cloud-category', 'value')])\ndef update_word_cloud(category):\n '''Generate a word cloud showing the most common words for a\n given category in the training dataset'''\n return generate_word_cloud(category)\n\n\n# Run Server #######################################################################################\n\nif __name__ == '__main__':\n server = app.server\n waitress.serve(server)\n","repo_name":"rp13g10/udacity-disaster-response","sub_path":"app/Index.py","file_name":"Index.py","file_ext":"py","file_size_in_byte":11992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"24413913391","text":"# -*- coding: utf-8 -*-\nimport datetime\n\nfrom req_crawler.logger import logger\nfrom req_crawler.utils import log_process_time\n\n\nclass Query(object):\n \"\"\"\n Query for DB actions\n \"\"\"\n def __init__(self, connect_db, settings):\n self.conn = connect_db.connection\n self.cursor = connect_db.connection.cursor()\n self._tables = settings.DB_TABLES\n self._db_rows = settings.DB_ROWS\n self._db_settings = settings.DB_SETTINGS\n self.cursor.execute('use {0}'.format(self._db_settings.get('db')))\n self.value_str = \"('python', '{0}', 'Wantedly', '{1}', '{1}')\"\n\n def create_init_table(self) -> None:\n \"\"\"\n If there are not tables, create table\n \"\"\"\n is_exist_table = self.cursor.execute('show tables')\n\n if is_exist_table:\n return None\n\n for table in self._tables:\n try:\n cols = self._db_rows.get(table)\n cols_str = ','.join(cols)\n sql = \"CREATE TABLE {0}({1});\".format(table, cols_str)\n self.cursor.execute(sql)\n except Exception as e:\n logger.exception(e)\n self.close()\n\n def create_cols(self, table_name: str) -> str:\n \"\"\"\n Create string for INSERT query\n \"\"\"\n table_rows = self._db_rows[table_name]\n return ','.join([s.split(' ')[0] for s in table_rows if s[:2] != 'id'])\n\n @log_process_time\n def select(self) -> set:\n \"\"\"\n Get company names from tables for checking diff\n \"\"\"\n for table in self._tables:\n sql = \"SELECT * FROM {0};\".format(table)\n self.cursor.execute(sql)\n\n return set(c['company_name'] for c in self.cursor.fetchall())\n\n @log_process_time\n def insert(self, company_list: set, commit=False) -> None:\n \"\"\"\n Execute INSERT query\n \"\"\"\n dt = datetime.datetime.now()\n values = ''\n for i, company in enumerate(company_list):\n value_str = self.value_str.format(company, str(dt).split('.')[0])\n if i == len(company_list) - 1:\n values += value_str + ';'\n else:\n values += value_str + ','\n\n for table in self._tables:\n cols = self.create_cols(table)\n sql = \"INSERT INTO {0} ({1}) VALUES {2}\".format(table, cols, values)\n logger.info(sql)\n logger.info(self.cursor.execute(sql))\n\n if commit:\n self.conn.commit()\n\n def close(self) -> None:\n \"\"\"\n Close connection, when it happens exception\n \"\"\"\n try:\n self.cursor.close()\n self.conn.close()\n except Exception as e:\n logger.info(e)\n exit()\n","repo_name":"tarunama/req-crawler","sub_path":"req_crawler/db/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"72910071438","text":"import argparse\nimport json\nimport os\nimport sys\n\nfrom depfile import DepFile\n\nfrom typing import Dict, Optional\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\n 'Create a flat list of files included in the images. This is used to inform infrastructure what files to upload'\n )\n parser.add_argument(\n '--product-config',\n type=argparse.FileType('r'),\n nargs='+',\n required=True)\n parser.add_argument(\n \"--assembly-input-bundles\", type=argparse.FileType('r'), required=True)\n parser.add_argument(\n '--images-config',\n type=argparse.FileType('r'),\n nargs='+',\n required=True)\n parser.add_argument(\n '--partitions-config', type=argparse.FileType('r'), required=True)\n parser.add_argument('--sources', type=str, nargs='*')\n parser.add_argument('--output', type=argparse.FileType('w'), required=True)\n parser.add_argument('--depfile', type=argparse.FileType('w'), required=True)\n args = parser.parse_args()\n\n # The files to put in the output with source mapped to destination.\n file_mapping = {}\n\n # Add a file or directory path to one of the lists, relative to CWD.\n # The destination is the path when placed inside \"built/artifacts\".\n # If the path is prefixed with ../../, the prefix is removed.\n def add_source(source):\n # Absolute paths are not portable out-of-tree, therefore if a file is\n # using an absolute path we throw an error.\n if os.path.isabs(source):\n raise Exception(\"Absolute paths are not allowed\", source)\n\n source = os.path.relpath(source, os.getcwd())\n prefix = \"../../\"\n if source.startswith(prefix):\n destination = source[len(prefix):]\n else:\n destination = os.path.join(\"built/artifacts\", source)\n file_mapping[source] = destination\n\n # Add a package and all the included blobs.\n manifests_for_depfile = []\n\n def add_package(entry: Dict):\n manifest = entry[\"manifest\"]\n manifests_for_depfile.append(manifest)\n add_source(manifest)\n with open(manifest, 'r') as f:\n manifest = json.load(f)\n for blob in manifest.get(\"blobs\", []):\n add_source(blob[\"source_path\"])\n for config in entry.get(\"config_data\", []):\n add_source(config[\"source\"])\n\n # Add the product configs.\n def add_product_config(product_config):\n add_source(product_config.name)\n product_config = json.load(product_config)\n if \"product\" in product_config:\n product = product_config[\"product\"]\n if \"packages\" in product:\n packages = product[\"packages\"]\n for package in packages.get(\"base\", []):\n add_package(package)\n for package in packages.get(\"cache\", []):\n add_package(package)\n\n for product_config in args.product_config:\n add_product_config(product_config)\n\n # Add the assembly input bundles\n assembly_input_bundles = json.load(args.assembly_input_bundles)\n for bundle_entry in assembly_input_bundles:\n dirname, basename = os.path.split(bundle_entry[\"path\"])\n if basename.endswith(\".tgz\"):\n basename = basename[:-4]\n add_source(os.path.join(dirname, basename))\n\n # Add the images configs.\n def add_images_config(images_config):\n add_source(images_config.name)\n images = json.load(images_config).get(\"images\", [])\n for image in images:\n if image[\"type\"] == \"vbmeta\":\n add_source(image[\"key\"])\n add_source(image[\"key_metadata\"])\n if \"additional_descriptor_files\" in image:\n for descriptor in image[\"additional_descriptor_files\"]:\n add_source(descriptor)\n elif image[\"type\"] == \"zbi\":\n if \"postprocessing_script\" in image:\n add_source(image[\"postprocessing_script\"][\"path\"])\n\n for images_config in args.images_config:\n add_images_config(images_config)\n\n # Add the partitions config.\n add_source(args.partitions_config.name)\n partitions_config = json.load(args.partitions_config)\n for cred in partitions_config.get(\"unlock_credentials\", []):\n add_source(cred)\n for part in partitions_config.get(\"bootloader_partitions\", []):\n add_source(part[\"image\"])\n for part in partitions_config.get(\"bootstrap_partitions\", []):\n add_source(part[\"image\"])\n\n # Add any additional sources to copy.\n for source in args.sources:\n add_source(source)\n\n # Convert the map into a list of maps.\n files = []\n for src, dest in file_mapping.items():\n files.append({\n \"source\": src,\n \"destination\": dest,\n })\n\n # Write a depfile with any opened package manifests.\n if manifests_for_depfile:\n depfile = DepFile(args.output.name)\n depfile.update(manifests_for_depfile)\n depfile.write_to(args.depfile)\n\n # Write the list.\n json.dump(files, args.output, indent=2)\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","repo_name":"gnoliyil/fuchsia","sub_path":"build/assembly/scripts/generated_assembly_inputs.py","file_name":"generated_assembly_inputs.py","file_ext":"py","file_size_in_byte":5186,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"29"} +{"seq_id":"72039362639","text":"import logging\nfrom os.path import basename\n\n\ndef get_logger(file_name, level=logging.INFO):\n logger = logging.getLogger(basename(file_name))\n logger.setLevel(logging.DEBUG)\n\n formatter = logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n console_handler = logging.StreamHandler()\n console_handler.setLevel(level)\n console_handler.setFormatter(formatter)\n file_handler = logging.FileHandler('py_logs.log')\n file_handler.setLevel(logging.DEBUG)\n file_handler.setFormatter(formatter)\n logger.addHandler(console_handler)\n logger.addHandler(file_handler)\n return logger\n\n","repo_name":"massih-m/websocket-service","sub_path":"py_scripts/websocket_service/my_logging.py","file_name":"my_logging.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"11466101515","text":"import sys\nfrom rtd266x.rtd266x import RTD266x\nfrom argparse import ArgumentParser\nfrom argparse import RawTextHelpFormatter\n\ndef save_file(filename, data):\n\tfile = open(filename, \"wb\")\n\tfile.write(bytearray(data))\n\tfile.close()\n\t\ndef load_file(filename):\n\tfile = open(filename, \"rb\")\n\tdata = file.read()\n\tfile.close()\n\t\n\treturn list(bytearray(data))\n\ndef cmp(a, b):\n\treturn (a > b) - (a < b) \n\nparser = ArgumentParser(description = \"A tool to read and write the flash of an RTD266x display driver IC via I2C\", epilog='''Examples:\n\nRead 512 KB to file out.bin:\nrtd266x_flash -r 524288 -f out.bin\n\nRead 1024 bytes to file out.bin using I2C interface 2:\nrtd266x_flash -i 2 -r 1024 -f out.bin\n\nWrite all bytes from file in.bin:\nrtd266x_flash -w -f in.bin\n\nWrite differences between base file base.bin and file with modifications mod.bin:\nrtd266x_flash -d base.bin -f mod.bin\n\nWrite all bytes from file in.bin, starting at offset 2048:\nrtd266x_flash -w -o 2048 -f in.bin\n\nErase the entire chip:\nrtd266x_flash -c''', formatter_class = RawTextHelpFormatter)\n\nparser.add_argument(\"-f\", \"--file\", help = \"File name\", metavar = \"file\", required = False)\nparser.add_argument(\"-i\", \"--interface\", help = \"Interface number (default = 2)\", metavar = \"x\", type = int, default = 2)\nparser.add_argument(\"-r\", \"--read\", help = \"Reads x bytes from the device to a file\", metavar = \"x\", type = int)\nparser.add_argument(\"-w\", \"--write\", help = \"Writes all bytes from a file to the device\", action = \"store_true\")\nparser.add_argument(\"-d\", \"--write_diff\", help = \"Writes all sectors from file which are different from file_base\", metavar = \"file_base\")\nparser.add_argument(\"-o\", \"--offset\", help = \"Read/write offset of x bytes\", metavar = \"x\", type = int, default = 0)\nparser.add_argument(\"-c\", \"--chip_erase\", help = \"Erases the entire chip\", action = \"store_true\")\nparser.add_argument(\"-s\", \"--no_reset\", help = \"Don't reset the device\", action = \"store_true\")\n\nargs = parser.parse_args()\n\nif ((args.read or args.write or args.write_diff) and args.file == None):\n print(\"File parameter is missing!\")\n parser.print_help()\n sys.exit(1)\n\nif (args.read == None and args.write_diff == None and args.write == False and args.chip_erase == False):\n\tparser.print_help()\n\tsys.exit(1)\n\nrtd = RTD266x(args.interface, 0x4A)\n\nif (not args.no_reset):\n\tprint(\"Resetting device...\")\n\trtd.reset()\n\nprint(\"Entering ISP mode...\")\n\t\nif (not rtd.enter_isp_mode()):\n\tprint(\"Error: cannot enter ISP mode!\")\n\tsys.exit(2)\n\nprint(\"Reading chip data...\")\n\t\njedec_id = rtd.read_jedec_id()\nprint(\"JEDEC ID: \" + hex(jedec_id))\n\nif (not rtd.setup_chip_commands(jedec_id)):\n\tprint(\"Cannot setup chip commands! The flash chip id is unknown.\")\n\tsys.exit(3)\n\nprint(\"ID: \" + hex(rtd.read_id()))\nprint(\"Status: \" + hex(rtd.read_status()))\n\t\nprint(\"Clearing lock bits...\")\nrtd.write_status(0)\n\nprint(\"Status: \" + hex(rtd.read_status()))\n\nif (args.chip_erase):\n\tprint(\"Erasing chip...\")\n\trtd.erase_chip()\n\nif (args.read != None):\n\tprint(\"Reading \" + str(args.read) + \" bytes from offset \" + hex(args.offset) + \" to file \" + args.file + \"...\")\n\t\n\tbytes = []\n\tblock_size = 1024\n\t\n\tfor i in range(args.offset, args.offset + args.read, block_size):\n\t\tif (i + block_size > args.offset + args.read):\n\t\t\tread_len = args.offset + args.read - i\n\t\telse:\n\t\t\tread_len = block_size\n\t\n\t\tbytes += rtd.read_flash(i, read_len)\n\t\n\t\tif (bytes == None):\n\t\t\tprint(\"Error: cannot read flash!\")\n\t\t\tsys.exit(4)\n\t\t\n\tsave_file(args.file, bytes)\n\nif (args.write):\n\tprint(\"Writing data from file \" + args.file + \" to offset \" + str(args.offset) + \"...\")\n\tdata = load_file(args.file)\n\t\n\tif (not rtd.program_flash(args.offset, data)):\n\t\tprint(\"Error: cannot program flash!\")\n\nif (args.write_diff != None):\n\tprint(\"Writing sectors from file \" + args.file + \" which differ from sectors of file \" + args.write_diff + \"...\")\n\tdata = load_file(args.file)\n\tdata_base = load_file(args.write_diff)\n\t\n\tif (len(data) != len(data_base)):\n\t\tprint(\"Error: file lengths are different but must be equal!\")\n\t\tsys.exit(5)\n\t\t\n\tfor i in range(0, len(data), rtd.SECTOR_SIZE):\n\t\tsector = data[i:i + rtd.SECTOR_SIZE]\n\t\tsector_base = data_base[i:i + rtd.SECTOR_SIZE]\n\t\t\n\t\tif (cmp(sector, sector_base) != 0):\n\t\t\trtd.program_flash(i, sector)\n\t\t\t\nif (not args.no_reset):\n\tprint(\"Resetting device...\")\n\trtd.reset()","repo_name":"floppes/RTD266xFlash","sub_path":"RTD266xPy/rtd266x_flash.py","file_name":"rtd266x_flash.py","file_ext":"py","file_size_in_byte":4309,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"29"} +{"seq_id":"70431156557","text":"from django.urls import path\r\nfrom .views import home, search, detail, RecipeCreate, comentar\r\n\r\nurlpatterns = [\r\n path(\"\", home, name=\"home\"),\r\n path('cadastrar/', RecipeCreate.as_view(), name='cadastros'),\r\n path(\"search\", search, name=\"search\"),\r\n path(\"\", detail, name=\"detail\"),\r\n path('comentar/', comentar.as_view(), name='comentar'),\r\n]","repo_name":"LucasRamosLobo/docker-guiasul","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"23882936908","text":"with open('input.txt') as f:\n lines = map(lambda x: [x.replace(\"\\n\",\"\").split(\" \")[0], int(x.replace(\"\\n\",\"\").split(\" \")[1])], f.readlines())\n\ndepth = 0\nhorizontal = 0\n\nfor move in lines:\n if move[0] == 'forward':\n horizontal += move[1]\n elif move[0] == 'down':\n depth += move[1]\n elif move[0] == 'up':\n depth -= move[1]\nprint(\"horizontal: \" + str(horizontal) + \" depth: \" + str(depth))\n","repo_name":"petrosDemetrakopoulos/advent-of-code-2021","sub_path":"2/a/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"14495259236","text":"from typing import List\nfrom dtos.classe_dto import ClasseDTO\nfrom schemas.classes import Classes\nfrom rich import print\n\n\nclass ClasseService:\n def add_classe(self, classe: ClasseDTO):\n print(\"On arrive ici c'est sure\")\n co = Classes(**classe.model_dump()).save()\n print(f\"Add one classe {co}\")\n return co\n\n def getClasses(self):\n classes: List = []\n try:\n val = Classes.objects.scalar()\n print(f\"Leka: {val}\")\n for cl in val:\n classes.append(cl.__dict__())\n return classes\n except BaseException as e:\n print(e)\n\n def getById(self, id: str):\n return Classes.objects.get(id=id)\n","repo_name":"jeydi243/totory","sub_path":"services/classe_service.py","file_name":"classe_service.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"3649870733","text":"# -*- coding: utf-8 -*-\n\nfrom .models import *\nfrom configparser import ConfigParser\n#from config import config\nimport os,sys\nimport numpy as np\nimport pandas as pd\nfrom pprint import pprint\nfrom glob import glob\nimport requests,json\nfrom openpyxl import load_workbook\nfrom openpyxl import Workbook\n\n\n\n\ndef getFalabellaClientePreview(straPorta,straCliente,straFile):\n\tDataPortafolioarchivosStraus.objects.filter(id=straFile).update(archivos_portafolio=straPorta)\n\tinfoArchivo = DataPortafolioarchivosStraus.objects.filter(id=straFile).last()\n\n\tarchivo = '/home/pentaho/strauss/cargues/static/upload/%s'%(infoArchivo.archivos_archivo)\n\tdf = pd.read_excel(archivo)\n\tdf = df[['num_documento','NOMBRE', 'Tipo_documento','fecha_apertura','fechaasigna','saldo_total','cupo','dias_mora','Rango','habito_pago','cuenta','TlfCelular','teldom1','TelefCom1','Calle_Corresp','Depto_Correspondencia','Ciudad_Correspondencia','barrio','Calle_Com','Depto_Com','Ciudad_Com','Mail']]\n\tfor row in df.head(1).itertuples(index=False):\n\t\tlista1 = row\n\tfor row in df.head(2).itertuples(index=False):\n\t\tlista2 = row\n\tfor row in df.head(3).itertuples(index=False):\n\t\tlista = row\n\treturn lista1,lista2,lista\n\n\n\n\ndef procesadoFinalFalabella(stra_id,stra_file,stra_portafolio,straUsuario,strCliente,straEmpresas):\n\n\tarchivo = '/home/pentaho/strauss/cargues/static/upload/%s'%(stra_file)\n\tdf = pd.read_excel(archivo)\n\tdf = df[['num_documento','NOMBRE', 'Tipo_documento','fecha_apertura','fechaasigna','saldo_total','cupo','dias_mora','Rango','habito_pago','cuenta','TlfCelular','teldom1','TelefCom1','Calle_Corresp','Depto_Correspondencia','Ciudad_Correspondencia','barrio','Calle_Com','Depto_Com','Ciudad_Com','Mail']]\n\tdf = df.head(20)\n\n\tcant_columns = len(df.columns)\n\n\tcant_cc = df['num_documento'].count()\n\n\tcolumns_obli = list(df.columns.values)\n\n\tsum_saldo_capital = round(df['saldo_total'].sum(),2)\n\n\t#df.head(3)\n\n\tdf_personas = df.copy()\n\tdf_personas.drop_duplicates(subset=[\"num_documento\",\"Tipo_documento\"], keep='first', inplace=True)\n\ttipoDoc = {1:\"CC\", 3:\"CE\"}\n\tdf_personas[\"Tipo_documento\"]=df_personas[\"Tipo_documento\"].map(tipoDoc)\n\t#df_personas.head()\n\tdf_personas.rename(columns={\"num_documento\":\"persona_identificacion\",\n \"NOMBRE\":\"persona_nombre\",\n \"Tipo_documento\":\"persona_tipoidentificacion\"},inplace=True)\n\t#df_personas.head()\n\n\n\tdef insertPersona(row):\n\t\tif DataPersona.objects.filter(persona_identificacion=row['persona_identificacion']).exists():\n\t\t\trow['persona_id'] = DataPersona.objects.filter(persona_identificacion=row['persona_identificacion']).last()\n\t\t\trow['persona_id'] = row['persona_id']\n\t\telse:\n\t\t\trow['persona_id'] = DataPersona.objects.create(\n\t\t\t\tpersona_identificacion = row['persona_identificacion'],\n\t\t\t\tpersona_nombre = row['persona_nombre'],\n\t\t\t\tpersona_tipoidentificacion = row['persona_tipoidentificacion']\n\t\t\t)\n\t\t\tpass\n\t\treturn row\n\n\tdf_person = pd.DataFrame()\n\tfor index, row in df_personas.iterrows():\n\t df_person = df_person.append(insertPersona(row))\n\tdf_personas = df_person\n\t#df_personas.head(3)\n\n\t\n\tdef insertobligaciones(row):\n\t\tDataObligacion.objects.create(\n\t\t\tobligacionpersona =DataPersona.objects.get(id=row['persona_id'].id), \n\t\t\tobligacionportafolio =DataPortafolio.objects.get(id=stra_portafolio.id),\n\t\t\tobligacionestado_obligacion =DataEstadoobligacion.objects.get(id=1),\n\t\t\tobligacionsaldo_capital =row['saldototal'],\n\t\t\tobligacionseguro =0,\n\t\t\tobligacioncomision =0,\n\t\t\tobligacionsaldo_interes_corriente =row['saldointerescorriente'],\n\t\t\tobligacionsaldo_interes_mora =row['saldointeresmora'],\n\t\t\tobligacionsaldo_total =row['saldototal'],\n\t\t\tobligaciontipo_obligacion =row['tipoobligacion'],\n\t\t\tobligacionfecha_creacion_obligacion =row['fechacreacionobligacion'],\n\t\t\tobligacionfecha_vencimiento_obligacion =row['fecha_vencimientoobligacion'],\n\t\t\tvariable1 =row['variable1'],\n\t\t variable1_descripcion =row['variable1_descripcion'],\n\t\t variable2 =row['variable2'],\n\t\t variable2_descripcion =row['variable2_descripcion'],\n\t\t variable3 =row['variable3'],\n\t\t variable3_descripcion =row['variable3_descripcion'],\n\t\t variable4 =row['variable4'],\n\t\t variable4_descripcion =row['variable4_descripcion'],\n\t\t obligacionproducto =row['cuenta'],\n\t\t obligaciontipo_prducto =row['tipo_producto'],\n\t\t)\n\t\treturn row\n\n\n\tdf_obligaciones = df[['num_documento','fecha_apertura','fechaasigna','saldo_total','cupo','dias_mora','Rango','habito_pago','cuenta']].copy()\n\tdf_obligaciones['persona_id'] = df_obligaciones['num_documento'].map(df_personas.set_index('persona_identificacion')['persona_id'])\n\tdf_obligaciones['saldointerescorriente'] = 0\n\tdf_obligaciones['saldointeresmora'] = 0\n\tdf_obligaciones['tipoobligacion'] = 'Administrativa'\n\tdf_obligaciones['tipo_producto'] = 'Tarjeta Credito'\n\tdf_obligaciones['variable1_descripcion'] = 'cupo tarjeta credito'\n\tdf_obligaciones['variable2_descripcion'] = 'dias de mora'\n\tdf_obligaciones['variable3_descripcion'] = 'etapa de mora'\n\tdf_obligaciones['variable4_descripcion'] = 'frecuencia de pago'\n\tdf_obligaciones = df_obligaciones.drop(['num_documento'],axis=1)\n\tdf_obligaciones = df_obligaciones.rename(columns={'fecha_apertura':'fechacreacionobligacion','fechaasigna':'fecha_vencimientoobligacion','saldo_total':'saldototal'})\n\tdf_obligaciones = df_obligaciones.rename(columns={'cupo':'variable1','dias_mora':'variable2','Rango':'variable3','habito_pago':'variable4'})\n\tdf_obligaciones['fechacreacionobligacion'] = df_obligaciones['fechacreacionobligacion'].apply(lambda x: str(x)[0:4]+\"-\"+str(x)[4:6]+\"-\"+str(x)[6:])\n\t#df_obligaciones.head()\n\n\n\tdf_obligacion = pd.DataFrame()\n\tfor index, row in df_obligaciones.iterrows():\n\t\tdf_obligacion = df_obligacion.append(insertobligaciones(row))\n\tdf_obligaciones = df_obligacion\n\tdf_obligaciones.head()\n\n\n\t# Demograficos\n\n\t# Telefonos\n\n\tdef inserttelefonos(row):\n\t\ttmp = int(float(row['numero']))\n\t\tif ( (len(str(tmp))==10) | (len(str(tmp))=='10') ):\n\t\t\ttip = 'Celular'\n\t\telif ( (len(str(tmp))==7) | (len(str(tmp))=='7') ):\n\t\t\ttip = 'Fijo'\n\t\telse:\n\t\t\ttip = 'No Valido'\n\t\t\tpass\n\t\tDataTelefonos.objects.create(\n\t\t\ttelefono_numero =tmp,\n\t\t\ttelefono_persona =DataPersona.objects.get(id=row['persona_id'].id),\n\t\t\ttelefono_tipo =tip\n\t\t)\n\t\treturn row\n\n\n\tdf_telefonos = df[['num_documento','TlfCelular','teldom1','TelefCom1']].copy()\n\tdf_telefonos['persona_id'] = df_telefonos['num_documento'].map(df_personas.set_index('persona_identificacion')['persona_id'])\n\tdf_telefonos = df_telefonos.drop(['num_documento'],axis=1)\n\tdf_telefonos = df_telefonos.melt(id_vars=['persona_id'])\n\tdf_telefonos = df_telefonos.rename(columns={'value':'numero'})\n\tdf_telefonos = df_telefonos.drop(['variable'],axis=1)\n\t# df_telefonos = df_telefonos.sort_values('persona_id')\n\n\tdf_telefono = pd.DataFrame()\n\tfor index, row in df_telefonos.iterrows():\n\t\tdf_telefono = df_telefono.append(inserttelefonos(row))\n\tdf_telefonos = df_telefono\n\t#df_telefonos.head()\n\n\n\t# Ubicación Personal\n\n\tdef insertubicaciones(row):\n\t\tDataUbicacion.objects.create(\n\t\t\tubicacion_direccion =row['Calle_Corresp'],\n\t\t\tubicacion_pais =row['pais'],\n\t\t\tubicacion_departamento =row['Depto_Correspondencia'],\n\t\t\tubicacion_ciudad =row['Ciudad_Correspondencia'],\n\t\t\tubicacion_barrio =row['barrio'],\n\t\t\tubicacion_persona =DataPersona.objects.get(id=row['persona_id'].id)\n\t\t)\n\t\treturn row\n\n\n\tdf_ubicaciones = df[['num_documento','Calle_Corresp','Depto_Correspondencia','Ciudad_Correspondencia','barrio']].copy()\n\tdf_ubicaciones['persona_id'] = df_ubicaciones['num_documento'].map(df_personas.set_index('persona_identificacion')['persona_id'])\n\tdf_ubicaciones['pais'] = 'Colombia'\n\tdf_ubicaciones = df_ubicaciones.drop(['num_documento'],axis=1)\n\t#df_ubicaciones.head()\n\n\n\n\tdf_ubicacion = pd.DataFrame()\n\tfor index, row in df_ubicaciones.iterrows():\n\t\tdf_ubicacion = df_ubicacion.append(insertubicaciones(row))\n\tdf_ubicaciones = df_ubicacion\n\t#df_ubicaciones.head()\n\n\n\t# Ubicacion Empresa\n\n\tdef insertubicaciones_empresas(row):\n\t\tDataUbicacionEmpresa.objects.create(\n\t\t\tempresa_direccion=row['Calle_Com'],\n\t\t\tempresa_pais=row['pais'],\n\t\t\tempresa_departamento=row['Depto_Com'],\n\t\t\tempresa_ciudad=row['Ciudad_Com'],\n\t\t\tempresa_persona=DataPersona.objects.get(id=row['persona_id'].id),\n\t\t)\n\t\treturn row\n\n\n\tdf_ubicaciones_empresas = df[['num_documento','Calle_Com','Depto_Com','Ciudad_Com']].copy()\n\tdf_ubicaciones_empresas['persona_id'] = df_ubicaciones_empresas['num_documento'].map(df_personas.set_index('persona_identificacion')['persona_id'])\n\tdf_ubicaciones_empresas['pais'] = 'Colombia'\n\tdf_ubicaciones_empresas = df_ubicaciones_empresas.drop(['num_documento'],axis=1)\n\t#df_ubicaciones_empresas.head()\n\n\n\n\tdf_ubicacion_empresa = pd.DataFrame()\n\tfor index, row in df_ubicaciones_empresas.iterrows():\n\t df_ubicacion_empresa = df_ubicacion_empresa.append(insertubicaciones_empresas(row))\n\tdf_ubicaciones_empresas = df_ubicacion_empresa\n\t#df_ubicaciones_empresas.head()\n\n\n\t# Email\n\n\n\tdef insertcorreoelectronico(row):\n\t\tDataCorreoelectronico.objects.create(\n\t\t\tcorreoelectronico_correo = row['Mail'],\n\t\t\tcorreoelectronico_persona = DataPersona.objects.get(id=row['persona_id'].id)\n\t\t)\n\t\treturn row\n\n\n\tdf_correoelectronico = df[['num_documento','Mail']].copy()\n\tdf_correoelectronico['persona_id'] = df_correoelectronico['num_documento'].map(df_personas.set_index('persona_identificacion')['persona_id'])\n\tdf_correoelectronico['pais'] = 'Colombia'\n\tdf_correoelectronico = df_correoelectronico.drop(['num_documento'],axis=1)\n\t#df_correoelectronico.head()\n\n\n\tdf_correo = pd.DataFrame()\n\tfor index, row in df_correoelectronico.iterrows():\n\t df_correo = df_correo.append(insertcorreoelectronico(row))\n\tdf_correoelectronico = df_correo\n\t#df_correoelectronico.head()\n\n\n\t# print('Personas Insertadas'+' '+str(len(df_person)))\n\t# print('Obligaciones Insertadas'+' '+str(len(df_obligacion)))\n\t# print('Telefonos Insertadas'+' '+str(len(df_telefono)))\n\t# print('Email Insertadas'+' '+str(len(df_correo)))\n\t# print('Ubicacion Insertadas'+' '+str(len(df_ubicacion)))\n\t# print('UbicacionEmpresa Insertadas'+' '+str(len(df_ubicacion_empresa)))\n\n\tresultados = dict(\n\t\t\t\t\tpersonas = len(df_person),\n\t\t\t\t\tobligaciones = len(df_obligacion),\n\t\t\t\t\ttelefonos = len(df_telefono),\n\t\t\t\t\tcorreos = len(df_correo),\n\t\t\t\t\ttokens = 0\n\t\t\t\t)\n\treturn resultados\n\n","repo_name":"plasticleader/plasticDjango","sub_path":"app/cargueArchivos/falabellaOld.py","file_name":"falabellaOld.py","file_ext":"py","file_size_in_byte":10926,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"34778157993","text":"import math\nimport argparse\n\n\ndef sigmoid(x):\n t1 = 1 / (1+ math.exp (-float(x)))\n t2 = 1 - t1\n return t1, t2\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--value\",\n )\n \"\"\"\n parser.add_argument(\n '--resolution', default=1024\n )\n \"\"\"\n hyperparams = parser.parse_args()\n\n x = hyperparams.value\n #resolution = hyperparams.resolution\n \n #x=0\n t1 , t2 = sigmoid(x)\n print(f'Sigmoid activation for {x} to be part of one class is {t1}')\n print(f'Sigmoid activation for {x} to be part of onother class is {t2}')\n\n\n\n \n \n","repo_name":"kaushikdasroy/nn_code","sub_path":"sigmoid.py","file_name":"sigmoid.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"29"} +{"seq_id":"31975062158","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport implicit_maml.utils as utils\nimport random\nimport time as timer\nimport pickle\nimport argparse\nimport pathlib\n\nfrom tqdm import tqdm\nfrom implicit_maml.dataset import OmniglotTask, OmniglotFewShotDataset\nfrom implicit_maml.learner_model import Learner\nfrom implicit_maml.learner_model import make_fc_network, make_conv_network\nfrom implicit_maml.utils import DataLog\n\nimport matplotlib.pyplot as plt\n\nnp.random.seed(123)\ntorch.manual_seed(123)\nrandom.seed(123)\nlogger = DataLog()\n\n# There are 1623 characters\ntrain_val_permutation = list(range(1623))\nrandom.shuffle(train_val_permutation)\n\n# ===================\n# hyperparameters\n# ===================\nparser = argparse.ArgumentParser(description='Implicit MAML on Omniglot dataset')\nparser.add_argument('--data_dir', type=str, default='/home/aravind/data/omniglot-py/',\n help='location of the dataset')\nparser.add_argument('--N_way', type=int, default=5, help='number of classes for few shot learning tasks')\nparser.add_argument('--K_shot', type=int, default=1, help='number of instances for few shot learning tasks')\nparser.add_argument('--inner_lr', type=float, default=1e-2, help='inner loop learning rate')\nparser.add_argument('--outer_lr', type=float, default=1e-2, help='outer loop learning rate')\nparser.add_argument('--n_steps', type=int, default=16, help='number of steps in inner loop')\nparser.add_argument('--meta_steps', type=int, default=1000, help='number of meta steps')\nparser.add_argument('--task_mb_size', type=int, default=16)\nparser.add_argument('--lam', type=float, default=1.0, help='regularization in inner steps')\nparser.add_argument('--cg_steps', type=int, default=5)\nparser.add_argument('--cg_damping', type=float, default=1.0)\nparser.add_argument('--use_gpu', type=bool, default=True)\nparser.add_argument('--num_tasks', type=int, default=20000)\nparser.add_argument('--save_dir', type=str, default='/tmp')\nparser.add_argument('--lam_lr', type=float, default=0.0)\nparser.add_argument('--lam_min', type=float, default=0.0)\nparser.add_argument('--scalar_lam', type=bool, default=True, help='keep regularization as a scalar or diagonal matrix (vector)')\nparser.add_argument('--taylor_approx', type=bool, default=False, help='Use Neumann approximation for (I+eps*A)^-1')\nparser.add_argument('--inner_alg', type=str, default='gradient', help='gradient or sqp for inner solve')\nparser.add_argument('--load_agent', type=str, default=None)\nparser.add_argument('--load_tasks', type=str, default=None)\nargs = parser.parse_args()\nlogger.log_exp_args(args)\n\nprint(\"Generating tasks ...... \")\nif args.load_tasks is None:\n task_defs = [OmniglotTask(train_val_permutation, root=args.data_dir, num_cls=args.N_way, num_inst=args.K_shot) for _ in tqdm(range(args.num_tasks))]\n dataset = OmniglotFewShotDataset(task_defs=task_defs, GPU=args.use_gpu)\nelse:\n task_defs = pickle.load(open(args.load_tasks, 'rb'))\n assert args.N_way == task_defs[0].num_cls and args.K_shot == task_defs[0].num_inst and args.num_tasks <= len(task_defs)\n task_defs = task_defs[:args.num_tasks]\n dataset = OmniglotFewShotDataset(task_defs=task_defs, GPU=args.use_gpu)\n\nif args.load_agent is None:\n learner_net = make_conv_network(in_channels=1, out_dim=args.N_way)\n fast_net = make_conv_network(in_channels=1, out_dim=args.N_way)\n meta_learner = Learner(model=learner_net, loss_function=torch.nn.CrossEntropyLoss(), inner_alg=args.inner_alg,\n inner_lr=args.inner_lr, outer_lr=args.outer_lr, GPU=args.use_gpu)\n fast_learner = Learner(model=fast_net, loss_function=torch.nn.CrossEntropyLoss(), inner_alg=args.inner_alg,\n inner_lr=args.inner_lr, outer_lr=args.outer_lr, GPU=args.use_gpu)\nelse:\n meta_learner = pickle.load(open(args.load_agent, 'rb'))\n meta_learner.set_params(meta_learner.get_params())\n fast_learner = pickle.load(open(args.load_agent, 'rb'))\n fast_learner.set_params(fast_learner.get_params())\n for learner in [meta_learner, fast_learner]:\n learner.inner_alg = args.inner_alg\n learner.inner_lr = args.inner_lr\n learner.outer_lr = args.outer_lr\n \ninit_params = meta_learner.get_params()\ndevice = 'cuda' if args.use_gpu is True else 'cpu'\nlam = torch.tensor(args.lam) if args.scalar_lam is True else torch.ones(init_params.shape[0])*args.lam\nlam = lam.to(device)\n\npathlib.Path(args.save_dir).mkdir(parents=True, exist_ok=True)\n\n# ===================\n# Train\n# ===================\nprint(\"Training model ......\")\nlosses = np.zeros((args.meta_steps, 4))\naccuracy = np.zeros((args.meta_steps, 2))\nfor outstep in tqdm(range(args.meta_steps)):\n task_mb = np.random.choice(args.num_tasks, size=args.task_mb_size)\n w_k = meta_learner.get_params()\n meta_grad = 0.0\n lam_grad = 0.0\n \n for idx in task_mb:\n fast_learner.set_params(w_k.clone()) # sync weights\n task = dataset.__getitem__(idx) # get task\n vl_before = fast_learner.get_loss(task['x_val'], task['y_val'], return_numpy=True)\n tl = fast_learner.learn_task(task, num_steps=args.n_steps)\n # pull back for regularization\n fast_learner.inner_opt.zero_grad()\n regu_loss = fast_learner.regularization_loss(w_k, lam)\n regu_loss.backward()\n fast_learner.inner_opt.step()\n vl_after = fast_learner.get_loss(task['x_val'], task['y_val'], return_numpy=True)\n tacc = utils.measure_accuracy(task, fast_learner, train=True)\n vacc = utils.measure_accuracy(task, fast_learner, train=False)\n \n valid_loss = fast_learner.get_loss(task['x_val'], task['y_val'])\n valid_grad = torch.autograd.grad(valid_loss, fast_learner.model.parameters())\n flat_grad = torch.cat([g.contiguous().view(-1) for g in valid_grad])\n \n if args.cg_steps <= 1:\n task_outer_grad = flat_grad\n else:\n task_matrix_evaluator = fast_learner.matrix_evaluator(task, lam, args.cg_damping)\n task_outer_grad = utils.cg_solve(task_matrix_evaluator, flat_grad, args.cg_steps, x_init=None)\n \n meta_grad += (task_outer_grad/args.task_mb_size)\n losses[outstep] += (np.array([tl[0], vl_before, tl[-1], vl_after])/args.task_mb_size)\n accuracy[outstep] += np.array([tacc, vacc]) / args.task_mb_size\n \n if args.lam_lr <= 0.0:\n task_lam_grad = 0.0\n else:\n print(\"Warning: lambda learning is not tested for this version of code\")\n train_loss = fast_learner.get_loss(task['x_train'], task['y_train'])\n train_grad = torch.autograd.grad(train_loss, fast_learner.model.parameters())\n train_grad = torch.cat([g.contiguous().view(-1) for g in train_grad])\n inner_prod = train_grad.dot(task_outer_grad)\n task_lam_grad = inner_prod / (lam**2 + 0.1)\n\n lam_grad += (task_lam_grad / args.task_mb_size)\n \n meta_learner.outer_step_with_grad(meta_grad, flat_grad=True)\n lam_delta = - args.lam_lr * lam_grad\n lam = torch.clamp(lam + lam_delta, args.lam_min, 5000.0) # clips each element individually if vector\n logger.log_kv('train_pre', losses[outstep,0])\n logger.log_kv('test_pre', losses[outstep,1])\n logger.log_kv('train_post', losses[outstep,2])\n logger.log_kv('test_post', losses[outstep,3])\n logger.log_kv('train_acc', accuracy[outstep, 0])\n logger.log_kv('val_acc', accuracy[outstep, 1])\n \n if (outstep % 50 == 0 and outstep > 0) or outstep == args.meta_steps-1:\n smoothed_losses = utils.smooth_vector(losses[:outstep], window_size=10)\n plt.figure(figsize=(10,6))\n plt.plot(smoothed_losses)\n plt.ylim([0, 2.0])\n plt.xlim([0, args.meta_steps])\n plt.grid(True)\n plt.legend(['Train pre', 'Test pre', 'Train post', 'Test post'], loc=1)\n plt.savefig(args.save_dir+'/learn_curve.png', dpi=100)\n plt.clf()\n plt.close('all')\n \n smoothed_acc = utils.smooth_vector(accuracy[:outstep], window_size=25)\n plt.figure(figsize=(10,6))\n plt.plot(smoothed_acc)\n plt.ylim([50.0, 100.0])\n plt.xlim([0, args.meta_steps])\n plt.grid(True)\n plt.legend(['Train post', 'Test post'], loc=4)\n plt.savefig(args.save_dir+'/accuracy.png', dpi=100)\n plt.clf()\n plt.close('all')\n\n pickle.dump(meta_learner, open(args.save_dir+'/agent.pickle', 'wb'))\n logger.save_log()\n\n if (outstep % 500 == 0 and outstep > 0):\n checkpoint_file = args.save_dir + '/checkpoint_' + str(outstep) + '.pickle'\n pickle.dump(meta_learner, open(checkpoint_file, 'wb'))\n if outstep == args.meta_steps-1:\n checkpoint_file = args.save_dir + '/final_model.pickle'\n pickle.dump(meta_learner, open(checkpoint_file, 'wb'))","repo_name":"aravindr93/imaml_dev","sub_path":"examples/omniglot_implicit_maml.py","file_name":"omniglot_implicit_maml.py","file_ext":"py","file_size_in_byte":8834,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"29"} +{"seq_id":"35186580529","text":"from tkinter import *\nfrom view.solicitar_cert import *\nimport view\nimport controler\nimport view\nclass main_view(view.GenericView.GenericView):\n y_size=250\n def create_elements(self):\n self.main_frame = Frame(self.root,width=self.x_size,height=self.y_size)\n self.boton_solicitar = Button(self.main_frame,text=\"Solicitar certificado\")\n self.boton_descargar = Button(self.main_frame,text=\"Descargar certificado\")\n self.boton_firmar = Button(self.main_frame,text=\"Firmar documento\")\n self.boton_verificar = Button(self.main_frame,text=\"Verificar documento\")\n self.boton_solicitar.bind('